@deveco-test/deveco-cli 1.3.0-Test.1 → 1.3.0-Test.10

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.
Files changed (36) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +1423 -788
  3. package/SKILL.md +214 -116
  4. package/THIRD-PARTY-LICENSES +4441 -3538
  5. package/dist/cli.js +207 -88
  6. package/dist/internal/doc-init-background.js +1 -0
  7. package/docs.zip +0 -0
  8. package/index.zip +0 -0
  9. package/package.json +22 -7
  10. package/scripts/postinstall.mjs +33 -0
  11. package/src/resources/aclPermission/aclPermissionsInfo.json +311 -0
  12. package/templates/application/AppScope/app.json5 +10 -10
  13. package/templates/application/AppScope/resources/base/element/string.json +8 -8
  14. package/templates/application/AppScope/resources/base/media/layered_image.json +6 -6
  15. package/templates/application/build-profile.json5 +41 -41
  16. package/templates/application/code-linter.json5 +31 -31
  17. package/templates/application/entry/build-profile.json5 +32 -32
  18. package/templates/application/entry/gitignore.txt +6 -0
  19. package/templates/application/entry/hvigorfile.ts +7 -7
  20. package/templates/application/entry/obfuscation-rules.txt +19 -19
  21. package/templates/application/entry/oh-package.json5 +10 -10
  22. package/templates/application/entry/src/main/ets/entryability/EntryAbility.ets +62 -62
  23. package/templates/application/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets +30 -30
  24. package/templates/application/entry/src/main/ets/pages/Index.ets +37 -37
  25. package/templates/application/entry/src/main/module.json5 +49 -49
  26. package/templates/application/entry/src/main/resources/base/element/color.json +7 -7
  27. package/templates/application/entry/src/main/resources/base/element/float.json +8 -8
  28. package/templates/application/entry/src/main/resources/base/element/string.json +15 -15
  29. package/templates/application/entry/src/main/resources/base/media/layered_image.json +6 -6
  30. package/templates/application/entry/src/main/resources/base/profile/backup_config.json +2 -2
  31. package/templates/application/entry/src/main/resources/base/profile/main_pages.json +5 -5
  32. package/templates/application/entry/src/main/resources/dark/element/color.json +7 -7
  33. package/templates/application/gitignore.txt +12 -0
  34. package/templates/application/hvigor/hvigor-config.json5 +23 -23
  35. package/templates/application/hvigorfile.ts +7 -7
  36. package/templates/application/oh-package.json5 +10 -10
package/dist/cli.js CHANGED
@@ -1,43 +1,53 @@
1
1
  #!/usr/bin/env node
2
- import{bootstrap as Ip}from"global-agent";import{program as V}from"commander";import{red as Ap}from"colorette";import{Command as ya}from"commander";import{green as Pi,red as cr,yellow as Ei}from"colorette";import U from"fs";import*as B from"path";import Oe from"json5";import*as ir from"fs";import*as F from"path";function v(r){process.env.DEVECO_CLI_DEBUG&&console.log(`[DEBUG] ${r}`)}var D=class r{static ASCII_CONTROL_MAX=31;static ASCII_DELETE=127;static parsePositiveInteger(e,t="value"){let n=e.trim();if(!/^\d+$/.test(n))throw new Error(`${t} must be a positive integer`);let i=Number.parseInt(n,10);if(!Number.isInteger(i)||i<=0)throw new Error(`${t} must be a positive integer`);return i}static getLastLines(e,t){return!t||t<=0?e:e.split(/\r?\n/).slice(-t).join(`
3
- `)}static parseDurationToSeconds(e,t="value"){let i=e.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)([sm])?$/);if(!i)throw new Error(`${t} must be like 30s, 5m or 2.5m (only s/m supported).`);let o=i[1];if((i[2]??"s")==="s")return r.parsePositiveInteger(o,t);if(!/^\d+(?:\.\d)?$/.test(o))throw new Error(`${t} supports a maximum of 1 decimal place for minutes (e.g. 2.5m).`);let a=Number.parseFloat(o);if(!Number.isFinite(a)||a<=0)throw new Error(`${t} must be a positive duration.`);return Math.round(a*60)}static assertRelativeTimeRange(e,t){if(e!==void 0&&t!==void 0&&e<t)throw new Error("--from must be greater than or equal to --to when both are provided (e.g. --from 30s --to 10s)")}static filterLogsByRelativeWindow(e,t,n,i=new Date){if(!t&&!n)return e;let[o,s]=r.resolveTimeBounds(t,n,i),a=e.split(/\r?\n/),c=[],d=!1;for(let p of a){let g=r.extractTimestampFromLogLine(p,i);g&&(d=r.isWithinBounds(g,o,s)),d&&c.push(p)}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),p=n[6]??"0",g=Number.parseInt(p.padEnd(3,"0").slice(0,3),10),k=new Date(i,o,s,a,c,d,g);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 v(`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(F.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let n=F.resolve(F.normalize(e),t);return r.ensurePathWithinRoot(e,n)}static ensurePathWithinRoot(e,t){let n=F.normalize(e),i=F.relative(n,t);if(i.split(F.sep)[0]===".."||F.isAbsolute(i))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||F.isAbsolute(e)}static isPathContained(e,t){let n=F.resolve(t,e),i=F.relative(t,n);return r.isPathEscaping(i)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){if(F.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=ir.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let o=F.resolve(i,e),s;try{s=ir.realpathSync(o)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${o}`}}return r.isPathContained(s,i)}};var Le=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=B.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=B.join(e,"build-profile.json5");if(!U.existsSync(t))return null;try{let n=U.readFileSync(t,"utf-8"),i=Oe.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=D.resolvePathWithinRoot(this.rootDir,t.srcPath),i=B.join(n,"src","main","module.json5");if(!U.existsSync(i))return"entry";try{let o=U.readFileSync(i,"utf-8");return Oe.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=D.resolvePathWithinRoot(this.rootDir,t.srcPath),i=B.join(n,"build-profile.json5");if(!U.existsSync(i))throw new Error(`Build profile for module '${e}' not found at ${i}.`);let o=U.readFileSync(i,"utf-8");return Oe.parse(o)}getBundleName(){let e=B.join(this.rootDir,"AppScope","app.json5");if(U.existsSync(e))try{let t=U.readFileSync(e,"utf-8"),n=Oe.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=D.resolvePathWithinRoot(this.rootDir,n.srcPath),o=B.join(i,"src","main","module.json5");if(!U.existsSync(o))return"EntryAbility";try{let s=U.readFileSync(o,"utf-8"),c=Oe.parse(s)?.module?.abilities||[];if(c.length===0)return"EntryAbility";let d=c.find(p=>p.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=D.resolvePathWithinRoot(this.rootDir,t.srcPath),i=B.join(n,"oh-package.json5");if(!U.existsSync(i))return[];let o=[];try{let s=U.readFileSync(i,"utf-8"),c=Oe.parse(s)?.dependencies||{};for(let d of Object.values(c)){if(typeof d!="string")continue;let p=d;if(!(p.startsWith("file:")||p.startsWith(".")||p.startsWith("..")))continue;p.startsWith("file:")&&(p=p.substring(5));let k=B.join(t.srcPath,p),re=D.resolvePathWithinRoot(this.rootDir,k),Se=this.profile.modules.find(Be=>B.resolve(this.rootDir,Be.srcPath)===re);Se&&o.push(Se.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(re=>re.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(!U.existsSync(d))throw new Error(`Build metadata not found for module '${e}' at ${d}. Build the project first.`);let{packageName:p,isSigned:g}=this.parseOutputMetadata(d,c);if(!n&&!g)throw new Error(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`);let k=this.buildOutputPath(o.srcPath,i,["outputs",t,p]);if(!U.existsSync(k))throw new Error(`Generated package file not found in ${k}.`);return k}buildOutputPath(e,t,n){let i=D.resolvePathWithinRoot(this.rootDir,e),o=B.resolve(i,"build",t,...n);return D.ensurePathWithinRoot(this.rootDir,o)}parseOutputMetadata(e,t){let n=U.readFileSync(e,"utf-8"),i=Oe.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=B.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 or}from"child_process";import M,{existsSync as gi}from"fs";import*as C from"path";import*as Z from"os";import aa from"regedit";import{join as yi}from"path";import{red as ca}from"colorette";var vi="https://developer.huawei.com/consumer/cn/download/",wi="6.1.0",Gt=r=>new Promise((e,t)=>{aa.list(r,(n,i)=>{n?t(n):e(i)})}),O=class r{_devecoStudioPath;_nodePath;_ohpmJsPath;_hvigorJsPath;_javaPath;_sdkPath;_hdcPath;_emulatorPath;_emulatorLauncherPath;static _verifiedPaths=new Set;static _powerShellPath;static verifyAndCache(e){r._verifiedPaths.has(e)||(r.verifySignature(e),r._verifiedPaths.add(e))}get devecoStudioPath(){return this._devecoStudioPath}get nodePath(){return r.verifyAndCache(this._nodePath),this._nodePath}get ohpmJsPath(){return this._ohpmJsPath}get hvigorJsPath(){return this._hvigorJsPath}get javaPath(){return r.verifyAndCache(this._javaPath),this._javaPath}get sdkPath(){return this._sdkPath}get hdcPath(){return r.verifyAndCache(this._hdcPath),this._hdcPath}get emulatorPath(){return r.verifyAndCache(this._emulatorPath),this._emulatorPath}get emulatorLauncherPath(){return this._emulatorLauncherPath&&r.verifyAndCache(this._emulatorLauncherPath),this._emulatorLauncherPath}constructor(e,t,n,i,o,s,a,c,d){this._devecoStudioPath=e,this._nodePath=t,this._ohpmJsPath=n,this._hvigorJsPath=i,this._javaPath=o,this._sdkPath=s,this._hdcPath=a,this._emulatorPath=c,this._emulatorLauncherPath=d}static 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 v(`[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=C.normalize(i).toLowerCase();e.has(s)||(e.add(s),t.push(i),v(`[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 Gt([t]))[t]?.keys??[]).filter(r.isDevEcoStudioUninstallSubkey);if(o.length===0)continue;let s=o.map(c=>`${t}\\${c}`),a=await Gt(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 Gt([t]))[t]?.keys??[];if(o.length===0)return;let s=o.map(c=>`${t}\\${c}`),a=await Gt(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=C.join("C:","Program Files","Huawei","DevEco Studio");e(t,"default installation path")}static collectCandidatesMac(){let e=Z.homedir(),t=[C.join(e,"Applications"),"/Applications"],n=[],i=new Set;for(let o of t){if(!M.existsSync(o))continue;let s;try{s=M.readdirSync(o)}catch{continue}for(let a of s){if(!a.endsWith(".app")||!a.toLowerCase().includes("deveco"))continue;let d=C.join(o,a);r.isExistingDirectory(d)&&(i.has(d)||(i.add(d),n.push(d),v(`[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"?C.join(e,"Contents","product-info.json"):C.join(e,"product-info.json")}static macInfoPlistPath(e){return C.join(e,"Contents","Info.plist")}static readMacInfoPlistKey(e,t){if(!M.existsSync(e)){v(`[ToolProvider] Info.plist not found at: ${e}`);return}try{let n=or("defaults",["read",e,t],{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:5e3}).trim();if(n.length>0&&n!=="(null)")return n}catch{v(`[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)){v(`[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(!M.existsSync(t)){v(`[ToolProvider] product-info.json not found at: ${t}`);return}try{let i=JSON.parse(M.readFileSync(t,"utf-8"))?.version;if(typeof i!="string"||i.trim()===""){v(`[ToolProvider] product-info.json at ${t} has no valid "version" field`);return}return i.trim()}catch{v(`[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 v(`[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}),v(`[ToolProvider] ${n} => version ${i}`)):v(`[ToolProvider] Skipping ${n}: could not read version (Info.plist / product-info.json).`)}if(t.length===0){let n=e.join(`
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
- Searched locations:
7
- ${n}
8
- Please reinstall DevEco Studio or download the latest version from:
9
- `+vi)}return t.reduce((n,i)=>r.compareVersion(i.version,n.version)>0?i:n)}static assertMinVersion(e,t){r.compareVersion(t,wi)>=0||(v(`[ToolProvider] Selected DevEco Studio ${t} at ${e} \u2014 below minimum`),console.error(ca(`Error: The detected DevEco Studio version is ${t}, which is below the minimum required version ${wi}. Upgrade to the latest version before using deveco-cli:`)+`
10
- `+vi),process.exit(1))}static isExistingDirectory(e){return!!e&&M.existsSync(e)&&M.statSync(e).isDirectory()}static resolveWindowsTools(e){let t=C.join(e,"tools");return{nodePath:C.join(t,"node","node.exe"),ohpmJsPath:C.join(t,"ohpm","bin","pm-cli.js"),hvigorJsPath:C.join(t,"hvigor","bin","hvigorw.js"),javaPath:C.join(e,"jbr","bin","java.exe"),sdkPath:C.join(e,"sdk")}}static resolveMacTools(e){let t=C.join(e,"Contents","tools");return{nodePath:C.join(t,"node","bin","node"),ohpmJsPath:C.join(t,"ohpm","bin","pm-cli.js"),hvigorJsPath:C.join(t,"hvigor","bin","hvigorw.js"),javaPath:C.join(e,"Contents","jbr","Contents","Home","bin","java"),sdkPath:C.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=[C.join(e,"default","openharmony","toolchains",`hdc${n}`),C.join(e,"toolchains",`hdc${n}`)];for(let o of i)if(M.existsSync(o))return o;throw new Error(`hdc executable not found. Searched in:
11
- ${i.join(`
12
- `)}`)}static resolveEmulatorPath(e,t){let n;if(t==="win32")n=C.join(e,"tools","emulator","Emulator.exe");else if(t==="darwin")n=C.join(e,"Contents","tools","emulator","Emulator");else throw new Error("Linux is not fully supported yet");if(!M.existsSync(n))throw new Error(`Emulator executable not found at: ${n}`);return n}static verifyTools(e,t,n,i){if(!M.existsSync(e))throw new Error(`Node executable not found at: ${e}`);if(!M.existsSync(t))throw new Error(`ohpm js file not found at: ${t}`);if(!M.existsSync(n))throw new Error(`hvigor js file not found at: ${n}`);if(!M.existsSync(i))throw new Error(`java executable not found at: ${i}`)}static getEmulatorExe(e){let t=Z.platform(),n;if(t==="win32")n=yi(e,"tools","emulator","Emulator.exe");else if(t==="darwin")n=yi(e,"Contents","tools","emulator","Emulator");else return;return gi(n)?n:void 0}static isValidApiLevel(e,t){let n=t??23;return Number.isInteger(e)&&e>=17&&e<=n}static parseApiLevelFromFile(e){if(M.existsSync(e))try{let t=M.readFileSync(e,"utf-8"),n=JSON.parse(t),i=n?.apiVersion??n?.data?.apiVersion;if(typeof i!="string"&&typeof i!="number")return;let o=Number(i);return Number.isInteger(o)&&o>=17?o:void 0}catch{return}}static detectFromSdkPkg(e){let t=C.join(e,"default","sdk-pkg.json");return r.parseApiLevelFromFile(t)}static detectFromOhUniPackage(e){let t=[C.join(e,"default","openharmony","toolchains","oh-uni-package.json"),C.join(e,"default","openharmony","native","oh-uni-package.json"),C.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=C.join(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return gi(e)?(v(`[ToolProvider] Found PowerShell at: ${e}`),r._powerShellPath=e,e):(r._powerShellPath="",r._powerShellPath)}static verifySignature(e){if(!M.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=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 C.extname(e).toLowerCase()===".exe";if(t==="darwin")try{return M.accessSync(e,M.constants.X_OK),!0}catch{return!1}return!1}static createSignatureScript(){let e=M.mkdtempSync(C.join(Z.tmpdir(),"deveco-verify-")),t=C.join(e,"Verify-Signature.ps1");return M.writeFileSync(t,"$env:PSModulePath = ($env:PSModulePath -split ';' | Where-Object { $_ -notmatch 'windowsapps' }) -join ';'; Get-AuthenticodeSignature -FilePath $args[0] | ConvertTo-Json -Depth 3 -Compress","utf-8"),{tmpDir:e,scriptPath:t}}static verifyWindowsSignature(e){let t=r.findPowerShellPath();if(!t)throw new Error("PowerShell application not found");let{tmpDir:n,scriptPath:i}=r.createSignatureScript();try{let o=or(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 v(`[ToolProvider] verify Windows Signature, error msg: ${o}`),{signed:!0}}finally{try{M.rmSync(n,{recursive:!0,force:!0})}catch{}}}static verifyMacSignature(e){try{return or("codesign",["-v",e],{encoding:"utf-8",timeout:5e3}),{signed:!0}}catch{return{signed:!1}}}};import{execa as la}from"execa";import*as Yt from"path";var Ne=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let i=`${Yt.dirname(e.javaPath)}${Yt.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];v(`Executing: ${t} ${n.join(" ")}`),await la(t,n,{cwd:this.projectRoot,env:this.env,stdout:"inherit",stderr:"inherit"})}};import{execa as da}from"execa";var ze=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"];v(`Executing: ${e} ${t.join(" ")}`),await da(e,t,{cwd:this.projectRoot,stdout:"inherit",stderr:"inherit"})}};import{mkdir as ua}from"fs/promises";import{dirname as pa,resolve as ha}from"path";import{execa as fa}from"execa";import{lock as sr,check as oh}from"proper-lockfile";function ar(r){return ha(r,".hvigor",".build-lock")}function ma(r){let e=!1;return()=>{e||(e=!0,r?.())}}async function bi(r){let e=pa(ar(r));if(await ua(e,{recursive:!0}),process.platform==="win32")try{await fa("attrib",["+h",e])}catch{}}async function ga(r,e){let t=new AbortController,n=ma(e);await bi(r);let i={lockfilePath:ar(r),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await sr(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 sr(r,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function bt(r,e,t){let{release:n,signal:i}=await ga(r,t);try{return await e(i)}finally{await n()}}async function Si(r,e){let t=new AbortController;await bi(r);let n={lockfilePath:ar(r),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},i;try{i=await sr(r,{...n,retries:0})}catch(o){if(o&&typeof o=="object"&&"code"in o&&o.code==="ELOCKED")return{acquired:!1};throw o}try{return{acquired:!0,result:await e(t.signal)}}finally{await i()}}function va(r,e){if(e.product&&r.validateProduct(e.product),e.buildMode&&!r.profile.app.buildModeSet.some(n=>n.name===e.buildMode))throw new Error(`Build mode '${e.buildMode}' not found in project build-profile.json5.`)}function wa(r,e){let t;if(e.modules&&e.modules.length>0)t=e.modules;else{let i=r.profile.modules,o=i.filter(s=>r.getModuleType(s.name)==="entry");if(i.length===1)t=[i[0].name];else if(o.length===1)t=[o[0].name];else throw o.length>1?new Error(`Multiple entry modules found (${o.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`):new Error(`No entry module found and multiple modules available (${i.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`)}let n=new Set;for(let i of t){let o=i.indexOf("@"),s=o!==-1?i.substring(0,o):i,a=o!==-1?i.substring(o+1):"default";n.add(`${s}@${a}`)}return Array.from(n)}function 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 St(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){console.log(`
13
- [1/3] Running ohpm install...`);try{await r.installAll()}catch(o){St("ohpm install",o)}console.log(`
14
- [2/3] Running hvigor sync...`);try{await e.sync(t,n)}catch(o){St("hvigor sync",o)}console.log(`
15
- [3/3] Running hvigor build...`);try{i.type==="product"?await e.buildProduct(t,n):await e.buildModules(t,n,i.modulesToBuild,i.moduleTasks)}catch(o){St("hvigor build",o)}}var Ci=new ya("build").description("Build HarmonyOS project").option("--product <product>","Product name defined in build-profile.json5 (default: default)").option("--modules <modules...>","Modules to build (format: module or module@target)").option("--build-mode <mode>","Build mode (buildModeSet in build-profile.json5; e.g. debug, release; default: debug)").action(async r=>{try{let e=process.cwd(),t=Le.discover(e);console.warn(Ei("Ensure the project source is trustworthy before proceeding."));let n=await O.new();va(t,r);let i=r.product||"default",o=r.buildMode||"debug",s;if(r.product&&!r.modules)s={type:"product"};else{let d=wa(t,r),p=lr(t,d);s={type:"modules",modulesToBuild:d,moduleTasks:p}}let a=new ze(n,t.rootDir),c=new Ne(n,t.rootDir);await bt(t.rootDir,async()=>dr(a,c,i,o,s),()=>{console.log("Another build is already running for this project. Waiting for completion...")}),console.log(`
16
- `+Pi("Build completed successfully"))}catch(e){console.error(cr(e.message)),process.exit(1)}});Ci.command("clean").description("Clean HarmonyOS project build outputs").action(async()=>{try{let r=process.cwd(),e=Le.discover(r);console.warn(Ei("Ensure the project source is trusted before proceeding."));let t=await O.new(),n=new Ne(t,e.rootDir);await bt(e.rootDir,async()=>{console.log(`
17
- [1/2] Running hvigor clean...`);try{await n.clean()}catch(i){St("hvigor clean",i)}console.log(`
18
- [2/2] Running hvigor --stop-daemon...`);try{await n.stopDaemon()}catch(i){St("hvigor --stop-daemon",i)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
19
- `+Pi("Clean completed successfully."))}catch(r){console.error(cr(r.message)),process.exit(1)}});var Di=Ci;import{Command as La}from"commander";import{green as Mi,red as Na,yellow as Ha}from"colorette";import{randomUUID as Ma}from"crypto";import{execa as Oa}from"execa";import{execa as xa}from"execa";import{execFile as ba,spawn as Sa}from"child_process";import{promisify as Pa}from"util";var Ea=Pa(ba);function Ii(r,e,t){let i=r.replace(/\r\n/g,`
2
+ var yy=Object.defineProperty;var wy=(n,e)=>{for(var t in e)yy(n,t,{get:e[t],enumerable:!0})};import{bootstrap as ET}from"global-agent";import*as my from"path";import{program as K}from"commander";import{red as bT}from"colorette";import{Command as Cw}from"commander";import{green as Wa,red as Ga,yellow as Va}from"colorette";import X from"fs";import*as Q from"path";import Dt from"json5";import*as Ia from"fs";import*as ne from"path";function m(n){if(process.env.DEVECO_CLI_DEBUG){let e=typeof n=="function"?n():n;console.log(`[DEBUG] ${e}`)}}var P=class n{static ASCII_CONTROL_MAX=31;static ASCII_DELETE=127;static parsePositiveInteger(e,t="value"){let r=e.trim();if(!/^\d+$/.test(r))throw new Error(`${t} must be a positive integer`);let i=Number.parseInt(r,10);if(!Number.isInteger(i)||i<=0)throw new Error(`${t} must be a positive integer`);return i}static getLastLines(e,t){return!t||t<=0?e:e.split(/\r?\n/).slice(-t).join(`
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 n.parsePositiveInteger(o,t);if(!/^\d+(?:\.\d)?$/.test(o))throw new Error(`${t} supports a maximum of 1 decimal place for minutes (e.g. 2.5m).`);let a=Number.parseFloat(o);if(!Number.isFinite(a)||a<=0)throw new Error(`${t} must be a positive duration.`);return Math.round(a*60)}static filterLogsByRelativeWindow(e,t,r,i=new Date){if(!t&&!r)return e;let[o,s]=n.resolveTimeBounds(t,r,i),a=e.split(/\r?\n/),c=[],l=!1;for(let p of a){let g=n.extractTimestampFromLogLine(p,i);g&&(l=n.isWithinBounds(g,o,s)),l&&c.push(p)}return c.join(`
4
+ `)}static resolveTimeBounds(e,t,r){let i=e?new Date(r.getTime()-e*1e3):null,o=t?new Date(r.getTime()-t*1e3):null;return i&&o?i<o?[i,o]:[o,i]:i?[i,r]:o?[null,o]:[null,null]}static isWithinBounds(e,t,r){let i=e.getTime(),o=t?Math.floor(t.getTime()/1e3)*1e3:null,s=r?Math.floor(r.getTime()/1e3)*1e3+999:null;return!(o!==null&&i<o||s!==null&&i>s)}static extractTimestampFromLogLine(e,t){let r=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!r)return null;let i=t.getFullYear(),o=Number.parseInt(r[1],10)-1,s=Number.parseInt(r[2],10),a=Number.parseInt(r[3],10),c=Number.parseInt(r[4],10),l=Number.parseInt(r[5],10),p=r[6]??"0",g=Number.parseInt(p.padEnd(3,"0").slice(0,3),10),w=new Date(i,o,s,a,c,l,g);return w.getTime()>t.getTime()+1440*60*1e3&&w.setFullYear(i-1),w}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static assertHilogToken(e,t){if(!/^[A-Za-z0-9_.:\\-]{1,64}$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogKeyword(e){if(e.length===0||e.length>128)throw new Error(`Invalid keyword: ${JSON.stringify(e)}`);if([...e].some(r=>{let i=r.charCodeAt(0);return i<=n.ASCII_CONTROL_MAX||i===n.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let r=`'${e.replace(/'/g,"'\\''")}'`;return m(`quotePosixShellArg: ${e} -> ${r}`),r}static assertCrashFilename(e){if(!/^\w+-[\w.]+-\d+-\d+$/.test(e))throw new Error(`Invalid crash log filename: ${JSON.stringify(e)}`)}static assertHilogLevel(e){if(!/^[DIWEF]$/.test(e))throw new Error(`Invalid log level: ${e}`)}static resolvePathWithinRoot(e,t){if(ne.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=ne.resolve(ne.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=ne.normalize(e),i=ne.relative(r,t);if(i.split(ne.sep)[0]===".."||ne.isAbsolute(i))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||ne.isAbsolute(e)}static isPathContained(e,t){let r=ne.resolve(t,e),i=ne.relative(t,r);return n.isPathEscaping(i)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){if(ne.isAbsolute(e))return{contained:!1,reason:`Absolute path is not allowed: ${e}`};let r=n.isPathContained(e,t);if(!r.contained)return r;let i;try{i=Ia.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let o=ne.resolve(i,e),s;try{s=Ia.realpathSync(o)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${o}`}}return n.isPathContained(s,i)}};var U=class n{rootDir;profile;constructor(e,t){this.rootDir=e,this.profile=t}static discover(e){let t=e;for(;;){let r=n.tryLoadProjectProfile(t);if(r)return new n(t,r);let i=Q.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=Q.join(e,"build-profile.json5");if(!X.existsSync(t))return null;try{let r=X.readFileSync(t,"utf-8"),i=Dt.parse(r);return i.app?i:null}catch(r){return console.error(`Error parsing ${t}:`,r),null}}getRunnableModuleNames(){return this.profile.modules.map(e=>e.name).filter(e=>this.getModuleType(e)!=="har").join(", ")}getModuleType(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let r=P.resolvePathWithinRoot(this.rootDir,t.srcPath),i=Q.join(r,"src","main","module.json5");if(!X.existsSync(i))return"entry";try{let o=X.readFileSync(i,"utf-8");return Dt.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 r=P.resolvePathWithinRoot(this.rootDir,t.srcPath),i=Q.join(r,"build-profile.json5");if(!X.existsSync(i))throw new Error(`Build profile for module '${e}' not found at ${i}.`);let o=X.readFileSync(i,"utf-8");return Dt.parse(o)}getBundleName(){let e=Q.join(this.rootDir,"AppScope","app.json5");if(X.existsSync(e))try{let t=X.readFileSync(e,"utf-8"),r=Dt.parse(t);if(r?.app?.bundleName)return r.app.bundleName}catch(t){console.warn(`Warning: Failed to parse ${e}:`,t)}throw new Error("Could not find bundleName in AppScope/app.json5.")}isAtomicService(){let e=Q.join(this.rootDir,"AppScope","app.json5");if(!X.existsSync(e))return!1;try{let t=X.readFileSync(e,"utf-8");return Dt.parse(t)?.app?.bundleType==="atomicService"}catch{return!1}}getMainAbility(e,t){if(t)return t;let r=this.profile.modules.find(s=>s.name===e);if(!r)return"EntryAbility";let i=P.resolvePathWithinRoot(this.rootDir,r.srcPath),o=Q.join(i,"src","main","module.json5");if(!X.existsSync(o))return"EntryAbility";try{let s=X.readFileSync(o,"utf-8"),c=Dt.parse(s)?.module?.abilities||[];if(c.length===0)return"EntryAbility";let l=c.find(p=>p.name==="EntryAbility");return l?l.name:c[0].name}catch(s){return console.warn(`Warning: Failed to parse ${o}:`,s),"EntryAbility"}}validateProduct(e){if(!/^[\da-zA-Z_-]+$/.test(e))throw new Error(`Invalid product name '${e}'. Product names must only contain letters, digits, underscores, and hyphens.`);if(!this.profile.app.products?.some(r=>r.name===e)){let r=this.profile.app.products?.map(i=>i.name).join(", ")||"none";throw new Error(`Product '${e}' not found in project configuration. Available products: ${r}`)}}getModuleDependencies(e){let t=this.profile.modules.find(s=>s.name===e);if(!t)return[];let r=P.resolvePathWithinRoot(this.rootDir,t.srcPath),i=Q.join(r,"oh-package.json5");if(!X.existsSync(i))return[];let o=[];try{let s=X.readFileSync(i,"utf-8"),c=Dt.parse(s)?.dependencies||{};for(let l of Object.values(c)){if(typeof l!="string")continue;let p=l;if(!(p.startsWith("file:")||p.startsWith(".")||p.startsWith("..")))continue;p.startsWith("file:")&&(p=p.substring(5));let w=Q.join(t.srcPath,p),C=P.resolvePathWithinRoot(this.rootDir,w),_=this.profile.modules.find(fe=>Q.resolve(this.rootDir,fe.srcPath)===C);_&&o.push(_.name)}}catch{}return o}collectNonHarDependentModuleList(e){let t=[],r=[],i=new Set;for(r.push(e),i.add(e);r.length>0;){let o=r.shift();this.getModuleType(o)!=="har"&&t.push(o);let a=this.getModuleDependencies(o);for(let c of a)i.has(c)||(r.push(c),i.add(c))}return t}resolveModuleMetadata(e,t,r){this.validateProduct(r);let i=this.profile.modules.find(l=>l.name===e);if(!i){let l=this.getRunnableModuleNames();throw new Error(`Module '${e}' not found. Available modules: ${l}`)}let o=this.getModuleType(e)==="shared",s=o?"hspName":"hapName",a=this.buildOutputPath(i.srcPath,r,["intermediates",o?"hsp_metadata":"hap_metadata",t,"output_metadata.json"]);if(!X.existsSync(a))throw new Error(`Build metadata not found for module '${e}' at ${a}. Build the project first.`);let c=this.parseOutputMetadata(a,s);return{moduleNode:i,isShared:o,metadataPath:a,metadata:c}}findArtifactPath(e,t,r,i="default"){let{moduleNode:o,isShared:s,metadata:a}=this.resolveModuleMetadata(e,t,i),{packageName:c,isSigned:l}=a,p=c;if(!l){let C=this.getSignedHapName(c,o.srcPath,i,t);C&&(p=C)}let g=s?"-signed.hsp":"-signed.hap";if(!r&&!p.endsWith(g))throw new Error(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`);let w=this.buildOutputPath(o.srcPath,i,["outputs",t,p]);if(!X.existsSync(w))throw new Error(`Generated package file not found in ${w}.`);return w}findRemoteHspPaths(e,t,r="default"){let{moduleNode:i,metadata:o}=this.resolveModuleMetadata(e,t,r),s=[],a=new Set;for(let{hspPath:c}of o.dependRemoteHsps){if(a.has(c))continue;a.add(c);let l=Q.isAbsolute(c)?c:this.buildOutputPath(i.srcPath,r,["outputs",t,c]);if(!X.existsSync(l))throw new Error(`Remote HSP dependency not found: ${l}`);s.push(l)}return s}getSignedHapName(e,t,r,i){let o=null;if(e.endsWith("-unsigned.hap")?o=e.replace("-unsigned.hap","-signed.hap"):e.endsWith("-unsigned.hsp")&&(o=e.replace("-unsigned.hsp","-signed.hsp")),!o)return null;let s=this.buildOutputPath(t,r,["outputs",i,o]);return X.existsSync(s)?o:null}buildOutputPath(e,t,r){let i=P.resolvePathWithinRoot(this.rootDir,e),o=Q.resolve(i,"build",t,...r);return P.ensurePathWithinRoot(this.rootDir,o)}collectRemoteHsps(e){return e.flatMap(t=>{let r=t.dependRemoteHsps;return Array.isArray(r)?r.filter(i=>!!(i.hspName&&i.hspPath)).map(i=>({hspName:i.hspName,hspPath:i.hspPath})):[]})}parseOutputMetadata(e,t){let r=X.readFileSync(e,"utf-8"),i=Dt.parse(r),o,s=!1,a=Array.isArray(i)?i:[i];for(let l of a)o||(o=l[t]),s||(s=l.isSigned===!0);if(!o)throw new Error(`Could not find ${t} in output_metadata.json at ${e}`);this.validatePackageName(o);let c=this.collectRemoteHsps(a);return{packageName:o,isSigned:s,dependRemoteHsps:c}}validatePackageName(e){let t=Q.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 xd}from"child_process";import Y from"fs";import*as Pe from"os";import*as S from"path";import Id from"fs";import*as zi from"os";import*as Vi from"path";import by from"regedit";import{execFileSync as Sy}from"child_process";import Ed from"fs";import*as bd from"os";import*as Aa from"path";import{compare as vy}from"semver";function Sd(n,e){return vy(n,e)}function Rn(n,e){let t=Math.max(n.split(".").length,e.split(".").length);for(let r=0;r<t;r++){let i=Number(n.split(".")[r]??0)-Number(e.split(".")[r]??0);if(i)return i}return 0}function Gi(n,e){let t=Aa.join(n,"Contents","Info.plist");if(!Ed.existsSync(t)){m(`[ToolProvider] Info.plist not found at: ${t}`);return}for(let[r,i]of[["/usr/libexec/PlistBuddy",["-c",`Print :${e}`,t]],["plutil",["-extract",e,"raw","-o","-",t]]])try{let o=Sy(r,i,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(o&&!o.includes("Does Not Exist"))return o}catch{}}function Ey(n){let e=Gi(n,"CFBundleShortVersionString");if(!e)return Gi(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[Gi(n,"CFBundleVersion"),Gi(n,"CFBundleGetInfoString")?.match(/DS-[\d.]+/)?.[0]];for(let i of r){let o=i?.split(".").at(-1)?.replace(new RegExp(`^${t}`),"");if(o&&/^\d+$/.test(o))return`${e}.${o}`}return e}function Er(n){if(bd.platform()==="darwin")return Ey(n);let e=Aa.join(n,"product-info.json");try{let t=JSON.parse(Ed.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}function Py(n){return n.filter(e=>{try{return Id.statSync(e).isDirectory()}catch{return!1}})}function Cy(){let n=[];for(let e of[Vi.join(zi.homedir(),"Applications"),"/Applications"])try{n.push(...Id.readdirSync(e).filter(t=>t.endsWith(".app")&&t.toLowerCase().includes("deveco")).map(t=>Vi.join(e,t)))}catch{}return n}function Pd(n){return new Promise((e,t)=>by.list(n,(r,i)=>r?t(r):e(i)))}async function Cd(n,e,t){let i=((await Pd([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(i.length===0)return[];let o=await Pd(i);return i.flatMap(s=>{let a=o[s]?.values?.[t]?.value;return a?[a]:[]})}async function Iy(){let n=[Vi.join("C:","Program Files","Huawei","DevEco Studio")];for(let e of["HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall","HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"])try{n.push(...await Cd(e,t=>t.normalize("NFKC").trim().toLowerCase().startsWith("deveco studio"),"InstallLocation"))}catch{}for(let e of["HKLM\\SOFTWARE\\Huawei\\DevEco Studio","HKLM\\SOFTWARE\\WOW6432Node\\Huawei\\DevEco Studio"])try{n.push(...await Cd(e,()=>!0,""))}catch{}return n}async function Ad(){let n=zi.platform();if(n==="linux")throw new Error("DevEco Studio is not available on Linux. Set DEVECO_CLI_CLT_PATH to a Command Line Tools installation.");let e=n==="darwin"?Cy():await Iy(),t=Py(e).flatMap(r=>{let i=Er(r);return i?(m(`[ToolProvider] ${r} => version ${i}`),[{root:r,version:i}]):(m(`[ToolProvider] Skipping ${r}: could not read version`),[])});if(!t.length)throw new Error("DevEco Studio installation not found in default locations.");return t.reduce((r,i)=>Rn(i.version,r.version)>0?i:r)}import*as Dd from"fs";import*as ge from"path";function Da(n,e){let t=ge.relative(e,n);return t===""||!ge.isAbsolute(t)&&!t.startsWith(`..${ge.sep}`)&&t!==".."}function rt(n){let e=ge.resolve(n),t=[],r=e;for(;;)try{let i=Dd.realpathSync(r);return t.length===0?i:ge.join(i,...t.reverse())}catch(i){if(i.code!=="ENOENT")throw i;let o=ge.dirname(r);if(o===r)return e;t.push(ge.basename(r)),r=o}}function qi(n,e){let t=rt(e),r=rt(n);return Da(r,t)?r:null}function Yi(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function Ji(n){let e=Yi(n);if(!e)throw new Error("Path must not be empty.");return rt(e)}var br={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},Ki={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 le={APP_ID:"1009",CONFIG_DIR_NAME:".config",APP_NAME:"deveco-cli",TOKEN_FILE_NAME:"token.enc",KEY_FILE_NAME:"token.dek",API_VERSION:"1.0.0",AUTH_SOURCE_DEVECO_CODE:"deveco-code"},We={LOGIN_URL:"https://devecostudio.huawei.com",CN_LOGIN_URL:"https://cn.devecostudio.huawei.com",AUTH_APPLY_PATH:"console/DevEcoIDE/apply",TEMP_TOKEN_CHECK_PATH:"authrouter/auth/api/temptoken/check",JWT_TOKEN_CHECK_PATH:"authrouter/auth/api/jwToken/check",LOGIN_SUCCESS_PATH:"console/DevEcoCLI/loginSuccess",LOGIN_FAILED_PATH:"console/DevEcoCLI/loginFailed",LOGOUT_PATH:"authrouter/auth/api/logout",AGC_TEAM_LIST_URL:"https://connect-api.cloud.huawei.com/api/ups/user-permission-service/v1/user-team-list"},nn={ALGORITHM:"aes-256-gcm",KEY_LENGTH:32,IV_LENGTH:12,KEK_VERSIONS:["kek-v1","kek-v2","kek-v3"]},Pr={baseUrl:We.LOGIN_URL,authUrl:We.AUTH_APPLY_PATH,tempTokenCheckUrl:We.TEMP_TOKEN_CHECK_PATH,jwtTokenCheckUrl:We.JWT_TOKEN_CHECK_PATH,successRedirectUrl:We.LOGIN_SUCCESS_PATH,failedRedirectUrl:We.LOGIN_FAILED_PATH,logoutUrl:We.LOGOUT_PATH,agcTeamListUrl:We.AGC_TEAM_LIST_URL,appId:le.APP_ID,timeout:br.LOGIN_TIMEOUT_MS,countryCode:"CN"};var Ra="https://matrix.openharmony.cn",Ge={TAGS_API_URL:`${Ra}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${Ra}/api/registry/skill/skills`,SKILL_API_BASE:`${Ra}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},Ve={"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 lt}from"os";import be from"path";var it="deveco-mcp";var Rt={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:be.join(lt(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:be.join(process.platform==="win32"?be.join(process.env.APPDATA??be.join(lt(),"AppData","Roaming"),"Trae CN","User"):be.join(lt(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:be.join(lt(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:be.join(lt(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:be.join(process.platform==="win32"?be.join(process.env.APPDATA??be.join(lt(),"AppData","Roaming"),"Qoder","SharedClientCache"):be.join(lt(),"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:be.join(lt(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:be.join(lt(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function kd(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function Rd(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function Td(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function Xi(n,e){return n.format==="opencode"?kd(e):n.format==="claude-code"||n.format==="codex"?Rd(e):Td(e)}var ze={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var ka="https://developer.huawei.com/consumer/cn/download/";var Ay=/^#\s*Version:\s*(\S+)/,Dy="26.0.0.810";function Ry(n){try{let e=JSON.parse(Y.readFileSync(n,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch{return}}function ky(n){let e=S.join(n,"default","openharmony");return[S.join(n,"default","sdk-pkg.json"),...["toolchains","native","previewer"].map(t=>S.join(e,t,"oh-uni-package.json"))]}var I=class n{constructor(e,t,r,i,o,s,a,c,l,p){this._sourceType=e;this._toolchainRoot=t;this._devecoStudioPath=r;this._nodePath=i;this._ohpmJsPath=o;this._hvigorJsPath=s;this._javaPath=a;this._sdkPath=c;this._hdcPath=l;this._emulatorPath=p}_sourceType;_toolchainRoot;_devecoStudioPath;_nodePath;_ohpmJsPath;_hvigorJsPath;_javaPath;_sdkPath;_hdcPath;_emulatorPath;static verifiedPaths=new Set;static powerShellPath;static powerShellModulesPath;static installSourcePromise;get sourceType(){return this._sourceType}get toolchainRoot(){return this._toolchainRoot}get devecoStudioPath(){return this._devecoStudioPath}get nodePath(){return this.verify(this._nodePath)}get ohpmJsPath(){return this._ohpmJsPath}get hvigorJsPath(){return this._hvigorJsPath}get codelinterPath(){return n.resolveCodelinterPath(this._toolchainRoot,this._sourceType)}get javaPath(){return this._javaPath?this.verify(this._javaPath):""}get sdkPath(){return this._sdkPath}get hdcPath(){return this.verify(this._hdcPath)}get emulatorPath(){return this.verify(this._emulatorPath)}get emulatorLauncherPath(){return this.emulatorPath}verify(e){return n.verifiedPaths.has(e)||(n.verifySignature(e),n.verifiedPaths.add(e)),e}assertJava(){if(this._sourceType==="clt"&&!this._javaPath&&(this._javaPath=n.resolveCltJava(!0)),!this._javaPath)throw new Error("Java runtime is required to run hvigor. Set JAVA_HOME or add Java to PATH.");this.verify(this._javaPath)}assertEmulator(){this.verify(this._emulatorPath)}assertStudio(){if(this._sourceType==="clt")throw new Error("This operation requires DevEco Studio. Set DEVECO_CLI_STUDIO_PATH to a DevEco Studio installation.")}assertLsp(){this.assertStudio()}static compareVersion(e,t){return Rn(e,t)}static async checkVersion(){let e=await n.resolveInstallSource();(e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)).assertVersion()}static async new(){let e=await n.resolveInstallSource();return e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)}static fromCLT(e){let t=n.buildToolPaths(e,"clt");return n.assertBuiltPathsInsideRoot(e,t,!1),new n("clt",e,void 0,t.nodePath,t.ohpmJsPath,t.hvigorJsPath,n.resolveCltJava(!1),t.sdkPath,t.hdcPath,t.emulatorPath)}static fromIDE(e,t="studio"){let r=n.buildToolPaths(e,"studio");return n.assertBuiltPathsInsideRoot(e,r,!0),new n(t,e,e,r.nodePath,r.ohpmJsPath,r.hvigorJsPath,r.javaPath,r.sdkPath,r.hdcPath,r.emulatorPath)}assertVersion(){if(this._sourceType==="clt"){this.assertCltVersion();return}this.assertIdeVersion()}assertCltVersion(e="26.0.0"){if(this._sourceType!=="clt")throw new Error("This operation requires Command Line Tools.");n.assertMinimumVersion(n.readCltVersion(this._toolchainRoot),"Command Line Tools","version.txt",e,this._toolchainRoot)}assertIdeVersion(e="6.1.0"){this.assertStudio(),n.assertMinimumVersion(Er(this._toolchainRoot),"DevEco Studio","product-info.json / Info.plist",e,this._toolchainRoot)}require(e){if(this._sourceType==="clt"){this.requireClt(e.clt);return}this.requireIde(e.studio)}requireClt(e){if(e===!1)throw new Error("This operation is not supported in Command Line Tools mode.");typeof e=="string"&&this.assertCltVersion(e)}requireIde(e){if(e===!1)throw new Error("This operation is not supported in DevEco Studio mode.");typeof e=="string"&&this.assertIdeVersion(e)}static assertMinimumVersion(e,t,r,i,o){if(!e)throw new Error(`Failed to determine ${t} version from ${r} at ${o}`);if(!/^\d+(?:\.\d+){1,3}$/.test(e))throw new Error(`Invalid ${t} version "${e}" from ${r} at ${o}`);if(Rn(e,i)<0)throw new Error(`The detected ${t} version is ${e}, which is below the minimum required version ${i}. Upgrade before using deveco-cli:
5
+ ${ka}`)}static resolveCodelinterPath(e,t){let r=n.getCodelinterCandidates(e,t),i=r.find(n.isFile);if(!i){let a=t==="studio"?"Code Linter not found in DevEco Studio.":"Code Linter not found in DevEco Command Line Tools.";throw new Error(`${a}
6
+ Searched paths:
7
+ ${r.join(`
8
+ `)}`)}let o=rt(e),s=rt(i);return n.assertInsideRoot(s,o,"codelinter"),s}static getCodelinterCandidates(e,t){if(t==="studio"){let r=Pe.platform()==="darwin"?["Contents"]:[];return[S.join(e,...r,"plugins","codelinter","run","index.js"),S.join(e,...r,"plugins","codelinter","index.js"),S.join(e,...r,"tools","codelinter","bin","codelinter.js"),S.join(e,...r,"tools","codelinter","codelinter.js")]}return[S.join(e,"codelinter","index.js"),S.join(e,"codelinter","run","index.js"),S.join(e,"tool","codelinter","bin","codelinter.js"),S.join(e,"tool","codelinter","codelinter.js")]}static isValidRoot(e,t){if(!n.isDirectory(e))return!1;if(t==="clt")return Y.existsSync(S.join(e,"version.txt"));let r=Pe.platform()==="darwin"?S.join(e,"Contents"):e,i=Pe.platform()==="darwin"?S.join(r,"Info.plist"):S.join(r,"product-info.json");if(!Y.existsSync(i))return!1;let o=n.buildToolPaths(e,"studio");return[o.nodePath,o.ohpmJsPath,o.hvigorJsPath].every(Y.existsSync)}static buildToolPaths(e,t){return t==="clt"?n.buildCltToolPaths(e):n.buildStudioToolPaths(e)}static buildCltToolPaths(e){let t=S.join(e,"sdk"),r=Pe.platform()==="win32",i=r?".exe":"";return{nodePath:r?S.join(e,"tool","node","node.exe"):S.join(e,"tool","node","bin","node"),ohpmJsPath:S.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:S.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:t,hdcPath:S.join(t,"default","openharmony","toolchains",`hdc${i}`),emulatorPath:S.join(e,"emulator",r?"Emulator.exe":"Emulator")}}static buildStudioToolPaths(e){let t=Pe.platform()==="darwin",r=Pe.platform()==="win32",i=t?S.join(e,"Contents"):e,o=S.join(i,"tools"),s=S.join(i,"sdk"),a=r?".exe":"";return{nodePath:r?S.join(o,"node","node.exe"):S.join(o,"node","bin","node"),ohpmJsPath:S.join(o,"ohpm","bin","pm-cli.js"),hvigorJsPath:S.join(o,"hvigor","bin","hvigorw.js"),javaPath:r?S.join(e,"jbr","bin","java.exe"):t?S.join(i,"jbr","Contents","Home","bin","java"):S.join(i,"jbr","bin","java"),sdkPath:s,hdcPath:S.join(s,"default","openharmony","toolchains",`hdc${a}`),emulatorPath:S.join(o,"emulator",r?"Emulator.exe":"Emulator")}}static isFile(e){try{return Y.statSync(e).isFile()}catch{return!1}}static isDirectory(e){try{return Y.existsSync(e)&&Y.statSync(e).isDirectory()}catch{return!1}}static resolveInstallSource(){return n.installSourcePromise||(n.installSourcePromise=n.resolveInstallSourceUncached()),n.installSourcePromise}static async resolveInstallSourceUncached(){let e=[["DEVECO_CLI_STUDIO_PATH","studio","studio"],["DEVECO_CLI_CLT_PATH","clt","clt"],["DEVECO_HOME","studio","studio"],["DEVECO_PATH","studio","studio"]];for(let[r,i,o]of e){let s=process.env[r]?.trim();if(s){let a=n.resolveExplicitRoot(s,i,r);return m(`[ToolProvider] Using ${r} \u2192 ${a}`),{sourceType:o,toolchainRoot:a}}}let t=await Ad();return m(`[ToolProvider] Using auto \u2192 ${t.root} (${t.version})`),{sourceType:"studio",toolchainRoot:t.root}}static resolveExplicitRoot(e,t,r){let i;try{i=Ji(e)}catch(o){throw new Error(`Invalid ${r}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}return t==="studio"&&Pe.platform()==="darwin"&&(i=n.normalizeMacStudioRoot(i)),n.isValidRoot(i,t)?i:n.throwInvalidSource(i,t,r,e)}static assertBuiltPathsInsideRoot(e,t,r){let i=rt(e),o=[["node",t.nodePath],["ohpm",t.ohpmJsPath],["hvigor",t.hvigorJsPath],["sdk",t.sdkPath],["hdc",t.hdcPath],["emulator",t.emulatorPath]];r&&t.javaPath&&o.push(["java",t.javaPath]);for(let[s,a]of o)n.assertInsideRoot(a,i,s)}static assertInsideRoot(e,t,r){if(qi(e,t)===null)throw new Error(`Unsafe toolchain path: ${r} resolves outside the toolchain root`)}static throwInvalidSource(e,t,r,i){throw t==="clt"&&n.isValidRoot(e,"studio")?new Error(`${r} must point to Command Line Tools, not a DevEco Studio installation; use DEVECO_CLI_STUDIO_PATH instead`):t==="studio"&&n.isValidRoot(e,"clt")?new Error(`${r} must point to a DevEco Studio installation, not Command Line Tools; use DEVECO_CLI_CLT_PATH instead`):new Error(`Invalid ${r}: ${i}`)}static normalizeMacStudioRoot(e){let t=`${S.sep}Contents`,r=S.normalize(e);return r.endsWith(t)?r.slice(0,-t.length):r}static readCltVersion(e){try{return Y.readFileSync(S.join(e,"version.txt"),"utf-8").split(/\r?\n/).map(t=>t.match(Ay)?.[1]?.trim()).find(Boolean)}catch{return}}static resolveCltJava(e){let t=process.env.JAVA_HOME?.trim(),r=t&&(n.javaIn(S.join(t,"bin"))??n.javaIn(t)),i=(process.env.Path??process.env.PATH??"").split(S.delimiter).map(s=>n.javaIn(s.trim())).find(Boolean),o=r??i;if(o)return Y.realpathSync(o);if(e)throw new Error("No Java runtime found in CLT mode. Set JAVA_HOME to a JDK/JBR installation directory (or point JAVA_HOME at the JDK bin directory), or add the JDK bin directory to PATH.");return""}static javaIn(e){return(Pe.platform()==="win32"?["java.exe","java.cmd"]:["java"]).map(r=>S.join(e,r)).find(Y.existsSync)}getMaxApiLevel(){for(let e of ky(this.sdkPath)){let t=Ry(e);if(t!==void 0)return t}return 23}detectApiLevel(){return this.getMaxApiLevel()}_apiscanPaths;getApiscanPaths(){if(this._apiscanPaths)return this._apiscanPaths;let e=Pe.platform();if(e!=="darwin"&&e!=="win32")throw new Error(`Unsupported platform: ${e}. compat only supports macOS and Windows.`);if(!this._devecoStudioPath)throw new Error("DevEco Studio is required for compatibility checking. Set DEVECO_CLI_STUDIO_PATH or install DevEco Studio.");let t=e==="darwin"?"Contents":"",r=S.join(this._devecoStudioPath,t,"plugins","harmony","arkanalyzer-apiscan"),i=S.join(r,"resources","apiChange"),o=S.join(r,"api-change-scan.js");if(!Y.existsSync(i)||!Y.existsSync(o)){let s=Er(this._toolchainRoot)??"unknown";throw new Error(`A required component is missing. The detected DevEco Studio version is ${s}. The minimum required version is ${Dy}. Upgrade before using 'check compat' at ${ka}`)}return this._apiscanPaths={apiChangeDir:i,scriptPath:o},this._apiscanPaths}static verifySignature(e){if(!Y.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=Pe.platform();if(t==="linux"){n.assertExecutable(e);return}if(t==="win32"&&S.extname(e).toLowerCase()===".exe"){n.assertSigned(n.verifyWindowsSignature(e),e);return}t==="darwin"&&(n.assertExecutable(e),n.assertSigned(n.verifyMacSignature(e),e))}static assertExecutable(e){try{if(!Y.statSync(e).isFile())throw new Error;Y.accessSync(e,Y.constants.X_OK)}catch{throw new Error(`executable is not accessible: ${e}`)}}static assertSigned(e,t){if(!e.signed)throw new Error(`The executable is not digitally signed: ${t}`)}static findPowerShellPath(){if(n.powerShellPath!==void 0)return n.powerShellPath;let e=S.join(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return n.powerShellPath=Y.existsSync(e)?e:"",n.powerShellPath&&(n.powerShellModulesPath=S.join(S.dirname(n.powerShellPath),"Modules")),n.powerShellPath}static verifyWindowsSignature(e){let t=n.findPowerShellPath();if(!t)throw new Error("The PowerShell application was not found");let r=Y.mkdtempSync(S.join(Pe.tmpdir(),"deveco-verify-")),i=S.join(r,"Verify-Signature.ps1");Y.writeFileSync(i,"Get-AuthenticodeSignature -FilePath $args[0] | ConvertTo-Json -Depth 3 -Compress","utf8");try{let o=xd(t,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",i,e],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"],env:{...process.env,PSModulePath:n.powerShellModulesPath}}),s=JSON.parse(o);return{signed:Number(s.Status)===0}}catch(o){return m(`[ToolProvider] verify Windows Signature, error msg: ${o}`),{signed:!1}}finally{Y.rmSync(r,{recursive:!0,force:!0})}}static verifyMacSignature(e){try{return xd("codesign",["-v",e],{encoding:"utf8",timeout:5e3,stdio:["ignore","ignore","ignore"]}),{signed:!0}}catch{return{signed:!1}}}};import{execa as Ty}from"execa";import*as Cr from"path";var dt=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let i=Cr.dirname(e.javaPath),o=`${i}${Cr.delimiter}${process.env.PATH||""}`,s={...process.env,PATH:o,DEVECO_SDK_HOME:e.sdkPath};e.sourceType==="clt"&&e.javaPath&&(s.JAVA_HOME=Cr.dirname(i)),this.env=s}async sync(e,t){let r=["--sync","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(r)}async buildProduct(e,t){let r=["assembleApp","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(r)}async buildModules(e,t,r,i){let o=[...Array.from(i),"--mode","module","-p",`module=${r.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];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 compileNative(e,t){let r=["--mode","module"];t&&r.push("-p",`module=${t}`),r.push("-p",`product=${e}`,"compileNative","--analyze=normal"),await this.runHvigor(r)}async runHvigor(e){let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];m(`Executing: ${t} ${r.join(" ")}`);let i=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit";await Ty(t,r,{cwd:this.projectRoot,env:this.env,stdout:i,stderr:i})}};import{execa as xy}from"execa";var kn=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 xy(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"})}};import{mkdir as Ly}from"fs/promises";import{dirname as Ny,resolve as Oy}from"path";import{execa as My}from"execa";import{lock as Ta,check as Jx}from"proper-lockfile";function xa(n){return Oy(n,".hvigor",".build-lock")}function _y(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function Ld(n){let e=Ny(xa(n));if(await Ly(e,{recursive:!0}),process.platform==="win32")try{await My("attrib",["+h",e])}catch{}}async function Fy(n,e){let t=new AbortController,r=_y(e);await Ld(n);let i={lockfilePath:xa(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await Ta(n,{...i,retries:0}),signal:t.signal}}catch(s){if(s&&typeof s=="object"&&"code"in s&&s.code!=="ELOCKED")throw s}return r(),{release:await Ta(n,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function rn(n,e,t){let{release:r,signal:i}=await Fy(n,t);try{return await e(i)}finally{await r()}}async function Zi(n,e){let t=new AbortController;await Ld(n);let r={lockfilePath:xa(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},i;try{i=await Ta(n,{...r,retries:0})}catch(o){if(o&&typeof o=="object"&&"code"in o&&o.code==="ELOCKED")return{acquired:!1};throw o}try{return{acquired:!0,result:await e(t.signal)}}finally{await i()}}import*as kt from"fs";import*as on from"path";import jy from"json5";var $y=1e3;function eo(n){m(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=on.join(n,ze.SYNC_OUTPUT_PATH);if(!kt.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return m(`[ProjectCheck] ${l.reason}`),l}let t=kt.statSync(e).mtimeMs;m(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=Hy(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return m(`[ProjectCheck] ${l.reason}`),l}let i=on.join(n,ze.OH_PACKAGE_JSON5),o=Qi(i,t,"root");if(o.required)return m(`[ProjectCheck] Root check: ${o.reason}`),o;let s=on.join(n,ze.BUILD_PROFILE_JSON5),a=Qi(s,t,"build-profile");if(a.required)return m(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let p=on.join(n,l.srcPath,ze.OH_PACKAGE_JSON5),g=Qi(p,t,l.name);if(g.required)return m(`[ProjectCheck] Module '${l.name}' check: ${g.reason}`),g;let w=on.join(n,l.srcPath,ze.BUILD_PROFILE_JSON5),C=Qi(w,t,l.name);if(C.required)return m(`[ProjectCheck] Module '${l.name}' build-profile check: ${C.reason}`),C}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return m(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function Qi(n,e,t){if(!kt.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=kt.statSync(n).mtimeMs;return r-e>$y?{required:!0,reason:`${t}: source mtime (${new Date(r).toISOString()}) is newer than sync baseline (${new Date(e).toISOString()})`}:{required:!1,reason:`${t}: up-to-date`}}function Hy(n){let e=on.join(n,ze.BUILD_PROFILE_JSON5);try{let t=kt.readFileSync(e,"utf-8");if(!t.trim())return null;let r=jy.parse(t);if(typeof r!="object"||r===null)return null;let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):null}catch{return null}}import*as Ie from"fs";import*as Ne from"path";import*as qd from"util";import*as O from"fs";import*as uo from"path";import T from"fs";import*as to from"os";import*as A from"path";import Uy from"json5";var La="Huawei";var Md=3,_d=3,Nd="DevEco Studio",Fd={DevEcoStudio:"deveco_studio"};function no(n){if(!T.existsSync(n)||!T.statSync(n).isDirectory())return!1;let e=T.existsSync(A.join(n,"build-profile.json5")),t=T.existsSync(A.join(n,"hvigorfile.js"))||T.existsSync(A.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=T.readFileSync(A.join(n,"build-profile.json5"),"utf-8");return Uy.parse(r).app!==void 0}catch{return!1}}function Na(n,e,t){if(e>=t)return null;let r=By(n),i=Wy(r);if(i)return i;for(let o of r){let s=Na(o,e+1,t);if(s)return s}return null}function By(n){try{let e=T.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(A.join(n,r.name));return t}catch{return[]}}function Wy(n){for(let e of n)if(no(e))return e;return null}function ut(n){if(!n||n.trim()==="")return null;let e=A.resolve(n),t;try{t=T.realpathSync(e)}catch{t=e}if(!T.existsSync(t))return null;if(no(t))return t;let r=t;for(let i=1;i<=3;i++){let o=A.dirname(r);if(o===r)break;if(no(o))return o;r=o}if(T.statSync(t).isDirectory()){let i=Na(t,0,Md);if(i)return i}return null}function ro(n){if(!n||n.trim()==="")return null;let e=A.resolve(n),t;try{t=T.realpathSync(e)}catch{t=e}return!T.existsSync(t)||!T.statSync(t).isDirectory()?null:no(t)?t:Na(t,0,Md)}function Gy(n){let e=n??Ma();if(!e)return null;let t=null;if(process.platform==="win32"?t=A.join(e,"plugins","openharmony"):process.platform==="darwin"&&(t=A.join(e,"contents","plugins","openharmony")),t){let o=A.join(t,"ace-server","out","index.js");if(T.existsSync(o))return t}let r=A.join(e,"arkts-lsp","lib"),i=A.join(r,"out","index.js");return T.existsSync(i)?r:null}function Oa(n){let e=Yy(n??""),t=jd(e);return A.join(t,"sdk")}function io(n){return{sdkPath:Oa(n),arktsLangServerPath:Gy(n)}}function Ir(n,e){let t=e?A.join("standardIndex","index.js"):"index.js";return T.existsSync(A.join(n,"ace-server"))?A.join(n,"ace-server","out",t):A.join(n,"out",t)}function oo(n){return T.existsSync(Ir(n,!0))}var Vy=["default","openharmony","native","llvm","bin","clangd"],zy=[".idea",".deveco","cxx","compile_commands.json"];function so(n){let e=A.join(n,...Vy),t=process.platform==="win32"?e+".exe":e;return T.existsSync(t)?t:null}function Ar(n){return A.join(n,...zy)}function Ma(){if(process.platform==="win32"){let n=[A.join("C:\\Program Files",La,Nd),A.join("C:\\Program Files (x86)",La,Nd)];return Od(n)}if(process.platform==="darwin"){let n=["/Applications/DevEco Studio.app",A.join(process.env.HOME??"","Applications","DevEco Studio.app")];return Od(n)}return null}function Od(n){for(let e of n)if(T.existsSync(e))return e;return null}function jd(n){return process.platform==="darwin"?A.join(n,"Contents"):n}function qy(n){if(!n||!T.existsSync(n)||!$d(n))return!1;let e=jd(n);return[A.join(e,"plugins","openharmony"),A.join(e,"sdk"),A.join(e,"tools")].some(r=>T.existsSync(r))}function $d(n){try{return T.statSync(n).isDirectory()}catch{return!1}}function _a(n,e){return!n||!T.existsSync(n)?!1:e===Fd.DevEcoStudio?qy(n):!1}function Yy(n,e=Fd.DevEcoStudio){if(!n)return"";if(_a(n,e))return n;let t=Jy(n,e);if(t)return t;let r=Ky(n,e);return r||n}function Jy(n,e){let t=n;for(let r=0;r<_d;r++){let i=A.dirname(t);if(!i||i===t)break;if(_a(i,e))return i;t=i}return null}function Ky(n,e){if(!T.existsSync(n)||!$d(n))return null;let t=[{p:n,depth:0}];for(;t.length>0;){let{p:r,depth:i}=t.shift();if(i>=_d)continue;let o=Xy(r,i,e,t);if(o)return o}return null}function Xy(n,e,t,r){let i;try{i=T.readdirSync(n,{withFileTypes:!0})}catch{return null}for(let o of i){if(!o.isDirectory())continue;let s=A.join(n,o.name);if(_a(s,t))return s;r.push({p:s,depth:e+1})}return null}function Hd(n){return new Promise(e=>setTimeout(e,n))}var Zy=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function sn(n){let e=A.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&Zy.has(e)}function ao(n){return A.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function re(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function Qy(n){return re(n)}function an(n){let e=Qy(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function Tt(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??A.join(to.homedir(),"AppData","Local");return A.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?A.join(to.homedir(),"Library","Logs","devecocli-mcp-server"):A.join(to.homedir(),".local","share","devecocli-mcp-server","logs")}function Ud(n,e){let t=ew(e),r=tw(t,n);if(r!==null)return r;let i=Date.now(),s=`${n.replace(/:/g,"\\:")}=${i}`,a=nw(t,n,s);return rw(e,a),i}function ew(n){let e;try{e=T.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function tw(n,e){for(let t of n){let r=t.indexOf("=");if(r<=0||t.slice(0,r).replace(/\\:/g,":")!==e)continue;let o=parseInt(t.slice(r+1),10);return Number.isFinite(o)&&o>0?o:null}return null}function nw(n,e,t){let r=!1,i=n.map(o=>{if(r)return o;let s=o.indexOf("=");return s<=0?o:o.slice(0,s).replace(/\\:/g,":")===e?(r=!0,t):o});return r||i.push(t),i}function rw(n,e){try{T.mkdirSync(A.dirname(n),{recursive:!0})}catch{}try{T.writeFileSync(n,e.join(`
9
+ `)+`
10
+ `,"utf8")}catch{}}function Fa(n,e,t="[Cleanup]"){try{let r=A.dirname(n);if(!T.existsSync(r))return;let i=Date.now();for(let o of T.readdirSync(r,{withFileTypes:!0}))o.isDirectory()&&iw(A.join(r,o.name),i,e,t)}catch{}}function iw(n,e,t,r){try{let{mtimeMs:i}=T.statSync(n);if(e-i<=t)return;T.rmSync(n,{recursive:!0,force:!0});let o=Math.floor((e-i)/1e3);console.error(`${r} Removed expired dir (age ${Math.floor(o/86400)}d ${Math.floor(o%86400/3600)}h): ${n}`)}catch(i){console.error(`${r} Failed to remove expired dir ${n}: ${i}`)}}function co(n){let e=n.replace(/sdk\/?$/i,"tools"),t=process.platform==="win32"?"node.exe":"node",r=A.join(e,"node",t);return T.existsSync(r)||process.platform!=="win32"&&(r=A.join(e,"node","bin","node"),T.existsSync(r))?r:process.execPath??"node"}var Bd="mcp-server.log",ow="mcp-server",sw={maxSize:10*1024*1024,maxFiles:4},ja=class n{fd=null;logDir=null;currentLogFile=null;mode;rotationOptions;currentFileSize=0;currentDate="";isRotating=!1;minLevel;static LEVEL_ORDER={debug:0,info:1,warn:2,error:3};constructor(e,t){this.rotationOptions={...sw,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=Tt(),this.currentLogFile=uo.join(this.logDir,Bd),O.existsSync(this.logDir)||O.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${i}`}getRotatedFileName(e,t){return uo.join(this.logDir,`${ow}-${e}.log.${t}`)}fileExists(e){try{return O.accessSync(e,O.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=O.readdirSync(this.logDir),t=[];for(let i of e)if(i===Bd||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=uo.join(this.logDir,i),s=O.statSync(o);t.push({name:i,mtime:s.mtime,path:o})}t.sort((i,o)=>o.mtime.getTime()-i.mtime.getTime());let r=1+this.rotationOptions.maxFiles;for(let i=r;i<t.length;i++)try{O.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)&&O.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)&&O.renameSync(o,s)}let r=this.getRotatedFileName(e,1);O.renameSync(this.currentLogFile,r),this.cleanupOrphanLogFiles(),this.openLogFile()}catch{this.openLogFile()}finally{this.isRotating=!1}}}openLogFile(){if(this.currentLogFile){this.currentDate=this.getCurrentDateString();try{if(this.fileExists(this.currentLogFile)){let e=O.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=O.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{O.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...r){if(this.mode==="silent"||n.LEVEL_ORDER[e]<n.LEVEL_ORDER[this.minLevel])return;let i=r.map(c=>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}
11
+ `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);O.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{O.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},xe=null;function cn(n=!1){xe&&xe.dispose(),xe=new ja(n)}function Wd(){xe&&(xe.dispose(),xe=null)}function Gd(){xe&&xe.flush()}function Vd(){return xe?.getLogFilePath()??null}function zd(){return xe?.getLogDirectory()??null}function lo(){return xe||cn(!1),xe}var h={debug:(n,...e)=>lo().debug(n,...e),info:(n,...e)=>lo().info(n,...e),warn:(n,...e)=>lo().warn(n,...e),error:(n,...e)=>lo().error(n,...e)};var $a="";function fo(n){if(!n||n==="auto"||n==="stdout"||n==="none"){$a="";return}$a=n}function Yd(){return $a||(zd()??"")}function po(n,...e){if(e.length===0)return n;try{return qd.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var f={info(n,...e){h.info(`[lsp] ${po(n,...e)}`)},warn(n,...e){h.warn(`[lsp] ${po(n,...e)}`)},error(n,...e){h.error(`[lsp] ${po(n,...e)}`)},debug(n,...e){h.debug(`[lsp] ${po(n,...e)}`)}};import*as Dr from"fs";import*as Rr from"os";import*as Tn from"path";import aw from"json5";var y={INITIALIZE:"initialize",INITIALIZED:"initialized",SHUTDOWN:"shutdown",EXIT:"exit",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",DID_CLOSE:"textDocument/didClose",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",DECLARATION:"textDocument/declaration",REFERENCES:"textDocument/references",IMPLEMENTATION:"textDocument/implementation",COMPLETION:"textDocument/completion",COMPLETION_ITEM_RESOLVE:"completionItem/resolve",SIGNATURE_HELP:"textDocument/signatureHelp",CODE_ACTION:"textDocument/codeAction",PREPARE_RENAME:"textDocument/prepareRename",RENAME:"textDocument/rename",DOCUMENT_HIGHLIGHT:"textDocument/documentHighlight",DOCUMENT_LINK:"textDocument/documentLink",INLAY_HINT:"textDocument/inlayHint",DOCUMENT_SYMBOL:"textDocument/documentSymbol",WORKSPACE_SYMBOL:"workspace/symbol",DIAGNOSTIC:"textDocument/diagnostic",WORKSPACE_DIAGNOSTIC:"workspace/diagnostic",PREPARE_CALL_HIERARCHY:"textDocument/prepareCallHierarchy",INCOMING_CALLS:"callHierarchy/incomingCalls",OUTGOING_CALLS:"callHierarchy/outgoingCalls",PREPARE_TYPE_HIERARCHY:"textDocument/prepareTypeHierarchy",SUPERTYPES:"typeHierarchy/supertypes",SUBTYPES:"typeHierarchy/subtypes",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",DID_CREATE_FILES:"workspace/didCreateFiles",DID_DELETE_FILES:"workspace/didDeleteFiles",PROGRESS:"$/progress",WINDOW_SHOW_MESSAGE:"window/showMessage",WINDOW_LOG_MESSAGE:"window/logMessage",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing",ARKTS_ERROR:"arkts/error",CPP_INITIALIZED:"cpp/initialized",CPP_INITIALIZATION_FAILED:"cpp/initializationFailed",CPP_INDEXING_PROGRESS:"cpp/indexingProgress",CPP_SYNC_PROJECT:"cpp/syncProject",CPP_SYNC_COMPLETED:"cpp/syncCompleted",CPP_REINITIALIZING:"cpp/reinitializing",CPP_ERROR:"cpp/error",BROADCAST:"lsp/broadcast"},R="2.0";var Jd=8192,Ha=100,Kd=.03,Xd=.7,Le=900*1e3;function Ce(n){if(!Dr.existsSync(n))return null;try{let e=Dr.readFileSync(n,"utf-8");return e.trim()?aw.parse(e):null}catch{return null}}function mo(n,e){let t=Math.floor(Rr.totalmem()/1048576),r=Math.floor(t*Xd),i,o;e!==void 0&&Number.isFinite(e)&&e>0?(i=e,o=`override(${e})`):(i=Jd,n>Ha&&(i+=(n-Ha)*Kd*1024),o=`formula(moduleCount=${n})`);let s=r>0&&i>r;s&&(i=r);let a=Math.round(i);return f.info(`[computeLspServerMaxSize] source=${o}, physicalTotal=${t}MB, physicalCap(70%)=${r}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function qe(n){if(n.startsWith("file:"))return n;try{let e=Tn.resolve(n),t=new URL(`file://${e}`).toString();if(Rr.platform()==="win32"){let r=t.match(/^file:\/\/\/([A-Za-z]):/);if(r){let i=r[1].toUpperCase(),o=t.substring(`file:///${r[1]}:`.length);t=`file:///${i}%3A${o}`}}return t}catch{return n}}function xn(n){return n&&n.replace(/\\/g,"/")}function j(n){let e=Tn.normalize(n).replace(/\\/g,"/");if(Rr.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function Zd(n){return Tn.join(n,"build-profile.json5")}var pt=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=Zd(this.projectRoot);try{let t=Ce(e);if(typeof t!="object"||t===null)return[];let r=t.modules;return Array.isArray(r)?r.filter(i=>{if(typeof i!="object"||i===null)return!1;let o=i;return typeof o.name=="string"&&typeof o.srcPath=="string"}):[]}catch(t){return f.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};import{spawn as cw}from"child_process";import*as yo from"path";import*as go from"fs";var lw=600*1e3;function dw(n,e,t){let r=t.split(/\s+/).filter(i=>i.length>0);return[n,[e,...r]]}function uw(n){let e=[],t=[];return n.stdout?.on("data",r=>{e.push(r.toString())}),n.stderr?.on("data",r=>{t.push(r.toString())}),{stdout:e,stderr:t}}function ho(n){return n.join("")}function pw(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
12
+ Output so far:
13
+ `+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function fw(n,e,t){return new Promise(r=>{let i=cw(n[0],n[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:o,stderr:s}=uw(i),a=setTimeout(()=>{i.kill();let c=[ho(o),ho(s)].filter(Boolean).join(`
14
+ `).trim();r({success:!1,output:`Build process timeout after 10 minutes.
15
+ Output so far:
16
+ `+c,exitCode:-1})},lw);i.on("close",(c,l)=>{clearTimeout(a);let p=[ho(o),ho(s)].filter(Boolean).join(`
17
+ `).trim()||"";r(pw(c,l,p))}),i.on("error",c=>{clearTimeout(a),r({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function Ua(n,e,t,r,i){let o={...process.env,DEVECO_SDK_HOME:r},s=dw(e,t,i);return await fw(s,n,o)}function mw(n){let e=yo.join(yo.dirname(n),"tools","hvigor","bin","hvigorw.js");return{node_path:co(n),hvigor_path:e,sdk_path:n}}function hw(n){return!n.node_path||!go.existsSync(n.node_path)?`Node path not found or invalid: ${n.node_path}`:!n.hvigor_path||!go.existsSync(n.hvigor_path)?`Hvigor path not found or invalid: ${n.hvigor_path}`:!n.sdk_path||!go.existsSync(n.sdk_path)?`SDK path not found or invalid: ${n.sdk_path}`:null}var gw="--sync -p product=default --analyze=normal --parallel --incremental --no-daemon";async function Qd(n,e){try{let t=mw(e),r=hw(t);return r!=null?(f.info(`Config validation failed: ${r}`),!1):(await Ua(n,t.node_path,t.hvigor_path,e,gw)).success}catch(t){return f.info(`syncProject failed: ${JSON.stringify(t)}`),!1}}function yw(n){let e=Ne.extname(n).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh","c++","h++"].includes(e)}function ww(n,e){let t=Ne.join(n,e.name);return e.isDirectory()?e.name===".cxx"||eu(t):yw(t)}function eu(n){if(!Ie.existsSync(n))return!1;try{return Ie.readdirSync(n,{withFileTypes:!0}).some(t=>ww(n,t))}catch{}return!1}function ln(n){let t=new pt(n).getAllModuleInfo(),r=[];for(let i of t){let o=P.resolvePathWithinRoot(n,i.srcPath);eu(o)&&r.push(i)}return r}function vw(n){let e=[],r=new pt(n).getAllModuleInfo();for(let i of r){let o=P.resolvePathWithinRoot(n,i.srcPath),s=Ne.join(o,".cxx");Ie.existsSync(s)&&tu(s,e)}return e}function tu(n,e){try{let t=Ie.readdirSync(n,{withFileTypes:!0});for(let r of t){let i=Ne.join(n,r.name);r.isDirectory()?tu(i,e):r.name==="compile_commands.json"&&e.push(i)}}catch{}}function Sw(n){let e=[];for(let t of n)try{let r=Ie.readFileSync(t,"utf8"),i=JSON.parse(r);e.push(...i)}catch{}return e}function Ew(n,e){let t=Ne.join(n,...bw.slice(0,-1));Ie.mkdirSync(t,{recursive:!0});let r=Ne.join(t,"compile_commands.json");Ie.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function Ba(n){let e=vw(n);if(e.length>0){let t=Sw(e);Ew(n,t),h.info(`[CppCompile] compile_commands.json generated, ${t.length} compile commands`)}else h.warn("[CppCompile] No compile_commands.json files found")}var bw=[".idea",".deveco","cxx","compile_commands.json"];async function Pw(n,e,t){let r=Ne.join(Ne.dirname(e),"tools"),i=Ne.join(r,"hvigor","bin","hvigorw.js"),o=process.execPath||"node";h.info(`[CppCompile] sdkPath: ${e}, toolsDir: ${r}, hvigorPath: ${i}`);for(let s of t){let a=["--mode","module","-p",`module=${s.name}`,"-p","product=default","compileNative","--analyze=normal","--parallel","--incremental","--no-daemon"].join(" ");h.info(`[CppCompile] Running compileNative for module: ${s.name}`);let c=await Ua(n,o,i,e,a);c.success?h.info(`[CppCompile] compileNative ${s.name} succeeded`):h.warn(`[CppCompile] compileNative ${s.name} failed: ${c.output}`)}}async function nu(n,e){let t=ln(n);if(t.length===0){h.info("[CppCompile] No C++ modules found, skipping initialization");return}h.info(`[CppCompile] Found ${t.length} C++ module(s): ${t.map(r=>r.name).join(", ")}`),await Pw(n,e,t),Ba(n)}function Iw(n,e){if(e.product&&n.validateProduct(e.product),e.buildMode&&!n.profile.app.buildModeSet.some(r=>r.name===e.buildMode))throw new Error(`Build mode '${e.buildMode}' not found in project build-profile.json5.`)}function Aw(n,e){let t;if(e.modules&&e.modules.length>0)t=e.modules;else{let i=n.profile.modules,o=i.filter(s=>n.getModuleType(s.name)==="entry");if(i.length===1)t=[i[0].name];else if(o.length===1)t=[o[0].name];else throw o.length>1?new 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 r=new Set;for(let i of t){let o=i.indexOf("@"),s=o!==-1?i.substring(0,o):i,a=o!==-1?i.substring(o+1):"default";r.add(`${s}@${a}`)}return Array.from(r)}function za(n,e){let t=new Set;for(let r of e){let i=r.indexOf("@"),o=i!==-1?r.substring(0,i):r,s=n.getModuleType(o);s==="shared"?t.add("assembleHsp"):s==="har"?t.add("assembleHar"):t.add("assembleHap")}return t}function kr(n,e){let t=e,r=`${n} failed`;console.error(Ga(r));let i=t.stdout||t.message;throw i&&console.error(i),t.stderr&&console.error(t.stderr),new Error(r,{cause:e})}async function qa(n,e,t,r,i,o){let s=eo(o);console.log(`
18
+ [ohpm install] Running...`);try{await n.installAll()}catch(a){kr("ohpm install",a)}if(s.required){console.log(`
19
+ [hvigor sync] Running...`);try{await e.sync(t,r)}catch(a){kr("hvigor sync",a)}}else console.log(`
20
+ [hvigor sync] Skipped (configurations unchanged)`);console.log(`
21
+ [hvigor build] Running...`);try{i.type==="product"?await e.buildProduct(t,r):await e.buildModules(t,r,i.modulesToBuild,i.moduleTasks)}catch(a){kr("hvigor build",a)}Dw(o)}function Dw(n){try{if(ln(n).length===0)return;Ba(n),console.log(Wa(`
22
+ Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(Va(`
23
+ Failed to merge compile_commands.json: ${e.message}`))}}var ru=new Cw("build").description("Build HarmonyOS project").option("--product <product>","Product name defined in build-profile.json5 (default: default)").option("--modules <modules...>","Modules to build (format: module or module@target)").option("--build-mode <mode>","Build mode (buildModeSet in build-profile.json5; e.g. debug, release; default: debug)").action(async n=>{try{let e=process.cwd(),t=U.discover(e);console.warn(Va("Ensure the project source is trustworthy before proceeding."));let r=await I.new();r.assertJava(),Iw(t,n);let i=n.product||"default",o=n.buildMode||"debug",s;if(n.product&&!n.modules)s={type:"product"};else{let l=Aw(t,n),p=za(t,l);s={type:"modules",modulesToBuild:l,moduleTasks:p}}let a=new kn(r,t.rootDir),c=new dt(r,t.rootDir);await rn(t.rootDir,async()=>qa(a,c,i,o,s,t.rootDir),()=>{console.log("Another build is already running for this project. Waiting for completion...")}),console.log(`
24
+ `+Wa("Build completed successfully"))}catch(e){console.error(Ga(e.message)),process.exit(1)}});ru.command("clean").description("Clean HarmonyOS project build outputs").action(async()=>{try{let n=process.cwd(),e=U.discover(n);console.warn(Va("Ensure the project source is trusted before proceeding."));let t=await I.new();t.assertJava();let r=new dt(t,e.rootDir);await rn(e.rootDir,async()=>{console.log(`
25
+ [1/2] Running hvigor clean...`);try{await r.clean()}catch(i){kr("hvigor clean",i)}console.log(`
26
+ [2/2] Running hvigor --stop-daemon...`);try{await r.stopDaemon()}catch(i){kr("hvigor --stop-daemon",i)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
27
+ `+Wa("Clean completed successfully."))}catch(n){console.error(Ga(n.message)),process.exit(1)}});var iu=ru;import{Command as Xw}from"commander";import{green as wu,red as Zw,yellow as Co}from"colorette";import*as Io from"path";import{randomUUID as Hw}from"crypto";import{execa as Uw}from"execa";import{execa as $w}from"execa";import{execFile as Rw,spawn as kw}from"child_process";import{promisify as Tw}from"util";var xw=Tw(Rw);function ou(n,e,t){let i=n.replace(/\r\n/g,`
20
28
  `).split(`
21
- `),o=i.pop()??"",s=i.map(a=>a.endsWith("\r")?a.slice(0,-1):a).filter(a=>a.length>0);return s.length>0&&t.onData(s,e),o}function Ai(r,e,t){let n=r.endsWith("\r")?r.slice(0,-1):r;n.length>0&&t.onData([n],e)}function Ca(r,e){return{stdout:r.stdoutChunks.join(""),stderr:r.stderrChunks.join(""),exitCode:e??0}}function Da(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function Ia(r,e,t,n,i){r.stdout?.on("data",o=>{let s=o.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=Ii(e.stdoutLineBuffer+s,"stdout",t)}),r.stderr?.on("data",o=>{let s=o.toString();e.stderrChunks.push(s),e.stderrLineBuffer=Ii(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,Ai(e.stdoutLineBuffer,"stdout",t),Ai(e.stderrLineBuffer,"stderr",t),t.onClose(o);let s=Ca(e,o);s.exitCode!==0&&t.onError(new Error(`Command process exited with code ${s.exitCode}`)),n(s)})}async function ki(r,e=[],t={}){try{let{stdout:n,stderr:i}=await Ea(r,e,t);return{stdout:typeof n=="string"?n.trim():"",stderr:typeof i=="string"?i.trim():"",exitCode:0}}catch(n){let i=n;return{stdout:i.stdout?.trim()||"",stderr:i.stderr?.trim()||i.message,exitCode:typeof i.code=="number"?i.code:1}}}async function Ti(r,e,t){return await new Promise((n,i)=>{let o=Sa(r,e,{stdio:["inherit","pipe","pipe"]}),s=Da();Ia(o,s,t,n,i)})}function Ri(r){let e=r.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var Aa=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],ka=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function qe(r){return r?Aa.some(e=>e.test(r))?"transient":ka.some(e=>e.test(r))?"fatal":"ok":"ok"}var ur=[800,1500,2500];function Ta(r){return new Promise(e=>setTimeout(e,r))}async function Pe(r,e){let t=1+ur.length,n={stdout:"",stderr:"",exitCode:-1};for(let i=0;i<t;i++){n=await ki(r,e);let o=n.exitCode===0?n.stdout:n.stderr||n.stdout;if(qe(o)!=="transient"||i>=t-1)return n;v(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${ur[i]}ms`),await Ta(ur[i])}return n}async function Jt(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||qe(i)!=="ok"))return Ri(i)}var pr="__DEVECO_PARAM_DELIM__";function Ra(r,e){let t=new Map,n=r.split(pr);for(let i=0;i<e.length;i++){let o=(n[i]??"").trim();if(!o||qe(o)!=="ok")continue;let s=Ri(o);s&&t.set(e[i],s)}return t}async function Ve(r,e,t){if(t.length===0)return new Map;if(t.length===1){let s=new Map,a=await Jt(r,e,t[0]);return a&&s.set(t[0],a),s}let n=t.map(s=>`param get ${s}`).join(`; echo ${pr}; `)+`; echo ${pr}`,i=await Pe(r,["-t",e,"shell",n]);if(i.exitCode===0){let s=Ra(i.stdout,t);if(s.size>0)return s}v(`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 Jt(r,e,s);a&&o.set(s,a)}return o}function Pt(r){return r.startsWith("127.0.0.1:")}var xi=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],G=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 xa(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let n of e.split(`
22
- `)){let i=n.trim();if(!i||i.startsWith("[Empty]"))continue;let o=i.split(/\s+/),s=o[0];!s||s.startsWith("[Empty]")||t.push({serial:s,status:o.length>=2?o[1]:"device"})}return t}extractDisplayName(e){let t=e.get("ohos.qemu.hvd.name");if(t)return t;let n=e.get("const.product.name");if(n&&n!=="emulator")return n;let i=e.get("const.product.model");if(i&&i!=="emulator"){let s=e.get("const.product.brand");return this.stripBrandPrefix(i,s)}let o=e.get("const.build.product");if(o&&o!=="emulator")return o}async getDeviceName(e){let t=await Ve(this.hdcPath,e,[...xi]);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:
29
+ `),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 su(n,e,t){let r=n.endsWith("\r")?n.slice(0,-1):n;r.length>0&&t.onData([r],e)}function Lw(n,e){return{stdout:n.stdoutChunks.join(""),stderr:n.stderrChunks.join(""),exitCode:e??-1}}function Nw(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function Ow(n,e,t,r,i){n.stdout?.on("data",o=>{let s=o.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=ou(e.stdoutLineBuffer+s,"stdout",t)}),n.stderr?.on("data",o=>{let s=o.toString();e.stderrChunks.push(s),e.stderrLineBuffer=ou(e.stderrLineBuffer+s,"stderr",t)}),n.on("error",o=>{e.settled||(e.settled=!0,t.onError(o),i(o))}),n.on("close",o=>{if(e.settled)return;e.settled=!0,su(e.stdoutLineBuffer,"stdout",t),su(e.stderrLineBuffer,"stderr",t),t.onClose(o);let s=Lw(e,o);r(s)})}async function Tr(n,e=[],t={}){try{let{stdout:r,stderr:i}=await xw(n,e,t);return{stdout:typeof r=="string"?r.trim():"",stderr:typeof i=="string"?i.trim():"",exitCode:0}}catch(r){let i=r;return{stdout:i.stdout?.trim()||"",stderr:i.stderr?.trim()||i.message,exitCode:typeof i.code=="number"?i.code:1}}}async function au(n,e,t){return await new Promise((r,i)=>{let o=kw(n,e,{stdio:["inherit","pipe","pipe"]}),s=Nw();Ow(o,s,t,r,i)})}function cu(n){let e=n.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var Mw=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],_w=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function Ln(n){return n?Mw.some(e=>e.test(n))?"transient":_w.some(e=>e.test(n))?"fatal":"ok":"ok"}var Ya=[800,1500,2500];function Fw(n){return new Promise(e=>setTimeout(e,n))}async function Ae(n,e){let t=1+Ya.length,r={stdout:"",stderr:"",exitCode:-1};for(let i=0;i<t;i++){if(r=await Tr(n,e),r.exitCode===0||Ln(r.stderr)!=="transient"||i>=t-1)return r;m(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${Ya[i]}ms`),await Fw(Ya[i])}return r}var lu=/^[\w.-]+$/;async function wo(n,e,t){if(!lu.test(t)){m(`Skipping invalid param key: ${JSON.stringify(t)}`);return}let r=["-t",e,"shell","param","get",t];m(`Executing: ${n} ${r.join(" ")}`);let i=await Ae(n,r);if(i.exitCode!==0)return;let o=i.stdout.trim();if(!(!o||Ln(o)!=="ok"))return cu(o)}var Ja="__DEVECO_PARAM_DELIM__";function jw(n,e){let t=new Map,r=n.split(Ja);for(let i=0;i<e.length;i++){let o=(r[i]??"").trim();if(!o||Ln(o)!=="ok")continue;let s=cu(o);s&&t.set(e[i],s)}return t}async function Nn(n,e,t){let r=t.filter(a=>lu.test(a)?!0:(m(`Skipping invalid param key: ${JSON.stringify(a)}`),!1));if(r.length===0)return new Map;if(r.length===1){let a=new Map,c=await wo(n,e,r[0]);return c&&a.set(r[0],c),a}let i=r.map(a=>`param get ${a}`).join(`; echo ${Ja}; `)+`; echo ${Ja}`,o=await Ae(n,["-t",e,"shell",i]);if(o.exitCode===0){let a=jw(o.stdout,r);if(a.size>0)return a}m(`Batched param fetch failed (exit=${o.exitCode}), falling back to individual calls for ${e}`);let s=new Map;for(let a of r){let c=await wo(n,e,a);c&&s.set(a,c)}return s}function dn(n){return n.startsWith("127.0.0.1:")}var du=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],Z=class n{hdcPath;constructor(e){this.hdcPath=e}static from(e){return new n(e.hdcPath)}static withHdcPath(e){return new n(e)}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}stripBrandPrefix(e,t){let r=e.trim(),i=t?.trim();if(!r||!i)return r;let o=new RegExp(`^${this.escapeRegExp(i)}(\\s+|[-_]+)?`,"i");return r.replace(o,"").trim()||r}async executeHdc(e){return m(`Executing: ${this.hdcPath} ${e.join(" ")}`),$w(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let r of e.split(`
30
+ `)){let i=r.trim();if(!i||i.startsWith("[Empty]"))continue;let o=i.split(/\s+/),s=o[0];if(!s||s.startsWith("[Empty]"))continue;let a=o.length>=2?o[1]:"device";if(a.toLowerCase()==="unauthorized"){m(`[DeviceManager] Skipping unauthorized device: ${s}`);continue}t.push({serial:s,status:a})}return t}extractDisplayName(e){let t=e.get("ohos.qemu.hvd.name");if(t)return t;let r=e.get("const.product.name");if(r&&r!=="emulator")return r;let i=e.get("const.product.model");if(i&&i!=="emulator"){let s=e.get("const.product.brand");return this.stripBrandPrefix(i,s)}let o=e.get("const.build.product");if(o&&o!=="emulator")return o}async getDeviceName(e){let t=await Nn(this.hdcPath,e,[...du]);return this.extractDisplayName(t)??e}async getDeviceInfo(e,t){if(e.length===0)return null;if(t){let r=e.find(s=>s.serial===t);if(r)return r;let i=t.toLowerCase(),o=[];for(let s of e){let a=await this.getDeviceName(s.serial);a.toLowerCase()===i&&o.push({device:s,name:a})}if(o.length===1)return o[0].device;throw o.length>1?new Error(`Multiple devices match "${t}". Use a serial instead:
23
31
  `+o.map(s=>` - ${s.name} (${s.device.serial})`).join(`
24
- `)):new Error(`Device "${t}" not found. Use \`devecocli device list\` to see available targets.`)}return e[0]}async getDeviceDetail(e){let t={serial:e,status:"device"};try{let n=await Ve(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=Pt(e),n,i;try{let o=await Ve(this.hdcPath,e,[...xi]);n=this.extractDisplayName(o),i=o.get("const.product.devicetype")}catch{}return{serial:e,name:n,isEmulator:t,deviceType:i}}};var Kt=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=G.from(e)}async runHdc(e,t=!0){let n=this.toolProvider.hdcPath;v(`Executing: ${n} ${e.join(" ")}`);try{let{stdout:i}=await Oa(n,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}async listTargets(){return(await this.deviceManager.listDevicesWithName()).map(t=>({name:t.name,id:t.serial}))}async uninstallApp(e,t){let n=await this.runHdc(["-t",e,"shell","bm","uninstall","-n",t],!1);if(n.includes("uninstall bundle successfully"))return!0;if(n.includes("uninstall missing installed bundle"))return!1;throw new Error(`Uninstall failed: ${n}`)}async installApp(e,t){if(t.length===0)return;let i=`/data/local/tmp/${Ma()}`;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 Fa(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 ja(r,e){let t=await r.listDevices();if(t.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");if(!e&&t.length>1){let i=await r.listDevicesWithName();throw new Error("Multiple devices found. Specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+i.map(o=>` - ${o.name} (${o.serial})`).join(`
25
- `))}let n=await r.getDeviceInfo(t,e);if(!n)throw new Error("No active devices found.");if(!e){let i=await r.getDeviceName(n.serial);console.log(`Auto-selected device: ${i} (${n.serial})`)}return n.serial}function $a(r,e){if(e)return e;let t=r.profile.modules.filter(n=>{let i=r.getModuleType(n.name);return i==="entry"||i==="feature"||i==="shared"});if(t.length===1){let n=t[0].name;return console.log(`Auto-selected module: ${n}`),n}throw new Error(`Specify a module using --module <name>.
32
+ `)):new Error(`Device "${t}" not found. Use \`devecocli device list\` to see available targets.`)}return e[0]}async getDeviceDetail(e){let t={serial:e,status:"device"};try{let r=await Nn(this.hdcPath,e,["const.product.devicetype","const.ohos.apiversion","const.ohos.releasetype"]);t.deviceType=r.get("const.product.devicetype");let i=r.get("const.ohos.apiversion"),o=r.get("const.ohos.releasetype");i&&(t.osVersion=o?`API ${i} (${o})`:`API ${i}`)}catch{}return t}async listDevicesWithName(){let e=await this.listDevices();return Promise.all(e.map(async t=>({serial:t.serial,name:await this.getDeviceName(t.serial)})))}async getConnectedEntries(){let e=await this.listDevices();return Promise.all(e.map(t=>this.buildConnectedEntry(t.serial)))}async buildConnectedEntry(e){let t=dn(e),r,i;try{let o=await Nn(this.hdcPath,e,[...du]);r=this.extractDisplayName(o),i=o.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:i}}};var On=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=Z.from(e)}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;m(`Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await Uw(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}async listTargets(){return(await this.deviceManager.listDevicesWithName()).map(t=>({name:t.name,id:t.serial}))}async uninstallApp(e,t){let r=await this.runHdc(["-t",e,"shell","bm","uninstall","-n",t],!1);if(r.includes("uninstall bundle successfully"))return!0;if(r.includes("uninstall missing installed bundle"))return!1;throw new Error(`Uninstall failed: ${r}`)}async installApp(e,t){if(t.length===0)return;let i=`/data/local/tmp/${Hw()}`;try{await this.runHdc(["-t",e,"shell","mkdir",i]);for(let s of t){let a=await this.runHdc(["-t",e,"file","send",s,i+"/"]);if(!a.startsWith("FileTransfer finish"))throw new Error(a)}let o=await this.runHdc(["-t",e,"shell","bm","install","-p",i]);if(!o.includes("install bundle successfully."))throw new Error(o);console.log("App installed successfully")}finally{await this.runHdc(["-t",e,"shell","rm","-rf",i],!1)}}async launchApp(e,t,r){let i=["-t",e,"shell","aa","start","-a",r,"-b",t];return await this.runHdc(i)}async forceStopApp(e,t){let r=["-t",e,"shell","aa","force-stop",t];return await this.runHdc(r,!1)}};import Ka from"fs";import*as Xa from"path";function uu(n,e){if(!Ka.existsSync(n))throw new Error(`Apply file list not found: ${n}`);let r=Ka.readFileSync(n,"utf-8").split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0&&!a.startsWith("#"));if(r.length===0)throw new Error("Apply file list is empty (no valid entries)");let i=Xa.resolve(e),o=new Set,s=[];for(let a of r){let c=Xa.resolve(i,a),l=P.isPathContainedWithSymlink(a,i);if(!l.contained){if(P.isPathContained(a,i).contained&&!Ka.existsSync(c))throw new Error(`File not found: ${a}`);let p=l.reason?`; ${l.reason}`:"";throw new Error(`File path is outside the project directory: ${a}${p}`)}o.has(c)||(o.add(c),s.push(c))}return s}import Za from"fs";import xr from"path";import{execa as Gw}from"execa";import pu from"fs";import*as fu from"path";import Bw from"json5";function Ww(n,e){try{let r=Bw.parse(pu.readFileSync(n,"utf-8")).modules?.find(i=>i.name===e);return r?.srcPath?r.srcPath.replace(/^\.\//,""):null}catch(t){return m(`[apply] resolveModuleSrcPath fallback (module=${e}): ${t.message}`),null}}function vo(n,e){let t=fu.join(n,"build-profile.json5");return pu.existsSync(t)?Ww(t,e)??e:e}async function mu(n,e,t,r){let i=xr.dirname(n.javaPath),o={...process.env,PATH:`${i}${xr.delimiter}${process.env.PATH||""}`,DEVECO_SDK_HOME:n.sdkPath},s=[n.hvigorJsPath,"--mode","module","-p",`module=${t.join(",")}@${r}`,"-p",`product=${r}`,"-p","debuggable=true","assembleDevHqf","--analyze=normal","--parallel","--incremental","--no-daemon"];m(`[buildSignedHqf] ${n.nodePath} ${s.join(" ")}`);let a=await Gw(n.nodePath,s,{cwd:e,env:o,stdout:"inherit",stderr:"inherit",reject:!1}),c=(a.exitCode??0)|0;if(c===-1)throw new Error("hvigor hot compile produced invalid abc (exit code -1)");if(c!==0)throw new Error(`hvigor assembleDevHqf failed with exit code ${a.exitCode}`);return t.map(l=>zw(e,l,r))}function hu(n,e,t){let r=vo(n,e);return xr.join(n,r,"build",t,"outputs")}function Vw(n,e,t){return xr.join(hu(n,e,t),`${e}-${t}-signed.hqf`)}function zw(n,e,t){let r=hu(n,e,t),i=Vw(n,e,t);if(Za.existsSync(i))return i;let o=Qa(r,"-signed.hqf")??Qa(r,".hqf");if(!o)throw new Error(`Signed hqf not found at ${i} (and no *.hqf under ${r})`);return m(`[buildSignedHqf] signed hqf not at exact path, using fallback: ${o}`),o}function Qa(n,e){if(!Za.existsSync(n))return null;for(let t of Za.readdirSync(n,{withFileTypes:!0})){let r=xr.join(n,t.name);if(t.isDirectory()){let i=Qa(r,e);if(i)return i}else if(t.isFile()&&t.name.endsWith(e))return r}return null}import B from"fs";import*as x from"path";import ec from"json5";var gu="default",So=class n{static writeChangedFileLists(e,t,r,i){let o=t||gu,s=n.loadBuildProfile(e);if(!s)return{writtenModules:[],skippedFiles:r};let a=s.modules,c=n.filterRunnableModules(e,a);if(c.length===0)return{writtenModules:[],skippedFiles:r};let l=n.buildReverseDependencyMap(e,a),p=n.createCollectors(c),g=n.collectChanges(r,e,a,l,p);return{writtenModules:n.flushCollectors(e,o,c,p,i),skippedFiles:g}}static initEmptyChangedFileLists(e,t,r){let i=t||gu,o=n.loadBuildProfile(e);if(!o)return[];let s=o.modules,a=[];for(let c of s){let l=n.getModuleType(e,c.srcPath);if(l!=="entry"&&l!=="shared")continue;let p=!r||c.name===r;n.initEmptyForModule(e,i,c.srcPath,p),a.push(c.name)}return a}static filterRunnableModules(e,t){return t.filter(r=>{let i=n.getModuleType(e,r.srcPath);return i==="entry"||i==="shared"})}static createCollectors(e){let t=new Map;for(let r of e)t.set(r.name,{hotReloadEntries:[],patchEtsFiles:[],patchRawFiles:[],patchResFiles:[]});return t}static collectChanges(e,t,r,i,o){let s=[];for(let a of e){let c=x.normalize(a),l=n.classifyFile(c,t,r);if(l.fileClass==="unknown"){s.push(c);continue}let p=n.findModuleByFilePath(c,t,r);if(!p){s.push(c);continue}let g=n.resolveTargetModules(p,t,r,i);if(g.length===0){s.push(c);continue}n.dispatchToCollectors(g,o,c,l,p.srcPath,t)}return s}static resolveTargetModules(e,t,r,i){let o=n.getModuleType(t,e.srcPath);return o==="entry"||o==="shared"?[e.name]:Array.from(n.findTopLevelConsumers(e.name,i,t,r))}static dispatchToCollectors(e,t,r,i,o,s){for(let a of e){let c=t.get(a);c&&n.addFileToCollector(c,r,i.fileClass,o,s)}}static flushCollectors(e,t,r,i,o){let s=[];for(let a of r){let c=i.get(a.name);if(!c||!n.hasAnyChange(c))continue;(!o||a.name===o)&&c.hotReloadEntries.length>0&&n.writeApplyFile(e,a.srcPath,t,c.hotReloadEntries),n.writePatchFile(e,a.srcPath,t,c.patchEtsFiles,c.patchRawFiles,c.patchResFiles),s.push(a.name)}return s}static hasAnyChange(e){return e.hotReloadEntries.length>0||e.patchEtsFiles.length>0||e.patchRawFiles.length>0||e.patchResFiles.length>0}static initEmptyForModule(e,t,r,i){let o=x.join(e,r,"build",t,"intermediates","patch","default"),s=x.join(o,"changedFileList.json");if(B.existsSync(s)||(B.mkdirSync(o,{recursive:!0}),B.writeFileSync(s,JSON.stringify({resources:{resFile:[],rawFile:[]},modifiedFiles:[]}),"utf-8")),!i)return;let a=x.join(e,r,"build",t,"intermediates","hotReload"),c=x.join(a,"changedFileList.json");B.existsSync(c)||(B.mkdirSync(a,{recursive:!0}),B.writeFileSync(c,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=x.join(e,"build-profile.json5");if(!B.existsSync(t))return null;try{let r=B.readFileSync(t,"utf-8");return ec.parse(r)}catch{return null}}static classifyFile(e,t,r){let i=x.extname(e).toLowerCase();if(i===".ets"||i===".ts")return{fileClass:"ets_ts",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""};let o=e.replace(/\\/g,"/");return o.includes("/resources/rawfile/")?{fileClass:"raw_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:o.includes("/resources/resfile/")?{fileClass:"res_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:{fileClass:"unknown",moduleSrcPath:""}}static findModuleByFilePath(e,t,r){let i=x.normalize(e);for(let o of r){let s=x.normalize(x.join(t,o.srcPath)),a=s+x.sep;if(i.startsWith(a)||i===s)return o}return null}static getModuleType(e,t){let r=x.join(e,t,"src","main","module.json5");if(!B.existsSync(r))return"entry";try{let i=B.readFileSync(r,"utf-8");return ec.parse(i)?.module?.type||"entry"}catch{return"entry"}}static buildReverseDependencyMap(e,t){let r=new Map;for(let i of t){let o=n.readLocalDependencies(e,i.srcPath);for(let s of o){let a=r.get(s)||[];a.includes(i.name)||a.push(i.name),r.set(s,a)}}return r}static readLocalDependencies(e,t){let r=x.join(e,t,"oh-package.json5");if(!B.existsSync(r))return[];try{let i=B.readFileSync(r,"utf-8"),o=ec.parse(i);return n.resolveDepModuleNames(e,t,o.dependencies||{})}catch{return[]}}static resolveDepModuleNames(e,t,r){let i=n.loadBuildProfile(e);if(!i)return[];let o=i.modules,s=[];for(let a of Object.values(r)){if(typeof a!="string")continue;let c=n.tryResolveDepModule(e,t,a,o);c&&s.push(c)}return s}static tryResolveDepModule(e,t,r,i){let o=r;if(!(o.startsWith("file:")||o.startsWith(".")||o.startsWith("..")))return null;o.startsWith("file:")&&(o=o.substring(5));let a=x.resolve(e,t,o);return i.find(l=>x.resolve(e,l.srcPath)===a)?.name??null}static findTopLevelConsumers(e,t,r,i){let o=new Set,s=new Set,a=[e];for(;a.length>0;){let c=a.shift();s.has(c)||(s.add(c),n.processDependents(c,t,r,i,o,a))}return o}static processDependents(e,t,r,i,o,s){let a=t.get(e)||[];for(let c of a){let l=i.find(g=>g.name===c);if(!l)continue;let p=n.getModuleType(r,l.srcPath);(p==="entry"||p==="shared")&&o.add(c),p==="har"&&s.push(c)}}static addFileToCollector(e,t,r,i,o){let s=x.join(o,i,"src","main","resources");r==="ets_ts"?(e.hotReloadEntries.push({filePath:t,belongProjectPath:o}),e.patchEtsFiles.push(t)):r==="raw_file"?e.patchRawFiles.push({filePath:t,resourcePath:s}):r==="res_file"&&e.patchResFiles.push({filePath:t,resourcePath:s})}static writeApplyFile(e,t,r,i){let o=t.replace(/^\.\//,""),s=x.join(e,o,"build",r,"intermediates","hotReload","changedFileList.json"),a=n.readExistingApply(s),c=n.mergeApplyEntries(a,i),l=x.dirname(s);B.existsSync(l)||B.mkdirSync(l,{recursive:!0}),B.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),m(`[ChangedFileListWriter] Written hotReload: ${s} (${c.length} entries)`)}static readExistingApply(e){if(!B.existsSync(e))return[];try{let t=B.readFileSync(e,"utf-8");return JSON.parse(t)?.modifiedFilesV2||[]}catch{return[]}}static writePatchFile(e,t,r,i,o,s){let a=t.replace(/^\.\//,""),c=x.join(e,a,"build",r,"intermediates","patch","default","changedFileList.json"),l=n.readExistingPatch(c),p=x.join(e,a,"src","main","ets"),g=i.map(It=>n.resolveRelativePathForPatch(It,p)),w=n.mergeStrings(l.modifiedFiles,g),C=n.mergePatchResources(l.rawFile,o),_=n.mergePatchResources(l.resFile,s),fe=x.dirname(c);B.existsSync(fe)||B.mkdirSync(fe,{recursive:!0}),B.writeFileSync(c,JSON.stringify({resources:{resFile:_,rawFile:C},modifiedFiles:w}),"utf-8"),m(`[ChangedFileListWriter] Written patch: ${c}`)}static readExistingPatch(e){if(!B.existsSync(e))return{modifiedFiles:[],rawFile:[],resFile:[]};try{let t=B.readFileSync(e,"utf-8"),r=JSON.parse(t);return{modifiedFiles:r?.modifiedFiles||[],rawFile:r?.resources?.rawFile||[],resFile:r?.resources?.resFile||[]}}catch{return{modifiedFiles:[],rawFile:[],resFile:[]}}}static resolveRelativePathForPatch(e,t){return x.relative(x.normalize(t),x.normalize(e)).replace(/\\/g,"/")}static mergeApplyEntries(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o.filePath)||(r.add(o.filePath),i.push(o));return i}static mergeStrings(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o)||(r.add(o),i.push(o));return i}static mergePatchResources(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o.filePath)||(r.add(o.filePath),i.push(o));return i}};import qw from"fs";import{randomUUID as Yw}from"crypto";import{execa as Jw}from"execa";var Eo=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,r){for(let a of t)if(!qw.existsSync(a)){let c=`Signed hqf file not found: ${a}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}let o=`/data/local/tmp/${Yw()}`,s=[];try{for(let a=0;a<t.length;a++){let c=`${o}/${r}_${a}.hqf`;s.push(c),await this.pushHqf(e,t[a],o,c)}return await this.executeQuickfix(e,s)}catch(a){let c=`hqf install error: ${a.message}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}finally{await this.runHdc(["-t",e,"shell","rm","-rf",o],!1)}}async pushHqf(e,t,r,i){console.log(`[Apply] Pushing hqf to device ${e}: ${t}`),await this.runHdc(["-t",e,"shell","mkdir","-p",r]);let o=await this.runHdc(["-t",e,"file","send",t,i]);if(!o.startsWith("FileTransfer finish"))throw new Error(`Failed to send hqf: ${o}`)}async executeQuickfix(e,t){console.log(`[Apply] Installing ${t.length} hqf patch(es) via quickfix...`);let r=await this.runHdc(["-t",e,"shell","bm","quickfix","-a","-f",...t,"-o"],!1);if(m(`[InstallHqf] quickfix output: ${r}`),/succe(?:ed|ss)/i.test(r))return console.log("[Apply] hqf installed successfully."),{success:!0,message:"hqf quickfix installed successfully."};let i=`hqf quickfix install failed. Device response: ${r||"(empty)"}. Please try reinstalling the application.`;return console.error(`[Apply] ${i}`),{success:!1,message:i}}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;m(`[InstallHqf] Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await Jw(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}};var Kw="6.1.1",bo=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}toolProvider;projectRoot;async execute(e){await rn(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion(Kw);let t=uu(e.applyFile,this.projectRoot);console.log(`[Apply] Parsed ${t.length} changed file(s)`);let r=this.writeChangeFileList(e,t),i=await this.buildHqf(e,r);await this.installHqf(e,i),await this.restartApp(e),console.log("[Apply] Apply complete")}writeChangeFileList(e,t){let r=So.writeChangedFileLists(this.projectRoot,e.productName,t);if(r.writtenModules.length===0)throw new Error("No changed files belong to a runnable module");return console.log(`[Apply] changeFileList written for: ${r.writtenModules.join(", ")}`),r.writtenModules}async buildHqf(e,t){return m(`[Apply] hvigor assembleDevHqf --no-daemon (modules=${t.join(",")})`),await mu(this.toolProvider,this.projectRoot,t,e.productName)}async installHqf(e,t){console.log(`[Apply] Installing ${t.length} hqf(s) to ${e.targetDeviceId}`);let i=await new Eo(this.toolProvider).install(e.targetDeviceId,t,e.bundleName);if(!i.success)throw new Error(`hqf install failed: ${i.message}`);console.log("[Apply] hqf installed")}async restartApp(e){let t=new On(this.toolProvider);try{await t.forceStopApp(e.targetDeviceId,e.bundleName),await t.launchApp(e.targetDeviceId,e.bundleName,e.abilityName),console.log("[Apply] app restarted")}catch(r){console.warn(`[Apply] restart failed (hqf already applied): ${r.message}`)}}};import yu from"fs";import*as F from"path";var Po=class n{static generate(e,t,r,i){let o=vo(e,t),s=F.join(e,o),a=F.join(s,"build","config"),c=n.buildConfig(e,s,r,i);yu.mkdirSync(a,{recursive:!0}),yu.writeFileSync(F.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),m(`[BuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,i){let o=F.dirname(i.nodePath)+F.sep,s=F.join(t,"build",r),a=F.join(s,"intermediates"),c=F.join(a,"loader_out",r),l=F.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:o,projectProfilePath:F.join(e,"build-profile.json5"),localPropertiesPath:F.join(e,"local.properties"),appResource:F.join(l,"ResourceTable.txt"),cachePath:F.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:F.join(a,"loader",r,"loader.json"),aceModuleJsonPath:F.join(l,"module.json"),aceSoPath:F.join(c,"nativeDependencies.txt"),aceModuleRoot:F.join(t,"src","main","ets"),aceModuleBuild:F.join(c,"ets"),aceProfilePath:F.join(l,"resources","base","profile"),aceSuperVisualPath:F.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:F.join(c,"ets"),changedFileList:F.join(a,"patch","default","changedFileList.json"),patchAbcPath:F.join(a,"patch","default","ets"),removeChangedFileListInSdk:"true"}}}};function Qw(n){let e=n.indexOf("@"),t=e!==-1?n.substring(0,e):n,r=e!==-1?n.substring(e+1):"default";return{moduleName:t,targetName:r}}async function vu(n,e){let t=await n.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 n.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(`
33
+ `))}let r=await n.getDeviceInfo(t,e);if(!r)throw new Error("No active devices found.");if(!e){let i=await n.getDeviceName(r.serial);console.log(`Auto-selected device: ${i} (${r.serial})`)}return r.serial}function ev(n,e){if(e&&e.length>0)return e;let t=n.profile.modules.filter(r=>{let i=n.getModuleType(r.name);return i==="entry"||i==="feature"||i==="shared"});if(t.length===1){let r=t[0].name;return console.log(`Auto-selected module: ${r}`),[r]}throw new Error(`Specify module(s) using --module <name> [<name>...].
26
34
  Available runnable modules:
27
- `+t.map(n=>` - ${n.name}`).join(`
28
- `))}function _a(r,e,t,n,i){let o=[],s=r.collectNonHarDependentModuleList(e);for(let c of s){let d=r.findArtifactPath(c,t,n,i);o.push(d)}let a=r.findArtifactPath(e,t,n,i);return o.push(a),o}async function Wa(r,e,t,n,i,o){o&&(console.log(`Uninstalling ${t}...`),await r.uninstallApp(e,t)||console.log(`App ${t} not installed; skipping uninstallation.`)),console.log(`
29
- Installing artifacts to device ${e}...`),await r.installApp(e,n),console.log(`Launching ${t}/${i}...`);let s=await r.launchApp(e,t,i);console.log(Mi(`
30
- Application '${t}': ${s}`))}var Ua=new La("run").description("Build and run the project on a connected device").option("--module <module>","Module to run (format: module or module@target)").option("--device <device>","Target device name or serial").option("--product <product>","Product name (default: default)").option("--build-mode <mode>","Build mode (options: debug, release; default: debug)").option("--ability <ability>","Ability name to launch").option("--uninstall","Uninstall existing app before installation").option("--skip-build","Skip build step and deploy existing artifacts").action(async r=>{try{await za(r)}catch(e){console.error(Na(e.message)),process.exit(1)}});async function Ba(r,e,t,n,i,o){let s=new ze(e,r.rootDir),a=new Ne(e,r.rootDir),d=r.collectNonHarDependentModuleList(t).map(k=>`${k}@${n}`),p=lr(r,d),g={type:"modules",modulesToBuild:d,moduleTasks:p};await bt(r.rootDir,()=>dr(s,a,i,o,g),()=>console.log("Another build is already running for this project. Waiting for completion...")),console.log(`
31
- `+Mi("Build completed successfully."))}async function za(r){let e=Le.discover(process.cwd());console.warn(Ha("Ensure the project source is trusted before proceeding."));let t=await O.new(),n=$a(e,r.module),{moduleName:i,targetName:o}=Fa(n),s=e.getModuleType(i);if(s!=="entry"&&s!=="feature"&&s!=="shared")throw new Error(`Module '${i}' '${s}' is not runnable. Specify an entry or feature module.`);let a=new Kt(t),c=G.from(t),d=await ja(c,r.device),p=d.includes("127.0.0.1")||d.includes("localhost"),g=r.product||"default";e.validateProduct(g);let k=r.buildMode||"debug";r.skipBuild||await Ba(e,t,i,o,g,k);let re=_a(e,i,o,p,g),Se=e.getBundleName(),Be=e.getMainAbility(i,r.ability);await Wa(a,d,Se,re,Be,!!r.uninstall)}var Oi=Ua;import{Command as qa}from"commander";import{green as Li,red as Ni,cyan as hr}from"colorette";import{execa as Hi}from"execa";function Va(){return"@deveco-test/deveco-cli"}function Ga(){return"1.3.0-Test.1"}var Ya=new qa("update").description("Update deveco-cli to latest").action(async()=>{let r=Va(),e=Ga();console.log(hr("Checking for updates..."));try{let{stdout:t}=await Hi("npm",["view",r,"version"]),n=t.trim();if(n===e){console.log(Li(`
32
- ${r} is already up to date (version ${e}.)`));return}console.log(hr(`
33
- New version found: ${n} (current: ${e})`)),console.log(hr(`Updating ${r}...`)),await Hi("npm",["install","-g",`${r}@latest`],{stdio:"inherit"}),console.log(`
34
- `+Li(`${r} updated successfully to version ${n}.`))}catch(t){let n=t;console.error(Ni(`Failed to update ${r}`)),n.message&&console.error(Ni(n.message)),process.exit(1)}}),Fi=Ya;import{Command as gc}from"commander";import{execa as yr}from"execa";function j(r){return r.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as Ja}from"child_process";var Ka=2500;function Za(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 Xa(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=p=>{if(!i){i=!0,clearTimeout(d),r.removeAllListeners(),r.stderr?.removeAllListeners();try{r.kill()}catch{}n(new Error(p))}},d=setTimeout(a,Ka);r.once("error",p=>c(p.message)),Za(r,d,s,a,c,o)}function ji(r,e,t){return v(`Spawning emulator: ${r} ${t.join(" ")}`),new Promise((n,i)=>{let o=[],s=Ja(r,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});s.stderr?.on("data",a=>o.push(a)),Xa(s,o,n,i)})}import*as Ge from"path";function Qa(r){let e=new Set,t=[];for(let n of r){let i=JSON.stringify(n);e.has(i)||(e.add(i),t.push(n))}return t}function ec(r){let e=r.instancePath?.trim();if(e)return Ge.dirname(Ge.normalize(e)).replace(/\\/g,"/");let t=r.path?.trim();return t?Ge.dirname(Ge.normalize(t)).replace(/\\/g,"/"):""}function tc(r){let e=[];return r&&e.push(["-imageRoot",r]),e.push([]),e}function $i(r,e){return e?[...r,"-bootmode",e]:r}function nc(r,e,t){let n=[$i(["-start",r],t)],i=ec(e);if(i)for(let o of tc(e.imageRoot))n.push($i(["-hvd",r,"-path",i,...o],t));return Qa(n)}async function _i(r,e,t,n){let i=new Error("No start strategy ran"),o=nc(r,e,n);for(let s of o)try{return await t(s),{ok:!0}}catch(a){i=a}return{ok:!1,lastError:i}}async function fr(r){return(await G.withHdcPath(r).listDevices()).map(t=>t.serial).filter(Pt)}async function mr(r){let e=await fr(r);return e.length===0?[]:(await Promise.all(e.map(n=>Jt(r,n,"ohos.qemu.hvd.name")))).filter(n=>!!n)}async function Wi(r,e){return(await mr(r)).includes(e)}import*as Je from"path";import{existsSync as rc,statSync as ic}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 oc(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 sc(r){return Ye(r,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function ac(r){let e=r.find(n=>n.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=Je.dirname(Je.normalize(e.instancePath));for(let n of r){if(n.instancePath?.trim())continue;let i=Je.join(t,n.name);rc(i)&&ic(i).isDirectory()&&(n.instancePath=i.replace(/\\/g,"/"))}}function cc(r){try{let e=JSON.parse(r);return Array.isArray(e)?e.map(t=>{let n=sc(t),i=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:oc(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 lc(r){let e=[],t=/^(name|isrunning|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,n=null,i;for(;(i=t.exec(r))!==null;){let[,o,s]=i;if(o.toLowerCase()==="name")n&&e.push(n),n={name:s.trim()};else if(n){let a=o.toLowerCase();a==="isrunning"?n.isRunning=s.trim().toLowerCase()==="true":a==="instancepath"?n.instancePath=s.trim():a==="path"?n.path=s.trim():a==="imageroot"?n.imageRoot=s.trim():a==="devicetype"?n.deviceType=s.trim():a==="os.osversion"&&(n.osVersion=s.trim())}}return n&&e.push(n),e}function Ui(r){let t=cc(r)??lc(r);return ac(t),t}function gr(r,e){for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim())return n.trim()}return""}function dc(r){let e=r.downloaded??r.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function uc(r){if(!dc(r))return null;let e=gr(r,["osVersion","OsVersion","OSVersion"]),t=gr(r,["SoftWareVersion","SoftwareVersion","softwareVersion"]),n=gr(r,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:n}}function Zt(r){let e=r.trim();if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let n=[];for(let i of t){if(!i||typeof i!="object")continue;let o=uc(i);o&&n.push(o)}return n}catch{return[]}}function Bi(r){let t=Zt(r).map(n=>n.osVersion).filter(Boolean);return[...new Set(t)]}var zi=/no images are available/i;function ce(r){return r.normalize("NFKC").trim().toLowerCase()}function pc(r){let e=r.message||"";return zi.test(e)}var Ke=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 yr(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return ji(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return Ui(e)}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let n of t)n.name&&n.deviceType&&e.set(j(n.name),n.deviceType)}catch{}return e}async startEmulator(e){let t=await this.listEmulators(),n=j(e),i=t.find(a=>j(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 _i(o,i,a=>this.executeEmulatorDetached(a),"snapshot");if(s.ok)return"started";if(await this.isAlreadyRunning(o))return"already-running";throw new Error(`Unable to start emulator "${e}". All methods failed.
35
- Last error: ${s.lastError.message||"unknown"}`)}async isAlreadyRunning(e,t){return t?.isRunning===!0||t===void 0&&(await this.listEmulators()).find(i=>i.name===e)?.isRunning===!0?!0:Wi(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),n=j(e),i=t.find(a=>j(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 yr(this.emulatorPath,e,{stdio:"inherit",env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1});if(t!==0)throw new Error(`Emulator exited with code ${t===null?"null":t}.`)}async installEmulatorImage(e){let t=["-install","-deviceType",e.deviceType,"-osVersion",e.osVersion];e.force&&t.push("-force"),await this.executeEmulatorInherit(t)}async uninstallEmulatorImage(e){let t=await this.resolveSoftwareVersionsForUninstall(e);if(t.length===0)throw new Error(`No downloaded image matches --os-version "${e.osVersion}" for --device-type "${e.deviceType}".`);let n;try{await this.runUninstallImageChecked(e.deviceType,e.osVersion)}catch(o){if(!pc(o))throw o;n=o}(n!==void 0||await this.hasMatchingDownloadedImage(e))&&await this.runSoftwareVersionFallback(e,t,n)}async listEmulatorImages(e){let t=["-imageList"];e.deviceType&&t.push("-deviceType",e.deviceType),e.downloaded!==void 0&&t.push("-downloaded",e.downloaded?"true":"false");let{stdout:n}=await this.executeEmulator(t);return n}async listDownloadedImageOsVersions(){let e=await this.listEmulatorImages({downloaded:!0});return Bi(e)}async hasMatchingDownloadedImage(e){return(await this.findMatchingDownloadedImages(e)).length>0}async runSoftwareVersionFallback(e,t,n){try{for(let i of t)await this.runUninstallImageChecked(e.deviceType,i)}catch(i){let o=n!==void 0?`Primary uninstall failed: ${n.message}
36
- `:"";throw new Error(`${o}Fallback uninstall failed: ${i.message}`,{cause:i})}if(await this.hasMatchingDownloadedImage(e))throw new Error(`Image for --device-type "${e.deviceType}" and --os-version "${e.osVersion}" remains listed as downloaded after uninstallation.`)}async resolveSoftwareVersionsForUninstall(e){let t=await this.findMatchingDownloadedImages(e);return[...new Set(t.map(n=>n.softwareVersion).filter(Boolean))]}async findMatchingDownloadedImages(e){let t=await this.listEmulatorImages({deviceType:e.deviceType,downloaded:!0}),n=Zt(t),i=ce(e.deviceType),o=ce(e.osVersion);return n.filter(s=>ce(s.deviceType)===i&&(ce(s.osVersion)===o||ce(s.softwareVersion)===o))}async hasDownloadedSystemImage(e,t){let n=await this.listEmulatorImages({downloaded:!0}),i=Zt(n),o=ce(t),s=e?.trim()?ce(e):void 0;return i.some(a=>ce(a.osVersion)===o||ce(a.softwareVersion)===o?s===void 0?!0:ce(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:[zi]})}async runEmulatorChecked(e,t){let{stdout:n,stderr:i,exitCode:o}=await yr(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:20971520}),s=[n,i].filter(Boolean).join(`
37
- `).trim(),a=/Invalid command|无效命令|鏃犳晥鍛戒护/i.test(s)||/please attach the correct parameter/i.test(s),c=(t?.extraReject??[]).some(p=>p.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 p=(t?.transformOutput?t.transformOutput(s):s).trim();p&&console.log(p)}}async checkExistingVirtualDevice(e,t){let n=await this.listEmulators(),i=j(e),o=n.find(s=>j(s.name)===i);if(o)if(t)await this.deleteVirtualDevice(o.name);else throw new Error(`Emulator "${e}" already exists. Use \`--force\` to overwrite.`);return i}async createVirtualDevice(e){let t=await this.checkExistingVirtualDevice(e.name,e.force),n=["-create",e.name,"-deviceType",e.deviceType,"-osVersion",e.osVersion];if(await this.runEmulatorChecked(n,{extraReject:[/Device create fail/i,/already exists/i,/Invalid OS version/i,/cannot be empty/i],printOutputOnSuccess:!0,transformOutput:o=>o.split(/\r?\n/).map(s=>s.trim().startsWith("Device create success.")?"Device create success.":s).join(`
38
- `)}),!await this.waitForEmulatorPresenceByList(t))throw new Error(`Emulator "${e.name}" was reported as created, but it did not appear in the emulator list within the waiting period. Open the device manager list in DevEco Studio, then run this command again.`)}async waitForEmulatorPresenceByList(e,t=1e4,n=500){let i=Date.now()+t;for(;Date.now()<i;){if((await this.listEmulators()).some(a=>j(a.name)===e))return!0;await new Promise(a=>setTimeout(a,n))}return!1}async deleteVirtualDevice(e){let t=await this.listEmulators(),n=j(e),i=t.find(s=>j(s.name)===n);if(!i)throw new Error(`Emulator "${e}" not found.`);let o=i.name;if(i.isRunning===!0||await this.isAlreadyRunning(o,i))throw new Error(`Failed to delete device: ${o}
39
- The device may be running.`);return await this.runEmulatorChecked(["-delete",o,"-force"],{printOutputOnSuccess:!1}),o}};import{red as vr,yellow as Vi,gray as Gi}from"colorette";import yc from"ora";import{red as hc}from"colorette";function Xt(r,e){r?r.fail(e):console.error(hc(e)),process.exit(1)}import{green as fc}from"colorette";function qi(r,e){return r+" ".repeat(Math.max(0,e-r.length))}function mc(r,e){return r.map((t,n)=>{let i=t.length;for(let o of e){let s=o.cells[n]??"";i=Math.max(i,s.length)}return i})}function Et(r,e){let t=mc(r,e),n=[];n.push(r.map((i,o)=>qi(i,t[o])).join(" ")),n.push(t.map(i=>"-".repeat(i)).join(" "));for(let i of e){let o=i.cells.map((s,a)=>qi(s??"",t[a])).join(" ").trimEnd();n.push(i.highlight?fc(o):o)}return n.join(`
40
- `)}function vc(r,e){if(e.size!==0)for(let t of r){if(!t.isEmulator||!t.name)continue;let n=e.get(j(t.name));n&&(t.deviceType=n)}}var wc=["Name","Serial","Kind","Device Type"];function bc(r){return{cells:[r.name??r.serial,r.serial,r.isEmulator?"emulator":"device",r.deviceType??"-"],highlight:!0}}function Sc(r,e){return r.isEmulator!==e.isEmulator?r.isEmulator?1:-1:(r.name??r.serial).localeCompare(e.name??e.serial)}function Pc(){console.log(Vi(" No active devices.")),console.log(Gi(" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function Ec(r){let t=[...r].sort(Sc).map(bc);console.log(Et(wc,t))}async function Cc(r,e){if(!r.some(i=>i.isEmulator)||!e.emulatorPath)return;let n=await Ke.from(e).getDeviceTypeByName();vc(r,n)}async function Dc(r,e,t){try{let n=await r.getConnectedEntries();await Cc(n,e),t?.stop(),n.length===0?Pc():Ec(n)}catch(n){Xt(t,`Failed to list devices: ${n.message}`)}}async function Ic(r,e){let t=await r.listDevices();if(!(t.length<2)){console.error(vr("Multiple devices connected. Specify a device with:"));for(let n of t){let i=await r.getDeviceName(n.serial);console.error(Gi(` ${e} -t ${n.serial} # ${i}`))}process.exit(1)}}async function Ac(r,e){try{e||await Ic(r,"devecocli device view");let t=await r.listDevices(),n=await r.getDeviceInfo(t,e);n||(console.log(Vi("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(vr(`Failed to show device details: ${t.message}`)),process.exit(1)}}async function Yi(){try{let r=await O.new();return{manager:G.from(r),toolProvider:r}}catch(r){console.error(vr(`Failed to initialize device manager: ${r.message}`)),process.exit(1);return}}var wr=new gc("device").description("Manage connected devices");wr.command("list").description("List all connected devices").action(async()=>{let{manager:r,toolProvider:e}=await Yi(),t=yc({text:"Querying connected devices\u2026",color:"cyan"}).start();await Dc(r,e,t)});wr.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").action(async r=>{let{manager:e}=await Yi();await Ac(e,r.target)});var Ji=wr;import{Command as Cr,Option as uo}from"commander";import{green as en,cyan as Xe,red as Y,yellow as le,gray as Dt}from"colorette";import Vc from"ora";import kc from"readline/promises";import{execa as Zi}from"execa";import*as Ee from"fs/promises";import*as Sr from"os";import*as He from"path";var br=`1/4:\r
35
+ `+t.map(r=>` - ${r.name}`).join(`
36
+ `))}function tv(n,e,t){if(t)return t;let r=e.find(({moduleName:o})=>n.getModuleType(o)==="entry");if(r)return n.getMainAbility(r.moduleName);let i=e.find(({moduleName:o})=>n.getModuleType(o)==="feature");if(i)return n.getMainAbility(i.moduleName)}async function nv(n,e,t,r,i,o){if(o&&(console.log(`Uninstalling ${t}...`),await n.uninstallApp(e,t)||console.log(`App ${t} not installed; skipping uninstallation.`)),console.log(`
37
+ Installing artifacts to device ${e}...`),await n.installApp(e,r),i){console.log(`Launching ${t}/${i}...`);let s=await n.launchApp(e,t,i);console.log(wu(`
38
+ Application '${t}': ${s}`))}else console.log(`
39
+ Application '${t}' installed successfully (no ability to launch).`)}var rv=new Xw("run").description("Build and run the project on a connected device").option("--module <modules...>","Module(s) to run (format: module or module@target)").option("--device <device>","Target device name or serial").option("--product <product>","Product name (default: default)").option("--build-mode <mode>","Build mode (options: debug, release; default: debug)").option("--ability <ability>","Ability name to launch").option("--uninstall","Uninstall existing app before installation").option("--skip-build","Skip build step and deploy existing artifacts").option("--apply <fileName>","Quick-apply changed files via quickfix (incremental hqf) and restart. <fileName> under project .hvigor/").action(async n=>{try{await ov(n)}catch(e){console.error(Zw(e.message)),process.exit(1)}});async function iv(n,e,t,r,i){let o=new kn(e,n.rootDir),s=new dt(e,n.rootDir),a=new Set,c=new Set;for(let{moduleName:w,targetName:C}of t)for(let _ of n.collectNonHarDependentModuleList(w))a.add(`${_}@${C}`),c.add(_);let l=[...a],p=za(n,l),g={type:"modules",modulesToBuild:l,moduleTasks:p};for(let w of c)Po.generate(n.rootDir,w,r,e);await rn(n.rootDir,()=>qa(o,s,r,i,g,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion...")),console.log(`
40
+ `+wu("Build completed successfully."))}async function ov(n){let e=U.discover(process.cwd());console.warn(Co("Ensure the project source is trusted before proceeding."));let t=await I.new();if(n.skipBuild||t.assertJava(),n.apply){await av(n,e,t);return}await Su(n,e,t)}function sv(n,e,t,r){let i=new Set;for(let{moduleName:o,targetName:s}of e)for(let a of n.collectNonHarDependentModuleList(o)){i.add(n.findArtifactPath(a,s,t,r));for(let c of n.findRemoteHspPaths(a,s,r))i.add(c)}return[...i]}async function Su(n,e,t){let i=ev(e,n.module).map(Qw);for(let{moduleName:_}of i){let fe=e.getModuleType(_);if(fe!=="entry"&&fe!=="feature"&&fe!=="shared")throw new Error(`Module '${_}' '${fe}' is not runnable. Specify an entry or feature module.`)}let o=new On(t),s=Z.from(t),a=await vu(s,n.device),c=a.includes("127.0.0.1")||a.includes("localhost"),l=n.product||"default";e.validateProduct(l);let p=n.buildMode||"debug";n.skipBuild||await iv(e,t,i,l,p);let g=sv(e,i,c,l),w=e.getBundleName(),C=tv(e,i,n.ability);await nv(o,a,w,g,C,!!n.uninstall)}async function av(n,e,t){let r=n.apply;if(!r)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(Io.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let i=Io.join(e.rootDir,".hvigor",r),o=Z.from(t),s=await vu(o,n.device),a=n.product||"default";e.validateProduct(a);let c=e.getBundleName(),l=e.profile.modules.find(w=>e.getModuleType(w.name)==="entry")?.name,p=l?e.getMainAbility(l,n.ability):n.ability||"EntryAbility",g=new bo(t,e.rootDir);try{await g.execute({applyFile:i,productName:a,targetDeviceId:s,bundleName:c,abilityName:p}),console.log(Co("[Apply] \u5B8C\u6210\u3002\u82E5\u6539\u52A8\u672A\u751F\u6548\uFF0C\u8BF7\u68C0\u67E5 <module>/build/config/buildConfig.json \u662F\u5426\u6709\u5185\u5BB9\uFF0C\u6216\u6267\u884C devecocli run \u5168\u91CF\u6784\u5EFA\u3002"));return}catch(w){console.warn(Co(`[Apply] \u5931\u8D25\uFF1A${w.message}`)),console.warn(Co("[Apply] \u81EA\u52A8\u56DE\u9000\u5230\u5168\u91CF devecocli run..."))}await Su(n,e,t)}var Eu=rv;import{Command as gv}from"commander";import*as Ru from"path";import{green as Au,red as Du,cyan as rc}from"colorette";import{execa as ic}from"execa";import{spawn as pv}from"child_process";import*as Iu from"fs";import*as Ro from"path";import{yellow as fv}from"colorette";import mv from"proper-lockfile";import*as xt from"fs";import*as bu from"path";import{homedir as cv}from"os";var lv="deveco-cli",tc,un=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function dv(){let n=process.env.DEVECO_CLI_DATA_DIR;return n!==void 0&&Yi(n)!==""}function Pu(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":Yi(n))||bu.join(cv(),".local","share",lv);try{return Ji(t)}catch(r){throw new un(r instanceof Error?r.message:String(r))}}async function Cu(){let n=Pu();await xt.promises.mkdir(n,{recursive:!0});let e;try{e=await xt.promises.realpath(n)}catch(r){throw new un(`DEVECO_CLI_DATA_DIR is not usable: ${r instanceof Error?r.message:String(r)}`)}if(!(await xt.promises.stat(e)).isDirectory())throw new un("DEVECO_CLI_DATA_DIR must be a writable directory.");return tc=e,e}function Ao(){let n=Ye();return dv()?[`Data directory (DEVECO_CLI_DATA_DIR): ${n}`,"If you changed this in System Environment Variables, open a new terminal and retry."]:[`Data directory (default): ${n}`,"To use a custom location, set DEVECO_CLI_DATA_DIR and open a new terminal."]}function Ye(){if(tc!==void 0)return tc;let n=Pu();try{if(xt.existsSync(n))return xt.realpathSync(n)}catch{}return n}function Do(){return"@deveco-test/deveco-cli"}function Lt(){return"1.3.0-Test.10"}function Mn(){return"daily"}function _n(){let n=process.env.DEVECO_CLI_DISABLE_UPDATE;return n==="check"||n==="all"?n:"off"}import*as Lr from"fs";import*as Nr from"path";var uv={lastCheckedTimestamp:null,latestVersion:null,blockedVersions:[],checkError:null},nc=new Map,Nt=class n{static CHECK_WINDOW_HOUR=21;static ONE_DAY_MS=1440*60*1e3;cacheFilePath;lockFilePath;constructor(e){this.cacheFilePath=Nr.join(e,"cache.json"),this.lockFilePath=Nr.join(e,"check.lock")}async writeSuccess(e,t=[],r,i){await this.write({lastCheckedTimestamp:Date.now(),latestVersion:e,blockedVersions:t,checkError:null,checkedAgainstVersion:r,checkedAgainstTag:i})}async writeError(e){let t=this.read();await this.write({...t,lastCheckedTimestamp:Date.now(),checkError:e})}getLatestVersion(){return this.read().latestVersion}getBlockedVersions(){return[...this.read().blockedVersions]}getCheckedAgainstVersion(){return this.read().checkedAgainstVersion}getCheckedAgainstTag(){return this.read().checkedAgainstTag}isCheckNeeded(){let{lastCheckedTimestamp:e}=this.read();if(!e||e>Date.now())return!0;let t=new Date().setHours(n.CHECK_WINDOW_HOUR,0,0,0),r=t>Date.now()?t-n.ONE_DAY_MS:t;return e<r}getLockPath(){return this.lockFilePath}read(){let e=nc.get(this.cacheFilePath);if(e)return e;try{let t=Lr.readFileSync(this.cacheFilePath,"utf-8"),r=JSON.parse(t);return nc.set(this.cacheFilePath,r),r}catch{return{...uv}}}async write(e){m(()=>`Writing update cache: lastChecked=${e.lastCheckedTimestamp}, latest=${e.latestVersion}, blocked=[${e.blockedVersions.join(",")}], error=${e.checkError}`),await Lr.promises.mkdir(Nr.dirname(this.cacheFilePath),{recursive:!0}),await Lr.promises.writeFile(this.cacheFilePath,JSON.stringify(e,null,2),"utf-8"),nc.set(this.cacheFilePath,e)}};var Or=class{constructor(e){this.actionCommand=e}actionCommand;cache=new Nt(Ro.join(Ye(),"update"));async checkAndNotify(){if(!this.shouldSkip())try{let e=Lt(),t=Mn(),r=this.cache.getCheckedAgainstVersion(),i=this.cache.getCheckedAgainstTag(),o=i!=null&&i!==t,s=r!=null&&r!==e,a=o?null:this.cache.getLatestVersion();a&&Sd(a,e)>0&&(console.log(),console.log(fv(`New version ${a} available, run \`devecocli update\` to upgrade`))),(o||s||this.cache.isCheckNeeded())&&await this.spawnBackgroundCheck()}catch(e){m(`Update check failed: ${e instanceof Error?e.message:String(e)}`)}}shouldSkip(){let e=this.actionCommand;for(;e;){if(e.name()==="update")return!0;e=e.parent}return!1}async spawnBackgroundCheck(){if(!process.argv[1]?.endsWith(".ts"))try{await hv(this.cache.getLockPath(),()=>{let e=[process.argv[1],"update","_check"];m(`Executing: ${process.execPath} ${e.join(" ")}`),pv(process.execPath,e,{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1"}}).unref()})}catch{m("Update check lock held by another process, skipping")}}};async function hv(n,e){await Iu.promises.mkdir(Ro.dirname(n),{recursive:!0});let t=await mv.lock(n,{stale:6e4,retries:0,realpath:!1});try{await e()}finally{await t()}}var oc=new gv("update").description("Update deveco-cli to latest");oc.command("_check",{hidden:!0}).action(async()=>{let n=new Nt(Ru.join(Ye(),"update"));try{let e=Mn(),t=Do();m(`Executing: npm view ${t}@${e} --json`);let{stdout:r}=await ic("npm",["view",`${t}@${e}`,"--json"]),i=JSON.parse(r),o=typeof i.version=="string"?i.version.trim():null,s=Array.isArray(i.blockedVersions)?i.blockedVersions:[];await n.writeSuccess(o,s,Lt(),e)}catch(e){await n.writeError(e instanceof Error?e.message:String(e))}});oc.action(async()=>{if(_n()==="all")throw new Error("devecocli update is disabled (DEVECO_CLI_DISABLE_UPDATE=all).");let n=Lt(),e=Mn();console.log(rc("Checking for updates..."));let t=Do();try{let{stdout:r}=await ic("npm",["view",t,`dist-tags.${e}`]),i=r.trim();if(!i||i===n){console.log(Au(`
41
+ ${t} is already up to date (v${n}, tag: ${e})`));return}console.log(rc(`
42
+ New version found: ${i} (current: ${n})`)),console.log(rc(`Updating ${t}...`)),await ic("npm",["install","-g",`${t}@${e}`],{stdio:"inherit"}),console.log(`
43
+ `+Au(`${t} updated successfully to version ${i}.`))}catch(r){let i=r;console.error(Du(`Failed to update ${t}`)),i.message&&console.error(Du(i.message)),process.exit(1)}});var ku=oc;import{Command as Wv}from"commander";import{execa as To}from"execa";function de(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as yv}from"child_process";var wv=2500;function vv(n,e,t,r,i,o){n.once("exit",s=>{if(o())return;clearTimeout(e);let a=t();s===0||s===null?r():i(a||`Emulator process exited with code ${s}`)})}function Sv(n,e,t,r){let i=!1,o=()=>i,s=()=>Buffer.concat(e).toString("utf8").trim(),a=()=>{i||(i=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners(),n.stderr?.destroy(),n.unref(),t())},c=p=>{if(!i){i=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners();try{n.kill()}catch{}r(new Error(p))}},l=setTimeout(a,wv);n.once("error",p=>c(p.message)),vv(n,l,s,a,c,o)}function Tu(n,e,t){return m(`Spawning emulator: ${n} ${t.join(" ")}`),new Promise((r,i)=>{let o=[],s=yv(n,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});s.stderr?.on("data",a=>o.push(a)),Sv(s,o,r,i)})}import*as Fn from"path";function Ev(n){let e=new Set,t=[];for(let r of n){let i=JSON.stringify(r);e.has(i)||(e.add(i),t.push(r))}return t}function bv(n){let e=n.instancePath?.trim();if(e)return Fn.dirname(Fn.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?Fn.dirname(Fn.normalize(t)).replace(/\\/g,"/"):""}function Pv(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function xu(n,e){return e?[...n,"-bootmode",e]:n}function Cv(n,e,t){let r=[xu(["-start",n],t)],i=bv(e);if(i)for(let o of Pv(e.imageRoot))r.push(xu(["-hvd",n,"-path",i,...o],t));return Ev(r)}async function Lu(n,e,t,r){let i=new Error("No start strategy ran"),o=Cv(n,e,r);for(let s of o)try{return await t(s),{ok:!0}}catch(a){i=a}return{ok:!1,lastError:i}}async function sc(n){return(await Z.withHdcPath(n).listDevices()).map(t=>t.serial).filter(dn)}async function ac(n){let e=await sc(n);return e.length===0?[]:(await Promise.all(e.map(r=>wo(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function Nu(n,e){return(await ac(n)).includes(e)}import*as $n from"path";import{existsSync as Iv,statSync as Av}from"fs";function jn(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function Dv(n){let e=jn(n,["instancePath","instance_path","InstancePath","instancepath","instanceDir","instance_dir","InstanceDir","deployPath","deploy_path","deployedPath","deployed_path","workPath","work_path","dataPath","data_path"]);if(e)return e;for(let[t,r]of Object.entries(n)){if(typeof r!="string"||!r.trim())continue;let i=t.toLowerCase();if(i.includes("instance")&&(i.includes("path")||i.includes("dir"))||i==="deployedpath")return r.trim()}return""}function Rv(n){return jn(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function kv(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=$n.dirname($n.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let i=$n.join(t,r.name);Iv(i)&&Av(i).isDirectory()&&(r.instancePath=i.replace(/\\/g,"/"))}}function Tv(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=Rv(t),i=jn(t,["deviceType","DeviceType","devicetype"]),o=jn(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:Dv(t),path:jn(t,["path","Path","hvdPath","hvd_path"]),imageRoot:jn(t,["imageRoot","image_root","ImageRoot"]),uuid:r||void 0,deviceType:i||void 0,osVersion:o||void 0}}).filter(t=>t.name):null}catch{return null}}function xv(n){let e=[],t=/^(name|isrunning|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,r=null,i;for(;(i=t.exec(n))!==null;){let[,o,s]=i;if(o.toLowerCase()==="name")r&&e.push(r),r={name:s.trim()};else if(r){let a=o.toLowerCase();a==="isrunning"?r.isRunning=s.trim().toLowerCase()==="true":a==="instancepath"?r.instancePath=s.trim():a==="path"?r.path=s.trim():a==="imageroot"?r.imageRoot=s.trim():a==="devicetype"?r.deviceType=s.trim():a==="os.osversion"&&(r.osVersion=s.trim())}}return r&&e.push(r),e}function Ou(n){let t=Tv(n)??xv(n);return kv(t),t}function cc(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function Lv(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function Nv(n){if(!Lv(n))return null;let e=cc(n,["osVersion","OsVersion","OSVersion"]),t=cc(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=cc(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function ko(n){let e=n.trim();if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let r=[];for(let i of t){if(!i||typeof i!="object")continue;let o=Nv(i);o&&r.push(o)}return r}catch{return[]}}function Mu(n){let t=ko(n).map(r=>r.osVersion).filter(Boolean);return[...new Set(t)]}var _u=/no images are available/i,Ov="7.0.0",Mv={foldable:["open","half-open","close"],"2in1_foldable":["open","vertical-open","half-open","close"],triplefold:["single","double","triple","left-folded-right-half-folded","left-half-folded-right-expanded","left-expanded-right-folded","left-half-folded-right-folded","left-expanded-right-half-folded","left-half-folded-right-half-folded"]};function Je(n){return n.normalize("NFKC").trim().toLowerCase()}function _v(n,e){let t=n.deviceType?.trim(),r=t?Mv[Je(t)]:void 0;if(!r)throw new Error(`Fold-state control is not supported for emulator "${n.name}" (device type: ${t||"unknown"}).`);if(!r.includes(e))throw new Error(`Fold state "${e}" is not supported by emulator "${n.name}" (device type: ${t}). Available states: ${r.join(", ")}.`)}function Fv(n){let e=n.message||"";return _u.test(e)}function jv(n){return n.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function Mr(n,e){return`${n} ${e.join(" ")}`.trim()}function $v(n){switch(n.type){case"gps":return`${n.type}:${n.key}=${n.value}`;case"sensor":return`${n.type}:${n.key}=${n.value}`;case"rotation":case"volume":return`${n.type}:${n.direction}`;case"folded-state":return`${n.type}:${n.state}`;case"battery":return`${n.type}:${n.level}`;case"battery-status":return`${n.type}:${n.status}`;default:return n.type}}var Hn=class n{static supportedControlPaths=new Set;emulatorPath;sdkPath;hdcPath;constructor(e,t,r){this.emulatorPath=e,this.sdkPath=t,this.hdcPath=r}static from(e){return new n(e.emulatorPath,e.sdkPath,e.hdcPath)}async executeEmulator(e){return m(`Executing: ${Mr(this.emulatorPath,e)}`),To(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return Tu(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return Ou(e)}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let r of t)r.name&&r.deviceType&&e.set(de(r.name),r.deviceType)}catch{}return e}async startEmulator(e){let t=await this.listEmulators(),r=de(e),i=t.find(a=>de(a.name)===r);if(!i)throw new Error(`Emulator "${e}" not found.`);let o=i.name;if(await this.isAlreadyRunning(o,i))return"already-running";await this.assertSystemImageAvailable(i);let s=await Lu(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.
44
+ 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:Nu(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),r=de(e),i=t.find(a=>de(a.name)===r);if(!i)throw new Error(`Emulator "${e}" not found.`);let o=i.name;return await this.isAlreadyRunning(o,i)?(await this.executeEmulator(["-stop",o]),"stopped"):"already-stopped"}async controlEmulator(e,t){await this.assertControlCommandSupported();let i=(await this.listEmulators()).find(s=>s.name===e);if(!i)throw new Error(`Emulator "${e}" not found.`);if(!await this.isAlreadyRunning(i.name,i))throw new Error(`Emulator "${e}" is not running.`);t.type==="folded-state"&&_v(i,t.state);let o=this.buildControlArgs(i.name,t);m(`[EmulatorManager] control ${$v(t)} -> ${Mr(this.emulatorPath,o)}`),await this.runEmulatorChecked(o,{printOutputOnSuccess:!1})}async assertControlCommandSupported(){let e=this.emulatorPath;if(n.supportedControlPaths.has(e))return;let t=["-version"];m(`Executing: ${Mr(this.emulatorPath,t)}`);let{stdout:r,stderr:i,exitCode:o}=await To(this.emulatorPath,t,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:1024*1024}),s=[r,i].filter(Boolean).join(`
45
+ `).trim(),a=jv(s);if(o!==0||!a)throw new Error("Emulator scene control commands require Emulator 7.0 or later. Unable to determine the current Emulator version.");if(I.compareVersion(a,Ov)<0)throw new Error(`Emulator scene control commands require Emulator 7.0 or later. Current Emulator version is ${a}. Please upgrade DevEco Studio or the Emulator SDK.`);n.supportedControlPaths.add(e)}buildControlArgs(e,t){let r=["-instance",e];switch(t.type){case"shake":return[...r,"-shake"];case"power":return[...r,"-power"];case"rotation":return[...r,"-rotation",t.direction];case"volume":return[...r,"-volume",t.direction];case"folded-state":return[...r,"-foldedState",t.state];case"battery":return[...r,"-battery",String(t.level)];case"battery-status":return[...r,"-batteryStatus",String(t.status)];case"gps":return[...r,"-gps",`-${t.key}`,t.value];case"outdoor-running":return[...r,"-outdoorRunning"];case"outdoor-cycling":return[...r,"-outdoorCycling"];case"driving-navigation":return[...r,"-drivingNavigation"];case"sensor":return[...r,"-sensor",`-${t.key}`,String(t.value)];default:throw new Error(`Unknown emulator control action type: ${t.type}`)}}async executeEmulatorInherit(e){m(`Executing: ${Mr(this.emulatorPath,e)}`);let{exitCode:t}=await To(this.emulatorPath,e,{stdio:"inherit",env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1});if(t!==0)throw new Error(`Emulator exited with code ${t===null?"null":t}.`)}async installEmulatorImage(e){let t=["-install","-deviceType",e.deviceType,"-osVersion",e.osVersion];e.force&&t.push("-force"),await this.executeEmulatorInherit(t)}async uninstallEmulatorImage(e){let t=await this.resolveSoftwareVersionsForUninstall(e);if(t.length===0)throw new Error(`No downloaded image matches --os-version "${e.osVersion}" for --device-type "${e.deviceType}".`);let r;try{await this.runUninstallImageChecked(e.deviceType,e.osVersion)}catch(o){if(!Fv(o))throw o;r=o}(r!==void 0||await this.hasMatchingDownloadedImage(e))&&await this.runSoftwareVersionFallback(e,t,r)}async listEmulatorImages(e){let t=["-imageList"];e.deviceType&&t.push("-deviceType",e.deviceType),e.downloaded!==void 0&&t.push("-downloaded",e.downloaded?"true":"false");let{stdout:r}=await this.executeEmulator(t);return r}async listDownloadedImageOsVersions(){let e=await this.listEmulatorImages({downloaded:!0});return Mu(e)}async hasMatchingDownloadedImage(e){return(await this.findMatchingDownloadedImages(e)).length>0}async runSoftwareVersionFallback(e,t,r){try{for(let i of t)await this.runUninstallImageChecked(e.deviceType,i)}catch(i){let o=r!==void 0?`Primary uninstall failed: ${r.message}
46
+ `:"";throw new Error(`${o}Fallback uninstall failed: ${i.message}`,{cause:i})}if(await this.hasMatchingDownloadedImage(e))throw new Error(`Image for --device-type "${e.deviceType}" and --os-version "${e.osVersion}" remains listed as downloaded after uninstallation.`)}async resolveSoftwareVersionsForUninstall(e){let t=await this.findMatchingDownloadedImages(e);return[...new Set(t.map(r=>r.softwareVersion).filter(Boolean))]}async findMatchingDownloadedImages(e){let t=await this.listEmulatorImages({deviceType:e.deviceType,downloaded:!0}),r=ko(t),i=Je(e.deviceType),o=Je(e.osVersion);return r.filter(s=>Je(s.deviceType)===i&&(Je(s.osVersion)===o||Je(s.softwareVersion)===o))}async hasDownloadedSystemImage(e,t){let r=await this.listEmulatorImages({downloaded:!0}),i=ko(r),o=Je(t),s=e?.trim()?Je(e):void 0;return i.some(a=>Je(a.osVersion)===o||Je(a.softwareVersion)===o?s===void 0?!0:Je(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:[_u]})}async runEmulatorChecked(e,t){m(`Executing: ${Mr(this.emulatorPath,e)}`);let{stdout:r,stderr:i,exitCode:o}=await To(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:20*1024*1024}),s=[r,i].filter(Boolean).join(`
47
+ `).trim(),a=/Invalid command|无效命令|鏃犳晥鍛戒护/i.test(s)||/please attach the correct parameter/i.test(s),c=(t?.extraReject??[]).some(p=>p.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 p=(t?.transformOutput?t.transformOutput(s):s).trim();p&&console.log(p)}}async checkExistingVirtualDevice(e,t){let r=await this.listEmulators(),i=de(e),o=r.find(s=>de(s.name)===i);if(o)if(t)await this.deleteVirtualDevice(o.name);else throw new Error(`Emulator "${e}" already exists. Use \`--force\` to overwrite.`);return i}async createVirtualDevice(e){let t=await this.checkExistingVirtualDevice(e.name,e.force),r=["-create",e.name,"-deviceType",e.deviceType,"-osVersion",e.osVersion];if(await this.runEmulatorChecked(r,{extraReject:[/Device create fail/i,/already exists/i,/Invalid OS version/i,/cannot be empty/i],printOutputOnSuccess:!0,transformOutput:o=>o.split(/\r?\n/).map(s=>s.trim().startsWith("Device create success.")?"Device create success.":s).join(`
48
+ `)}),!await this.waitForEmulatorPresenceByList(t))throw new Error(`Emulator "${e.name}" was reported as created, but it did not appear in the emulator list within the waiting period. Open the device manager list in DevEco Studio, then run this command again.`)}async waitForEmulatorPresenceByList(e,t=1e4,r=500){let i=Date.now()+t;for(;Date.now()<i;){if((await this.listEmulators()).some(a=>de(a.name)===e))return!0;await new Promise(a=>setTimeout(a,r))}return!1}async deleteVirtualDevice(e){let t=await this.listEmulators(),r=de(e),i=t.find(s=>de(s.name)===r);if(!i)throw new Error(`Emulator "${e}" not found.`);let o=i.name;if(i.isRunning===!0||await this.isAlreadyRunning(o,i))throw new Error(`Failed to delete device: ${o}
49
+ The device may be running.`);return await this.runEmulatorChecked(["-delete",o,"-force"],{printOutputOnSuccess:!1}),o}};import{red as lc,yellow as ju,gray as $u}from"colorette";import Gv from"ora";import{red as Hv}from"colorette";function xo(n,e){n?n.fail(e):console.error(Hv(e)),process.exit(1)}import{green as Uv}from"colorette";function Fu(n,e){return n+" ".repeat(Math.max(0,e-n.length))}function Bv(n,e){return n.map((t,r)=>{let i=t.length;for(let o of e){let s=o.cells[r]??"";i=Math.max(i,s.length)}return i})}function ft(n,e){let t=Bv(n,e),r=[];r.push(n.map((i,o)=>Fu(i,t[o])).join(" ")),r.push(t.map(i=>"-".repeat(i)).join(" "));for(let i of e){let o=i.cells.map((s,a)=>Fu(s??"",t[a])).join(" ").trimEnd();r.push(i.highlight?Uv(o):o)}return r.join(`
50
+ `)}function Vv(n,e){if(e.size!==0)for(let t of n){if(!t.isEmulator||!t.name)continue;let r=e.get(de(t.name));r&&(t.deviceType=r)}}var zv=["Name","Serial","Kind","Device Type"];function qv(n){return{cells:[n.name??n.serial,n.serial,n.isEmulator?"emulator":"device",n.deviceType??"-"],highlight:!0}}function Yv(n,e){return n.isEmulator!==e.isEmulator?n.isEmulator?1:-1:(n.name??n.serial).localeCompare(e.name??e.serial)}function Jv(){console.log(ju(" No active devices.")),console.log($u(" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function Kv(n){let t=[...n].sort(Yv).map(qv);console.log(ft(zv,t))}async function Xv(n,e){if(!n.some(i=>i.isEmulator)||!e.emulatorPath)return;let r=await Hn.from(e).getDeviceTypeByName();Vv(n,r)}async function Zv(n,e,t){try{let r=await n.getConnectedEntries();await Xv(r,e),t?.stop(),r.length===0?Jv():Kv(r)}catch(r){xo(t,`Failed to list devices: ${r.message}`)}}async function Qv(n,e){let t=await n.listDevices();if(!(t.length<2)){console.error(lc("Multiple devices connected. Specify a device with:"));for(let r of t){let i=await n.getDeviceName(r.serial);console.error($u(` ${e} -t ${r.serial} # ${i}`))}process.exit(1)}}async function eS(n,e){try{e||await Qv(n,"devecocli device view");let t=await n.listDevices(),r=await n.getDeviceInfo(t,e);r||(console.log(ju("No connected device found.")),process.exit(1));let i=await n.getDeviceDetail(r.serial),o=await n.getDeviceName(r.serial);console.log(` Serial: ${r.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(lc(`Failed to show device details: ${t.message}`)),process.exit(1)}}async function Hu(){try{let n=await I.new();return{manager:Z.from(n),toolProvider:n}}catch(n){console.error(lc(`Failed to initialize device manager: ${n.message}`)),process.exit(1);return}}var dc=new Wv("device").description("Manage connected devices");dc.command("list").description("List all connected devices").action(async()=>{let{manager:n,toolProvider:e}=await Hu(),t=Gv({text:"Querying connected devices\u2026",color:"cyan"}).start();await Zv(n,e,t)});dc.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").action(async n=>{let{manager:e}=await Hu();await eS(e,n.target)});var Uu=dc;import{Argument as yc,Command as wc,Option as $r}from"commander";import{green as Hr,cyan as Bn,red as me,yellow as ot,gray as jr}from"colorette";import gS from"ora";import tS from"readline/promises";import{execa as Wu}from"execa";import*as Ot from"fs/promises";import*as pc from"os";import*as pn from"path";var uc=`1/4:\r
41
51
  ---------------------------------------\r
42
52
  Statement About HarmonyOS and Privacy\r
43
53
  \r
@@ -1207,59 +1217,168 @@ Part I: Chinese mainland.\r
1207
1217
  Part II: Aland Islands, Albania, Andorra, Australia, Austria, Belgium, Bonaire, Bosnia and Herzegovina, Bulgaria, Canada, Croatia, Curacao, Cyprus, Czech Republic, Denmark, Dutch Caribbean, Estonia, Faroe Islands, Finland, France, Germany, Gibraltar, Greece, Greenland, Guernsey, Hungary, Iceland, Israel, Italy, Jersey, Latvia, Liechtenstein, Lithuania, Luxembourg, Malta, Moldova, Monaco, Montenegro, Netherlands, New Zealand, North Macedonia, Norway, Poland, Portugal, Ireland, Romania, Saba, Saint Vincent and the Grenadines, San Marino, Serbia, Sint Eustatius, Sint Maarten, Slovakia, Slovenia, Spain, St. Martin, St. Pierre and Miquelon (France), Sweden, Switzerland, Turkey, Ukraine, United Kingdom, United States, Vatican City.\r
1208
1218
  \r
1209
1219
  Part III: Other countries and regions.\r
1210
- ---------------------------------------\r`;var Tc=new Set,Qt=new Map,Pr="HarmonyOS_Software_Service_Agreement",Xi=["Emulator license agreements are not accepted yet.","","Accept the agreements in an interactive terminal:"," devecocli emulator license accept","","To review the agreement text (read-only):"," devecocli emulator license view"].join(`
1211
- `),Qi=Xi,Er="HarmonyOS_SDK_Agreement";function eo(r,e){return`${r}\0${e}`}function Rc(){Tc.clear(),Qt.clear()}var xc=Xi,ie=class extends Error{constructor(e=xc){super(e),this.name="EmulatorLicenseBlockedError"}};function to(r,e){return[r??"",e??""].join(`
1212
- `)}function no(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 Mc(r){return`Emulator${r.trim()}`}function ro(r){let e=Mc(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 He.join(n,"Huawei",e,".emu_config")}if(process.platform==="darwin")return He.join(Sr.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||He.join(Sr.homedir(),".cache");return He.join(t,"Huawei",e,".emu_config")}async function Oc(r,e,t){let n=eo(r,e),i=Qt.get(n);if(i!==void 0)return i;let o=await Zi(r,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=to(o.stdout,o.stderr).trim();if(o.exitCode!==0||!s)throw new ie(t);return Qt.set(n,s),s}function Lc(r){let e=r[0],t=r[r.length-1];return(e==='"'||e==="'")&&e===t?r.slice(1,-1):r}function Nc(r){try{let e=JSON.parse(r);if(e&&typeof e=="object"&&!Array.isArray(e)){let t={};for(let[n,i]of Object.entries(e))t[n]={value:typeof i=="string"?i:String(i),delimiter:"json"};return t}}catch{return}}function Hc(r){let e=r.trim();if(!(!e||e.startsWith("#")))for(let t of["=",":"]){let n=e.indexOf(t);if(n<=0)continue;let i=e.slice(0,n).trim();if(!i||t===":"&&i.includes("//"))continue;let o=Lc(e.slice(n+1).trim());return{key:i,entry:{value:o,delimiter:t}}}}function Fc(r){let e={};for(let t of r.split(/\r?\n/)){let n=Hc(t);n&&(e[n.key]=n.entry)}return e}function jc(r){let e=r.trim();if(!e)return{};let t=Nc(e);return t||Fc(r)}function $c(r){return typeof r!="string"?!1:r.normalize("NFKC").trim().toLowerCase()==="agree"}async function io(r,e,t,n){let i=await Oc(r,e,n),o=no(i);if(!o)throw new ie(n);let s=ro(o),a;try{a=await Ee.readFile(s,"utf8")}catch(p){throw p.code==="ENOENT"?new ie(n):p}let d=jc(a)[t];if(!d)throw new ie(n);if(d.delimiter==="=")throw new ie(n);if(!$c(d.value))throw new ie(n)}async function oo(r,e){await io(r,e,Pr,Qi)}async function so(r,e){await io(r,e,Er,Qi)}async function _c(r,e){let t=await Zi(r,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),n=to(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=eo(r,e);return Qt.set(i,n),n}async function Wc(r,e){let t=await _c(r,e),n=no(t);if(!n)throw new Error(`Cannot parse Emulator major.minor from:
1213
- ${t}.`);return ro(n)}function Ki(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function Uc(r,e,t){if(!t.startsWith("{"))return!1;try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return n[Pr]="agree",n[Er]="agree",await Ee.writeFile(r,`${JSON.stringify(n,null,2)}
1214
- `,"utf8"),!0}catch{}return!1}async function Bc(r,e){let t=Pr,n=Er,i=[{k:t,re:new RegExp(`^\\s*${Ki(t)}\\s*[:=]`)},{k:n,re:new RegExp(`^\\s*${Ki(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:p,re:g}of i)if(g.test(c)){s.push(`${p}:agree`),a.add(p),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(`
1220
+ ---------------------------------------\r`;var nS=new Set,Lo=new Map,fc="HarmonyOS_Software_Service_Agreement",Gu=["Emulator license agreements are not accepted yet.","","Accept the agreements interactively (shows full text + y/N prompt):"," devecocli emulator license","","Or accept non-interactively (no prompt, for CI/scripts):"," devecocli emulator license accept","","To review the agreement text (read-only):"," devecocli emulator license view"].join(`
1221
+ `),Vu=Gu,mc="HarmonyOS_SDK_Agreement";function zu(n,e){return`${n}\0${e}`}function qu(){nS.clear(),Lo.clear()}var rS=Gu,Oe=class extends Error{constructor(e=rS){super(e),this.name="EmulatorLicenseBlockedError"}};function Yu(n,e){return[n??"",e??""].join(`
1222
+ `)}function Ju(n){let e=n.normalize("NFKC"),t=e.match(/(\d+)\.(\d+)\.\d+/);if(t)return`${t[1]}.${t[2]}`;let r=e.match(/(\d+)\.(\d+)\b/);return r?`${r[1]}.${r[2]}`:null}function iS(n){return`Emulator${n.trim()}`}function Ku(n){let e=iS(n);if(process.platform==="win32"){let r=process.env.LOCALAPPDATA;if(!r)throw new Error("LOCALAPPDATA is not set; cannot resolve .emu_config path.");return pn.join(r,"Huawei",e,".emu_config")}if(process.platform==="darwin")return pn.join(pc.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||pn.join(pc.homedir(),".cache");return pn.join(t,"Huawei",e,".emu_config")}async function oS(n,e,t){let r=zu(n,e),i=Lo.get(r);if(i!==void 0)return i;let o=await Wu(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=Yu(o.stdout,o.stderr).trim();if(o.exitCode!==0||!s)throw new Oe(t);return Lo.set(r,s),s}function sS(n){let e=n[0],t=n[n.length-1];return(e==='"'||e==="'")&&e===t?n.slice(1,-1):n}function aS(n){try{let e=JSON.parse(n);if(e&&typeof e=="object"&&!Array.isArray(e)){let t={};for(let[r,i]of Object.entries(e))t[r]={value:typeof i=="string"?i:String(i),delimiter:"json"};return t}}catch{return}}function cS(n){let e=n.trim();if(!(!e||e.startsWith("#")))for(let t of["=",":"]){let r=e.indexOf(t);if(r<=0)continue;let i=e.slice(0,r).trim();if(!i||t===":"&&i.includes("//"))continue;let o=sS(e.slice(r+1).trim());return{key:i,entry:{value:o,delimiter:t}}}}function lS(n){let e={};for(let t of n.split(/\r?\n/)){let r=cS(t);r&&(e[r.key]=r.entry)}return e}function dS(n){let e=n.trim();if(!e)return{};let t=aS(e);return t||lS(n)}function uS(n){return typeof n!="string"?!1:n.normalize("NFKC").trim().toLowerCase()==="agree"}async function Xu(n,e,t,r){let i=await oS(n,e,r),o=Ju(i);if(!o)throw new Oe(r);let s=Ku(o),a;try{a=await Ot.readFile(s,"utf8")}catch(p){throw p.code==="ENOENT"?new Oe(r):p}let l=dS(a)[t];if(!l)throw new Oe(r);if(l.delimiter==="=")throw new Oe(r);if(!uS(l.value))throw new Oe(r)}async function hc(n,e){await Xu(n,e,fc,Vu)}async function gc(n,e){await Xu(n,e,mc,Vu)}async function pS(n,e){let t=await Wu(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),r=Yu(t.stdout,t.stderr).trim();if(t.exitCode!==0||!r)throw new Error(`Emulator -version failed (exit ${String(t.exitCode)}); cannot resolve .emu_config path.`);let i=zu(n,e);return Lo.set(i,r),r}async function Zu(n,e){let t=await pS(n,e),r=Ju(t);if(!r)throw new Error(`Cannot parse Emulator major.minor from:
1223
+ ${t}.`);return Ku(r)}function Bu(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function fS(n,e,t){if(!t.startsWith("{"))return!1;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return r[fc]="agree",r[mc]="agree",await Ot.writeFile(n,`${JSON.stringify(r,null,2)}
1224
+ `,"utf8"),!0}catch{}return!1}async function mS(n,e){let t=fc,r=mc,i=[{k:t,re:new RegExp(`^\\s*${Bu(t)}\\s*[:=]`)},{k:r,re:new RegExp(`^\\s*${Bu(r)}\\s*[:=]`)}],o=e.length===0?[]:e.split(/\r?\n/),s=[],a=new Set;for(let c of o){let l=!1;for(let{k:p,re:g}of i)if(g.test(c)){s.push(`${p}:agree`),a.add(p),l=!0;break}l||s.push(c)}a.has(t)||s.push(`${t}:agree`),a.has(r)||s.push(`${r}:agree`),await Ot.writeFile(n,s.join(`
1215
1225
  `)+(s.length>0?`
1216
- `:""),"utf8")}async function zc(r){await Ee.mkdir(He.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 Uc(r,e,t)||await Bc(r,e)}async function ao(r,e){return console.log(br),0}var qc="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function co(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=kc.createInterface({input:process.stdin,output:process.stdout}),i;try{i=await n.question(qc)}finally{n.close()}let o=i.trim().toLowerCase();if(o!=="y"&&o!=="yes")return 1;try{let s=await Wc(r,e);await zc(s),Rc()}catch(s){return console.error(s.message),1}return 0}var Gc=["ohos.qemu.hvd.name","const.product.name","const.product.model"];function Yc(r){let e=r.trim();if(!e||!/^[A-Za-z0-9_ ]+$/.test(e))throw new Error("The virtual device name can only contain letters, spaces, numbers, and underscores (_).")}function Jc(r){let e=r.trim();if(!e)throw new Error("--os-version must not be empty.");if(/^\d+$/.test(e))throw new Error(`--os-version "${r}" is invalid. use the full image label, e.g. HarmonyOS 5.1.1(19).`);if(!/^HarmonyOS\s+/i.test(e))throw/^HarmonyOS$/i.test(e)?new Error('--os-version is incomplete (only "HarmonyOS"). On PowerShell/cmd, quote the full label, e.g. --os-version "HarmonyOS 6.0.1(21)".'):new Error(`Invalid --os-version "${r}". It must start with "HarmonyOS " (e.g. "HarmonyOS 5.1.1(19)").`)}function Kc(r,e){let t=i=>i.normalize("NFKC").trim(),n=t(r);if(e.length===0)throw console.error(le("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(le("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(Y("--os-version does not match any downloaded image (exact string required).")),console.log(le("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 Zc=["Name","Status","Serial","Device Type","OS Version"];function Xc(r,e,t){return{cells:[r.name,t?"running":"stopped",e??"-",r.deviceType??"-",r.osVersion??"-"],highlight:t}}async function Qc(r,e){let t=await Promise.all(e.map(async n=>{let i=await Ve(r,n,Gc);return[n,i]}));return new Map(t)}async function el(r){let e=await fr(r),t=await Qc(r,e);return{serials:e,params:t}}function tl(r,e,t,n,i){if(e)for(let o of["const.product.name","const.product.model"]){let s=e.get(o);if(!s)continue;let a=t.indexOf(s);if(a===-1)continue;t.splice(a,1),i.set(s,r);let c=n.indexOf(r);c!==-1&&n.splice(c,1);return}}function nl(r,e,t){let n=new Map,i=new Map,o=[...r],s=[...t];for(let a of r){let c=e.get(a),d=c?.get("ohos.qemu.hvd.name");d&&i.set(d,a),t.length>0&&tl(a,c,s,o,n)}for(let a=0;a<s.length&&a<o.length;a++)n.set(s[a],o[a]);return{productSerialMap:n,hvdSerialMap:i}}function rl(r,e,t){let n=r.map(i=>({emu:i,serial:e.get(i.name)??t.get(i.name),effectiveRunning:i.isRunning===!0||t.has(i.name)}));return n.sort((i,o)=>i.effectiveRunning!==o.effectiveRunning?i.effectiveRunning?-1:1:i.emu.name.localeCompare(o.emu.name)),n.map(i=>Xc(i.emu,i.serial,i.effectiveRunning))}async function il(r,e,t){try{let[n,i]=await Promise.all([r.listEmulators(),el(e)]);if(n.length===0){t?.stop(),console.log(le(" No emulator instances found."));return}let o=n.filter(d=>d.isRunning).map(d=>d.name),{productSerialMap:s,hvdSerialMap:a}=nl(i.serials,i.params,o);t?.stop();let c=rl(n,s,a);console.log(Et(Zc,c))}catch(n){Xt(t,`Failed to list emulators: ${n.message}`)}}function po(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(Y(`Failed to ${t} emulator "${e[i]}": ${s.message}`)),s.stdout&&console.error(Dt(s.stdout)),s.stderr&&console.error(Dt(s.stderr))}return n}var ol=2e3,sl=6e4;async function al(r,e){let t=j(e);return(await mr(r)).some(i=>j(i)===t)}async function ho(r,e,t,n=sl,i=ol){let o=Date.now()+n;for(;Date.now()<o;){if(await al(r,e)===t)return!0;await new Promise(a=>setTimeout(a,i))}return!1}async function cl(r,e,t){if(await r.startEmulator(t)==="already-running"){console.log(le(`Emulator "${t}" is already running.`));return}console.log(Xe(`Starting emulator "${t}"...`));let i=await ho(e,t,!0);console.log(i?en(`Emulator "${t}" started successfully.`):le(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function ll(r,e,t){let n=await Promise.allSettled(t.map(o=>cl(r,e,o)));po(n,t,"start")&&process.exit(1)}async function dl(r,e){let t=e.trim();if(!Pt(t))return t;let n=await G.withHdcPath(r).getDeviceName(t);if(n===t)throw new Error(`Cannot resolve a running emulator with serial "${t}". Use \`devecocli emulator list\` or pass the emulator name instead.`);return n}async function ul(r,e,t){let n=await dl(e,t);if(console.log(Xe(`Stopping emulator "${n}"...`)),await r.stopEmulator(n)==="already-stopped"){console.log(le(`Emulator "${n}" is already stopped.`));return}let o=await ho(e,n,!1);console.log(o?en(`Emulator "${n}" stopped successfully.`):le(`Emulator "${n}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function pl(r,e,t){let n=await Promise.allSettled(t.map(o=>ul(r,e,o)));po(n,t,"stop")&&process.exit(1)}async function de(){try{let r=await O.new();return{manager:Ke.from(r),toolProvider:r}}catch(r){console.error(Y(`Failed to initialize emulator: ${r.message}`)),process.exit(1);return}}var Ce=new Cr("emulator").description("Manage emulator instances"),hl=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function tn(r){let e=new uo("--device-type <type>","Emulator device type").choices([...hl]);return r?e.makeOptionMandatory():e}function Ze(r,e){for(let t of e)if(t in r)return r[t]}function Ct(r){return r==null?"":typeof r=="string"?r.trim():String(r).trim()}function lo(r){let e=Ct(r).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var fl=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],ml="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function fo(r){try{let e=JSON.parse(r);return Array.isArray(e)?e:null}catch{return null}}function mo(r,e){let t=[];for(let n of r){if(!n||typeof n!="object")continue;let i=n,o=Ct(Ze(i,["osVersion","OsVersion","OSVersion","os_version"])),s=Ct(Ze(i,["deviceType","DeviceType","device_type"])),a=lo(Ze(i,["downloaded","Downloaded","isDownloaded"])),c=Ct(Ze(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),d=Ct(Ze(i,["releaseType","ReleaseType","release_type"])),p=lo(Ze(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,d,p,a],highlight:e&&a==="true"})}return t}function gl(r){let e=r.trim();if(!e)return!0;let t=fo(e);return t===null?!1:t.length===0?!0:mo(t,!0).length===0}function yl(r,e){let t=r.trim();if(!t)return"";let n=fo(t);if(!n)return r.trimEnd();let i=mo(n,e);return Et(fl,i)}var nn=new Cr("image").description("HarmonyOS emulator system images (download, list, remove)");nn.command("download").description("Download system image").addOption(tn(!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 de();try{await so(t.emulatorPath,t.sdkPath)}catch(n){throw n instanceof ie&&(console.error(Y(n.message)),process.exit(1)),n}r.deviceType?.trim()||(console.error(Y("Error: missing required option '--device-type <type>'")),process.exit(1)),r.osVersion?.trim()||(console.error(Y("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(Y(`Failed to download system image: ${n.message}`)),process.exit(1)}});nn.command("remove").description("Remove a downloaded system image").addOption(tn(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async r=>{let{manager:e}=await de();try{await e.uninstallEmulatorImage({deviceType:r.deviceType,osVersion:r.osVersion})}catch(t){console.error(Y(`Failed to remove system image: ${t.message}`)),process.exit(1)}});nn.command("list").description("List system images").addOption(tn(!1)).option("--all","List all images (local and remote)").addOption(new uo("--format <format>","Output format").choices(["table","json"]).default("table")).action(async r=>{let{manager:e}=await de();try{let t;r.all?t=void 0:t=!0;let n=await e.listEmulatorImages({deviceType:r.deviceType,downloaded:t});if(gl(n)){console.log(le(ml));return}if(r.format==="json"){console.log(n.trimEnd());return}let i=yl(n,r.all===!0);console.log(i)}catch(t){console.error(Y(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});Ce.addCommand(nn);var Dr=new Cr("license").description("local emulator license");Dr.command("view").description("Review agreement text(read-only)").action(async()=>{let{toolProvider:r}=await de(),e=await ao(r.emulatorPath,r.sdkPath);process.exit(e)});Dr.command("accept").description("review and accept agreements").action(async()=>{let{toolProvider:r}=await de(),e=await co(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 de(),t=Vc({text:"Listing emulators\u2026",color:"cyan"}).start();await il(r,e.hdcPath,t)});Ce.command("start [names...]").description("Start one or more emulator instances").action(async r=>{let{manager:e,toolProvider:t}=await de();try{await oo(t.emulatorPath,t.sdkPath)}catch(n){throw n instanceof ie&&(console.error(Y(n.message)),process.exit(1)),n}r?.length||(console.error(Y("Error: missing required argument 'names'")),process.exit(1)),await ll(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 de();r?.length||(console.error(Y("Error: missing required argument 'names'")),process.exit(1)),await pl(e,t.hdcPath,r)});var go=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(tn(!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");go.configureOutput({outputError:(r,e)=>{e(r),/too many arguments/i.test(r)&&e(`
1217
- ${le("Tip: ")}${Dt("Unquoted --os-version values with spaces/parentheses are split into multiple arguments. Use:")}
1218
- ${Xe('devecocli emulator create 123 --device-type phone --os-version "HarmonyOS 6.0.1(21)"')}
1219
- ${Xe('devecocli emulator create 123 --device-type phone --os-version="HarmonyOS 6.0.1(21)"')}
1220
- `)}});go.action(async(r,e)=>{try{Yc(r),Jc(e.osVersion);let{manager:t}=await de(),n=await t.listDownloadedImageOsVersions();Kc(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(en(`Emulator "${r}" created successfully.`))}catch(t){console.error(Y(`${t.message}`)),process.exit(1)}});Ce.command("delete <name>").description("Delete a local emulator instance").action(async r=>{let{manager:e}=await de();console.log(Xe(`Deleting emulator "${r}"...`));try{let t=await e.deleteVirtualDevice(r);console.log(en(`Emulator "${t}" deleted successfully.`))}catch(t){let n=t;console.error(Y(n.message)),n.stdout&&console.error(Dt(n.stdout)),n.stderr&&console.error(Dt(n.stderr)),process.exit(1)}});var yo=Ce;import{Command as Ml}from"commander";import{green as Ol,red as Rt,cyan as Uo,yellow as Bo,dim as zo}from"colorette";import Ll from"p-limit";import vl from"ora";var Fe=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=vl(e),this.spinner.start(),this.isRunning=!0}stop(){this.spinner&&this.isRunning&&(this.spinner.stop(),this.isRunning=!1)}succeed(e){this.spinner&&(this.spinner.succeed(e),this.isRunning=!1)}fail(e){this.spinner&&(this.spinner.fail(e),this.isRunning=!1)}};import*as So from"fs";import*as Po from"path";import{homedir as bl}from"os";import wl from"axios";var Ir={HTTP_TIMEOUT_MS:2e4},rn={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",oe={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"},pe={"trae-cn":{path:".trae-cn/skills",displayName:"trae-cn"},opencode:{path:".config/opencode/skills",displayName:"opencode"},cursor:{path:".cursor/skills",displayName:"cursor"},codebuddy:{path:".codebuddy/skills",displayName:"codebuddy"},qoder:{path:".qoder/skills",displayName:"qoder"},"claude-code":{path:".claude/skills",displayName:"claude-code"},codex:{path:".codex/skills",displayName:"codex"}};import{homedir as he}from"os";import X from"path";var ue="deveco-mcp";var De={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:X.join(he(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:X.join(process.platform==="win32"?X.join(process.env.APPDATA??X.join(he(),"AppData","Roaming"),"Trae CN","User"):X.join(he(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:X.join(he(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:X.join(he(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:X.join(process.platform==="win32"?X.join(process.env.APPDATA??X.join(he(),"AppData","Roaming"),"Qoder","SharedClientCache"):X.join(he(),"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:X.join(he(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:X.join(he(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function wo(r){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:r??"."},enabled:!0}}function vo(r){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:r??"."},enabled:!0}}function bo(r){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:r??"${workspaceFolder}"}}}function on(r,e){return r.format==="opencode"?wo(e):r.format==="claude-code"||r.format==="codex"?vo(e):bo(e)}var kr=class{client;constructor(){let e={timeout:Ir.HTTP_TIMEOUT_MS,headers:{"User-Agent":rn.USER_AGENT,"accept-language":rn.ACCEPT_LANGUAGE},transformResponse:[t=>t],proxy:!1};this.client=wl.create(e),this.client.interceptors.response.use(t=>t,t=>{let n=`Network connection failed (${t.code}). Please check your proxy configuration or network settings`;throw new Error(`${t.message}
1221
- ${n}`)})}async get(e,t){let n=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(n)}async post(e,t){let n=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(n)}convertResponse(e){return{data:typeof e.data=="string"?e.data:JSON.stringify(e.data),statusCode:e.status,headers:e.headers}}parseJson(e){return JSON.parse(e.data)}async getBinary(e,t){let n=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout});if(n.status!==200)throw new Error(`HTTP ${n.status}`);return Buffer.from(n.data)}},Ie=new kr;async function sn(){let r=await Ie.get(oe.TAGS_API_URL),t=an(r,"Tags API").data.skill.filter(n=>n.name==="HMOS"||n.name==="DevEco");if(t.length===0)throw new Error("No HMOS or DevEco tags found.");return t.map(n=>n.id)}async function Sl(r){let e=[],t=oe.DEFAULT_PAGE_SIZE,n=1;for(;;){let i=await Ie.post(oe.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:n,pageSize:t,tagIds:[r]}}),o=an(i,"Skills API");if(e.push(...o.data.list),o.data.list.length<t)break;n++}return e}async function Tr(r){let e=new Map,t=r.map(i=>Sl(i)),n=await Promise.all(t);for(let i of n)for(let o of i)e.has(o.id)||e.set(o.id,o);return Array.from(e.values())}async function Pl(r,e){let t=await Ie.post(oe.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:oe.DEFAULT_PAGE_SIZE,keyword:r,tagIds:[e]}});return an(t,"Skills API").data.list}async function Rr(r,e){let t=new Map,n=e.map(o=>Pl(r,o)),i=await Promise.all(n);for(let o of i)for(let s of o)t.has(s.id)||t.set(s.id,s);return Array.from(t.values())}function Eo(r){let e=[];for(let[,t]of Object.entries(pe)){let n=Po.join(bl(),t.path,r);So.existsSync(n)&&e.push(t.displayName)}return e.sort()}function an(r,e){if(r.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${r.statusCode}`);let t=Ie.parseJson(r);if(t.code!==oe.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Co(r){let e=`${oe.SKILL_API_BASE}/${r}/checksum`,t=await Ie.get(e);return an(t,"Checksum API").data}import El from"adm-zip";import Cl from"crypto";import Io from"fs";import L from"path";import{fileURLToPath as Dl}from"url";import{homedir as Ao}from"os";import{red as Il}from"colorette";var fe=Io.promises;function xr(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=L.resolve(e),n=L.resolve(r),i=L.relative(n,t);if(i.startsWith("..")||L.isAbsolute(i))throw new Error(`Path traversal detected: ${e}.`)}function Mr(r){return L.isAbsolute(r)?r:L.resolve(process.cwd(),r)}function Al(r){return Cl.createHash("sha256").update(r).digest("hex")}async function kl(r,e){if(r.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let n=Al(r),i=e.sha256.toLowerCase();if(n!==i)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function ko(r){let e=`${oe.SKILL_API_BASE}/${r}/install?format=zip`,t=await Ie.getBinary(e),n=await Co(r);return await kl(t,n),t}async function Tl(r,e,t){xr(t);let n=new El(r),i=n.getEntries();try{await fe.stat(e)}catch{await fe.mkdir(e,{recursive:!0})}let o=L.join(e,t);Do(e,o);for(let s of i){let a=L.join(o,s.entryName);Do(o,a)}n.extractAllTo(o,!0)}async function Or(r){let e=pe[r];if(!e)throw new Error(`Invalid agent: ${r}, Valid options are: ${Object.keys(pe).join(", ")}`);let t=L.join(Ao(),e.path.replace("/skills",""));try{return await fe.access(t),!0}catch{return!1}}function Lr(r){let e=pe[r];return L.join(Ao(),e.path)}function Nr(r,e){return L.join(r,"."+e,"skills")}async function Rl(r,e,t){xr(e);let n=L.join(r,e);try{if(await fe.access(n),t)await fe.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 Hr(r,e,t){await Tl(r,e,t),console.log(`Skill ${t} installed to ${L.join(e,t)}.`)}async function Fr(r,e,t){let n=L.join(e,t);await fe.mkdir(n,{recursive:!0});let i=L.join(n,L.basename(r));await fe.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(Il(`Faild to exute operation for skill "${r}": ${n}`)),{success:!1,error:n}}async function Qe(r,e,t,n){try{let i=await e(),{shouldSkip:o}=await Rl(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{xr(r);let t=await e(),n=L.join(t,r);try{await fe.access(n)}catch{return console.log(`Skill ${r} not found in ${t}`),{success:!0,skipped:!0}}return await fe.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 Ro(r,e,t,n=!1){return Qe(r,()=>Lr(e),i=>Hr(t,i,r),n)}async function xo(r,e,t,n=!1){return Qe(r,()=>t,i=>Hr(e,i,r),n)}async function Mo(r,e,t,n,i=!1){return Qe(r,()=>Nr(t,n),o=>Hr(e,o,r),i)}async function Oo(r,e,t,n=!1){return Qe(r,()=>Lr(t),i=>Fr(e,i,r),n)}async function Lo(r,e,t,n,i=!1){return Qe(r,()=>Nr(t,n),o=>Fr(e,o,r),i)}async function No(r,e,t,n=!1){return Qe(r,()=>t,i=>Fr(e,i,r),n)}async function Ho(r,e){return jr(r,()=>Lr(e))}async function Fo(r,e){return jr(r,()=>e)}async function jo(r,e,t){return jr(r,()=>Nr(e,t))}function $o(){let e=L.dirname(Dl(import.meta.url));for(;;){let t=L.join(e,"SKILL.md");if(Io.existsSync(t))return t;let n=L.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 xl}from"colorette";async function It(r){if(!r)return[];let e=[],t=r.split(",").map(n=>n.trim());for(let n of t){if(!await Or(n))throw new Error(`Agent ${n} not found`);e.push(n)}return e}async function At(){let r=[];for(let e of Object.keys(pe))await Or(e)&&r.push(e);return r}function kt(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(xl("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${n}`),n>0&&(process.exitCode=1)}function Ae(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 Tt(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 cn(r,e,t){let n=[],i=[],o;if(e?o=e:t&&r.agent?i=(await It(r.agent)).map(a=>({project:t,agent:a})):t?i=(await At()).map(a=>({project:t,agent:a})):r.agent?n=await It(r.agent):n=await At(),!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 Nl(r){let e=await sn();if(r.all)return(await Tr(e)).map(n=>n.enName);{let n=(await Rr(r.skill,e)).find(i=>i.enName===r.skill);if(!n)throw new Error(`Skill "${r.skill}" not found`);return[n.enName]}}async function Hl(r,e,t,n){let i=[];if(t.customPath){let o=await xo(r,e,t.customPath,n);return i.push(o),i}for(let o of t.agents){let s=await Ro(r,o,e,n);i.push(s)}for(let{project:o,agent:s}of t.projectAgents){let a=await Mo(r,e,o,s,n);i.push(a)}return i}function Fl(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}=Tt(r.path,r.project,r.agent);return t&&Ae(t,"Project directory",r.force),e&&Ae(e,"Directory",r.force),{resolvedPath:e,resolvedProject:t}}async function jl(r,e,t){let n=await cn(r,e,t);return{skillNames:await Nl(r),targets:n}}async function $l(r,e,t,n){let i=[],o=r.length,s=Ll(5),a=r.map(async c=>s(async()=>{try{let d=await ko(c);return{name:c,buffer:d,success:!0}}catch(d){let p=d instanceof Error?d.message:"unknown error";return{name:c,error:p,success:!1}}}));for(let c=0;c<r.length;c++){let d=r[c],p=o>1?` (${c+1}/${o})`:"";n.start(`Installing ${d}${p}...`);let g=await a[c];if(!g.success){n.fail(),console.log(Rt(`${d}: Download failed - ${g.error}`)),i.push({success:!1});continue}n.stop();let k=await Hl(d,g.buffer,e,t);i.push(...k)}return i}async function _l(r){let e=new Fe;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:n}=Fl(r),{skillNames:i,targets:o}=await jl(r,t,n),s=await $l(i,o,r.force||!1,e);e.stop(),kt(s)}catch(t){throw e.stop(),t}}function Wl(r){let{resolvedPath:e,resolvedProject:t}=Tt(r.path,r.project,r.agent);return t&&Ae(t,"Project directory"),e&&Ae(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function Ul(r,e){let t=new Fe;try{t.start("Removing skill...");let{resolvedPath:n,resolvedProject:i}=Wl(e);t.stop();let o=await Bl(e,r,n,i);t.stop(),kt(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 ln(r,e){let t=[];for(let n of e){let i=n.type==="agent"?await Ho(r,n.agent):await jo(r,n.project,n.agent);t.push(i)}return t}async function Bl(r,e,t,n){if(t)return[await Fo(e,t)];if(n&&r.agent){let a=(await It(r.agent)).map(c=>({type:"projectAgent",agent:c,project:n}));return ln(e,a)}if(n){let s=await At();Wo(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:n}));return ln(e,a)}if(r.agent){let a=(await It(r.agent)).map(c=>({type:"agent",agent:c}));return ln(e,a)}let i=await At();Wo(i,"or use --path for a custom location.");let o=i.map(s=>({type:"agent",agent:s}));return ln(e,o)}var xt=new Ml("skills").description("Manage HarmonyOS skills");xt.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 Fe;try{e.start("Fetching skills...");let t=await sn(),n=await Tr(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(zo(i.description));let o=Eo(i.enName);o.length>0&&console.log(Ol(`Installed for: ${o.join(", ")}`)),console.log()}else console.log(i.enName)}catch(t){e.stop(),console.error(Rt(t.message)),process.exit(1)}});xt.command("find <keyword>").description("Search skills by keyword").action(async r=>{let e=new Fe;try{e.start("Searching skills...");let t=await sn(),n=await Rr(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(zo(i.description)),console.log()}catch(t){e.stop(),console.error(Rt(t.message)),process.exit(1)}});xt.command("add").description("Install skills to AI agents").option("--all","Install all available skills").option("--agent <agents>","Target agents, comma-separated; Omit to install to all available agents").option("--skill <skill-name>","Name of the skill to install").option("-f, --force","Overwrite an existing skill installation").option("--project <path>","Project root directory for skill installation").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").action(async r=>{try{await _l(r)}catch(e){console.error(Rt(e.message)),process.exit(1)}});xt.command("remove").description("Remove an installed skill from AI agents").requiredOption("--skill <skill-name>","Name of the skill to remove").option("--agent <agents>","Target agents, comma-separated.Omit to remove from all available agents").option("--project <path>","Project root directory for skill removal").option("--path <path>","Path for skill removal").action(async r=>{try{await Ul(r.skill,r)}catch(e){console.error(Rt(e.message)),process.exit(1)}});var qo=xt;import{Command as ql,InvalidArgumentError as Go}from"commander";import{cyan as dn}from"colorette";function je(r,e){if(r.exitCode===0)return null;let t=r.stderr||r.stdout,n=qe(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 $r=[800,1500,2500];function zl(r){return new Promise(e=>setTimeout(e,r))}var un=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=G.from(e)}createFollowLineHandler(e){return(t,n)=>{let i=e.keyword?t.filter(o=>o.includes(e.keyword)):t;if(n!=="stderr")for(let o of i)console.log(o)}}findDeviceByArg(e,t){return e.find(n=>n.serial===t||n.name===t)}formatConnectedDeviceList(e){return e.map(t=>` - ${t.name} (${t.serial})`).join(`
1222
- `)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let i=t[0];return v(dn(`Using device serial: ${i}`)),i}if(e&&t.includes(e))return v(dn(`Using device serial: ${e}`)),e;let n=await this.loadConnectedDevicesByName();if(e){let i=this.findDeviceByArg(n,e);if(i)return v(dn(`Using device: ${i.name} (${i.serial})`)),i.serial;let o=this.formatConnectedDeviceList(n);throw new Error(`Device '${e}' not found.
1226
+ `:""),"utf8")}async function Qu(n){await Ot.mkdir(pn.dirname(n),{recursive:!0});let e="";try{e=await Ot.readFile(n,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}let t=e.trim();await fS(n,e,t)||await mS(n,e)}async function ep(n,e){return console.log(uc),0}var hS="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function tp(n,e){try{return await hc(n,e),await gc(n,e),!0}catch(t){if(t instanceof Oe)return!1;throw t}}async function np(n,e){if(await tp(n,e))return console.log("Emulator license agreements are already accepted."),0;if(console.log(uc),!process.stdin.isTTY||!process.stdout.isTTY)return console.error("`devecocli emulator license` requires an interactive terminal.\nFor non-interactive environments, use: devecocli emulator license accept"),1;let r=tS.createInterface({input:process.stdin,output:process.stdout}),i;try{i=await r.question(hS)}finally{r.close()}let o=i.trim().toLowerCase();if(o!=="y"&&o!=="yes")return console.error("Agreements not accepted. Emulator features will remain blocked until accepted."),1;try{let s=await Zu(n,e);await Qu(s),qu()}catch(s){return console.error(s.message),1}return console.log("Emulator license agreements accepted."),0}async function rp(n,e){if(await tp(n,e))return console.log("Emulator license agreements are already accepted."),0;try{let t=await Zu(n,e);await Qu(t),qu()}catch(t){return console.error(t.message),1}return console.log("Emulator license agreements accepted."),0}var yS=["ohos.qemu.hvd.name","const.product.name","const.product.model"],ip=["open","half-open","close","vertical-open","single","double","triple","left-folded-right-half-folded","left-half-folded-right-expanded","left-expanded-right-folded","left-half-folded-right-folded","left-expanded-right-half-folded","left-half-folded-right-half-folded"],wS=`
1227
+ Folded state scene mappings:
1228
+ foldableFold (3):
1229
+ open Fully expanded state
1230
+ half-open Semi-folded state
1231
+ close Fully folded state
1232
+
1233
+ 2in1foldableFold (4):
1234
+ open Landscape unfolded state
1235
+ vertical-open Portrait unfolded state
1236
+ half-open Semi-folded state
1237
+ close Magnetic attachment state
1238
+
1239
+ tripleFold (9):
1240
+ single
1241
+ double
1242
+ triple
1243
+ left-folded-right-half-folded
1244
+ left-half-folded-right-expanded
1245
+ left-expanded-right-folded
1246
+ left-half-folded-right-folded
1247
+ left-expanded-right-half-folded
1248
+ left-half-folded-right-half-folded
1249
+ `;function vS(n){let e=n.trim();if(!e)throw new Error("--target must not be empty.");return e}function SS(n){let e=n.trim();if(!ip.includes(e))throw new Error(`Invalid fold state "${n}". Available values: ${ip.join(", ")}`);return e}function sp(n,e,t,r){let i=e.trim();if(!/^-?\d+$/.test(i))throw new Error(`${n} must be an integer in [${t}, ${r}].`);let o=Number(i);if(o<t||o>r)throw new Error(`${n} must be in [${t}, ${r}].`);return o}function ap(n,e,t,r,i){let o=e.trim(),s=Number(o);if(!o||Number.isNaN(s))throw new Error(`${n} must be a number in [${t}, ${r}].`);if(i!==void 0&&!ES(o,i))throw new Error(`${n} supports at most ${i} decimal place(s).`);if(s<t||s>r)throw new Error(`${n} must be in [${t}, ${r}].`);return o}function ES(n,e){let t=n.split(".")[1];return t===void 0||t.length<=e}function bS(n,e,t,r,i){return Number(ap(n,e,t,r,i))}function PS(n){let e=n.trim();if(!e||!/^[A-Za-z0-9_ ]+$/.test(e))throw new Error("The virtual device name can only contain letters, spaces, numbers, and underscores (_).")}function CS(n){let e=n.trim();if(!e)throw new Error("--os-version must not be empty.");if(/^\d+$/.test(e))throw new Error(`--os-version "${n}" is invalid. use the full image label, e.g. HarmonyOS 5.1.1(19).`);if(!/^HarmonyOS\s+/i.test(e))throw/^HarmonyOS$/i.test(e)?new Error('--os-version is incomplete (only "HarmonyOS"). On PowerShell/cmd, quote the full label, e.g. --os-version "HarmonyOS 6.0.1(21)".'):new Error(`Invalid --os-version "${n}". It must start with "HarmonyOS " (e.g. "HarmonyOS 5.1.1(19)").`)}function IS(n,e){let t=i=>i.normalize("NFKC").trim(),r=t(n);if(e.length===0)throw console.error(ot("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(ot("Run `devecocli emulator image download ...` followed by `devecocli emulator image list` and then copy an `osVersion` string exactly.")),new Error("No downloaded osVersion values parsed; cannot validate --os-version.");if(!e.some(i=>t(i)===r)){console.error(me("--os-version does not match any downloaded image (exact string required).")),console.log(ot("Use one of these --os-version values:"));for(let i of e)console.log(` ${i}`);throw new Error(`No downloaded image matches --os-version "${n}".`)}}var AS=["Name","Status","Serial","Device Type","OS Version"];function DS(n,e,t){return{cells:[n.name,t?"running":"stopped",e??"-",n.deviceType??"-",n.osVersion??"-"],highlight:t}}async function RS(n,e){let t=await Promise.all(e.map(async r=>{let i=await Nn(n,r,yS);return[r,i]}));return new Map(t)}async function kS(n){let e=await sc(n),t=await RS(n,e);return{serials:e,params:t}}function TS(n,e,t,r,i){if(e)for(let o of["const.product.name","const.product.model"]){let s=e.get(o);if(!s)continue;let a=t.indexOf(s);if(a===-1)continue;t.splice(a,1),i.set(s,n);let c=r.indexOf(n);c!==-1&&r.splice(c,1);return}}function xS(n,e,t){let r=new Map,i=new Map,o=[...n],s=[...t];for(let a of n){let c=e.get(a),l=c?.get("ohos.qemu.hvd.name");l&&i.set(l,a),t.length>0&&TS(a,c,s,o,r)}for(let a=0;a<s.length&&a<o.length;a++)r.set(s[a],o[a]);return{productSerialMap:r,hvdSerialMap:i}}function LS(n,e,t){let r=n.map(i=>({emu:i,serial:e.get(i.name)??t.get(i.name),effectiveRunning:i.isRunning===!0||t.has(i.name)}));return r.sort((i,o)=>i.effectiveRunning!==o.effectiveRunning?i.effectiveRunning?-1:1:i.emu.name.localeCompare(o.emu.name)),r.map(i=>DS(i.emu,i.serial,i.effectiveRunning))}async function NS(n,e,t){try{let[r,i]=await Promise.all([n.listEmulators(),kS(e)]);if(r.length===0){t?.stop(),console.log(ot(" No emulator instances found."));return}let o=r.filter(l=>l.isRunning).map(l=>l.name),{productSerialMap:s,hvdSerialMap:a}=xS(i.serials,i.params,o);t?.stop();let c=LS(r,s,a);console.log(ft(AS,c))}catch(r){xo(t,`Failed to list emulators: ${r.message}`)}}function cp(n,e,t){let r=!1;for(let i=0;i<n.length;i++){let o=n[i];if(o.status!=="rejected")continue;r=!0;let s=o.reason;console.error(me(`Failed to ${t} emulator "${e[i]}": ${s.message}`)),s.stdout&&console.error(jr(s.stdout)),s.stderr&&console.error(jr(s.stderr))}return r}var OS=2e3,MS=6e4;async function _S(n,e){let t=de(e);return(await ac(n)).some(i=>de(i)===t)}async function lp(n,e,t,r=MS,i=OS){let o=Date.now()+r;for(;Date.now()<o;){if(await _S(n,e)===t)return!0;await new Promise(a=>setTimeout(a,i))}return!1}async function FS(n,e,t){if(await n.startEmulator(t)==="already-running"){console.log(ot(`Emulator "${t}" is already running.`));return}console.log(Bn(`Starting emulator "${t}"...`));let i=await lp(e,t,!0);console.log(i?Hr(`Emulator "${t}" started successfully.`):ot(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function jS(n,e,t){let r=await Promise.allSettled(t.map(o=>FS(n,e,o)));cp(r,t,"start")&&process.exit(1)}async function dp(n,e){let t=e.trim();if(!dn(t))return t;let r=await Z.withHdcPath(n).getDeviceName(t);if(r===t)throw new Error(`Cannot resolve a running emulator with serial "${t}". Use \`devecocli emulator list\` or pass the emulator name instead.`);return r}async function $S(n,e,t){let r=await dp(e,t);if(console.log(Bn(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(ot(`Emulator "${r}" is already stopped.`));return}let o=await lp(e,r,!1);console.log(o?Hr(`Emulator "${r}" stopped successfully.`):ot(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function HS(n,e,t){let r=await Promise.allSettled(t.map(o=>$S(n,e,o)));cp(r,t,"stop")&&process.exit(1)}async function Me(){try{let n=await I.new();return{manager:Hn.from(n),toolProvider:n}}catch(n){console.error(me(`Failed to initialize emulator: ${n.message}`)),process.exit(1);return}}async function mt(n,e){try{let t=vS(n.target),r=e(),{manager:i,toolProvider:o}=await Me(),s=await dp(o.hdcPath,t);await i.controlEmulator(s,r),console.log(Hr(`Emulator "${t}" operation completed.`))}catch(t){let r=n.target?.trim()||"<unknown>";console.error(me(`Failed to operate emulator "${r}": ${t.message}`)),process.exit(1)}}function US(n){let e=[];return No(e,"longitude",n.longitude,-180,180,8),No(e,"latitude",n.latitude,-90,90,8),No(e,"altitude",n.altitude,-1e4,1e4,2),No(e,"bearing",n.direction,0,359.99,2,"--direction"),vc(e,"Specify one geolocation option.")}function BS(n){let e=[];return _r(e,"light",n.lightIntensity,0,1e5,!1,"--light-intensity"),_r(e,"humidity",n.humidity,0,100,!1),_r(e,"temperature",n.temperature,-273.1,100,!1),_r(e,"steps",n.steps,0,1e4,!0),_r(e,"heartrate",n.heartrate,0,255,!0),vc(e,"Specify one sensor option.")}function vc(n,e){if(n.length===0)throw new Error(e);if(n.length>1)throw new Error("Only one operation option can be specified.");return n[0]}function No(n,e,t,r,i,o,s=`--${e}`){t!==void 0&&n.push({type:"gps",key:e,value:ap(s,t,r,i,o)})}function _r(n,e,t,r,i,o,s=`--${e}`){if(t===void 0)return;let a=o?sp(s,t,r,i):bS(s,t,r,i,1);n.push({type:"sensor",key:e,value:a})}function WS(n){let e=[];return n.level!==void 0&&e.push({type:"battery",level:sp("--level",n.level,1,100)}),n.status!==void 0&&e.push({type:"battery-status",status:n.status==="charging"?1:0}),vc(e,"Specify --level or --status.")}var ie=new wc("emulator").description("Manage emulator instances"),GS=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function Oo(n){let e=new $r("--device-type <type>","Emulator device type").choices([...GS]);return n?e.makeOptionMandatory():e}function Un(n,e){for(let t of e)if(t in n)return n[t]}function Fr(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function op(n){let e=Fr(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var VS=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],zS="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function up(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function pp(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let i=r,o=Fr(Un(i,["osVersion","OsVersion","OSVersion","os_version"])),s=Fr(Un(i,["deviceType","DeviceType","device_type"])),a=op(Un(i,["downloaded","Downloaded","isDownloaded"])),c=Fr(Un(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=Fr(Un(i,["releaseType","ReleaseType","release_type"])),p=op(Un(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,l,p,a],highlight:e&&a==="true"})}return t}function qS(n){let e=n.trim();if(!e)return!0;let t=up(e);return t===null?!1:t.length===0?!0:pp(t,!0).length===0}function YS(n,e){let t=n.trim();if(!t)return"";let r=up(t);if(!r)return n.trimEnd();let i=pp(r,e);return ft(VS,i)}var Mo=new wc("image").description("HarmonyOS emulator system images (download, list, remove)");Mo.command("download").description("Download system image").addOption(Oo(!1)).option("--os-version <version>","Example: HarmonyOS 5.1.1(19) or HarmonyOS 6.0.1(21) (required)").option("--force","Overwrite an existing image").action(async n=>{let{manager:e,toolProvider:t}=await Me();try{await gc(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof Oe&&(console.error(me(r.message)),process.exit(1)),r}n.deviceType?.trim()||(console.error(me("Error: missing required option '--device-type <type>'")),process.exit(1)),n.osVersion?.trim()||(console.error(me("Error: misssing required option '--os-version <version>'")),process.exit(1));try{await e.installEmulatorImage({deviceType:n.deviceType.trim(),osVersion:n.osVersion.trim(),force:n.force===!0})}catch(r){console.error(me(`Failed to download system image: ${r.message}`)),process.exit(1)}});Mo.command("remove").description("Remove a downloaded system image").addOption(Oo(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let{manager:e}=await Me();try{await e.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})}catch(t){console.error(me(`Failed to remove system image: ${t.message}`)),process.exit(1)}});Mo.command("list").description("List system images").addOption(Oo(!1)).option("--all","List all images (local and remote)").addOption(new $r("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let{manager:e}=await Me();try{let t;n.all?t=void 0:t=!0;let r=await e.listEmulatorImages({deviceType:n.deviceType,downloaded:t});if(qS(r)){console.log(ot(zS));return}if(n.format==="json"){console.log(r.trimEnd());return}let i=YS(r,n.all===!0);console.log(i)}catch(t){console.error(me(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});ie.addCommand(Mo);var _o=new wc("license").description("Review and accept emulator license agreements interactively (prints full text + y/N prompt)");_o.command("view").description("Review agreement text (read-only, no changes)").action(async()=>{let{toolProvider:n}=await Me(),e=await ep(n.emulatorPath,n.sdkPath);process.exit(e)});_o.command("accept").description("Accept all emulator license agreements non-interactively (skips review and prompt)").action(async()=>{let{toolProvider:n}=await Me(),e=await rp(n.emulatorPath,n.sdkPath);process.exit(e)});_o.action(async()=>{let{toolProvider:n}=await Me(),e=await np(n.emulatorPath,n.sdkPath);process.exit(e)});ie.addCommand(_o);ie.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>mt(n,()=>({type:"shake"})));ie.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>mt(n,()=>({type:"power"})));ie.command("rotate").description("Rotate emulator").addOption(new $r("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new yc("<direction>").choices(["left","right"])).action((n,e)=>mt(e,()=>({type:"rotation",direction:n})));ie.command("volume").description("Change volume").addOption(new $r("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new yc("<direction>").choices(["up","down"])).action((n,e)=>mt(e,()=>({type:"volume",direction:n})));ie.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",wS).action((n,e)=>mt(e,()=>({type:"folded-state",state:SS(n)})));ie.command("battery").description("Set battery level or charging status").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--level <1-100>","Battery level, SOC (integer 1-100)").addOption(new $r("--status <status>","Charging status").choices(["charging","discharging"])).action(n=>mt(n,()=>WS(n)));ie.command("geolocation").description("Inject geographic coordinates and direction").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--longitude <value>","Longitude (-180.0 to 180.0)").option("--latitude <value>","Latitude (-90.0 to 90.0)").option("--altitude <value>","Altitude (-10000.0 to 10000.0)").option("--direction <value>","Heading direction in degrees (0.00 to 359.99)").action(n=>mt(n,()=>US(n)));ie.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new yc("<type>","Motion simulation scene").choices(["outdoorRunning","outdoorCycling","drivingNavigation"])).action((n,e)=>{let t={outdoorRunning:{type:"outdoor-running"},outdoorCycling:{type:"outdoor-cycling"},drivingNavigation:{type:"driving-navigation"}};return mt(e,()=>t[n])});ie.command("sensor").description("Inject sensor data").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--light-intensity <value>","Light sensor (0 to 100000)").option("--humidity <value>","Humidity sensor (0 to 100)").option("--temperature <value>","Temperature sensor (-273.1 to 100)").option("--steps <value>","Steps sensor (integer 0 to 10000)").option("--heartrate <value>","Heart rate sensor (integer 0 to 255)").action(n=>mt(n,()=>BS(n)));ie.command("list").description("List all emulator instances").action(async()=>{let{manager:n,toolProvider:e}=await Me(),t=gS({text:"Listing emulators\u2026",color:"cyan"}).start();await NS(n,e.hdcPath,t)});ie.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let{manager:e,toolProvider:t}=await Me();try{await hc(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof Oe&&(console.error(me(r.message)),process.exit(1)),r}n?.length||(console.error(me("Error: missing required argument 'names'")),process.exit(1)),await jS(e,t.hdcPath,n)});ie.command("stop <names...>").description("Stop one or more emulator instances (by name or serial,e.g.,127.0.0.1:<port>)").action(async n=>{let{manager:e,toolProvider:t}=await Me();n?.length||(console.error(me("Error: missing required argument 'names'")),process.exit(1)),await HS(e,t.hdcPath,n)});var fp=ie.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(Oo(!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");fp.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
1250
+ ${ot("Tip: ")}${jr("Unquoted --os-version values with spaces/parentheses are split into multiple arguments. Use:")}
1251
+ ${Bn('devecocli emulator create 123 --device-type phone --os-version "HarmonyOS 6.0.1(21)"')}
1252
+ ${Bn('devecocli emulator create 123 --device-type phone --os-version="HarmonyOS 6.0.1(21)"')}
1253
+ `)}});fp.action(async(n,e)=>{try{PS(n),CS(e.osVersion);let{manager:t}=await Me(),r=await t.listDownloadedImageOsVersions();IS(e.osVersion,r),console.log(Bn(`Creating emulator "${n}"...`)),await t.createVirtualDevice({name:n,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(Hr(`Emulator "${n}" created successfully.`))}catch(t){console.error(me(`${t.message}`)),process.exit(1)}});ie.command("delete <name>").description("Delete a local emulator instance").action(async n=>{let{manager:e}=await Me();console.log(Bn(`Deleting emulator "${n}"...`));try{let t=await e.deleteVirtualDevice(n);console.log(Hr(`Emulator "${t}" deleted successfully.`))}catch(t){let r=t;console.error(me(r.message)),r.stdout&&console.error(jr(r.stdout)),r.stderr&&console.error(jr(r.stderr)),process.exit(1)}});var mp=ie;import{Command as pE}from"commander";import{red as Ic,cyan as Fe}from"colorette";import*as _p from"readline";import*as Np from"crypto";import*as hp from"http";import*as gp from"crypto";import{URL as JS}from"url";var Fo=class{server=null;port=0;clientSecret;callbackPath="/callback";resolveCallback=null;rejectCallback=null;timeoutId=null;baseUrl;successRedirectUrl;failedRedirectUrl;constructor(e,t,r,i){this.clientSecret=e,this.baseUrl=t,this.successRedirectUrl=r,this.failedRedirectUrl=i}async start(){return new Promise((e,t)=>{let r=hp.createServer((i,o)=>{this.handleRequest(i,o)});r.keepAliveTimeout=1,r.on("error",i=>{t(new Error("Failed to start local auth server",{cause:i}))}),r.listen(0,"127.0.0.1",()=>{this.server=r;let i=r.address();this.port=i.port,e()})})}async waitForCallback(e=3e4){return new Promise((t,r)=>{this.resolveCallback=i=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),t(i)},this.rejectCallback=i=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),r(i)},this.timeoutId=setTimeout(()=>{this.timeoutId=null,this.rejectCallback?.(new Error("Callback timeout"))},e)})}async stop(){return this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.server?new Promise(e=>{let t=this.server;this.server=null,typeof t.closeAllConnections=="function"&&t.closeAllConnections();let r=setTimeout(()=>{e()},100);t.close(()=>{clearTimeout(r),e()})}):Promise.resolve()}handleRequest(e,t){let r=e.headers.host||"";if(![`127.0.0.1:${this.port}`,`localhost:${this.port}`].includes(r.toLowerCase())){t.writeHead(400),t.end("Bad Host");return}let o=new JS(e.url??"",`http://${r}`);if(o.pathname!==this.callbackPath){t.writeHead(404),t.end("Not Found");return}try{let s=o.searchParams;if(e.method==="POST"){let a="";e.on("data",c=>{a+=c.toString()}),e.on("end",()=>{this.handleCallbackRequest(e,t,s,a)})}else this.handleCallbackRequest(e,t,s,"")}catch(s){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(s)}}handleCallbackRequest(e,t,r,i){try{let o=this.parseParams(r,i),s=o.get("code"),a=o.get("tempToken"),c=o.get("siteId"),l=o.get("quit");if(!this.validateCode(s)){t.writeHead(400),t.end("Bad Request");return}if(this.isQuitRequest(l)){this.handleQuitRequest(t);return}if(!a||!c){t.writeHead(400),t.end("Bad Request");return}let p={tempToken:a,siteId:c,quit:l??void 0};this.resolveCallback?.(p),this.sendSuccessResponse(t)}catch(o){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(o)}}parseParams(e,t){return t&&t.trim()?new URLSearchParams(t):e}validateCode(e){let t=Buffer.from(e||"","utf8"),r=Buffer.from(this.clientSecret,"utf8");return t.length===r.length&&gp.timingSafeEqual(t,r)}isQuitRequest(e){return e==="true"||e==="access_denied"||e==="quit"}handleQuitRequest(e){this.rejectCallback?.(new Error("User quit the login process")),e.writeHead(302,{Location:`${this.baseUrl}/${this.failedRedirectUrl}`}),e.end()}sendSuccessResponse(e){e.writeHead(302,{Location:`${this.baseUrl}/${this.successRedirectUrl}`}),e.end()}getPort(){return this.port}};import*as we from"fs";import*as Gn from"path";import{homedir as nE}from"os";var gt={};wy(gt,{LocalCrypto:()=>gt,decryptForLocalStorage:()=>QS,decryptForLocalStorageFromDirectory:()=>eE,encryptForLocalStorage:()=>ZS,isEncryptedBlob:()=>tE});import*as W from"fs";import*as ht from"path";import*as ye from"crypto";import*as wp from"os";import{homedir as vp}from"os";var st=class extends Error{constructor(e){super(e),this.name="DefinedError"}};var Ur=nn.ALGORITHM,Sp=nn.IV_LENGTH,Br=nn.KEY_LENGTH,Wr=nn.KEY_LENGTH,Gr=nn.KEK_VERSIONS,jo=process.env.DEVECO_CLI_DATA_DIR||ht.join(vp(),le.CONFIG_DIR_NAME,le.APP_NAME),$o=ht.join(vp(),".local","share",le.APP_NAME,"keys"),Wn=ht.join(jo,le.KEY_FILE_NAME);function yp(n){return wp.platform()==="win32"?`Permission denied. Please run as administrator or grant write permission to ${n}.`:`Permission denied. You can try: sudo chown -R $(whoami) ${n}`}function Sc(n){return ht.join($o,`${n}.bin`)}function Ep(){if(!W.existsSync(jo))try{W.mkdirSync(jo,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new st(yp(jo)):n}if(!W.existsSync($o))try{W.mkdirSync($o,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new st(yp(ht.dirname($o))):n}}function bp(){Ep();for(let n of Gr){let e=Sc(n);W.existsSync(e)||W.writeFileSync(e,ye.randomBytes(Br),{mode:384})}}function Pp(n){bp();let e=Sc(n),t=W.readFileSync(e);if(t.length===Br)return t;let r=ye.randomBytes(Br);return W.writeFileSync(e,r,{mode:384}),r}function Ec(n,e){let t=ye.randomBytes(Sp),r=Pp(e),i=ye.createCipheriv(Ur,r,t),o=Buffer.concat([i.update(n),i.final()]),s=i.getAuthTag();return{version:1,algorithm:Ur,kekId:e,encryptedDek:o.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function Cp(n,e){return Ip(Buffer.from(n.encryptedDek,"base64"),e,n.iv,n.authTag)}function Ip(n,e,t,r){let i=ye.createDecipheriv(Ur,e,Buffer.from(t,"base64"));return i.setAuthTag(Buffer.from(r,"base64")),Buffer.concat([i.update(n),i.final()])}function Ap(n,e){return Ip(Buffer.from(n.ciphertext,"base64"),e,n.iv,n.authTag).toString("utf8")}function KS(){if(bp(),W.existsSync(Wn))return;let n=ye.randomBytes(Wr),e=Ec(n,Gr[0]);W.writeFileSync(Wn,JSON.stringify(e,null,2),{mode:384})}function Dp(){KS();let n=JSON.parse(W.readFileSync(Wn,"utf8")),e=Cp(n,Pp(n.kekId));if(e.length===Wr)return e;let t=ye.randomBytes(Wr),r=Ec(t,Gr[0]);return W.writeFileSync(Wn,JSON.stringify(r,null,2),{mode:384}),t}function XS(){Ep();for(let t of Gr){let r=Sc(t);W.existsSync(r)||W.writeFileSync(r,ye.randomBytes(Br),{mode:384})}if(W.existsSync(Wn))return;let n=ye.randomBytes(Wr),e=Ec(n,Gr[0]);W.writeFileSync(Wn,JSON.stringify(e,null,2),{mode:384})}function ZS(n){let e=Dp(),t=ye.randomBytes(Sp),r=ye.createCipheriv(Ur,e,t),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o=r.getAuthTag();return{version:1,algorithm:Ur,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:o.toString("base64"),timeStamp:Date.now()}}function QS(n){try{return Ap(n,Dp())}catch{throw XS(),new Error("Failed to decrypt local ciphertext")}}function eE(n,e){let t=ht.join(e,le.KEY_FILE_NAME),r=JSON.parse(W.readFileSync(t,"utf8")),i=ht.join(e,"keys",`${r.kekId}.bin`),o=W.readFileSync(i);if(o.length!==Br)throw new Error("Invalid external root key");let s=Cp(r,o);if(s.length!==Wr)throw new Error("Invalid external data encryption key");return Ap(n,s)}function tE(n){if(!n||typeof n!="object")return!1;let e=n;return e.algorithm==="aes-256-gcm"&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}function Ke(){return process.env.DEVECO_CLI_AUTH_SOURCE===le.AUTH_SOURCE_DEVECO_CODE}var Ho=class{getLocalTokenFilePath(){let e=process.env.DEVECO_CLI_DATA_DIR||Gn.join(nE(),le.CONFIG_DIR_NAME,le.APP_NAME);return Gn.join(e,le.TOKEN_FILE_NAME)}ensureConfigDir(){let e=Gn.dirname(this.getLocalTokenFilePath());we.existsSync(e)||we.mkdirSync(e,{recursive:!0,mode:448})}async saveJwtToken(e){if(!e)throw new Error("Token is empty");let t=gt.encryptForLocalStorage(e);this.ensureConfigDir();let r=this.getLocalTokenFilePath();we.writeFileSync(r,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){return Ke()?this.loadDevecoCodeToken():this.loadLocalJwtToken()}loadDevecoCodeToken(){if(!Ke())return null;let e=process.env.DEVECO_CODE_AUTH_DIR?.trim();if(!e)return null;try{let t=Gn.join(e,le.TOKEN_FILE_NAME);if(!we.existsSync(t))return null;let r=JSON.parse(we.readFileSync(t,"utf8"));return gt.isEncryptedBlob(r)?gt.decryptForLocalStorageFromDirectory(r,e):null}catch{return null}}async loadLocalJwtToken(){let e=this.getLocalTokenFilePath();try{if(!we.existsSync(e))return null;let t=JSON.parse(we.readFileSync(e,"utf8"));return gt.isEncryptedBlob(t)?gt.decryptForLocalStorage(t):null}catch{return await this.clearToken(),null}}async clearToken(){if(Ke())throw new Error("Current session is managed by DevEco Code. Cannot modify via CLI.");let e=this.getLocalTokenFilePath();try{we.existsSync(e)&&we.unlinkSync(e)}catch(t){throw new Error("Failed to clear token",{cause:t})}}},_e=new Ho;var at={CHINA:"CN",RUSSIA:"RU",SINGAPORE:"SG",EUROPE:"EU"},Vr={CHINA:"zh_CN",RUSSIA:"ru_RU",EUROPE:"de_DE"},Uo={CHINA:"1",SINGAPORE:"5",EUROPE:"7",RUSSIA:"8"},rE={[at.CHINA]:Vr.CHINA,[at.RUSSIA]:Vr.RUSSIA,[at.EUROPE]:Vr.EUROPE,[at.SINGAPORE]:Vr.CHINA},iE={[Uo.CHINA]:at.CHINA,[Uo.SINGAPORE]:at.SINGAPORE,[Uo.EUROPE]:at.EUROPE,[Uo.RUSSIA]:at.RUSSIA};function Rp(n){return rE[n]??Vr.CHINA}function kp(n){return iE[n]??at.CHINA}function Bo(n,e){return n?.toUpperCase()===at.CHINA?We.CN_LOGIN_URL:e}import{exec as oE}from"child_process";import{promisify as sE}from"util";var aE=sE(oE);async function Tp(n){let e=process.platform,t;switch(e){case"win32":t=`start "" "${n}"`;break;case"darwin":t=`open "${n}"`;break;default:t=`xdg-open "${n}"`;break}try{await aE(t)}catch(r){throw new Error("Failed to open browser",{cause:r})}}import cE from"axios";var bc=class{client;constructor(){let e={timeout:br.HTTP_TIMEOUT_MS,headers:{"User-Agent":Ki.USER_AGENT,"accept-language":Ki.ACCEPT_LANGUAGE},transformResponse:[t=>t],proxy:!1};this.client=cE.create(e),this.client.interceptors.response.use(t=>t,t=>{let r=`Network connection failed (${t.code}). Please check your proxy configuration or network settings`;throw new Error(`${t.message}
1254
+ ${r}`)})}async get(e,t){let r=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}async post(e,t){let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}convertResponse(e){return{data:typeof e.data=="string"?e.data:JSON.stringify(e.data),statusCode:e.status,statusText:e.statusText??"",headers:e.headers}}parseJson(e){return JSON.parse(e.data)}async getBinary(e,t){let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout});if(r.status!==200)throw new Error(`HTTP ${r.status}`);return Buffer.from(r.data)}async postAllowFailure(e,t){let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});return this.convertResponse(r)}async deleteAllowFailure(e,t){let r=await this.client.request({method:"DELETE",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});return this.convertResponse(r)}async getBinaryAllowFailure(e,t){let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0}),i=Buffer.from(r.data),o=i.toString("utf8");return{statusCode:r.status,statusText:r.statusText??"",buffer:i,body:o}}},L=new bc;var Pc=class{async checkJwtToken(e,t,r){let i={refresh:"false",jwtToken:e},s=`${t()}/${r}`,a=await L.get(s,{headers:i});if(a.statusCode!==200)throw new Error(`Failed to check jwtToken: ${a.statusCode}`);return L.parseJson(a)}async refreshToken(e,t){let r=await _e.loadJwtToken();return r?this.refreshTokenWithToken(r,e,t):null}async refreshTokenWithToken(e,t,r){try{let i={refresh:"true",jwtToken:e},s=`${t()}/${r}`,a=await L.get(s,{headers:i});if(a.statusCode!==200)return null;let c=L.parseJson(a);return!c.status||!c.userInfo?null:{accessToken:c.userInfo.accessToken,refreshToken:c.userInfo.refreshToken??""}}catch(i){let o=i;return console.error(`Failed to refresh token: ${o.code??""} ${o.message??""}`),null}}},zr=new Pc;function xp(n){try{let e=n.split(".");if(e.length!==3)return null;let r=e[1].replace(/-/g,"+").replace(/_/g,"/"),i=r.padEnd(r.length+(4-r.length%4)%4,"="),o=Buffer.from(i,"base64").toString("utf8");return JSON.parse(o)}catch{return null}}function Lp(n){let e=n.split(".");return e.length===3&&e.every(t=>t.length>0)}var Cc=class{async getJwtToken(e,t,r,i,o){let s=e.split("&")[0],a=kp(t),c=r(),l={tempToken:s,site:a,version:le.API_VERSION,appid:o},p=`${c}/${i}`,g=await L.get(p,{params:l});if(g.statusCode!==200)throw new Error(`Failed to get jwtToken: status=${g.statusCode}`);let w=g.data.trim();if(!Lp(w))throw new Error("Invalid jwtToken format");return w}async getUserInfoFromJwt(e,t){let r=await t(e);if(!r.status||!r.userInfo)throw new Error("Invalid jwtToken");let i=xp(e);if(!i)throw new Error("Invalid jwtToken: failed to parse payload");return{userId:i.userId,userName:i.userName,accessToken:r.userInfo.accessToken,refreshToken:r.userInfo.refreshToken??"",jwtToken:e,countryCode:r.userInfo.nationalCode,language:Rp(r.userInfo.nationalCode),isRealName:String(r.userInfo.realName)==="true"}}},Wo=new Cc;var Go=class{config;server=null;constructor(e){this.config={...Pr,...e}}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}async login(){try{m(`Login started, isDevecoCodeAuth: ${Ke()}`);let e=this.generateClientSecret();this.server=new Fo(e,this.getRegionalizedBaseUrl(),this.config.successRedirectUrl,this.config.failedRedirectUrl),await this.server.start(),m(`Local auth server started on port ${this.server.getPort()}`),await this.openLoginPage(this.server.getPort(),e),m("Browser opened for authentication");let t=await this.server.waitForCallback(this.config.timeout);if(m(`Callback received: siteId=${t.siteId}`),t.siteId!=="1")throw new st("Non-China accounts are not supported.");let r=await Wo.getJwtToken(t.tempToken,t.siteId,()=>this.getRegionalizedBaseUrl(),this.config.tempTokenCheckUrl,this.config.appId);m("JWT token received");let i=await Wo.getUserInfoFromJwt(r,o=>zr.checkJwtToken(o,()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl));return m(`User info received: ${i.userName}`),await _e.saveJwtToken(r),m("JWT token saved"),i}finally{this.server&&(await this.server.stop(),this.server=null)}}async isLoggedIn(){let e=await _e.loadJwtToken();return e?(await zr.checkJwtToken(e,()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl)).status?!0:(Ke()||await _e.clearToken(),!1):!1}async logout(){let e=await _e.loadJwtToken();if(!e)return!1;let r=`${this.getRegionalizedBaseUrl()}/${this.config.logoutUrl}?jwtToken=${e}`;try{await L.post(r,{timeout:5e3})}finally{await _e.clearToken()}return!0}async getUserInfo(){let e=await _e.loadJwtToken();return e?Wo.getUserInfoFromJwt(e,t=>zr.checkJwtToken(t,()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl)):null}generateClientSecret(){return Np.randomUUID().replace(/-/g,"")}getRegionalizedBaseUrl(){return Bo(this.config.countryCode??"",this.config.baseUrl)}async openLoginPage(e,t){let i=`${this.getRegionalizedBaseUrl()}/${this.config.authUrl}?port=${e}&appid=${this.config.appId}&code=${t}`;await Tp(i)}async refreshToken(){return zr.refreshToken(()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl)}},ee=new Go;import Op from"axios";var dE="No JWT in local storage. Run `devecocli auth login` first.";function uE(n){if(n==null||typeof n!="object")return[];let e=n;if(e.ret&&e.ret.code!==0)throw new Error(`team list request failed: code=${e.ret.code}${e.ret.msg?`, msg=${e.ret.msg}`:""}`);return Array.isArray(e.teams)?e.teams.filter(t=>typeof t=="object"&&t!==null).map(t=>({id:String(t.id??""),upSiteId:Number(t.upSiteId??0),name:String(t.name??""),countryCode:String(t.countryCode??""),siteId:Number(t.siteId??0),userType:Number(t.userType??0),lastLoginTime:String(t.lastLoginTime??""),isMirror:t.isMirror===!0})).filter(t=>t.id.length>0):[]}var Vo=class{config;constructor(e){this.config={...Pr,...e}}updateConfig(e){this.config={...this.config,...e}}async listTeams(){let e=await _e.loadJwtToken();if(!e)throw new Error(dE);let{accessToken:t,userId:r}=await this.fetchAccessToken(e);if(!t)throw new Error("Session expired. Run `devecocli auth login` again.");let i=await this.fetchTeamList(t,r??""),o=uE(i);return{userId:r??"",teamList:o}}async fetchTeamList(e,t){let r=this.config.agcTeamListUrl;m(`Executing: GET ${r}`);let i;try{i=await Op.request({method:"GET",url:r,headers:{oauth2Token:e,uid:t,source:"cli",lang:"zh_CN"},timeout:15e3,transformResponse:[o=>o],proxy:!1,validateStatus:()=>!0})}catch(o){throw new Error(`Network error while listing teams: ${o.message}`,{cause:o})}if(i.status===401)throw new Error("AGC rejected the AGC token. Run `devecocli auth login` again.");if(i.status!==200)throw new Error(`Failed to list teams: HTTP ${i.status}`);return typeof i.data=="string"?JSON.parse(i.data):i.data}async fetchAccessToken(e){let r=`${this.getRegionalizedBaseUrl()}/${this.config.jwtTokenCheckUrl}`;m(`Executing: GET ${r} (accessToken refresh)`);let i;try{i=await Op.request({method:"GET",url:r,headers:{refresh:"true",jwtToken:e},timeout:15e3,transformResponse:[a=>a],proxy:!1,validateStatus:()=>!0})}catch(a){throw new Error(`Network error while refreshing accessToken: ${a.message}`,{cause:a})}if(i.status!==200)throw new Error(`Failed to refresh accessToken: HTTP ${i.status}. Run \`devecocli auth login\` again.`);let s=typeof i.data=="string"?JSON.parse(i.data):i.data;if(!s.status)throw new Error("JWT is invalid. Run `devecocli auth login` again.");return{accessToken:s.userInfo?.accessToken,userId:s.userInfo?.userId}}getRegionalizedBaseUrl(){return Bo(this.config.countryCode??"",this.config.baseUrl)}},Mp=new Vo;async function Mt(){return Mp.listTeams()}function fE(n){if(n.length===0)return Fe("No teams found for the current user.");let e=["Id","Name"],t=n.map(s=>[s.id,s.name]),r=e.map((s,a)=>Math.max(s.length,...t.map(c=>c[a].length))),i=s=>s.map((a,c)=>a.padEnd(r[c])).join(" "),o=r.map(s=>"-".repeat(s)).join(" ");return[i(e),o,...t.map(i)].join(`
1255
+ `)}function mE(){return new Promise(n=>{let e=_p.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),n()})})}var qr=new pE("auth").description("Authentication commands (login, logout, status, team)");qr.command("login").description("Log in to your Huawei Developer account").action(async()=>{if(Ke()){console.log(Ic("Login is managed by DevEco Code. Login from DevEco Code instead."));return}try{if(await ee.isLoggedIn()){let t=await ee.getUserInfo();if(t){console.log(Fe(`Already logged in, User Name:${t.userName}`));return}}console.log(Fe("Starting login process...")),console.log(Fe("Press Enter to open browser for login...")),await mE();let e=await ee.login();console.log(Fe(`Login successful. Logged in as ${e.userName}.`))}catch(n){throw n instanceof st?n:new Error("Login failed",{cause:n})}});qr.command("logout").description("Log out of your Huawei Developer account").action(async()=>{if(Ke()){console.log(Ic("Login is managed by DevEco Code. Log out from DevEco Code instead."));return}try{let n=await ee.logout();console.log(n?Fe("Logout successful"):Fe("Already logged out."))}catch(n){throw new Error("Logout failed",{cause:n})}});qr.command("status").description("Show the currently logged-in user").action(async()=>{try{if(!await ee.isLoggedIn()){console.log(Fe("Not logged in"));return}let e=await ee.getUserInfo();if(!e){console.log(Fe("Not logged in"));return}console.log(Fe(`Current user: ${e.userName}`))}catch{console.log(Fe("Not logged in"))}});var hE=qr.command("team").description("Team-related commands");hE.command("list").description("List team accounts the current user has joined").action(async()=>{try{if(!await ee.isLoggedIn()){Ke()?console.log(Ic("Not logged in. Please login via DevEco Code first.")):console.log(Fe("Please run `devecocli auth login` first."));return}let e=await Mt();console.log(fE(e.teamList))}catch(n){throw new Error("Failed to list teams",{cause:n})}});var Fp=qr;import{Command as TE}from"commander";import{green as xE,red as Zr,cyan as af,yellow as cf,dim as lf}from"colorette";import LE from"p-limit";import gE from"ora";var Xe=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=gE(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 jp from"fs";import*as $p from"path";import{homedir as yE}from"os";var Hp=["DevEco"];async function zo(){let n=await L.get(Ge.TAGS_API_URL),t=qo(n,"Tags API").data.skill.filter(r=>r.name==="HMOS");if(t.length===0)throw new Error("No HMOS tag found.");return t.map(r=>r.id)}async function wE(n){let e=[],t=Ge.DEFAULT_PAGE_SIZE,r=1;for(;;){let i=await L.post(Ge.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:r,pageSize:t,tagIds:[n]}}),o=qo(i,"Skills API");if(e.push(...o.data.list),o.data.list.length<t)break;r++}return e}async function Ac(n){let e=new Map,t=n.map(i=>wE(i)),r=await Promise.all(t);for(let i of r)for(let o of i)e.has(o.id)||e.set(o.id,o);return Array.from(e.values()).filter(i=>i.tags?.every(o=>!Hp.includes(o.name)))}async function vE(n,e){let t=await L.post(Ge.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:Ge.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return qo(t,"Skills API").data.list}async function Dc(n,e){let t=new Map,r=e.map(o=>vE(n,o)),i=await Promise.all(r);for(let o of i)for(let s of o)t.has(s.id)||t.set(s.id,s);return Array.from(t.values()).filter(o=>o.tags?.every(s=>!Hp.includes(s.name)))}function Up(n){let e=[];for(let[,t]of Object.entries(Ve)){let r=$p.join(yE(),t.path,n);jp.existsSync(r)&&e.push(t.displayName)}return e.sort()}function qo(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=L.parseJson(n);if(t.code!==Ge.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Bp(n){let e=`${Ge.SKILL_API_BASE}/${n}/checksum`,t=await L.get(e);return qo(t,"Checksum API").data}import SE from"adm-zip";import EE from"crypto";import Gp from"fs";import z from"path";import{fileURLToPath as bE}from"url";import{homedir as Vp}from"os";import{red as PE}from"colorette";var yt=Gp.promises;function Rc(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}function Wp(n,e){let t=z.resolve(e),r=z.resolve(n),i=z.relative(r,t);if(i.startsWith("..")||z.isAbsolute(i))throw new Error(`Path traversal detected: ${e}.`)}function kc(n){return z.isAbsolute(n)?n:z.resolve(process.cwd(),n)}function CE(n){return EE.createHash("sha256").update(n).digest("hex")}async function IE(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=CE(n),i=e.sha256.toLowerCase();if(r!==i)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function zp(n){let e=`${Ge.SKILL_API_BASE}/${n}/install?format=zip`,t=await L.getBinary(e),r=await Bp(n);return await IE(t,r),t}async function AE(n,e,t){Rc(t);let r=new SE(n),i=r.getEntries();try{await yt.stat(e)}catch{await yt.mkdir(e,{recursive:!0})}let o=z.join(e,t);Wp(e,o);for(let s of i){let a=z.join(o,s.entryName);Wp(o,a)}r.extractAllTo(o,!0)}async function Tc(n){let e=Ve[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(Ve).join(", ")}`);let t=z.join(Vp(),e.path.replace("/skills",""));try{return await yt.access(t),!0}catch{return!1}}function xc(n){let e=Ve[n];return z.join(Vp(),e.path)}function DE(n){let e=Ve[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(Ve).join(", ")}`);return e}function Lc(n,e){let t=DE(e),r="projectPath"in t?t.projectPath:z.join("."+e,"skills");return z.join(n,r)}async function RE(n,e,t){Rc(e);let r=z.join(n,e);try{if(await yt.access(r),t)await yt.rm(r,{recursive:!0,force:!0});else return console.log(`Skill ${e} exists in ${n}.`),{skillDir:r,shouldSkip:!0}}catch{}return{skillDir:r,shouldSkip:!1}}async function Nc(n,e,t){await AE(n,e,t),console.log(`Skill ${t} installed to ${z.join(e,t)}.`)}async function Oc(n,e,t){let r=z.join(e,t);await yt.mkdir(r,{recursive:!0});let i=z.join(r,z.basename(n));await yt.copyFile(n,i),console.log(`Skill ${t} installed to ${r}.`)}function qp(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(PE(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function Vn(n,e,t,r){try{let i=await e(),{shouldSkip:o}=await RE(i,n,r);return o?{success:!0,skipped:!0}:(await t(i),{success:!0})}catch(i){return qp(n,i,"Installation failed")}}async function Mc(n,e){try{Rc(n);let t=await e(),r=z.join(t,n);try{await yt.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await yt.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return qp(n,t,"Removal failed")}}async function Yp(n,e,t,r=!1){return Vn(n,()=>xc(e),i=>Nc(t,i,n),r)}async function Jp(n,e,t,r=!1){return Vn(n,()=>t,i=>Nc(e,i,n),r)}async function Kp(n,e,t,r,i=!1){return Vn(n,()=>Lc(t,r),o=>Nc(e,o,n),i)}async function Xp(n,e,t,r=!1){return Vn(n,()=>xc(t),i=>Oc(e,i,n),r)}async function Zp(n,e,t,r,i=!1){return Vn(n,()=>Lc(t,r),o=>Oc(e,o,n),i)}async function Qp(n,e,t,r=!1){return Vn(n,()=>t,i=>Oc(e,i,n),r)}async function ef(n,e){return Mc(n,()=>xc(e))}async function tf(n,e){return Mc(n,()=>e)}async function nf(n,e,t){return Mc(n,()=>Lc(e,t))}function rf(){let e=z.dirname(bE(import.meta.url));for(;;){let t=z.join(e,"SKILL.md");if(Gp.existsSync(t))return t;let r=z.dirname(e);if(r===e)break;e=r}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import of from"fs";import{cyan as kE}from"colorette";async function Yr(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await Tc(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function Jr(){let n=[];for(let e of Object.keys(Ve))await Tc(e)&&n.push(e);return n}function Kr(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(kE("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function _t(n,e,t){if(!of.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!of.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function Xr(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?kc(n):void 0,resolvedProject:e?kc(e):void 0}}async function Yo(n,e,t){let r=[],i=[],o;if(e?o=e:t&&n.agent?i=(await Yr(n.agent)).map(a=>({project:t,agent:a})):t?i=(await Jr()).map(a=>({project:t,agent:a})):n.agent?r=await Yr(n.agent):r=await Jr(),!o&&r.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:r,projectAgents:i,customPath:o}}async function NE(n){let e=await zo();if(n.all)return(await Ac(e)).map(r=>r.enName);{let r=(await Dc(n.skill,e)).find(i=>i.enName===n.skill);if(!r)throw new Error(`Skill "${n.skill}" not found`);return[r.enName]}}async function OE(n,e,t,r){let i=[];if(t.customPath){let o=await Jp(n,e,t.customPath,r);return i.push(o),i}for(let o of t.agents){let s=await Yp(n,o,e,r);i.push(s)}for(let{project:o,agent:s}of t.projectAgents){let a=await Kp(n,e,o,s,r);i.push(a)}return i}function ME(n){if(n.all&&n.skill)throw new Error("`--all` and `--skill` cannot be specified together.");if(!n.all&&!n.skill)throw new Error("Must specify `--all` or `--skill`");let{resolvedPath:e,resolvedProject:t}=Xr(n.path,n.project,n.agent);return t&&_t(t,"Project directory",n.force),e&&_t(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}async function _E(n,e,t){let r=await Yo(n,e,t);return{skillNames:await NE(n),targets:r}}async function FE(n,e,t,r){let i=[],o=n.length,s=LE(5),a=n.map(c=>s(()=>jE(c)));for(let c=0;c<n.length;c++){let l=n[c],p=o>1?` (${c+1}/${o})`:"";r.start(`Installing ${l}${p}...`);let g=await a[c];if(!g.success){r.fail(),console.log(Zr(`${l}: Download failed - ${g.error}`)),i.push({success:!1});continue}r.stop();let w=await OE(l,g.buffer,e,t);i.push(...w)}return i}async function jE(n){try{let e=await zp(n);return{name:n,buffer:e,success:!0}}catch(e){let t=e instanceof Error?e.message:"unknown error";return{name:n,error:t,success:!1}}}async function $E(n){let e=new Xe;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=ME(n),{skillNames:i,targets:o}=await _E(n,t,r),s=await FE(i,o,n.force||!1,e);e.stop(),Kr(s)}catch(t){throw e.stop(),t}}function HE(n){let{resolvedPath:e,resolvedProject:t}=Xr(n.path,n.project,n.agent);return t&&_t(t,"Project directory"),e&&_t(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function UE(n,e){let t=new Xe;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:i}=HE(e);t.stop();let o=await BE(e,n,r,i);t.stop(),Kr(o)}catch(r){throw t.stop(),r}}function sf(n,e=""){if(n.length===0)throw new Error(`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function Jo(n,e){let t=[];for(let r of e){let i=r.type==="agent"?await ef(n,r.agent):await nf(n,r.project,r.agent);t.push(i)}return t}async function BE(n,e,t,r){if(t)return[await tf(e,t)];if(r&&n.agent){let a=(await Yr(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return Jo(e,a)}if(r){let s=await Jr();sf(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return Jo(e,a)}if(n.agent){let a=(await Yr(n.agent)).map(c=>({type:"agent",agent:c}));return Jo(e,a)}let i=await Jr();sf(i,"or use --path for a custom location.");let o=i.map(s=>({type:"agent",agent:s}));return Jo(e,o)}var Qr=new TE("skills").description("Manage HarmonyOS skills");Qr.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async n=>{let e=new Xe;try{e.start("Fetching skills...");let t=await zo(),r=await Ac(t);if(r.length===0){e.stop(),console.log(cf("No skills available."));return}e.succeed(`Fetched ${r.length} skills`);for(let i of r)if(n.long){console.log(af(i.enName)),console.log(lf(i.description));let o=Up(i.enName);o.length>0&&console.log(xE(`Installed for: ${o.join(", ")}`)),console.log()}else console.log(i.enName)}catch(t){e.stop(),console.error(Zr(t.message)),process.exit(1)}});Qr.command("find <keyword>").description("Search skills by keyword").action(async n=>{let e=new Xe;try{e.start("Searching skills...");let t=await zo(),r=await Dc(n,t);if(r.length===0){console.log(cf(`No skills found matching '${n}'.`)),e.stop();return}e.succeed(`Found ${r.length} skills.`);for(let i of r)console.log(af(i.enName)),console.log(lf(i.description)),console.log()}catch(t){e.stop(),console.error(Zr(t.message)),process.exit(1)}});Qr.command("add").description("Install skills to AI agents").option("--all","Install all available skills").option("--agent <agents>","Target agents, comma-separated; Omit to install to all available agents").option("--skill <skill-name>","Name of the skill to install").option("-f, --force","Overwrite an existing skill installation").option("--project <path>","Project root directory for skill installation").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").action(async n=>{try{await $E(n)}catch(e){console.error(Zr(e.message)),process.exit(1)}});Qr.command("remove").description("Remove an installed skill from AI agents").requiredOption("--skill <skill-name>","Name of the skill to remove").option("--agent <agents>","Target agents, comma-separated.Omit to remove from all available agents").option("--project <path>","Project root directory for skill removal").option("--path <path>","Path for skill removal").action(async n=>{try{await UE(n.skill,n)}catch(e){console.error(Zr(e.message)),process.exit(1)}});var df=Qr;import{Command as GE,InvalidArgumentError as pf}from"commander";import{cyan as Ko}from"colorette";function fn(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=Ln(t);return r==="transient"?new Error(`${e}: Device communication channel unavailable. Retry in a few seconds.`):r==="fatal"?new Error(`${e}: ${t.trim()}`):null}var _c=[800,1500,2500];function WE(n){return new Promise(e=>setTimeout(e,n))}var zn=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=Z.from(e)}createFollowLineHandler(){return(e,t)=>{if(t==="stderr"){for(let r of e)console.error(r);return}for(let r of e)console.log(r)}}findDeviceByArg(e,t){return e.find(r=>r.serial===t||r.name===t)}formatConnectedDeviceList(e){return e.map(t=>` - ${t.name} (${t.serial})`).join(`
1256
+ `)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let i=t[0];return m(Ko(`Using device serial: ${i}`)),i}if(e&&t.includes(e))return m(Ko(`Using device serial: ${e}`)),e;let r=await this.loadConnectedDevicesByName();if(e){let i=this.findDeviceByArg(r,e);if(i)return m(Ko(`Using device: ${i.name} (${i.serial})`)),i.serial;let o=this.formatConnectedDeviceList(r);throw new Error(`Device '${e}' not found.
1223
1257
  Available devices:
1224
- ${o}`)}if(n.length===1){let i=n[0];return v(dn(`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){v(`Retrieving PID for bundle ${n}`),D.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 v(`Found PID for ${n}: ${a}`),a}return v(`No PID found for bundle: ${n}`),null}async resizeHilogBuffer(e,t,n){v(`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&&(D.assertHilogToken(e.tag,"tag"),n.push("-T",e.tag)),e.level&&(D.assertHilogLevel(e.level),n.push("-L",e.level)),e.domain&&(D.assertHilogToken(e.domain,"domain"),n.push("-D",e.domain)),t&&n.push("-P",t),e.keyword&&(D.assertHilogKeyword(e.keyword),n.push("-e",D.quotePosixShellArg(e.keyword))),n.join(" ")}async followHilog(e,t,n,i,o){let a=await Ti(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+$r.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(qe(d)!=="transient"||c>=s-1)return a;v(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${$r[c]}ms`),await zl($r[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=D.filterLogsByRelativeWindow(a.stdout||a.stderr,n.fromSeconds,n.toSeconds);d=D.getLastLines(d,n.tail),d.trim()&&console.log(d)}async getHilogOnce(e,t,n,i){let[o,s]=this.buildHilogCommand(e,t,n,i);v(`Ready to run hilog command: ${o} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(o,s,()=>{},g=>{v(`Callback triggered when an error occurs during a single hilog streaming read: ${g.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,p=D.filterLogsByRelativeWindow(d,n.fromSeconds,n.toSeconds);return p=D.getLastLines(p,n.tail),p}async runHilogFollow(e,t,n,i){await this.printTailSnapshotIfNeeded(e,t,n,i);let[o,s]=this.buildHilogCommand(e,t,n,i);v(`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){v(`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 p=c.split("-").pop()||"";return(d.split("-").pop()||"").localeCompare(p)})[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"];v(`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 v(`Crash logs list output:
1225
- ${o.stdout}`),o.stdout.split(`
1226
- `).map(c=>c.trim()).filter(c=>c.length>0).filter(c=>{try{return D.assertCrashFilename(c),!0}catch{return!1}}).filter(c=>n?c.toLowerCase().includes(n.toLowerCase()):!0)}async fetchCrashLogContent(e,t,n){v(`Fetching latest crash log file: ${n}`);let i=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${n}`];v(`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 Yo}from"colorette";import Vl from"ora";function Gl(r){try{return D.parsePositiveInteger(r,"tail")}catch{throw new Go("`tail` must be a positive integer.")}}function Vo(r,e){try{return D.parseDurationToSeconds(r,e)}catch{throw new Go(`${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 Yl(r){if(r.to&&r.follow)throw new Error("`--to` cannot be used with `--follow`.");D.assertRelativeTimeRange(r.from,r.to)}async function Jl(r,e,t,n,i){return t.crash?await r.getCrashLog(e,t.bundleName):await r.getHilog(e,{level:t.level,bundleName:t.bundleName,keyword:t.keyword,isFollow:!!t.follow,tail:t.tail,fromSeconds:n,toSeconds:i})}function Kl(r,e,t,n){let i=D.filterLogsByRelativeWindow(r,t,n);return e.tail?D.getLastLines(i,e.tail):i}var Zl=new ql("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",Gl).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",r=>Vo(r,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",r=>Vo(r,"to")).option("--follow","Follow the log stream in real-time.").action(async r=>{await Xl(r)});async function Xl(r){let e=Vl({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),Yl(r);let n=r.from,i=r.to,o=await O.new(),s=new un(o),a=await s.selectDevice(r.device);a||(t(),process.exit(1)),v(_r(`deviceId: ${a}`)),v(_r(`type: ${r.crash?"Crash logs":"Common logs"}`)),v(_r("Obtaining logs ...")),e.text="Fetching logs\u2026",r.follow&&t();let c=await Jl(s,a,r,n,i);t(),r.crash&&c&&(c=Kl(c,r,n,i)),c&&console.log(c)}catch(n){t(),console.error(Yo(n.message)),process.exit(1)}}var Jo=Zl;import Ot from"path";import me from"fs";import Ur from"process";import rs from"os";import{Command as dd}from"commander";import{green as Qo,red as Wr,cyan as ud,yellow as es}from"colorette";import $ from"fs-extra";import x from"path";import*as Ko from"os";import{fileURLToPath as Ql}from"url";var ed={17:{sdkVersion:"5.0.5(17)",modelVersion:"5.0.5"},18:{sdkVersion:"5.1.0(18)",modelVersion:"5.1.0"},19:{sdkVersion:"5.1.1(19)",modelVersion:"5.1.1"},20:{sdkVersion:"6.0.0(20)",modelVersion:"6.0.0"},21:{sdkVersion:"6.0.1(21)",modelVersion:"6.0.1"},22:{sdkVersion:"6.0.2(22)",modelVersion:"6.0.2"},23:{sdkVersion:"6.1.0(23)",modelVersion:"6.1.0"},24:{sdkVersion:"6.1.1(24)",modelVersion:"6.1.1"}},td=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function nd(){let r=import.meta.url,e=Ql(r);if(e.includes("dist")){let o=x.dirname(e),s=x.dirname(o);return x.join(s,"templates","application")}let t=x.dirname(e),n=x.dirname(t),i=x.dirname(n);return x.join(i,"templates","application")}function Zo(r,e){$.mkdirSync(e,{recursive:!0});for(let t of $.readdirSync(r,{withFileTypes:!0})){let n=x.join(r,t.name),i=x.join(e,t.name);if(t.isDirectory()){Zo(n,i);continue}$.existsSync(i)||($.mkdirSync(x.dirname(i),{recursive:!0}),$.copyFileSync(n,i))}}function Mt(r,e){let t=$.readFileSync(r,"utf-8"),n=t;for(let[i,o]of e)n=n.replaceAll(i,o);n!==t&&$.writeFileSync(r,n,"utf-8")}function rd(r,e){if(e===22)return;let t=ed[e];t&&(Mt(x.join(r,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),Mt(x.join(r,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),Mt(x.join(r,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function id(r){return td.filter(t=>!$.existsSync(x.join(r,t))).length===0}function od(){return Buffer.from([137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,1,0,0,0,1,8,2,0,0,0,144,119,83,222,0,0,0,12,73,68,65,84,8,215,99,248,255,255,255,0,5,254,2,254,0,0,0,0,73,69,78,68,174,66,96,130])}function sd(r){return Ko.platform()==="darwin"?x.join(r,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):x.join(r,"plugins","codegenie-plugin","previewProjectTemplate")}function ad(r,e){let t=sd(e);if(!$.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=x.join(t,i),a=x.join(r,o);$.existsSync(s)&&($.mkdirSync(x.dirname(a),{recursive:!0}),$.copyFileSync(s,a))}return!0}function cd(r){let e=od(),t=["AppScope/resources/base/media/background.png","AppScope/resources/base/media/foreground.png","entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/startIcon.png"];for(let n of t){let i=x.join(r,n);$.mkdirSync(x.dirname(i),{recursive:!0}),$.writeFileSync(i,e)}}function ld(r,e){e&&ad(r,e)||cd(r)}function Xo(r,e,t,n,i){let o=nd();if(!$.existsSync(o))throw new Error(`Template directory not found: ${o}`);$.mkdirSync(r,{recursive:!0}),Zo(o,r),ld(r,i),Mt(x.join(r,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),Mt(x.join(r,"AppScope","app.json5"),[["com.example.myapplication",t]]),rd(r,n);let s=id(r);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:r,appName:e,bundleName:t,apiLevel:n,verified:s}}function pd(r){if(r.length<1||r.length>200)throw new Error(`App name length must be 1-200 characters. Current: ${r.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(r))throw new Error("Application name must start with a letter (a-z, A-Z) and contain only letters, digits, and underscores")}function hd(r){if(r.length<7||r.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${r.length}`);if(r.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example").');let e=r.split(".");if(e.length<3)throw new Error("Bundle name must contain at least 3 dot-separated segments.");let t=/^[a-zA-Z0-9_]+$/;for(let n=0;n<e.length;n++){let i=e[n];if(!t.test(i))throw new Error(`Segment "${i}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(n===0){if(!/^[a-zA-Z]/.test(i))throw new Error(`First segment "${i}" must start with a letter (a-z, A-Z).`)}else if(!/^[a-zA-Z0-9]/.test(i))throw new Error(`Segment "${i}" must start with a letter or digit.`);if(!/[a-zA-Z0-9]$/.test(i))throw new Error(`Segment "${i}" must end with a letter or digit.`)}}function 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 fd(r){let e=r,t=Ot.parse(r).root;for(;e!==t;){if(me.existsSync(e))return e;e=Ot.dirname(e)}return me.existsSync(t)?t:null}function ns(r){let e=fd(r);if(!e)throw new Error(`No existing parent directory found for '${r}'. Cannot create project directory.`);try{me.accessSync(e,me.constants.W_OK)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}let t=Ot.join(e,`.deveco_write_test_${Date.now()}`);try{me.writeFileSync(t,"test"),me.unlinkSync(t)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}}function md(r){return`com.example.${r.toLowerCase()}`}function gd(r,e){if(e){let i=is(e),o=Ot.resolve(i);if(me.existsSync(o)){if(me.readdirSync(o).length>0)throw new Error(`Directory '${o}' is not empty. Cannot create project here.`)}else ns(o);return o}let t=Ur.cwd(),n=Ot.join(t,r);if(me.existsSync(n))throw new Error(`Directory '${n}' already exists. Cannot create project here.`);return ns(n),n}function yd(r,e){let t=e?.getMaxApiLevel(),n=23;if(r.apiLevel){let i=Number(r.apiLevel);if(!Number.isInteger(i)||i<17)throw new Error(`Invalid API version ${r.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(i>t)throw new Error(`Invalid API version ${r.apiLevel}. Your SDK supports API version 17-${t}`)}else if(i>n)throw new Error(`Invalid API version ${r.apiLevel}. Without DevEco Studio, supported range is API version 17-${n}`);return i}return t!==void 0?t:23}async function vd(){try{return await O.new()}catch(r){console.error(es(`DevEco Studio not found: ${r.message}`)),console.log(es("Use placeholder API level instead."));return}}var wd=new dd("create").description("Scaffold a new HarmonyOS application project").option("--project-path <path>","Project directory path (default: ./<app-name>)").option("--app-name <name>","Application name").option("--bundle-name <bundle>","Bundle name (auto-derived as com.example.<app-name> if omitted)").option("--api-level <level>","API level (auto-detected from SDK if omitted; minimum: 17)").action(async r=>{try{r.appName||(console.error(Wr("Error: --app-name is required")),Ur.exit(1));let e=r.appName;pd(e);let t=r.bundleName||md(e);hd(t),r.projectPath&&ts(r.projectPath);let n=gd(e,r.projectPath);ts(n),console.log(ud("Initializing project...")),console.log(`Project path: ${n}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let i=await vd(),o=yd(r,i);console.log(`API level: ${o}`);let s=i?.devecoStudioPath,a=Xo(n,e,t,o,s);console.log(`
1227
- `+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(Wr(`
1228
- Failed to create project.`)),console.error(Wr(t.message)),Ur.exit(1)}}),os=wd;import{Command as Id}from"commander";import{red as Ad,cyan as ps}from"colorette";import bd from"fs";import pn from"path";import{cyan as Sd}from"colorette";import*as hn from"smol-toml";var et=bd.promises;async function Pd(r){try{let e=await et.readFile(r,"utf8");return e.trim()===""?{}:JSON.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read configuration file ${r}: ${e.message}`,{cause:e})}}async function Ed(r){try{let e=await et.readFile(r,"utf8");return e.trim()===""?{}:hn.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read TOML config file ${r}: ${e.message}`,{cause:e})}}async function Cd(r,e){let t=pn.dirname(r);await et.mkdir(t,{recursive:!0});let n=JSON.stringify(e,null,2);await et.writeFile(r,n,"utf8")}async function Dd(r,e){let t=pn.dirname(r);await et.mkdir(t,{recursive:!0});let n=hn.stringify(e);await et.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"?Ed(e):Pd(e)}async function ls(r,e,t){return r.format==="codex"?Dd(e,t):Cd(e,t)}async function ds(r,e,t=!1){let n=De[r];if(!n)return{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys(De).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,ue)&&!t)return console.log(`MCP server ${ue} already configured in ${n.globalConfigPath}.`),{success:!0,skipped:!0,configPath:n.globalConfigPath,agentName:r,installType:"global"};let o=on(n,void 0);return as(i,n.mcpServersKey,ue,o,t),await ls(n,n.globalConfigPath,i),console.log(`MCP server ${ue} 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 Br(r,e,t=!1){let n=De[r];if(!n)return{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys(De).join(", ")}`};let i=pn.isAbsolute(n.projectConfigPath)?n.projectConfigPath:pn.join(e,n.projectConfigPath);try{let o=await cs(n,i);if(ss(o,n.mcpServersKey,ue)&&!t)return console.log(`MCP server ${ue} already configured in ${i}.`),{success:!0,skipped:!0,configPath:i,agentName:r,installType:"project"};let s=on(n,e);return as(o,n.mcpServersKey,ue,s,t),await ls(n,i,o),console.log(`MCP server ${ue} 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(Sd("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${n}`);for(let i of r)!i.success&&i.error&&console.error(` - ${i.agentName??"unknown"}: ${i.error}`);n>0&&(process.exitCode=1)}var zr="deveco-cli";async function kd(r,e,t){if(r.customPath)return[await No(zr,e,r.customPath,t.force)];let n=[...r.projectAgents.map(({project:s,agent:a})=>()=>Lo(zr,e,s,a,t.force)),...r.agents.map(s=>()=>Oo(zr,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 Td(r,e,t){let n=[];for(let{project:i,agent:o}of r.projectAgents){let s=await Br(o,i,t);n.push(s)}for(let i of r.agents){let o=await Br(i,e,t);n.push(o)}return n}async function Rd(r,e){let t=[];for(let n of r){if(!De[n])continue;let o=await ds(n,process.cwd(),e);t.push(o)}return t}async function xd(r,e,t){if(t.agent&&t.agent.split(",").map(d=>d.trim()).includes("qoder"))throw new Error("Qoder does not support MCP configuration via DevEco CLI. Use other supported agents instead.");let n=t.force??!1,i=r.projectAgents.filter(c=>c.agent!=="qoder"),o=r.agents.filter(c=>c!=="qoder"),s={...r,projectAgents:i,agents:o},a=e?await Td(s,e,n):await Rd(s.agents,n);a.length>0&&(console.log(ps("MCP Configuration:")),us(a))}async function Md(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}=Tt(r.path,r.project,r.agent);t&&Ae(t,"Project directory",r.force),e&&Ae(e,"Directory",r.force);let n=await cn(r,e,t);if(r.mcp){await xd(n,t,r);return}let i=$o(),o=await kd(n,i,r);console.log(),o.length>0&&(console.log(ps("Skill Installation:")),kt(o))}var Od=new Id("init").description("Install the deveco-cli skill or configure the deveco-mcp server into AI agents").option("--agent <agents>","Target agents, comma-separated; installs to all available agents if omitted").option("--project <path>","Project root directory for skill or MCP configuration").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").option("--skill","Install the deveco-cli skill only (same as default behavior; explicit for symmetry with --mcp)").option("--mcp","Configure the deveco-mcp server (syntax checking for .ets and C/C++) only; no skill installation").option("-f, --force","Overwrite existing skill/MCP configuration").action(async r=>{try{await Md(r)}catch(e){console.error(Ad(e.message)),process.exit(1)}}),hs=Od;import{Command as lp}from"commander";import{McpServer as Xu}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Qu}from"@modelcontextprotocol/sdk/server/stdio.js";import*as vt from"path";import{z as W}from"zod";var fn=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 qr(){return new fn}import*as K from"fs";import*as _ from"path";import{z as ri}from"zod";import A from"fs";import*as mn from"os";import*as S from"path";import Ld from"json5";var Vr="Huawei";var Nd=3,ys=3,fs="DevEco Studio",vs={DevEcoStudio:"deveco_studio"};function Gr(r){if(!A.existsSync(r)||!A.statSync(r).isDirectory())return!1;let e=A.existsSync(S.join(r,"build-profile.json5")),t=A.existsSync(S.join(r,"hvigorfile.js"))||A.existsSync(S.join(r,"hvigorfile.ts"));if(!e||!t)return!1;try{let n=A.readFileSync(S.join(r,"build-profile.json5"),"utf-8");return Ld.parse(n).app!==void 0}catch{return!1}}function ws(r,e,t){if(e>=t)return null;let n=Hd(r),i=Fd(n);if(i)return i;for(let o of n){let s=ws(o,e+1,t);if(s)return s}return null}function Hd(r){try{let e=A.readdirSync(r,{withFileTypes:!0}),t=[];for(let n of e)n.isDirectory()&&t.push(S.join(r,n.name));return t}catch{return[]}}function Fd(r){for(let e of r)if(Gr(e))return e;return null}function ge(r){if(!r||r.trim()==="")return null;let e=S.resolve(r),t;try{t=A.realpathSync(e)}catch{t=e}if(!A.existsSync(t))return null;if(Gr(t))return t;let n=t;for(let i=1;i<=3;i++){let o=S.dirname(n);if(o===n)break;if(Gr(o))return o;n=o}if(A.statSync(t).isDirectory()){let i=ws(t,0,Nd);if(i)return i}return null}function gn(r){if(process.platform==="linux")return null;let e=r??ye();if(!e)return null;let t;if(process.platform==="win32")t=S.join(e,"plugins","openharmony");else if(process.platform==="darwin")t=S.join(e,"contents","plugins","openharmony");else return null;let n=S.join(t,"ace-server","out","index.js");return A.existsSync(n)?t:null}var jd=["sdk","default","openharmony","native","llvm","bin","clangd"],Yr=[".idea",".deveco","cxx","compile_commands.json"];function $d(r){return process.platform==="darwin"&&r.endsWith(".app")?S.join(r,"Contents"):r}function ms(r){let e=new Set,t=[r,$d(r)];for(let n of t){let i=S.join(n,...jd);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 ms(t.trim()))if(e.push(i),A.existsSync(i))return i}let n=r??ye();if(n){for(let i of ms(n))if(e.push(i),A.existsSync(i))return i}return null}function yn(r){return S.join(r,...Yr)}function ye(){if(process.platform==="win32"){let r=[S.join("C:\\Program Files",Vr,fs),S.join("C:\\Program Files (x86)",Vr,fs)];return gs(r)}if(process.platform==="darwin"){let r=["/Applications/DevEco Studio.app",S.join(process.env.HOME??"","Applications","DevEco Studio.app")];return gs(r)}return null}function gs(r){for(let e of r)if(A.existsSync(e))return e;return null}function ee(r){return process.platform==="darwin"?S.join(r,"Contents"):r}function _d(r){if(!r||!A.existsSync(r)||!Ss(r))return!1;let e=ee(r);return[S.join(e,"plugins","openharmony"),S.join(e,"sdk"),S.join(e,"tools")].some(n=>A.existsSync(n))}function Ss(r){try{return A.statSync(r).isDirectory()}catch{return!1}}function Jr(r,e){return!r||!A.existsSync(r)?!1:e===vs.DevEcoStudio?_d(r):!1}function vn(r,e=vs.DevEcoStudio){if(!r)return"";if(Jr(r,e))return r;let t=Wd(r,e);if(t)return t;let n=Ud(r,e);return n||r}function Wd(r,e){let t=r;for(let n=0;n<ys;n++){let i=S.dirname(t);if(!i||i===t)break;if(Jr(i,e))return i;t=i}return null}function Ud(r,e){if(!A.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>=ys)continue;let o=Bd(n,i,e,t);if(o)return o}return null}function Bd(r,e,t,n){let i;try{i=A.readdirSync(r,{withFileTypes:!0})}catch{return null}for(let o of i){if(!o.isDirectory())continue;let s=S.join(r,o.name);if(Jr(s,t))return s;n.push({p:s,depth:e+1})}return null}function Ps(r){return new Promise(e=>setTimeout(e,r))}var zd=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function wn(r){let e=S.extname(r).replace(/^\./,"").toLowerCase();return e.length>0&&zd.has(e)}function Es(r){return S.extname(r).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function te(r){let e=r.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function qd(r){return te(r)}function $e(r){let e=qd(r);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function tt(){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA??S.join(mn.homedir(),"AppData","Local");return S.join(r,"devecocli-mcp-server","logs")}return process.platform==="darwin"?S.join(mn.homedir(),"Library","Logs","devecocli-mcp-server"):S.join(mn.homedir(),".local","share","devecocli-mcp-server","logs")}function Cs(r,e){let t=Vd(e),n=Gd(t,r);if(n!==null)return n;let i=Date.now(),s=`${r.replace(/:/g,"\\:")}=${i}`,a=Yd(t,r,s);return Jd(e,a),i}function Vd(r){let e;try{e=A.readFileSync(r,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function Gd(r,e){for(let t of r){let n=t.indexOf("=");if(n<=0||t.slice(0,n).replace(/\\:/g,":")!==e)continue;let o=parseInt(t.slice(n+1),10);return Number.isFinite(o)&&o>0?o:null}return null}function Yd(r,e,t){let n=!1,i=r.map(o=>{if(n)return o;let s=o.indexOf("=");return s<=0?o:o.slice(0,s).replace(/\\:/g,":")===e?(n=!0,t):o});return n||i.push(t),i}function Jd(r,e){try{A.mkdirSync(S.dirname(r),{recursive:!0})}catch{}try{A.writeFileSync(r,e.join(`
1229
- `)+`
1230
- `,"utf8")}catch{}}function Kr(r,e,t="[Cleanup]"){try{let n=S.dirname(r);if(!A.existsSync(n))return;let i=Date.now();for(let o of A.readdirSync(n,{withFileTypes:!0}))o.isDirectory()&&Kd(S.join(n,o.name),i,e,t)}catch{}}function Kd(r,e,t,n){try{let{mtimeMs:i}=A.statSync(r);if(e-i<=t)return;A.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 bn(r){let e=r.replace(/sdk\/?$/i,"tools"),t=process.platform==="win32"?"node.exe":"node",n=S.join(e,"node",t);return A.existsSync(n)||process.platform!=="win32"&&(n=S.join(e,"node","bin","node"),A.existsSync(n))?n:process.execPath??"node"}import*as T from"fs";import*as Pn from"path";var Ds="mcp-server.log",Zd="mcp-server",Xd={maxSize:10*1024*1024,maxFiles:4},Zr=class r{fd=null;logDir=null;currentLogFile=null;mode;rotationOptions;currentFileSize=0;currentDate="";isRotating=!1;minLevel;static LEVEL_ORDER={debug:0,info:1,warn:2,error:3};constructor(e,t){this.rotationOptions={...Xd,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=tt(),this.currentLogFile=Pn.join(this.logDir,Ds),T.existsSync(this.logDir)||T.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 Pn.join(this.logDir,`${Zd}-${e}.log.${t}`)}fileExists(e){try{return T.accessSync(e,T.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=T.readdirSync(this.logDir),t=[];for(let i of e)if(i===Ds||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=Pn.join(this.logDir,i),s=T.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{T.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)&&T.unlinkSync(t);for(let i=this.rotationOptions.maxFiles-1;i>=1;i--){let o=this.getRotatedFileName(e,i),s=this.getRotatedFileName(e,i+1);this.fileExists(o)&&T.renameSync(o,s)}let n=this.getRotatedFileName(e,1);T.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=T.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=T.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{T.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...n){if(this.mode==="silent"||r.LEVEL_ORDER[e]<r.LEVEL_ORDER[this.minLevel])return;let i=n.map(c=>typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),o=i?`${t} ${i}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] ${o}
1231
- `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);T.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{T.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},ne=null;function Lt(r=!1){ne&&ne.dispose(),ne=new Zr(r)}function Is(){ne&&(ne.dispose(),ne=null)}function As(){ne&&ne.flush()}function ks(){return ne?.getLogFilePath()??null}function Ts(){return ne?.getLogDirectory()??null}function Sn(){return ne||Lt(!1),ne}var u={debug:(r,...e)=>Sn().debug(r,...e),info:(r,...e)=>Sn().info(r,...e),warn:(r,...e)=>Sn().warn(r,...e),error:(r,...e)=>Sn().error(r,...e)};function Rs(r){return"method"in r&&!("id"in r)}import{spawn as eu}from"child_process";import{EventEmitter as tu}from"events";import*as rt from"fs";import*as js from"path";import*as xs from"util";var Xr="";function Ms(r){if(!r||r==="auto"||r==="stdout"||r==="none"){Xr="";return}Xr=r}function Os(){return Xr||(Ts()??"")}function En(r,...e){if(e.length===0)return r;try{return xs.format(r,...e)}catch{return[r,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var l={info(r,...e){u.info(`[lsp] ${En(r,...e)}`)},warn(r,...e){u.warn(`[lsp] ${En(r,...e)}`)},error(r,...e){u.error(`[lsp] ${En(r,...e)}`)},debug(r,...e){u.debug(`[lsp] ${En(r,...e)}`)}};import*as Nt from"fs";import*as Ht from"os";import*as nt from"path";import Qd from"json5";var m={INITIALIZE:"initialize",INITIALIZED:"initialized",SHUTDOWN:"shutdown",EXIT:"exit",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",DID_CLOSE:"textDocument/didClose",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",DECLARATION:"textDocument/declaration",REFERENCES:"textDocument/references",IMPLEMENTATION:"textDocument/implementation",COMPLETION:"textDocument/completion",COMPLETION_ITEM_RESOLVE:"completionItem/resolve",SIGNATURE_HELP:"textDocument/signatureHelp",CODE_ACTION:"textDocument/codeAction",PREPARE_RENAME:"textDocument/prepareRename",RENAME:"textDocument/rename",DOCUMENT_HIGHLIGHT:"textDocument/documentHighlight",DOCUMENT_LINK:"textDocument/documentLink",INLAY_HINT:"textDocument/inlayHint",DOCUMENT_SYMBOL:"textDocument/documentSymbol",WORKSPACE_SYMBOL:"workspace/symbol",DIAGNOSTIC:"textDocument/diagnostic",WORKSPACE_DIAGNOSTIC:"workspace/diagnostic",PREPARE_CALL_HIERARCHY:"textDocument/prepareCallHierarchy",INCOMING_CALLS:"callHierarchy/incomingCalls",OUTGOING_CALLS:"callHierarchy/outgoingCalls",PREPARE_TYPE_HIERARCHY:"textDocument/prepareTypeHierarchy",SUPERTYPES:"typeHierarchy/supertypes",SUBTYPES:"typeHierarchy/subtypes",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",DID_CREATE_FILES:"workspace/didCreateFiles",DID_DELETE_FILES:"workspace/didDeleteFiles",PROGRESS:"$/progress",WINDOW_SHOW_MESSAGE:"window/showMessage",WINDOW_LOG_MESSAGE:"window/logMessage",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing",ARKTS_ERROR:"arkts/error",BROADCAST:"lsp/broadcast"},I="2.0";var Ls=8192,Qr=100,Ns=.03,Hs=.7,ke=900*1e3;function z(r){if(!Nt.existsSync(r))return null;try{let e=Nt.readFileSync(r,"utf-8");return e.trim()?Qd.parse(e):null}catch{return null}}function Cn(r,e){let t=Math.floor(Ht.totalmem()/1048576),n=Math.floor(t*Hs),i,o;e!==void 0&&Number.isFinite(e)&&e>0?(i=e,o=`override(${e})`):(i=Ls,r>Qr&&(i+=(r-Qr)*Ns*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 Te(r){if(r.startsWith("file:"))return r;try{let e=nt.resolve(r),t=new URL(`file://${e}`).toString();if(Ht.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 Dn(r){return r&&r.replace(/\\/g,"/")}function N(r){let e=nt.normalize(r).replace(/\\/g,"/");if(Ht.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function Fs(r){return nt.join(r,"build-profile.json5")}var it=class extends tu{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;ensureDirectories(){let t=js.join(this.config.logPath,"lspLog");return rt.existsSync(t)||rt.mkdirSync(t,{recursive:!0}),rt.existsSync(this.config.indexingDataLocation)||rt.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){let n=this.ensureDirectories();l.info(`[LspClient] serverMaxSize=${t}MB`);let i=N(n),o=["--expose-gc",`--max-old-space-size=${t}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${i}`,this.config.serverPath,"--stdio",`--logger-path=${i}`,"--logger-level=TRACE"];l.info(`[LspClient] Starting process: node ${o.join(" ")}`);let s=process.execPath??"node";l.info(`[LspClient] nodePath: ${s}`),this.process=eu(s,o,{cwd:this.config.cwd||process.cwd(),stdio:["pipe","pipe","pipe"],windowsHide:!0}),this.process.stdout?.on("data",a=>{this.handleData(a)}),this.process.stderr?.on("data",a=>{let c=a.toString("utf8").trim();l.error(`[LspClient] stderr: ${c}`),this.isClosing||this.emit("error",new Error(`[LspClient] stderr: ${c}`))}),this.process.on("exit",a=>{l.info(`[LSP EXIT] code=${a}`),this.isClosing||this.emit("error",new Error(`LSP process exited with code ${a}`))}),await new Promise(a=>setTimeout(a,500)),l.info("[LspClient] start lsp process success")}sendRaw(t,n){if(!this.process?.stdin?.writable){l.warn("[LspClient] Cannot send message, stdin not writable");return}l.info(`[LspClient] send message: ${n}`);let i=this.buildLspMessage(t);this.process.stdin.write(i,"utf8")}send(t,n,i){let o={jsonrpc:"2.0",method:t,params:n};i!==void 0&&(o.id=i),this.sendRaw(JSON.stringify(o),t)}sendNotification(t,n){this.sendRaw(JSON.stringify({jsonrpc:"2.0",method:t,params:n}),t)}sendRequest(t,n,i){this.sendRaw(JSON.stringify({jsonrpc:"2.0",id:i,method:t,params:n}),t)}buildLspMessage(t){return`Content-Length: ${Buffer.from(t,"utf8").length}\r
1232
- \r
1233
- ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let n=this.buffer.indexOf(`\r
1234
- \r
1235
- `);if(n===-1)break;let o=this.buffer.slice(0,n).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!o){l.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(n+4);continue}let s=parseInt(o[1],10),a=n+4,c=a+s;if(this.buffer.length<c)break;let d=this.buffer.slice(a,c).toString("utf8"),p=this.recoverFramedJson(d);if(p&&p.rest.length>0){l.warn(`[LspClient] recovered mixed LSP frame, bodyLen=${d.length}, restLen=${p.rest.length}`),this.emit("message",p.json),this.buffer=Buffer.concat([Buffer.from(p.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),p=t.slice(a+1);return{json:d,rest:p}}}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 ot=class{callbacks=new Map;pending=new Map;timeouts=new Map;registerPending(e,t,n){return new Promise((i,o)=>{let s;n>0&&(s=setTimeout(()=>{this.pending.delete(e),this.timeouts.delete(e),o(new Error(`LSP request '${t}' (id=${e}) timeout after ${n}ms`))},n),this.timeouts.set(e,s)),this.pending.set(e,{resolve:i,reject:o,method:t,timer:s})})}resolvePending(e,t){this.clearTimeout(e);let n=this.pending.get(e);return n?(n.resolve(t),this.pending.delete(e),!0):!1}rejectPending(e,t){this.clearTimeout(e);let n=this.pending.get(e);return n?(n.reject(t),this.pending.delete(e),!0):!1}register(e,t){this.callbacks.set(e,t)}emit(e,t,n){l.info(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let i=this.callbacks.get(e);if(i)i(t,n),this.callbacks.delete(e);else{let o=[...this.callbacks.keys()].map(s=>String(s));l.info(`[RequestCallbackManager] emit: NO callback for key='${e}', registered keys=[${o.join(",")}]`)}}registerTimeout(e,t,n,i){let o=this.timeouts.get(e);o&&clearTimeout(o);let s=setTimeout(()=>{l.info(`[RequestCallbackManager] timeout, key=${e}, method=${t}`),i(),this.timeouts.delete(e)},n);this.timeouts.set(e,s)}clearTimeout(e){let t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e))}deleteCallback(e){this.callbacks.delete(e)}hasCallback(e){return this.callbacks.has(e)||this.pending.has(e)}clear(e){this.clearTimeout(e);let t=this.pending.get(e);t&&(t.reject(new Error(`Request '${t.method}' (id=${e}) cancelled`)),this.pending.delete(e)),this.callbacks.delete(e)}rejectAll(e){for(let[,t]of this.pending)t.reject(e);this.pending.clear();for(let[,t]of this.timeouts)clearTimeout(t);this.timeouts.clear(),this.callbacks.clear()}};var In=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var st=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 b(r){return typeof r=="object"&&r!==null}var $s=20*1e3,nu=30*1e3,An=class{client;nextRequestId=1;stopOnce=null;callbacks=new st;requestCallbacks=new ot;diagnosticMap=new Map;initProgressReset=null;constructor(e){this.client=new it(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 shutdown request"),this.client.sendRequest(m.SHUTDOWN,null,this.nextRequestId++),l.info("[ClientMessageHandle] Sending exit notification"),this.client.sendNotification(m.EXIT,null),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(m.BROADCAST),this.callbacks.register(m.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(m.BROADCAST,e)}async sendInitialize(e){let t=this.nextRequestId++,n=this.requestCallbacks.registerPending(t,m.INITIALIZE,ke);return this.client.sendRequest(m.INITIALIZE,e,t),n}sendInitializeResettable(e,t){let n=this.nextRequestId++,i=this.requestCallbacks.registerPending(n,m.INITIALIZE,0);return this.client.sendRequest(m.INITIALIZE,e,n),new Promise((o,s)=>{let a,c=()=>{a=setTimeout(()=>{this.initProgressReset=null,s(new Error(`LSP initialization timeout after ${t}ms`))},t)},d=()=>{clearTimeout(a),c()};this.initProgressReset=d,c(),i.then(()=>{clearTimeout(a),this.initProgressReset=null,o()},p=>{clearTimeout(a),this.initProgressReset=null,s(p)})})}sendInitialized(){this.client.sendNotification(m.INITIALIZED,{})}sendDidOpen(e){let t=e.textDocument.uri;this.diagnosticMap.has(t)||(this.diagnosticMap.set(t,new In(t)),this.registerDiagnosticTimeout(t)),this.client.sendNotification(m.DID_OPEN,e)}sendDidChange(e){let t=e.textDocument.uri,n=this.diagnosticMap.get(t);n&&(n.clear(),this.registerDiagnosticTimeout(t)),this.client.sendNotification(m.DID_CHANGE,e)}closeFile(e){this.cleanupDiagnosticState(e.textDocument.uri),this.client.sendNotification(m.DID_CLOSE,e)}sendLspRequest(e,t,n=nu){let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,n);return this.client.sendRequest(e,t,i),o}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}onDidChangeWatchedFiles(e){e.length!==0&&this.client.sendNotification(m.WORKSPACE_DID_CHANGE_WATCHED_FILES,{changes:e})}sendDidChangeConfiguration(e){this.client.sendNotification(m.WORKSPACE_DID_CHANGE_CONFIGURATION,{settings:e})}sendNotification(e,t){this.client.sendNotification(e,t)}getDiagnosticMessages(e){let t=this.diagnosticMap.get(e);return t?t.get():[]}clearDiagnostic(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(n){let i=n instanceof Error?n.message:String(n);l.error(`[LSP] JSON parse error: ${i}, raw: ${e}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotificationOrRequest(t):l.warn(`[LSP] Unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t===void 0)return;let n=t;if(e.error){let i=new Error(`LSP error ${e.error.code}: ${e.error.message}`);this.requestCallbacks.rejectPending(n,i)}else this.requestCallbacks.resolvePending(n,e.result)}handleNotificationOrRequest(e){let t=e.method;if(t)switch(this.initProgressReset?.(),t){case m.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case m.PROGRESS:this.handleProgress(e.params);break;case m.WINDOW_SHOW_MESSAGE:l.info(`[LSP] window/showMessage: ${JSON.stringify(e.params)}`);break;case m.WINDOW_LOG_MESSAGE:l.info(`[LSP] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.broadcastToClients(e)}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=e.uri,n=this.diagnosticMap.get(t);if(!n)return;let i=e.diagnostics||[];this.normalizeDiagnostics(i),n.set(i),this.finalizeDiagnostic(t,i)}normalizeDiagnostics(e){for(let t of e)if(t.severity!==void 0){let n={1:"Error",2:"Warning",3:"Information",4:"Hint"};t.severityStr=n[t.severity]||"Unknown"}}handleProgress(e){b(e)&&this.broadcastToClients({jsonrpc:I,method:m.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,m.PUBLISH_DIAGNOSTICS,$s,()=>{let t=this.diagnosticMap.get(e),n=t?t.get():[];this.finalizeDiagnostic(e,n,n.length>0?void 0:`received no diagnostics within ${$s}ms, uri: ${e}`)})}finalizeDiagnostic(e,t,n){let i={uri:e,diagnostics:t,...n?{errorMessage:n}:{}};this.requestCallbacks.emit(e,m.PUBLISH_DIAGNOSTICS,i),this.diagnosticMap.get(e)?.clear()}handleError(e){let t=Array.from(this.diagnosticMap.keys()).filter(n=>this.requestCallbacks.hasCallback(n));if(t.length>0){let n={range:{start:{line:0,character:0},end:{line:0,character:0}},severity:1,message:e.message};for(let i of t)this.finalizeDiagnostic(i,[n]);return}this.broadcastToClients({jsonrpc:I,method:m.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var kn=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(`[LegacyDiagnostic] 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 ru={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"},iu={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate",ON_FORCE_OPEN_FILE:"aceProject/onForceOpenFile",ON_PACKAGE_CHANGE_FINISH:"aceProject/onPackageChangeFinish",TEXT_DOCUMENT_ON_ASYNC_DEFINITION:"textDocument/onAsyncDefinition",ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:"textDocument/onDidChangePackageDependencies",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",REFERENCES:"textDocument/references",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",BROADCAST:"lsp/broadcast",ARKTS_ERROR:"arkts/error",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing"},E={...ru,...iu},Re={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"},_s=new Set([1e3,2e3,3e3,3001]);function ou(r){if(!b(r))return!1;let e=r.textDocument;return b(e)&&typeof e.uri=="string"}function su(r){return b(r)?typeof r.uri=="string"&&typeof r.type=="number":!1}function au(r){return b(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 Tn=class r{client;isInitialized=!1;stopOnce=null;callbacks=new st;requestCallbacks=new ot;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;constructor(e){this.client=new it(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("[LegacyClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:I,method:E.EXIT,params:{}}),Re.EXIT),l.info("[LegacyClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),l.info("[LegacyClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(E.BROADCAST),this.callbacks.register(E.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(E.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(E.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(E.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:I,method:E.INITIALIZED,params:{editors:e}}),Re.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:I,id:0,result:{}}),Re.EMPTY)}sendAsyncRequest(e,t,n,i){if(!b(t)){l.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!ou(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=Te(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:I,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(!su(n)){l.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(n)}`);continue}t.push(n)}this.client.sendRaw(JSON.stringify({jsonrpc:I,method:E.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),E.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!b(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:I,method:E.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),Re.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,n=t.split(".").pop()||"";if(n!=="ets"&&n!=="ts")return;let i=Te(t);e.textDocument.uri=i,l.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new kn(i),this.diagnosticMap.set(i,o),this.registerDiagnosticTimeout(i,E.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(o.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:I,method:E.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),Re.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=Te(e.uri),n=this.diagnosticMap.get(t);n&&(n.clear(),this.registerDiagnosticTimeout(t,E.PUBLISH_DIAGNOSTICS)),l.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:I,method:E.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),Re.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let n=Te(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:I,method:E.DID_CLOSE,params:{textDocument:{uri:n}}}),Re.DID_CLOSE)}getDiagnosticMessage(e){let t=Te(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,E.PUBLISH_DIAGNOSTICS,[n]);return}this.broadcastToClients({jsonrpc:I,method:E.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 E.MODULE_INIT_FINISH:return l.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(E.MODULE_INIT_FINISH),this.callbacks.unregister(E.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case E.INDEXING_PROGRESS_UPDATE:return l.info(`[LSP] onIndexingProgressUpdate: ${au(t.params)}`),this.callbacks.invoke(E.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case E.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case E.ON_PACKAGE_CHANGE_FINISH:l.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case E.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case E.ON_ASYNC_HOVER:this.handleAsyncResponse(t,E.HOVER);return;case E.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,E.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case E.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,E.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;b(t)&&b(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:I,method:E.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(!b(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,E.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(_s)&&this.finalizeDiagnostic(t,E.PUBLISH_DIAGNOSTICS,i.getMessages())}normalizeDiagnostic(e){let t=e;if(delete t.source,t.severity!==void 0){let n=typeof t.severity=="number"?t.severity:parseInt(t.severity),o={1:"Error",2:"Warning",3:"Information",4:"Hint"}[n]||"Unknown";t.severityStr=o,t.severity=o}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 Wt from"path";import*as Hn from"path";var Rn=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var xn=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 On=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var Ln=class{typeSetting=new Mn;parameterNames=new On};var Nn=class{constructor(e,t,n,i){this.rootUri=e;this.lspServerWorkspacePath=N(Hn.dirname(t)),this.indexingDataLocation=N(i),this.loggerPath=N(Hn.join(n,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new Rn;gutterIconsSetting=new xn;inlayHintsSetting=new Ln;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as Ws from"path";var Ft=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(N(Ws.join(e,"src","main","resources")))}};var cu="OS",at=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${cu}`;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 Ft(e)):this.buildProfileParam=new Ft}toString(){return JSON.stringify(this)}};var ct=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as q from"path";import*as ut from"fs";var Fn=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 lt=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 ve from"path";import*as jn from"fs";var dt=class{name="";version="";storePath="";dependencyPath="";path=""};var P={HVIGOR_CACHE:".hvigor",DEPENDENCY:"dependencyMap",JSON5:".json5",KEY_DEPENDENCY:"dependencies",KEY_DYNAMIC_DEPENDENCY:"dynamicDependencies",KEY_DEV_DEPENDENCY:"devDependencies",OH_MODULES_PATH:"oh_modules",OHPM_PATH:".ohpm",LOCK_JSON5_FILE:"lock.json5",OH_PACKAGE_JSON5:"oh-package.json5",SYNC_OUTPUT_FILE:"output.json",ENV_FORCE_SYNC:"DEVECO_MCP_FORCE_SYNC"},jt=`${P.HVIGOR_CACHE}/${P.DEPENDENCY}`,We=`${P.DEPENDENCY}${P.JSON5}`,Us=`${P.HVIGOR_CACHE}/outputs/sync/${P.SYNC_OUTPUT_FILE}`;var $t=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=ve.join(this.dependencyPath,P.OH_PACKAGE_JSON5),n=z(t);n&&(this.dependencies=this.getDependencyList(n,P.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(n,P.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(n,P.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let n=[];if(!b(e))return n;let i=e[t];if(!b(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 dt;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=ve.normalize(ve.join(this.modulePath,P.OH_MODULES_PATH,e));if(!(t.startsWith(r.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){n.dependencyPath=o;return}if(n.path=t,this.fileNameForOhpm.test(t)){n.dependencyPath=o;return}let s=t;if(t.startsWith(r.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(r.FILE_DEPENDENCY_PREFIX.length)),ve.isAbsolute(s)){n.dependencyPath=o;return}i||(o=ve.normalize(ve.join(this.modulePath,s))),jn.existsSync(o)&&jn.statSync(o).isDirectory()&&(n.dependencyPath=o)}catch(o){l.error("parser dependency path is invalid",o)}}};import*as _t from"fs";import*as xe from"path";import lu from"json5";var $n=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 xe.join(this.projectPath,P.OH_MODULES_PATH,P.OHPM_PATH,P.LOCK_JSON5_FILE)}readLockFile(e){if(!_t.existsSync(e))return l.error("lock file does not exist"),this.clearDependencies(),null;try{let t=_t.readFileSync(e,"utf8"),n=lu.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(!b(e))return l.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return l.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let n=e.packages;return n?{valid:!0,modules:t,packages:n}:(l.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,n){this.storePathMap=t,this.finalDependencies=this.getDependencyList(e,P.KEY_DEPENDENCY,n),this.finalDevDependencies=this.getDependencyList(e,P.KEY_DEV_DEPENDENCY,n),this.finalDynamicDependencies=this.getDependencyList(e,P.KEY_DYNAMIC_DEPENDENCY,n)}parseStorePathMap(e){let t=new Map;if(!b(e))return t;for(let[n,i]of Object.entries(e)){if(!b(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(!b(e))return[];for(let[i,o]of Object.entries(e))if(b(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(!b(i))return l.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!b(s))return[];for(let[a,c]of Object.entries(s)){if(!b(c))continue;let d=typeof c.specifier=="string"?c.specifier:"",p=typeof c.version=="string"?c.version:"",g=new dt;g.name=a,g.version=p.startsWith(r.FILE_DEPENDENCY_PREFIX)?p.substring(r.FILE_DEPENDENCY_PREFIX.length):p,this.parseDependencyPath(g,n,a,d,p);let k=`${a}@${p}`;this.storePathMap.has(k)&&(g.storePath=this.storePathMap.get(k)||""),o.push(g)}return o}parseDependencyPath(e,t,n,i,o){let s=xe.normalize(xe.join(this.projectPath,t,P.OH_MODULES_PATH,n));try{let a=o;o.startsWith(r.FILE_DEPENDENCY_PREFIX)&&(a=o.substring(r.FILE_DEPENDENCY_PREFIX.length));let c=a;if(xe.isAbsolute(c)||(c=xe.join(this.projectPath,a)),!_t.existsSync(c)){e.dependencyPath=s;return}if(e.path=i,this.fileNameForOhpm.test(o)){e.dependencyPath=s;return}e.dependencyPath=c}catch(a){l.error("Invalid dependency path in lock.json5",a)}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};var we=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=Fs(this.projectRoot);try{let t=z(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 b(r)?typeof r.name=="string"&&typeof r.srcPath=="string":!1}var Ue=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new we(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,n=q.join(t,jt),i=q.join(n,We);if(!ut.existsSync(n)||!ut.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 lt(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=q.join(n,jt),o=q.join(i,We);if(!ut.existsSync(i)||!ut.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 lt(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 p=d.name;if(s&&!s.has(p))continue;let g=d.srcPath,k=q.resolve(this.projectPath,g),re=q.join(i,p),Se=N(k),Be=this.buildModuleDependencies(p,Se,re,a);Be.moduleName=p,t.push(Be)}return t}parseSingleModule(e,t,n,i){let o=e.name,s=e.srcPath,a=q.resolve(this.projectPath,s),c=q.join(t,o),d=N(a),p=new at(d),g=this.buildModuleDependencies(o,d,c,n);this.parseModuleJson5(d,p);let k=this.parseMainPages(d);this.parseSdkJson(p),this.parseCompatibleSdkVersion(p),p.moduleName=o,p.moduleType=o,p.packageName=o,p.moduleDependencies=g,p.moduleJsonParam=new ct(k),i.push(p)}buildModuleDependencies(e,t,n,i){let o=new lt(this.projectPath,e,t);$t.getInstance(n,t,this.projectPath).parseDependency(o),this.parseLockJson(o),o.finalDependencies.push(...i.finalDependencies),o.finalDevDependencies.push(...i.finalDevDependencies),o.finalDynamicDependencies.push(...i.finalDynamicDependencies),o.finalDependencies.push(...o.finalDevDependencies);let a=new Fn;return a.modulePath=t,this.toModuleDependencies(o,a),a}toModuleDependencies(e,t){let n={},i={};for(let o of e.finalDependencies)n[o.name]=new _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=q.join(e,P.OH_PACKAGE_JSON5);if(!ut.existsSync(n))return;$t.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 $n(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let n=q.join(e,"src","main","module.json5"),i=z(n);if(!b(i)||!b(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(b(e)&&Array.isArray(e.requestPermissions))for(let n of e.requestPermissions)b(n)&&typeof n.name=="string"&&t.push(n.name);return t}parseMainPages(e){let t=q.join(e,"src","main","resources","base","profile","main_pages.json"),n=z(t);return!b(n)||!Array.isArray(n.src)?[]:n.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=this.getSdkPkg();if(!(!b(t)||!b(t.data))){if(typeof t.data.apiVersion=="string"){let n=parseInt(t.data.apiVersion,10);!Number.isNaN(n)&&n>=26&&typeof t.data.platformVersion=="string"?e.compileSdkLevel=t.data.platformVersion:e.compileSdkLevel=t.data.apiVersion}typeof t.data.releaseType=="string"&&(e.compileSdkType=t.data.releaseType),typeof t.data.version=="string"&&(e.compileSdkVersion=t.data.version)}}getSdkPkg(){if(this.sdkPkgCache===void 0){let e=q.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=z(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!b(t)||!b(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let n=t.app.products[0];if(!b(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=q.join(this.projectPath,"build-profile.json5");this.buildProfileCache=z(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,e];let n=e.substring(0,t),i=e.substring(t+1,e.length-1);return[n,i]}parseDeviceTypes(e){return!b(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 _n=class{constructor(e=[]){this.valueSet=e}valueSet};var pt=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var zs=(y=>(y[y.File=1]="File",y[y.Module=2]="Module",y[y.Namespace=3]="Namespace",y[y.Package=4]="Package",y[y.Class=5]="Class",y[y.Method=6]="Method",y[y.Property=7]="Property",y[y.Field=8]="Field",y[y.Constructor=9]="Constructor",y[y.Enum=10]="Enum",y[y.Interface=11]="Interface",y[y.Function=12]="Function",y[y.Variable=13]="Variable",y[y.Constant=14]="Constant",y[y.String=15]="String",y[y.Number=16]="Number",y[y.Boolean=17]="Boolean",y[y.Array=18]="Array",y[y.Object=19]="Object",y[y.Key=20]="Key",y[y.Null=21]="Null",y[y.EnumMember=22]="EnumMember",y[y.Struct=23]="Struct",y[y.Event=24]="Event",y[y.Operator=25]="Operator",y[y.TypeParameter=26]="TypeParameter",y))(zs||{}),qs=()=>Object.values(zs).filter(r=>typeof r=="number");var Wn=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Un=class{applyEdit=!0;workspaceEdit=new Wn;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new _n(qs());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new pt;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Bn=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var zn=class{constructor(e=[]){this.valueSet=e}valueSet};var qn=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var Vs=(w=>(w[w.Text=1]="Text",w[w.Method=2]="Method",w[w.Function=3]="Function",w[w.Constructor=4]="Constructor",w[w.Field=5]="Field",w[w.Variable=6]="Variable",w[w.Class=7]="Class",w[w.Interface=8]="Interface",w[w.Module=9]="Module",w[w.Property=10]="Property",w[w.Unit=11]="Unit",w[w.Value=12]="Value",w[w.Enum=13]="Enum",w[w.Keyword=14]="Keyword",w[w.Snippet=15]="Snippet",w[w.Color=16]="Color",w[w.File=17]="File",w[w.Reference=18]="Reference",w[w.Folder=19]="Folder",w[w.EnumMember=20]="EnumMember",w[w.Constant=21]="Constant",w[w.Struct=22]="Struct",w[w.Event=23]="Event",w[w.Operator=24]="Operator",w[w.TypeParameter=25]="TypeParameter",w))(Vs||{}),Gs=()=>Object.values(Vs).filter(r=>typeof r=="number");var Vn=class{completionItemKind=new zn(Gs());completionItem=new qn;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var Gn=class{synchronization=new Bn;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 pt;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var Yn=class{workspace=new Un;textDocument=new Gn;notebookDocument=null;window=null;general=null;experimental=null};var Jn=class{constructor(e,t,n){this.rootUri=e;this.initializationOptions=t;this.capabilities=n}rootUri;initializationOptions;capabilities};var Kn=class{constructor(e,t,n,i,o,s=!0){this.sdkPath=e;this.rootUri=n;this.nodeMaxOldSpaceSize=o;this.useStandardProtocol=s;this.serverPath=this.useStandardProtocol?Wt.resolve(t,"ace-server","out","standardIndex","index.js"):Wt.resolve(t,"ace-server","out","index.js"),this.logPath=Os(),this.indexLogPath=i||this.logPath;let a={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath};this.messageHandle=this.useStandardProtocol?new An(a):new Tn(a),this.messageHandle.setBroadcastToClients(c=>this.onLspMessage(c))}sdkPath;rootUri;nodeMaxOldSpaceSize;useStandardProtocol;messageHandle;get stdHandle(){return this.messageHandle}get legacyHandle(){return this.messageHandle}onAsyncOpenFile(e){this.legacyHandle.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.legacyHandle.closeFile(e,t)}serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];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=Te(this.rootUri),o=new Nn(i,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new Ue(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),o.modules=s;let d=Cn(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(d),this.currentParams=new Jn(i,o,new Yn),this.useStandardProtocol){let p=this.messageHandle;await p.sendInitializeResettable(this.currentParams,ke),l.info("[LSP] initialize response received"),p.broadcastToClients({jsonrpc:I,method:m.ARKTS_INDEXING_PROGRESS,params:{}}),p.sendInitialized()}else await this.startLegacy(this.currentParams,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)}async startLegacy(e,t){let n=this.messageHandle;n.sendInitialize(e,1),n.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:I,method:m.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((i,o)=>{n.onIndexingProgressUpdate(o),n.onInitializationCompleted(i)},"LSP initialization",ke),n.sendInitialized(t)}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)})}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){l.info(`[LSP] registerDiagnosticCallback uri='${e}', useStandardProtocol=${this.useStandardProtocol}`),this.messageHandle.registerRequestCallback(e,(t,n)=>{let i=b(n)?n:{};l.info(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let o={jsonrpc:I,method:t,params:{uri:typeof i.uri=="string"?i.uri:e,diagnostics:Array.isArray(i.diagnostics)?i.diagnostics:[],...typeof i.errorMessage=="string"?{errorMessage:i.errorMessage}:{}}};this.onLspMessage(o)})}async hover(e){let t=e.textDocument.uri;return this.registerDiagnosticCallback(t),this.stdHandle.sendLspRequest(m.HOVER,e)}async definition(e){return this.stdHandle.sendLspRequest(m.DEFINITION,e)}async references(e){return this.stdHandle.sendLspRequest(m.REFERENCES,e)}async completion(e){return this.stdHandle.sendLspRequest(m.COMPLETION,e)}async documentSymbol(e){return this.stdHandle.sendLspRequest(m.DOCUMENT_SYMBOL,e)}async diagnostic(e){return this.stdHandle.sendLspRequest(m.DIAGNOSTIC,e,120*1e3)}async sendFeatureRequest(e,t){return this.stdHandle.sendLspRequest(e,t)}reloadDependenciesOnly(e){let t=e?.fullReload??!1,n=new Ue(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 p=this.mergeDepsOnlyIntoModuleList(d,i);return this.applyModuleModelsUpdate(p),this.sendDidChangeConfiguration({moduleSet:p}),l.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${p.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),this.sendDidChangeConfiguration({moduleSet:c}),l.info(`[LspServerProxy] Dependencies only (incremental) reloaded, count: ${c.length}`),this.lastDepsOnlyForDiff=a,a}sendDidChangeConfiguration(e){this.stdHandle.sendDidChangeConfiguration(e)}getModuleModelsByName(){return new Map(this.currentModuleModels.map(e=>[e.moduleName??"",e]))}markDependencyTypesIncremental(e){let t=this.getModuleModelsByName(),n=new Map(this.lastDepsOnlyForDiff.map(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,(p,g)=>{(i.dependencies??={})[p]=this.makeDeleteEntry(p,g)}),this.markAddAndDeleteInDeps(a,d,(p,g)=>{(i.dynamicDependencies??={})[p]=this.makeDeleteEntry(p,g)})}}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 at(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new ct([]),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=Dn(Wt.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=Dn(Wt.join(t,"default/openharmony/ets/api")),o=Dn(Wt.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=n,s.sdkJsPath=i,s.hosSdkPath=o}sendRequest(e){switch(e.method){case m.HOVER:this.stdHandle.sendLspRequest(m.HOVER,e.params).then(t=>this.onLspMessage({jsonrpc:I,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:I,id:e.id,error:{code:-32603,message:t.message}}));break;case m.DEFINITION:this.stdHandle.sendLspRequest(m.DEFINITION,e.params).then(t=>this.onLspMessage({jsonrpc:I,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:I,id:e.id,error:{code:-32603,message:t.message}}));break;case m.REFERENCES:this.stdHandle.sendLspRequest(m.REFERENCES,e.params).then(t=>this.onLspMessage({jsonrpc:I,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:I,id:e.id,error:{code:-32603,message:t.message}}));break;default:l.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!Rs(e)){l.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case m.DID_OPEN:this.handleDidOpenNotification(e);break;case m.DID_CHANGE:this.handleDidChangeNotification(e);break;case m.DID_CLOSE:this.handleDidCloseNotification(e);break;case m.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;case m.DID_CREATE_FILES:this.handleDidCreateFiles(e);break;case m.DID_DELETE_FILES:this.handleDidDeleteFiles(e);break;default:l.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){l.error("Invalid textDocument/didOpen params");return}this.stdHandle.sendDidOpen(t)}handleDidChangeNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){l.error("Invalid textDocument/didChange params");return}this.stdHandle.sendDidChange(t)}handleDidCloseNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){l.error("Invalid textDocument/didClose params");return}this.stdHandle.closeFile(t)}handleDidChangeWatchedFiles(e){let t=e.params;!t||!Array.isArray(t.changes)||this.messageHandle.onDidChangeWatchedFiles(t.changes)}handleDidCreateFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(m.DID_CREATE_FILES,t)}handleDidDeleteFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(m.DID_DELETE_FILES,t)}async dispose(){await this.messageHandle.stop()}};import*as be from"fs";import*as J from"path";import{createHash as uu}from"crypto";import{EventEmitter as pu}from"events";var Zn=class extends pu{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(!be.existsSync(t)){l.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=be.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=J.resolve(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:o,relativePath:i.srcPath,timestamp:n,moduleName:i.name})}}emitModuleRemovedEvents(t,n){for(let i of t){let o=J.resolve(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:o,relativePath:i.srcPath,timestamp:n,removedModuleName:i.name})}}emitModuleRenamedEvents(t,n){for(let i of t){let o=J.resolve(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:o,relativePath:i.after.srcPath,timestamp:n,moduleName:i.after.name,removedModuleName:i.before.name})}}emitModuleMovedEvents(t,n){for(let i of t){let o=J.resolve(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:o,relativePath:i.after.srcPath,timestamp:n,moduleName:i.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let n=Date.now();this.emitModuleAddedEvents(t.added,n),this.emitModuleRemovedEvents(t.removed,n),this.emitModuleRenamedEvents(t.renamed,n),this.emitModuleMovedEvents(t.moved,n)}onBuildProfileChanged(){let t="__build_profile__",n=this.debounceTimers.get(t);n&&clearTimeout(n);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(o);if(s===this.lastModulesSnapshot){l.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,o);this.lastModules=o,this.lastModulesSnapshot=s,l.info(`[ConfigFileWatcher] build-profile.json5 modules changed, added=${a.added.length}, removed=${a.removed.length}, renamed=${a.renamed.length}, moved=${a.moved.length}`),this.processBuildProfileDiff(a)},this.debounceMs);this.debounceTimers.set(t,i)}computeModulesSnapshot(t){return t.map(i=>`${i.name}::${i.srcPath}`).sort().join("|")}diffModules(t,n){let i=this.buildModuleMatchState(n),o={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,i),this.matchRenamedModules(t,i,o),this.matchMovedModules(t,i,o),this.collectRemovedModules(t,i,o),this.collectAddedModules(n,i,o),o}buildModuleMatchState(t){let n=new Map,i=new Map;for(let o of t)n.set(o.srcPath,o),i.set(o.name,o);return{matchedOld:new Set,matchedNew:new Set,newBySrc:n,newByName:i}}matchExactModules(t,n){for(let i of t){let o=n.newBySrc.get(i.srcPath);o&&o.name===i.name&&(n.matchedOld.add(i),n.matchedNew.add(o))}}matchRenamedModules(t,n,i){for(let o of t){if(n.matchedOld.has(o))continue;let s=n.newBySrc.get(o.srcPath);s&&!n.matchedNew.has(s)&&s.name!==o.name&&(i.renamed.push({before:o,after:s}),n.matchedOld.add(o),n.matchedNew.add(s))}}matchMovedModules(t,n,i){for(let o of t){if(n.matchedOld.has(o))continue;let s=n.newByName.get(o.name);s&&!n.matchedNew.has(s)&&s.srcPath!==o.srcPath&&(i.moved.push({before:o,after:s}),n.matchedOld.add(o),n.matchedNew.add(s))}}collectRemovedModules(t,n,i){for(let o of t)n.matchedOld.has(o)||i.removed.push(o)}collectAddedModules(t,n,i){for(let o of t)n.matchedNew.has(o)||i.added.push(o)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let n=z(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=J.join(this.projectRoot,P.OH_PACKAGE_JSON5);be.existsSync(n)&&t.push(n);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=J.resolve(this.projectRoot,o.srcPath),a=J.join(s,P.OH_PACKAGE_JSON5);be.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return J.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let n=be.readFileSync(t,"utf-8");return uu("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=be.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:J.basename(t),relativePath:J.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 Me from"fs";import*as se from"path";import{createHash as hu}from"crypto";import{EventEmitter as fu}from"events";var Xn=class extends fu{constructor(t,n=500){super();this.projectRoot=t;this.debounceMs=n,this.coalesceMs=n+300,this.depMapDir=se.join(t,jt)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!Me.existsSync(this.depMapDir)){l.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=Me.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 N(se.resolve(t))}onDirEvent(t,n){if(!n||typeof n!="string")return;let i=n.replace(/\\/g,"/"),o;if(i===P.OH_PACKAGE_JSON5)o="root-oh-package";else if(i===We)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=se.join(this.depMapDir,n);Me.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=se.join(this.depMapDir,P.OH_PACKAGE_JSON5),n=se.join(this.depMapDir,We),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:n,tag:"dep-map-json"},...i.map(s=>({path:se.join(this.depMapDir,s.name,P.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!Me.existsSync(s))continue;let c=this.canonicalPath(s),d=this.computeFileHash(s);if(!d)continue;let p=this.contentHashes.get(c);if(!this.initialScanDone){this.contentHashes.set(c,d);continue}p!==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=se.join(this.depMapDir,We);try{let n=z(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 N(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=se.join(this.depMapDir,a.name,P.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(d)),l.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,n,i,o){for(let[s,a]of t){if(i.has(s))continue;let c=n.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),i.add(s),o.add(s),l.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,n,i){for(let[o]of t)i.has(o)||n.has(o)||(this.pendingTags.push(`dep-added:${o}`),i.add(o))}detectRemovedModules(t,n,i){for(let[o]of t)if(!i.has(o)&&!n.has(o)){this.pendingTags.push(`dep-removed:${o}`),i.add(o);let s=se.join(this.depMapDir,o,P.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(i=>i.startsWith("dep-")),n=this.pendingRenames.map(i=>`${i.kind}(${i.info.oldName}\u2192${i.info.newName})`);l.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${n.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:n,bySrcPath:i}=this.buildModuleLookupMaps(this.lastModules),{byName:o,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(i,s,a,c),this.detectModuleMoves(n,o,a,c),this.detectAddedModules(o,n,c),this.detectRemovedModules(n,o,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let n=Me.readFileSync(t,"utf-8");return hu("sha256").update(n).digest("hex")}catch{return null}}};import{spawn as mu}from"child_process";import*as tr from"path";import*as er from"fs";var gu=600*1e3;function yu(r,e,t){let n=t.split(/\s+/).filter(i=>i.length>0);return[r,[e,...n]]}function vu(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 Qn(r){return r.join("")}function wu(r,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
1236
- Output so far:
1237
- `+t,exitCode:-1};let n=r??-1;return{success:n===0,output:t,exitCode:n}}function bu(r,e,t){return new Promise(n=>{let i=mu(r[0],r[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:o,stderr:s}=vu(i),a=setTimeout(()=>{i.kill();let c=[Qn(o),Qn(s)].filter(Boolean).join(`
1238
- `).trim();n({success:!1,output:`Build process timeout after 10 minutes.
1239
- Output so far:
1240
- `+c,exitCode:-1})},gu);i.on("close",(c,d)=>{clearTimeout(a);let p=[Qn(o),Qn(s)].filter(Boolean).join(`
1241
- `).trim()||"";n(wu(c,d,p))}),i.on("error",c=>{clearTimeout(a),n({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function ti(r,e,t,n,i){let o={...process.env,DEVECO_SDK_HOME:n},s=yu(e,t,i);return await bu(s,r,o)}function Su(r){let e=tr.join(tr.dirname(r),"tools","hvigor","bin","hvigorw.js");return{node_path:bn(r),hvigor_path:e,sdk_path:r}}function Pu(r){return!r.node_path||!er.existsSync(r.node_path)?`Node path not found or invalid: ${r.node_path}`:!r.hvigor_path||!er.existsSync(r.hvigor_path)?`Hvigor path not found or invalid: ${r.hvigor_path}`:!r.sdk_path||!er.existsSync(r.sdk_path)?`SDK path not found or invalid: ${r.sdk_path}`:null}var Eu="--sync -p product=default --analyze=normal --parallel --incremental --no-daemon";async function Ys(r,e){try{let t=Su(e),n=Pu(t);return n!=null?(l.info(`Config validation failed: ${n}`),!1):(await ti(r,t.node_path,t.hvigor_path,e,Eu)).success}catch(t){return l.info(`syncProject failed: ${JSON.stringify(t)}`),!1}}import{spawn as Cu}from"child_process";import*as ni from"fs";import*as Ut from"path";var Du=["install","--all"];function Iu(r){let e=r.replace(/sdk\/?$/i,"tools"),t=Ut.join(e,"ohpm","bin","pm-cli.js");if(ni.existsSync(t))return t;let n=r.toLowerCase().endsWith("sdk")?Ut.dirname(r):r;return t=Ut.join(n,"ohpm","bin","pm-cli.js"),ni.existsSync(t)?t:null}async function Au(r,e,t,n){return new Promise(i=>{let o=Cu(r,[e,...Du],{cwd:t,env:{...process.env,DEVECO_SDK_HOME:n},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),s="",a="";o.stdout?.on("data",c=>{s+=c.toString()}),o.stderr?.on("data",c=>{a+=c.toString()}),o.on("close",c=>{let d=[s,a].filter(Boolean).join(`
1242
- `);i({exitCode:c??-1,output:d})}),o.on("error",c=>{let d=[s,a].filter(Boolean).join(`
1243
- `);i({exitCode:-1,output:d+`
1244
- `+c.message})})})}function ku(r){r.split(/\r?\n/).filter(Boolean).forEach(e=>l.info("[ohpm] %s",e))}async function Js(r,e){try{let t=bn(e);if(!t)return l.error("node \u8DEF\u5F84\u4E0D\u5B58\u5728"),!1;let n=Iu(e);if(!n)return l.error("ohpm (pm-cli.js) \u4E0D\u5B58\u5728"),!1;let{exitCode:i,output:o}=await Au(t,n,r,e);return ku(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 Ks={UNINITIALIZED:-32099,UNKNOWN:-32e3},Bt=class r extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new r(e,Ks.UNINITIALIZED)}static unknown(e="Unknown error"){return new r(e,Ks.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var ht=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)}async diagnostic(e){if(!this.lspProxy)throw new Error("[ArktsLspManager] diagnostic before LSP ready");return this.lspProxy.diagnostic(e)}async sendFeatureRequest(e,t){if(!this.useStandardProtocol)throw new Error(`Language feature '${e}' is not supported on the installed DevEco Studio. The standard LSP protocol entry (plugins/openharmony/ace-server/out/standardIndex/index.js) was not found. Please upgrade DevEco Studio to version 26.0.0.610 or later to use this tool.`);if(!this.lspProxy)throw new Error("LSP not ready");return this.lspProxy.sendFeatureRequest(e,t)}get useStandardProtocol(){return this.config.useStandardProtocol}onAsyncOpenFile(e){this.lspProxy?.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.lspProxy?.closeFileLegacy(e,t)}registerDiagnosticCallback(e){this.lspProxy?.registerDiagnosticCallback(e)}static async handleSyncProject(e,t){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 Si(e,async()=>await Js(e,t)?await Ys(e,t)?(l.info("[ArktsLspManager] syncProject completed successfully"),{status:"success"}):(l.error("[ArktsLspManager] syncProject failed"),{status:"failed",reason:"hvigor sync failed"}):(l.error("[ArktsLspManager] ohpm install failed"),{status:"failed",reason:"ohpm install failed"}));return n.acquired?n.result:(l.info("[ArktsLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){try{this.configWatcher?.stop()}catch(e){l.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){l.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){l.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e){let t=new Kn(this.config.sdkPath,this.config.arktsLangServerPath,this.config.workspaceRoot,this.config.indexLogPath,this.config.nodeMaxOldSpaceSize,this.config.useStandardProtocol);t.setOnMessage(n=>this.handleLspMessage(n)),t.start(e,n=>this.handleLspInitialized(n)),this.lspProxy=t}handleLspInitialized=e=>{if(this.isInitialized=e,e)l.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:I,method:m.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();l.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let n=t?Bt.uninitialized(t):Bt.unknown();this.onMessage({jsonrpc:I,method:m.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:I,method:m.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new Zn(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.onMessage({jsonrpc:I,method:m.ARKTS_SYNC_COMPLETED,params:{success:!0,moduleSet:n}})}),this.depMapWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){l.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),this.onConfigChanged?.()}};var Tu=10080*60*1e3,Ru=7200*60*1e3,xu=120*1e3,ft=class r{manager=null;initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;devecoPath;nodeMaxOldSpaceSize;onConfigChangedCallback=null;useStandardProtocol=!0;diagnosticWaiters=new Map;static FEATURE_METHOD_MAP={hover:m.HOVER,definition:m.DEFINITION,declaration:m.DECLARATION,references:m.REFERENCES,implementation:m.IMPLEMENTATION,completion:m.COMPLETION,signatureHelp:m.SIGNATURE_HELP,documentHighlight:m.DOCUMENT_HIGHLIGHT};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:ri.object({files:ri.array(ri.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,useStandardProtocol:i}=this.resolveProjectAndDeveco();this.useStandardProtocol=i;let o=te(e),{logPath:s,indexPath:a}=this.getLogAndIndexPath(o);setImmediate(()=>{Kr(a,Tu,"[ArkTS-Check]"),Kr(s,Ru,"[ArkTS-Check]")}),Ms(s);let c=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,d=Number.isNaN(c)?void 0:c;u.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${d??"undefined \u2192 dynamic formula applies"}`);let p=_.join(ee(t),"sdk");u.info(`ArktsCheck devecoPath: ${t}, contentRoot: ${ee(t)}, sdkPath: ${p}`),this.manager=new ht({sdkPath:p,arktsLangServerPath:n,workspaceRoot:N(o),indexLogPath:a,nodeMaxOldSpaceSize:d,useStandardProtocol:i}),this.manager.setOnMessage(g=>this.handleLspMessage(g)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((g,k)=>{this.initResolve=g,this.initReject=k,this.armInitTimer(ke),this.manager.start([]).catch(re=>{let Se=re instanceof Error?re:new Error(String(re));this.failInit(Se)})})}resolveProjectAndDeveco(){let e=ge(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.devecoPath??ye();if(u.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=gn(t);if(!n)throw new Error("arkts-lang-server path not found");let i=_.resolve(n,"ace-server","out","standardIndex","index.js"),o=K.existsSync(i);return u.info(`ArktsCheck protocol: ${o?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${o})`),{harmonyRoot:e,devecoPath:t,arktsLangServerPath:n,useStandardProtocol:o}}armInitTimer(e){this.initDeadlineTimer&&clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=setTimeout(()=>{let t=this.initReject;this.clearInitHandlers(),t?.(new Error("LSP initialize timeout"))},e)}clearInitHandlers(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async checkFile(e){this.initialized||await this.initialize();let t=this.manager;if(!t)throw new Error("ArktsLspManager not initialized");let n=$e(e),i=await K.promises.readFile(e,"utf8"),s=`deveco.apptool.${_.extname(e).replace(/^\./,"")||"plaintext"}`;return t.useStandardProtocol?this.checkFileStandard(t,n,i,s):this.checkFileLegacy(t,e,n,i,s)}async checkFileStandard(e,t,n,i){u.debug(`textDocument/didOpen uri=${t} content_len=${n.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:n,languageId:i,version:1}});try{u.debug(`textDocument/diagnostic uri=${t}`);let o=await e.diagnostic({textDocument:{uri:t}});return Mu(o)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:t}})}}async checkFileLegacy(e,t,n,i,o){let s=n;e.registerDiagnosticCallback(n);let a=new Promise((c,d)=>{let p=setTimeout(()=>{this.diagnosticWaiters.delete(s)&&d(new Error("Wait for diagnostics timeout"))},xu);this.diagnosticWaiters.set(s,{resolve:c,reject:d,timer:p})});u.debug(`textDocument/didOpen(legacy) uri=${n} content_len=${i.length}`),e.onAsyncOpenFile({textDocument:{uri:n,text:i,languageId:o,version:i.length},editorFiles:[n],isFromEditor:!1});try{return await a}finally{e.closeFileLegacy(n,!1)}}async handleCall(e){if(!this.initialized)return this.buildNotReadyResponse();let t=[],n=[],i=this.collectValidFiles(e.files,t);return i.length===0?{content:[{type:"text",text:t.length>0?t.join(`
1245
- `):"\u6CA1\u6709\u6709\u6548\u7684 .ets \u6587\u4EF6"}],isError:!0}:(await this.runDiagnosticsForFiles(i,t,n),this.formatCallResult(t,n))}async handleLspFeature(e,t){if(!this.initialized)return this.buildNotReadyResponse();let n=this.resolveSingleFile(t.file);if(!n)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${t.file}`}],isError:!0};let i=r.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};u.info(`handleLspFeature: ${e} file=${n} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(n,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){let s=o instanceof Error?o.message:String(o);return u.error(`handleLspFeature ${e} failed: ${s}`),{content:[{type:"text",text:`${e} failed: ${s}`}],isError:!0}}}async handleWorkspaceSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();u.info(`handleWorkspaceSymbol: query="${e}"`);try{let t=await this.manager.sendFeatureRequest(m.WORKSPACE_SYMBOL,{query:e});return{content:[{type:"text",text:t==null?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(t,null,2)}`}]}}catch(t){let n=t instanceof Error?t.message:String(t);return u.error(`handleWorkspaceSymbol failed: ${n}`),{content:[{type:"text",text:`workspaceSymbol failed: ${n}`}],isError:!0}}}async handleDocumentSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};u.info(`handleDocumentSymbol: file=${t}`);try{let n=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(m.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:n==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(n,null,2)}`}]}}catch(n){let i=n instanceof Error?n.message:String(n);return u.error(`handleDocumentSymbol failed: ${i}`),{content:[{type:"text",text:`documentSymbol failed: ${i}`}],isError:!0}}}async handleCallHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};u.info(`handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let n=await this.withOpenFile(t,async o=>{let s=await this.manager.sendFeatureRequest(m.PREPARE_CALL_HIERARCHY,{textDocument:{uri:o},position:{line:e.line,character:e.character}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],calls:[]};let c=e.direction==="incoming"?m.INCOMING_CALLS:m.OUTGOING_CALLS,d=[];for(let p of a){let g=await this.manager.sendFeatureRequest(c,{item:p});Array.isArray(g)?d.push(...g):g&&d.push(g)}return{items:a,calls:d}});return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(n,null,2)}`}]}}catch(n){let i=n instanceof Error?n.message:String(n);return u.error(`handleCallHierarchy failed: ${i}`),{content:[{type:"text",text:`callHierarchy failed: ${i}`}],isError:!0}}}async handleCodeAction(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};u.info(`handleCodeAction: file=${t} line=${e.line} char=${e.character}`);try{let n=await this.withOpenFile(t,async o=>{let s={line:e.line,character:e.character};return this.manager.sendFeatureRequest(m.CODE_ACTION,{textDocument:{uri:o},range:{start:s,end:s},context:{diagnostics:[]}})});return{content:[{type:"text",text:n==null?"codeAction: no result":`codeAction: ${JSON.stringify(n,null,2)}`}]}}catch(n){return this.buildErrorResponse("codeAction",n)}}async handleRename(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};u.info(`handleRename: file=${t} line=${e.line} char=${e.character} newName=${e.newName}`);try{let n=await this.withOpenFile(t,async o=>{let s={line:e.line,character:e.character};if(await this.manager.sendFeatureRequest(m.PREPARE_RENAME,{textDocument:{uri:o},position:s})==null)throw new Error("Symbol at this position cannot be renamed");return this.manager.sendFeatureRequest(m.RENAME,{textDocument:{uri:o},position:s,newName:e.newName})});return{content:[{type:"text",text:n==null?"rename: no result":`rename: ${JSON.stringify(n,null,2)}`}]}}catch(n){return this.buildErrorResponse("rename",n)}}async handleTypeHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};u.info(`handleTypeHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let n=await this.withOpenFile(t,async o=>{let s=await this.manager.sendFeatureRequest(m.PREPARE_TYPE_HIERARCHY,{textDocument:{uri:o},position:{line:e.line,character:e.character}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],results:[]};let c=e.direction==="supertypes"?m.SUPERTYPES:m.SUBTYPES,d=[];for(let p of a){let g=await this.manager.sendFeatureRequest(c,{item:p});Array.isArray(g)?d.push(...g):g&&d.push(g)}return{items:a,results:d}});return{content:[{type:"text",text:`typeHierarchy (${e.direction}): ${JSON.stringify(n,null,2)}`}]}}catch(n){return this.buildErrorResponse("typeHierarchy",n)}}async handleCompletionItemResolve(e){if(!this.initialized)return this.buildNotReadyResponse();u.info("handleCompletionItemResolve");try{let t=await this.manager.sendFeatureRequest(m.COMPLETION_ITEM_RESOLVE,{item:e});return{content:[{type:"text",text:t==null?"completionItemResolve: no result":`completionItemResolve: ${JSON.stringify(t,null,2)}`}]}}catch(t){return this.buildErrorResponse("completionItemResolve",t)}}async handleInlayHint(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};try{let i=(await K.promises.readFile(t,"utf8")).split(`
1246
- `).length,o=await this.withOpenFile(t,async a=>this.manager.sendFeatureRequest(m.INLAY_HINT,{textDocument:{uri:a},range:{start:{line:0,character:0},end:{line:i,character:0}}}));return{content:[{type:"text",text:o==null?"inlayHint: no result":`inlayHint: ${JSON.stringify(o,null,2)}`}]}}catch(n){return this.buildErrorResponse("inlayHint",n)}}async handleDocumentLink(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};try{let n=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(m.DOCUMENT_LINK,{textDocument:{uri:o}}));return{content:[{type:"text",text:n==null?"documentLink: no result":`documentLink: ${JSON.stringify(n,null,2)}`}]}}catch(n){return this.buildErrorResponse("documentLink",n)}}buildErrorResponse(e,t){let n=t instanceof Error?t.message:String(t);return u.error(`${e} failed: ${n}`),{content:[{type:"text",text:`${e} failed: ${n}`}],isError:!0}}async withOpenFile(e,t){let n=$e(e),i=await K.promises.readFile(e,"utf8"),s=`deveco.apptool.${_.extname(e).replace(/^\./,"")||"plaintext"}`;u.debug(`withOpenFile didOpen uri=${n} len=${i.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:n,text:i,languageId:s,version:i.length}});try{return await t(n)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:n},isManual:!1})}}resolveSingleFile(e){let t=_.isAbsolute(e)?e:_.join(this.projectPath,e);return!K.existsSync(t)||!K.statSync(t).isFile()||!t.endsWith(".ets")?null:t}buildNotReadyResponse(){return{content:[{type:"text",text:this.initializing?"LSP \u6B63\u5728\u521D\u59CB\u5316\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5":this.projectPath?"LSP\u672A\u521D\u59CB\u5316":"\u6CA1\u6709\u914D\u7F6E\u5DE5\u7A0B\u8DEF\u5F84\uFF0C\u8BF7\u914D\u7F6EPROJECT_PATH\u53C2\u6570"}],isError:!0}}collectValidFiles(e,t){let n=this.projectPath,i=[];for(let o of e){let s=_.isAbsolute(o)?o:_.join(n,o);if(!K.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!K.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${o}`);continue}if(!s.endsWith(".ets")){t.push(`\u4E0D\u662F .ets \u6587\u4EF6: ${o}`);continue}i.push(s)}return i}async runDiagnosticsForFiles(e,t,n){for(let i of e){await Ps(500);try{let o=await this.checkFile(i);n.push(Ou(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(`
1247
- `)),t.length>0&&n.push(t.join(`
1248
- `));let i=n.join(`
1249
- `).trim(),o=e.length>0;return!o&&t.length===0&&(i="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:i}],isError:o}}async shutdown(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(t){u.warn(`Failed to dispose ArktsLspManager: ${t}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,n=t.method;if(n)switch(n){case"textDocument/publishDiagnostics":{this.handleDiagnosticsNotification(t.params);break}case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(ke),u.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{u.info("Received arkts/initialized");let i=this.initResolve;this.clearInitHandlers(),i?.();break}case"arkts/initializationFailed":{let o=t.params?.message??"unknown";u.error(`LSP initialization failed: ${o}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${o}`));break}case"workspace/didChangeConfiguration":u.info("Received workspace/didChangeConfiguration, sync deferred to next check");break;default:break}}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let n=this.popDiagnosticWaiter(t);if(!n&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;n=this.popDiagnosticWaiter(s)}if(!n)return;if(typeof e.errorMessage=="string"){u.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;u.debug(`diagnostics received uri=${t} count=${o}`),n.resolve(Array.isArray(i)?i:[])}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}getLogAndIndexPath(e){try{let t=_.join(tt(),"ArkTSCheck"),n=_.join(t,"mapping-config.properties"),i=Cs(e,n),o=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=_.join(t,"lsp-log",String(i),o),a=_.join(t,"lsp-index",String(i));return K.mkdirSync(s,{recursive:!0}),K.mkdirSync(a,{recursive:!0}),{logPath:te(s),indexPath:te(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function Mu(r){if(Array.isArray(r))return r;if(r&&typeof r=="object"){let e=r;if(e.kind==="full"&&Array.isArray(e.items))return e.items}return[]}function Ou(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 Lu}from"child_process";import*as R from"fs";import*as H from"path";import{z as ii}from"zod";var Zs=60*1e3,Nu=30*1e3,Hu=new Set(["textDocument/didOpen","textDocument/didChange","textDocument/didClose","textDocument/didSave"]),Fu=1e3,oi=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=>{u.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=te(this.projectPath),i=$e(n),o=H.basename(n)||"workspace",s={processId:null,clientInfo:{name:"devecocli-mcp-server",version:"1.3.0-Test.1"},rootPath:n,rootUri:i,workspaceFolders:[{uri:i,name:o}],capabilities:{}};await this.sendRequestToClangd("initialize",s,Zs),await this.sendNotificationToClangd("initialized",{}),this.backendReady=!0,this.wrapperState="proxying";for(let a of this.queuedDocumentNotifications)await this.writeToClangd(a);this.queuedDocumentNotifications.length=0,u.info("[CppCheck] clangd backend ready, switched to proxying mode")}async waitForBackendReady(){if(this.backendReady)return;let e=Zs,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=R.realpathSync(e)}catch{t=e}let n=$e(t),i=Es(t),o=await R.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}`))},Nu);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=>{u.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){u.warn(`[CppCheck] shutdown request failed: ${e}`)}try{await this.sendNotificationToClangd("exit",null)}catch(e){u.warn(`[CppCheck] exit notification failed: ${e}`)}try{this.clangdStdin.end()}catch(e){u.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}Hu.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(p){n(new Error(`Failed to encode LSP message: ${p}`));return}let o=Buffer.from(i,"utf8"),s=Buffer.from(`Content-Length: ${o.length}\r
1250
- \r
1251
- `,"ascii"),a=!1,c=p=>{a||(a=!0,p?n(p):t())};if(this.clangdStdin.write(Buffer.concat([s,o]),p=>{p?c(p):a||c()}))c();else{let p=()=>c();this.clangdStdin.once("drain",p)}})}handleClangdData(e){for(this.clangdBuffer=this.clangdBuffer.length===0?e:Buffer.concat([this.clangdBuffer,e]);;){let t=this.clangdBuffer.indexOf(`\r
1252
- \r
1253
- `);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){u.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=ju(n),o=this.diagnosticWaiters.get(i);if(o){this.diagnosticWaiters.delete(i),clearTimeout(o.timer);let s=Array.isArray(t.diagnostics)?t.diagnostics:[];u.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 ju(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 $u(r){let e=H.extname(r).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh","c++","h++"].includes(e)}function _u(r,e){let t=H.join(r,e.name);return e.isDirectory()?e.name===".cxx"||Xs(t):$u(t)}function Xs(r){if(!R.existsSync(r))return!1;try{return R.readdirSync(r,{withFileTypes:!0}).some(t=>_u(r,t))}catch{}return!1}function Qs(r){let t=new we(r).getAllModuleInfo(),n=[];for(let i of t){let o=i.srcPath.replace(/^\.\//,""),s=H.join(r,o);Xs(s)&&n.push(i)}return n}function Wu(r){let e=[],n=new we(r).getAllModuleInfo();for(let i of n){let o=i.srcPath.replace(/^\.\//,""),s=H.join(r,o,".cxx");R.existsSync(s)&&ea(s,e)}return e}function ea(r,e){try{let t=R.readdirSync(r,{withFileTypes:!0});for(let n of t){let i=H.join(r,n.name);n.isDirectory()?ea(i,e):n.name==="compile_commands.json"&&e.push(i)}}catch{}}function Uu(r){let e=[];for(let t of r)try{let n=R.readFileSync(t,"utf8"),i=JSON.parse(n);e.push(...i)}catch{}return e}function Bu(r,e){let t=H.join(r,...Yr.slice(0,-1));R.mkdirSync(t,{recursive:!0});let n=H.join(t,"compile_commands.json");R.writeFileSync(n,JSON.stringify(e,null,2),"utf8")}function zu(r){let e=Wu(r);if(e.length>0){let t=Uu(e);Bu(r,t),u.info(`[CppCheck] compile_commands.json \u5DF2\u751F\u6210\uFF0C\u5171 ${t.length} \u6761\u7F16\u8BD1\u547D\u4EE4`)}else u.warn("[CppCheck] \u672A\u627E\u5230\u4EFB\u4F55 compile_commands.json \u6587\u4EF6")}function qu(r){let e=new Set;for(let t of r)if(t.file)try{e.add(R.realpathSync(t.file))}catch{e.add(t.file)}return e}function Vu(r,e){try{let t=R.realpathSync(r);if(!e.has(t))return u.info(`[CppCheck] File not covered by compile_commands.json: ${r}`),!1}catch{}return!0}function Gu(r,e){if(!R.existsSync(r))return!1;try{let t=R.readFileSync(r,"utf8"),n=JSON.parse(t),i=qu(n);for(let o of e)if(!Vu(o,i))return!1;return!0}catch(t){return u.warn(`[CppCheck] Failed to read/parse compile_commands.json: ${t}`),!1}}async function Yu(r,e,t){let n=H.join(ee(e),"sdk"),i=process.execPath||"node",o=H.join(ee(e),"tools");u.info(`CppCheck devecoPath: ${e}, contentRoot: ${ee(e)}, sdkPath: ${n}, toolsDir: ${o}`);let s=H.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(" ");u.info(`[CppCheck] Running compileNative for module: ${a.name}`);let d=await ti(r,i,s,n,c);d.success?u.info(`[CppCheck] compileNative ${a.name} \u6210\u529F`):u.warn(`[CppCheck] compileNative ${a.name} \u5931\u8D25: ${d.output}`)}}async function Ju(r,e){let t=Qs(r);if(t.length===0){u.info("[CppCheck] \u672A\u53D1\u73B0\u542BC++\u7684\u6A21\u5757\uFF0C\u8DF3\u8FC7\u521D\u59CB\u5316");return}u.info(`[CppCheck] \u53D1\u73B0 ${t.length} \u4E2A\u542BC++\u7684\u6A21\u5757: ${t.map(n=>n.name).join(", ")}`),await Yu(r,e,t),zu(r)}var mt=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=vn(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:ii.object({files:ii.array(ii.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(`
1254
- `):"\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(`
1255
- `)}],isError:!0}}return await this.runDiagnosticsForFiles(o,i,t,n)&&this.shutdown().catch(a=>{u.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(`
1256
- `),e.join(`
1257
- `)].filter(o=>o.trim().length>0).join(`
1258
- `).trim()}],isError:n}}async ensureInitializedWithFiles(e){let t=te(this.projectPath);if(this.prepareCppCheck(t,e)){this.client&&this.initializedProjectPath&&(u.info("[CppCheck] Re-initializing C++ project due to file changes"),await this.shutdown());let i=this.devecoPath??ye();if(!i)throw new Error("DevEco Studio installation path not found");this.devecoPath=i,await Ju(t,i)}else if(this.client&&this.initializedProjectPath){let i=te(this.projectPath);if(this.initializedProjectPath===i)return this.client;await this.shutdown()}return this.doEnsureInitialized()}prepareCppCheck(e,t){let n=yn(e);return R.existsSync(n)?Qs(e).length===0?(u.info("[CppCheck] No cpp modules found, no initialization needed"),!1):Gu(n,t)?(u.info("[CppCheck] All files covered, no initialization needed"),!1):(u.info("[CppCheck] Files not fully covered by compile_commands.json, needs initialization"),!0):(u.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 oi,await this.client.initialize(e),this.initializedProjectPath=e,u.info(`[CppCheck] Client initialized in wrapper mode for workspace: ${e}`),this.startPollingForClangd(e)}resolveProjectRoot(){let e=ge(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);return this.projectPath=e,te(e)}startPollingForClangd(e){let t=yn(e);if(R.existsSync(t)){u.info("[CppCheck] compile_commands.json found, spawning clangd immediately"),this.spawnAndConnectClangd(e).catch(n=>{u.error(`[CppCheck] Immediate clangd spawn failed: ${n}`)});return}u.info("[CppCheck] compile_commands.json not found, starting poll..."),this.pollHandle=setInterval(()=>{if(!this.client||this.client.isClosed()||this.backendReady){this.stopPolling();return}R.existsSync(t)&&(this.stopPolling(),u.info("[CppCheck] compile_commands.json found via poll, spawning clangd..."),this.spawnAndConnectClangd(e).catch(n=>{u.error(`[CppCheck] Clangd spawn from poll failed: ${n}`)}))},Fu)}stopPolling(){this.pollHandle&&(clearInterval(this.pollHandle),this.pollHandle=null)}async spawnAndConnectClangd(e){let{clangdPath:t,compileCommandsDir:n}=this.resolveClangdPaths(e);u.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,u.info(`[CppCheck] clangd connected for workspace: ${e}`)}catch(o){if(u.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??ye();if(!t)throw new Error("DevEco Studio installation path not found");this.devecoPath=t;let n=bs(t);if(!n)throw new Error("clangd executable not found inside DevEco Studio SDK");let i=yn(e),o=H.dirname(i);return{clangdPath:n,compileCommandsDir:o}}spawnClangd(e,t,n){let i=Lu(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&&u.warn(`[CppLsp stderr] ${s}`)}),i.on("exit",(o,s)=>{u.warn(`[CppCheck] clangd exited code=${o} signal=${s??"null"}`),this.clangdProcess===i&&(this.clangdProcess=null,this.backendReady=!1)}),i.on("error",o=>{u.error(`[CppCheck] clangd spawn error: ${o}`)}),i}collectValidFiles(e,t){let n=this.projectPath,i=[];for(let o of e){let s=H.isAbsolute(o)?o:H.join(n,o);if(!R.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!R.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${o}`);continue}if(!wn(s)){t.push(`\u4E0D\u662F\u53D7\u652F\u6301\u7684 C/C++ \u6587\u4EF6: ${o}`);continue}try{i.push(R.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){u.warn(`[CppCheck] client.close() failed: ${n}`)}if(t&&!t.killed)try{t.kill()}catch(n){u.warn(`[CppCheck] failed to kill clangd: ${n}`)}}};import*as yt from"fs";import*as gt from"path";var Ku=1e3;function ta(r,e){if(e)return l.info(`[SyncGuard] ${P.ENV_FORCE_SYNC}=1, forcing sync`),{required:!0,reason:`${P.ENV_FORCE_SYNC}=1`};let t=gt.join(r,Us);if(!yt.existsSync(t))return l.info(`[SyncGuard] Baseline file not found: ${t}`),{required:!0,reason:"sync baseline file not found: "+t};let n=yt.statSync(t).mtimeMs;l.info(`[SyncGuard] Sync baseline: ${new Date(n).toISOString()} (${t})`);let i=Zu(r);if(i===null)return l.warn("[SyncGuard] Failed to parse build-profile.json5, falling back to sync"),{required:!0,reason:"failed to parse build-profile.json5"};let o=gt.join(r,P.OH_PACKAGE_JSON5),s=si(o,n,"root");if(s.required)return l.info(`[SyncGuard] Root check: ${s.reason}`),s;let a=gt.join(r,"build-profile.json5"),c=si(a,n,"build-profile");if(c.required)return l.info(`[SyncGuard] Build profile check: ${c.reason}`),c;for(let p of i){let g=gt.join(r,p.srcPath,P.OH_PACKAGE_JSON5),k=si(g,n,p.name);if(k.required)return l.info(`[SyncGuard] Module '${p.name}' check: ${k.reason}`),k}let d=`all oh-package.json5 files are up-to-date (sync baseline: ${new Date(n).toISOString()})`;return l.info(`[SyncGuard] ${d}`),{required:!1,reason:d}}function si(r,e,t){if(!yt.existsSync(r))return{required:!1,reason:`${t}: source not found, skip`};let n=yt.statSync(r).mtimeMs;return n-e>Ku?{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 Zu(r){let e=gt.join(r,"build-profile.json5");try{let t=z(e);if(typeof t!="object"||t===null)return null;let n=t.modules;return Array.isArray(n)?n.filter(i=>{if(typeof i!="object"||i===null)return!1;let o=i;return typeof o.name=="string"&&typeof o.srcPath=="string"}):null}catch{return null}}var ci=(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))(ci||{}),ai=3,na=600*1e3,nr=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,Lt(e.debug??!1);let t,n=e.projectPath?.trim()??"";this.originalProjectPath=n,n==="."?(t=process.cwd(),u.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):n===""?(t="",u.info("Constructor: configuredPath is empty, startPath remains empty")):(t=n,u.info(`Constructor: using configured path as startPath: '${t}'`));let i=ge(t);u.info(`Constructor: findHarmonyProject('${t}') => ${i??"null"}`),this.config.projectPath=i??void 0,this.server=new Xu({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=qr(),this.registerTools()}registerTools(){this.registerCheckTool(),this.registerLspFeatureTools()}registerCheckTool(){this.toolRouter.add({name:"check",description:"Perform static syntax analysis on HarmonyOS project source files and return structured diagnostics. Supported languages: ArkTS and C/C++.",inputSchema:W.object({files:W.array(W.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))}registerLspFeatureTools(){let e=W.object({file:W.string().describe("ArkTS (.ets) file path, relative to the project root"),line:W.number().describe("Line number (0-based)"),character:W.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:n,feature:i}of this.getPositionFeatures())this.toolRouter.add({name:t,description:n,inputSchema:e},async o=>this.handleLspFeatureCall(i,o));this.registerSymbolTools(),this.registerCallHierarchyTool()}getPositionFeatures(){return[{name:"hover",description:"Get hover information (type info, documentation) at a specific position in an ArkTS (.ets) file.",feature:"hover"},{name:"definition",description:"Find where the symbol at the given position is defined. Returns file path, line, and character.",feature:"definition"},{name:"declaration",description:"Find the declaration of the symbol at the given position. In ArkTS, this may differ from definition.",feature:"declaration"},{name:"references",description:"Find all references to the symbol at the given position across the HarmonyOS project.",feature:"references"},{name:"implementation",description:"Find implementations of the symbol at the given position (e.g., interface implementations).",feature:"implementation"}]}registerSymbolTools(){this.toolRouter.add({name:"workspaceSymbol",description:"Search for symbols by name across the entire HarmonyOS project.",inputSchema:W.object({query:W.string().describe("Symbol name (or partial) to search for")})},async e=>this.handleWorkspaceSymbolCall(e)),this.toolRouter.add({name:"documentSymbol",description:"Get the symbol tree (functions, classes, variables with ranges) of an ArkTS (.ets) file. Useful for file overview, structured code breakdown, and large file slicing.",inputSchema:W.object({file:W.string().describe("ArkTS (.ets) file path, relative to the project root")})},async e=>this.handleDocumentSymbolCall(e))}registerCallHierarchyTool(){this.toolRouter.add({name:"callHierarchy",description:'Query call hierarchy for a function at the given position. Use direction "incoming" to find callers, "outgoing" to find callees.',inputSchema:W.object({file:W.string().describe("ArkTS (.ets) file path, relative to the project root"),line:W.number().describe("Line number (0-based)"),character:W.number().describe("Character offset in the line (0-based)"),direction:W.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}validateContainment(e){let t=this.config.projectPath;if(t){let i=[];for(let o of e){let s=D.isPathContainedWithSymlink(o,t);s.contained||(u.warn(`Containment check failed: ${s.reason}`),i.push(s.reason))}return i.length>0?{content:[{type:"text",text:i.join(`
1259
- `)}],isError:!0}:null}let n=e.filter(i=>vt.isAbsolute(i));return n.length>0?(u.warn(`Absolute paths rejected (no project root): ${n.join(", ")}`),{content:[{type:"text",text:n.map(i=>`Absolute path is not allowed: ${i}`).join(`
1260
- `)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(g=>typeof g=="string"):[];if(t.length===0)return u.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}=ep(t);s.length>0&&u.warn(`Unsupported file types in check request: ${s.join(", ")}`);let a=s.map(g=>`Unsupported file type: ${g} (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(`
1258
+ ${o}`)}if(r.length===1){let i=r[0];return m(Ko(`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(r))}async getConnectedDeviceSerials(){let e=await this.deviceManager.listDevices();if(e.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");return e.map(t=>t.serial)}async getConnectedDevices(){let e=await this.deviceManager.listDevicesWithName();if(e.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");return e}async getPidForBundle(e,t,r){m(`Retrieving PID for bundle ${r}`),P.assertBundleName(r);let i=await Ae(e,["-t",t,"shell","pidof",r]),o=fn(i,"Failed to look up PID");if(o)throw o;if(i.exitCode===0&&i.stdout.trim()){let s=i.stdout.trim(),a=s.split(/\s+/)[0]||s;return m(`Found PID for ${r}: ${a}`),a}return m(`No PID found for bundle: ${r}`),null}async resizeHilogBuffer(e,t,r){m(`Setting hilog buffer size to: ${r}`);let i=await Ae(e,["-t",t,"shell","hilog","-G",r]),o=fn(i,"Failed to resize hilog buffer");if(o)throw o;i.exitCode!==0&&console.error(`Failed to resize hilog buffer: ${i.stderr||i.stdout}`)}buildHilogCommand(e,t,r,i){let o=this.buildHilogShellCommand(r,i);return[e,["-t",t,"shell",o]]}buildHilogShellCommand(e,t){let r=["hilog"];return e.isFollow||r.push("-x"),e.tag&&(P.assertHilogToken(e.tag,"tag"),r.push("-T",e.tag)),e.level&&(P.assertHilogLevel(e.level),r.push("-L",e.level)),e.domain&&(P.assertHilogToken(e.domain,"domain"),r.push("-D",e.domain)),t&&r.push("-P",t),e.keyword&&(P.assertHilogKeyword(e.keyword),r.push("-e",P.quotePosixShellArg(e.keyword))),r.join(" ")}async followHilog(e,t,r,i,o){let a=await au(e,t,{onData:r,onError:i,onClose:o});return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}async runHilogWithSpawnRetry(e,t,r,i,o){let s=1+_c.length,a={stdout:"",stderr:"",exitCode:-1};for(let c=0;c<s;c++){if(a=await this.followHilog(e,t,r,i,o),a.exitCode===0||Ln(a.stderr)!=="transient"||c>=s-1)return a;m(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${_c[c]}ms`),await WE(_c[c])}return a}async runHilogStreamingCollect(e,t,r){return this.runHilogWithSpawnRetry(e,t,()=>{},i=>{m(`Callback triggered when an error occurs during ${r}: ${i.message}`)},()=>{})}async printTailSnapshotIfNeeded(e,t,r,i){if(!r.tail&&!r.fromSeconds&&!r.toSeconds)return;let o={...r,isFollow:!1},[s,a]=this.buildHilogCommand(e,t,o,i);m(`Ready to run hilog snapshot command: ${s} ${a.join(" ")}`);let c=await this.runHilogStreamingCollect(s,a,"a hilog snapshot streaming read"),l=fn(c,"Failed to get hilog");if(l)throw l;if(c.exitCode!==0&&c.stderr)throw new Error(`Failed to get hilog: ${c.stderr}`);let p=P.filterLogsByRelativeWindow(c.stdout||c.stderr,r.fromSeconds,r.toSeconds);p=P.getLastLines(p,r.tail),p.trim()&&console.log(p)}async getHilogOnce(e,t,r,i){let[o,s]=this.buildHilogCommand(e,t,r,i);m(`Ready to run hilog command: ${o} ${s.join(" ")}`);let a=await this.runHilogStreamingCollect(o,s,"a single hilog streaming read"),c=fn(a,"Failed to get hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to get hilog: ${a.stderr}`);let l=a.stdout||a.stderr,p=P.filterLogsByRelativeWindow(l,r.fromSeconds,r.toSeconds);return p=P.getLastLines(p,r.tail),p}async runHilogFollow(e,t,r,i){try{await this.printTailSnapshotIfNeeded(e,t,r,i)}catch(l){console.error(`Warning: Failed to fetch log snapshot, continuing with live stream: ${l.message}`)}let[o,s]=this.buildHilogCommand(e,t,r,i);m(`Ready to run hilog command which contain \`follow\` and \`tail\`: ${o} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(o,s,this.createFollowLineHandler(),l=>{m(`Spawn error during hilog follow: ${l.message}`)},()=>{}),c=fn(a,"Failed to follow hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to follow hilog: ${a.stderr}`);return""}async getHilog(e,t){let r=this.toolProvider.hdcPath,i=t.bundleName?await this.getPidForBundle(r,e,t.bundleName):void 0;if(t.bundleName&&!i)throw new 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(r,e,t.logSize),t.isFollow?await this.runHilogFollow(r,e,t,i||""):await this.getHilogOnce(r,e,t,i||"")}async getCrashLog(e,t){m(`Fetching crash logs from device: ${e}`);let r=this.toolProvider.hdcPath,i=await this.listCrashLogs(r,e,t);if(i.length===0)return t?`No crash logs found for bundle '${t}'.`:"No crash logs found.";let s=[...i].sort((c,l)=>{let p=c.split("-").pop()||"";return(l.split("-").pop()||"").localeCompare(p)})[0],a=await this.fetchCrashLogContent(r,e,s);return`--- Latest Crash Log File: ${s} ---${a}`}async listCrashLogs(e,t,r){let i=["-t",t,"shell","hidumper","-s","1201","-a","-p Faultlogger"];m(`Running command: ${e} ${i.join(" ")}`);let o=await this.runHilogStreamingCollect(e,i,"a crash log list streaming read"),s=fn(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:
1259
+ ${o.stdout}`),this.parseCrashLogFilenames(o.stdout,r)}parseCrashLogFilenames(e,t){return e.split(`
1260
+ `).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>{try{return P.assertCrashFilename(r),!0}catch{return!1}}).filter(r=>t?r.toLowerCase().includes(t.toLowerCase()):!0)}async fetchCrashLogContent(e,t,r){m(`Fetching latest crash log file: ${r}`);let i=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];m(`Executing command: ${e} ${i.join(" ")}`);let o=await this.runHilogStreamingCollect(e,i,"a crash log streaming read"),s=fn(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 Fc,red as ff}from"colorette";import VE from"ora";function zE(n){try{return P.parsePositiveInteger(n,"tail")}catch{throw new pf("`tail` must be a positive integer.")}}function uf(n,e){try{return P.parseDurationToSeconds(n,e)}catch{throw new pf(`${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 qE(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.")}async function YE(n,e,t,r,i){return t.crash?await n.getCrashLog(e,t.bundleName):await n.getHilog(e,{level:t.level,bundleName:t.bundleName,keyword:t.keyword,isFollow:!!t.follow,tail:t.tail,fromSeconds:r,toSeconds:i})}function JE(n,e,t,r){let i=P.filterLogsByRelativeWindow(n,t,r);return e.tail?P.getLastLines(i,e.tail):i}var KE=new GE("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(ff(n))}).option("--device <device>","Target device (name or serial)").option("--crash","Only obtain crash logs").option("--level <level>","Log level filter: D, I, W, E, F").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",zE).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>uf(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>uf(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await XE(n)});async function XE(n){let e=VE({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),qE(n);let r=n.from,i=n.to,o=await I.new(),s=new zn(o),a=await s.selectDevice(n.device);a||(t(),process.exit(1)),m(Fc(`deviceId: ${a}`)),m(Fc(`type: ${n.crash?"Crash logs":"Common logs"}`)),m(Fc("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await YE(s,a,n,r,i);t(),n.crash&&c&&(c=JE(c,n,r,i)),c&&console.log(c)}catch(r){t(),console.error(ff(r.message)),process.exit(1)}}var mf=KE;import ti from"path";import wt from"fs";import $c from"process";import Pf from"os";import{Command as db}from"commander";import{green as vf,red as jc,cyan as ub,yellow as Sf}from"colorette";import te from"fs-extra";import M from"path";import*as gf from"os";import{fileURLToPath as ZE}from"url";var hf={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"}},QE=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function eb(){let n=import.meta.url,e=ZE(n);if(e.includes("dist")){let o=M.dirname(e),s=M.dirname(o);return M.join(s,"templates","application")}let t=M.dirname(e),r=M.dirname(t),i=M.dirname(r);return M.join(i,"templates","application")}function yf(n,e){te.mkdirSync(e,{recursive:!0});for(let t of te.readdirSync(n,{withFileTypes:!0})){let r=M.join(n,t.name),i=M.join(e,t.name);if(t.isDirectory()){yf(r,i);continue}te.existsSync(i)||(te.mkdirSync(M.dirname(i),{recursive:!0}),te.copyFileSync(r,i))}}function ei(n,e){let t=te.readFileSync(n,"utf-8"),r=t;for(let[i,o]of e)r=r.replaceAll(i,o);r!==t&&te.writeFileSync(n,r,"utf-8")}function tb(n){if(hf[n])return hf[n];if(n>=26){let e=`${n}.0.0`;return{sdkVersion:e,modelVersion:e}}}function nb(n,e){if(e===22)return;let t=tb(e);t&&(ei(M.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),ei(M.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),ei(M.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function rb(n){return QE.filter(t=>!te.existsSync(M.join(n,t))).length===0}function ib(){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 ob(n){return gf.platform()==="darwin"?M.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):M.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function sb(n,e){let t=ob(e);if(!te.existsSync(t))return!1;let r=[["AppScope/resources/base/media/background.png","AppScope/resources/base/media/background.png"],["AppScope/resources/base/media/foreground.png","AppScope/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/background.png"],["entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/startIcon.png","entry/src/main/resources/base/media/startIcon.png"]];for(let[i,o]of r){let s=M.join(t,i),a=M.join(n,o);te.existsSync(s)&&(te.mkdirSync(M.dirname(a),{recursive:!0}),te.copyFileSync(s,a))}return!0}function ab(n){let e=ib(),t=["AppScope/resources/base/media/background.png","AppScope/resources/base/media/foreground.png","entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/startIcon.png"];for(let r of t){let i=M.join(n,r);te.mkdirSync(M.dirname(i),{recursive:!0}),te.writeFileSync(i,e)}}function cb(n,e){e&&sb(n,e)||ab(n)}function lb(n){let e=[M.join(n,"gitignore.txt"),M.join(n,"entry","gitignore.txt")];for(let t of e)if(te.existsSync(t)){let r=M.dirname(t);te.renameSync(t,M.join(r,".gitignore"))}}function wf(n,e,t,r,i){let o=eb();if(!te.existsSync(o))throw new Error(`Template directory not found: ${o}`);te.mkdirSync(n,{recursive:!0}),yf(o,n),lb(n),cb(n,i),ei(M.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),ei(M.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),nb(n,r);let s=rb(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function pb(n){if(n.length<1||n.length>200)throw new Error(`App name length must be 1-200 characters. Current: ${n.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(n))throw new Error("Application name must start with a letter (a-z, A-Z) and contain only letters, digits, and underscores")}function fb(n){if(n.length<7||n.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${n.length}`);if(n.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example").');let e=n.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 r=0;r<e.length;r++){let i=e[r];if(!t.test(i))throw new Error(`Segment "${i}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(r===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 Cf(n){if(Pf.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function Ef(n){if(n.length===0)throw new Error("Project path cannot be empty.");if(n.length>120)throw new Error(`Project path cannot exceed 120 characters (current: ${n.length}).`);let e=Pf.platform();if(!(e==="win32"?/^[a-zA-Z0-9._\-:\\/]+$/:/^[a-zA-Z0-9._\-/]+$/).test(n)){let o=e==="win32"?"letters, digits, dots, underscores, hyphens, colons, slashes (/) or backslashes (\\)":"letters, digits, dots, underscores, hyphens or slashes (/)";throw new Error(`Project path can only contain ${o}.`)}let r=Cf(n);if(/[\u4e00-\u9fff]/.test(r))throw new Error("Project path cannot contain Chinese characters.");if(r.endsWith("."))throw new Error("Project path cannot end with a dot (.)")}function mb(n){let e=n,t=ti.parse(n).root;for(;e!==t;){if(wt.existsSync(e))return e;e=ti.dirname(e)}return wt.existsSync(t)?t:null}function bf(n){let e=mb(n);if(!e)throw new Error(`No existing parent directory found for '${n}'. Cannot create project directory.`);try{wt.accessSync(e,wt.constants.W_OK)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}let t=ti.join(e,`.deveco_write_test_${Date.now()}`);try{wt.writeFileSync(t,"test"),wt.unlinkSync(t)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}}function hb(n){return`com.example.${n.toLowerCase()}`}function gb(n,e){if(e){let i=Cf(e),o=ti.resolve(i);if(wt.existsSync(o)){if(wt.readdirSync(o).length>0)throw new Error(`Directory '${o}' is not empty. Cannot create project here.`)}else bf(o);return o}let t=$c.cwd(),r=ti.join(t,n);if(wt.existsSync(r))throw new Error(`Directory '${r}' already exists. Cannot create project here.`);return bf(r),r}function yb(n,e){let t=e?.getMaxApiLevel(),r=23;if(n.apiLevel){let i=Number(n.apiLevel);if(!Number.isInteger(i)||i<17)throw new Error(`Invalid API version ${n.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(i>t)throw new Error(`Invalid API version ${n.apiLevel}. Your SDK supports API version 17-${t}`)}else if(i>r)throw new Error(`Invalid API version ${n.apiLevel}. Without DevEco Studio, supported range is API version 17-${r}`);return i}return t!==void 0?t:23}async function wb(){try{return await I.new()}catch(n){console.error(Sf(`DevEco Studio not found: ${n.message}`)),console.log(Sf("Use placeholder API level instead."));return}}var vb=new db("create").description("Scaffold a new HarmonyOS application project").option("--project-path <path>","Project directory path (default: ./<app-name>)").option("--app-name <name>","Application name").option("--bundle-name <bundle>","Bundle name (auto-derived as com.example.<app-name> if omitted)").option("--api-level <level>","API level (auto-detected from SDK if omitted; minimum: 17)").action(async n=>{try{n.appName||(console.error(jc("Error: --app-name is required")),$c.exit(1));let e=n.appName;pb(e);let t=n.bundleName||hb(e);fb(t),n.projectPath&&Ef(n.projectPath);let r=gb(e,n.projectPath);Ef(r),console.log(ub("Initializing project...")),console.log(`Project path: ${r}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let i=await wb(),o=yb(n,i);console.log(`API level: ${o}`);let s=i?.devecoStudioPath,a=wf(r,e,t,o,s);console.log(`
1261
+ `+vf("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(vf("Template integrity check passed."))}catch(e){let t=e;console.error(jc(`
1262
+ Failed to create project.`)),console.error(jc(t.message)),$c.exit(1)}}),If=vb;import{Command as Ab}from"commander";import{red as Db,cyan as Lf}from"colorette";import Sb from"fs";import Xo from"path";import{cyan as Eb}from"colorette";import*as Zo from"smol-toml";var qn=Sb.promises;async function bb(n){try{let e=await qn.readFile(n,"utf8");return e.trim()===""?{}:JSON.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read configuration file ${n}: ${e.message}`,{cause:e})}}async function Pb(n){try{let e=await qn.readFile(n,"utf8");return e.trim()===""?{}:Zo.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read TOML config file ${n}: ${e.message}`,{cause:e})}}async function Cb(n,e){let t=Xo.dirname(n);await qn.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await qn.writeFile(n,r,"utf8")}async function Ib(n,e){let t=Xo.dirname(n);await qn.mkdir(t,{recursive:!0});let r=Zo.stringify(e);await qn.writeFile(n,r,"utf8")}function Af(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function Df(n,e,t,r,i){(!n[e]||typeof n[e]!="object")&&(n[e]={});let o=n[e];return t in o&&!i?!1:(o[t]=r,!0)}async function Rf(n,e){return n.format==="codex"?Pb(e):bb(e)}async function kf(n,e,t){return n.format==="codex"?Ib(e,t):Cb(e,t)}async function Tf(n,e,t=!1){let r=Rt[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Rt).join(", ")}`};if(!r.supportsGlobal)return{success:!1,error:`${r.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`};try{let i=await Rf(r,r.globalConfigPath);if(Af(i,r.mcpServersKey,it)&&!t)return console.log(`MCP server ${it} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let o=Xi(r,void 0);return Df(i,r.mcpServersKey,it,o,t),await kf(r,r.globalConfigPath,i),console.log(`MCP server ${it} configured in ${r.globalConfigPath}.`),{success:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"}}catch(i){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${i.message}`}}}async function Hc(n,e,t=!1){let r=Rt[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Rt).join(", ")}`};let i=Xo.isAbsolute(r.projectConfigPath)?r.projectConfigPath:Xo.join(e,r.projectConfigPath);try{let o=await Rf(r,i);if(Af(o,r.mcpServersKey,it)&&!t)return console.log(`MCP server ${it} already configured in ${i}.`),{success:!0,skipped:!0,configPath:i,agentName:n,installType:"project"};let s=Xi(r,e);return Df(o,r.mcpServersKey,it,s,t),await kf(r,i,o),console.log(`MCP server ${it} configured in ${i}.`),{success:!0,configPath:i,agentName:n,installType:"project"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${o.message}`}}}function xf(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(Eb("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`);for(let i of n)!i.success&&i.error&&console.error(` - ${i.agentName??"unknown"}: ${i.error}`);r>0&&(process.exitCode=1)}var Uc="deveco-cli";async function Rb(n,e,t){if(n.customPath)return[await Qp(Uc,e,n.customPath,t.force)];let r=[...n.projectAgents.map(({project:s,agent:a})=>()=>Zp(Uc,e,s,a,t.force)),...n.agents.map(s=>()=>Xp(Uc,e,s,t.force))],i=5,o=[];for(let s=0;s<r.length;s+=i){let a=r.slice(s,s+i);o.push(...await Promise.all(a.map(c=>c())))}return o}async function kb(n,e,t){let r=[];for(let{project:i,agent:o}of n.projectAgents){let s=await Hc(o,i,t);r.push(s)}for(let i of n.agents){let o=await Hc(i,e,t);r.push(o)}return r}async function Tb(n,e){let t=[];for(let r of n){if(!Rt[r])continue;let o=await Tf(r,process.cwd(),e);t.push(o)}return t}async function xb(n,e,t){if(t.agent&&t.agent.split(",").map(l=>l.trim()).includes("qoder"))throw new Error("Qoder does not support MCP configuration via DevEco CLI. Use other supported agents instead.");let r=t.force??!1,i=n.projectAgents.filter(c=>c.agent!=="qoder"),o=n.agents.filter(c=>c!=="qoder"),s={...n,projectAgents:i,agents:o},a=e?await kb(s,e,r):await Tb(s.agents,r);a.length>0&&(console.log(Lf("MCP Configuration:")),xf(a))}async function Lb(n){if(n.skill&&n.mcp)throw new Error("Cannot use `--skill` and `--mcp` together. Use `--skill` for skill installation only, or `--mcp` for MCP configuration only.");let{resolvedPath:e,resolvedProject:t}=Xr(n.path,n.project,n.agent);t&&_t(t,"Project directory",n.force),e&&_t(e,"Directory",n.force);let r=await Yo(n,e,t);if(n.mcp){await xb(r,t,n);return}let i=rf(),o=await Rb(r,i,n);console.log(),o.length>0&&(console.log(Lf("Skill Installation:")),Kr(o))}var Nb=new Ab("init").description("Install the deveco-cli skill or configure the deveco-mcp server into AI agents").option("--agent <agents>","Target agents, comma-separated; installs to all available agents if omitted").option("--project <path>","Project root directory for skill or MCP configuration").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").option("--skill","Install the deveco-cli skill only (same as default behavior; explicit for symmetry with --mcp)").option("--mcp","Configure the deveco-mcp server (syntax checking for .ets and C/C++) only; no skill installation").option("-f, --force","Overwrite existing skill/MCP configuration").action(async n=>{try{await Lb(n)}catch(e){console.error(Db(e.message)),process.exit(1)}}),Nf=Nb;import{Command as DP}from"commander";import{McpServer as uP}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as pP}from"@modelcontextprotocol/sdk/server/stdio.js";import*as Ns from"path";import{z as ue}from"zod";var Qo=class{tools=new Map;add(e,t){return this.tools.set(e.name,{definition:e,handler:t}),this}getAll(){return Array.from(this.tools.values())}registerToServer(e){for(let{definition:t,handler:r}of this.getAll())e.registerTool(t.name,{description:t.description,inputSchema:t.inputSchema},(async i=>r(i)))}};function Bc(){return new Qo}import*as Re from"fs";import*as De from"path";import{z as zc}from"zod";function Of(n){return"method"in n&&!("id"in n)}import{spawn as Ob}from"child_process";import{EventEmitter as Mb}from"events";import*as Yn from"fs";import*as Mf from"path";var Ft=class extends Mb{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;ensureDirectories(){let t=Mf.join(this.config.logPath,"lspLog");return Yn.existsSync(t)||Yn.mkdirSync(t,{recursive:!0}),Yn.existsSync(this.config.indexingDataLocation)||Yn.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){let r=this.ensureDirectories();f.info(`[LspClient] serverMaxSize=${t}MB`);let i=j(r),o=["--expose-gc",`--max-old-space-size=${t}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${i}`,this.config.serverPath,"--stdio",`--logger-path=${i}`,"--logger-level=TRACE"];f.info(`[LspClient] Starting process: node ${o.join(" ")}`);let s=process.execPath??"node";f.info(`[LspClient] nodePath: ${s}`),this.process=Ob(s,o,{cwd:this.config.cwd||process.cwd(),stdio:["pipe","pipe","pipe"],windowsHide:!0}),this.bindProcessEvents(),await new Promise(a=>setTimeout(a,500)),f.info("[LspClient] start lsp process success")}attachProcess(t,r){if(this.process)throw new Error("[LspClient] process already attached");this.process=t,this.bindProcessEvents(r?.stderrAsError??!0),f.info("[LspClient] attached to external process")}bindProcessEvents(t=!0){this.process&&(this.process.stdout?.on("data",r=>{this.handleData(r)}),this.process.stderr?.on("data",r=>{let i=r.toString("utf8").trim();f.error(`[LspClient] stderr: ${i}`),!this.isClosing&&t&&this.emit("error",new Error(`[LspClient] stderr: ${i}`))}),this.process.on("exit",r=>{f.info(`[LSP EXIT] code=${r}`),this.isClosing||this.emit("error",new Error(`LSP process exited with code ${r}`))}))}sendRaw(t,r){if(!this.process?.stdin?.writable){f.warn("[LspClient] Cannot send message, stdin not writable");return}f.info(`[LspClient] send message: ${r}`);let i=this.buildLspMessage(t);this.process.stdin.write(i,"utf8")}send(t,r,i){let o={jsonrpc:"2.0",method:t,params:r};i!==void 0&&(o.id=i),this.sendRaw(JSON.stringify(o),t)}sendNotification(t,r){this.sendRaw(JSON.stringify({jsonrpc:"2.0",method:t,params:r}),t)}sendRequest(t,r,i){this.sendRaw(JSON.stringify({jsonrpc:"2.0",id:i,method:t,params:r}),t)}buildLspMessage(t){return`Content-Length: ${Buffer.from(t,"utf8").length}\r
1263
+ \r
1264
+ ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this.buffer.indexOf(`\r
1265
+ \r
1266
+ `);if(r===-1)break;let o=this.buffer.slice(0,r).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!o){f.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(r+4);continue}let s=parseInt(o[1],10),a=r+4,c=a+s;if(this.buffer.length<c)break;let l=this.buffer.slice(a,c).toString("utf8"),p=this.recoverFramedJson(l);if(p&&p.rest.length>0){f.warn(`[LspClient] recovered mixed LSP frame, bodyLen=${l.length}, restLen=${p.rest.length}`),this.emit("message",p.json),this.buffer=Buffer.concat([Buffer.from(p.rest,"utf8"),this.buffer.slice(c)]);continue}this.emit("message",l),this.buffer=this.buffer.slice(c)}}waitForExitOrTimeout(t){let r=this.process;return!r||r.exitCode!==null||r.signalCode!==null?Promise.resolve():new Promise(i=>{let o=!1,s=()=>{o||(o=!0,clearTimeout(c),r.off("exit",a),i())},a=()=>s();r.once("exit",a);let c=setTimeout(s,t)})}recoverFramedJson(t){let r=t.search(/\S/);if(r<0||t[r]!=="{"&&t[r]!=="[")return null;let i=0,o=!1,s=!1;for(let a=r;a<t.length;a++){let c=t[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(o=!1);continue}if(c==='"'){o=!0;continue}if(c==="{"||c==="["){i++;continue}if((c==="}"||c==="]")&&(i--,i===0)){let l=t.slice(r,a+1),p=t.slice(a+1);return{json:l,rest:p}}}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 jt=class{callbacks=new Map;pending=new Map;timeouts=new Map;registerPending(e,t,r){return new Promise((i,o)=>{let s;r>0&&(s=setTimeout(()=>{this.pending.delete(e),this.timeouts.delete(e),o(new Error(`LSP request '${t}' (id=${e}) timeout after ${r}ms`))},r),this.timeouts.set(e,s)),this.pending.set(e,{resolve:i,reject:o,method:t,timer:s})})}resolvePending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.resolve(t),this.pending.delete(e),!0):!1}rejectPending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.reject(t),this.pending.delete(e),!0):!1}register(e,t){this.callbacks.set(e,t)}emit(e,t,r){f.info(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let i=this.callbacks.get(e);if(i)i(t,r),this.callbacks.delete(e);else{let o=[...this.callbacks.keys()].map(s=>String(s));f.info(`[RequestCallbackManager] emit: NO callback for key='${e}', registered keys=[${o.join(",")}]`)}}registerTimeout(e,t,r,i){let o=this.timeouts.get(e);o&&clearTimeout(o);let s=setTimeout(()=>{f.info(`[RequestCallbackManager] timeout, key=${e}, method=${t}`),i(),this.timeouts.delete(e)},r);this.timeouts.set(e,s)}clearTimeout(e){let t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e))}deleteCallback(e){this.callbacks.delete(e)}hasCallback(e){return this.callbacks.has(e)||this.pending.has(e)}clear(e){this.clearTimeout(e);let t=this.pending.get(e);t&&(t.reject(new Error(`Request '${t.method}' (id=${e}) cancelled`)),this.pending.delete(e)),this.callbacks.delete(e)}rejectAll(e){for(let[,t]of this.pending)t.reject(e);this.pending.clear();for(let[,t]of this.timeouts)clearTimeout(t);this.timeouts.clear(),this.callbacks.clear()}};var es=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var Jn=class{map=new Map;register(e,t){let r=this.map.get(e);r||(r=new Set,this.map.set(e,r)),r.add(t)}unregister(e,t){let r=this.map.get(e);r&&(t!==void 0?r.delete(t):r.clear(),r.size===0&&this.map.delete(e))}invoke(e,...t){let r=this.map.get(e);if(r)for(let i of r)try{i(...t)}catch(o){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,o)}}invokeOnce(e,...t){this.invoke(e,...t),this.unregister(e)}clear(){this.map.clear()}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}};function D(n){return typeof n=="object"&&n!==null}var _f=20*1e3,_b=30*1e3,ts=class{client;nextRequestId=1;stopOnce=null;callbacks=new Jn;requestCallbacks=new jt;diagnosticMap=new Map;initProgressReset=null;constructor(e){this.client=new Ft(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{f.info("[ClientMessageHandle] Sending shutdown request"),this.client.sendRequest(y.SHUTDOWN,null,this.nextRequestId++),f.info("[ClientMessageHandle] Sending exit notification"),this.client.sendNotification(y.EXIT,null),f.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),f.info("[ClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(y.BROADCAST),this.callbacks.register(y.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(y.BROADCAST,e)}async sendInitialize(e){let t=this.nextRequestId++,r=this.requestCallbacks.registerPending(t,y.INITIALIZE,Le);return this.client.sendRequest(y.INITIALIZE,e,t),r}sendInitializeResettable(e,t){let r=this.nextRequestId++,i=this.requestCallbacks.registerPending(r,y.INITIALIZE,0);return this.client.sendRequest(y.INITIALIZE,e,r),new Promise((o,s)=>{let a,c=()=>{a=setTimeout(()=>{this.initProgressReset=null,s(new Error(`LSP initialization timeout after ${t}ms`))},t)},l=()=>{clearTimeout(a),c()};this.initProgressReset=l,c(),i.then(()=>{clearTimeout(a),this.initProgressReset=null,o()},p=>{clearTimeout(a),this.initProgressReset=null,s(p)})})}sendInitialized(){this.client.sendNotification(y.INITIALIZED,{})}sendDidOpen(e){let t=e.textDocument.uri;this.diagnosticMap.has(t)||(this.diagnosticMap.set(t,new es(t)),this.registerDiagnosticTimeout(t)),this.client.sendNotification(y.DID_OPEN,e)}sendDidChange(e){let t=e.textDocument.uri,r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t)),this.client.sendNotification(y.DID_CHANGE,e)}closeFile(e){this.cleanupDiagnosticState(e.textDocument.uri),this.client.sendNotification(y.DID_CLOSE,e)}sendLspRequest(e,t,r=_b){let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,r);return this.client.sendRequest(e,t,i),o}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}onDidChangeWatchedFiles(e){e.length!==0&&this.client.sendNotification(y.WORKSPACE_DID_CHANGE_WATCHED_FILES,{changes:e})}sendDidChangeConfiguration(e){this.client.sendNotification(y.WORKSPACE_DID_CHANGE_CONFIGURATION,{settings:e})}sendNotification(e,t){this.client.sendNotification(e,t)}getDiagnosticMessages(e){let t=this.diagnosticMap.get(e);return t?t.get():[]}clearDiagnostic(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let i=r instanceof Error?r.message:String(r);f.error(`[LSP] JSON parse error: ${i}, raw: ${e}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotificationOrRequest(t):f.warn(`[LSP] Unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t===void 0)return;let r=t;if(e.error){let i=new Error(`LSP error ${e.error.code}: ${e.error.message}`);this.requestCallbacks.rejectPending(r,i)}else this.requestCallbacks.resolvePending(r,e.result)}handleNotificationOrRequest(e){let t=e.method;if(t)switch(this.initProgressReset?.(),t){case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.handleProgress(e.params);break;case y.WINDOW_SHOW_MESSAGE:f.info(`[LSP] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:f.info(`[LSP] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.broadcastToClients(e)}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=e.uri,r=this.diagnosticMap.get(t);if(!r)return;let i=e.diagnostics||[];this.normalizeDiagnostics(i),r.set(i),this.finalizeDiagnostic(t,i)}normalizeDiagnostics(e){for(let t of e)if(t.severity!==void 0){let r={1:"Error",2:"Warning",3:"Information",4:"Hint"};t.severityStr=r[t.severity]||"Unknown"}}handleProgress(e){D(e)&&this.broadcastToClients({jsonrpc:R,method:y.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,y.PUBLISH_DIAGNOSTICS,_f,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${_f}ms, uri: ${e}`)})}finalizeDiagnostic(e,t,r){let i={uri:e,diagnostics:t,...r?{errorMessage:r}:{}};this.requestCallbacks.emit(e,y.PUBLISH_DIAGNOSTICS,i),this.diagnosticMap.get(e)?.clear()}handleError(e){let t=Array.from(this.diagnosticMap.keys()).filter(r=>this.requestCallbacks.hasCallback(r));if(t.length>0){let r={range:{start:{line:0,character:0},end:{line:0,character:0}},severity:1,message:e.message};for(let i of t)this.finalizeDiagnostic(i,[r]);return}this.broadcastToClients({jsonrpc:R,method:y.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var ns=class{uri;messages=[];receivedTypes=new Set;uniqueMessages=new Set;isFromEditor=!1;constructor(e){this.uri=e}setReceivedType(e){this.receivedTypes.add(e)}addMessage(e,t){this.receivedTypes.add(e);let r=`${e}:${t}`;if(this.uniqueMessages.has(r)){f.info(`[LegacyDiagnostic] addMessage: duplicate message=${r}`);return}this.uniqueMessages.add(r),this.messages.push(new Wc(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)}},Wc=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var Fb={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"},jb={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate",ON_FORCE_OPEN_FILE:"aceProject/onForceOpenFile",ON_PACKAGE_CHANGE_FINISH:"aceProject/onPackageChangeFinish",TEXT_DOCUMENT_ON_ASYNC_DEFINITION:"textDocument/onAsyncDefinition",ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:"textDocument/onDidChangePackageDependencies",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",REFERENCES:"textDocument/references",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",BROADCAST:"lsp/broadcast",ARKTS_ERROR:"arkts/error",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing"},k={...Fb,...jb},$t={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"},Ff=new Set([1e3,2e3,3e3,3001]);function $b(n){if(!D(n))return!1;let e=n.textDocument;return D(e)&&typeof e.uri=="string"}function Hb(n){return D(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function Ub(n){return D(n)&&typeof n.moduleName=="string"&&typeof n.current=="number"&&typeof n.total=="number"?`indexing module '${n.moduleName}', ${n.current} of total ${n.total} modules`:`params=${JSON.stringify(n??null)}`}var rs=class n{client;isInitialized=!1;stopOnce=null;callbacks=new Jn;requestCallbacks=new jt;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;constructor(e){this.client=new Ft(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{f.info("[LegacyClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:k.EXIT,params:{}}),$t.EXIT),f.info("[LegacyClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),f.info("[LegacyClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(k.BROADCAST),this.callbacks.register(k.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(k.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(k.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(k.INDEXING_PROGRESS_UPDATE,e)}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}sendInitialize(e,t){this.client.send("initialize",e,t)}sendInitialized(e){this.client.sendRaw(JSON.stringify({jsonrpc:R,method:k.INITIALIZED,params:{editors:e}}),$t.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:R,id:0,result:{}}),$t.EMPTY)}sendAsyncRequest(e,t,r,i){if(!D(t)){f.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!$b(t)){f.warn(`[LSP] sendAsyncRequest missing textDocument.uri, method=${e}, params=${JSON.stringify(t)}`);return}if(typeof r!="number"){f.warn(`[LSP] sendAsyncRequest invalid requestId, method=${e}, requestId=${String(r)}`);return}let o=t.textDocument.uri,s=qe(o);t.textDocument.uri=s,delete t.requestId;let a=i??e;f.info(`[LSP] sendAsyncRequest ${a}, filePath: ${o}`),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:e,params:{params:t,requestId:r}}),a)}onDidChangeWatchedFiles(e){if(f.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let r of e){if(!Hb(r)){f.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:R,method:k.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),k.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!D(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){f.warn("[LSP] sendModuleDependencyUpdate, moduleSet is empty or null");return}let t=e.moduleSet;f.info(`[LSP] sending module dependency updated, count: ${t.length}`),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:k.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),$t.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let i=qe(t);e.textDocument.uri=i,f.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new ns(i),this.diagnosticMap.set(i,o),this.registerDiagnosticTimeout(i,k.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(o.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:k.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),$t.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=qe(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,k.PUBLISH_DIAGNOSTICS)),f.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:k.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),$t.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=qe(e);f.info(`[LSP] didClose, uri: ${r}`);let i=this.diagnosticMap.get(r);if(!t&&(!i||i.isFromEditor)){f.info(`[LSP] closeFile skip, !diagnostic: ${!i}, isFromEditor: ${i?.isFromEditor}`);return}this.cleanupDiagnosticState(r),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:k.DID_CLOSE,params:{textDocument:{uri:r}}}),$t.DID_CLOSE)}getDiagnosticMessage(e){let t=qe(e),r=this.diagnosticMap.get(t);return r?r.getMessages():[]}clear(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){try{let t=JSON.parse(e);this.handleLspMessage(t)}catch(t){let r=t instanceof Error?t.message:String(t);f.error(`[LSP] JSON parse error: ${r}, raw: ${e}`)}}handleError(e){let t=this.getPendingDiagnosticUris();if(t.length>0){let r=JSON.stringify({message:e.message,severity:"Error",severityStr:"Error"});for(let i of t)this.finalizeDiagnostic(i,k.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:R,method:k.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 k.MODULE_INIT_FINISH:return f.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(k.MODULE_INIT_FINISH),this.callbacks.unregister(k.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case k.INDEXING_PROGRESS_UPDATE:return f.info(`[LSP] onIndexingProgressUpdate: ${Ub(t.params)}`),this.callbacks.invoke(k.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case k.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case k.ON_PACKAGE_CHANGE_FINISH:f.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case k.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case k.ON_ASYNC_HOVER:this.handleAsyncResponse(t,k.HOVER);return;case k.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,k.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case k.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,k.REFERENCES);return;default:f.warn(`[LSP] handleLspMessage: no handler for notification, ignoring, method: ${e}, initialized: ${this.isInitialized}`)}}handleOnForceOpenFile(e){f.info("[LSP] handleLspMessage, receive onForceOpenFile");let t=e.params;D(t)&&D(t.result)&&typeof t.result.uri=="string"&&this.handleForceOpenFile(t.result.uri)}handlePublishDiagnostics(e){f.info("[LSP] handleLspMessage, receive publishDiagnostics");let t=e.params;t&&this.parseDiagnostics(t)}handlePackageChangeFinish(e){let t=e.params,r={jsonrpc:R,method:k.ON_PACKAGE_CHANGE_FINISH,params:[!1]};if(!t||!Array.isArray(t)){f.warn("[LSP] aceProject/onPackageChangeFinish params invalid"),this.broadcastToClients(r);return}if(!(t.length>0&&t[0]===!0)){f.warn("[LSP] aceProject/onPackageChangeFinish: package request failed"),this.broadcastToClients(r);return}f.info("[LSP] aceProject/onPackageChangeFinish: success"),this.broadcastToClients(e)}handleAsyncResponse(e,t){f.info(`[LSP] handleAsyncResponse\uFF0C method: ${t}`);let r=e.params;if(!D(r)){f.warn("[LSP] aceProject/onAsyncHover message invalid");return}let i=r.requestId;if(typeof i!="number"){f.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(i,t,r)}handleForceOpenFile(e){if(!e){f.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,k.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){f.info("[LSP] publishDiagnostics uri is null");return}let r=e.version??-1;if(r===-1)return;let i=this.diagnosticMap.get(t);if(!i){f.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let o=e.diagnostics||[];o.length!==0?o.forEach(s=>{this.normalizeDiagnostic(s),i.addMessage(r,JSON.stringify(s))}):i.setReceivedType(r),i.hasReceivedAllTypes(Ff)&&this.finalizeDiagnostic(t,k.PUBLISH_DIAGNOSTICS,i.getMessages())}normalizeDiagnostic(e){let t=e;if(delete t.source,t.severity!==void 0){let r=typeof t.severity=="number"?t.severity:parseInt(t.severity),o={1:"Error",2:"Warning",3:"Information",4:"Hint"}[r]||"Unknown";t.severityStr=o,t.severity=o}e.range&&(this.adjustPositionLine(e.range,"start"),this.adjustPositionLine(e.range,"end"))}adjustPositionLine(e,t){let r=e[t];r&&typeof r.line=="number"&&(r.line=r.line+1)}registerDiagnosticTimeout(e,t){this.requestCallbacks.registerTimeout(e,t,n.DIAGNOSTIC_TIMEOUT_MS,()=>{let r=this.diagnosticMap.get(e),i=r?r.getMessages():[];this.finalizeDiagnostic(e,t,i,i.length>0?void 0:`received no diagnostics within ${n.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,r,i){let o={uri:e,diagnostics:r,...i?{errorMessage:i}:{}};this.requestCallbacks.emit(e,t,o),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import Gc from"path";import*as ds from"path";var is=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var os=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var ss=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var as=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var cs=class{typeSetting=new ss;parameterNames=new as};var ls=class{constructor(e,t,r,i){this.rootUri=e;this.lspServerWorkspacePath=j(ds.dirname(t)),this.indexingDataLocation=j(i),this.loggerPath=j(ds.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new is;gutterIconsSetting=new os;inlayHintsSetting=new cs;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as jf from"path";var ni=class{productName="default";buildModeName="debug";targetName="default";arkTSVersion="1.1";resourceDirectories=[];targetESVersion="ES2021";maxFlowDepth=2e3;caseSensitiveCheck=!0;tsImportSendable=!1;compatibleSdkVersionStage="";useNormalizedOHMUrl=!0;reExportCheckMode="noCheck";skipOhModulesLint=!1;byteCodeHar=!0;obfuscationRuleOptionsEnable=!1;enableStrictCheckOHModules=!1;sourceRoots=[];constructor(e){e&&this.resourceDirectories.push(j(jf.join(e,"src","main","resources")))}};var Bb="OS",Kn=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${Bb}`;moduleName;moduleType;compileMode="jsbundle";crossPlatform=!1;ignoreCrossPlatform=!1;packageManagerType="ohpm";permissions=[];testPermissions=[];buildProfileParam;appParam={bundleType:"app"};packageName;projectType="OHOS";projectName;moduleDependencies;moduleJsonParam=null;globalDeclarationFiles=[];constructor(e){e?(this.modulePath=e,this.buildProfileParam=new ni(e)):this.buildProfileParam=new ni}toString(){return JSON.stringify(this)}};var Xn=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as je from"path";import*as er from"fs";var us=class{modulePath;dependencies={};dynamicDependencies={}};var mn=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 Zn=class{constructor(e,t,r){this.projectPath=e;this.moduleName=t;this.modulePath=r}projectPath;moduleName;modulePath;dependencies=[];devDependencies=[];dynamicDependencies=[];finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[]};import*as vt from"path";import*as ps from"fs";var Qn=class{name="";version="";storePath="";dependencyPath="";path=""};var N={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:ze.OH_PACKAGE_JSON5},ri=`${N.HVIGOR_CACHE}/${N.DEPENDENCY}`,hn=`${N.DEPENDENCY}${N.JSON5}`,LH=ze.SYNC_OUTPUT_PATH;var ii=class n{dependencyPath;modulePath;projectPath;static FILE_DEPENDENCY_PREFIX="file:";static PARAMETER_PREFIX="@param:";fileSpecPattern;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;static PACKAGE_JSON_PARSER_MAP=new Map;dependencies=[];devDependencies=[];dynamicDependencies=[];static getInstance(e,t,r){let i=this.PACKAGE_JSON_PARSER_MAP.get(e);return i||(i=new n(e,t,r),this.PACKAGE_JSON_PARSER_MAP.set(e,i)),i}constructor(e,t,r){this.dependencyPath=e,this.modulePath=t,this.projectPath=r,this.fileSpecPattern=n.isWindows()?/^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/:/^(?:[.]|~[/]|[/]|[a-zA-Z]:)/}static isWindows(){return process.platform==="win32"}parseDependency(e){let t=vt.join(this.dependencyPath,N.OH_PACKAGE_JSON5),r=Ce(t);r&&(this.dependencies=this.getDependencyList(r,N.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(r,N.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(r,N.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let r=[];if(!D(e))return r;let i=e[t];if(!D(i))return r;for(let[o,s]of Object.entries(i)){if(typeof s!="string"){f.error(`${o} package dependency value is not String ${t}`);continue}let a=new Qn;a.name=o;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(n.PARAMETER_PREFIX)||this.parseDependencyPath(o,c,a,!1),r.push(a)}return r}parseDependencyPath(e,t,r,i){if(!(!e||!t))try{let o=vt.normalize(vt.join(this.modulePath,N.OH_MODULES_PATH,e));if(!(t.startsWith(n.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){r.dependencyPath=o;return}if(r.path=t,this.fileNameForOhpm.test(t)){r.dependencyPath=o;return}let s=t;if(t.startsWith(n.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(n.FILE_DEPENDENCY_PREFIX.length)),vt.isAbsolute(s)){r.dependencyPath=o;return}if(!i){let a=vt.resolve(this.modulePath,s);o=P.ensurePathWithinRoot(this.projectPath,a)}ps.existsSync(o)&&ps.statSync(o).isDirectory()&&(r.dependencyPath=o)}catch(o){f.error("parser dependency path is invalid",o)}}};import*as oi from"fs";import*as si from"path";import Wb from"json5";var fs=class n{projectPath;static FILE_DEPENDENCY_PREFIX="file:";fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[];storePathMap=new Map;lockFileCache=null;lockFileParsed=!1;constructor(e=""){this.projectPath=e}parseDependencies(e){if(!this.ensureLockFileParsed())return!1;let t=this.lockFileCache;return this.extractDependencies(t.modules,t.storePathMap,e),!0}ensureLockFileParsed(){if(this.lockFileParsed)return this.lockFileCache!==null;this.lockFileParsed=!0;let e=this.getLockFilePath(),t=this.readLockFile(e);if(!t)return!1;let r=this.validateLockFile(t);return r.valid?(this.lockFileCache={modules:r.modules,storePathMap:this.parseStorePathMap(r.packages)},!0):!1}getLockFilePath(){return si.join(this.projectPath,N.OH_MODULES_PATH,N.OHPM_PATH,N.LOCK_JSON5_FILE)}readLockFile(e){if(!oi.existsSync(e))return f.error("lock file does not exist"),this.clearDependencies(),null;try{let t=oi.readFileSync(e,"utf8"),r=Wb.parse(t);return r||(f.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return f.error("Error parsing lock.json5:",t),this.clearDependencies(),null}}validateLockFile(e){if(!D(e))return f.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return f.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let r=e.packages;return r?{valid:!0,modules:t,packages:r}:(f.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,r){this.storePathMap=t,this.finalDependencies=this.getDependencyList(e,N.KEY_DEPENDENCY,r),this.finalDevDependencies=this.getDependencyList(e,N.KEY_DEV_DEPENDENCY,r),this.finalDynamicDependencies=this.getDependencyList(e,N.KEY_DYNAMIC_DEPENDENCY,r)}parseStorePathMap(e){let t=new Map;if(!D(e))return t;for(let[r,i]of Object.entries(e)){if(!D(i)){f.error(`${r} value is not json object`);continue}typeof i.storePath=="string"&&t.set(r,i.storePath)}return t}getDependencyList(e,t,r){if(!D(e))return[];for(let[i,o]of Object.entries(e))if(D(o)){let s=typeof o.name=="string"?o.name:"";if(r==="."&&s===""||s===r)return this.getFinalDependencyList(e,t,i)}return[]}getFinalDependencyList(e,t,r){let i=e[r];if(!D(i))return f.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!D(s))return[];for(let[a,c]of Object.entries(s)){if(!D(c))continue;let l=typeof c.specifier=="string"?c.specifier:"",p=typeof c.version=="string"?c.version:"",g=new Qn;g.name=a,g.version=p.startsWith(n.FILE_DEPENDENCY_PREFIX)?p.substring(n.FILE_DEPENDENCY_PREFIX.length):p,this.parseDependencyPath(g,r,a,l,p);let w=`${a}@${p}`;this.storePathMap.has(w)&&(g.storePath=this.storePathMap.get(w)||""),o.push(g)}return o}parseDependencyPath(e,t,r,i,o){let s=P.resolvePathWithinRoot(this.projectPath,si.join(t,N.OH_MODULES_PATH,r));try{let a=o.startsWith(n.FILE_DEPENDENCY_PREFIX)?o.substring(n.FILE_DEPENDENCY_PREFIX.length):o,c=si.isAbsolute(a)?P.ensurePathWithinRoot(this.projectPath,a):P.resolvePathWithinRoot(this.projectPath,a);oi.existsSync(c)?(e.path=i,e.dependencyPath=this.fileNameForOhpm.test(o)?s:c):e.dependencyPath=s}catch(a){f.error("Invalid dependency path in lock.json5",a)}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};function $f(n){return D(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var gn=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new pt(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=je.join(t,ri),i=je.join(r,hn);if(!er.existsSync(r)||!er.existsSync(i)){let c="Dependency map or JSON not found";return f.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let o=new Zn(this.projectPath,".",this.projectPath);this.parseProjectDependencies(r,o),this.parseLockJson(o);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let c="No modules found in build-profile.json5";return f.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:c}}let a=Date.now();for(let c=0;c<s.length;c++){let l=s[c];$f(l)&&(this.parseSingleModule(l,r,o,e),(c+1)%100===0&&f.info(`[Parser] getAllDependencyMap progress: ${c+1}/${s.length} (${Date.now()-a}ms)`))}return f.info(`[Parser] getAllDependencyMap parsed ${e.length} modules in ${Date.now()-a}ms`),{status:"OK"}}getDependenciesOnly(e){let t=[],r=this.projectPath,i=je.join(r,ri),o=je.join(i,hn);if(!er.existsSync(i)||!er.existsSync(o))return f.warn("[Parser] Dependency map or JSON not found."),t;let s=e&&e.length>0?new Set(e.map(l=>l.trim()).filter(Boolean)):null,a=new Zn(this.projectPath,".",this.projectPath);this.parseProjectDependencies(i,a),this.parseLockJson(a);let c=this.moduleInfoParse.getAllModuleInfo();if(c.length===0)return f.warn("[Parser] getAllDependencyMap failed: No modules found in build-profile.json5."),t;for(let l of c){if(!$f(l))continue;let p=l.name;if(s&&!s.has(p))continue;let g=P.resolvePathWithinRoot(this.projectPath,l.srcPath),w=je.join(i,p),C=j(g),_=this.buildModuleDependencies(p,C,w,a);_.moduleName=p,t.push(_)}return t}parseSingleModule(e,t,r,i){let o=e.name,s=P.resolvePathWithinRoot(this.projectPath,e.srcPath),a=je.join(t,o),c=j(s),l=new Kn(c),p=this.buildModuleDependencies(o,c,a,r);this.parseModuleJson5(c,l);let g=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=o,l.moduleType=o,l.packageName=o,l.moduleDependencies=p,l.moduleJsonParam=new Xn(g),i.push(l)}buildModuleDependencies(e,t,r,i){let o=new Zn(this.projectPath,e,t);ii.getInstance(r,t,this.projectPath).parseDependency(o),this.parseLockJson(o),o.finalDependencies.push(...i.finalDependencies),o.finalDevDependencies.push(...i.finalDevDependencies),o.finalDynamicDependencies.push(...i.finalDynamicDependencies),o.finalDependencies.push(...o.finalDevDependencies);let a=new us;return a.modulePath=t,this.toModuleDependencies(o,a),a}toModuleDependencies(e,t){let r={},i={};for(let o of e.finalDependencies)r[o.name]=new mn(o);for(let o of e.finalDynamicDependencies)i[o.name]=new mn(o);t.dependencies=r,t.dynamicDependencies=i}parseProjectDependencies(e,t){let r=je.join(e,N.OH_PACKAGE_JSON5);if(!er.existsSync(r))return;ii.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 fs(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=je.join(e,"src","main","module.json5"),i=Ce(r);if(!D(i)||!D(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(D(e)&&Array.isArray(e.requestPermissions))for(let r of e.requestPermissions)D(r)&&typeof r.name=="string"&&t.push(r.name);return t}parseMainPages(e){let t=je.join(e,"src","main","resources","base","profile","main_pages.json"),r=Ce(t);return!D(r)||!Array.isArray(r.src)?[]:r.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=this.getSdkPkg();if(!(!D(t)||!D(t.data))){if(typeof t.data.apiVersion=="string"){let r=parseInt(t.data.apiVersion,10);!Number.isNaN(r)&&r>=26&&typeof t.data.platformVersion=="string"?e.compileSdkLevel=t.data.platformVersion:e.compileSdkLevel=t.data.apiVersion}typeof t.data.releaseType=="string"&&(e.compileSdkType=t.data.releaseType),typeof t.data.version=="string"&&(e.compileSdkVersion=t.data.version)}}getSdkPkg(){if(this.sdkPkgCache===void 0){let e=je.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=Ce(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!D(t)||!D(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let r=t.app.products[0];if(!D(r)||typeof r.compatibleSdkVersion!="string")return;let[i,o]=this.parseBySplit(r.compatibleSdkVersion);e.compatibleSdkVersion=i,e.compatibleSdkLevel=o}getBuildProfile(){if(this.buildProfileCache===void 0){let e=je.join(this.projectPath,"build-profile.json5");this.buildProfileCache=Ce(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,e];let r=e.substring(0,t),i=e.substring(t+1,e.length-1);return[r,i]}parseDeviceTypes(e){return!D(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 ms=class{constructor(e=[]){this.valueSet=e}valueSet};var tr=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var Hf=(E=>(E[E.File=1]="File",E[E.Module=2]="Module",E[E.Namespace=3]="Namespace",E[E.Package=4]="Package",E[E.Class=5]="Class",E[E.Method=6]="Method",E[E.Property=7]="Property",E[E.Field=8]="Field",E[E.Constructor=9]="Constructor",E[E.Enum=10]="Enum",E[E.Interface=11]="Interface",E[E.Function=12]="Function",E[E.Variable=13]="Variable",E[E.Constant=14]="Constant",E[E.String=15]="String",E[E.Number=16]="Number",E[E.Boolean=17]="Boolean",E[E.Array=18]="Array",E[E.Object=19]="Object",E[E.Key=20]="Key",E[E.Null=21]="Null",E[E.EnumMember=22]="EnumMember",E[E.Struct=23]="Struct",E[E.Event=24]="Event",E[E.Operator=25]="Operator",E[E.TypeParameter=26]="TypeParameter",E))(Hf||{}),Uf=()=>Object.values(Hf).filter(n=>typeof n=="number");var hs=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var gs=class{applyEdit=!0;workspaceEdit=new hs;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new ms(Uf());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new tr;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var ys=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var ws=class{constructor(e=[]){this.valueSet=e}valueSet};var vs=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var Bf=(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))(Bf||{}),Wf=()=>Object.values(Bf).filter(n=>typeof n=="number");var Ss=class{completionItemKind=new ws(Wf());completionItem=new vs;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var Es=class{synchronization=new ys;completion=new Ss;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 tr;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var bs=class{workspace=new gs;textDocument=new Es;notebookDocument=null;window=null;general=null;experimental=null};var Ps=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};var Cs=class{constructor(e,t,r,i,o,s=!0){this.sdkPath=e;this.rootUri=r;this.nodeMaxOldSpaceSize=o;this.useStandardProtocol=s;this.serverPath=Ir(t,this.useStandardProtocol),this.logPath=Yd(),this.indexLogPath=i||this.logPath;let a={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath};this.messageHandle=this.useStandardProtocol?new ts(a):new rs(a),this.messageHandle.setBroadcastToClients(c=>this.onLspMessage(c))}sdkPath;rootUri;nodeMaxOldSpaceSize;useStandardProtocol;messageHandle;get stdHandle(){return this.messageHandle}get legacyHandle(){return this.messageHandle}onAsyncOpenFile(e){this.legacyHandle.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.legacyHandle.closeFile(e,t)}serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}async start(e,t){let r=!1;try{f.info(`serverPath: ${this.serverPath}`),f.info(`rootUri: ${this.rootUri}`),f.info(`sdkPath: ${this.sdkPath}`),f.info(`logPath: ${this.logPath}`);let i=qe(this.rootUri),o=new ls(i,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new gn(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),o.modules=s;let l=mo(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(l),this.currentParams=new Ps(i,o,new bs),this.useStandardProtocol){let p=this.messageHandle;await p.sendInitializeResettable(this.currentParams,Le),f.info("[LSP] initialize response received"),p.broadcastToClients({jsonrpc:R,method:y.ARKTS_INDEXING_PROGRESS,params:{}}),p.sendInitialized()}else await this.startLegacy(this.currentParams,e);r=!0}catch(i){this.lastStartErrorMessage=i instanceof Error?i.message:String(i),f.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(r)}async startLegacy(e,t){let r=this.messageHandle;r.sendInitialize(e,1),r.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:R,method:y.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((i,o)=>{r.onIndexingProgressUpdate(o),r.onInitializationCompleted(i)},"LSP initialization",Le),r.sendInitialized(t)}withResettableTimeout(e,t,r){return new Promise((i,o)=>{let s,a=()=>{s=setTimeout(()=>{o(new Error(`${t} timeout after ${r}ms`))},r)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),i()},c)})}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){f.info(`[LSP] registerDiagnosticCallback uri='${e}', useStandardProtocol=${this.useStandardProtocol}`),this.messageHandle.registerRequestCallback(e,(t,r)=>{let i=D(r)?r:{};f.info(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let o={jsonrpc:R,method:t,params:{uri:typeof i.uri=="string"?i.uri:e,diagnostics:Array.isArray(i.diagnostics)?i.diagnostics:[],...typeof i.errorMessage=="string"?{errorMessage:i.errorMessage}:{}}};this.onLspMessage(o)})}async hover(e){let t=e.textDocument.uri;return this.registerDiagnosticCallback(t),this.stdHandle.sendLspRequest(y.HOVER,e)}async definition(e){return this.stdHandle.sendLspRequest(y.DEFINITION,e)}async references(e){return this.stdHandle.sendLspRequest(y.REFERENCES,e)}async completion(e){return this.stdHandle.sendLspRequest(y.COMPLETION,e)}async documentSymbol(e){return this.stdHandle.sendLspRequest(y.DOCUMENT_SYMBOL,e)}async diagnostic(e){return this.stdHandle.sendLspRequest(y.DIAGNOSTIC,e,120*1e3)}async sendFeatureRequest(e,t){return this.stdHandle.sendLspRequest(e,t)}reloadDependenciesOnly(e){let t=e?.fullReload??!1,r=new gn(this.rootUri,this.sdkPath),i=this.getModuleModelsByName();if(t){f.info("[LspServerProxy] Project-level oh-package changed, parsing all modules' dependencies");let l=r.getDependenciesOnly();this.markDependencyTypesIncremental(l);let p=this.mergeDepsOnlyIntoModuleList(l,i);return this.applyModuleModelsUpdate(p),this.sendDidChangeConfiguration({moduleSet:p}),f.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${p.length}`),this.lastDepsOnlyForDiff=l,l}let o=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(o.length===0&&s.size===0)return f.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];f.info(`[LspServerProxy] Module-level deps changed, parsing: [${o.join(", ")}]`);let a=r.getDependenciesOnly(o);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),this.sendDidChangeConfiguration({moduleSet:c}),f.info(`[LspServerProxy] Dependencies only (incremental) reloaded, count: ${c.length}`),this.lastDepsOnlyForDiff=a,a}sendDidChangeConfiguration(e){this.stdHandle.sendDidChangeConfiguration(e)}getModuleModelsByName(){return new Map(this.currentModuleModels.map(e=>[e.moduleName??"",e]))}markDependencyTypesIncremental(e){let t=this.getModuleModelsByName(),r=new Map(this.lastDepsOnlyForDiff.map(i=>[i.moduleName??"",i]));for(let i of e){let o=i.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(o,t,r),c=i.dependencies??{},l=i.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(p,g)=>{(i.dependencies??={})[p]=this.makeDeleteEntry(p,g)}),this.markAddAndDeleteInDeps(a,l,(p,g)=>{(i.dynamicDependencies??={})[p]=this.makeDeleteEntry(p,g)})}}getOldDepsForModule(e,t,r){let i=t.get(e),o=i?.moduleDependencies?.dependencies??{},s=i?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(o).length===0&&Object.keys(s).length===0){let a=r.get(e);a&&(o=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:o,oldDynamic:s}}markAddAndDeleteInDeps(e,t,r){for(let i of Object.keys(t))i in e||(t[i].type="add");for(let i of Object.keys(e))i in t||r(i,e[i])}makeDeleteEntry(e,t){return new mn({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Kn(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new Xn([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let r=[];for(let i of e){let o=i.moduleName??"",s=t.get(o);s?(s.modulePath=i.modulePath,s.moduleDependencies=i):s=this.createMinimalModelFromDepsItem(i),r.push(s)}return r}mergeIncrementalDeps(e,t,r){let i=new Map(r.map(s=>[s.moduleName??"",s])),o=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=i.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,i.delete(a)),o.push(s)}for(let[,s]of i)o.push(this.createMinimalModelFromDepsItem(s));return o}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,r=xn(Gc.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=xn(Gc.join(t,"default/openharmony/ets/api")),o=xn(Gc.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=i,s.hosSdkPath=o}sendRequest(e){switch(e.method){case y.HOVER:this.stdHandle.sendLspRequest(y.HOVER,e.params).then(t=>this.onLspMessage({jsonrpc:R,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:R,id:e.id,error:{code:-32603,message:t.message}}));break;case y.DEFINITION:this.stdHandle.sendLspRequest(y.DEFINITION,e.params).then(t=>this.onLspMessage({jsonrpc:R,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:R,id:e.id,error:{code:-32603,message:t.message}}));break;case y.REFERENCES:this.stdHandle.sendLspRequest(y.REFERENCES,e.params).then(t=>this.onLspMessage({jsonrpc:R,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:R,id:e.id,error:{code:-32603,message:t.message}}));break;default:f.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!Of(e)){f.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case y.DID_OPEN:this.handleDidOpenNotification(e);break;case y.DID_CHANGE:this.handleDidChangeNotification(e);break;case y.DID_CLOSE:this.handleDidCloseNotification(e);break;case y.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;case y.DID_CREATE_FILES:this.handleDidCreateFiles(e);break;case y.DID_DELETE_FILES:this.handleDidDeleteFiles(e);break;default:f.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){f.error("Invalid textDocument/didOpen params");return}this.stdHandle.sendDidOpen(t)}handleDidChangeNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){f.error("Invalid textDocument/didChange params");return}this.stdHandle.sendDidChange(t)}handleDidCloseNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){f.error("Invalid textDocument/didClose params");return}this.stdHandle.closeFile(t)}handleDidChangeWatchedFiles(e){let t=e.params;!t||!Array.isArray(t.changes)||this.messageHandle.onDidChangeWatchedFiles(t.changes)}handleDidCreateFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(y.DID_CREATE_FILES,t)}handleDidDeleteFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(y.DID_DELETE_FILES,t)}async dispose(){await this.messageHandle.stop()}};import*as St from"fs";import*as Ht from"path";import{createHash as Vb}from"crypto";import{EventEmitter as zb}from"events";var Is=class extends zb{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r}projectRoot;watchers=new Map;debounceTimers=new Map;contentHashes=new Map;buildProfileWatcher=null;lastModulesSnapshot="";lastModules=[];debounceMs;start(){let t=this.parseModulesFromBuildProfile();this.lastModules=t,this.lastModulesSnapshot=this.computeModulesSnapshot(t),this.refreshWatchTargets(),this.watchBuildProfile()}refreshWatchTargets(){let t=new Set(this.collectWatchTargets()),r=new Set(this.watchers.keys());for(let i of t)r.has(i)||this.watchFile(i);for(let i of r)t.has(i)||(this.unwatchFile(i),f.info(`[ConfigFileWatcher] Stopped watching: ${i}`));f.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!St.existsSync(t)){f.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=St.watch(t,r=>{r==="change"&&this.onBuildProfileChanged()}),this.buildProfileWatcher.on("error",r=>{f.error(`[ConfigFileWatcher] build-profile.json5 watch error: ${r.message}`)}),f.info(`[ConfigFileWatcher] Watching module registry: ${t}`)}catch(r){f.error(`[ConfigFileWatcher] Failed to watch build-profile.json5: ${r instanceof Error?r.message:String(r)}`)}}emitModuleAddedEvents(t,r){for(let i of t){let o=P.resolvePathWithinRoot(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:o,relativePath:i.srcPath,timestamp:r,moduleName:i.name})}}emitModuleRemovedEvents(t,r){for(let i of t){let o=P.resolvePathWithinRoot(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:o,relativePath:i.srcPath,timestamp:r,removedModuleName:i.name})}}emitModuleRenamedEvents(t,r){for(let i of t){let o=P.resolvePathWithinRoot(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:o,relativePath:i.after.srcPath,timestamp:r,moduleName:i.after.name,removedModuleName:i.before.name})}}emitModuleMovedEvents(t,r){for(let i of t){let o=P.resolvePathWithinRoot(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:o,relativePath:i.after.srcPath,timestamp:r,moduleName:i.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let r=Date.now();this.emitModuleAddedEvents(t.added,r),this.emitModuleRemovedEvents(t.removed,r),this.emitModuleRenamedEvents(t.renamed,r),this.emitModuleMovedEvents(t.moved,r)}onBuildProfileChanged(){let t="__build_profile__",r=this.debounceTimers.get(t);r&&clearTimeout(r);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(o);if(s===this.lastModulesSnapshot){f.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,o);this.lastModules=o,this.lastModulesSnapshot=s,f.info(`[ConfigFileWatcher] build-profile.json5 modules changed, added=${a.added.length}, removed=${a.removed.length}, renamed=${a.renamed.length}, moved=${a.moved.length}`),this.processBuildProfileDiff(a)},this.debounceMs);this.debounceTimers.set(t,i)}computeModulesSnapshot(t){return t.map(i=>`${i.name}::${i.srcPath}`).sort().join("|")}diffModules(t,r){let i=this.buildModuleMatchState(r),o={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,i),this.matchRenamedModules(t,i,o),this.matchMovedModules(t,i,o),this.collectRemovedModules(t,i,o),this.collectAddedModules(r,i,o),o}buildModuleMatchState(t){let r=new Map,i=new Map;for(let o of t)r.set(o.srcPath,o),i.set(o.name,o);return{matchedOld:new Set,matchedNew:new Set,newBySrc:r,newByName:i}}matchExactModules(t,r){for(let i of t){let o=r.newBySrc.get(i.srcPath);o&&o.name===i.name&&(r.matchedOld.add(i),r.matchedNew.add(o))}}matchRenamedModules(t,r,i){for(let o of t){if(r.matchedOld.has(o))continue;let s=r.newBySrc.get(o.srcPath);s&&!r.matchedNew.has(s)&&s.name!==o.name&&(i.renamed.push({before:o,after:s}),r.matchedOld.add(o),r.matchedNew.add(s))}}matchMovedModules(t,r,i){for(let o of t){if(r.matchedOld.has(o))continue;let s=r.newByName.get(o.name);s&&!r.matchedNew.has(s)&&s.srcPath!==o.srcPath&&(i.moved.push({before:o,after:s}),r.matchedOld.add(o),r.matchedNew.add(s))}}collectRemovedModules(t,r,i){for(let o of t)r.matchedOld.has(o)||i.removed.push(o)}collectAddedModules(t,r,i){for(let o of t)r.matchedNew.has(o)||i.added.push(o)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let r=Ce(t);if(typeof r!="object"||r===null)return[];let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return f.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${r instanceof Error?r.message:String(r)}`),[]}}collectWatchTargets(){let t=[],r=Ht.join(this.projectRoot,N.OH_PACKAGE_JSON5);St.existsSync(r)&&t.push(r);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=P.resolvePathWithinRoot(this.projectRoot,o.srcPath),a=Ht.join(s,N.OH_PACKAGE_JSON5);St.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return Ht.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=St.readFileSync(t,"utf-8");return Vb("sha256").update(r).digest("hex")}catch{return null}}watchFile(t){if(!this.watchers.has(t))try{let r=this.computeFileHash(t);r&&this.contentHashes.set(t,r);let i=St.watch(t,o=>{o==="change"&&this.onFileChanged(t)});i.on("error",o=>{f.error(`[ConfigFileWatcher] Watch error for ${t}: ${o.message}`)}),this.watchers.set(t,i)}catch(r){f.error(`[ConfigFileWatcher] Failed to watch ${t}: ${r instanceof Error?r.message:String(r)}`)}}unwatchFile(t){let r=this.watchers.get(t);r&&(r.close(),this.watchers.delete(t)),this.contentHashes.delete(t);let i=this.debounceTimers.get(t);i&&(clearTimeout(i),this.debounceTimers.delete(t))}onFileChanged(t){let r=this.debounceTimers.get(t);r&&clearTimeout(r);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.computeFileHash(t);if(!o){f.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===o){f.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,o),f.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:Ht.basename(t),relativePath:Ht.relative(this.projectRoot,t),timestamp:Date.now()};this.emit("configChanged",a)},this.debounceMs);this.debounceTimers.set(t,i)}stop(){for(let[,t]of this.watchers)t.close();this.watchers.clear(),this.buildProfileWatcher&&(this.buildProfileWatcher.close(),this.buildProfileWatcher=null);for(let t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.contentHashes.clear(),f.info("[ConfigFileWatcher] All watchers stopped")}};import*as Ut from"fs";import*as Ze from"path";import{createHash as qb}from"crypto";import{EventEmitter as Yb}from"events";var As=class extends Yb{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=Ze.join(t,ri)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!Ut.existsSync(this.depMapDir)){f.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=Ut.watch(this.depMapDir,{recursive:!0},(t,r)=>this.onDirEvent(t,r)),this.dirWatcher.on("error",t=>{f.error(`[DependencyMapWatcher] Directory watch error for ${this.depMapDir}: ${t.message}`)})}catch(t){f.error(`[DependencyMapWatcher] Failed to watch directory ${this.depMapDir}: ${t instanceof Error?t.message:String(t)}`);return}this.pollInterval=setInterval(()=>this.scanAllCacheFiles(),2500),f.info(`[DependencyMapWatcher] Started, watching directory (recursive): ${this.depMapDir}, modules: [${this.lastModules.map(t=>t.name).join(", ")}]`)}canonicalPath(t){return j(Ze.resolve(t))}onDirEvent(t,r){if(!r||typeof r!="string")return;let i=r.replace(/\\/g,"/"),o;if(i===N.OH_PACKAGE_JSON5)o="root-oh-package";else if(i===hn)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=Ze.join(this.depMapDir,r);Ut.existsSync(s)&&this.scheduleDebouncedFullScan()}stop(){this.dirWatcher&&(this.dirWatcher.close(),this.dirWatcher=null),this.fullScanTimer&&(clearTimeout(this.fullScanTimer),this.fullScanTimer=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.coalesceTimer&&(clearTimeout(this.coalesceTimer),this.coalesceTimer=null),this.pendingTags=[],this.pendingRenames=[],this.contentHashes.clear(),this.initialScanDone=!1,f.info("[DependencyMapWatcher] All watchers stopped")}scheduleDebouncedFullScan(){this.fullScanTimer&&clearTimeout(this.fullScanTimer),this.fullScanTimer=setTimeout(()=>{this.fullScanTimer=null,this.scanAllCacheFiles()},this.debounceMs)}scanAllCacheFiles(){let t=Ze.join(this.depMapDir,N.OH_PACKAGE_JSON5),r=Ze.join(this.depMapDir,hn),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...i.map(s=>({path:Ze.join(this.depMapDir,s.name,N.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!Ut.existsSync(s))continue;let c=this.canonicalPath(s),l=this.computeFileHash(s);if(!l)continue;let p=this.contentHashes.get(c);if(!this.initialScanDone){this.contentHashes.set(c,l);continue}p!==l&&(this.contentHashes.set(c,l),f.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=Ze.join(this.depMapDir,hn);try{let r=Ce(t);if(typeof r!="object"||r===null)return[];let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return f.warn(`[DependencyMapWatcher] Failed to parse dependencyMap.json5: ${r instanceof Error?r.message:String(r)}`),[]}}scheduleCoalescedReload(t){this.pendingTags.push(t),t==="dep-map-json"&&this.applyDepMapJsonDiff(),this.coalesceTimer&&clearTimeout(this.coalesceTimer),this.coalesceTimer=setTimeout(()=>{this.coalesceTimer=null,this.flushPendingReload()},this.coalesceMs)}collectPendingState(){let t=this.pendingTags,r=this.pendingRenames;return this.pendingTags=[],this.pendingRenames=[],{tags:t,renameEntries:r}}processTagsIntoSets(t,r,i,o){for(let s of t)s.startsWith("module:")?(i.add(s.substring(7)),r.add("moduleDepsChanged")):s.startsWith("dep-added:")?(i.add(s.substring(10)),r.add("moduleAdded")):s.startsWith("dep-removed:")&&(o.add(s.substring(12)),r.add("moduleRemoved"))}processRenameEntries(t,r,i,o,s){for(let a of t)s.push(a.info),i.add(a.info.newName),o.add(a.info.oldName),r.add(a.kind)}buildAddedNamesSet(t,r){let i=new Set;for(let o of t)o.startsWith("dep-added:")&&i.add(o.substring(10));for(let o of r)i.add(o.info.newName);return i}emitIncrementalReload(t,r,i,o,s){f.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...r].join(",")}], removed=[${[...i].join(",")}], added=[${[...o].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...r],removedModuleNames:[...i],addedModuleNames:[...o],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:r}=this.collectPendingState();if(t.length===0&&r.length===0)return;if(f.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${r.length}`),t.includes("root-oh-package")){f.info("[DependencyMapWatcher] Root oh-package.json5 in batch \u2192 full reload"),this.emit("reload",{fullReload:!0,kinds:["projectDepsChanged"]});return}let i=new Set,o=new Set,s=new Set,a=[];this.processTagsIntoSets(t,i,o,s),this.processRenameEntries(r,i,o,s,a);for(let l of o)s.delete(l);if(o.size===0&&s.size===0&&a.length===0){f.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,r);this.emitIncrementalReload(i,o,s,c,a)}normalizeSrcPath(t){return j(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let r=new Map(t.map(o=>[o.name,o])),i=new Map(t.map(o=>[this.normalizeSrcPath(o.srcPath),o]));return{byName:r,bySrcPath:i}}detectModuleRenames(t,r,i,o){for(let[s,a]of t){let c=r.get(s);if(!c||c.name===a.name)continue;this.pendingRenames.push({kind:"moduleRenamed",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleRenamed"}}),i.add(a.name),o.add(c.name);let l=Ze.join(this.depMapDir,a.name,N.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(l)),f.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,r,i,o){for(let[s,a]of t){if(i.has(s))continue;let c=r.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),i.add(s),o.add(s),f.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,r,i){for(let[o]of t)i.has(o)||r.has(o)||(this.pendingTags.push(`dep-added:${o}`),i.add(o))}detectRemovedModules(t,r,i){for(let[o]of t)if(!i.has(o)&&!r.has(o)){this.pendingTags.push(`dep-removed:${o}`),i.add(o);let s=Ze.join(this.depMapDir,o,N.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(i=>i.startsWith("dep-")),r=this.pendingRenames.map(i=>`${i.kind}(${i.info.oldName}\u2192${i.info.newName})`);f.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${r.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:r,bySrcPath:i}=this.buildModuleLookupMaps(this.lastModules),{byName:o,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(i,s,a,c),this.detectModuleMoves(r,o,a,c),this.detectAddedModules(o,r,c),this.detectRemovedModules(r,o,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let r=Ut.readFileSync(t,"utf-8");return qb("sha256").update(r).digest("hex")}catch{return null}}};import{spawn as Jb}from"child_process";import*as Vc from"fs";import*as ai from"path";var Kb=["install","--all"];function Xb(n){let e=n.replace(/sdk\/?$/i,"tools"),t=ai.join(e,"ohpm","bin","pm-cli.js");if(Vc.existsSync(t))return t;let r=n.toLowerCase().endsWith("sdk")?ai.dirname(n):n;return t=ai.join(r,"ohpm","bin","pm-cli.js"),Vc.existsSync(t)?t:null}async function Zb(n,e,t,r){return new Promise(i=>{let o=Jb(n,[e,...Kb],{cwd:t,env:{...process.env,DEVECO_SDK_HOME:r},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),s="",a="";o.stdout?.on("data",c=>{s+=c.toString()}),o.stderr?.on("data",c=>{a+=c.toString()}),o.on("close",c=>{let l=[s,a].filter(Boolean).join(`
1267
+ `);i({exitCode:c??-1,output:l})}),o.on("error",c=>{let l=[s,a].filter(Boolean).join(`
1268
+ `);i({exitCode:-1,output:l+`
1269
+ `+c.message})})})}function Qb(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>f.info("[ohpm] %s",e))}async function Gf(n,e){try{let t=co(e);if(!t)return f.error("node \u8DEF\u5F84\u4E0D\u5B58\u5728"),!1;let r=Xb(e);if(!r)return f.error("ohpm (pm-cli.js) \u4E0D\u5B58\u5728"),!1;let{exitCode:i,output:o}=await Zb(t,r,n,e);return Qb(o),i===0?(f.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(f.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",i),f.error("ohpm \u8F93\u51FA: %s",o),!1)}catch(t){return f.error("ohpm \u5B89\u88C5\u5F02\u5E38",t),!1}}var Vf={UNINITIALIZED:-32099,UNKNOWN:-32e3},ci=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,Vf.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,Vf.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var nr=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){f.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){f.warn("[ArktsLspManager] sendRequest before LSP ready, dropped");return}this.lspProxy.sendRequest(e)}async diagnostic(e){if(!this.lspProxy)throw new Error("[ArktsLspManager] diagnostic before LSP ready");return this.lspProxy.diagnostic(e)}async sendFeatureRequest(e,t){if(!this.useStandardProtocol)throw new Error(`Language feature '${e}' is not supported on the installed DevEco Studio. The standard LSP protocol entry (plugins/openharmony/ace-server/out/standardIndex/index.js) was not found. Please upgrade DevEco Studio to version 26.0.0.610 or later to use this tool.`);if(!this.lspProxy)throw new Error("LSP not ready");return this.lspProxy.sendFeatureRequest(e,t)}get useStandardProtocol(){return this.config.useStandardProtocol}onAsyncOpenFile(e){this.lspProxy?.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.lspProxy?.closeFileLegacy(e,t)}registerDiagnosticCallback(e){this.lspProxy?.registerDiagnosticCallback(e)}static async handleSyncProject(e,t,r){if(f.info("[ArktsLspManager] Received arkts/syncProject"),!e||!t)return f.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let i=r?.skipHvigorSync===!0,o=await Zi(e,async()=>await Gf(e,t)?i?(f.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await Qd(e,t)?(f.info("[ArktsLspManager] syncProject completed successfully"),{status:"success"}):(f.error("[ArktsLspManager] syncProject failed"),{status:"failed",reason:"hvigor sync failed"}):(f.error("[ArktsLspManager] ohpm install failed"),{status:"failed",reason:"ohpm install failed"}));return o.acquired?o.result:(f.info("[ArktsLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){try{this.configWatcher?.stop()}catch(e){f.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){f.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){f.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e){let t=new Cs(this.config.sdkPath,this.config.arktsLangServerPath,this.config.workspaceRoot,this.config.indexLogPath,this.config.nodeMaxOldSpaceSize,this.config.useStandardProtocol);t.setOnMessage(r=>this.handleLspMessage(r)),t.start(e,r=>this.handleLspInitialized(r)),this.lspProxy=t}handleLspInitialized=e=>{if(this.isInitialized=e,e)f.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:R,method:y.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();f.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?ci.uninitialized(t):ci.unknown();this.onMessage({jsonrpc:R,method:y.ARKTS_INITIALIZATION_FAILED,params:r.toJsonRpcErrorParams()}),this.lspProxy=null}};handleLspMessage(e){this.onMessage(e)}maybeRetryLspAfterSuccessfulSync(){this.isInitialized||this.lspProxy!==null||(f.info("[ArktsLspManager] Retrying LSP startup after successful sync"),this.onMessage({jsonrpc:R,method:y.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new Is(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new As(this.config.workspaceRoot),this.depMapWatcher.on("reload",e=>{if(!this.lspProxy){f.warn("[ArktsLspManager] LspServerProxy not initialized, skip reload");return}let r=this.lspProxy.reloadDependenciesOnly(e).map(i=>({modulePath:i.modulePath??"",dependencies:i.dependencies??{},dynamicDependencies:i.dynamicDependencies??{}}));this.onMessage({jsonrpc:R,method:y.ARKTS_SYNC_COMPLETED,params:{success:!0,moduleSet:r}})}),this.depMapWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){f.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),this.onConfigChanged?.()}};var eP=10080*60*1e3,tP=7200*60*1e3,nP=120*1e3,rr=class n{manager=null;initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;sdkPath;arktsLangServerPath;nodeMaxOldSpaceSize;onConfigChangedCallback=null;useStandardProtocol=!0;diagnosticWaiters=new Map;static FEATURE_METHOD_MAP={hover:y.HOVER,definition:y.DEFINITION,declaration:y.DECLARATION,references:y.REFERENCES,implementation:y.IMPLEMENTATION,completion:y.COMPLETION,signatureHelp:y.SIGNATURE_HELP,documentHighlight:y.DOCUMENT_HIGHLIGHT};constructor(e,t,r,i){this.projectPath=e,this.sdkPath=t,this.arktsLangServerPath=r,this.nodeMaxOldSpaceSize=i}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:zc.object({files:zc.array(zc.string()).describe('\u5F85\u68C0\u67E5\u7684 ETS \u6587\u4EF6\u8DEF\u5F84\u5217\u8868\uFF0C\u683C\u5F0F\u4E3A ["file1.ets","file2.ets",...]')})}}isInitializing(){return this.initializing}isInitialized(){return this.initialized}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initializing=!0,this.initPromise=this.doInitialize().then(()=>{this.initialized=!0}).finally(()=>{this.initializing=!1}),await this.initPromise}}async doInitialize(){let{harmonyRoot:e,arktsLangServerPath:t,useStandardProtocol:r}=this.resolveProjectAndDeveco();this.useStandardProtocol=r;let i=re(e),{logPath:o,indexPath:s}=this.getLogAndIndexPath(i);setImmediate(()=>{Fa(s,eP,"[ArkTS-Check]"),Fa(o,tP,"[ArkTS-Check]")}),fo(o);let a=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,c=Number.isNaN(a)?void 0:a;h.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${c??"undefined \u2192 dynamic formula applies"}`);let l=this.sdkPath;h.info(`[ArktsCheck] sdkPath=${l}, arktsLangServerPath=${t}, useStandardProtocol=${r}`),this.manager=new nr({sdkPath:l,arktsLangServerPath:t,workspaceRoot:j(i),indexLogPath:s,nodeMaxOldSpaceSize:c,useStandardProtocol:r}),this.manager.setOnMessage(p=>this.handleLspMessage(p)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((p,g)=>{this.initResolve=p,this.initReject=g,this.armInitTimer(Le),this.manager.start([]).catch(w=>{let C=w instanceof Error?w:new Error(String(w));this.failInit(C)})})}resolveProjectAndDeveco(){let e=ut(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.arktsLangServerPath;if(!t)throw new Error("arkts-lang-server path not found");let r=oo(t);return h.info(`ArktsCheck protocol: ${r?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${r})`),{harmonyRoot:e,arktsLangServerPath:t,useStandardProtocol:r}}armInitTimer(e){this.initDeadlineTimer&&clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=setTimeout(()=>{let t=this.initReject;this.clearInitHandlers(),t?.(new Error("LSP initialize timeout"))},e)}clearInitHandlers(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async checkFile(e){this.initialized||await this.initialize();let t=this.manager;if(!t)throw new Error("ArktsLspManager not initialized");let r=an(e),i=await Re.promises.readFile(e,"utf8"),s=`deveco.apptool.${De.extname(e).replace(/^\./,"")||"plaintext"}`;return t.useStandardProtocol?this.checkFileStandard(t,r,i,s):this.checkFileLegacy(t,e,r,i,s)}async checkFileStandard(e,t,r,i){h.debug(`textDocument/didOpen uri=${t} content_len=${r.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:r,languageId:i,version:1}});try{h.debug(`textDocument/diagnostic uri=${t}`);let o=await e.diagnostic({textDocument:{uri:t}});return rP(o)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:t}})}}async checkFileLegacy(e,t,r,i,o){let s=r;e.registerDiagnosticCallback(r);let a=new Promise((c,l)=>{let p=setTimeout(()=>{this.diagnosticWaiters.delete(s)&&l(new Error("Wait for diagnostics timeout"))},nP);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:p})});h.debug(`textDocument/didOpen(legacy) uri=${r} content_len=${i.length}`),e.onAsyncOpenFile({textDocument:{uri:r,text:i,languageId:o,version:i.length},editorFiles:[r],isFromEditor:!1});try{return await a}finally{e.closeFileLegacy(r,!1)}}async handleCall(e){if(!this.initialized)return this.buildNotReadyResponse();let t=[],r=[],i=this.collectValidFiles(e.files,t);return i.length===0?{content:[{type:"text",text:t.length>0?t.join(`
1270
+ `):"\u6CA1\u6709\u6709\u6548\u7684 .ets \u6587\u4EF6"}],isError:!0}:(await this.runDiagnosticsForFiles(i,t,r),this.formatCallResult(t,r))}async handleLspFeature(e,t){if(!this.initialized)return this.buildNotReadyResponse();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${t.file}`}],isError:!0};let i=n.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};h.info(`handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(r,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){let s=o instanceof Error?o.message:String(o);return h.error(`handleLspFeature ${e} failed: ${s}`),{content:[{type:"text",text:`${e} failed: ${s}`}],isError:!0}}}async handleWorkspaceSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();h.info(`handleWorkspaceSymbol: query="${e}"`);try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return{content:[{type:"text",text:t==null?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(t,null,2)}`}]}}catch(t){let r=t instanceof Error?t.message:String(t);return h.error(`handleWorkspaceSymbol failed: ${r}`),{content:[{type:"text",text:`workspaceSymbol failed: ${r}`}],isError:!0}}}async handleWorkspaceSymbolRaw(e){if(!this.initialized)return null;try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return h.error(`handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};h.info(`handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){let i=r instanceof Error?r.message:String(r);return h.error(`handleDocumentSymbol failed: ${i}`),{content:[{type:"text",text:`documentSymbol failed: ${i}`}],isError:!0}}}async handleCallHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,async o=>{let s=await this.manager.sendFeatureRequest(y.PREPARE_CALL_HIERARCHY,{textDocument:{uri:o},position:{line:e.line,character:e.character}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],calls:[]};let c=e.direction==="incoming"?y.INCOMING_CALLS:y.OUTGOING_CALLS,l=[];for(let p of a){let g=await this.manager.sendFeatureRequest(c,{item:p});Array.isArray(g)?l.push(...g):g&&l.push(g)}return{items:a,calls:l}});return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){let i=r instanceof Error?r.message:String(r);return h.error(`handleCallHierarchy failed: ${i}`),{content:[{type:"text",text:`callHierarchy failed: ${i}`}],isError:!0}}}async handleCodeAction(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleCodeAction: file=${t} line=${e.line} char=${e.character}`);try{let r=await this.withOpenFile(t,async o=>{let s={line:e.line,character:e.character};return this.manager.sendFeatureRequest(y.CODE_ACTION,{textDocument:{uri:o},range:{start:s,end:s},context:{diagnostics:[]}})});return{content:[{type:"text",text:r==null?"codeAction: no result":`codeAction: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("codeAction",r)}}async handleRename(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleRename: file=${t} line=${e.line} char=${e.character} newName=${e.newName}`);try{let r=await this.withOpenFile(t,async o=>{let s={line:e.line,character:e.character};if(await this.manager.sendFeatureRequest(y.PREPARE_RENAME,{textDocument:{uri:o},position:s})==null)throw new Error("Symbol at this position cannot be renamed");return this.manager.sendFeatureRequest(y.RENAME,{textDocument:{uri:o},position:s,newName:e.newName})});return{content:[{type:"text",text:r==null?"rename: no result":`rename: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("rename",r)}}async handleTypeHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleTypeHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.fetchTypeHierarchy(t,e.line,e.character,e.direction);return{content:[{type:"text",text:`typeHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("typeHierarchy",r)}}async handleCompletionItemResolve(e){if(!this.initialized)return this.buildNotReadyResponse();h.info("handleCompletionItemResolve");try{let t=await this.manager.sendFeatureRequest(y.COMPLETION_ITEM_RESOLVE,{item:e});return{content:[{type:"text",text:t==null?"completionItemResolve: no result":`completionItemResolve: ${JSON.stringify(t,null,2)}`}]}}catch(t){return this.buildErrorResponse("completionItemResolve",t)}}async fetchTypeHierarchy(e,t,r,i){return this.withOpenFile(e,async o=>{let s=await this.manager.sendFeatureRequest(y.PREPARE_TYPE_HIERARCHY,{textDocument:{uri:o},position:{line:t,character:r}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],results:[]};let c=i==="supertypes"?y.SUPERTYPES:y.SUBTYPES,l=await this.collectHierarchyItems(c,a);return{items:a,results:l}})}async collectHierarchyItems(e,t){let r=[];for(let i of t){let o=await this.manager.sendFeatureRequest(e,{item:i});Array.isArray(o)?r.push(...o):o&&r.push(o)}return r}async handleInlayHint(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};try{let i=(await Re.promises.readFile(t,"utf8")).split(`
1271
+ `).length,o=await this.withOpenFile(t,async a=>this.manager.sendFeatureRequest(y.INLAY_HINT,{textDocument:{uri:a},range:{start:{line:0,character:0},end:{line:i,character:0}}}));return{content:[{type:"text",text:o==null?"inlayHint: no result":`inlayHint: ${JSON.stringify(o,null,2)}`}]}}catch(r){return this.buildErrorResponse("inlayHint",r)}}async handleDocumentLink(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(y.DOCUMENT_LINK,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentLink: no result":`documentLink: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("documentLink",r)}}buildErrorResponse(e,t){let r=t instanceof Error?t.message:String(t);return h.error(`${e} failed: ${r}`),{content:[{type:"text",text:`${e} failed: ${r}`}],isError:!0}}async withOpenFile(e,t){let r=an(e),i=await Re.promises.readFile(e,"utf8"),s=`deveco.apptool.${De.extname(e).replace(/^\./,"")||"plaintext"}`;h.debug(`withOpenFile didOpen uri=${r} len=${i.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:r,text:i,languageId:s,version:i.length}});try{return await t(r)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:r},isManual:!1})}}resolveSingleFile(e){let t=De.isAbsolute(e)?e:De.join(this.projectPath,e);return!Re.existsSync(t)||!Re.statSync(t).isFile()||!t.endsWith(".ets")?null:t}buildNotReadyResponse(){return{content:[{type:"text",text:this.initializing?"LSP \u6B63\u5728\u521D\u59CB\u5316\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5":this.projectPath?"LSP\u672A\u521D\u59CB\u5316":"\u6CA1\u6709\u914D\u7F6E\u5DE5\u7A0B\u8DEF\u5F84\uFF0C\u8BF7\u914D\u7F6EPROJECT_PATH\u53C2\u6570"}],isError:!0}}collectValidFiles(e,t){let r=this.projectPath,i=[];for(let o of e){let s=De.isAbsolute(o)?o:De.join(r,o);if(!Re.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!Re.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${o}`);continue}if(!s.endsWith(".ets")){t.push(`\u4E0D\u662F .ets \u6587\u4EF6: ${o}`);continue}i.push(s)}return i}async runDiagnosticsForFiles(e,t,r){for(let i of e){await Hd(500);try{let o=await this.checkFile(i);r.push(iP(i,o))}catch(o){t.push(`${i} => wait for diagnostics failed: ${o.message}`)}}}formatCallResult(e,t){let r=[];e.length>0&&r.push(e.join(`
1272
+ `)),t.length>0&&r.push(t.join(`
1273
+ `));let i=r.join(`
1274
+ `).trim(),o=e.length>0;return!o&&t.length===0&&(i="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:i}],isError:o}}async shutdown(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(t){h.warn(`Failed to dispose ArktsLspManager: ${t}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,r=t.method;if(r)switch(r){case"textDocument/publishDiagnostics":{this.handleDiagnosticsNotification(t.params);break}case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(Le),h.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{h.info("Received arkts/initialized");let i=this.initResolve;this.clearInitHandlers(),i?.();break}case"arkts/initializationFailed":{let o=t.params?.message??"unknown";h.error(`LSP initialization failed: ${o}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${o}`));break}case"workspace/didChangeConfiguration":h.info("Received workspace/didChangeConfiguration, sync deferred to next check");break;default:break}}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let r=this.popDiagnosticWaiter(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.popDiagnosticWaiter(s)}if(!r)return;if(typeof e.errorMessage=="string"){h.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),r.resolve({errorMessage:e.errorMessage});return}let i=e.diagnostics,o=Array.isArray(i)?i.length:0;h.debug(`diagnostics received uri=${t} count=${o}`),r.resolve(Array.isArray(i)?i:[])}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}getLogAndIndexPath(e){try{let t=De.join(Tt(),"ArkTSCheck"),r=De.join(t,"mapping-config.properties"),i=Ud(e,r),o=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=De.join(t,"lsp-log",String(i),o),a=De.join(t,"lsp-index",String(i));return Re.mkdirSync(s,{recursive:!0}),Re.mkdirSync(a,{recursive:!0}),{logPath:re(s),indexPath:re(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function rP(n){if(Array.isArray(n))return n;if(n&&typeof n=="object"){let e=n;if(e.kind==="full"&&Array.isArray(e.items))return e.items}return[]}function iP(n,e){if(Array.isArray(e))return e.length===0?`${n} => no diagnostics`:`${n} => Diagnostic: ${JSON.stringify(e)}`;if(e&&typeof e=="object"&&typeof e.errorMessage=="string"){let t=e.errorMessage;return`${n} diagnostic failed, error_message: ${t}`}return`${n} => diagnostic failed, result: ${JSON.stringify(e)}`}import*as Bt from"fs";import*as Rs from"path";import{z as qc}from"zod";function ir(){return{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}}function Ds(n,e){let t=e instanceof Error?e.message:String(e);return h.error(`[CppLsp] ${n} failed: ${t}`),{content:[{type:"text",text:`${n} failed: ${t}`}],isError:!0}}var oP=500,or=class{manager;constructor(e){this.manager=e}static getToolDefinition(){return{name:"check_cpp_files",description:"Perform static syntax checks on the provided C/C++ files and return clangd diagnostics.",inputSchema:qc.object({files:qc.array(qc.string()).describe('List of C/C++ file paths to check, format: ["file1.cpp","file2.hpp",...]')})}}async handleCall(e){if(!this.manager.ready)return ir();let t=[],r=[],i=this.collectValidFiles(e.files,t);if(i.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
1275
+ `):"No valid C/C++ files"}],isError:!0};for(let c of i){await aP(oP);try{let l=await this.checkFile(c);r.push(sP(c,l))}catch(l){t.push(`${c} => wait for diagnostics failed: ${l.message}`)}}let o=t.length>0,s=[];t.length>0&&s.push(t.join(`
1276
+ `)),r.length>0&&s.push(r.join(`
1277
+ `));let a=s.join(`
1278
+ `).trim();return!o&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:o}}async checkFile(e){let t=an(e),r=await Bt.promises.readFile(e,"utf8"),i=ao(e),o=this.manager.registerDiagnosticCallback(t);this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:t,text:r,languageId:i,version:r.length}}});try{return await o}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:t}}})}}collectValidFiles(e,t){let r=this.manager.projectRoot,i=[];for(let o of e){let s=Rs.isAbsolute(o)?o:Rs.join(r,o);if(!Bt.existsSync(s)){t.push(`File does not exist: ${o}`);continue}if(!Bt.statSync(s).isFile()){t.push(`Not a regular file: ${o}`);continue}if(!sn(s)){t.push(`Not a supported C/C++ file: ${o}`);continue}try{i.push(Bt.realpathSync(s))}catch{i.push(s)}}return i}};function sP(n,e){if(Array.isArray(e))return e.length===0?`${n} => no diagnostics`:`${n} => Diagnostic: ${JSON.stringify(e)}`;if(e&&typeof e=="object"&&typeof e.errorMessage=="string"){let t=e.errorMessage;return`${n} diagnostic failed, error_message: ${t}`}return`${n} => diagnostic failed, result: ${JSON.stringify(e)}`}function aP(n){return new Promise(e=>setTimeout(e,n))}import*as ar from"fs";import*as ks from"path";var sr=class n{manager;static FEATURE_METHOD_MAP={hover:y.HOVER,definition:y.DEFINITION,declaration:y.DECLARATION,references:y.REFERENCES,implementation:y.IMPLEMENTATION};constructor(e){this.manager=e}async handleLspFeature(e,t){if(!this.manager.ready)return ir();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${t.file}`}],isError:!0};let i=n.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};h.info(`[ClangdLspTool] handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(r,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){return Ds(e,o)}}async handleWorkspaceSymbolRaw(e){if(!this.manager.ready)return null;try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return h.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return ir();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e}`}],isError:!0};h.info(`[ClangdLspTool] handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){return Ds("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return ir();if(e.direction==="outgoing")return{content:[{type:"text",text:"callHierarchy outgoing is not supported by clangd (incoming only)"}],isError:!0};let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e.file}`}],isError:!0};h.info(`[ClangdLspTool] handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,o=>this.fetchCallHierarchyResult(o,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return Ds("callHierarchy",r)}}async fetchCallHierarchyResult(e,t){let r=await this.manager.sendFeatureRequest(y.PREPARE_CALL_HIERARCHY,{textDocument:{uri:e},position:{line:t.line,character:t.character}}),i=this.normalizeCallHierarchyItems(r);if(i.length===0)return{items:[],calls:[]};let o=await this.collectIncomingCalls(i);return{items:i,calls:o}}normalizeCallHierarchyItems(e){return Array.isArray(e)?e:e?[e]:[]}async collectIncomingCalls(e){let t=[];for(let r of e)t.push(...await this.fetchIncomingCalls(r));return t}async fetchIncomingCalls(e){let t=await this.manager.sendFeatureRequest(y.INCOMING_CALLS,{item:e});return Array.isArray(t)?t:t?[t]:[]}async withOpenFile(e,t){let r=an(e),i=await ar.promises.readFile(e,"utf8"),o=ao(e);h.info(`[ClangdLspTool] withOpenFile didOpen uri=${r} langId=${o} len=${i.length}`),this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:r,text:i,languageId:o,version:i.length}}});try{return await t(r)}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:r}}})}}resolveSingleFile(e){let t=ks.isAbsolute(e)?e:ks.join(this.manager.projectRoot,e);return!ar.existsSync(t)||!ar.statSync(t).isFile()||!sn(t)?null:t}};import{spawn as cP}from"child_process";import*as xs from"fs";import*as zf from"path";var lP=30*1e3,dP=30*1e3,Ts=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new jt;diagnosticWaiters=new Map;lastStartErrorMessage=null;onMessage=()=>{};disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}async start(e){let t=!1;try{f.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),f.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),f.info(`[ClangdLspProxy] compileCommandsDir: ${this.config.compileCommandsDir}`),this.ensureLogDir(),this.clangdProcess=this.spawnClangd();let r={serverPath:"",logPath:this.config.logPath,indexingDataLocation:this.config.logPath,cwd:this.config.workspaceRoot};this.client=new Ft(r),this.client.on("message",o=>this.handleRawMessage(o)),this.client.on("error",o=>this.handleError(o)),this.client.attachProcess(this.clangdProcess,{stderrAsError:!1});let i=this.buildInitializeParams();await this.sendLspRequest(y.INITIALIZE,i,Le),f.info("[ClangdLspProxy] initialize response received"),this.sendNotification(y.INITIALIZED,{}),t=!0}catch(r){this.lastStartErrorMessage=r instanceof Error?r.message:String(r),f.error(`[ClangdLspProxy] initialization failed: ${this.lastStartErrorMessage}`),await this.dispose()}e?.(t)}async hover(e){return this.sendLspRequest(y.HOVER,e)}async definition(e){return this.sendLspRequest(y.DEFINITION,e)}async declaration(e){return this.sendLspRequest(y.DECLARATION,e)}async references(e){return this.sendLspRequest(y.REFERENCES,e)}async implementation(e){return this.sendLspRequest(y.IMPLEMENTATION,e)}async documentSymbol(e){return this.sendLspRequest(y.DOCUMENT_SYMBOL,e)}async workspaceSymbol(e){return this.sendLspRequest(y.WORKSPACE_SYMBOL,e)}async prepareCallHierarchy(e){return this.sendLspRequest(y.PREPARE_CALL_HIERARCHY,e)}async incomingCalls(e){return this.sendLspRequest(y.INCOMING_CALLS,e)}async sendFeatureRequest(e,t){return this.sendLspRequest(e,t)}sendDidOpen(e){this.sendNotification(y.DID_OPEN,e)}sendDidChange(e){this.sendNotification(y.DID_CHANGE,e)}sendDidClose(e){this.sendNotification(y.DID_CLOSE,e)}sendNotification(e,t){if(!this.client){f.warn("[ClangdLspProxy] sendNotification before ready, dropped");return}this.client.sendNotification(e,t)}registerDiagnosticCallback(e){let t=this.normalizeClangdUri(e);if(this.diagnosticWaiters.has(t)){f.warn(`[ClangdLspProxy] overwrite existing diagnostic waiter for ${t}`);let r=this.diagnosticWaiters.get(t);clearTimeout(r.timer),this.diagnosticWaiters.delete(t)}return new Promise((r,i)=>{let o=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&i(new Error(`Wait for clangd diagnostics timeout, uri: ${t}`))},dP);this.diagnosticWaiters.set(t,{resolve:r,reject:i,timer:o})})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){this.requestCallbacks.rejectAll(new Error("ClangdLspProxy disposing"));for(let[,e]of this.diagnosticWaiters)clearTimeout(e.timer),e.reject(new Error("ClangdLspProxy disposing"));if(this.diagnosticWaiters.clear(),this.client&&this.clangdProcess)try{await this.sendLspRequest(y.SHUTDOWN,null,3e3).catch(e=>{f.warn(`[ClangdLspProxy] shutdown request failed: ${e}`)}),this.sendNotification(y.EXIT,null),await this.client.waitForExitOrTimeout(300)}catch(e){f.warn(`[ClangdLspProxy] dispose error: ${e}`)}if(this.clangdProcess){try{this.clangdProcess.exitCode===null&&this.clangdProcess.signalCode===null&&this.clangdProcess.kill()}catch{}this.clangdProcess=null}this.client=null}spawnClangd(){let e=[`--compile-commands-dir=${j(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];f.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=cP(this.config.clangdPath,e,{cwd:this.config.workspaceRoot,stdio:["pipe","pipe","pipe"],windowsHide:!0});if(!t.stdin||!t.stdout||!t.stderr)throw new Error("Failed to spawn clangd: stdio not available");return t}buildInitializeParams(){let e=xn(this.config.workspaceRoot),t=qe(e),r=zf.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.3.0-Test.10"},rootPath:e,rootUri:t,workspaceFolders:[{uri:t,name:r}],capabilities:this.buildClientCapabilities(),initializationOptions:null}}buildClientCapabilities(){return{textDocument:{synchronization:{didOpen:!0,didChange:!0,didClose:!0,willSave:!1,save:!1},publishDiagnostics:{relatedInformation:!0,versionSupport:!1,tagSupport:{valueSet:[1,2]}},hover:{contentFormat:["markdown","plaintext"]},completion:{contextSupport:!1,completionItemKind:{valueSet:[]}},signatureHelp:{signatureInformation:{documentationFormat:["markdown","plaintext"]}},references:{},declaration:{linkSupport:!0},definition:{linkSupport:!0},implementation:{linkSupport:!0},documentSymbol:{hierarchicalDocumentSymbolSupport:!0,symbolKind:{valueSet:[]}},callHierarchy:{dynamicRegistration:!1}},workspace:{symbol:{symbolKind:{valueSet:[]}},configuration:!1,didChangeWatchedFiles:{dynamicRegistration:!1}}}}sendLspRequest(e,t,r=lP){if(!this.client)return Promise.reject(new Error("[ClangdLspProxy] client not ready"));let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,r);return this.client.sendRequest(e,t,i),o}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let i=r instanceof Error?r.message:String(r);f.error(`[ClangdLspProxy] JSON parse error: ${i}, raw: ${e.slice(0,200)}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotification(t):f.warn(`[ClangdLspProxy] unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t==null||typeof t!="string"&&typeof t!="number")return;let r=t;if(e.error!==void 0){let i=e.error;f.warn(`[ClangdLspProxy] LSP error id=${r}: code=${i.code??-1} message=${i.message??"unknown"}`),this.requestCallbacks.rejectPending(r,new Error(`LSP error ${i.code??-1}: ${i.message??"unknown"}`))}else this.requestCallbacks.resolvePending(r,e.result)}handleNotification(e){let t=e.method;if(t)switch(t){case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.onMessage({jsonrpc:R,method:y.PROGRESS,params:e.params});break;case y.WINDOW_SHOW_MESSAGE:f.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:f.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:R,method:t,params:e.params})}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=this.normalizeClangdUri(e.uri),r=this.diagnosticWaiters.get(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.diagnosticWaiters.get(s),r&&this.diagnosticWaiters.delete(s)}else r&&this.diagnosticWaiters.delete(t);if(!r)return;clearTimeout(r.timer);let i=Array.isArray(e.diagnostics)?e.diagnostics:[],o=i.length;f.info(`[ClangdLspProxy] diagnostics received uri=${t} count=${o}`),r.resolve(i)}handleError(e){for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear(),this.requestCallbacks.rejectAll(e),this.onMessage({jsonrpc:R,method:y.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{xs.existsSync(this.config.logPath)||xs.mkdirSync(this.config.logPath,{recursive:!0})}catch{}}normalizeClangdUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=decodeURIComponent(t.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(r)&&(r=r.slice(1)),qe(r)}}catch{}return e}};import*as li from"path";import*as Yc from"fs";var di=class{config;proxy=null;isInitialized=!1;onMessage=()=>{};disposeOnce=null;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;resolvedRoot="";constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}get ready(){return this.isInitialized&&this.proxy!==null}get projectRoot(){return this.resolvedRoot}async start(){if(!this.isInitialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doStart();try{await this.initPromise}catch(e){throw this.initPromise=null,e}}}sendNotification(e){if(!this.proxy){f.warn("[ClangdLspManager] sendNotification before LSP ready, dropped");return}this.dispatchNotification(e)}async sendFeatureRequest(e,t){if(!this.proxy)throw new Error("[ClangdLspManager] LSP not ready");return this.proxy.sendFeatureRequest(e,t)}registerDiagnosticCallback(e){return this.proxy?this.proxy.registerDiagnosticCallback(e):Promise.reject(new Error("[ClangdLspManager] LSP not ready"))}static async handleSyncCppProject(e,t){if(f.info("[ClangdLspManager] Received cpp/syncProject"),!e||!t)return f.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};if(ln(e).length===0)return f.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let i=await Zi(e,async()=>{try{return await nu(e,t),f.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(o){let s=o instanceof Error?o.message:String(o);return f.error(`[ClangdLspManager] compileNative failed: ${s}`),{status:"failed",reason:s}}});return i.acquired?i.result:(f.info("[ClangdLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}doStart(){return new Promise((e,t)=>{this.initResolve=e,this.initReject=t,this.armInitTimer(Le);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=ut(this.config.workspaceRoot);this.resolvedRoot=e?re(e):re(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();fo(t);let r=so(this.config.sdkPath);if(!r){let s=`clangd executable not found under sdk: ${this.config.sdkPath}`;f.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let i=li.dirname(Ar(this.resolvedRoot));try{Yc.mkdirSync(i,{recursive:!0})}catch(s){f.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${s}`)}f.info(`[ClangdLspManager] clangdPath: ${r}`),f.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),f.info(`[ClangdLspManager] compileCommandsDir: ${i}`);let o=new Ts({clangdPath:r,workspaceRoot:this.resolvedRoot,compileCommandsDir:i,logPath:t});o.setOnMessage(s=>this.handleLspMessage(s)),this.proxy=o,o.start(s=>this.handleProxyInitialized(s)).catch(s=>{let a=s instanceof Error?s:new Error(String(s));this.handleProxyInitialized(!1,a.message)})}handleProxyInitialized=(e,t)=>{if(this.clearInitTimer(),e){this.isInitialized=!0,f.info("[ClangdLspManager] clangd initialized");let r=this.initResolve;this.clearInitHandlers(),r?.()}else{let r=t??this.proxy?.consumeStartErrorMessage()??"unknown error";f.error(`[ClangdLspManager] clangd initialization failed: ${r}`),this.isInitialized=!1,this.proxy=null;let i=this.initReject;this.clearInitHandlers(),i?.(new Error(`C++ LSP initialize failed: ${r}`))}};handleLspMessage(e){this.onMessage(e)}dispatchNotification(e){if(!this.proxy)return;let t=e,r=t.method;if(!r){f.warn("[ClangdLspManager] dispatchNotification: missing method");return}let i=t.params;switch(r){case y.DID_OPEN:this.proxy.sendDidOpen(i);break;case y.DID_CHANGE:this.proxy.sendDidChange(i);break;case y.DID_CLOSE:this.proxy.sendDidClose(i);break;default:this.proxy.sendNotification(r,i)}}armInitTimer(e){this.clearInitTimer(),this.initDeadlineTimer=setTimeout(()=>{this.failInit(new Error("C++ LSP initialize timeout"))},e)}clearInitTimer(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null)}clearInitHandlers(){this.clearInitTimer(),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async performDispose(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("ClangdLspManager disposing")),this.proxy){try{await this.proxy.dispose()}catch(t){f.warn(`[ClangdLspManager] proxy dispose error: ${t}`)}this.proxy=null}this.isInitialized=!1,this.initPromise=null}getLogPath(){try{let e=li.join(Tt(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=li.join(e,"lsp-log",t);return Yc.mkdirSync(r,{recursive:!0}),re(r)}catch{return"auto"}}};function qf(n){let e=eo(n);return f.info(`[SyncGuard] ${e.reason}`),e}var Kc=(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))(Kc||{}),Yf=(s=>(s[s.IDLE_CPP=0]="IDLE_CPP",s[s.DISCOVERING_CPP=1]="DISCOVERING_CPP",s[s.SYNCING_CPP=2]="SYNCING_CPP",s[s.INITIALIZING_CPP=3]="INITIALIZING_CPP",s[s.READY_CPP=4]="READY_CPP",s[s.ERROR_CPP=5]="ERROR_CPP",s))(Yf||{}),Wt=3,Jc=600*1e3,Ls=class{server;toolRouter;config={};arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";sdkPath="";arktsLangServerPath=null;initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;standardProtocolAvailable=!1;cppProjectState=0;cppInitPromise=null;cppNeedsReinit=!1;cppInitRetryCount=0;cppSyncSkippedDueToLock=!1;cppSyncSkipStartedAt=0;cppHasNoCppCode=!1;constructor(e={}){this.config=e,cn(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),h.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",h.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,h.info(`Constructor: using configured path as startPath: '${t}'`));let i=ut(t);h.info(`Constructor: findHarmonyProject('${t}') => ${i??"null"}`),this.config.projectPath=i??void 0;let o=io(this.config.devecoPath);this.sdkPath=o.sdkPath,this.arktsLangServerPath=o.arktsLangServerPath,h.info(`Constructor: sdkPath='${this.sdkPath}', arktsLangServerPath='${this.arktsLangServerPath??"(null)"}'`),this.server=new uP({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=Bc(),this.standardProtocolAvailable=this.detectStandardProtocolAvailable(),this.registerTools()}registerTools(){this.registerCheckTool(),this.registerLspFeatureTools()}registerCheckTool(){this.toolRouter.add({name:"check",description:"Perform static syntax analysis on HarmonyOS project source files and return structured diagnostics. Supported languages: ArkTS and C/C++.",inputSchema:ue.object({files:ue.array(ue.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))}registerLspFeatureTools(){if(!this.standardProtocolAvailable){h.info("Skip registering LSP feature tools (hover/definition/declaration/references/implementation, workspaceSymbol, documentSymbol, callHierarchy): standard LSP protocol unavailable (standardIndex/index.js not found). These tools require a DevEco Studio version that ships the standard LSP server entry.");return}let e=ue.object({file:ue.string().describe("Source file path, relative to the project root. Supports .ets (ArkTS) and C/C++ extensions."),line:ue.number().describe("Line number (0-based)"),character:ue.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:r,feature:i}of this.getPositionFeatures())this.toolRouter.add({name:t,description:r,inputSchema:e},async o=>this.handleLspFeatureCall(i,o));this.registerSymbolTools(),this.registerCallHierarchyTool()}getPositionFeatures(){return[{name:"hover",description:"Get hover information (type info, documentation) at a specific position in an ArkTS (.ets) or C/C++ file.",feature:"hover"},{name:"definition",description:"Find where the symbol at the given position is defined. Returns file path, line, and character.",feature:"definition"},{name:"declaration",description:"Find the declaration of the symbol at the given position. In ArkTS, this may differ from definition.",feature:"declaration"},{name:"references",description:"Find all references to the symbol at the given position across the HarmonyOS project.",feature:"references"},{name:"implementation",description:"Find implementations of the symbol at the given position (e.g., interface implementations).",feature:"implementation"}]}registerSymbolTools(){this.toolRouter.add({name:"workspaceSymbol",description:"Search for symbols by name across the entire HarmonyOS project.",inputSchema:ue.object({query:ue.string().describe("Symbol name (or partial) to search for")})},async e=>this.handleWorkspaceSymbolCall(e)),this.toolRouter.add({name:"documentSymbol",description:"Get the symbol tree (functions, classes, variables with ranges) of an ArkTS (.ets) or C/C++ file. Useful for file overview, structured code breakdown, and large file slicing.",inputSchema:ue.object({file:ue.string().describe("Source file path, relative to the project root. Supports .ets and C/C++ extensions.")})},async e=>this.handleDocumentSymbolCall(e))}registerCallHierarchyTool(){this.toolRouter.add({name:"callHierarchy",description:'Query call hierarchy for a function at the given position. Use direction "incoming" to find callers, "outgoing" to find callees. ArkTS supports both directions; C/C++ (clangd) supports incoming only.',inputSchema:ue.object({file:ue.string().describe("Source file path, relative to the project root. Supports .ets and C/C++ extensions."),line:ue.number().describe("Line number (0-based)"),character:ue.number().describe("Character offset in the line (0-based)"),direction:ue.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.arktsLangServerPath;if(!e)return h.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=oo(e);return h.info(`ArktsCheck protocol: ${t?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${t})`),t}catch(e){return h.warn(`Failed to detect standard LSP protocol availability: ${e}`),!1}}validateContainment(e){let t=this.config.projectPath;if(t){let i=[];for(let o of e){let s=P.isPathContainedWithSymlink(o,t);s.contained||(h.warn(`Containment check failed: ${s.reason}`),i.push(s.reason))}return i.length>0?{content:[{type:"text",text:i.join(`
1279
+ `)}],isError:!0}:null}let r=e.filter(i=>Ns.isAbsolute(i));return r.length>0?(h.warn(`Absolute paths rejected (no project root): ${r.join(", ")}`),{content:[{type:"text",text:r.map(i=>`Absolute path is not allowed: ${i}`).join(`
1280
+ `)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(g=>typeof g=="string"):[];if(t.length===0)return h.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};let r=this.validateContainment(t);if(r)return r;let{etsFiles:i,cppFiles:o,unsupported:s}=fP(t);s.length>0&&h.warn(`Unsupported file types in check request: ${s.join(", ")}`);let a=s.map(g=>`Unsupported file type: ${g} (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 l=a.length>0;return{content:[{type:"text",text:[c.join(`
1261
1281
  `),a.join(`
1262
1282
  `)].filter(g=>g.trim().length>0).join(`
1263
- `).trim()||"No diagnostics collected"}],isError:d}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return u.warn(`ArkTS check rejected: project is ${ci[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return u.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 handleLspFeatureCall(e,t){let n=t.file,i=t.line,o=t.character;if(typeof n!="string"||typeof i!="number"||typeof o!="number")return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};let s=this.validateContainment([n]);return s||this.callArktsFeature(e,{file:n,line:i,character:o})}async handleWorkspaceSymbolCall(e){let t=e.query;return typeof t!="string"||t.trim().length===0?{content:[{type:"text",text:"Missing or invalid parameter: query (non-empty string required)."}],isError:!0}:this.callArktsWorkspaceSymbol(t)}async handleDocumentSymbolCall(e){let t=e.file;if(typeof t!="string")return{content:[{type:"text",text:"Missing or invalid parameter: file (string required)."}],isError:!0};let n=this.validateContainment([t]);return n||this.routeArktsRequest("documentSymbol",()=>this.arktsCheckTool.handleDocumentSymbol(t))}async handleCallHierarchyCall(e){let t=e.file,n=e.line,i=e.character,o=e.direction;if(typeof t!="string"||typeof n!="number"||typeof i!="number")return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};if(o!=="incoming"&&o!=="outgoing")return{content:[{type:"text",text:'Parameter direction must be "incoming" or "outgoing".'}],isError:!0};let s=this.validateContainment([t]);return s||this.routeArktsRequest(`callHierarchy(${o})`,()=>this.arktsCheckTool.handleCallHierarchy({file:t,line:n,character:i,direction:o}))}async handleCodeActionCall(e){let{file:t,line:n,character:i}=this.extractPositionArgs(e);if(!t)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};let o=this.validateContainment([t]);return o||this.routeArktsRequest("codeAction",()=>this.arktsCheckTool.handleCodeAction({file:t,line:n,character:i}))}async handleRenameCall(e){let{file:t,line:n,character:i}=this.extractPositionArgs(e),o=e.newName;if(!t||typeof o!="string"||o.trim().length===0)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number), newName (non-empty string)."}],isError:!0};let s=this.validateContainment([t]);return s||this.routeArktsRequest("rename",()=>this.arktsCheckTool.handleRename({file:t,line:n,character:i,newName:o}))}async handleTypeHierarchyCall(e){let{file:t,line:n,character:i}=this.extractPositionArgs(e),o=e.direction;if(!t)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};if(o!=="supertypes"&&o!=="subtypes")return{content:[{type:"text",text:'Parameter direction must be "supertypes" or "subtypes".'}],isError:!0};let s=this.validateContainment([t]);return s||this.routeArktsRequest(`typeHierarchy(${o})`,()=>this.arktsCheckTool.handleTypeHierarchy({file:t,line:n,character:i,direction:o}))}async handleCompletionItemResolveCall(e){let t=e.item;return t==null?{content:[{type:"text",text:"Missing parameter: item (completion item object required)."}],isError:!0}:this.routeArktsRequest("completionItemResolve",()=>this.arktsCheckTool.handleCompletionItemResolve(t))}extractPositionArgs(e){let t=e.file,n=e.line,i=e.character;return typeof t!="string"||typeof n!="number"||typeof i!="number"?{file:null,line:0,character:0}:{file:t,line:n,character:i}}async callArktsFeature(e,t){return this.routeArktsRequest(e,()=>this.arktsCheckTool.handleLspFeature(e,t))}async callArktsWorkspaceSymbol(e){return this.routeArktsRequest("workspaceSymbol",()=>this.arktsCheckTool.handleWorkspaceSymbol(e))}async routeArktsRequest(e,t){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return u.warn(`ArkTS ${e} rejected: project is ${ci[this.projectState]}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return u.warn(`ArkTS ${e} rejected: LSP is initializing`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return t()}}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"),u.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(u.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}):(u.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>=ai?(u.error(`Init retry limit reached (${this.initRetryCount}/${ai}), will not auto-retry`),{content:[{type:"text",text:"Project initialization failed multiple times. Please check project configuration and restart the MCP Server."}],isError:!0}):(u.info(`Error check: auto-retrying (${this.initRetryCount}/${ai})`),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 u.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(`
1264
- `);i&&(e.isError?t.push(i):n.push(i))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{u.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool&&(this.cppCheckTool.shutdown().catch(t=>{u.warn("Failed to shutdown CppCheckTool during setProjectPath:",t)}),this.cppCheckTool=null),this.initPromise?(this.needsReinit=!0,u.info("Project path changed while init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{u.warn("Failed to re-init project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new Qu;if(await this.server.connect(e),u.info("devecocli-mcp-server started"),!this.config.debug){let t=ks();t&&u.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=ge(t);n?(u.info(`Detected project path from client root: ${n}`),this.config.projectPath=n,this.sdkPath=this.computeSdkPath()):u.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?u.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):u.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{u.warn("Background project init failed:",t)}),this.initializeCppCheck()}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return u.warn("Client did not provide any roots"),null;let n=t.uri;return this.resolveFileUri(n)}catch(e){return u.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){u.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,u.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{u.info("shutdown completed, exiting process"),process.exit(0)}).catch(n=>{u.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){u.warn("C++ LSP initialization skipped: project path is not configured");return}this.cppCheckTool=new mt(e,this.config.devecoPath??null),u.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=>{u.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?ge(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=ge(this.originalProjectPath),t&&u.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 ft(this.config.projectPath,this.config.devecoPath??null,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{u.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,u.info("Project fully initialized, check tool is available")}catch(e){u.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=ta(e,this.config.forceSync??!1);return t.required?(u.info(`Sync required: ${t.reason}`),this.runSync(e)):(u.info(`Sync skipped: ${t.reason}`),!0)}async runSync(e){this.projectState=2,u.info("Starting project sync...");let t=await ht.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>=na?(u.error(`Sync skipped for ${i}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(u.warn(`Sync skipped: ${t.reason}, resetting to IDLE for retry (elapsed ${i}s / ${na/1e3}s)`),this.projectState=0,!1)}case"failed":return u.error(`Project sync failed: ${t.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}computeSdkPath(){let e=vn(this.config.devecoPath??""),t=ee(e);return vt.join(t,"sdk")}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppCheckTool&&await this.cppCheckTool.shutdown();try{await this.server.close()}catch(e){u.warn("Failed to close MCP server connection:",e)}u.info("devecocli-mcp-server stopped"),As(),Is()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function ep(r){let e=[],t=[],n=[];for(let i of r)vt.extname(i).toLowerCase()===".ets"?e.push(i):wn(i)?t.push(i):n.push(i);return{etsFiles:e,cppFiles:t,unsupported:n}}function li(r={}){return new nr(r)}import*as di from"fs";import*as wt from"path";import{spawn as tp}from"child_process";async function ra(r){Lt(!1);let{serverPath:e,logPath:t,projectPath:n,sdkPath:i,serverMaxSize:o}=await np(r),s=sp(e,t,n,i,o);u.info("ace-server started, bridging stdio (initialize is left to the client)"),cp(s)}async function np(r){let e=await rp();e||(u.error("DevEco Studio not found. Ensure DevEco Studio is installed."),process.exit(1));let t=te(r.projectPath??process.cwd()),n=wt.join(ee(e),"sdk"),i=gn(e);i||(u.error("ace-server not found in DevEco Studio installation."),process.exit(1));let o=wt.resolve(i,"ace-server","out","standardIndex","index.js"),s=wt.join(tt(),"lsp-server",String(Date.now()));di.mkdirSync(s,{recursive:!0});let a=ip(t,n);return u.info(`projectPath=${t}, sdkPath=${n}, serverPath=${o}, logPath=${s}, serverMaxSize=${a}MB`),{projectPath:t,sdkPath:n,serverPath:o,logPath:s,serverMaxSize:a}}function rp(){return O.new().then(r=>r.devecoStudioPath).catch(()=>ye())}function ip(r,e){let t=process.env.NODE_MAX_OLD_SPACE_SIZE,n=t?parseInt(t,10):NaN,i=Number.isFinite(n)&&n>0?n:void 0,o=op(r,e),s=Cn(o,i);return u.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${o}, override=${i??"none"})`),s}function op(r,e){try{let t=[];return new Ue(r,e).getAllDependencyMap(t).status==="OK"?t.length:new we(r).getAllModuleInfo().length}catch{return 0}}function sp(r,e,t,n,i){let o=wt.join(e,"lspLog");di.mkdirSync(o,{recursive:!0});let s=ap(r,o,t,n,i),a=process.execPath??"node";return u.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),tp(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function ap(r,e,t,n,i){let o=N(e);return["--expose-gc",`--max-old-space-size=${i}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${o}`,r,"--stdio",`--logger-path=${o}`,"--logger-level=TRACE",`--projectPath=${N(t)}`,`--sdkPath=${N(n)}`]}function cp(r){r.stdout?.on("data",e=>process.stdout.write(e)),r.stderr?.on("data",e=>{u.error(`[ace-server] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{r.stdin?.write(e)}),process.stdin.on("end",()=>{u.info("Editor disconnected, shutting down"),r.kill(),process.exit(0)}),r.on("exit",e=>{u.info(`ace-server exited with code ${e}`),process.exit(e??0)})}async function dp(){let r=process.env.PROJECT_PATH||"",e=process.env.DEVECO_PATH,t=process.env.NODE_MAX_OLD_SPACE_SIZE,n=process.env.DEBUG==="true"||process.env.DEBUG==="1",i=process.env.DEVECO_MCP_FORCE_SYNC==="1",o=await O.new(),s=r,a=e??o.devecoStudioPath,c=li({projectPath:s,devecoPath:a,nodeMaxOldSpaceSize:t,debug:n,forceSync:i}),d=async()=>{await c.shutdown(),process.exit(0)};process.once("SIGINT",d),process.once("SIGTERM",d),process.platform==="win32"&&process.once("SIGBREAK",d);try{await c.start()}catch(p){console.error("Failed to start MCP server:",p),process.exit(1)}}var ui=new lp("serve").description("Host bundled auxiliary protocol servers");ui.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await dp()});ui.command("lsp").description("Start a bundled LSP language server").option("--arkts","Start the ArkTS language server (ace-server)").option("--project-path <path>","HarmonyOS project root path",process.cwd()).action(async r=>{r.arkts||(console.error("Use --arkts to start the ArkTS language server."),process.exit(1)),await ra({projectPath:r.projectPath})});var ia=ui;import{Command as wp,InvalidArgumentError as fi}from"commander";import{red as Vt,dim as bp}from"colorette";import*as Q from"path";import*as ae from"fs";import{homedir as up}from"os";import{execa as pp}from"execa";import{rgPath as hp}from"@vscode/ripgrep";import fp from"adm-zip";import{fileURLToPath as mp}from"url";import gp from"ora";var zt=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],qt={"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 yp="deveco-cli",vp="docs",pi=class{docsDir;versionFile;initialized=!1;initPromise=null;constructor(){this.docsDir=Q.join(up(),".local","share",yp,vp),this.versionFile=Q.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.3.0-Test.1"}async getExistingVersion(){try{return(await ae.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=gp({text:"Extracting documentation\u2026",color:"cyan"}).start();try{let i=Q.dirname(this.docsDir);await ae.promises.mkdir(i,{recursive:!0}),await this.cleanOldDocs(),await ae.promises.mkdir(this.docsDir,{recursive:!0}),new fp(t).extractAllTo(this.docsDir,!0),await ae.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=mp(e),n=Q.dirname(t),i=[Q.join(n,"..","docs.zip")];for(let o of i)if(ae.existsSync(o))return o;return null}async cleanOldDocs(){try{await ae.promises.rm(this.docsDir,{recursive:!0,force:!0})}catch{}}async search(e,t){await this.ensureInitialized();let n=t?Q.join(this.docsDir,qt[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 p=await this.readContentPreview(c.filePath);return{title:c.metadata.title,documentId:d,content:p}}))).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 pp(hp,["--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(`
1265
- `),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=>D.isPathContainedWithSymlink(i,this.docsDir).contained).map(i=>Q.join(this.docsDir,i));for(let i of n)try{return await ae.promises.readFile(i,"utf-8")}catch{continue}throw new Error(`Document not found: ${e}`)}parseFilePath(e){if(!e.endsWith(".md"))return null;let t=Q.relative(this.docsDir,e);if(!t||t.startsWith("..")||Q.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 ae.promises.readFile(t,"utf-8");return JSON.parse(n)}catch{return null}}async readContentPreview(e){try{let t=await ae.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""}}},hi=new pi;function oa(...r){return e=>{if(!r.includes(e))throw new fi(`Allowed values: ${r.join(", ")}`);return e}}function Sp(r){let e=Number(r);if(!Number.isInteger(e)||e<=0)throw new fi("Must be a positive integer.");return e}var Pp=oa("json","default"),Ep=oa("json","default"),rr=new wp("docs").description("Search and read HarmonyOS documentation from local docs directory");rr.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all : all catalogs)",Cp,"all").option("--format <fmt>","Output format (default, json)",Pp,"default").option("--limit <n>","Max number of results",Sp,20).action(async(r,e)=>{try{let t=r.map(s=>s.trim()).filter(s=>s);t.length===0&&(console.error(Vt("Keywords cannot be empty.")),process.exit(1)),t.length>10&&(console.error(Vt("Keywords cannot exceed 10.")),process.exit(1));let n=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=(await hi.search(t,n)).slice(0,e.limit);e.format==="json"?console.log(JSON.stringify(o,null,2)):Dp(o)}catch(t){console.error(Vt(t.message)),process.exit(1)}});rr.command("read <documentId>").description("Read full content of a document by document ID").action(async r=>{try{let e=r.trim();e||(console.error(Vt("Document ID cannot be empty.")),process.exit(1));let t=await hi.readDocument(e);console.log(t)}catch(e){console.error(Vt(e.message)),process.exit(1)}});rr.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (options: default,json)",Ep,"default").action(r=>{if(r.format==="json"){let e=zt.map(t=>({name:t,title:qt[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of zt)console.log(` ${e.padEnd(20)} ${bp(qt[e])}`)});function Cp(r){if(r==="all")return"all";if(!zt.includes(r))throw new fi(`Invalid catalog "${r}". Allowed: all, ${zt.join(", ")}`);return r}function Dp(r){for(let e=0;e<r.length;e++){let t=r[e];console.log(t.documentId),console.log(` Title: ${t.title}`),t.content&&console.log(` Content: ${t.content}`),e<r.length-1&&console.log()}}var sa=rr;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";Ip();V.name("devecocli").description("HarmonyOS application development command line tool").version("1.3.0-Test.1");V.addCommand(Di);V.addCommand(Oi);V.addCommand(Fi);V.addCommand(Ji);V.addCommand(yo);V.addCommand(qo);V.addCommand(Jo);V.addCommand(os);V.addCommand(hs);V.addCommand(ia);V.addCommand(sa);var mi=process.argv.slice(2);mi.length>=2&&mi[mi.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var kp=new Set(["update"]);V.hook("preAction",async(r,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==V;)t=t.parent;kp.has(t.name())||await O.checkVersion()});V.parseAsync(process.argv).catch(r=>{let e=r instanceof Error?r.message:String(r??"Unknown error");console.error(Ap(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&r instanceof Error&&r.stack&&console.error(r.stack),process.exit(1)});
1283
+ `).trim()||"No diagnostics collected"}],isError:l}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return h.warn(`ArkTS check rejected: project is ${Kc[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return h.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return this.arktsCheckTool.handleCall({files:e});default:return h.error(`ArkTS check: unknown project state ${this.projectState}, files: ${e.join(", ")}`),{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],isError:!0}}}async handleLspFeatureCall(e,t){let r=t.file,i=t.line,o=t.character;if(typeof r!="string"||typeof i!="number"||typeof o!="number")return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};let s=this.validateContainment([r]);return s||this.routeLspRequest(r,e,async()=>{if(r.endsWith(".ets"))return this.arktsCheckTool.handleLspFeature(e,{file:r,line:i,character:o});let a=e;return this.cppLspTool.handleLspFeature(a,{file:r,line:i,character:o})})}async handleWorkspaceSymbolCall(e){let t=e.query;return typeof t!="string"||t.trim().length===0?{content:[{type:"text",text:"Missing or invalid parameter: query (non-empty string required)."}],isError:!0}:this.routeWorkspaceSymbolRequest(t)}async routeWorkspaceSymbolRequest(e){let t=this.projectState===4&&this.arktsCheckTool!==null,r=this.cppProjectState===4&&!this.cppHasNoCppCode&&this.cppLspTool!==null;if(!t&&!r){let a=this.describeArktsState(),c=this.describeCppState();return h.info(`workspaceSymbol rejected: ArkTS ${a}; C++ ${c}`),{content:[{type:"text",text:`workspaceSymbol: ArkTS ${a}; C++ ${c}`}],isError:!0}}let i=[],o=new Set;if(t)try{this.mergeSymbolItems(await this.arktsCheckTool.handleWorkspaceSymbolRaw(e),o,i)}catch(a){h.warn(`workspaceSymbol ArkTS query failed: ${a.message}`)}if(r)try{this.mergeSymbolItems(await this.cppLspTool.handleWorkspaceSymbolRaw(e),o,i)}catch(a){h.warn(`workspaceSymbol C++ query failed: ${a.message}`)}return{content:[{type:"text",text:i.length===0?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(i,null,2)}`}]}}symbolDedupKey(e){let t=e,r=t?.location?.uri??"",i=t?.location?.range?.start?.line??0,o=t?.location?.range?.start?.character??0;return`${r}:${i}:${o}`}mergeSymbolItems(e,t,r){if(e)for(let i of e){let o=this.symbolDedupKey(i);t.has(o)||(t.add(o),r.push(i))}}describeArktsState(){switch(this.projectState){case 0:return"idle";case 1:return"discovering";case 2:return"syncing (retry 10s)";case 3:return"initializing (retry 10s)";case 5:return`error (${this.initRetryCount}/${Wt})`;case 4:return"ready";default:return"unknown"}}describeCppState(){switch(this.cppProjectState){case 0:return"idle";case 1:return"discovering";case 2:return"syncing (retry 25s)";case 3:return"initializing (retry 10s)";case 5:return`error (${this.cppInitRetryCount}/${Wt})`;case 4:return this.cppHasNoCppCode?"ready (no C++ code)":"ready";default:return"unknown"}}async handleDocumentSymbolCall(e){let t=e.file;if(typeof t!="string")return{content:[{type:"text",text:"Missing or invalid parameter: file (string required)."}],isError:!0};let r=this.validateContainment([t]);return r||this.routeLspRequest(t,"documentSymbol",async()=>t.endsWith(".ets")?this.arktsCheckTool.handleDocumentSymbol(t):this.cppLspTool.handleDocumentSymbol(t))}async handleCallHierarchyCall(e){let t=e.file,r=e.line,i=e.character,o=e.direction;if(typeof t!="string"||typeof r!="number"||typeof i!="number")return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};if(o!=="incoming"&&o!=="outgoing")return{content:[{type:"text",text:'Parameter direction must be "incoming" or "outgoing".'}],isError:!0};let s=this.validateContainment([t]);return s||this.routeLspRequest(t,`callHierarchy(${o})`,async()=>t.endsWith(".ets")?this.arktsCheckTool.handleCallHierarchy({file:t,line:r,character:i,direction:o}):this.cppLspTool.handleCallHierarchy({file:t,line:r,character:i,direction:o}))}async handleCodeActionCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e);if(!t)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};let o=this.validateContainment([t]);return o||this.routeArktsRequest("codeAction",()=>this.arktsCheckTool.handleCodeAction({file:t,line:r,character:i}))}async handleRenameCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e),o=e.newName;if(!t||typeof o!="string"||o.trim().length===0)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number), newName (non-empty string)."}],isError:!0};let s=this.validateContainment([t]);return s||this.routeArktsRequest("rename",()=>this.arktsCheckTool.handleRename({file:t,line:r,character:i,newName:o}))}async handleTypeHierarchyCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e),o=e.direction;if(!t)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};if(o!=="supertypes"&&o!=="subtypes")return{content:[{type:"text",text:'Parameter direction must be "supertypes" or "subtypes".'}],isError:!0};let s=this.validateContainment([t]);return s||this.routeArktsRequest(`typeHierarchy(${o})`,()=>this.arktsCheckTool.handleTypeHierarchy({file:t,line:r,character:i,direction:o}))}async handleCompletionItemResolveCall(e){let t=e.item;return t==null?{content:[{type:"text",text:"Missing parameter: item (completion item object required)."}],isError:!0}:this.routeArktsRequest("completionItemResolve",()=>this.arktsCheckTool.handleCompletionItemResolve(t))}extractPositionArgs(e){let t=e.file,r=e.line,i=e.character;return typeof t!="string"||typeof r!="number"||typeof i!="number"?{file:null,line:0,character:0}:{file:t,line:r,character:i}}async routeArktsRequest(e,t){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return h.warn(`ArkTS ${e} rejected: project is ${Kc[this.projectState]}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return h.warn(`ArkTS ${e} rejected: LSP is initializing`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return t();default:return h.warn(`ArkTS ${e} rejected: unknown project state ${this.projectState}`),{content:[{type:"text",text:"Unknown project state, please retry"}],isError:!0}}}async handleIdleCheck(){if(this.ensureProjectReady(),this.config.projectPath){let e,t;return this.syncSkippedDueToLock?(e=`Another build process is running, sync deferred (waiting ${this.syncSkipStartedAt>0?Math.round((Date.now()-this.syncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,t="lock contention",this.syncSkippedDueToLock=!1):this.configChangedTriggeredResync?(e="Config file changed, resyncing project, please retry in 10 seconds",t="config changed",this.configChangedTriggeredResync=!1):(e="HarmonyOS project detected, syncing, please retry in 10 seconds",t="initial"),h.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(h.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:"Initializing, please retry in 10 seconds"}],isError:!0}):(h.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"No HarmonyOS project detected. Please verify the project directory or create a project first."}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=Wt?(h.error(`Init retry limit reached (${this.initRetryCount}/${Wt}), will not auto-retry`),{content:[{type:"text",text:"Project initialization failed multiple times. Please check project configuration and restart the MCP Server."}],isError:!0}):(h.info(`Error check: auto-retrying (${this.initRetryCount}/${Wt})`),this.ensureProjectReady(),{content:[{type:"text",text:"Project initialization failed, auto-retrying, please retry in 10 seconds"}],isError:!0})}async routeCppRequest(e,t){switch(this.cppProjectState){case 0:return this.handleCppIdleCheck();case 1:case 2:return h.warn(`C++ ${e} rejected: C++ project is ${Yf[this.cppProjectState]}`),{content:[{type:"text",text:"C++ project is syncing (compileNative), please retry in 25 seconds"}],isError:!0};case 3:return h.warn(`C++ ${e} rejected: clangd is initializing`),{content:[{type:"text",text:"C++ LSP (clangd) is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleCppErrorCheck();case 4:return this.cppHasNoCppCode?{content:[{type:"text",text:"No C++ code in this project"}],isError:!0}:this.cppLspManager?.ready?t():{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0};default:return h.warn(`C++ ${e} rejected: unknown C++ project state ${this.cppProjectState}`),{content:[{type:"text",text:"Unknown C++ project state, please retry"}],isError:!0}}}async routeLspRequest(e,t,r){return e.endsWith(".ets")?this.routeArktsRequest(t,r):sn(e)?this.routeCppRequest(t,r):{content:[{type:"text",text:`Unsupported file type: ${e} (only .ets and C/C++ source/header files are supported)`}],isError:!0}}async handleCppIdleCheck(){if(this.ensureCppProjectReady(),this.config.projectPath){let e;return this.cppSyncSkippedDueToLock?(e=`Another build process is running, C++ sync deferred (waiting ${this.cppSyncSkipStartedAt>0?Math.round((Date.now()-this.cppSyncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,this.cppSyncSkippedDueToLock=!1):e="C++ project detected, syncing (compileNative), please retry in 25 seconds",h.info(`C++ idle check: project '${this.config.projectPath}', triggering C++ init`),{content:[{type:"text",text:e}],isError:!0}}return{content:[{type:"text",text:"No HarmonyOS project detected for C++ tools."}],isError:!0}}async handleCppErrorCheck(){return this.cppInitRetryCount>=Wt?(h.error(`C++ init retry limit reached (${this.cppInitRetryCount}/${Wt}), will not auto-retry`),{content:[{type:"text",text:"C++ project initialization failed multiple times. Please check project configuration and restart the MCP Server."}],isError:!0}):(h.info(`C++ error check: auto-retrying (${this.cppInitRetryCount}/${Wt})`),this.ensureCppProjectReady(),{content:[{type:"text",text:"C++ project initialization failed, auto-retrying, please retry in 25 seconds"}],isError:!0})}async callCppCheck(e){return this.routeCppRequest("check",async()=>this.cppCheckTool.handleCall({files:e}))}mergeCheckResult(e,t,r){let i=e.content.map(o=>o.text).filter(o=>o&&o.trim().length>0).join(`
1284
+ `);i&&(e.isError?t.push(i):r.push(i))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{h.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(t=>{h.warn("Failed to dispose ClangdLspManager during setProjectPath:",t)}),this.cppLspManager=null),this.initPromise?(this.needsReinit=!0,h.info("Project path changed while ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{h.warn("Failed to re-init project after setProjectPath:",t)})),this.cppInitPromise?(this.cppNeedsReinit=!0,h.info("Project path changed while C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.cppHasNoCppCode=!1,this.cppInitRetryCount=0,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.ensureCppProjectReady().catch(t=>{h.warn("Failed to re-init C++ project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new pP;if(await this.server.connect(e),h.info("devecocli-mcp-server started"),!this.config.debug){let t=Vd();t&&h.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=ut(t);r?(h.info(`Detected project path from client root: ${r}`),this.config.projectPath=r):h.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?h.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):h.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{h.warn("Background project init failed:",t)})}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return h.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return h.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){h.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,h.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{h.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{h.error("shutdown failed:",r),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{h.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?ut(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=ut(this.originalProjectPath),t&&h.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(this.discoverProject()&&await this.ensureProjectSynced()){this.ensureCppProjectReady().catch(e=>{h.warn("Background C++ project init failed:",e)}),this.projectState=3,this.arktsCheckTool=new rr(this.config.projectPath,this.sdkPath,this.arktsLangServerPath,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{h.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,h.info("Project fully initialized, check tool is available")}catch(e){h.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=qf(e),r=!t.required;return h.info(`Sync check: skipHvigor=${r}, reason=${t.reason}`),this.runSync(e,{skipHvigorSync:r})}async runSync(e,t){this.projectState=2,h.info("Starting project sync...");let r=await nr.handleSyncProject(e,this.sdkPath,t);switch(r.status){case"success":return this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,!0;case"skipped":{this.syncSkippedDueToLock=!0,this.syncSkipStartedAt===0&&(this.syncSkipStartedAt=Date.now());let i=Date.now()-this.syncSkipStartedAt,o=Math.round(i/1e3);return i>=Jc?(h.error(`Sync skipped for ${o}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(h.warn(`Sync skipped: ${r.reason}, resetting to IDLE for retry (elapsed ${o}s / ${Jc/1e3}s)`),this.projectState=0,!1)}case"failed":return h.error(`Project sync failed: ${r.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:return h.error(`Project sync: unknown status ${r.status}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}async ensureCppProjectReady(){if(!this.cppInitPromise){this.cppInitPromise=this.doEnsureCppProjectReady();try{await this.cppInitPromise}finally{this.cppInitPromise=null}this.cppNeedsReinit&&(this.cppNeedsReinit=!1,this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>{h.warn("Failed to re-init C++ project after cppNeedsReinit:",e)}))}}async doEnsureCppProjectReady(){let e=this.config.projectPath;if(!e){h.info("[Cpp] No project path, skipping C++ init");return}this.cppProjectState=1;let t=ln(e);if(t.length===0){h.info('[Cpp] No C++ modules found, C++ tools will return "no C++ code"'),this.cppHasNoCppCode=!0,this.cppProjectState=4,this.cppInitRetryCount=0;return}if(this.cppHasNoCppCode=!1,h.info(`[Cpp] Found ${t.length} C++ module(s): ${t.map(r=>r.name).join(", ")}`),!!await this.runSyncCpp(e)){this.cppProjectState=3,this.cppLspManager=new di({workspaceRoot:e,sdkPath:this.sdkPath});try{await this.cppLspManager.start(),this.cppCheckTool=new or(this.cppLspManager),this.cppLspTool=new sr(this.cppLspManager),this.cppProjectState=4,this.cppInitRetryCount=0,h.info("[Cpp] C++ project fully initialized, C++ tools are available")}catch(r){h.error("[Cpp] C++ LSP initialization failed:",r),this.cppLspManager&&this.cppLspManager.dispose().catch(()=>{}),this.cppLspManager=null,this.cppCheckTool=null,this.cppLspTool=null,this.cppInitRetryCount++,this.cppProjectState=5}}}async runSyncCpp(e){this.cppProjectState=2,h.info("[Cpp] Starting C++ project sync (compileNative)...");let t=await di.handleSyncCppProject(e,this.sdkPath);switch(t.status){case"success":return this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,!0;case"skipped":{this.cppSyncSkippedDueToLock=!0,this.cppSyncSkipStartedAt===0&&(this.cppSyncSkipStartedAt=Date.now());let r=Date.now()-this.cppSyncSkipStartedAt,i=Math.round(r/1e3);return r>=Jc?(h.error(`[Cpp] C++ sync skipped for ${i}s due to lock contention, giving up`),this.cppInitRetryCount++,this.cppSyncSkipStartedAt=0,this.cppProjectState=5,!1):(h.warn(`[Cpp] C++ sync skipped: ${t.reason}, resetting to IDLE_CPP for retry (elapsed ${i}s)`),this.cppProjectState=0,!1)}case"failed":return h.error(`[Cpp] C++ project sync failed: ${t.reason}`),this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitRetryCount++,this.cppProjectState=5,!1}return!1}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppLspManager&&await this.cppLspManager.dispose(),this.cppCheckTool=null,this.cppLspTool=null;try{await this.server.close()}catch(e){h.warn("Failed to close MCP server connection:",e)}h.info("devecocli-mcp-server stopped"),Gd(),Wd()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function fP(n){let e=[],t=[],r=[];for(let i of n)Ns.extname(i).toLowerCase()===".ets"?e.push(i):sn(i)?t.push(i):r.push(i);return{etsFiles:e,cppFiles:t,unsupported:r}}function Xc(n={}){return new Ls(n)}import*as Zc from"fs";import*as ui from"path";import{spawn as mP}from"child_process";async function Jf(n){cn(!1);let{serverPath:e,logPath:t,projectPath:r,sdkPath:i,serverMaxSize:o}=await hP(n),s=wP(e,t,r,i,o);h.info("ace-server started, bridging stdio (initialize is left to the client)"),SP(s)}async function hP(n){let e=await I.new(),t=e.sourceType==="clt"?e.toolchainRoot:e.devecoStudioPath,r;if(n.projectPath)r=re(ui.resolve(n.projectPath)),h.info(`projectPath=specified ('${r}'), no search`);else if(n.autoDetect){let l=ro(process.cwd());r=re(l??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${l??"null, fallback to cwd"}`)}else r=re(process.cwd()),h.info(`projectPath=cwd ('${r}'), no search (pass --auto-detect to search subdirs)`);let{sdkPath:i,arktsLangServerPath:o}=io(t);o||(h.error("ace-server not found (install DevEco Studio / CLT)."),process.exit(1));let s=Ir(o,!0),a=ui.join(Tt(),"lsp-server",String(Date.now()));Zc.mkdirSync(a,{recursive:!0});let c=gP(r,i);return h.info(`projectPath=${r}, sdkPath=${i}, arktsLangServerPath=${o}, serverPath=${s}, logPath=${a}, serverMaxSize=${c}MB`),{projectPath:r,sdkPath:i,serverPath:s,logPath:a,serverMaxSize:c}}function gP(n,e){let t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=t?parseInt(t,10):NaN,i=Number.isFinite(r)&&r>0?r:void 0,o=yP(n,e),s=mo(o,i);return h.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${o}, override=${i??"none"})`),s}function yP(n,e){try{let t=[];return new gn(n,e).getAllDependencyMap(t).status==="OK"?t.length:new pt(n).getAllModuleInfo().length}catch{return 0}}function wP(n,e,t,r,i){let o=ui.join(e,"lspLog");Zc.mkdirSync(o,{recursive:!0});let s=vP(n,o,t,r,i),a=process.execPath??"node";return h.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),mP(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function vP(n,e,t,r,i){let o=j(e);return["--expose-gc",`--max-old-space-size=${i}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${o}`,n,"--stdio",`--logger-path=${o}`,"--logger-level=TRACE",`--projectPath=${j(t)}`,`--sdkPath=${j(r)}`]}function SP(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{h.error(`[ace-server] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{h.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{h.info(`ace-server exited with code ${e}`),process.exit(e??0)})}import*as Kf from"fs";import*as yn from"path";import{spawn as EP}from"child_process";async function Xf(n){cn(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await bP(n),i=yn.join(t,"compile_commands.json");Kf.existsSync(i)||h.warn(`compile_commands.json not found at ${i}. Cross-file navigation/completion will be limited. Run \`devecocli build\` first to generate it.`);let o=CP(e,t,r);h.info("clangd started, bridging stdio (initialize is left to the client)"),AP(o)}async function bP(n){let e=await PP();e||(h.error("DevEco Studio not found. Ensure DevEco Studio is installed."),process.exit(1));let t;if(n.projectPath)t=re(yn.resolve(n.projectPath)),h.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let a=ro(process.cwd());t=re(a??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${a??"null, fallback to cwd"}`)}else t=re(yn.resolve(process.cwd())),h.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=Oa(e),i=so(r);i||(h.error(`clangd not found under sdk '${r}'. Expected at <sdkPath>/default/openharmony/native/llvm/bin/clangd`),process.exit(1));let o=Ar(t),s=yn.dirname(o);return h.info(`projectPath=${t}, sdkPath=${r}, clangdPath=${i}, compileCommandsDir=${s}`),{projectPath:t,clangdPath:i,compileCommandsDir:s}}function PP(){return I.new().then(n=>n.devecoStudioPath).catch(()=>Ma())}function CP(n,e,t){let r=IP(e);return h.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),EP(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function IP(n){return[`--compile-commands-dir=${j(n)}`,"--log=info","--pch-storage=memory"]}function AP(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{h.error(`[clangd] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{h.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{h.info(`clangd exited with code ${e}`),process.exit(e??0)})}async function RP(){let n=process.env.PROJECT_PATH||"",e=process.env.NODE_MAX_OLD_SPACE_SIZE,t=process.env.DEBUG==="true"||process.env.DEBUG==="1",r=n,i=await I.new(),o=i.sourceType==="clt"?i.toolchainRoot:i.devecoStudioPath??null,s=Xc({projectPath:r,devecoPath:o??void 0,nodeMaxOldSpaceSize:e,debug:t}),a=async()=>{await s.shutdown(),process.exit(0)};process.once("SIGINT",a),process.once("SIGTERM",a),process.platform==="win32"&&process.once("SIGBREAK",a);try{await s.start()}catch(c){console.error("Failed to start MCP server:",c),process.exit(1)}}var Qc=new DP("serve").description("Host bundled auxiliary protocol servers");Qc.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await RP()});Qc.command("lsp").description("Start a bundled LSP language server").option("--arkts","Start the ArkTS language server (ace-server)").option("--cpp","Start the C/C++ language server (clangd)").option("--project-path <path>","project root path (used as-is, no search)").option("--auto-detect","When --project-path is not specified, search the current directory and its subdirectories for the project root (no upward search)").action(async n=>{n.arkts&&n.cpp&&(console.error("--arkts and --cpp are mutually exclusive. Specify only one."),process.exit(1)),n.arkts?await Jf({projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await Xf({projectPath:n.projectPath,autoDetect:n.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var Zf=Qc;import{Command as RI,InvalidArgumentError as xl}from"commander";import{red as Zs,dim as kI}from"colorette";import*as xi from"fs";import gI from"proper-lockfile";import Ih from"ora";import*as Qe from"fs";import*as Si from"path";var Gt=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],wn={"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 Os="1.9.1",KW=48*1024*1024;var pi=200,Qf=12,em=4,el=8,tm=6;var nm=1320,rm=120,im=450,om=250,sm=500,am=480,cm=80,lm=200,dm=60,um=200;var pm=200,fm=40,tl=500,XW=Object.fromEntries(Gt.map((n,e)=>[wn[n],e])),Vt=Object.fromEntries(Gt.map((n,e)=>[n,e]));import*as fi from"fs";import*as $ from"path";import{fileURLToPath as mm}from"url";var kP="docs";function cr(){return $.join(Ye(),kP)}function oe(){return $.join(cr(),".index")}function Ms(){return $.join(oe(),"build.lock")}function mi(){return $.join(oe(),"build-status.json")}function lr(){return $.join(oe(),"build-meta.json")}function vn(){return $.join(oe(),"search.db")}function dr(){return $.join(oe(),".tmp")}function TP(n,e){let t=e;for(;!t.endsWith(`${$.sep}dist`)&&t!==$.dirname(t);)t=$.dirname(t);return t}function hm(n,e){return $.dirname(TP(n,e))}function gm(){let n=mm(import.meta.url),e=$.dirname(n);return n.includes(`${$.sep}dist${$.sep}`)?hm(n,e):$.join(e,"..","..","..")}function xP(...n){let e=mm(import.meta.url),t=$.dirname(e);return e.includes(`${$.sep}dist${$.sep}`)?[$.join(hm(e,t),...n)]:[$.join(t,"..","..","..",...n)]}function ym(...n){let e=gm(),t=fi.realpathSync(e);for(let r of xP(...n))try{let i=fi.lstatSync(r);if(i.isSymbolicLink()||!i.isFile())throw new Error(`Unsafe documentation package asset: ${n.join("/")} must be a regular file.`);let o=fi.realpathSync(r);if(!Da(o,t))throw new Error(`Unsafe documentation package asset: ${n.join("/")} is outside the package.`);return o}catch(i){if(i.code!=="ENOENT")throw i}return null}function Sn(){return ym("docs.zip")}function nl(){return ym("index.zip")}function wm(){return $.join(gm(),"index","data")}import*as En from"fs";import*as hi from"path";var zt=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],_s=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};function Sm(n){return n instanceof _s}var vm=null;function Em(){if(vm)return vm;let n=oe();if(zt.every(i=>En.existsSync(hi.join(n,i))))return n;let t=wm();if(zt.every(i=>En.existsSync(hi.join(t,i))))return t;throw new _s("Lexicon files not found. Install the documentation index first (index.zip).")}function bm(){Em()}function ur(n){let e=hi.join(Em(),n);return En.readFileSync(e,"utf-8")}function Pm(n,e){return En.readFileSync(hi.join(e,n),"utf-8")}import*as Fs from"fs";import*as Cm from"path";import*as Im from"yauzl";var gi=null;function LP(n){return new Promise((e,t)=>{Im.open(n,{lazyEntries:!0,decodeStrings:!1,autoClose:!1},(r,i)=>{if(r||!i){t(r??new Error(`Failed to open zip: ${n}`));return}e(i)})})}function NP(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function OP(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",i=>{let o=NP(i);o.endsWith("/")||e.set(o,i),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function MP(){gi?.zipfile.close(),gi=null}async function _P(n){let e=Cm.resolve(n),t=await Fs.promises.stat(e),r=gi;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;MP();let i=await LP(e),o=await OP(i);return gi={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:i,entries:o,readChain:Promise.resolve()},gi}function FP(n,e){return new Promise((t,r)=>{n.openReadStream(e,(i,o)=>{if(i||!o){r(i??new Error(`Failed to read zip entry: ${e.fileName}`));return}let s=[];o.on("data",a=>{s.push(Buffer.isBuffer(a)?a:Buffer.from(a))}),o.on("end",()=>{t(Buffer.concat(s))}),o.on("error",r)})})}async function jP(n,e){let t=n.readChain,r;n.readChain=new Promise(i=>{r=i}),await t;try{return await FP(n.zipfile,e)}finally{r()}}function $P(n){let e=n.replace(/\\/g,"/").replace(/\.md$/,"");if(e.split("/").includes(".."))throw new Error("Invalid document ID: path traversal is not allowed.");return[`docs/${e}.md`,`${e}.md`,`docs/${e}`,e]}function HP(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function Am(n){let e=Sn();if(!e)throw new Error("docs.zip not found");let t=await _P(e),r=HP(t.entries,$P(n));if(!r)throw new Error(`Document not found: ${n}`);return(await jP(t,r)).toString("utf-8")}function rl(){let n=Sn();return n!==null&&Fs.existsSync(n)}import*as se from"fs";import*as Et from"path";import Dm from"adm-zip";import*as yi from"fs";import*as $s from"path";var js=class extends Error{constructor(e){super(`Unsafe documentation path: ${e}`),this.name="DocPathSafetyError"}};function wi(n){return n instanceof un||n instanceof js||n instanceof Error&&(n.name==="CliDataDirError"||n.name==="DocPathSafetyError")}function sl(n){return new js(n)}function UP(){return rt(Ye())}function ol(n,e,t){let r=qi(n,e);if(r===null)throw sl(`${t} resolves outside the data directory.`);return r}async function il(n,e){await yi.promises.mkdir(n,{recursive:!0});let t=ol(n,e,"directory");if(!(await yi.promises.stat(t)).isDirectory())throw sl("path must be a directory.")}function BP(n){let e=UP();try{let t=ol(n,e,"file");if(!yi.statSync(t).isFile())throw sl("path must be a regular file.")}catch(t){if(t.code==="ENOENT"){ol($s.dirname(n),e,"file parent");return}throw t}}async function vi(n={}){let e=n.mode??"write",t=await Cu();await il(cr(),t),await il(oe(),t),e==="write"&&await il(dr(),t);for(let r of[vn(),lr(),mi(),Ms(),...zt.map(i=>$s.join(oe(),i))])BP(r)}var al=["search.db","build-meta.json",...zt],WP=["corpus.json","corpus-offsets.json","orama.dpack"];async function GP(n){for(let e of WP)await se.promises.rm(Et.join(n,e),{force:!0})}async function VP(n){let e=await se.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await se.promises.rm(Et.join(n,t.name),{recursive:!0,force:!0})}function Rm(n){let t=new Dm(n).getEntry("build-meta.json");if(!t)throw new Error("index.zip is missing build-meta.json");return JSON.parse(t.getData().toString("utf-8"))}async function zP(n){let e=oe();await se.promises.mkdir(e,{recursive:!0});for(let t of al){let r=Et.join(e,t);await se.promises.rm(r,{force:!0}),await se.promises.rename(Et.join(n,t),r)}await GP(e),await se.promises.rm(dr(),{recursive:!0,force:!0})}function km(n){let e=nl();if(!e)return!1;try{let t=Rm(e);return t.indexVersion===Os&&t.docsZipSha256===n&&t.segmentCount>0}catch{return!1}}async function Tm(n){await vi({mode:"write"});let e=nl();if(!e)throw new Error("index.zip not found");let t=Rm(e);if(t.docsZipSha256!==n)throw new Error("Bundled index.zip does not match docs.zip. Rebuild index.zip with npm run build:index.");if(t.segmentCount<=0)throw new Error("Bundled index.zip is empty");let r=dr();await se.promises.rm(r,{recursive:!0,force:!0}),await se.promises.mkdir(r,{recursive:!0});let i=new Dm(e);for(let s of al){let a=i.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await se.promises.writeFile(Et.join(r,s),a.getData())}let o=JSON.parse(await se.promises.readFile(Et.join(r,"build-meta.json"),"utf-8"));if(!se.existsSync(Et.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await zP(r),await se.promises.mkdir(cr(),{recursive:!0}),await VP(cr()),o}async function xm(){await se.promises.rm(dr(),{recursive:!0,force:!0});let n=oe();for(let e of al)await se.promises.rm(Et.join(n,e),{force:!0})}import{createHash as Lm}from"crypto";import*as Nm from"fs";async function Hs(n){return new Promise((e,t)=>{let r=Lm("sha256"),i=Nm.createReadStream(n);i.on("data",o=>r.update(o)),i.on("error",t),i.on("end",()=>e(r.digest("hex")))})}function Om(n){return Lm("sha256").update(n,"utf8").digest("hex")}var cl=null;function qP(){let n=ur("harmonyos-synonyms.json");return JSON.parse(n)}function YP(n){let e=new Map;for(let t of n){let r=t.map(i=>i.trim()).filter(Boolean);for(let i of r){let o=r.filter(s=>s!==i);e.set(i.toLowerCase(),o),i!==i.toLowerCase()&&e.set(i,o)}}return e}function JP(){let n=YP(qP()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function KP(){return cl||(cl=JP()),cl}function ll(n,e){let t=KP(),r=n.split(/\s+/).filter(Boolean),i=new Set,o=Number.isFinite(e)?e:r.length;for(let s=0;s<r.length&&i.size<o;s+=1){let a=r[s];i.add(a);let c=t.get(a)??t.get(a.toLowerCase());if(c)for(let l of c){if(i.size>=o)break;i.add(l)}}return[...i].join(" ")}function Mm(n,e){let t=e?Pm(n,e):ur(n);return Om(t)}function _m(n){return Mm("harmonyos-synonyms.json",n)}function Fm(n){return Mm("harmonyos-terms.txt",n)}var XP={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function Us(){try{let n=await Qe.promises.readFile(mi(),"utf-8");return JSON.parse(n)}catch{return{...XP}}}async function dl(n){let e=mi();await Qe.promises.mkdir(Si.dirname(e),{recursive:!0}),await Qe.promises.writeFile(e,JSON.stringify(n,null,2))}function jm(n){let e=Date.now();return{state:"extracting",phase:1,phaseLabel:"Extracting documentation",current:0,total:0,message:n,startedAt:e,updatedAt:e,error:null}}async function Ei(n){let t={...await Us(),...n,updatedAt:Date.now()};return await dl(t),t}async function ul(){let n=Sn();return n?Hs(n):null}async function pl(){try{let n=await Qe.promises.readFile(lr(),"utf-8");return JSON.parse(n)}catch{return null}}async function Bs(n=!1){if(n)return"no-index";let e=await pl();if(!e||e.segmentCount===0)return"no-index";let t=await ul();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==Os?"engine-upgraded":e.termsHash!==Fm()?"terms-changed":e.synonymsHash!==_m()?"synonyms-changed":null}function bi(){if(!rl()||!Qe.existsSync(vn())||!Qe.existsSync(lr()))return!1;let n=Si.dirname(vn());if(!zt.every(e=>Qe.existsSync(Si.join(n,e))))return!1;try{let e=Qe.readFileSync(lr(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function fl(n=!1){return n?!0:rl()?bi()?await Bs()!==null:!0:!1}async function $m(){let n=await Us();return["installing","indexing","persisting"].includes(n.state)}var Hm=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),ml=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),Um=new Set(["a","an","and","api","app","application","arkts","arkui","for","get","harmonyos","how","in","oh","ohos","on","or","set","the","to","use","using","what","when","where","which","with","without","data","file","main","model","name","network","stage","system","type","user"]),Bm=new Set(["ability","extension","module","service","context","options","config","info","event","code","state","type","data","request","response","client","server","handler","helper","utils","factory","builder","listener","callback","observer","provider","consumer","delegate","adapter","driver","buffer","stream","channel","session","task","worker","controller","component","container","attribute","descriptor","modifier","validator","parser","formatter","encoder","decoder","filter","converter","generator","iterator","dispatcher","resolver","scanner","tracker","monitor","scheduler","renderer","loader","subscriber","proxy","button","surface","stack","heap","map","set","array","list"]);var ZP=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,QP=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,eC=/[A-Z][a-zA-Z0-9]{2,}/g,tC=/@[A-Z][a-zA-Z0-9]*/g,nC=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,Wm=6,rC=/^[a-z][a-z0-9]{2,}$/,iC=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,oC=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,sC=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,aC=/^[A-Z][a-zA-Z0-9]+$/;function cC(n){return`"${n.replace(/"/g,'""')}"`}function Ci(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(cC).join(` ${e} `)}function Pi(n){return Ci(n,"OR")}function Gm(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?Pi([...t,...r]):`(${Pi(t)}) AND (${Pi(r)})`}function Ii(n){return oC.test(n)}function Vm(n){return sC.test(n)&&n.length>=Wm}function lC(n){return aC.test(n)}function Ai(n){return Ii(n)||Vm(n)||lC(n)}function dC(n){let e=n.trim().toLowerCase();return Bm.has(e)?!1:Hm.has(e)}function uC(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function zm(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function pC(n){return[...n.matchAll(ZP)].map(e=>e[0])}function fC(n,e=Wm){let t=[];for(let r of n.matchAll(QP))r[0].length>=e&&t.push(r[0]);return t}function Ws(n){return n.filter(e=>{let t=e.toLowerCase();return!n.some(r=>{if(r===e)return!1;let i=r.toLowerCase();return i.length>t.length&&i.endsWith(t)&&t.length>=4})})}function bn(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function mC(n){let e=new Set;bn(e,n);let t=zm(n);return t&&bn(e,t),Ws([...e])}function Gs(n){if(Ii(n))return mC(n);let e=new Set;return bn(e,n),Ws([...e])}function Vs(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(iC);if(!t)return null;let r=t[1].toLowerCase(),i=t[2].toLowerCase();if(!rC.test(r)||Um.has(r)||!dC(i))return null;let o=uC(r,i);return{first:r,second:i,camelCase:o,lower:o.toLowerCase()}}function hl(n){let e=Vs(n.trim());return!e||e.second!=="manager"?null:e}function hC(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function qm(n){let e=n.trim(),t=hl(e);if(t&&ml.has(t.first))return!0;if(Vm(e)){let r=hC(e);return r!==null&&ml.has(r)}return!1}function gl(n,e,t){let r=t.toLowerCase(),i=new RegExp(`@ohos\\.[^\\s(]*${t}`,"i");for(let o of[n,e])if(o&&(o.toLowerCase().includes(r)||i.test(o)))return!0;return!1}function yl(n){let e=n.trim();if(Ai(e))return Gs(e);let t=new Set;for(let r of pC(n)){bn(t,r);let i=zm(r);i&&bn(t,i)}for(let r of fC(n))bn(t,r);for(let r of n.matchAll(tC))t.add(r[0]);for(let r of n.matchAll(nC))t.add(r[0]);for(let r of n.matchAll(eC))r[0].length>=4&&t.add(r[0]);return Ws([...t])}function Ym(n){let e=n.trim();if(Ai(e))return Gs(e);let t=new Set,r=Vs(e);r&&bn(t,r.camelCase);for(let i of yl(e))t.add(i);for(let i of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let o=i[0];o!==o.toLowerCase()&&t.add(o)}return Ws([...t])}function Jm(n){return Ai(n)}var G={pureApiSymbol:/^[A-Z][a-zA-Z0-9]+$/,stageModelExact:/^Stage\s*模型$/i,stageModelEnglishExact:/^stage\s+model$/i,stageModel:/Stage\s*模型/i,stageModelEntryPage:/Stage\s*模型.*EntryAbility.*(页面|新页面)/,declarePermissionBoost:/声明.*权限|应用权限.*声明|如何声明应用权限/,declarePermissionCatalog:/如何声明应用权限/,declarePermissionTokens:/如何声明应用权限|声明应用权限/,uiAbilityLifecycleBoost:/UIAbility.*生命周期|生命周期.*UIAbility|UIAblity/i,uiAbilityLifecycleCatalog:/UIAblity.*生命周期|UIAbility.*生命周期/i,entryAbilityPage:/EntryAbility.*(页面|启动|跳转|新页面)/,stateDecoratorBoost:/@State|@Prop|@Link|@Provide|@Consume/,stateDecoratorCatalog:/@State\s*装饰器|@Prop\s*装饰器|@Link\s*装饰器/,stateManagement:/状态管理原理/,routerRoute:/Router\s+路由/,dialogPopupExact:/^Dialog\s+弹窗$/,dialogPopupBoost:/Dialog\s+弹窗/};function Km(n){return G.pureApiSymbol.test(n.trim())}function Di(n){let e=n.trim();return G.stageModelExact.test(e)||G.stageModelEnglishExact.test(e)}function Xm(n){let e=[];return Di(n.trim())&&e.push("Stage\u6A21\u578B","Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0"),G.declarePermissionTokens.test(n)&&e.push("\u58F0\u660E\u6743\u9650"),G.stageModelEntryPage.test(n)&&e.push("\u9875\u9762\u8DEF\u7531","pushUrl"),/UIAblity|UIAbility/.test(n)&&/生命周期/.test(n)&&e.push("UIAbility\u7EC4\u4EF6\u751F\u547D\u5468\u671F"),e}function Zm(n){return Di(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var gC=[{matches:n=>G.uiAbilityLifecycleBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:n=>Di(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!Di(n)&&G.stageModel.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:n=>G.entryAbilityPage.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:n=>G.declarePermissionBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:n=>G.stateDecoratorBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:n=>G.stateManagement.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:n=>G.routerRoute.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:1.4},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]},{matches:n=>G.dialogPopupBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function yC(n,e){for(let{catalog:t,multiplier:r}of e){let i=Vt[t];n.set(i,(n.get(i)??1)*r)}}function Qm(n,e){for(let t of gC)t.matches(n)&&yC(e,t.weights)}function eh(n,e){if(e!==void 0)return!1;let t=n.trim();return Ii(t)||G.pureApiSymbol.test(t)||qm(t)}function th(n){let e=n.trim();if(Ii(e)||G.pureApiSymbol.test(e))return"harmonyos-references";if(Di(e)||G.uiAbilityLifecycleCatalog.test(e)||G.stateDecoratorCatalog.test(e)||G.stateManagement.test(e)||G.declarePermissionCatalog.test(e)||G.stageModelEntryPage.test(e)||G.routerRoute.test(e)||G.dialogPopupExact.test(e))return"harmonyos-guides"}import{createRequire as wC}from"module";var vC=wC(import.meta.url),zs=null,wl=null,vl=null;function SC(){if(zs)return zs;let n=ur("harmonyos-stopwords.txt");return zs=new Set(n.split(`
1285
+ `).map(e=>e.trim()).filter(Boolean)),zs}function EC(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t]?.trim();if(!r)continue;let i=n[t+1]?.trim();if(r==="@"&&i&&/^[A-Z][a-zA-Z0-9]*$/.test(i)){e.push(`@${i}`),t+=1;continue}e.push(r)}return e}function nh(n){let e=SC(),t=[];for(let r of EC(n)){let i=r.trim();!i||e.has(i)||(t.push(i.toLowerCase()),/[A-Z]/.test(i)&&/[a-zA-Z]/.test(i)&&t.push(i))}return t}async function bC(){let{cut:n,cut_for_search:e,with_dict:t}=vC("jieba-wasm"),r=ur("harmonyos-terms.txt");return t(r),m("doc-index: using jieba-wasm backend"),{cut:(i,o)=>n(i,o),cutForSearch:(i,o)=>e(i,o)}}async function pr(){return wl||(vl||(vl=bC().then(n=>(wl=n,n))),vl)}async function PC(n){let e=await pr();return nh(e.cutForSearch(n,!0))}async function rh(n){let e=await pr();return nh(e.cut(n,!0))}async function qs(n,e){let t=n.trim();if(!t||e<=0)return"";let r=(await PC(t)).join(" ");return r.length<=e?r:r.slice(0,e)}async function CC(n,e){let t=[];for(let i of n){let o=i.trim();o&&(t.push(o.toLowerCase()),/[A-Z]/.test(o)&&t.push(o))}let r=[...new Set(t)].join(" ");return r.length<=e?r:r.slice(0,e)}async function ih(n){let e=!!n.sectionTitle.trim(),t=n.titleTokens.trim(),r=e?am:nm,i=e?lm:im,o=e?await CC(n.apiSymbols,i):await qs(n.apiSymbols.join(" "),i),a=(await Promise.all([qs(t,e?cm:rm),Promise.resolve(o),qs(n.headingsText,e?dm:om),qs(n.bodySample,e?um:sm)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}function IC(n){return n.join(" ").replace(/\s+/g," ").trim().slice(0,pi)}function Sl(n,e){let t=new Set,r=[];for(let i of[...n,...e]){let o=i.toLowerCase();if(!(!i||t.has(o))&&(t.add(o),r.push(i),r.length>=Qf))break}return r}function AC(n){return n.length>=2&&n.length<=em}function DC(n,e){let t=ll(n,el),r=t.split(/\s+/).filter(Boolean),i=[e.first,...r.filter(a=>a!==e.second),e.lower,e.camelCase],o=[e.second,e.lower,e.camelCase],s=Sl(i,o);return{rawQuery:n,expandedQuery:t,tokens:s,preferAnd:!1,ftsMatch:Gm(i,o)}}function RC(n,e){let t=Sl(Gs(e),[]);return{rawQuery:n,expandedQuery:n,tokens:t,preferAnd:!1,ftsMatch:Pi(t)}}async function oh(n){let e=IC(n),t=e.trim(),r=Zm(t);if(r)return{rawQuery:e,expandedQuery:r.expandedQuery,tokens:r.tokens,preferAnd:!1};let i=Vs(t);if(i)return DC(e,i);if(Ai(t))return RC(e,t);let o=Xm(e),s=[...yl(e),...o],c=Jm(t)?e:ll(e,el),l=await rh(c),p=Sl(s,l);return{rawQuery:e,expandedQuery:c,tokens:p,preferAnd:o.length===0&&AC(p)}}var sh=["harmonyos-releases","harmonyos-roadmap"],kC=new Set(sh.map(n=>Vt[n])),TC=sh.map(n=>`${wn[n]}/`);function xC(n){return kC.has(n)}function LC(n){return TC.some(e=>n.startsWith(e))}function ah(n){let e=[],t=[];for(let r of n)xC(r.catalog_id)?t.push(r):e.push(r);return[...e,...t]}function ch(n){let e=[],t=[];for(let r of n)LC(r.documentId)?t.push(r):e.push(r);return[...e,...t]}var NC=[{pattern:/@ohos\./i,catalog:"harmonyos-references",multiplier:1.5},{pattern:/@[A-Z][a-zA-Z]+/,catalog:"harmonyos-guides",multiplier:1.35},{pattern:/(如何|怎么|怎样|步骤)/,catalog:"harmonyos-guides",multiplier:1.45},{pattern:/(生命周期|原理|概述|什么是|模型|介绍)/,catalog:"harmonyos-guides",multiplier:1.35},{pattern:/(报错|失败|错误|异常|排查)/,catalog:"harmonyos-guides",multiplier:1.25},{pattern:/(报错|失败|FAQ)/i,catalog:"harmonyos-faqs",multiplier:1.2},{pattern:/(构建|签名|打包|发布|上架|应用市场|hvigor|ohpm)/i,catalog:"harmonyos-guides",multiplier:1.3},{pattern:/(行为变更|changelog|升级|适配|版本说明)/i,catalog:"harmonyos-releases",multiplier:1.3},{pattern:/(路由|弹窗|手势|页面|权限|装饰器)/,catalog:"harmonyos-guides",multiplier:1.25,skipForPureApiSymbol:!0}];function Ri(n,e,t){let r=Vt[e];n.set(r,(n.get(r)??1)*t)}function OC(n,e){let t=n.trim(),r=/[\u4e00-\u9fff]/.test(t),i=/\b[A-Z][a-zA-Z0-9]{2,}\b/.test(t),o=/\b[a-z][a-zA-Z0-9]{3,}\b/.test(t);if(r&&(i||o)){Ri(e,"harmonyos-guides",1.45),Ri(e,"harmonyos-references",1.35);return}(i||o)&&Ri(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(t)&&Ri(e,"harmonyos-references",1.75)}function lh(n){let e=new Map,t=n.trim();if(!t)return e;let r=Km(t);OC(t,e),Qm(t,e);for(let i of NC)i.pattern.test(t)&&(i.skipForPureApiSymbol&&r||Ri(e,i.catalog,i.multiplier));return e}function dh(n){return th(n)}import{readFile as tI,stat as nI,writeFile as rI}from"fs/promises";var MC=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function _C(n,e){let t=-1;for(let r of MC){let i=n.lastIndexOf(r);i>t&&(t=i)}return t>=e?t:-1}function uh(n,e,t={}){let{maxLen:r=pm,contextChars:i=fm,excerptTruncated:o=!1}=t,s=n.replace(/\s+/g," ").trim();if(!s)return"";if(s.length<=r)return o?`${s}...`:s;let a=e.split(/\s+/).map(It=>It.trim()).filter(Boolean),c=0;for(let It of a){let At=s.toLowerCase().indexOf(It.toLowerCase());if(At>=0){c=At;break}}let l=Math.max(0,c-i),p=Math.min(s.length,l+r),g=s.slice(l,p),w=_C(g,r-25);w>=0&&(p=l+w);let C=s.slice(l,p).trim(),_=l>0?"...":"",fe=p<s.length||o?"...":"";return`${_}${C}${fe}`}var FC=`
1286
+ SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
1287
+ d.catalog_id, bm25(segments_fts) AS bm25
1288
+ FROM segments_fts
1289
+ JOIN segments s ON s.id = segments_fts.rowid
1290
+ JOIN documents d ON d.id = s.doc_id
1291
+ WHERE segments_fts MATCH ?
1292
+ ORDER BY bm25(segments_fts)
1293
+ LIMIT ?
1294
+ `,jC=`
1295
+ SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
1296
+ d.catalog_id, bm25(segments_fts) AS bm25
1297
+ FROM segments_fts
1298
+ JOIN segments s ON s.id = segments_fts.rowid
1299
+ JOIN documents d ON d.id = s.doc_id
1300
+ WHERE segments_fts MATCH ? AND d.catalog_id = ?
1301
+ ORDER BY bm25(segments_fts)
1302
+ LIMIT ?
1303
+ `,$C=3.5,HC=1.4,UC=4,BC=1.8,WC=1.35,GC=3.5,VC=1.8,zC=120,ph=6;function bl(n){return n.toLowerCase().replace(/[^\p{L}\p{N}@.]+/gu,"")}function qC(n){return n.split(/[^\p{L}\p{N}@.]+/u).map(bl).filter(e=>e.length>=2)}function YC(n,e){return e.length>1&&e.every(t=>n.includes(t))}function JC(n){return/^[a-z0-9]{1,4}$/.test(n.trim().toLowerCase())}function KC(n,e){return n===e?GC:n.startsWith(e)||n.includes(`@ohos.${e}`)?VC:1}function XC(n,e){let t=bl(e);if(t.length<2)return 1;let r=bl(n.doc_title);if(JC(e))return KC(r,t);if(r.includes(t))return UC;if(t.length>=ph&&r.includes(t.slice(0,ph)))return BC;let i=qC(e);return YC(r,i)?WC:1}function ZC(n,e){return e<=1?n:n<0?n*e:n/e}function Ys(n,e,t,r){let i=n.bm25/(e.get(n.catalog_id)??1);return i=ZC(i,XC(n,t)),r&&gl(n.doc_title,n.section_title,r)&&(i/=$C,n.catalog_id===Vt["harmonyos-references"]&&(i/=HC)),i}function El(n,e,t,r){return n.reduce((i,o)=>Ys(o,e,t,r)<Ys(i,e,t,r)?o:i)}function QC(n,e){return e.some(t=>n.section_title.includes(t)||n.doc_title.includes(t))}function eI(n,e,t,r,i){if(i){let o=n.filter(s=>gl(s.doc_title,s.section_title,i));if(o.length>0)return El(o,t,r,i)}if(e.length>0){let o=n.filter(s=>QC(s,e));if(o.length>0)return El(o,t,r,i)}return El(n,t,r,i)}function fh(n,e,t,r,i){let o=lh(e),s=Ym(e),c=hl(e)?.camelCase,l=new Map;for(let C of n){let _=l.get(C.document_id)??[];_.push(C),l.set(C.document_id,_)}let p=[];for(let C of l.values())p.push(eI(C,s,o,t,c));let g=p.sort((C,_)=>Ys(C,o,t,c)-Ys(_,o,t,c));return(i?ah(g):g).slice(0,r)}function mh(n,e,t,r,i,o){let s=e?Vt[e]:void 0,a=Math.max(t,t*tm,zC),c=s===void 0?n.all(FC,r,a):n.all(jC,r,s,a);return(s===void 0?fh(c,o,i,t,!0):fh(c,o,i,t,!1)).map(p=>({title:p.doc_title,documentId:p.document_id,sectionTitle:p.section_title||void 0,snippet:uh(p.lead_text,i,{excerptTruncated:!!p.excerpt_truncated})}))}var hh=`
1304
+ CREATE TABLE documents (
1305
+ id INTEGER PRIMARY KEY,
1306
+ document_id TEXT NOT NULL UNIQUE,
1307
+ catalog_id INTEGER NOT NULL,
1308
+ doc_title TEXT NOT NULL
1309
+ );
1310
+
1311
+ CREATE TABLE segments (
1312
+ id INTEGER PRIMARY KEY,
1313
+ doc_id INTEGER NOT NULL REFERENCES documents(id),
1314
+ section_title TEXT NOT NULL DEFAULT '',
1315
+ lead_text TEXT NOT NULL DEFAULT '',
1316
+ search_text TEXT NOT NULL,
1317
+ excerpt_truncated INTEGER NOT NULL DEFAULT 0
1318
+ );
1319
+
1320
+ CREATE VIRTUAL TABLE segments_fts USING fts5(
1321
+ search_text,
1322
+ content='segments',
1323
+ content_rowid='id',
1324
+ tokenize='unicode61'
1325
+ );
1326
+
1327
+ CREATE TRIGGER segments_ai AFTER INSERT ON segments BEGIN
1328
+ INSERT INTO segments_fts(rowid, search_text) VALUES (new.id, new.search_text);
1329
+ END;
1330
+
1331
+ CREATE TRIGGER segments_ad AFTER DELETE ON segments BEGIN
1332
+ INSERT INTO segments_fts(segments_fts, rowid, search_text) VALUES('delete', old.id, old.search_text);
1333
+ END;
1334
+
1335
+ CREATE TRIGGER segments_au AFTER UPDATE ON segments BEGIN
1336
+ INSERT INTO segments_fts(segments_fts, rowid, search_text) VALUES('delete', old.id, old.search_text);
1337
+ INSERT INTO segments_fts(rowid, search_text) VALUES (new.id, new.search_text);
1338
+ END;
1339
+
1340
+ CREATE INDEX segments_doc_id_idx ON segments(doc_id);
1341
+ `;var Pl=null,qt=null;async function Cl(){return Pl||(Pl=(async()=>{let n=(await import("@sqlite.org/sqlite-wasm")).default;return n()})()),Pl}function iI(n){return{all(e,...t){let r=n.prepare(e);t.length>0&&r.bind(t);let i=[];for(;r.step();)i.push(r.get({}));return r.finalize(),i}}}async function oI(n){let e=await nI(n);if(qt&&qt.dbPath===n&&qt.mtimeMs===e.mtimeMs)return qt.db;qt?.db.close();let t=await Cl(),r=t.capi,i=t.wasm,o=new Uint8Array(await tI(n)),s=i.allocFromTypedArray(o),a=new t.oo1.DB(":memory:"),c=r.SQLITE_DESERIALIZE_READONLY|r.SQLITE_DESERIALIZE_RESIZEABLE|r.SQLITE_DESERIALIZE_FREEONCLOSE;return r.sqlite3_deserialize(a.pointer,"main",s,o.byteLength,o.byteLength,c),qt={dbPath:n,mtimeMs:e.mtimeMs,db:a},a}function gh(){qt?.db.close(),qt=null}async function sI(n,e,t,r){n.exec("BEGIN");for(let i of r){let o=t(i.source);e.bind([o,i.source.sectionTitle,i.source.leadText,i.searchText,i.source.excerptTruncated?1:0]),e.step(),e.reset()}n.exec("COMMIT")}function aI(n,e,t){return r=>{let i=e.get(r.documentId);if(i!==void 0)return i;let o=n.selectValue("SELECT id FROM documents WHERE document_id = ?",[r.documentId]);if(o!=null){let a=Number(o);return e.set(r.documentId,a),a}t.bind([r.documentId,r.catalogId,r.docTitle]),t.step(),t.reset();let s=Number(n.selectValue("SELECT last_insert_rowid()"));return e.set(r.documentId,s),s}}async function cI(n,e,t){await pr();let r=await Cl(),i=new r.oo1.DB(":memory:","c");i.exec(hh);let o=new Map,s=i.prepare("INSERT INTO documents(document_id, catalog_id, doc_title) VALUES (?, ?, ?)"),a=i.prepare("INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated) VALUES (?, ?, ?, ?, ?)"),c=aI(i,o,s),l=e.length;for(let g=0;g<l;g+=tl){let w=e.slice(g,g+tl),C=await Promise.all(w.map(async _=>({source:_,searchText:await ih(_)})));await sI(i,a,c,C),await t?.(Math.min(g+w.length,l),l)}i.exec("ANALYZE");let p=r.capi.sqlite3_js_db_export(i);await rI(n,p),i.close(),gh()}async function lI(n,e,t,r,i,o){let s=await oI(n);return mh(iI(s),e,t,r,i,o)}async function yh(){return await Cl(),{resetCache:gh,buildSearchIndex:cI,searchIndex:(n,e,t,r,i,o,s)=>lI(r,e,t,i,o,s)}}var Js=null,Il=null;async function Ks(){return Js||(Js=yh().then(n=>(Il=n,n))),Js}function wh(){Il?.resetCache(),Js=null,Il=null}async function dI(n,e,t,r,i,o,s){let a=await Ks(),c=s??vn();return a.searchIndex(n,e,t,c,r,i,o)}function ki(){wh()}function Sh(n,e,t){let r=new Set,i=[];for(let o of[...n,...e])if(!r.has(o.documentId)&&(r.add(o.documentId),i.push(o),i.length>=t))break;return i}function Xs(n,e,t,r,i,o){return dI(n,e,t,i,r.expandedQuery,r.rawQuery,o)}async function uI(n,e,t,r,i){let o=await Xs(n,e,t,r,Ci(r.tokens,"AND"),i);if(o.length>=t)return o;let s=await Xs(n,e,t,r,Ci(r.tokens,"OR"),i);return Sh(o,s,t)}async function Al(n,e,t,r,i){return r.ftsMatch?Xs(n,e,t,r,r.ftsMatch,i):r.preferAnd?uI(n,e,t,r,i):Xs(n,e,t,r,Ci(r.tokens,"OR"),i)}async function pI(n,e,t,r){let i=await Al(n,"harmonyos-references",e,t,r);if(i.length>=e)return i;let o=await Al(n,void 0,e,t,r);return Sh(i,o,e)}function vh(n,e){return e!==void 0?n:ch(n)}async function Dl(n,e,t=20,r){let i=await oh(n);if(eh(i.rawQuery,e)){let a=await pI(n,t,i,r);return vh(a,e)}let o=e??dh(i.rawQuery),s=await Al(n,o,t,i,r);return vh(s,e)}var Ti=class extends Error{constructor(e){super(e),this.name="NativeDepsError"}};function fI(){let n=oe();return["Documentation search index is not installed yet.","",...Ao(),`Index directory: ${n}`,"","Try:"," 1. Wait a moment and run the docs command again (postinstall may still be running)"," 2. Reinstall: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>"].join(`
1342
+ `)}function mI(){return["Chinese tokenizer (jieba-wasm) failed to load.","",`Node.js: ${process.version} (required: >=18)`,"",...Ao(),"","Try:"," 1. Reinstall: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>"," 2. Use Node.js 18 or newer"].join(`
1343
+ `)}function hI(n){return[n,"",...Ao()].join(`
1344
+ `)}async function Eh(){try{bm()}catch(n){throw Sm(n)?new Ti(`${fI()}
1345
+
1346
+ Detail: ${n.message}`):n}try{await pr()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Ti(`${mI()}
1347
+
1348
+ Detail: ${e}`)}try{await Ks()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Ti(hI(e))}}var Rl=class extends Error{constructor(t,r){super(r);this.code=t;this.name="DocNotReadyError"}code};function yI(n){return new Promise(e=>setTimeout(e,n))}async function bh(n,e,t){e?.start(t),await Ei({state:"installing",phase:1,phaseLabel:"Installing index",message:t}),await Tm(n),ki(),e&&(e.text="Documentation index installed.")}async function wI(n,e){try{return await bh(n,e,"Installing documentation index\u2026"),await Ph(e),!0}catch(t){if(wi(t))throw t}try{return await xm(),ki(),await bh(n,e,"Retrying documentation index install\u2026"),await Ph(e),!0}catch(t){if(wi(t))throw t;return!1}}async function Ph(n){await Ei({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function vI(n){let e=await pl(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";n?.succeed(t),await Ei({state:"done",message:t,error:null})}async function SI(n,e){let t=n instanceof Error?n.message:String(n);throw await Ei({state:"error",error:t}),e?.fail(t),n}async function EI(){let n=oe();await xi.promises.mkdir(n,{recursive:!0});let e=Ms();return xi.existsSync(e)||await xi.promises.writeFile(e,"","utf-8"),e}async function bI(){let n=await EI();return gI.lock(n,{stale:1800*1e3})}async function PI(){let n=Sn(),e=(n?await Hs(n):null)??await ul();if(!e)throw new Error("docs.zip not found");return e}async function CI(n,e){let t=await PI(),r=n.force||await fl(n.force),i=await Bs(n.force);if(!r&&!i&&bi()){await vI(e);return}if(!(km(t)&&await wI(t,e)))throw new Error("Documentation index bundle is unavailable or corrupted. Reinstall the package with: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>")}var Li=class{static async run(e={}){let t=e.background??!1,i=e.quiet??t?void 0:Ih({text:"Checking documentation\u2026",color:"cyan"}),o;try{e.assumeStorageSafe||await vi({mode:"write"}),o=await bI(),await dl(jm("Starting documentation setup\u2026")),await CI(e,i)}catch(s){throw o&&await SI(s,i),s}finally{o&&await o()}}};async function II(n){for(;;){let e=await Us();if(e.state==="done"&&bi())return;if(e.state==="error")throw new Rl("build-failed",e.error??"Documentation setup failed. Try your docs command again in a moment.");n.text=e.message||"Documentation is being prepared\u2026",await yI(500)}}async function Ch(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await Li.run({builtBy:"doc-init",force:e,quiet:!0})}async function AI(){let n=await Bs()!==null;if(bi()&&!n)return;let e=Ih({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await $m()){await II(e),e.succeed("Documentation ready.");return}if(await fl()){await Ch(e),e.succeed("Documentation ready.");return}await Ch(e,!0),e.succeed("Documentation ready.")}catch(t){throw e.fail(t.message),t}}async function Ni(){await vi({mode:"read"}),await AI(),await Eh()}function DI(n){let e=n instanceof Error?n.message:String(n);return/file is not a database|database disk image is malformed|SQLITE_CORRUPT/i.test(e)}var kl=class{async search(e,t,r=20){await Ni();try{return await Dl(e,t,r)}catch(i){if(!DI(i))throw i;return ki(),await Li.run({builtBy:"doc-init",force:!0,quiet:!0,assumeStorageSafe:!0}),Dl(e,t,r)}}async readDocument(e){return await Ni(),Am(e)}},Tl=new kl;function Ah(...n){return e=>{if(!n.includes(e))throw new xl(`Allowed values: ${n.join(", ")}`);return e}}function TI(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new xl("Must be a positive integer.");return e}var xI=Ah("json","default"),LI=Ah("json","default");function Ll(n){let e=n instanceof Error?n.message:String(n);return wi(n)?e:/\b(EACCES|EPERM|ENOSPC|ENOTDIR|ELOOP)\b/.test(e)?"Documentation data directory is unavailable. Check DEVECO_CLI_DATA_DIR and retry.":e}var Qs=new RI("docs").description("Search and read HarmonyOS documentation from local docs directory");Qs.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",OI,"all").option("--format <fmt>","Output format (default, json)",xI,"default").option("--limit <n>","Max number of results",TI,20).action(async(n,e)=>{try{let t=NI(n),r=e.catalog&&e.catalog!=="all"?e.catalog:void 0,i=await Tl.search(t,r,e.limit);e.format==="json"?console.log(JSON.stringify(i,null,2)):MI(i)}catch(t){console.error(Zs(Ll(t))),process.exit(1)}});Qs.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{try{let e=n.trim();e||(console.error(Zs("Document ID cannot be empty.")),process.exit(1));let t=await Tl.readDocument(e);console.log(t)}catch(e){console.error(Zs(Ll(e))),process.exit(1)}});Qs.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",LI,"default").action(async n=>{try{if(await Ni(),n.format==="json"){let e=Gt.map(t=>({name:t,title:wn[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of Gt)console.log(` ${e.padEnd(20)} ${kI(wn[e])}`)}catch(e){console.error(Zs(Ll(e))),process.exit(1)}});function NI(n){let e=n.map(r=>r.trim()).filter(Boolean);if(e.length===0)throw new Error("Keywords cannot be empty.");if(e.join(" ").length>pi)throw new Error(`Query exceeds ${pi} characters.`);return e}function OI(n){if(n==="all")return"all";if(!Gt.includes(n))throw new xl(`Invalid catalog "${n}". Allowed: all, ${Gt.join(", ")}`);return n}function MI(n){for(let e=0;e<n.length;e++){let t=n[e];console.log(t.documentId),console.log(` Title: ${t.title}`),t.snippet&&console.log(` Content: ${t.snippet}`),e<n.length-1&&console.log()}}var Dh=Qs;import{Command as HA}from"commander";import{Command as qI,InvalidArgumentError as YI,Option as Ol}from"commander";import{readFileSync as FI,unlinkSync as jI}from"fs";import{tmpdir as $I}from"os";import{join as HI}from"path";var bt=class{constructor(e,t){this.hdcPath=e;this.serial=t}hdcPath;serial;async listWindows(e){let t=await this.fetchDump(),r=_I(t);return e?.all||(r=r.filter(i=>i.type===1)),r}async fetchDump(){let e=["-t",this.serial,"shell","hidumper","-s","WindowManagerService","-a","-a"];m(`Executing: ${this.hdcPath} ${e.join(" ")}`);let t=await Ae(this.hdcPath,e);if(t.exitCode!==0)throw new Error(`Failed to query windows: ${(t.stderr||t.stdout).trim()}`);return t.stdout}};function _I(n){let e=n.split(`
1349
+ `),t=e.findIndex(s=>s.trimStart().startsWith("WindowName"));if(t===-1)return[];let r=[];for(let s=t+1;s<e.length;s++){let a=e[s].trim();if(!a||/^-+$/.test(a)||a.startsWith("Focus window")||a.startsWith("total window"))break;let c=a.split(/\s+/);if(c.length<5)continue;let l=c[0],p=Number(c[1]),g=Number(c[2]),w=Number(c[3]),C=Number(c[4]);Number.isFinite(w)&&Number.isFinite(p)&&Number.isFinite(g)&&r.push({id:w,name:l,pid:g,displayId:p,type:C})}let i=e.find(s=>s.trim().startsWith("Focus window")),o=i?Number(i.replace(/.*:\s*/,"").trim()):NaN;return r.map(s=>({...s,focused:s.id===o}))}function Rh(n){if(!(!n||n==="HitTestMode.Default"))return n.startsWith("HitTestMode.")?n.slice(12):n}function Oi(n){if(!(n==null||n==="")){if(typeof n=="boolean")return n;if(n==="true")return!0;if(n==="false")return!1}}function kh(n){if(typeof n!="string")return;let e=n.match(/-?\d+/g);if(!(!e||e.length<4))return[Number(e[0]),Number(e[1]),Number(e[2]),Number(e[3])]}function Th(n){return n.originalText||void 0}function fr(n,e){let t=[],r=[...n].reverse();for(;r.length>0;){let i=r.pop();i.id===e&&t.push(i);for(let o=i.children.length-1;o>=0;o--)r.push(i.children[o])}return t}function xh(n,e){let t=[],r=[{current:n,parent:null,depth:0}];for(;r.length>0;){let{current:i,parent:o,depth:s}=r.pop(),a=o===null,c=!i.id&&!i.text&&!i.clickable&&!i.longClickable&&!i.scrollable&&!i.checkable,l=a||!c,p=o;if(l){let w={...i,children:[]};if(a?t.push(w):o.children.push(w),p=w,e>0&&s+1>=e)continue}if(process.env.DEVECO_CLI_DEBUG){let w=i.type?i.id?`${i.type}#${i.id}`:i.type:"#";m(`collapse ${w} depth=${s} -> ${a?"root":c?"collapsed":"emitted"}`)}let g=l?s+1:s;for(let w=i.children.length-1;w>=0;w--)r.push({current:i.children[w],parent:p,depth:g})}return t}function UI(n){let e=FI(n,"utf-8").trim();if(!e)throw new Error("Empty dumpLayout response from device");return JSON.parse(e)}function BI(n){return n.attributes??{}}function ea(n,e,t){let r=BI(n),i={id:r.id||void 0,type:r.type||void 0,text:Th(r),bounds:kh(r.bounds),clickable:Oi(r.clickable)||void 0,longClickable:Oi(r.longClickable)||void 0,scrollable:Oi(r.scrollable)||void 0,checkable:Oi(r.checkable)||void 0,hitTestBehavior:Rh(r.hitTestBehavior),children:[]};return e>0&&t+1>=e||n.children&&(i.children=n.children.map(o=>ea(o,e,t+1))),i}function WI(n,e){if(e){let r=n.find(i=>String(i.id)===e);if(!r){let i=n.map(o=>`${o.id} (${o.name})`).join(", ");throw new Error(`Window '${e}' not found. Available windows: ${i||"none"}`)}return r}let t=n.find(r=>r.focused);if(t)return t;throw new Error("No window id specified and could not detect focused window")}var Pn=class{hdcPath;constructor(e){this.hdcPath=e}buildRemoteDumpPath(){return`/data/local/tmp/deveco_cli_dump_${Date.now()}_${process.pid}.json`}async fetchRawDump(e,t,r){let i=this.buildRemoteDumpPath(),o=["-t",e,"shell","uitest","dumpLayout","-p",i];r!==void 0&&o.push("-d",String(r)),t&&o.push("-w",t),m(`Executing: ${this.hdcPath} ${o.join(" ")}`);let s=await Ae(this.hdcPath,o);if(s.exitCode!==0)throw new Error(`Failed to dump layout: ${(s.stderr||s.stdout).trim()}`);return this.recvAndParseDump(e,i)}async recvAndParseDump(e,t){let r=HI($I(),`deveco_cli_dump_${Date.now()}_${process.pid}.json`);try{return await this.recvDumpFile(e,t,r),UI(r)}finally{await this.cleanupDumpArtifacts(e,r,t)}}async recvDumpFile(e,t,r){let i=["-t",e,"file","recv",t,r];m(`Executing: ${this.hdcPath} ${i.join(" ")}`);let o=await Ae(this.hdcPath,i);if(o.exitCode!==0)throw new Error(`Failed to recv dump file: ${(o.stderr||o.stdout).trim()}`)}async cleanupDumpArtifacts(e,t,r){try{m(`Removing local dump file: ${t}`),jI(t)}catch(o){m(`Failed to clean local dump file ${t}: ${o.message}`)}let i=["-t",e,"shell","rm","-f",r];m(`Executing: ${this.hdcPath} ${i.join(" ")}`),await Ae(this.hdcPath,i).catch(o=>{m(`Failed to clean remote dump file ${r}: ${o.message}`)})}async dumpRawNodes(e,t,r){let o=await new bt(this.hdcPath,e).listWindows({all:!0});if(r){let a=[...new Set(o.map(l=>l.displayId))],c=[];for(let l of a)c.push(await this.fetchRawDump(e,void 0,l));return c}let s=WI(o,t);return[await this.fetchRawDump(e,String(s.id),s.displayId)]}async dumpFullTree(e,t,r,i){return(await this.dumpRawNodes(e,r,i)).map(s=>ea(s,t,0))}async dumpFullTreeByDisplays(e,t,r){let i=[];for(let o of r){let s=await this.fetchRawDump(e,void 0,o);i.push({displayId:o,tree:ea(s,t,0)})}return i}async dumpCollapsedTree(e,t,r,i){return(await this.dumpRawNodes(e,r,i)).flatMap(s=>xh(ea(s,0,0),t))}};var ta={left:"0",right:"1",up:"2",down:"3"};function he(n,e){let t=Number(n);if(!Number.isInteger(t)||t<=0)throw new Error(`${e} must be a positive integer`)}function Nl(n,e){n!==void 0&&he(n,e)}function Lh(n,e){if(n===void 0!=(e===void 0))throw new Error("x and y must be provided together")}function na(n,e){if(n!==void 0&&n.length===0)throw new Error(`${e} must not be empty`)}function Mi(n){if(n===void 0)return;let e=Number(n);if(!Number.isInteger(e)||e<200||e>4e4)throw new Error("--speed must be an integer between 200 and 40000");return n}function Nh(n){if(n!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(n))throw new Error("--window must consist of letters, digits, - or _")}function Oh(n,e,t,r=!0){if(t&&!e)throw new Error("--window must be used with --id");if(n&&e)throw new Error("Coordinates and --id are mutually exclusive");if(r&&!n&&!e)throw new Error("Either provide x y coordinates or use --id")}function mr(n,e,t,r,i=!0){Lh(n,e),na(t,"--id"),Nl(n,"x"),Nl(e,"y"),Nh(r),Oh(n!==void 0,!!t,!!r,i)}async function hr(n,e){let r=await new zn(n).selectDevice(e);if(!r)throw new Error("No device selected. Use `devecocli device list` to see targets.");return r}async function ct(n){let e=await I.new(),t=await hr(e,n);return{hdcPath:e.hdcPath,deviceId:t}}async function gr(n,e,t,r,i,o){if(t!==void 0&&r!==void 0)return{x:t,y:r};if(i===void 0)throw new Error("Either provide x y coordinates or use --id");let a=await new bt(n,e).listWindows({all:!0}),c=new Pn(n);return GI(c,e,a,i,o)}async function GI(n,e,t,r,i){if(i!==void 0){let o=t.find(a=>String(a.id)===i);if(o&&o.displayId!==0)throw new Error(`Window "${i}" is on display ${o.displayId}. The current command only supports operations on the primary display.`);let s=await n.dumpFullTree(e,0,i,!1);return zI(s,r)}return VI(n,e,t,r)}async function VI(n,e,t,r){let i=[...new Set(t.map(a=>a.displayId))],o=await n.dumpFullTreeByDisplays(e,0,i),s=[];for(let{displayId:a,tree:c}of o)for(let l of fr([c],r))s.push({node:l,displayId:a});if(s.length===0)throw new Error(`Node "${r}" not found.`);if(s.length>1)throw new Error(`Multiple nodes found with id "${r}".`);if(s[0].displayId!==0)throw new Error(`Node "${r}" is on display ${s[0].displayId}. The current command only supports operations on the primary display.`);return Mh(s[0].node,r)}function zI(n,e){let t=fr(n,e);if(t.length===0)throw new Error(`Node "${e}" not found.`);if(t.length>1)throw new Error(`Multiple nodes found with id "${e}".`);return Mh(t[0],e)}function Mh(n,e){let t=n.bounds;if(!t)throw new Error(`Node "${e}" has no bounds.`);let[r,i,o,s]=t;return{x:Math.ceil((r+o)/2),y:Math.ceil((i+s)/2)}}async function $e(n,e,t){let r=["-t",e,"shell",t.join(" ")];m(`Executing: ${n} ${r.join(" ")}`);let i=await Ae(n,r);if(i.exitCode!==0)throw new Error(i.stderr||i.stdout||`uitest exited with code ${i.exitCode}`);let o=i.stdout.toLowerCase();if(["illegal","fail","error","incorrect","please confirm that the coordinate values are correct"].some(a=>o.includes(a))&&!o.includes("no error"))throw new Error(i.stdout.trim()||"uitest command failed")}import JI from"ora";function KI(n){let e=parseInt(n,10);if(!Number.isInteger(e)||e<0||String(e)!==n.trim())throw new YI("depth must be a non-negative integer");return e}function XI(n){let e=[];(n.type||n.id)&&e.push(n.type?n.id?`${n.type}#${n.id}`:n.type:`#${n.id}`),e.push(n.bounds?`[${n.bounds.join(",")}]`:"[]"),n.text&&e.push(`"${JSON.stringify(n.text).slice(1,-1)}"`);let t=[];return n.clickable&&t.push("clickable"),n.longClickable&&t.push("longClickable"),n.scrollable&&t.push("scrollable"),n.checkable&&t.push("checkable"),t.length>0&&e.push(...t),e.join(" ")}function _h(n,e=0){let t=[],r=" ".repeat(e);for(let i of n)t.push(`${r}${XI(i)}`),i.children.length>0&&t.push(..._h(i.children,e+1).split(`
1350
+ `));return t.join(`
1351
+ `)}function ZI(n){if(n.allWindows&&n.window)throw new Error("--all-windows and --window are mutually exclusive.")}function QI(n,e){let t=fr(n,e);if(t.length===0)throw new Error(`Node '${e}' not found.`);let r=t.map(i=>({...i,children:[]}));console.log(JSON.stringify(r,null,2))}function eA(n,e){console.log(e==="json"?JSON.stringify(n,null,2):_h(n))}async function tA(n){ZI(n);let e=JI({text:"Dumping layout\u2026",color:"cyan"}).start(),t;try{let r=await I.new(),i=await hr(r,n.device),o=new Pn(r.hdcPath);t=n.mode==="full"?await o.dumpFullTree(i,n.depth,n.window,n.allWindows):await o.dumpCollapsedTree(i,n.depth,n.window,n.allWindows)}catch(r){throw e.stop(),new Error(`Failed to dump layout: ${r.message}`,{cause:r})}if(e.stop(),n.id){QI(t,n.id);return}eA(t,n.format)}var Fh=new qI("layout").description("Inspect on-screen node(s) for UI testing").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Layout node id").option("--window <windowId>","Target window id").option("--all-windows","Include all windows (mutually exclusive with --window)").addOption(new Ol("--depth <n>","Tree depth limit (0=unlimited, 1=root only, 2=root+children)").argParser(KI).default(0)).addOption(new Ol("--format <format>","Output format").choices(["default","json"]).default("default")).addOption(new Ol("--mode <mode>","Output mode: full | simplified").choices(["full","simplified"]).default("simplified")).action(async n=>{await tA(n)});import{Command as nA,Option as rA}from"commander";import{yellow as iA}from"colorette";import oA from"ora";var sA=["Id","Name","Pid","DisplayId","Focused"];function aA(n,e){if(e==="json"){let r=n.map(i=>({id:i.id,name:i.name,pid:i.pid,displayId:i.displayId,focused:i.focused}));console.log(JSON.stringify(r,null,2));return}let t=n.map(r=>({cells:[String(r.id),r.name,String(r.pid),String(r.displayId),String(r.focused)],highlight:r.focused}));console.log(ft(sA,t))}async function cA(n){let e=oA({text:"Listing windows\u2026",color:"cyan"}).start(),t;try{let r=await I.new(),i=await hr(r,n.device);t=await new bt(r.hdcPath,i).listWindows({all:n.all})}catch(r){throw e.stop(),new Error(`Failed to list windows: ${r.message}`,{cause:r})}if(e.stop(),t.length===0){console.log(iA(" No windows found."));return}aA(t,n.format)}var Ml=new nA("window").description("Manage device windows");Ml.command("list").description("List windows on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new rA("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show all windows including system windows").action(async n=>{await cA(n)});import{Command as lA}from"commander";import ke from"fs";import He from"path";import{randomUUID as dA}from"crypto";import{execa as jh}from"execa";import{green as uA,red as pA}from"colorette";function _l(){return String(Date.now())}function fA(n){if(!n?.trim())return He.resolve(`screenshot-${_l()}.png`);let e=He.resolve(n.trim());if(ke.existsSync(e)&&ke.statSync(e).isDirectory())return He.join(e,`screenshot-${_l()}.png`);if(He.extname(e).toLowerCase()!==".png"){if(!ke.existsSync(e))throw new Error(`Screenshot directory does not exist: ${e}`);if(!ke.statSync(e).isDirectory())throw new Error(`Screenshot path is not a directory: ${e}`);return He.join(e,`screenshot-${_l()}.png`)}let t=He.dirname(e);if(!ke.existsSync(t))throw new Error(`Screenshot directory does not exist: ${t}`);if(!ke.statSync(t).isDirectory())throw new Error(`Screenshot parent path is not a directory: ${t}`);return e}function $h(n){if(!ke.existsSync(n))throw new Error(`Screenshot file was not created: ${n}`);let e=ke.statSync(n);if(!e.isFile()||e.size===0)throw new Error(`Screenshot file is empty: ${n}`);let t=ke.readFileSync(n).subarray(0,8),r=Buffer.from([137,80,78,71,13,10,26,10]);if(!t.equals(r))throw new Error(`Screenshot file is not a valid PNG: ${n}`)}async function jl(n,e,t){m(`Executing: ${n} ${e.join(" ")}`);let{stdout:r}=await jh(n,e,{env:{...process.env},cwd:t});return r}async function mA(n,e,t){m(`Executing: ${n} ${e.join(" ")}`);let{stdout:r,stderr:i}=await jh(n,e,{env:{...process.env},cwd:t});return{stdout:r,stderr:i}}async function hA(n,e,t){try{return await jl(n,e,t)}catch(r){return r.stdout??""}}async function gA(n,e){let t=Z.from(n),r=await t.listDevices();if(r.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");if(e===void 0){if(r.length===1)return r[0].serial;let s=await yA(t,r);throw new Error(`Multiple devices found. Specify a target device using \`--device <name|serial>\`.
1352
+ Available devices:
1353
+ ${s}`)}let i=e.trim();if(!i)throw new Error("--device must not be empty.");let o=await t.getDeviceInfo(r,i);if(!o)throw new Error(`Device "${i}" not found.`);return o.serial}async function yA(n,e){return(await Promise.all(e.map(async r=>` - ${await n.getDeviceName(r.serial)} (${r.serial})`))).join(`
1354
+ `)}function wA(n,e){let t=["-t",n.serial,"shell","snapshot_display"];return n.display!==void 0&&t.push("-i",n.display),t.push("-f",n.remotePath),e&&t.push("-t",e),t}function vA(n){let e=n.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}function SA(n,e){ke.copyFileSync(n,e),$h(e)}function EA(n){let e=n.trim();if(!e||/No such file|not found|cannot access/i.test(e))return;let t=e.split(/\s+/),r=Number(t[4]);return Number.isFinite(r)?r:void 0}async function bA(n){let e=await hA(n.hdcPath,["-t",n.serial,"shell","ls","-l",n.remotePath]);return EA(e)}function PA(n){return[n.stdout,n.stderr].filter(Boolean).join(`
1355
+ `).trim()}async function CA(n,e){let t;try{t=await mA(n.hdcPath,wA(n,e))}catch(i){t={stdout:i.stdout??"",stderr:i.stderr??i.message}}let r=await bA(n);return{created:r!==void 0&&r>0,output:PA(t)}}async function IA(n){let e=[];for(let t of[void 0,"png"]){let r=await CA(n,t);if(r.created)return;r.output&&e.push(r.output)}throw new Error(e.length>0?`Screenshot was not created on device: ${n.remotePath}. snapshot_display output: ${e.join(`
1356
+ `)}`:`Screenshot was not created on device: ${n.remotePath}.`)}function Hh(n){try{return $h(n),!0}catch{return!1}}function Uh(n){let e=[];for(let t of ke.readdirSync(n,{withFileTypes:!0})){let r=He.join(n,t.name);if(t.isDirectory()){e.push(...Uh(r));continue}t.isFile()&&Hh(r)&&e.push(r)}return e}function AA(n,e){let t=He.join(n,He.basename(e));if(Hh(t))return t;let r=Uh(n);if(r.length===1)return r[0];if(r.length>1)throw new Error(`Multiple screenshot files were received in ${n}.`)}async function Fl(n,e,t,r){try{await jl(n.hdcPath,["-t",n.serial,"file","recv",n.remotePath,t],r)}catch(i){m(`hdc file recv failed: ${i.message}`)}return AA(e,n.remotePath)}async function DA(n){let e=ke.mkdtempSync(He.join(He.dirname(n.localPath),".devecocli-screenshot-"));try{let t=await Fl(n,e,".",e)??await Fl(n,e,e)??await Fl(n,e,He.join(e,"screenshot.png"));if(!t)throw new Error(`Screenshot file was not created in ${e}.`);SA(t,n.localPath)}finally{ke.rmSync(e,{recursive:!0,force:!0})}}async function RA(n){await jl(n.hdcPath,["-t",n.serial,"shell","rm","-f",n.remotePath]).catch(()=>{})}async function kA(n){try{await IA(n),await DA(n)}finally{await RA(n)}}async function TA(n){try{let e=n.display!==void 0?vA(n.display):void 0,t=await I.new(),r=await gA(t,n.device),i=fA(n.path),o=`/data/local/tmp/devecocli-${dA()}.png`;await kA({hdcPath:t.hdcPath,serial:r,localPath:i,remotePath:o,display:e}),console.log(uA(`Screenshot saved to ${i}`))}catch(e){console.error(pA(`Failed to capture screenshot: ${e.message}`)),process.exit(1)}}var Bh=new lA("screenshot").description("Capture a screenshot of the device screen").option("--device <name|serial>","Target device name or serial; required when multiple devices are connected").option("--display <displayId>","Target display id; omit for default screen").option("--path <path>","Save path: directory or full file path with name; PNG only (default: ./screenshot-<timestamp>.png)").action(TA);import{Command as Yt}from"commander";function xA(n){let t=`"$(printf '%s' '${Buffer.from(n,"utf8").toString("base64")}' | base64 -d)"`;return m(`escapeShellText: ${n} -> ${t}`),t}async function Jt(n,e,t){let r=new Xe;r.start(n);try{await t(r)}catch(i){throw r.stop(),new Error(`${e}: ${i.message}`,{cause:i})}}async function LA(n,e,t){await Jt("Executing click...","click failed",async r=>{mr(n,e,t.id,t.window);let{hdcPath:i,deviceId:o}=await ct(t.device),{x:s,y:a}=await gr(i,o,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await $e(i,o,["uitest","uiInput","click",String(s),String(a)]),r.succeed(`click at (${s}, ${a})`)})}async function NA(n,e,t){await Jt("Executing doubleclick...","doubleclick failed",async r=>{mr(n,e,t.id,t.window);let{hdcPath:i,deviceId:o}=await ct(t.device),{x:s,y:a}=await gr(i,o,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await $e(i,o,["uitest","uiInput","doubleClick",String(s),String(a)]),r.succeed(`doubleclick at (${s}, ${a})`)})}async function OA(n,e,t){await Jt("Executing longclick...","longclick failed",async r=>{mr(n,e,t.id,t.window);let{hdcPath:i,deviceId:o}=await ct(t.device),{x:s,y:a}=await gr(i,o,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await $e(i,o,["uitest","uiInput","longClick",String(s),String(a)]),r.succeed(`longclick at (${s}, ${a})`)})}async function MA(n,e,t,r,i){await Jt("Executing swipe...","swipe failed",async o=>{he(n,"x1"),he(e,"y1"),he(t,"x2"),he(r,"y2");let s=Mi(i.speed),{hdcPath:a,deviceId:c}=await ct(i.device),l=["uitest","uiInput","swipe",n,e,t,r];s&&l.push(s),await $e(a,c,l),o.succeed(`swipe from (${n}, ${e}) to (${t}, ${r})`)})}async function _A(n,e,t,r,i){await Jt("Executing fling...","fling failed",async o=>{he(n,"x1"),he(e,"y1"),he(t,"x2"),he(r,"y2");let s=Mi(i.speed),{hdcPath:a,deviceId:c}=await ct(i.device),l=["uitest","uiInput","fling",n,e,t,r];s&&l.push(s),await $e(a,c,l),o.succeed(`fling from (${n}, ${e}) to (${t}, ${r})`)})}async function FA(n,e,t,r,i){await Jt("Executing drag...","drag failed",async o=>{he(n,"x1"),he(e,"y1"),he(t,"x2"),he(r,"y2");let s=Mi(i.speed),{hdcPath:a,deviceId:c}=await ct(i.device),l=["uitest","uiInput","drag",n,e,t,r];s&&l.push(s),await $e(a,c,l),o.succeed(`drag from (${n}, ${e}) to (${t}, ${r})`)})}async function jA(n,e){await Jt("Executing dircfling...","dircfling failed",async t=>{let r=ta[n];if(r===void 0)throw new Error(`Invalid direction "${n}". Valid values: ${Object.keys(ta).join(", ")}`);let{hdcPath:i,deviceId:o}=await ct(e.device);await $e(i,o,["uitest","uiInput","dircFling",r]),t.succeed(`dircfling ${n}`)})}async function $A(n,e,t,r){await Jt("Executing text input...","input failed",async i=>{mr(e,t,r.id,r.window,!1),na(n,"text");let{hdcPath:o,deviceId:s}=await ct(r.device),a=xA(n);if(e!==void 0)await $e(o,s,["uitest","uiInput","inputText",`${e}`,`${t}`,a]),i.succeed(`input ${n} at (${e}, ${t})`);else if(r.id){let{x:c,y:l}=await gr(o,s,void 0,void 0,r.id,r.window);await $e(o,s,["uitest","uiInput","inputText",`${c}`,`${l}`,a]),i.succeed(`input ${n} at (${c}, ${l})`)}else await $e(o,s,["uitest","uiInput","text",a]),i.succeed(`input ${n}`)})}var Wh=new Yt("click").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Tap at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(LA),Gh=new Yt("doubleclick").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Double-tap at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(NA),Vh=new Yt("longclick").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Long-press at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(OA),zh=new Yt("swipe").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Swipe from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(MA),qh=new Yt("fling").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Fling from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(_A),Yh=new Yt("drag").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Drag from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(FA),Jh=new Yt("dircfling").argument("<direction>","Direction: up, down, left, right").description("Fling in a specified direction").option("--device <name|serial>","Target device (name or serial)").action(jA),Kh=new Yt("text").argument("<text>","Text to input").argument("[x]","Optional X coordinate").argument("[y]","Optional Y coordinate").description("Input text at a target location or the currently focused field").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id to target before input (auto-resolves to center)").option("--window <windowId>","Target window id (used with --id)").action($A);var Ue=new HA("ui").description("Inspect and interact with UI on a connected device");Ue.addCommand(Fh);Ue.addCommand(Ml);Ue.addCommand(Bh);Ue.addCommand(Wh);Ue.addCommand(Gh);Ue.addCommand(Vh);Ue.addCommand(zh);Ue.addCommand(qh);Ue.addCommand(Yh);Ue.addCommand(Jh);Ue.addCommand(Kh);var Xh=Ue;import{Command as CR}from"commander";import{execa as cD}from"execa";import Pt from"fs";import*as Bl from"os";import*as V from"path";var UA=new RegExp("\x1B\\[[0-?]*[ -/]*[@-~]","g"),BA=/\r/g,WA=/^(Working|Finished)\.\.\.\[[^\]]*\]\d+%$/,GA=/^<+\s*/,VA=/\s*>+$/,zA=[/^The configuration file .+ is in use\.$/,/^The configuration file .+ in the project is in use\.$/,/^Currently active product: ?.+$/,/^Writing the result to .+\.$/,/^Write finished\.$/,/^CodeLinter found some defects in your code\.$/];function $l(n){if(!n)return"";let e=n.replace(UA,"").replace(BA,`
1357
+ `).split(`
1358
+ `).map(t=>t.trimEnd()).filter(t=>YA(t));return e.length>0?`${e.join(`
1359
+ `)}
1360
+ `:""}function tg(n){let e=$l(n).trim();if(!e)return{jsonText:void 0,diagnostics:""};if(ng(e))return{jsonText:e,diagnostics:""};let t=JA(e);if(!t)return{jsonText:void 0,diagnostics:`${e}
1361
+ `};let r=[e.slice(0,t.start).trim(),e.slice(t.end).trim()].filter(Boolean).join(`
1362
+ `);return{jsonText:e.slice(t.start,t.end),diagnostics:r?`${r}
1363
+ `:""}}function qA(n){return WA.test(n.trim())}function YA(n){let e=n.trim();return!!e&&!qA(e)&&!zA.some(t=>t.test(e))}function ng(n){try{return JSON.parse(n),!0}catch{return!1}}function JA(n){for(let e=0;e<n.length;e++){if(n[e]!=="["&&n[e]!=="{")continue;let t=KA(n,e);if(t)return t}}function KA(n,e){for(let t=n.length;t>e;t--){let r=n[t-1];if(r!=="]"&&r!=="}")continue;let i=n.slice(e,t);if(ng(i))return{start:e,end:t}}}var Zh=["Error","Warning","Suggestion","Info","Off","Unknown"];function rg(n){let e=Hl(n);return{issues:eD(e),summary:XA(n,e)}}function XA(n,e){let t=nD(e);return{filesChecked:rD(n).size,issues:e.length,errors:t.get("Error")??0,warnings:t.get("Warning")??0,suggestions:t.get("Suggestion")??0}}function Hl(n,e=""){if(Array.isArray(n))return n.flatMap(o=>Hl(o,e));if(!ig(n))return[];let t=_i(n,["filePath","file","path"])??e,r=ZA(n,t);if(r.length>0)return r;let i=QA(n,t);return i?[i]:[]}function ZA(n,e){let t=["messages","defects","issues","results","files"];for(let r of t){let i=n[r];if(Array.isArray(i)){let o=i.flatMap(s=>Hl(s,e));if(o.length>0)return o}}return[]}function QA(n,e){let t=_i(n,["message","description","desc","detail"])??"",r=aD(_i(n,["rule","ruleId","ruleName"])),i=oD(n,["severity","level"]),o=_i(n,["filePath","file","path"])??e;if(!(!t&&!r&&i==="Unknown"))return{file:o,line:eg(n,["line","reportLine"]),column:eg(n,["column","reportColumn"]),severity:i,rule:r,message:t}}function eD(n){return[...n].sort((e,t)=>{let r=Qh(e.severity)-Qh(t.severity);return r===0?tD(e,t):r})}function tD(n,e){let t=n.file.localeCompare(e.file);if(t!==0)return t;let r=(n.line??Number.MAX_SAFE_INTEGER)-(e.line??Number.MAX_SAFE_INTEGER);return r!==0?r:(n.column??Number.MAX_SAFE_INTEGER)-(e.column??Number.MAX_SAFE_INTEGER)}function nD(n){let e=new Map;for(let t of n){let r=t.severity;e.set(r,(e.get(r)??0)+1)}return e}function rD(n){let e=new Set;return Ul(e,n,""),e}function Ul(n,e,t){if(Array.isArray(e)){for(let i of e)Ul(n,i,t);return}if(!ig(e))return;let r=_i(e,["filePath","file","path"])??t;r&&n.add(r),iD(n,e,r)}function iD(n,e,t){let r=["messages","defects","issues","results","files"];for(let i of r){let o=e[i];if(Array.isArray(o))for(let s of o)Ul(n,s,t)}}function oD(n,e){for(let t of e){let r=n[t];if(typeof r=="string"||typeof r=="number")return sD(r)}return"Unknown"}function sD(n){let e=String(n).normalize("NFKC").trim().toLowerCase();return e==="2"||e==="error"||e==="err"?"Error":e==="1"||e==="warn"||e==="warning"?"Warning":e==="3"||e==="suggest"||e==="suggestion"?"Suggestion":e==="info"||e==="information"?"Info":e==="0"||e==="off"?"Off":"Unknown"}function aD(n){let e=n?.normalize("NFKC").trim();if(e)return e.replace(GA,"").replace(VA,"").toLowerCase()}function Qh(n){let e=Zh.indexOf(n);return e===-1?Zh.length:e}function _i(n,e){for(let t of e){let r=n[t];if(typeof r=="string")return r}}function eg(n,e){for(let t of e){let r=n[t];if(typeof r=="number")return r}}function ig(n){return typeof n=="object"&&n!==null}var og="deveco-codelinter-",Fi=class n{resolution;cwd;constructor(e,t){this.resolution=n.resolveWithToolProvider(e),this.cwd=t}static resolveProjectRoot(e){try{return U.discover(e).rootDir}catch{return e}}async check(e){let t=Pt.mkdtempSync(V.join(Bl.tmpdir(),og)),r=V.join(t,"report.json");try{let i=n.resolveProjectRoot(this.cwd),o=this.resolveLintTarget(e.lintPath,i),s=this.resolveConfigPath(e.configPath,o),a=this.buildNativeArgs(e,o.path,s,r),c=await this.run(a),l=tg(c.stdout),p=l.diagnostics+$l(c.stderr);try{let g=this.readJsonReport(r,l.jsonText);return{exitCode:c.exitCode,diagnostics:p,report:rg(g)}}catch(g){return{exitCode:c.exitCode,diagnostics:p,reportError:g}}}finally{this.removeTempDir(t)}}resolveLintTarget(e,t){let r=e?V.resolve(this.cwd,e):t,i=this.resolveRealPath(r,"Lint path"),o=Pt.statSync(i);if(!o.isFile()&&!o.isDirectory())throw new Error(`Lint path must be a file or directory: ${r}`);let s=this.discoverProjectRoot(i,o.isDirectory());if(e!==void 0&&s===void 0)throw new Error(`Lint path is not in a valid project directory (project-level build-profile.json5 not found or invalid): ${i}`);return{path:i,projectRoot:s}}resolveConfigPath(e,t){let r=e?V.resolve(this.cwd,e):V.join(t.projectRoot??this.cwd,"code-linter.json5"),i=this.resolveRealPath(r,"`--config-path`");if(!Pt.statSync(i).isFile())throw new Error(`--config-path must point to a file: ${r}`);if(t.projectRoot){let o=this.discoverProjectRoot(i,!1);if(o===void 0||V.relative(t.projectRoot,o)!=="")throw new Error(`\`--config-path\` must belong to the same project as the lint path. Lint project: ${t.projectRoot}; Config project: ${o??"not found"}.`)}return i}discoverProjectRoot(e,t){let r=t?e:V.dirname(e);try{return Pt.realpathSync(U.discover(r).rootDir)}catch{return}}resolveRealPath(e,t){try{return Pt.realpathSync(e)}catch(r){throw new Error(`${t} does not exist or cannot be resolved: ${e}`,{cause:r})}}buildNativeArgs(e,t,r,i){let o=["--config",r];return e.fix&&o.push("--fix"),e.incremental&&o.push("--incremental"),o.push("--product",e.product,"--format","json","--output",i,t),o}async run(e){let t=[...this.resolution.argsPrefix,...e],r=this.resolution.workingDirectory??this.cwd;this.prepareRuntimeDirectories(),m(`Executing: ${this.resolution.command} ${t.join(" ")}`),m(`[CodelinterAdapter] Working directory: ${r}`);let i=await cD(this.resolution.command,t,{cwd:r,env:this.resolution.env,stdout:"pipe",stderr:"pipe",reject:!1});return{exitCode:i.exitCode??1,stdout:i.stdout,stderr:i.stderr}}prepareRuntimeDirectories(){for(let e of this.resolution.runtimeDirectories??[])Pt.mkdirSync(e,{recursive:!0})}readJsonReport(e,t){let i=(Pt.existsSync(e)?Pt.readFileSync(e,"utf-8").trim():void 0)||t?.trim();if(!i)throw new Error("Native JSON report was not generated.");return JSON.parse(i)}removeTempDir(e){let t=V.resolve(e),r=V.resolve(Bl.tmpdir());!(t.startsWith(`${r}${V.sep}`)||t===r)||!V.basename(t).startsWith(og)||Pt.rmSync(t,{recursive:!0,force:!0})}static resolveWithToolProvider(e){let t=n.getSource(e),r=e.toolchainRoot,i=e.codelinterPath,o=e.sdkPath,s=n.getPathEntries(e,t),a=t==="ide"?"DevEco Studio":"DevEco Command Line Tools",c={command:e.nodePath,argsPrefix:[i,o],env:{...process.env,PATH:[...s,process.env.PATH||""].join(V.delimiter),DEVECO_SDK_HOME:o}};return t==="command-line-tools"&&(c.workingDirectory=r,c.runtimeDirectories=[n.getResultDirectory(i)]),m(`[CodelinterAdapter] Selected ${a} entry: ${i}`),c}static getPathEntries(e,t){let r=[V.dirname(e.nodePath)];return t==="ide"&&e.javaPath&&r.unshift(V.dirname(e.javaPath)),r}static getResultDirectory(e){return V.resolve(e,"..","linter","result")}static getSource(e){return e.sourceType==="studio"?"ide":"command-line-tools"}};import{red as ia,yellow as vD}from"colorette";import{Argument as SD,Command as ED,InvalidArgumentError as Xt}from"commander";import $i from"fs";import*as ve from"path";import*as ji from"path";var sg="n/a",ag=/\\/g,lD=/\|/g,dD=/\r?\n/g;function cg(n,e){if(n.issues.length===0)return`No defects found.
1364
+ ${Wl(n.summary)}
1365
+ `;let t=e===void 0?n.issues:n.issues.slice(0,e),r=[pD(t),Wl(n.summary)];return e!==void 0&&t.length<n.issues.length&&r.push(uD(n.issues.length,t.length)),`${r.join(`
1366
+ `)}
1367
+ `}function lg(n,e){return[Wl(n.summary),`Full report: ${Gl(e)}`,""].join(`
1368
+ `)}function dg(n){let e=["# CodeLinter report",""];return n.issues.length===0?e.push("No defects found.",""):e.push(...fD(n.issues),""),e.push("## Summary","",...hD(n.summary),""),e.join(`
1369
+ `)}function ug(n){return`${JSON.stringify(n,null,2)}
1370
+ `}function Wl(n){return`Summary: Issues: ${Be(n.issues)} | Errors: ${Be(n.errors)} | Warnings: ${Be(n.warnings)} | Suggestions: ${Be(n.suggestions)} | Files checked: ${Be(n.filesChecked)}`}function uD(n,e){return`Showing ${Be(e)} of ${Be(n)} issues. Use --output-path <path> to write all results.`}function pD(n){let e=["No","File","Line","Column","Severity","Rule","Message"],t=n.map((r,i)=>({cells:yD(r,i+1)}));return["CodeLinter report","",ft(e,t)].join(`
1371
+ `)}function fD(n){let e=["| No | File | Line | Column | Severity | Rule | Message |","| ---: | --- | ---: | ---: | --- | --- | --- |"];for(let[t,r]of n.entries())e.push(mD(r,t+1));return e}function mD(n,e){return`| ${[String(e),Gl(Kt(n.file)),ra(n.line),ra(n.column),Kt(n.severity),Kt(n.rule),Kt(n.message)].map(gD).join(" | ")} |`}function hD(n){return[`- Issues: ${Be(n.issues)}`,`- Errors: ${Be(n.errors)}`,`- Warnings: ${Be(n.warnings)}`,`- Suggestions: ${Be(n.suggestions)}`,`- Files checked: ${Be(n.filesChecked)}`]}function gD(n){return n.replace(ag,"\\\\").replace(lD,"\\|").replace(dD,"<br>")}function yD(n,e){return[String(e),Gl(Kt(wD(n.file))),ra(n.line),ra(n.column),Kt(n.severity),Kt(n.rule),Kt(n.message)]}function wD(n){if(!ji.isAbsolute(n))return n;let e=ji.relative(process.cwd(),n);return!e||e.startsWith("..")||ji.isAbsolute(e)?n:e}function Gl(n){return n.replace(ag,"/")}function Kt(n){let e=n?.trim();return e||sg}function ra(n){return n===void 0?sg:String(n)}function Be(n){return n.toLocaleString("en-US")}var bD=/^\d+$/;function Vl(){return new ED("lint").description("Run DevEco Code Linter checks for TS/ArkTS code").helpOption("--help","display help for command").addArgument(new SD("[path]","File or directory to lint").argParser(DD)).option("--fix","Auto-fix fixable code issues").option("--incremental","Only check uncommitted files").option("--config-path <path>","Path to lint configuration file",CD).option("--product <product>","Product name defined in build-profile.json5",ID,"default").option("--format <format>","Report format (choices: default, json)",PD,"default").option("--output-path <path>","Complete report file or directory",AD).option("--limit <number>","Maximum terminal issues to display when --output-path is omitted",RD).action(async(n,e)=>{await kD(n,e)})}function PD(n){if(n==="default"||n==="json")return n;throw new Xt("Invalid --format. Expected one of: default, json.")}function CD(n){zl(n,"--config-path");let e=ve.extname(n).toLowerCase();if(e!==".json"&&e!==".json5")throw new Xt("`--config-path` must point to a .json or .json5 file.");return n}function ID(n){return pg(n,"product"),n}function AD(n){return zl(n,"--output-path"),n}function DD(n){return zl(n,"path"),n}function RD(n){if(pg(n,"limit"),!bD.test(n))throw new Xt("`--limit` must be a positive integer.");let e=Number.parseInt(n,10);if(e<=0||!Number.isSafeInteger(e))throw new Xt("`--limit` must be an integer greater than 0.");return e}function pg(n,e){if(n.trim().length===0||hg(n))throw new Xt(`Invalid --${e} value.`)}function zl(n,e){let t=`\`${e}\``;if(n.length===0||hg(n))throw new Xt(`${t} must be a non-empty path without control characters.`)}async function kD(n,e){let t=process.cwd(),r=OD(e.outputPath,e.format,t);e.fix&&console.warn(vD("Running codelinter with --fix. Ensure your project source is trusted."));let i=await TD(n,e,t);$D(i.diagnostics),process.exitCode=LD(i,r,e.format,e.limit,t)}async function TD(n,e,t){let r=await I.new(),i=new Fi(r,t);return xD(i,{lintPath:n,configPath:e.configPath,product:e.product,fix:e.fix,incremental:e.incremental})}async function xD(n,e){let t=new Xe;process.stderr.isTTY&&t.start("Checking code...");try{let r=await n.check(e);return t.stop(),r}catch(r){throw t.fail("Code check failed"),r}}function LD(n,e,t,r,i){if(!n.report)return console.error(ia("Failed to generate Code Linter report.")),console.error(ia(n.reportError?.message??"Native JSON report was not generated.")),n.exitCode===0?1:n.exitCode;try{if(e){ND(e,t,n.report);let o=mg(e,i);process.stdout.write(lg(n.report,o))}else process.stdout.write(cg(n.report,r));return n.exitCode}catch(o){return console.error(ia("Failed to generate Code Linter report.")),console.error(ia(o.message)),n.exitCode===0?1:n.exitCode}}function ND(n,e,t){$i.mkdirSync(ve.dirname(n),{recursive:!0});let r=e==="json"?ug(t):dg(t);try{$i.writeFileSync(n,r,{encoding:"utf-8",flag:"wx"})}catch(i){throw i.code==="EEXIST"?new Error(`Output file already exists: ${n}`,{cause:i}):i}}function OD(n,e,t){if(!n)return;let r=FD(n,t),i=_D(n,r),o=i?ve.join(r,jD(e)):r;if(i||MD(n,e),$i.existsSync(o))throw new Xt(`Output file already exists: ${mg(o,t)}`);return o}function MD(n,e){let t=fg(e);if(ve.extname(n).toLowerCase()!==t)throw new Xt(`--output-path must use the ${t} extension for --format ${e}.`)}function _D(n,e){return $i.existsSync(e)?$i.statSync(e).isDirectory():n.endsWith("/")||n.endsWith("\\")||ve.extname(n)===""}function FD(n,e){return ve.resolve(e,n)}function jD(n){let e=new Date,t=[e.getFullYear(),e.getMonth()+1,e.getDate()].map((o,s)=>String(o).padStart(s===0?4:2,"0")).join(""),r=[e.getHours(),e.getMinutes(),e.getSeconds()].map(o=>String(o).padStart(2,"0")).join(""),i=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${r}-${i}${fg(n)}`}function fg(n){return n==="json"?".json":".md"}function mg(n,e){let t=ve.relative(e,n);return t&&!t.startsWith("..")&&!ve.isAbsolute(t)?t:n}function $D(n){n&&process.stderr.write(n)}function hg(n){for(let e of n){let t=e.charCodeAt(0);if(t<=31||t===127)return!0}return!1}import{Command as HD,InvalidArgumentError as vg}from"commander";import*as H from"path";import*as ql from"os";import{readdirSync as UD,existsSync as oa,readFileSync as BD,unlinkSync as WD,copyFileSync as Sg,writeFileSync as Eg}from"fs";import{execa as GD}from"execa";import{cyan as ae,yellow as bg}from"colorette";import VD from"ora";var gg=["default","csv","json"];function Pg(n){if(gg.includes(n))return n;throw new vg(`--format must be one of: ${gg.join(", ")} (got "${n}")`)}function zD(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new vg(`--limit must be a positive integer (got "${n}")`);return e}function qD(n){return[...n].sort((e,t)=>{let r=yg(e),i=yg(t);return r.apiVersion-i.apiVersion||r.suffix.localeCompare(i.suffix)})}function yg(n){let e=n.match(/\((\d+)\)/),t=e?Number(e[1]):0,r=n.lastIndexOf("_"),i=r>=0?n.slice(r+1):n;return{apiVersion:t,suffix:i}}function Cg(n){let t=UD(n,{withFileTypes:!0}).filter(r=>r.isFile()&&r.name.toLowerCase().endsWith(".json")).map(r=>r.name.slice(0,-5));return qD(t)}function YD(n){let e=process.argv;for(let t=0;t<e.length;t+=1){let r=e[t],i;if(r==="--format"&&t+1<e.length?i=e[t+1]:r.startsWith("--format=")&&(i=r.slice(9)),i!==void 0){let o=Pg(i);return o==="default"?"csv":o}}return n}async function JD(n){let e=await I.new(),{apiChangeDir:t}=e.getApiscanPaths();m(ae(`[compat:versions] apiChangeDir: "${t}"`));let r=Cg(t);if(n==="json")console.log(JSON.stringify({versions:r,count:r.length},null,2));else{if(r.length===0){console.log("No SDK versions available.");return}console.log(r.join(`
1372
+ `))}}var wg=new Set([".ets",".c",".cpp"]);function KD(n,e){let t=new Set(n.profile.modules.map(s=>s.name)),r=e.filter(s=>!t.has(s));if(r.length===0)return;let i=n.profile.modules.map(s=>s.name).join(", "),o=r.length>1?"are":"is";throw new Error(`Module ${r.map(s=>`"${s}"`).join(", ")} ${o} not defined in build-profile.json5. Available modules: ${i}.`)}function XD(n){for(let e of n){let t=H.resolve(e);if(!oa(t))throw new Error(`File "${e}" does not exist.`);let r=H.extname(t).toLowerCase();if(!wg.has(r)){let i=Array.from(wg).join(", ");throw new Error(`Unsupported file extension "${r}" for "${e}". Supported: ${i}.`)}}}function ZD(n){let e=[],t=[];for(let r of n)H.extname(r).toLowerCase()===".ets"?e.push(r):t.push(r);return{arkTs:e,cpp:t}}function QD(n){let e=[],t=[],r="",i=!1,o=0;for(;o<n.length;){let s=n[o];i?{field:r,inQuotes:i,i:o}=eR(n,o,s,r,i):s==='"'?(i=!0,o+=1):s===","?(t.push(r),r="",o+=1):s===`
1373
+ `?(t.push(r),e.push(t),t=[],r="",o+=1):(s==="\r"||(r+=s),o+=1)}return(r.length>0||t.length>0)&&(t.push(r),e.push(t)),e}function eR(n,e,t,r,i){return t!=='"'?{field:r+t,inQuotes:i,i:e+1}:n[e+1]==='"'?{field:r+'"',inQuotes:i,i:e+2}:{field:r,inQuotes:!1,i:e+1}}function tR(n,e){return e.map(t=>{let r=i=>{let o=n.indexOf(i);return o>=0&&o<t.length?t[o]:""};return{apiDefinition:r("Api Definition"),language:r("Language"),changeId:r("ChangeId"),changedInSdk:r("Changed in SDK"),affectedVersions:r("Affected Versions"),title:r("Title"),codeLocation:r("Code Location"),changeType:r("Change Type")}})}function nR(n){let e=BD(n,"utf8"),t=e.startsWith("\uFEFF")?e.slice(1):e,r=QD(t);if(r.length<2)return[];let[i,...o]=r;return tR(i,o)}function rR(n,e){let t=n.match(/CSV saved to:\s*([^\r\n]+\.csv)/);if(!t)return null;let r=t[1].trim();return H.isAbsolute(r)?r:H.join(e,r)}function iR(n,e){let t=new Map;for(let o of n){let s=o.changeType||"(unknown)";t.set(s,(t.get(s)??0)+1)}let r=Array.from(t.entries()).sort((o,s)=>s[1]-o[1]||o[0].localeCompare(s[0])),i=Math.max(5,...r.map(([o])=>o.length));console.log(ae("API change scan summary:")),console.log(` ${"Total".padEnd(i)} ${n.length}`);for(let[o,s]of r)console.log(` ${o.padEnd(i)} ${s}`);e&&console.log(` ${"Report".padEnd(i)} ${e}`)}function oR(n,e){if(console.log(),n.length===0){console.log("No API changes detected.");return}let t=n.slice(0,e),r=n.length-t.length;console.log(ae(`Details (showing ${t.length}${r>0?` of ${n.length}`:""}):`));let i=[["Title","title"],["Language","language"],["ChangeId","changeId"],["Changed in","changedInSdk"],["Affected Versions","affectedVersions"],["Code Location","codeLocation"]],o=Math.max(...i.map(([a])=>a.length)),s=a=>a||"<unknown>";for(let a of t){console.log(` [${s(a.changeType)}] ${s(a.apiDefinition)}`);for(let[c,l]of i)console.log(` ${c.padEnd(o)} ${s(a[l])}`)}r>0&&console.log(bg(` ... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function sR(n,e){let t=n.slice(0,e),r=n.length-t.length;console.log(),console.log(JSON.stringify({count:n.length,records:t},null,2)),r>0&&console.log(bg(`... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function aR(n,e){let t=[];for(let r of e){let i=n.profile.modules.find(o=>o.name===r);if(!i)throw new Error(`Module "${r}" not found in build-profile.json5.`);t.push(H.resolve(n.rootDir,i.srcPath))}return t}function cR(n,e,t,r){if(!r.sourceVersion||!r.targetVersion)throw new Error("source-version and target-version are required.");let i=[n,"--startVersion",r.sourceVersion,"--endVersion",r.targetVersion];if(e.length>0){let{arkTs:o,cpp:s}=ZD(e),a=p=>H.resolve(process.cwd(),p),c=o.map(a),l=s.map(a);c.length>0&&i.push("--arkTsFiles",c.join(",")),l.length>0&&i.push("--cppFiles",l.join(","))}else if(r.modules&&r.modules.length>0){let o=aR(t,r.modules);i.push("--modulePaths",o.join(","))}else i.push("--projectPath",t.rootDir);return i.push("--outputPath",ql.tmpdir()),i}async function lR(n,e){let t=H.dirname(e[0]);try{let i=(await GD(n.nodePath,e,{cwd:t,stdin:"ignore",stdout:"pipe",stderr:"inherit"})).stdout;return process.env.DEVECO_CLI_DEBUG&&(console.log(ae("[compat:check] === scan stdout ===")),process.stdout.write(i),i.endsWith(`
1374
+ `)||process.stdout.write(`
1375
+ `),console.log(ae("[compat:check] === end stdout ==="))),i}catch(r){let i=r;process.env.DEVECO_CLI_DEBUG&&i.stdout&&(console.log(ae("[compat:check] === scan stdout (on error) ===")),process.stdout.write(i.stdout),i.stdout.endsWith(`
1376
+ `)||process.stdout.write(`
1377
+ `),console.log(ae("[compat:check] === end stdout ===")));let o=new Error(`Compatibility scan failed: ${i.message}`+(i.stderr?`
1378
+ ${i.stderr}`:""));throw i.stdout&&(o.stdout=i.stdout),o}}function dR(n,e){if(n.length>0&&e.modules&&e.modules.length>0)throw new Error("Cannot use `--modules` together with file arguments. Use either file-level scanning (with files) or module-level scanning (with --modules).");if(!e.sourceVersion)throw new Error("--source-version is required.");if(!e.targetVersion)throw new Error("--target-version is required.");if(!e.outputPath&&e.format==="csv")throw new Error("--format csv requires --output-path. For console output, use --format json or --format default (or omit the flag).")}function uR(n,e){let t=[];if(n.sourceVersion&&!e.includes(n.sourceVersion)&&t.push(`--source-version "${n.sourceVersion}"`),n.targetVersion&&!e.includes(n.targetVersion)&&t.push(`--target-version "${n.targetVersion}"`),t.length>0){let r=t.length>1?"are":"is";throw new Error(`${t.join(" and ")} ${r} not in the available SDK version list.
1379
+ Run \`devecocli compat versions\` to see all available versions.`)}if(n.sourceVersion&&n.targetVersion){let r=e.indexOf(n.sourceVersion),i=e.indexOf(n.targetVersion);if(r>=i)throw new Error(`--target-version "${n.targetVersion}" must be later than --source-version "${n.sourceVersion}". Run \`devecocli compat versions\` to see the available order.`)}}function pR(n,e,t,r,i){i==="none"&&(t==="json"?sR(n,r):oR(n,r)),iR(n,e)}function fR(n,e){let t=H.dirname(n),r=H.basename(n),i=e.slice(1).map(o=>o.startsWith("--")?o:`"${o}"`).join(" ");m(ae(`[compat:check] command: cd "${t}" && node "${r}" ${i}`))}function mR(n){try{WD(n),m(ae(`[compat:check] cleaned up tmp report: "${n}"`))}catch(e){m(ae(`[compat:check] failed to clean up tmp report: ${e.message}`))}}var hR=[".csv",".json"];function gR(n){return hR.includes(n.toLowerCase())}function yR(n,e){if(!n)return{kind:"none"};let t=H.extname(n).toLowerCase();if(!gR(t))return{kind:"dir",dirPath:H.resolve(n)};if(t===".csv"&&!(e==="default"||e==="csv")||t===".json"&&e!=="json")throw new Error(`The --output-path file extension '${t}' does not match --format ${e}. Use --format ${t===".json"?"json":"default"}, or rename the file.`);return{kind:"file",filePath:H.resolve(n),ext:t}}function wR(n){if(n.kind==="file"){if(oa(n.filePath))throw new Error(`Target file "${n.filePath}" already exists. Remove it first, or choose a different --output-path.`);let e=H.dirname(n.filePath);if(!oa(e))throw new Error(`Target directory "${e}" does not exist. Create it first, or choose a different --output-path.`)}else if(n.kind==="dir"&&!oa(n.dirPath))throw new Error(`Target directory "${n.dirPath}" does not exist. Create it first, or choose a different --output-path.`)}function Ig(n){return JSON.stringify({count:n.length,records:n},null,2)+`
1380
+ `}function vR(n,e,t,r){r===".csv"?Sg(n,t):Eg(t,Ig(e),"utf8"),m(ae(`[compat:check] saved report: "${t}"`))}function SR(n,e,t,r){if(r==="json"){let o=H.basename(n,".csv"),s=H.join(t,`${o}.json`);return Eg(s,Ig(e),"utf8"),m(ae(`[compat:check] saved report: "${s}"`)),s}let i=H.join(t,H.basename(n));return Sg(n,i),m(ae(`[compat:check] saved report: "${i}"`)),i}async function ER(n,e){let t=new dt(n,process.cwd(),!0),r=e.modules&&e.modules.length>0?e.modules[0]:void 0;try{await t.compileNative("default",r)}catch(i){throw new Error(`hvigorw compileNative failed (module=${r??"<project>"}): `+i.message,{cause:i})}}async function bR(n,e){dR(n,e);let t=U.discover(process.cwd());e.modules&&e.modules.length>0&&KD(t,e.modules),n.length>0&&XD(n);let r=await I.new(),{apiChangeDir:i,scriptPath:o}=r.getApiscanPaths();m(ae(`[compat:check] script: "${o}"`));let s=Cg(i);uR(e,s),e.outputPath&&m(ae(`[compat:check] outputPath: "${e.outputPath}"`));let a=yR(e.outputPath,e.format);return m(ae(`[compat:check] outputTarget: ${a.kind}`)),wR(a),{project:t,scriptPath:o,target:a,toolProvider:r}}async function PR(n,e){let{project:t,scriptPath:r,target:i,toolProvider:o}=await bR(n,e),s=VD({text:"Running compatibility check...",color:"cyan"}).start();try{await ER(o,e);let a=cR(r,n,t,e);fR(r,a);let c=await lR(o,a),l=rR(c,ql.tmpdir());if(!l)throw new Error("Scanner output format unexpected: missing report path.");m(ae(`[compat:check] tmp csv: "${l}"`));let p=nR(l),g=null;if(i.kind==="file")vR(l,p,i.filePath,i.ext),g=i.filePath;else if(i.kind==="dir")g=SR(l,p,i.dirPath,e.format);else if(i.kind!=="none")throw new Error(`Unexpected output target kind: ${i.kind}`);mR(l),s.stop(),pR(p,g,e.format,e.limit,i.kind)}catch(a){throw s.fail("Compatibility check failed"),a}}var Yl=new HD("compat").description("Compatibility checking utilities.");Yl.description("Check source code compatibility against a target SDK version. By default, performs a project-level scan; pass positional `files...` for file-level scanning; pass `--modules` for module-level scanning.").arguments("[files...]").option("--source-version <version>","Current project SDK version (required; use `compat versions` to list available versions). On zsh, quote the value because version strings contain parentheses; run `compat versions` first to copy a real example.").option("--target-version <version>","Target SDK version (required; use `compat versions` to list available versions). On zsh, quote the value because version strings contain parentheses; run `compat versions` first to copy a real example.").option("--modules <modules...>","Modules to check (default: all modules in the project). Mutually exclusive with positional file arguments.").option("--format <format>",'Output format: "json" or "default" (text) for console; "csv", "json", or "default" for file output (--output-path). "csv" requires --output-path.',Pg,"default").option("--output-path <path>","Directory to write the detailed report CSV to (default: ./compat-output)").option("--limit <num>","Maximum number of change records to display (default: 100)",zD,100).action(async(n,e)=>{await PR(n,e)});Yl.command("versions").description("List all available target SDK versions for compatibility checking").action(async()=>{let n=YD("csv");await JD(n)});var Ag=Yl;var IR=new CR("check").description("Run DevEco project checks").addCommand(Ag).addCommand(Vl()),Dg=IR;import{Command as uT}from"commander";import{green as yd,red as pT}from"colorette";import wd from"fs";import dy from"path";import uy from"json5";import{readFileSync as ZR}from"fs";import{join as AR}from"path";var q={BASE_URL:"https://connect-api.cloud.huawei.com",CERT_LIST_PATH:"/api/cps/harmony-cert-manage/v1/cert/list",CERT_DELETE_PATH:"/api/cps/harmony-cert-manage/v1/cert/delete",CERT_ADD_PATH:"/api/cps/harmony-cert-manage/v1/cert/add",CERT_DOWNLOAD_URL_PATH:"/api/amis/app-manage/v1/objects/url/reapply",DEVICE_ADD_PATH:"/api/cps/device-manage/v1/device/add",DEVICE_LIST_PATH:"/api/cps/device-manage/v1/device/list",PROVISION_ADD_REAL_PATH:"/api/cps/provision-manage/v1/ide/real/provision/add",PROVISION_ADD_TEST_PATH:"/api/cps/provision-manage/v1/ide/test/provision/add",PROVISION_DELETE_PATH:"/api/cps/provision-manage/v1/provision/delete"},Se={CERT_NAME_PREFIX:"auto_debug_",CERT_TYPE_DEBUG:"1",TEAM_ID_INVALID_CHARS:/[\\/.:]/g,CERT_PATTERN:/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/,TARGET_FRIENDLY_NAME:"debugKey",CERTIFICATE_PATTERN_GLOBAL:/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g,BUNDLE_NAME_REGEX:/^[a-zA-Z][a-zA-Z0-9._-]*$/,CERT_BEGIN_HEADER:"-----BEGIN CERTIFICATE-----",CERT_SAVE_DIR:AR(".ohos","config"),DOWNLOAD_CONNECT_TIMEOUT_MS:5e3},ce={SUCCESS_MARKER:'"code":0',SQUARE_BRACKETS:"[]",OPENPROXY_BLOCKED_URL:"Openproxy_Blocked_URL_list",CERT_LIMIT_CODE:"205389872",USER_NOT_HARMONY_CODE:"205389904",DEVICE_EXCEEDS_LIMIT_CODE:"205389859",DEVICE_NAME_REPEAT_CODE:"205389857",PROVISION_EXCEEDS_LIMIT_CODE:"205389938",PROVISION_NAME_REPEAT_CODE:"205389830"},et={FORBIDDEN:403,UNAUTHORIZED:401},v={ERR_FORBIDDEN:"You do not have AppGallery Connect permissions for the current team. Request access from the team administrator or switch to a team where you have permissions.",ERR_UNAUTHORIZED:"Invalid AccessToken. Sign in and try again.",ERR_CERT_LIMIT_REACHED:"The number of certificates has reached the limit. Delete some certificates and try again.",ERR_CERT_NETWORK_ERROR:"Ensure the external network connection is available before downloading the certificate.",ERR_CERT_INVALIDATE:"The downloaded .cer file is invalid. Try again.",ERR_DOWNLOAD_CER:"Failed to download the certificate file. Check the following configurations: Network connection, HTTP Proxy, etc.",ERR_USER_NOT_HARMONY:"The user is not in harmony allow list, please grant the permission",ERR_READ_CSR:"Failed to read the .csr file, please try again later",ERROR_WHILE_ADD_DEVICE:"Failed to add the device, please try again.",DEVICE_LIMIT_REACHED:"The number of devices has reached the limit. Delete some unused devices and try again.",DEVICE_NAME_REPEAT:"Duplicate device name, please try again.",DEVICE_LIST_EMPTY:"No devices available.",ADD_PROFILE_FAIL:"Failed to add the profile, please try again.",NO_AGC_PERMISSION:"You do not have the AppGallery Connect permission with the current team. Apply for the permission form the team administrator, or switch to a team with which you already have the permission.",ERROR_WHILE_DOWNLOAD_PROFILE:"Failed to download the profile, please try again.",PROFILE_NAME_REPEAT:"The profile name already exists in the AGC.",ERROR_WHILE_PARSE_PROFILE:"Failed to parse the profile, please try again.",TEST_PROVISION_EXCEEDS_LIMIT:"Provision number exceeds limit.",CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT:"The certificate application file is inconsistent with the file in profile, please try again.",CERTIFICATE_HAS_EXPIRED:"The signature does not take effect or has expired. It may be the current system time is inaccurate, please calibrate the system time and sign again.",ERROR_SIGN_BUNDLE_NAME_VALIDATE:"The bundle name contains 7 to 128 characters, including only letters, digits, and underscores (_). It must be start with a letter and contain at least three segments separated by periods (.), each of the segments ending with a digit or letter."},J={TOOLCHAIN_INIT_FAILED:"Auto-sign failed: unable to initialize toolchain",LOGIN_REQUIRED:"Failed to automatically generate signatures.Run devecocli auth login to sign in.",TEAM_INFO_FAILED:"Failed to obtain user team information.Check the network connection, HTTP proxy, and other configurations.",REALNAME_REQUIRED:"Users without real-name verification are not supported.Complete real-name verification in AppGallery Connect.",SESSION_EXPIRED:"User session expired or token invalid. Please login again.",REGION_CHINA_ONLY:"This feature is only available for accounts registered in Chinese mainland.",DEVICE_MISSING:"Unable to create the profile file due to missing devices.Connect a device through IP or USB, or manually add a device in AppGallery Connect first.If you are installing the HAP package on an emulator, you can skip the signing step.",DEVICE_DETECT_FAILED:"Unable to detect devices. Please check hdc status. If installing HAP on an emulator, signature step can be skipped.",PROJECT_DIR_MISSING:"Not in a valid project directory (project-level build-profile.json5 not found).",ATOMIC_SERVICE_UNSUPPORTED:"AtomicService projects are not yet supported. Please configure signing manually."};function sa(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}function Jl(n){let e=n.replace(Se.TEAM_ID_INVALID_CHARS,"");return`${Se.CERT_NAME_PREFIX}${e}.cer`}function yr(n,e,t){if(n===et.FORBIDDEN)return e===ce.OPENPROXY_BLOCKED_URL?new Error(v.ERR_CERT_NETWORK_ERROR):new Error(v.ERR_FORBIDDEN);if(n===et.UNAUTHORIZED)return new Error(v.ERR_UNAUTHORIZED);if(t.includes(ce.USER_NOT_HARMONY_CODE))return new Error(v.ERR_USER_NOT_HARMONY);if(t.includes(ce.CERT_LIMIT_CODE))return new Error(v.ERR_CERT_LIMIT_REACHED);let r=DR(t);return new Error(r??v.ERR_DOWNLOAD_CER)}function DR(n){let e=Rg(n);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let r=typeof t=="string"?Rg(t):t;if(r&&typeof r=="object"){let i=r.msg;if(typeof i=="string"&&i.trim()!=="")return i}return null}function Rg(n){try{return JSON.parse(n)}catch{return null}}function Kl(n){return JSON.parse(n)}async function kg(n){let e=`${q.BASE_URL}${q.CERT_LIST_PATH}`,t=await L.postAllowFailure(e,{headers:sa(n)});if(t.statusCode!==200)throw yr(t.statusCode,t.statusText,t.data);return Kl(t.data)?.certList??[]}async function aa(n,e){return(await kg(n)).find(r=>r.certName===e)??null}async function Xl(n,e){let t=`${q.BASE_URL}${q.CERT_DELETE_PATH}`,r=await L.deleteAllowFailure(t,{headers:sa(n),params:{certIds:[e]}});if(r.statusCode!==200)throw yr(r.statusCode,r.statusText,r.data);return Kl(r.data)?.ret?.code===0}async function Zl(n,e,t){let r=`${q.BASE_URL}${q.CERT_ADD_PATH}`,i={csr:e,certName:t,certType:Se.CERT_TYPE_DEBUG},o=await L.postAllowFailure(r,{headers:sa(n),params:i});if(o.statusCode!==200)throw yr(o.statusCode,o.statusText,o.data);if(!o.data.includes(ce.SUCCESS_MARKER))throw yr(void 0,o.statusText,o.data)}async function Ql(n,e){let t=`${q.BASE_URL}${q.CERT_DOWNLOAD_URL_PATH}`,r=await L.postAllowFailure(t,{headers:sa(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw yr(r.statusCode,r.statusText,r.data);return Kl(r.data)?.urlsInfo?.[0]?.newUrl??null}import{mkdirSync as RR,writeFileSync as kR,existsSync as TR}from"fs";import{dirname as xR}from"path";async function Hi(n,e){let{statusCode:t,statusText:r,buffer:i}=await L.getBinaryAllowFailure(n,{timeout:Se.DOWNLOAD_CONNECT_TIMEOUT_MS});if(t!==200)throw t===et.FORBIDDEN&&r===ce.OPENPROXY_BLOCKED_URL?new Error(v.ERR_CERT_NETWORK_ERROR):new Error(v.ERR_DOWNLOAD_CER);let o=xR(e);TR(o)||RR(o,{recursive:!0}),kR(e,i)}import JR from"fs/promises";import{readFileSync as KR}from"fs";import ca from"path";import Lg from"crypto";import LR from"os";import Ui from"fs/promises";var Ng={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},Tg=["ECC","RSA"],xg=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],NR={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},OR=8,ed=64,MR=/[\\:*?"<>|=-]/g,tt={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function _R(n){if(!n.keyAlias.trim())throw new Error("keyAlias cannot be empty");if(!n.keystoreFile.trim())throw new Error("keystoreFile cannot be empty");if(n.keyAlias.length>ed)throw new Error(`The length of keyAlias cannot exceed ${ed}`);if(!Tg.includes(n.keyAlg))throw new Error(`Invalid key algorithm ${n.keyAlg}, available: ${Tg.join(" / ")}`);let e=NR[n.keyAlg];if(!e.includes(n.keySize))throw new Error(`Key algorithm ${n.keyAlg} does not support size ${n.keySize}, available: ${e.join(", ")}`)}function FR(n){if(!n.keyAlias.trim())throw new Error("keyAlias cannot be empty");if(!n.keystoreFile.trim())throw new Error("keystoreFile cannot be empty");if(!n.subject.trim())throw new Error("subject cannot be empty");if(!xg.includes(n.signAlg))throw new Error(`Invalid sign algorithm ${n.signAlg}, available: ${xg.join(" / ")}`)}function jR(n){return Lg.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function $R(n){let e=n?.trim()??"";return e&&e.replace(MR,"_").slice(0,ed)||tt.productName}async function Og(){let n=await I.new(),e=n.javaPath;if(!e)throw new Error("Java runtime not found. DevEco Studio JBR is required to run hap-sign-tool.jar.");let t=n.sdkPath;f.info(`\u8BFB\u53D6SDK\u6839\u76EE\u5F55\uFF1A${t}`);let r=ca.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");try{await Ui.access(r)}catch(i){throw new Error(`Sign tool jar not found: ${r}`,{cause:i})}return{javaPath:e,jarPath:r}}async function HR(n){let{javaPath:e,jarPath:t}=await Og(),r=["-jar",t,Ng.GENERATE_KEYPAIR,"-keyAlias",n.keyAlias,"-keyAlg",n.keyAlg,"-keySize",n.keySize,"-keystoreFile",n.keystoreFile,"-keystorePwd",n.keystorePwd];n.keyPwd&&r.push("-keyPwd",n.keyPwd),n.pwdInputMode&&r.push("-pwdInputMode",n.pwdInputMode);let i=r.map(o=>["-keyPwd","-keystorePwd"].includes(o)?`${o} ******`:o);return f.debug("generate-keypair \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",i.join(" ")),[e,...r]}async function UR(n){let{javaPath:e,jarPath:t}=await Og(),r=["-jar",t,Ng.GENERATE_CSR,"-keyAlias",n.keyAlias,"-subject",n.subject,"-signAlg",n.signAlg,"-keystoreFile",n.keystoreFile,"-keystorePwd",n.keystorePwd];n.outFile&&r.push("-outFile",n.outFile),n.keyPwd&&r.push("-keyPwd",n.keyPwd),n.pwdInputMode&&r.push("-pwdInputMode",n.pwdInputMode);let i=r.map(o=>["-keyPwd","-keystorePwd"].includes(o)?`${o} ******`:o);return f.debug("generate-csr \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",i.join(" ")),[e,...r]}async function BR(n){f.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),_R(n);let e=await HR(n),t=await Tr(e[0],e.slice(1));if(t.exitCode!==0){let r=t.stderr||t.stdout||"Unknown tool error";throw new Error(`An error occurred while generating the private key P12, exit code${t.exitCode}\uFF1A${r}`)}return f.info("\u751F\u6210P12\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}async function WR(n){f.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),FR(n);let e=await UR(n),t=await Tr(e[0],e.slice(1));if(t.exitCode!==0){let r=t.stderr||t.stdout||"Unknown tool error";throw new Error(`An error occurred while generating the CSR, exit code${t.exitCode}\uFF1A${r}`)}return f.info("\u751F\u6210CSR\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}function GR(n=OR){return Lg.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function VR(){let n=LR.homedir();try{await Ui.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=ca.join(n,".ohos","config");try{await Ui.mkdir(e,{recursive:!0,mode:448})}catch(t){throw new Error(`Failed to create directory ${e}`,{cause:t})}return f.info(`\u7B7E\u540D\u914D\u7F6E\u76EE\u5F55\u5C31\u7EEA\uFF1A${e}`),e}async function pe(n,e,t){let r=$R(n),i=ca.basename(e),o=jR(e),s=`${r}_${i}_${o}=.${t}`,a=await VR();return ca.join(a,s)}function zR(n){let e;try{e=U.discover(n).rootDir}catch(t){throw new Error(`Current directory ${n} is not a valid project root`,{cause:t})}return e}async function qR(n){try{await Ui.access(n)}catch(e){throw new Error(`Project directory ${n} is not accessible, missing read/write permissions`,{cause:e})}}async function YR(n){try{await Ui.access(n)}catch(e){throw new Error(`P12 file ${n} does not exist, terminating CSR generation.`,{cause:e})}}async function td(n,e,t){let r=process.cwd(),i=zR(r);await qR(i),f.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${i}`);let o=GR(),s=await pe(n??"",i,"p12"),a=await pe(n??"",i,"csr");return console.log("Start generating p12"),await BR({keyAlias:e?.keyAlias??tt.keyAlias,keyPwd:o,keyAlg:e?.keyAlg??tt.keyAlg,keySize:e?.keySize??tt.keySize,keystoreFile:s,keystorePwd:o}),await YR(s),console.log("Start generating csr"),await WR({subject:t?.subject??tt.csrSubject,outFile:a,keyAlias:t?.keyAlias??tt.keyAlias,keyPwd:o,signAlg:t?.signAlg??tt.signAlg,keystoreFile:s,keystorePwd:o}),{p12FilePath:s,csrFilePath:a,keyPwd:o,keyAlias:e?.keyAlias??tt.keyAlias}}var XR=["p12","cer","csr","p7b"];async function nd(n,e){for(let t of XR){let r=await pe(n,e,t);await JR.rm(r,{force:!0})}}function rd(n){let e;try{e=KR(n,"utf-8")}catch{throw new Error(v.ERR_CERT_INVALIDATE)}if(!Se.CERT_PATTERN.test(e))throw new Error(v.ERR_CERT_INVALIDATE)}async function Mg(n,e){return{certPath:await pe(n,e,"cer"),csrPath:await pe(n,e,"csr"),p12Path:await pe(n,e,"p12"),profilePath:await pe(n,e,"p7b")}}async function id(n,e){let t=e??"",r=U.discover(process.cwd()).rootDir;await nd(t,r);let i=Jl(n.teamId),o=await aa(n,i);if(o&&!await Xl(n,o.id))throw new Error(v.ERR_DOWNLOAD_CER);let s=await td(e),a;try{a=ZR(s.csrFilePath,"utf-8")}catch{throw new Error(v.ERR_READ_CSR)}console.log("Start generating certificate"),await Zl(n,a,i);let c=await aa(n,i);if(!c)throw new Error(v.ERR_DOWNLOAD_CER);let l=await Ql(n,c.certObjectId);if(!l)throw new Error(v.ERR_DOWNLOAD_CER);let p=await pe(t,r,"cer");await Hi(l,p),rd(p);let g=await pe(t,r,"p7b");return{p12FilePath:s.p12FilePath,csrFilePath:s.csrFilePath,cerFilePath:p,profileFilePath:g,certId:c.id,keyAlias:s.keyAlias,keyPwd:s.keyPwd,storePassword:s.keyPwd}}import wa from"crypto";import tn from"fs";import*as Kg from"path";import Sk from"json5";import{execa as qg}from"execa";import Yg from"node-forge";import{createCipheriv as QR,createDecipheriv as ek,pbkdf2Sync as tk,randomBytes as cd}from"crypto";import{promises as In}from"fs";import{dirname as nk,join as nt}from"path";var la=3,Bi=16,rk=1e4,_g="material",ik=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Hg="aes-128-gcm",Cn=12,da=16,Zt=4;function od(n){return new Uint8Array(cd(n))}function ok(n){return cd(n).toString("hex")}function sk(...n){if(n.length===0)return new Uint8Array(0);let e=n[0].length,t=new Uint8Array(e);for(let r=0;r<e;r++){let i=0;for(let o of n)i^=o[r];t[r]=i}return t}function Fg(n,e,t=rk,r=Bi){let i=[...n,ik],o=sk(...i),s=Buffer.from(o).toString("utf8"),a=Buffer.from(s,"utf8"),c=tk(a,e,t,r,"sha256");return new Uint8Array(c)}function jg(n,e){let t=cd(Cn),r=QR(Hg,n,t),i=Buffer.concat([r.update(e),r.final()]),o=r.getAuthTag(),s=Buffer.concat([i,o]),a=s.length,c=Buffer.alloc(Zt+Cn+s.length);return c.writeUInt32BE(a,0),t.copy(c,Zt),s.copy(c,Zt+Cn),c}function $g(n,e){if(e.length<Zt+Cn+da)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(Zt,Zt+Cn),i=e.subarray(Zt+Cn,Zt+Cn+t);if(i.length<da)throw new Error("Ciphertext too short for auth tag");let o=i.subarray(0,i.length-da),s=i.subarray(i.length-da),a=ek(Hg,n,r);return a.setAuthTag(s),Buffer.concat([a.update(o),a.final()])}async function ak(n){try{await In.rm(n,{recursive:!0,force:!0})}catch{}}async function sd(n){let e=await In.readdir(n),t=e.filter(r=>r!==".DS_Store");if(t.length!==1)throw new Error(`Expected exactly 1 file in ${n}, but found ${t.length} (filtered from ${e.length})`);return In.readFile(nt(n,t[0]))}async function ad(n,e){let t=ok(Bi),r=nt(n,t);return await In.writeFile(r,e),t}var Qt=class{static async generateMaterial(e){let t=nt(e,_g);await ak(t);let r=nt(t,"ac"),i=nt(t,"ce");await In.mkdir(r,{recursive:!0}),await In.mkdir(i,{recursive:!0});for(let p=0;p<la;p++)await In.mkdir(nt(t,"fd",String(p)),{recursive:!0});let o=od(Bi),s=[];for(let p=0;p<la;p++)s.push(od(Bi));let a=od(Bi),c=Fg(s,o),l=jg(c,a);await ad(r,o),await ad(i,l);for(let p=0;p<la;p++){let g=nt(t,"fd",String(p));await ad(g,s[p])}return a}static async readMaterial(e){let t=nt(e,_g),r=nt(t,"ac"),i=new Uint8Array(await sd(r)),o=[];for(let p=0;p<la;p++){let g=nt(t,"fd",String(p)),w=await sd(g);o.push(new Uint8Array(w))}let s=nt(t,"ce"),a=await sd(s),c=Fg(o,i),l=$g(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t=nk(e);try{return await this.readMaterial(t)}catch{return await this.generateMaterial(t)}}static async encryptedPassword(e,t){let r=await this.getStoreKey(t),i=Buffer.from(e,"utf8");return jg(r,i).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let r=await this.getStoreKey(t),i=Buffer.from(e,"hex");return $g(r,i).toString("utf8")}};import Vg from"fs";import ga from"path";import fk from"json5";import*as ua from"fs";import*as Ug from"path";function pa(n){let e=Ug.resolve(n);if(!ua.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=ua.readFileSync(e,"utf-8")}catch(s){throw new Error(`Failed to read SDK info file: ${e}`,{cause:s})}let r;try{r=JSON.parse(t)}catch(s){throw new Error(`Invalid JSON in SDK info file: ${e}`,{cause:s})}let i=r?.data?.apiVersion;if(i==null||i==="")throw new Error(`Missing data.apiVersion in SDK info file: ${e}`);let o=Number(i);if(!Number.isFinite(o))throw new Error(`Invalid data.apiVersion in SDK info file: ${String(i)}`);return o}import*as vr from"fs";import*as Ee from"path";import{debuglog as wr}from"util";var Bg={"acl.SYSTEM_FLOAT_WINDOW.instead.name":"PiPWindow","acl.READ_CONTACTS.instead.name":"contact.selectContacts","acl.READ_IMAGEVIDEO.instead.name":"PhotoViewPicker","acl.WRITE_IMAGEVIDEO.instead.name":"SaveButton","acl.READ_AUDIO.instead.name":"AudioViewPicker","acl.WRITE_AUDIO.instead.name":"AudioViewPicker","acl.READ_PASTEBOARD.instead.name":"PasteButton"};function ck(n){return Object.prototype.hasOwnProperty.call(Bg,n)}function fa(n){if(ck(n))return Bg[n]}var Wg={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as lk}from"url";var ha=class{permissionName;permissionDisplayName;minSupportApiLevel;permissionInsteadName;permissionHelpUrlKey;constructor(e={}){this.permissionName=e.permissionName??"",this.permissionDisplayName=e.permissionDisplayName??"",this.minSupportApiLevel=e.minSupportApiLevel??"",this.permissionInsteadName=e.permissionInsteadName,this.permissionHelpUrlKey=e.permissionHelpUrlKey}};function ma(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Gg(n){return n==null||n.length===0}function dk(n){return!Gg(n)}function ld(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function uk(n,e){let t=n[e];if(typeof t=="boolean")return t;if(typeof t=="number")return t!==0;if(typeof t=="string"){let r=t.trim().toLowerCase();return r==="true"||r==="1"}return!1}function pk(n,e){let t=n[e];if(typeof t=="number")return Math.trunc(t);if(typeof t=="string"){let r=Number.parseInt(t,10);return Number.isNaN(r)?0:r}return 0}var en=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=Ee.join("aclPermission","aclPermissionsInfo.json");static ACL_HAVE_INSTEAD_NAME=new Set(["ohos.permission.SYSTEM_FLOAT_WINDOW","ohos.permission.READ_CONTACTS","ohos.permission.READ_IMAGEVIDEO","ohos.permission.WRITE_IMAGEVIDEO","ohos.permission.READ_AUDIO","ohos.permission.WRITE_AUDIO","ohos.permission.READ_PASTEBOARD"]);static ACL_AVAILABLE_LEVEL_VALUE="system_basic";static ACL_AVAILABLE_TYPE_VALUE="NORMAL";static ACL_AVAILABLE_LEVEL_KEY="availableLevel";static ACL_AVAILABLE_TYPE_KEY="availableType";static ACL_PROVISION_ENABLE_KEY="provisionEnable";static ACL_NAME_KEY="name";static ACL_CONFIG_PREFIX="acl.";static ACL_INSTEAD_NAME_SUFFIX=".instead.name";static ACL_HELP_URL_KEY_SUFFIX=".help.key";static ACL_DEFINE_PERMISSION_KEY="definePermissions";static ACL_SINCE_KEY="since";static PERMISSION_DEFINITIONS_RELATIVE_PATH=Ee.join("lib","permissionDefinitions.json");static INCLUDE_ACL_PERMISSIONS=new Set(["ohos.permission.FILE_ACCESS_PERSIST","ohos.permission.READ_WRITE_DOWNLOAD_DIRECTORY","ohos.permission.READ_WRITE_DOCUMENTS_DIRECTORY"]);static EXCLUDE_ACL_PERMISSIONS=new Set(["ohos.permission.READ_DOCUMENT","ohos.permission.WRITE_DOCUMENT"]);static handleSpecificAclPermissions(){this.addAclWhiteList(this.INCLUDE_ACL_PERMISSIONS),this.addAclBlackList(this.EXCLUDE_ACL_PERMISSIONS)}static aclPermissionInfoMap=new Map;static aclPermissionNamesMap=new Map;static aclWhiteList=new Set;static aclBlackList=new Set;static builtInConfigTextLoader;static initAclPermission(e,t){let r=e.rootDir,i=this.getOrCreateSet(this.aclPermissionNamesMap,r),o=this.getOrCreateSet(this.aclPermissionInfoMap,r);i.clear(),o.clear();let s=Ee.join(t.sdkPath,"default","sdk-pkg.json"),a=pa(s);this.MIN_API_TO_FIND_ACL_IN_SDK-a>0?this.initAclPermissionFromBuiltInConfig(i,o):this.initAclPermissionFromSDK(t,i,o)}static getAclPermissionInfos(e){return this.aclPermissionInfoMap.get(e.rootDir)??new Set}static getAclPermissionNames(e){return this.aclPermissionNamesMap.get(e.rootDir)??new Set}static addAclWhiteList(e){for(let t of e)this.aclWhiteList.add(t)}static addAclBlackList(e){for(let t of e)this.aclBlackList.add(t)}static getOrCreateSet(e,t){let r=e.get(t);return r||(r=new Set,e.set(t,r)),r}static readBuiltInConfigText(){if(this.builtInConfigTextLoader)return this.builtInConfigTextLoader();let e=Ee.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(vr.existsSync(e))return vr.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=lk(e);if(t.includes("dist")){let s=Ee.dirname(t),a=Ee.dirname(s);return Ee.join(a,"src","resources")}let r=Ee.dirname(t),i=Ee.dirname(r),o=Ee.dirname(i);return Ee.join(o,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let r;try{r=this.readBuiltInConfigText()}catch{wr("read builtin acl permission failed.");return}if(r!==void 0)try{let i=JSON.parse(r),s=(Array.isArray(i)?i:ma(i)?Object.values(i):[]).filter(ma).map(a=>new ha(a));s.forEach(a=>{let c=a.permissionInsteadName;dk(c)&&(a.permissionInsteadName=fa(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(i){wr(`failed to parse aclPermissionsInfo.json: ${i}`)}}static initAclPermissionFromSDK(e,t,r){let i=this.parsePermissionDefinitionFile(e);i&&i.forEach(o=>{if(!ma(o))return;let s=o,a=ld(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(Gg(a)||(this.generateAclInfos(r,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||ld(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||ld(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:uk(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let i=new ha;i.permissionName=t;let o=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;i.permissionDisplayName=o;let s=pk(r,this.ACL_SINCE_KEY);i.minSupportApiLevel=String(s),this.handleInsteadName(i,o),e.add(i)}static parsePermissionDefinitionFile(e){let t=Ee.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!vr.existsSync(t))return;let r;try{r=vr.readFileSync(t,"utf-8")}catch(s){wr(`failed to load permissionDefinitions.json: ${s}`);return}let i;try{let s=JSON.parse(r);if(!ma(s)){wr("json object is null");return}i=s}catch(s){wr(`failed to parse permissionDefinitions.json: ${s}`);return}let o=i[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(o)){wr("definePermissions is not an array");return}return o}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=fa(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=fa(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function ya(n,e){let t=new Set,r=new Set;en.handleSpecificAclPermissions(),en.initAclPermission(n,e);for(let i of n.profile.modules){let o=zg(i,n,e,r,ga.join("src","main"));for(let a of o)t.add(a);let s=zg(i,n,e,r,ga.join("src","ohosTest"));for(let a of s)t.add(a)}return mk(r),t}function mk(n){if(n.size>0)throw new Error(Wg.DUPLICATE_PERMISSION)}function zg(n,e,t,r,i){let o=gk(e.rootDir,n,i);if(o==null)return new Set;let s=[];for(let w of o){if(typeof w!="object"||w===null)continue;let C=hk(w,"name");C&&s.push(C)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=ga.join(t.sdkPath,"default","sdk-pkg.json"),l=pa(c),p=en.getAclPermissionInfos(e),g=new Set(Array.from(p).filter(w=>{let C=Number(w.minSupportApiLevel);return Number.isFinite(C)&&C<=l}).map(w=>w.permissionName));for(let w of Array.from(a))g.has(w)||a.delete(w);return a}function hk(n,e){let t=n[e];return typeof t=="string"?t:""}function gk(n,e,t){let r=ga.join(n,e.srcPath,t,"module.json5"),i=yk(r);if(i==null)return null;let o=wk(i,"module");return o==null?null:vk(o,"requestPermissions")}function yk(n){try{if(!Vg.existsSync(n))return null;let e=Vg.readFileSync(n,"utf-8");return fk.parse(e)}catch{return null}}function wk(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return t!=null&&typeof t=="object"&&!Array.isArray(t)?t:null}function vk(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}var ud=class{verifyStorePassword(e,t){try{let r=tn.readFileSync(e),i=Yg.asn1.fromDer(r.toString("binary"));return Yg.pkcs12.pkcs12FromAsn1(i,t),!0}catch{return!1}}getLocalCerFingerprints(e){let r=tn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(r&&r.length>0)return r.map(i=>this.formatFp(new wa.X509Certificate(i).fingerprint256));try{return[this.formatFp(new wa.X509Certificate(tn.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let i=tn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let o of i)try{let s=new wa.X509Certificate(o);if(this.formatFp(s.fingerprint256)===t){let a=new Date(s.validTo);return isNaN(a.getTime())?null:a}}catch{}return null}formatFp(e){let t=e.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}};function Ek(n){let e=tn.readFileSync(n,"utf-8"),t=bk(e),r=null;if(t)try{r=JSON.parse(t)}catch{r=null}let i=r?.["bundle-info"]??{};return{rawContent:e,bundleNameInProfile:dd(i["bundle-name"]),expiryDate:Pk(r?.validity?.["not-after"]),cerFingerprintInProfile:Ck(dd(i["development-certificate"])),deviceUdidsInProfile:Ik(r?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:Ak(r?.acls?.["allowed-acls"]),teamIdInProfile:dd(i["developer-id"])}}function bk(n){let e=n.indexOf("{");if(e<0)return null;let t=0,r=-1,i=!1,o=!1;for(let s=e;s<n.length;s++){let a=n[s];if(i){o?o=!1:a==="\\"?o=!0:a==='"'&&(i=!1);continue}if(a==='"')i=!0;else if(a==="{")t++;else if(a==="}"&&(t--,t===0)){r=s;break}}return r<0?null:n.slice(e,r+1)}function Pk(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function Ck(n){if(!n)return null;try{let t=new wa.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function Ik(n){if(!Array.isArray(n))return[];let e=[];for(let t of n)if(typeof t=="string"){let r=t.toUpperCase();e.includes(r)||e.push(r)}return e}function Ak(n){if(!Array.isArray(n))return[];let e=[];for(let t of n)typeof t=="string"?e.push(t):t&&typeof t=="object"&&typeof t.name=="string"&&e.push(t.name);return[...new Set(e)].sort()}function dd(n){return typeof n=="string"?n:null}var Wi=class n{static async shouldRegenerate(e,t){let r=await n.#e(e,t);return n.#t(r)??n.#n(r)??n.#r(r)??n.#i(r)??n.#o(r)??n.#s(r)??n.#a(r)??n.#c(r)??n.#l(r)??n.#d(r)??await n.#u(r)??n.#p()}static async#e(e,t){let r=e.force,i=e.teamId,o=e.productName??"default",s=U.discover(process.cwd()),a=s.rootDir,[c,l]=await Promise.all([Dk(o,a),kk(t.hdcPath)]),p=null;if(Jg(c).allExist)try{p=Ek(c.profileFile)}catch{}return{force:r,teamId:i,productName:o,projectPath:a,materialPaths:c,bundleName:s.getBundleName(),deviceUdids:l,storePassword:await Rk(a,o,c.storeFile),localAclPermissions:[...ya(s,t)].sort(),hapSignTool:new ud,profileInfo:p}}static#t(e){return e.force?(m("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:Te({force:!0})}):null}static#n(e){let t=Jg(e.materialPaths);return t.allExist?null:(m(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:Te({allFilesExist:!1,missingFiles:t.missing})})}static#r(e){return(e.profileInfo?.rawContent??"").trim().length>0?null:(m("[reGenerateSign] profile content is empty"),{shouldRegenerate:!0,reason:"Profile file content is empty",checkDetails:Te({allFilesExist:!0,profileContentNotEmpty:!1})})}static#i(e){let t=e.profileInfo?.expiryDate;return!t||t>=new Date?null:(m(`[reGenerateSign] profile expired at ${t.toISOString()}`),{shouldRegenerate:!0,reason:`Profile expired at ${t.toISOString()}`,checkDetails:Te({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!1})})}static#o(e){let t=e.profileInfo?.bundleNameInProfile;return t&&t===e.bundleName?null:(m(`[reGenerateSign] bundleName mismatch \u2014 current=${e.bundleName}, profile=${t}`),{shouldRegenerate:!0,reason:`bundleName mismatch: current=${e.bundleName}, in profile=${t}`,checkDetails:Te({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!1})})}static#s(e){let t=e.profileInfo?.teamIdInProfile;return t&&t===e.teamId?null:(m(`[reGenerateSign] teamId mismatch \u2014 current=${e.teamId}, profile=${t}`),{shouldRegenerate:!0,reason:`teamId mismatch: current=${e.teamId}, in profile=${t}`,checkDetails:Te({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=xk(e.profileInfo?.deviceUdidsInProfile??[],e.deviceUdids);return t.allPresent?null:(m(`[reGenerateSign] missing device UDIDs: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Device UDID(s) not in profile: ${t.missing.join(", ")}`,checkDetails:Te({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return Lk(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(m("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:Te({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!1})})}static#l(e){let t=e.hapSignTool.getLocalCerFingerprints(e.materialPaths.cerFile),r=e.profileInfo?.cerFingerprintInProfile;return r&&t.includes(r)?null:(m("[reGenerateSign] certificate mismatch"),{shouldRegenerate:!0,reason:"Certificate mismatch between profile and local .cer file",checkDetails:Te({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!1})})}static#d(e){let t=e.profileInfo?.cerFingerprintInProfile,r=e.hapSignTool.getLocalCerExpiry(e.materialPaths.cerFile,t);return!r||r>=new Date?null:(m(`[reGenerateSign] local certificate expired at ${r.toISOString()}`),{shouldRegenerate:!0,reason:`Local certificate expired at ${r.toISOString()}`,checkDetails:Te({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!1})})}static async#u(e){return e.storePassword?e.hapSignTool.verifyStorePassword(e.materialPaths.storeFile,e.storePassword)?null:(m("[reGenerateSign] keystore password verification failed"),{shouldRegenerate:!0,reason:"Keystore password verification failed (storeFile may be corrupted or password changed)",checkDetails:Te({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})}):(m("[reGenerateSign] no stored keystore password"),{shouldRegenerate:!0,reason:"No stored keystore password available for verification",checkDetails:Te({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})})}static#p(){return m("[reGenerateSign] all checks passed \u2014 skip regeneration"),{shouldRegenerate:!1,reason:"",checkDetails:Te({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function Dk(n,e){let[t,r,i,o]=await Promise.all([pe(n,e,"p12"),pe(n,e,"csr"),pe(n,e,"cer"),pe(n,e,"p7b")]);return{storeFile:t,csrFile:r,cerFile:i,profileFile:o}}async function Rk(n,e,t){let r=Kg.join(n,"build-profile.json5");if(!tn.existsSync(r))return;let i;try{i=Sk.parse(tn.readFileSync(r,"utf-8"))}catch{return}let a=(i?.app?.signingConfigs??[]).find(c=>c.name===e)?.material?.storePassword;if(a)try{return await Qt.decryptPassword(a,t)}catch{return}}async function kk(n){m(`Executing: ${n} list targets`);let{stdout:e}=await qg(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
1381
+ `)){let o=i.trim();if(!o||o.startsWith("[Empty]"))continue;let s=o.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let r=[];for(let i of t)try{m(`Executing: ${n} -t ${i} shell bm get -u`);let{stdout:o}=await qg(n,["-t",i,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),s=Tk(o);s&&r.push(s)}catch{m(`[reGenerateSign] Failed to get UDID for ${i}, skipping`)}return r}function Tk(n){let e=n.trim();if(!e)return null;let t=e.split(`
1382
+ `);for(let i=0;i<t.length-1;i++)if(t[i].includes("udid of current device is")){let s=t[i+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(s)return s[0].toUpperCase()}let r=e.match(/[A-Fa-f0-9]{64}/);return r?r[0].toUpperCase():null}function Jg(n){let e=[n.storeFile,n.csrFile,n.cerFile,n.profileFile],t=[];for(let r of e)tn.existsSync(r)||t.push(r);return{allExist:t.length===0,missing:t}}function xk(n,e){let t=[];for(let r of e)n.includes(r)||t.push(r);return{allPresent:t.length===0,missing:t}}function Lk(n,e){let t=[...n].sort(),r=[...e].sort();return t.length!==r.length?!1:t.every((i,o)=>i===r[o])}function Te(n){let e={force:!1,allFilesExist:!1,missingFiles:[],profileContentNotEmpty:!1,profileNotExpired:!1,bundleNameMatched:!1,teamIdMatched:!1,allDevicesInProfile:!1,missingDeviceUdids:[],aclMatched:!1,cerMatched:!1,cerNotExpired:!1,storePasswordValid:!1};return n.force?{...e,force:!0}:{...e,...n,force:!1}}import{debuglog as pd}from"util";import{execa as fd}from"execa";async function Zg(n,e){let t=await va(n);if(!t)throw new Error(v.DEVICE_LIST_EMPTY);let r=await Mk(e);if(t.length===0)for(let s of r)await Nk(n,s.udid,s.deviceName);else for(let s of r)await Ok(n,t,s.udid,s.deviceName);let o=(await va(n)).map(s=>s.id);if(o.length===0)throw new Error(v.DEVICE_LIST_EMPTY);return o}async function Nk(n,e,t){await ty(n,e,Qg(t))}async function Ok(n,e,t,r){for(let i=0;i<e.length;i++){if(t===e[i].udid)return;if(i===e.length-1){await ty(n,t,Qg(r));return}}}function Qg(n){switch(n){case"liteWearable":return"1";case"wearable":return"2";case"tv":return"3";default:return"4"}}async function Xg(n,e=1,t=100){let r=`${q.BASE_URL}${q.DEVICE_LIST_PATH}?encodeFlag=0&start=${e}&pageSize=${t}`,i=ny(n),o=await L.get(r,{headers:i});if(!o)throw pd("query devices failed: response is null"),new Error(v.ERROR_WHILE_ADD_DEVICE);if(o.statusCode!==200)throw ey(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.list)throw pd("query devices failed: response list is null"),new Error(s.ret?.msg||v.ERROR_WHILE_ADD_DEVICE);return{deviceList:s.list,total:s.totalCount||0}}function ey(n,e,t){return n===et.FORBIDDEN?e===ce.OPENPROXY_BLOCKED_URL?new Error(v.ERR_CERT_NETWORK_ERROR):new Error(v.ERR_FORBIDDEN):n===et.UNAUTHORIZED?new Error(v.ERR_UNAUTHORIZED):t.includes(ce.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(v.DEVICE_LIMIT_REACHED):new Error(v.ERROR_WHILE_ADD_DEVICE)}async function va(n){let t=await Xg(n,1,100);if(!t||!t.deviceList||t.deviceList.length===0)return[];let r=[...t.deviceList],i=t.total,o=Math.floor(i/100)+(i%100===0?0:1);for(let s=2;s<=o;s++){let a=await Xg(n,s,100);if(!a||!a.deviceList||a.deviceList.length===0)break;r.push(...a.deviceList)}return r}async function ty(n,e,t){let r=`${q.BASE_URL}${q.DEVICE_ADD_PATH}`,i=ny(n),s={deviceName:`auto_sign_device_No.${Math.floor(Math.random()*3e3)}${Date.now()}`,udid:e,deviceType:t},a=await L.postAllowFailure(r,{headers:i,params:s});if(!a)throw pd("add device failed: response is null"),new Error(v.ERROR_WHILE_ADD_DEVICE);if(a.statusCode!==200)throw ey(a.statusCode,a.statusText,a.data);let c=a.data,l=JSON.parse(a.data);if(!l||!l.ret||l.ret.code!==0)throw c.includes(ce.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(v.DEVICE_LIMIT_REACHED):c.includes(ce.DEVICE_NAME_REPEAT_CODE)?new Error(v.DEVICE_NAME_REPEAT):new Error(v.ERROR_WHILE_ADD_DEVICE)}function ny(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}async function Mk(n){let{stdout:e}=await fd(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
1383
+ `)){let o=i.trim();if(!o||o.startsWith("[Empty]"))continue;let s=o.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let r=[];for(let i of t)try{let o=await _k(i,n),s=await Fk(i,n);o.length>0&&r.push({id:"",udid:o,deviceName:s})}catch{m(`Failed to get device info for ${i}, skipping`)}return r}async function _k(n,e){let{stdout:t}=await fd(e,["-t",n,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),r=t.trim();if(!r)return"";let i=r.split(`
1384
+ `);for(let s=0;s<i.length-1;s++)if(i[s].includes("udid of current device is")){let c=i[s+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(c)return c[0].toUpperCase()}let o=r.match(/[A-Fa-f0-9]{64}/);return o?o[0].toUpperCase():""}async function Fk(n,e){let{stdout:t}=await fd(e,["-c","-t",n,"shell","getprop","hw_sc.build.os.deviceType"],{stdio:["ignore","pipe","pipe"]});return jk(t)}function jk(n){let e=n.trim();return!e||e.includes("inaccessible")?"phone":n.includes("liteWearable")?"liteWearable":n.includes("wearable")?"wearable":n.includes("tv")?"tv":"phone"}import An from"fs";import{createHash as $k}from"crypto";import{debuglog as Ct}from"util";import{Buffer as iy}from"buffer";import{createPublicKey as Hk,X509Certificate as md}from"crypto";import{readFileSync as Uk}from"fs";import Dn from"node-forge";async function oy(n,e){console.log("Start generating profile");let{productName:t,bundleName:r,projectPath:i,aclPermissionList:o,allDeviceIds:s,certIds:a,keyAlias:c,keyPwd:l}=e;if(s==null||s.length===0)throw new Error(v.DEVICE_LIST_EMPTY);let p=`${q.BASE_URL}${q.PROVISION_ADD_TEST_PATH}`,g=Bk(t,r),w=await Gk(n,p,a||[],r,s,g,o||[]);if(!w||!w.profileInfo||!w.profileInfo.provisionFileUrl)throw Ct("add provision failed, the provision file url is null"),new Error(v.ADD_PROFILE_FAIL);let C=w.profileInfo,fe=(await Yk(n,C.provisionFileUrl)).urlList,It=w.profileInfo.id;if(fe&&fe.length>0){let At=await Mg(t,i),Sr=At.profilePath;if(!await Jk(fe,Sr))throw await ry(n,It),new Error(v.ERROR_WHILE_DOWNLOAD_PROFILE);if(await ry(n,It),An.existsSync(At.certPath)&&An.existsSync(Sr)&&An.existsSync(At.p12Path)){let hy=An.readFileSync(At.certPath,"utf8"),gy=An.readFileSync(Sr,"utf8");return Kk(gy,hy,At.p12Path,c,l)||qk(Sr),Sr}}throw new Error(v.ADD_PROFILE_FAIL)}function Bk(n,e){let t=n?`${n}_`:"";return`${Wk(`${t}${e}_${e}`)}`}function Wk(n){return $k("sha256").update(n).digest("hex").substring(0,16)}async function Gk(n,e,t,r,i,o,s){Vk(r);let a=gd(n),c={certList:t,packageName:r,deviceList:i,provisionName:o};s.length&&(c.aclPermissionList=s);let l=await L.postAllowFailure(e,{headers:a,params:c});if(!l)throw Ct("add provision failed: response is null"),new Error(v.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw hd(l.statusCode,l.statusText,l.data);let p=JSON.parse(l.data);if(!p||!p.ret||p.ret.code!==0)throw Ct(`add provision fail: ${l.data}`),zk(l.data,o),new Error(p.ret?.msg||v.ADD_PROFILE_FAIL);let g=p.provisionFileUrl;return{profileInfo:{id:p.id,name:o,provisionFileUrl:g}}}function hd(n,e,t){return n===et.FORBIDDEN?e===ce.OPENPROXY_BLOCKED_URL?new Error(v.ERR_CERT_NETWORK_ERROR):new Error(v.ERR_FORBIDDEN):n===et.UNAUTHORIZED?new Error(v.ERR_UNAUTHORIZED):t.includes(ce.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(v.TEST_PROVISION_EXCEEDS_LIMIT):new Error(v.ADD_PROFILE_FAIL)}function Vk(n){if(!n||n.trim().length===0)throw new Error(v.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!Se.BUNDLE_NAME_REGEX.test(n))throw new Error(v.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function zk(n,e){if(n.includes(ce.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(v.TEST_PROVISION_EXCEEDS_LIMIT);if(n.includes(ce.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(v.PROFILE_NAME_REPEAT)}async function ry(n,e){if(!e||e.trim().length===0)return;let t=`${q.BASE_URL}${q.PROVISION_DELETE_PATH}?id=${e}`,r=await L.deleteAllowFailure(t,{headers:gd(n)});if(r.statusCode!==200)throw hd(r.statusCode,r.statusText,r.data);let i=JSON.parse(r.data);(!i||!i.ret||i.ret.code!==0)&&Ct(`delete provision failed: ${r.data}`)}function qk(...n){for(let e of n)try{An.existsSync(e)&&An.unlinkSync(e)}catch(t){Ct(`delete local sign file error: ${t.message}`)}}async function Yk(n,e){let t=`${q.BASE_URL}${q.CERT_DOWNLOAD_URL_PATH}`,r=gd(n),i={sourceUrls:e},o=await L.postAllowFailure(t,{headers:r,params:i});if(!o)throw Ct("get download list failed: response is null"),new Error(v.ADD_PROFILE_FAIL);if(o.statusCode!==200)throw hd(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw Ct("download: The application does not exist"),new Error(s.ret?.msg||v.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function Jk(n,e){if(!n||n.length===0)return!1;let t=n[0].newUrl;return await Hi(t,e),!0}function Kk(n,e,t,r,i){return Xk(n,e),r=r||Se.TARGET_FRIENDLY_NAME,i=i||"",Zk(e,t,r,i),!0}function Xk(n,e){if(e.lastIndexOf(Se.CERT_BEGIN_HEADER)<0)throw new Error(v.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(Se.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!n.includes(t))throw new Error(v.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}function Zk(n,e,t,r){let i=n.matchAll(Se.CERTIFICATE_PATTERN_GLOBAL),o=[],s=new Date;for(let c of i)try{let l=c[0],p=Qk(l),g=new Date(p.validFrom),w=new Date(p.validTo);if(s<g||s>w){let C=`Certificate is not valid, Valid from ${g} to ${w}`;throw console.warn(`checkCertificateInValidityPeriod: ${C}`),new Error(v.CERTIFICATE_HAS_EXPIRED)}o.push(p)}catch(l){throw console.warn(`checkCertificateInValidityPeriod\uFF1A ${l.message}`),new Error(v.CERTIFICATE_HAS_EXPIRED,{cause:l})}if(!o||o.length===0)throw new Error(v.CERTIFICATE_HAS_EXPIRED);if(!tT(e,t,r,o))throw new Error(v.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function Qk(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new md(t);let r=iy.from(t,"base64");return new md(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}function eT(n){if(n.cert){let e=Dn.pki.publicKeyToPem(n.cert.publicKey);return Hk(e).export({type:"spki",format:"der"})}if(n.asn1)try{let e=Dn.asn1.toDer(n.asn1).getBytes(),t=iy.from(e,"binary");return new md(t).publicKey.export({type:"spki",format:"der"})}catch(e){return Ct(`Failed to parse cert from asn1: ${e}`),null}return null}function tT(n,e,t,r){try{let i=Uk(n),o=Dn.asn1.fromDer(Dn.util.createBuffer(i)),c=Dn.pkcs12.pkcs12FromAsn1(o,t).getBags({bagType:Dn.pki.oids.certBag})[Dn.pki.oids.certBag]||[];for(let l of c){let p=l.attributes?.friendlyName?.[0];if(!p||p.toLowerCase()!==e.toLowerCase())continue;let g=eT(l);if(!g)continue;if(r.some(C=>{let _=C.publicKey.export({type:"spki",format:"der"});return g.equals(_)}))return!0}return!1}catch(i){let o=i instanceof Error?i.message:String(i);return Ct(`Failed to process P12 file: ${n}, error: ${o}`),!1}}function gd(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var ay="https://developer.huawei.com",nT={"ohos.permission.SYSTEM_FLOAT_WINDOW":"/consumer/cn/doc/harmonyos-guides/window-pipwindow","ohos.permission.READ_CONTACTS":"/consumer/cn/doc/harmonyos-references/js-apis-contact#contactselectcontacts10","ohos.permission.READ_IMAGEVIDEO":"/consumer/cn/doc/harmonyos-guides/select-user-file#%E9%80%89%E6%8B%A9%E5%9B%BE%E7%89%87%E6%88%96%E8%A7%86%E9%A2%91%E7%B1%BB%E6%96%87%E4%BB%B6","ohos.permission.WRITE_IMAGEVIDEO":"/consumer/cn/doc/harmonyos-guides/savebutton","ohos.permission.READ_AUDIO":"/consumer/cn/doc/harmonyos-guides/select-user-file#%E9%80%89%E6%8B%A9%E9%9F%B3%E9%A2%91%E7%B1%BB%E6%96%87%E4%BB%B6","ohos.permission.WRITE_AUDIO":"/consumer/cn/doc/harmonyos-guides/save-user-file#%E4%BF%9D%E5%AD%98%E9%9F%B3%E9%A2%91%E7%B1%BB%E6%96%87%E4%BB%B6","ohos.permission.READ_PASTEBOARD":"/consumer/cn/doc/harmonyos-guides/pastebutton"},rT="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function iT(n){let e=nT[n];return e?`${ay}${e}`:void 0}function oT(){return`${ay}${rT}`}var sT={"acl.can.apply.text":"Permission Application Scenarios","acl.permissions.warn":"Note: You are applying for restricted ACL permissions: {0} These permissions are subject to review together with your app release. For a faster review process, apply for the following permissions instead, if they are sufficient for your purposes: {1} {2}"};function sy(n,e){return(sT[n]??n).replace(/\{(\d+)\}/g,(r,i)=>String(e[Number(i)]??""))}function aT(n){return Array.from(n).join(", ")}function cy(n,e){if(n.size===0)return;let t=en.getAclPermissionInfos(e),r=new Set;for(let g of t)n.has(g.permissionName)&&r.add(g);for(let g of r){let w=iT(g.permissionName);w!=null&&(g.permissionHelpUrlKey=w)}let i=new Set;for(let g of r)i.add(g.permissionDisplayName);let o=new Set;for(let g of r)if(g.permissionHelpUrlKey!=null){let w=g.permissionInsteadName??g.permissionDisplayName;o.add(`${w} (${g.permissionHelpUrlKey})`)}let s=oT(),a=sy("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=o.size>0?Array.from(o).join(", ")+".":"",p=sy("acl.permissions.warn",[aT(i),l,c]);console.log(p)}var Sa=class{_project=null;get project(){if(!this._project)throw new Error("Project not initialized. Call checkProjectDir first.");return this._project}checkProjectDir(e){try{return this._project=U.discover(process.cwd()),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Project.discover() failed: ${t.message}`),e(J.PROJECT_DIR_MISSING)}}checkProduct(e,t){try{return this._project.validateProduct(e),{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Product validation failed: ${r.message}`),t(`Product "${e}" not found.Check the product property in the build-profile.json5 file.`)}}checkBundleName(e,t){try{return this._project.getBundleName(),{passed:!0,message:""}}catch(r){return m(`[EnvCheck] BundleName check failed: ${r.message}`),t(`bundleName was not found under product "${e}".Check the bundleName configuration.`)}}checkAtomicService(){return this._project.isAtomicService()?{passed:!1,message:J.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import cT from"fs";import ly from"path";var Ea=class{constructor(e){this.toolProvider=e}toolProvider;checkJava(e){try{return this.toolProvider.assertJava(),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Java check failed: ${t.message}`),e(`${t.message}`)}}checkHapSignTools(e){let t=this.toolProvider.sdkPath,r=ly.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");if(!cT.existsSync(r)){let i=ly.join("sdk","default","openharmony","toolchains","lib","hap_sign_tools.jar");return e(`hap_sign_tools.jar not found.Check whether ${i} exists.`)}return{passed:!0,message:""}}};var ba=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await ee.getUserInfo()}catch(e){return m(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await ee.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(J.LOGIN_REQUIRED)}catch(t){return m(`[EnvCheck] Login check failed: ${t.message}`),e(J.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(J.TEAM_INFO_FAILED);try{if((await Mt()).teamList.length>0)return{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Team API error: ${r.message}`),e(J.TEAM_INFO_FAILED)}return m("[EnvCheck] No teams found for current user"),e(J.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(J.REALNAME_REQUIRED):t.isRealName!==!0?(m("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(J.REALNAME_REQUIRED)):{passed:!0,message:""}:e(J.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let r=e??"";try{let i=await Mt();if(r=e??(i.teamList.length>0?i.teamList[0].id:t.userId)??"",!i.teamList.some(s=>s.id===r)){let s=`team-id for ${r} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`;return m(`[EnvCheck] ${s}`),{passed:!1,message:s}}return{passed:!0,message:""}}catch(i){return m(`[EnvCheck] Team ID check failed: ${i.message}`),{passed:!1,message:`team-id for ${r} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`}}}async checkRegion(e){let t=await this.ensureUserInfo();return t?t.countryCode?t.countryCode!=="CN"?e(J.REGION_CHINA_ONLY):{passed:!0,message:""}:(m("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(J.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function lT(n){try{let{teamList:e}=await Mt();if(e.length>0)return e[0].id}catch(e){m(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function dT(n){let e=await ee.getUserInfo(),t=await ee.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await lT(e.userId);if(!r)throw new Error("No team found");let i={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await va(i)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var Pa=class{constructor(e){this.toolProvider=e}toolProvider;async checkDevice(e,t){try{let r=await dT(t);if(r.length>0)return m(`[EnvCheck] Scenario 4 Device check: ${r.length} device(s) found in AGC cloud, skipping local device check`),{passed:!0,message:""};m("[EnvCheck] Scenario 4 Device check: no cloud devices found, falling back to local hdc");let o=await Z.from(this.toolProvider).listDevices();return o.length===0?(m("[EnvCheck] Scenario 4 Device check: no local devices found"),e(J.DEVICE_MISSING)):o.some(a=>dn(a.serial))?{passed:!0,message:""}:(m("[EnvCheck] Scenario 4 Device check: local device found but not an emulator"),e(J.DEVICE_MISSING))}catch(r){return m(`[EnvCheck] Scenario 4 Device check failed: ${r.message}`),e(J.DEVICE_DETECT_FAILED)}}};var Ca=class{projectChecker=new Sa;toolchainChecker=null;authChecker=new ba;deviceChecker=null;constructor(){}async preflight(e){let t=r=>this.blockingFail(r);return!(!await this.runAuthChain(e,t)||!await this.initToolchain()||!await this.runDeviceCheck(e,t)||!await this.runProjectChecks(e,t)||!await this.runAuxChecks(e))}async runAuthChain(e,t){let r=o=>(o.passed||this.fail(o),!0),i=[()=>this.authChecker.checkLogin(t),()=>this.authChecker.checkTeamInfo(t),()=>this.authChecker.checkRealname(t)];for(let o of i)if(!r(await o()))return!1;return!(e.teamId&&!r(await this.authChecker.checkTeamId(e.teamId)))}async initToolchain(){try{let e=await I.new();return this.toolchainChecker=new Ea(e),this.deviceChecker=new Pa(e),!0}catch(e){throw m(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(J.TOOLCHAIN_INIT_FAILED,{cause:e})}}async runDeviceCheck(e,t){return(i=>i.passed?!0:(this.fail(i),!1))(await this.deviceChecker.checkDevice(t,e.teamId))}async runProjectChecks(e,t){let r=o=>o.passed?!0:(this.fail(o),!1);if(!r(this.projectChecker.checkProjectDir(t))||!r(this.projectChecker.checkAtomicService()))return!1;let i=[()=>this.projectChecker.checkProduct(e.productName,t),()=>this.projectChecker.checkBundleName(e.productName,t),()=>this.toolchainChecker.checkJava(t),()=>this.toolchainChecker.checkHapSignTools(t)];for(let o of i)if(!r(o()))return!1;return!0}async runAuxChecks(e){let t=r=>r.passed?!0:(this.fail(r),!1);return!e.teamId&&!t(await this.authChecker.checkTeamId(e.teamId))?!1:(await this.authChecker.checkRegion(r=>this.blockingFail(r)),!0)}blockingFail(e){return{passed:!1,message:e}}fail(e){throw m(`[EnvCheck] FAIL: ${e.message}`),new Error(e.message)}};function fT(n){if(wd.existsSync(n)){let e=wd.readFileSync(n,"utf-8");return uy.parse(e)}return{app:{signingConfigs:[],products:[]}}}function mT(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function hT(n){if(n.keyPwd===n.storePassword){let r=await Qt.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await Qt.encryptedPassword(n.keyPwd,n.p12FilePath),t=await Qt.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function gT(n,e,t){let r=dy.join(n,"build-profile.json5"),i=fT(r);mT(i);let o=t??"default",{keyPassword:s,storePassword:a}=await hT(e),c={name:o,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:s,profile:e.profileFilePath,signAlg:tt.signAlg,storeFile:e.p12FilePath,storePassword:a}},l=i.app?.signingConfigs?.findIndex(g=>g.name===o);l!==void 0&&l>=0?i.app.signingConfigs[l]=c:i.app.signingConfigs.push(c);let p=i.app?.products?.findIndex(g=>g.name===o);p!==void 0&&p>=0?i.app.products[p].signingConfig=o:i.app.products.push({name:o,signingConfig:o}),wd.writeFileSync(r,uy.stringify(i,null,2),"utf-8")}async function yT(n){let e=await ee.getUserInfo(),t=await ee.refreshToken();if(!e||!t)throw new Error("Failed to obtain login credentials. Run `devecocli auth login` again.");return{uid:e.userId??"",teamId:n.teamId??e.userId??"",accessToken:t.accessToken??""}}async function wT(n){let e=n.product||"default";await new Ca().preflight({productName:e,teamId:n.teamId}),console.log("Executing signature generate command");let r=await yT(n),i=await I.new(),{shouldRegenerate:o}=await Wi.shouldRegenerate({force:n.force??!1,teamId:r.teamId,productName:n.product},i);if(!o){console.log(yd("Signature generation completed successfully."));return}await vT(n,r,i),console.log(yd("Signature generation completed successfully."))}async function vT(n,e,t){let r=await id(e,n.product),i=ST(n,e,r,t);i.allDeviceIds=await Zg(e,t.hdcPath),await oy(e,i);let o=U.discover(process.cwd()).rootDir;await gT(o,r,n.product??"default"),console.log(yd(`Signing config written to ${dy.join(o,"build-profile.json5")}`))}function ST(n,e,t,r){let i=process.cwd(),o=U.discover(i),s=ya(o,r);return cy(s,o),{productName:n.product||"default",bundleName:o.getBundleName(),projectPath:o.rootDir,teamId:e.teamId,force:n.force||!1,aclPermissionList:[...s],certIds:[t.certId],keyAlias:t.keyAlias,keyPwd:t.keyPwd}}var py=new uT("signature").description("Generate application signature.");py.command("generate").description("Automatically generate signing materials and write them to the project configuration.").option("--force","Force overwrite existing local signing materials.").option("--team-id <team-id>","Specify the team ID to use.").option("--product <product>","Specify the product. The default value is default.").action(async n=>{try{await wT(n)}catch(e){console.error(pT(e.message)),process.exit(1)}});var fy=py;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";ET();K.name("devecocli").description("HarmonyOS application development command line tool").version("1.3.0-Test.10");K.addCommand(iu);K.addCommand(Eu);K.addCommand(ku);K.addCommand(Uu);K.addCommand(mp);K.addCommand(Fp);K.addCommand(df);K.addCommand(mf);K.addCommand(If);K.addCommand(Nf);K.addCommand(Zf);K.addCommand(Dh);K.addCommand(Xh);K.addCommand(Dg);K.addCommand(fy);var vd=process.argv.slice(2);vd.length>=2&&vd[vd.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);function PT(n){let e=n;for(;e.parent&&e.parent!==K;)e=e.parent;return e}var CT=new Set(["update","auth","serve"]);K.hook("preAction",async(n,e)=>{let t=PT(e),r=_n();if(t.name()==="update")return;let i=new Nt(my.join(Ye(),"update")),o=Lt();if(r==="off"&&i.getBlockedVersions().includes(o))throw new Error(`devecocli ${o} has been disabled, run \`devecocli update\` to upgrade`);process.env.DEVECO_CLI_SKIP_VERSION_CHECK||CT.has(t.name())||await I.checkVersion()});K.hook("postAction",async(n,e)=>{if(process.exitCode||_n()!=="off")return;await new Or(e).checkAndNotify()});K.parseAsync(process.argv).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(bT(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});