@deveco-test/deveco-cli 1.3.0-Test.8 → 1.3.0-Test.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,53 +1,53 @@
1
1
  #!/usr/bin/env node
2
- var uw=Object.defineProperty;var pw=(n,e)=>{for(var t in e)uw(n,t,{get:e[t],enumerable:!0})};import{bootstrap as lL}from"global-agent";import{program as ee}from"commander";import{red as dL}from"colorette";import{Command as gv}from"commander";import{green as Za,red as Qa,yellow as ec}from"colorette";import Z from"fs";import*as te from"path";import Nt from"json5";import*as ja from"fs";import*as ie from"path";function m(n){process.env.DEVECO_CLI_DEBUG&&console.log(`[DEBUG] ${n}`)}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 assertRelativeTimeRange(e,t){if(e!==void 0&&t!==void 0&&e<t)throw new Error("--from must be greater than or equal to --to when both are provided (e.g. --from 30s --to 10s)")}static filterLogsByRelativeWindow(e,t,r,i=new Date){if(!t&&!r)return e;let[o,s]=n.resolveTimeBounds(t,r,i),a=e.split(/\r?\n/),c=[],l=!1;for(let d of a){let h=n.extractTimestampFromLogLine(d,i);h&&(l=n.isWithinBounds(h,o,s)),l&&c.push(d)}return c.join(`
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),d=r[6]??"0",h=Number.parseInt(d.padEnd(3,"0").slice(0,3),10),w=new Date(i,o,s,a,c,l,h);return w.getTime()>t.getTime()+1440*60*1e3&&w.setFullYear(i-1),w}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static 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(ie.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=ie.resolve(ie.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=ie.normalize(e),i=ie.relative(r,t);if(i.split(ie.sep)[0]===".."||ie.isAbsolute(i))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||ie.isAbsolute(e)}static isPathContained(e,t){let r=ie.resolve(t,e),i=ie.relative(t,r);return n.isPathEscaping(i)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){if(ie.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=ja.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let o=ie.resolve(i,e),s;try{s=ja.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=te.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=te.join(e,"build-profile.json5");if(!Z.existsSync(t))return null;try{let r=Z.readFileSync(t,"utf-8"),i=Nt.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=te.join(r,"src","main","module.json5");if(!Z.existsSync(i))return"entry";try{let o=Z.readFileSync(i,"utf-8");return Nt.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=te.join(r,"build-profile.json5");if(!Z.existsSync(i))throw new Error(`Build profile for module '${e}' not found at ${i}.`);let o=Z.readFileSync(i,"utf-8");return Nt.parse(o)}getBundleName(){let e=te.join(this.rootDir,"AppScope","app.json5");if(Z.existsSync(e))try{let t=Z.readFileSync(e,"utf-8"),r=Nt.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=te.join(this.rootDir,"AppScope","app.json5");if(!Z.existsSync(e))return!1;try{let t=Z.readFileSync(e,"utf-8");return Nt.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=te.join(i,"src","main","module.json5");if(!Z.existsSync(o))return"EntryAbility";try{let s=Z.readFileSync(o,"utf-8"),c=Nt.parse(s)?.module?.abilities||[];if(c.length===0)return"EntryAbility";let l=c.find(d=>d.name==="EntryAbility");return l?l.name:c[0].name}catch(s){return console.warn(`Warning: Failed to parse ${o}:`,s),"EntryAbility"}}validateProduct(e){if(!/^[\da-zA-Z_-]+$/.test(e))throw new 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=te.join(r,"oh-package.json5");if(!Z.existsSync(i))return[];let o=[];try{let s=Z.readFileSync(i,"utf-8"),c=Nt.parse(s)?.dependencies||{};for(let l of Object.values(c)){if(typeof l!="string")continue;let d=l;if(!(d.startsWith("file:")||d.startsWith(".")||d.startsWith("..")))continue;d.startsWith("file:")&&(d=d.substring(5));let w=te.join(t.srcPath,d),E=P.resolvePathWithinRoot(this.rootDir,w),N=this.profile.modules.find(he=>te.resolve(this.rootDir,he.srcPath)===E);N&&o.push(N.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(!Z.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,d=c;if(!l){let E=this.getSignedHapName(c,o.srcPath,i,t);E&&(d=E)}let h=s?"-signed.hsp":"-signed.hap";if(!r&&!d.endsWith(h))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,d]);if(!Z.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=te.isAbsolute(c)?c:this.buildOutputPath(i.srcPath,r,["outputs",t,c]);if(!Z.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 Z.existsSync(s)?o:null}buildOutputPath(e,t,r){let i=P.resolvePathWithinRoot(this.rootDir,e),o=te.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=Z.readFileSync(e,"utf-8"),i=Nt.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=te.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 Yd}from"child_process";import K from"fs";import*as Re from"os";import*as S from"path";import Ud from"fs";import*as io from"os";import*as ro from"path";import hw from"regedit";import{execFileSync as fw}from"child_process";import Fd from"fs";import*as jd from"os";import*as Ha from"path";function no(n,e){let t=Ha.join(n,"Contents","Info.plist");if(!Fd.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=fw(r,i,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(o&&!o.includes("Does Not Exist"))return o}catch{}}function mw(n){let e=no(n,"CFBundleShortVersionString");if(!e)return no(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[no(n,"CFBundleVersion"),no(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 Or(n){if(jd.platform()==="darwin")return mw(n);let e=Ha.join(n,"product-info.json");try{let t=JSON.parse(Fd.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}function Mr(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 gw(n){return n.filter(e=>{try{return Ud.statSync(e).isDirectory()}catch{return!1}})}function yw(){let n=[];for(let e of[ro.join(io.homedir(),"Applications"),"/Applications"])try{n.push(...Ud.readdirSync(e).filter(t=>t.endsWith(".app")&&t.toLowerCase().includes("deveco")).map(t=>ro.join(e,t)))}catch{}return n}function Hd(n){return new Promise((e,t)=>hw.list(n,(r,i)=>r?t(r):e(i)))}async function $d(n,e,t){let i=((await Hd([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(i.length===0)return[];let o=await Hd(i);return i.flatMap(s=>{let a=o[s]?.values?.[t]?.value;return a?[a]:[]})}async function ww(){let n=[ro.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 $d(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 $d(e,()=>!0,""))}catch{}return n}async function Bd(){let n=io.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"?yw():await ww(),t=gw(e).flatMap(r=>{let i=Or(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)=>Mr(i.version,r.version)>0?i:r)}import*as Wd from"fs";import*as ve from"path";function _r(n,e){let t=ve.relative(e,n);return t===""||!ve.isAbsolute(t)&&!t.startsWith(`..${ve.sep}`)&&t!==".."}function st(n){let e=ve.resolve(n),t=[],r=e;for(;;)try{let i=Wd.realpathSync(r);return t.length===0?i:ve.join(i,...t.reverse())}catch(i){if(i.code!=="ENOENT")throw i;let o=ve.dirname(r);if(o===r)return e;t.push(ve.basename(r)),r=o}}function oo(n,e){let t=st(e),r=st(n);return _r(r,t)?r:null}function so(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function ao(n){let e=so(n);if(!e)throw new Error("Path must not be empty.");return st(e)}var Fr={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},co={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 ge={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"},ze={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"},ln={ALGORITHM:"aes-256-gcm",KEY_LENGTH:32,IV_LENGTH:12,KEK_VERSIONS:["kek-v1","kek-v2","kek-v3"]},jr={baseUrl:ze.LOGIN_URL,authUrl:ze.AUTH_APPLY_PATH,tempTokenCheckUrl:ze.TEMP_TOKEN_CHECK_PATH,jwtTokenCheckUrl:ze.JWT_TOKEN_CHECK_PATH,successRedirectUrl:ze.LOGIN_SUCCESS_PATH,failedRedirectUrl:ze.LOGIN_FAILED_PATH,logoutUrl:ze.LOGOUT_PATH,agcTeamListUrl:ze.AGC_TEAM_LIST_URL,appId:ge.APP_ID,timeout:Fr.LOGIN_TIMEOUT_MS,countryCode:"CN"};var $a="https://matrix.openharmony.cn",Ve={TAGS_API_URL:`${$a}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${$a}/api/registry/skill/skills`,SKILL_API_BASE:`${$a}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},qe={"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 ft}from"os";import De from"path";var at="deveco-mcp";var Ot={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:De.join(ft(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:De.join(process.platform==="win32"?De.join(process.env.APPDATA??De.join(ft(),"AppData","Roaming"),"Trae CN","User"):De.join(ft(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:De.join(ft(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:De.join(ft(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:De.join(process.platform==="win32"?De.join(process.env.APPDATA??De.join(ft(),"AppData","Roaming"),"Qoder","SharedClientCache"):De.join(ft(),"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:De.join(ft(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:De.join(ft(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function zd(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function Gd(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function Vd(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function lo(n,e){return n.format==="opencode"?zd(e):n.format==="claude-code"||n.format==="codex"?Gd(e):Vd(e)}var Ye={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var qd="https://developer.huawei.com/consumer/cn/download/";var vw=/^#\s*Version:\s*(\S+)/,Sw="26.0.0.810";function Ew(n){try{let e=JSON.parse(K.readFileSync(n,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch{return}}function bw(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,d){this._sourceType=e;this._toolchainRoot=t;this._devecoStudioPath=r;this._nodePath=i;this._ohpmJsPath=o;this._hvigorJsPath=s;this._javaPath=a;this._sdkPath=c;this._hdcPath=l;this._emulatorPath=d}_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 Mr(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(Or(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(Mr(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
- ${qd}`)}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}
2
+ var kw=Object.defineProperty;var Rw=(n,e)=>{for(var t in e)kw(n,t,{get:e[t],enumerable:!0})};import{bootstrap as kL}from"global-agent";import*as Iw from"path";import{program as Z}from"commander";import{red as RL}from"colorette";import{Command as Mv}from"commander";import{green as uc,red as pc,yellow as fc}from"colorette";import X from"fs";import*as ee from"path";import Lt from"json5";import*as qa from"fs";import*as re from"path";function m(n){if(process.env.DEVECO_CLI_DEBUG){let e=typeof n=="function"?n():n;console.log(`[DEBUG] ${e}`)}}var C=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(re.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=re.resolve(re.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=re.normalize(e),i=re.relative(r,t);if(i.split(re.sep)[0]===".."||re.isAbsolute(i))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||re.isAbsolute(e)}static isPathContained(e,t){let r=re.resolve(t,e),i=re.relative(t,r);return n.isPathEscaping(i)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){if(re.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=qa.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let o=re.resolve(i,e),s;try{s=qa.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=ee.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=ee.join(e,"build-profile.json5");if(!X.existsSync(t))return null;try{let r=X.readFileSync(t,"utf-8"),i=Lt.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=C.resolvePathWithinRoot(this.rootDir,t.srcPath),i=ee.join(r,"src","main","module.json5");if(!X.existsSync(i))return"entry";try{let o=X.readFileSync(i,"utf-8");return Lt.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=C.resolvePathWithinRoot(this.rootDir,t.srcPath),i=ee.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 Lt.parse(o)}getBundleName(){let e=ee.join(this.rootDir,"AppScope","app.json5");if(X.existsSync(e))try{let t=X.readFileSync(e,"utf-8"),r=Lt.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=ee.join(this.rootDir,"AppScope","app.json5");if(!X.existsSync(e))return!1;try{let t=X.readFileSync(e,"utf-8");return Lt.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=C.resolvePathWithinRoot(this.rootDir,r.srcPath),o=ee.join(i,"src","main","module.json5");if(!X.existsSync(o))return"EntryAbility";try{let s=X.readFileSync(o,"utf-8"),c=Lt.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=C.resolvePathWithinRoot(this.rootDir,t.srcPath),i=ee.join(r,"oh-package.json5");if(!X.existsSync(i))return[];let o=[];try{let s=X.readFileSync(i,"utf-8"),c=Lt.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=ee.join(t.srcPath,p),E=C.resolvePathWithinRoot(this.rootDir,w),O=this.profile.modules.find(fe=>ee.resolve(this.rootDir,fe.srcPath)===E);O&&o.push(O.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 E=this.getSignedHapName(c,o.srcPath,i,t);E&&(p=E)}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=ee.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=C.resolvePathWithinRoot(this.rootDir,e),o=ee.resolve(i,"build",t,...r);return C.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=Lt.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=ee.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 pu}from"child_process";import J from"fs";import*as Ce from"os";import*as S from"path";import su from"fs";import*as so from"os";import*as oo from"path";import Nw from"regedit";import{execFileSync as xw}from"child_process";import nu from"fs";import*as ru from"os";import*as Ya from"path";import{compare as Tw}from"semver";function tu(n,e){return Tw(n,e)}function Nn(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 io(n,e){let t=Ya.join(n,"Contents","Info.plist");if(!nu.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=xw(r,i,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(o&&!o.includes("Does Not Exist"))return o}catch{}}function Lw(n){let e=io(n,"CFBundleShortVersionString");if(!e)return io(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[io(n,"CFBundleVersion"),io(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 Or(n){if(ru.platform()==="darwin")return Lw(n);let e=Ya.join(n,"product-info.json");try{let t=JSON.parse(nu.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}function Ow(n){return n.filter(e=>{try{return su.statSync(e).isDirectory()}catch{return!1}})}function Mw(){let n=[];for(let e of[oo.join(so.homedir(),"Applications"),"/Applications"])try{n.push(...su.readdirSync(e).filter(t=>t.endsWith(".app")&&t.toLowerCase().includes("deveco")).map(t=>oo.join(e,t)))}catch{}return n}function iu(n){return new Promise((e,t)=>Nw.list(n,(r,i)=>r?t(r):e(i)))}async function ou(n,e,t){let i=((await iu([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(i.length===0)return[];let o=await iu(i);return i.flatMap(s=>{let a=o[s]?.values?.[t]?.value;return a?[a]:[]})}async function _w(){let n=[oo.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 ou(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 ou(e,()=>!0,""))}catch{}return n}async function au(){let n=so.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"?Mw():await _w(),t=Ow(e).flatMap(r=>{let i=Or(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)=>Nn(i.version,r.version)>0?i:r)}import*as cu from"fs";import*as ge from"path";function Ja(n,e){let t=ge.relative(e,n);return t===""||!ge.isAbsolute(t)&&!t.startsWith(`..${ge.sep}`)&&t!==".."}function ot(n){let e=ge.resolve(n),t=[],r=e;for(;;)try{let i=cu.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 ao(n,e){let t=ot(e),r=ot(n);return Ja(r,t)?r:null}function co(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function lo(n){let e=co(n);if(!e)throw new Error("Path must not be empty.");return ot(e)}var Mr={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},uo={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"},Ve={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"},dn={ALGORITHM:"aes-256-gcm",KEY_LENGTH:32,IV_LENGTH:12,KEK_VERSIONS:["kek-v1","kek-v2","kek-v3"]},_r={baseUrl:Ve.LOGIN_URL,authUrl:Ve.AUTH_APPLY_PATH,tempTokenCheckUrl:Ve.TEMP_TOKEN_CHECK_PATH,jwtTokenCheckUrl:Ve.JWT_TOKEN_CHECK_PATH,successRedirectUrl:Ve.LOGIN_SUCCESS_PATH,failedRedirectUrl:Ve.LOGIN_FAILED_PATH,logoutUrl:Ve.LOGOUT_PATH,agcTeamListUrl:Ve.AGC_TEAM_LIST_URL,appId:le.APP_ID,timeout:Mr.LOGIN_TIMEOUT_MS,countryCode:"CN"};var Ka="https://matrix.openharmony.cn",ze={TAGS_API_URL:`${Ka}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${Ka}/api/registry/skill/skills`,SKILL_API_BASE:`${Ka}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},qe={"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 ut}from"os";import Pe from"path";var st="deveco-mcp";var Nt={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:Pe.join(ut(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:Pe.join(process.platform==="win32"?Pe.join(process.env.APPDATA??Pe.join(ut(),"AppData","Roaming"),"Trae CN","User"):Pe.join(ut(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:Pe.join(ut(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:Pe.join(ut(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:Pe.join(process.platform==="win32"?Pe.join(process.env.APPDATA??Pe.join(ut(),"AppData","Roaming"),"Qoder","SharedClientCache"):Pe.join(ut(),"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:Pe.join(ut(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:Pe.join(ut(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function du(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function lu(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function uu(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function po(n,e){return n.format==="opencode"?du(e):n.format==="claude-code"||n.format==="codex"?lu(e):uu(e)}var Ye={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var Za="https://developer.huawei.com/consumer/cn/download/";var Fw=/^#\s*Version:\s*(\S+)/,jw="26.0.0.810";function Hw(n){try{let e=JSON.parse(J.readFileSync(n,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch{return}}function $w(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 Nn(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(Or(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(Nn(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
+ ${Za}`)}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
6
  Searched paths:
7
7
  ${r.join(`
8
- `)}`)}let o=st(e),s=st(i);return n.assertInsideRoot(s,o,"codelinter"),s}static getCodelinterCandidates(e,t){if(t==="studio"){let r=Re.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 K.existsSync(S.join(e,"version.txt"));let r=Re.platform()==="darwin"?S.join(e,"Contents"):e,i=Re.platform()==="darwin"?S.join(r,"Info.plist"):S.join(r,"product-info.json");if(!K.existsSync(i))return!1;let o=n.buildToolPaths(e,"studio");return[o.nodePath,o.ohpmJsPath,o.hvigorJsPath].every(K.existsSync)}static buildToolPaths(e,t){return t==="clt"?n.buildCltToolPaths(e):n.buildStudioToolPaths(e)}static buildCltToolPaths(e){let t=S.join(e,"sdk"),r=Re.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=Re.platform()==="darwin",r=Re.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 K.statSync(e).isFile()}catch{return!1}}static isDirectory(e){try{return K.existsSync(e)&&K.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 Bd();return m(`[ToolProvider] Using auto \u2192 ${t.root} (${t.version})`),{sourceType:"studio",toolchainRoot:t.root}}static resolveExplicitRoot(e,t,r){let i;try{i=ao(e)}catch(o){throw new Error(`Invalid ${r}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}return t==="studio"&&Re.platform()==="darwin"&&(i=n.normalizeMacStudioRoot(i)),n.isValidRoot(i,t)?i:n.throwInvalidSource(i,t,r,e)}static assertBuiltPathsInsideRoot(e,t,r){let i=st(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(oo(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 K.readFileSync(S.join(e,"version.txt"),"utf-8").split(/\r?\n/).map(t=>t.match(vw)?.[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 K.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(Re.platform()==="win32"?["java.exe","java.cmd"]:["java"]).map(r=>S.join(e,r)).find(K.existsSync)}getMaxApiLevel(){for(let e of bw(this.sdkPath)){let t=Ew(e);if(t!==void 0)return t}return 23}detectApiLevel(){return this.getMaxApiLevel()}_apiscanPaths;getApiscanPaths(){if(this._apiscanPaths)return this._apiscanPaths;let e=Re.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(!K.existsSync(i)||!K.existsSync(o)){let s=Or(this._toolchainRoot)??"unknown";throw new Error(`A required component is missing. The detected DevEco Studio version is ${s}. The minimum required version is ${Sw}. Upgrade before using 'check compat' at ${DOWNLOAD_URL}`)}return this._apiscanPaths={apiChangeDir:i,scriptPath:o},this._apiscanPaths}static verifySignature(e){if(!K.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=Re.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(!K.statSync(e).isFile())throw new Error;K.accessSync(e,K.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=K.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=K.mkdtempSync(S.join(Re.tmpdir(),"deveco-verify-")),i=S.join(r,"Verify-Signature.ps1");K.writeFileSync(i,"Get-AuthenticodeSignature -FilePath $args[0] | ConvertTo-Json -Depth 3 -Compress","utf8");try{let o=Yd(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{K.rmSync(r,{recursive:!0,force:!0})}}static verifyMacSignature(e){try{return Yd("codesign",["-v",e],{encoding:"utf8",timeout:5e3,stdio:["ignore","ignore","ignore"]}),{signed:!0}}catch{return{signed:!1}}}};import{execa as Pw}from"execa";import*as Hr from"path";var mt=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let i=Hr.dirname(e.javaPath),o=`${i}${Hr.delimiter}${process.env.PATH||""}`,s={...process.env,PATH:o,DEVECO_SDK_HOME:e.sdkPath};e.sourceType==="clt"&&e.javaPath&&(s.JAVA_HOME=Hr.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 Pw(t,r,{cwd:this.projectRoot,env:this.env,stdout:i,stderr:i})}};import{execa as Cw}from"execa";var On=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 Cw(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"})}};import{mkdir as Iw}from"fs/promises";import{dirname as Aw,resolve as Dw}from"path";import{execa as Rw}from"execa";import{lock as Ua,check as LN}from"proper-lockfile";function Ba(n){return Dw(n,".hvigor",".build-lock")}function Tw(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function Jd(n){let e=Aw(Ba(n));if(await Iw(e,{recursive:!0}),process.platform==="win32")try{await Rw("attrib",["+h",e])}catch{}}async function kw(n,e){let t=new AbortController,r=Tw(e);await Jd(n);let i={lockfilePath:Ba(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await Ua(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 Ua(n,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function dn(n,e,t){let{release:r,signal:i}=await kw(n,t);try{return await e(i)}finally{await r()}}async function uo(n,e){let t=new AbortController;await Jd(n);let r={lockfilePath:Ba(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},i;try{i=await Ua(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 Mt from"fs";import*as un from"path";import xw from"json5";var Lw=1e3;function fo(n){m(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=un.join(n,Ye.SYNC_OUTPUT_PATH);if(!Mt.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return m(`[ProjectCheck] ${l.reason}`),l}let t=Mt.statSync(e).mtimeMs;m(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=Nw(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return m(`[ProjectCheck] ${l.reason}`),l}let i=un.join(n,Ye.OH_PACKAGE_JSON5),o=po(i,t,"root");if(o.required)return m(`[ProjectCheck] Root check: ${o.reason}`),o;let s=un.join(n,Ye.BUILD_PROFILE_JSON5),a=po(s,t,"build-profile");if(a.required)return m(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let d=un.join(n,l.srcPath,Ye.OH_PACKAGE_JSON5),h=po(d,t,l.name);if(h.required)return m(`[ProjectCheck] Module '${l.name}' check: ${h.reason}`),h;let w=un.join(n,l.srcPath,Ye.BUILD_PROFILE_JSON5),E=po(w,t,l.name);if(E.required)return m(`[ProjectCheck] Module '${l.name}' build-profile check: ${E.reason}`),E}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return m(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function po(n,e,t){if(!Mt.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=Mt.statSync(n).mtimeMs;return r-e>Lw?{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 Nw(n){let e=un.join(n,Ye.BUILD_PROFILE_JSON5);try{let t=Mt.readFileSync(e,"utf-8");if(!t.trim())return null;let r=xw.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 ke from"fs";import*as Xe from"path";import*as uu from"util";import*as _ from"fs";import*as Eo from"path";import k from"fs";import*as mo from"os";import*as D from"path";import Ow from"json5";var Wa="Huawei";var Qd=3,eu=3,Kd="DevEco Studio",tu={DevEcoStudio:"deveco_studio"};function ho(n){if(!k.existsSync(n)||!k.statSync(n).isDirectory())return!1;let e=k.existsSync(D.join(n,"build-profile.json5")),t=k.existsSync(D.join(n,"hvigorfile.js"))||k.existsSync(D.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=k.readFileSync(D.join(n,"build-profile.json5"),"utf-8");return Ow.parse(r).app!==void 0}catch{return!1}}function Ga(n,e,t){if(e>=t)return null;let r=Mw(n),i=_w(r);if(i)return i;for(let o of r){let s=Ga(o,e+1,t);if(s)return s}return null}function Mw(n){try{let e=k.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(D.join(n,r.name));return t}catch{return[]}}function _w(n){for(let e of n)if(ho(e))return e;return null}function ht(n){if(!n||n.trim()==="")return null;let e=D.resolve(n),t;try{t=k.realpathSync(e)}catch{t=e}if(!k.existsSync(t))return null;if(ho(t))return t;let r=t;for(let i=1;i<=3;i++){let o=D.dirname(r);if(o===r)break;if(ho(o))return o;r=o}if(k.statSync(t).isDirectory()){let i=Ga(t,0,Qd);if(i)return i}return null}function go(n){if(!n||n.trim()==="")return null;let e=D.resolve(n),t;try{t=k.realpathSync(e)}catch{t=e}return!k.existsSync(t)||!k.statSync(t).isDirectory()?null:ho(t)?t:Ga(t,0,Qd)}function Mn(n){if(process.platform==="linux")return null;let e=n??Je();if(!e)return null;let t;if(process.platform==="win32")t=D.join(e,"plugins","openharmony");else if(process.platform==="darwin")t=D.join(e,"contents","plugins","openharmony");else return null;let r=D.join(t,"ace-server","out","index.js");return k.existsSync(r)?t:null}var Fw=["sdk","default","openharmony","native","llvm","bin","clangd"],jw=[".idea",".deveco","cxx","compile_commands.json"];function Hw(n){return process.platform==="darwin"&&n.endsWith(".app")?D.join(n,"Contents"):n}function Xd(n){let e=new Set,t=[n,Hw(n)];for(let r of t){let i=D.join(r,...Fw);e.add(process.platform==="win32"?i+".exe":i)}return[...e]}function yo(n){let e=[],t=process.env.DEVECO_HOME??process.env.DEVECO_PATH;if(t&&t.trim()){for(let i of Xd(t.trim()))if(e.push(i),k.existsSync(i))return i}let r=n??Je();if(r){for(let i of Xd(r))if(e.push(i),k.existsSync(i))return i}return null}function $r(n){return D.join(n,...jw)}function Je(){if(process.platform==="win32"){let n=[D.join("C:\\Program Files",Wa,Kd),D.join("C:\\Program Files (x86)",Wa,Kd)];return Zd(n)}if(process.platform==="darwin"){let n=["/Applications/DevEco Studio.app",D.join(process.env.HOME??"","Applications","DevEco Studio.app")];return Zd(n)}return null}function Zd(n){for(let e of n)if(k.existsSync(e))return e;return null}function ct(n){return process.platform==="darwin"?D.join(n,"Contents"):n}function $w(n){if(!n||!k.existsSync(n)||!nu(n))return!1;let e=ct(n);return[D.join(e,"plugins","openharmony"),D.join(e,"sdk"),D.join(e,"tools")].some(r=>k.existsSync(r))}function nu(n){try{return k.statSync(n).isDirectory()}catch{return!1}}function za(n,e){return!n||!k.existsSync(n)?!1:e===tu.DevEcoStudio?$w(n):!1}function ru(n,e=tu.DevEcoStudio){if(!n)return"";if(za(n,e))return n;let t=Uw(n,e);if(t)return t;let r=Bw(n,e);return r||n}function Uw(n,e){let t=n;for(let r=0;r<eu;r++){let i=D.dirname(t);if(!i||i===t)break;if(za(i,e))return i;t=i}return null}function Bw(n,e){if(!k.existsSync(n)||!nu(n))return null;let t=[{p:n,depth:0}];for(;t.length>0;){let{p:r,depth:i}=t.shift();if(i>=eu)continue;let o=Ww(r,i,e,t);if(o)return o}return null}function Ww(n,e,t,r){let i;try{i=k.readdirSync(n,{withFileTypes:!0})}catch{return null}for(let o of i){if(!o.isDirectory())continue;let s=D.join(n,o.name);if(za(s,t))return s;r.push({p:s,depth:e+1})}return null}function iu(n){return new Promise(e=>setTimeout(e,n))}var Gw=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function pn(n){let e=D.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&Gw.has(e)}function wo(n){return D.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function oe(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function zw(n){return oe(n)}function fn(n){let e=zw(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function _t(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??D.join(mo.homedir(),"AppData","Local");return D.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?D.join(mo.homedir(),"Library","Logs","devecocli-mcp-server"):D.join(mo.homedir(),".local","share","devecocli-mcp-server","logs")}function ou(n,e){let t=Vw(e),r=qw(t,n);if(r!==null)return r;let i=Date.now(),s=`${n.replace(/:/g,"\\:")}=${i}`,a=Yw(t,n,s);return Jw(e,a),i}function Vw(n){let e;try{e=k.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function qw(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 Yw(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 Jw(n,e){try{k.mkdirSync(D.dirname(n),{recursive:!0})}catch{}try{k.writeFileSync(n,e.join(`
8
+ `)}`)}let o=ot(e),s=ot(i);return n.assertInsideRoot(s,o,"codelinter"),s}static getCodelinterCandidates(e,t){if(t==="studio"){let r=Ce.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 J.existsSync(S.join(e,"version.txt"));let r=Ce.platform()==="darwin"?S.join(e,"Contents"):e,i=Ce.platform()==="darwin"?S.join(r,"Info.plist"):S.join(r,"product-info.json");if(!J.existsSync(i))return!1;let o=n.buildToolPaths(e,"studio");return[o.nodePath,o.ohpmJsPath,o.hvigorJsPath].every(J.existsSync)}static buildToolPaths(e,t){return t==="clt"?n.buildCltToolPaths(e):n.buildStudioToolPaths(e)}static buildCltToolPaths(e){let t=S.join(e,"sdk"),r=Ce.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=Ce.platform()==="darwin",r=Ce.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 J.statSync(e).isFile()}catch{return!1}}static isDirectory(e){try{return J.existsSync(e)&&J.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 au();return m(`[ToolProvider] Using auto \u2192 ${t.root} (${t.version})`),{sourceType:"studio",toolchainRoot:t.root}}static resolveExplicitRoot(e,t,r){let i;try{i=lo(e)}catch(o){throw new Error(`Invalid ${r}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}return t==="studio"&&Ce.platform()==="darwin"&&(i=n.normalizeMacStudioRoot(i)),n.isValidRoot(i,t)?i:n.throwInvalidSource(i,t,r,e)}static assertBuiltPathsInsideRoot(e,t,r){let i=ot(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(ao(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 J.readFileSync(S.join(e,"version.txt"),"utf-8").split(/\r?\n/).map(t=>t.match(Fw)?.[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 J.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(Ce.platform()==="win32"?["java.exe","java.cmd"]:["java"]).map(r=>S.join(e,r)).find(J.existsSync)}getMaxApiLevel(){for(let e of $w(this.sdkPath)){let t=Hw(e);if(t!==void 0)return t}return 23}detectApiLevel(){return this.getMaxApiLevel()}_apiscanPaths;getApiscanPaths(){if(this._apiscanPaths)return this._apiscanPaths;let e=Ce.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(!J.existsSync(i)||!J.existsSync(o)){let s=Or(this._toolchainRoot)??"unknown";throw new Error(`A required component is missing. The detected DevEco Studio version is ${s}. The minimum required version is ${jw}. Upgrade before using 'check compat' at ${Za}`)}return this._apiscanPaths={apiChangeDir:i,scriptPath:o},this._apiscanPaths}static verifySignature(e){if(!J.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=Ce.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(!J.statSync(e).isFile())throw new Error;J.accessSync(e,J.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=J.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=J.mkdtempSync(S.join(Ce.tmpdir(),"deveco-verify-")),i=S.join(r,"Verify-Signature.ps1");J.writeFileSync(i,"Get-AuthenticodeSignature -FilePath $args[0] | ConvertTo-Json -Depth 3 -Compress","utf8");try{let o=pu(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{J.rmSync(r,{recursive:!0,force:!0})}}static verifyMacSignature(e){try{return pu("codesign",["-v",e],{encoding:"utf8",timeout:5e3,stdio:["ignore","ignore","ignore"]}),{signed:!0}}catch{return{signed:!1}}}};import{execa as Uw}from"execa";import*as Fr from"path";var pt=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let i=Fr.dirname(e.javaPath),o=`${i}${Fr.delimiter}${process.env.PATH||""}`,s={...process.env,PATH:o,DEVECO_SDK_HOME:e.sdkPath};e.sourceType==="clt"&&e.javaPath&&(s.JAVA_HOME=Fr.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 Uw(t,r,{cwd:this.projectRoot,env:this.env,stdout:i,stderr:i})}};import{execa as Bw}from"execa";var On=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 Bw(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"})}};import{mkdir as Ww}from"fs/promises";import{dirname as Gw,resolve as Vw}from"path";import{execa as zw}from"execa";import{lock as Xa,check as nO}from"proper-lockfile";function Qa(n){return Vw(n,".hvigor",".build-lock")}function qw(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function fu(n){let e=Gw(Qa(n));if(await Ww(e,{recursive:!0}),process.platform==="win32")try{await zw("attrib",["+h",e])}catch{}}async function Yw(n,e){let t=new AbortController,r=qw(e);await fu(n);let i={lockfilePath:Qa(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await Xa(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 Xa(n,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function un(n,e,t){let{release:r,signal:i}=await Yw(n,t);try{return await e(i)}finally{await r()}}async function fo(n,e){let t=new AbortController;await fu(n);let r={lockfilePath:Qa(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},i;try{i=await Xa(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 Ot from"fs";import*as pn from"path";import Jw from"json5";var Kw=1e3;function ho(n){m(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=pn.join(n,Ye.SYNC_OUTPUT_PATH);if(!Ot.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return m(`[ProjectCheck] ${l.reason}`),l}let t=Ot.statSync(e).mtimeMs;m(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=Zw(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return m(`[ProjectCheck] ${l.reason}`),l}let i=pn.join(n,Ye.OH_PACKAGE_JSON5),o=mo(i,t,"root");if(o.required)return m(`[ProjectCheck] Root check: ${o.reason}`),o;let s=pn.join(n,Ye.BUILD_PROFILE_JSON5),a=mo(s,t,"build-profile");if(a.required)return m(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let p=pn.join(n,l.srcPath,Ye.OH_PACKAGE_JSON5),g=mo(p,t,l.name);if(g.required)return m(`[ProjectCheck] Module '${l.name}' check: ${g.reason}`),g;let w=pn.join(n,l.srcPath,Ye.BUILD_PROFILE_JSON5),E=mo(w,t,l.name);if(E.required)return m(`[ProjectCheck] Module '${l.name}' build-profile check: ${E.reason}`),E}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return m(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function mo(n,e,t){if(!Ot.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=Ot.statSync(n).mtimeMs;return r-e>Kw?{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 Zw(n){let e=pn.join(n,Ye.BUILD_PROFILE_JSON5);try{let t=Ot.readFileSync(e,"utf-8");if(!t.trim())return null;let r=Jw.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 Ae from"fs";import*as Oe from"path";import*as ku from"util";import*as _ from"fs";import*as Io from"path";import T from"fs";import*as go from"os";import*as A from"path";import Xw from"json5";var ec="Huawei";var gu=3,yu=3,mu="DevEco Studio",wu={DevEcoStudio:"deveco_studio"};function yo(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 Xw.parse(r).app!==void 0}catch{return!1}}function tc(n,e,t){if(e>=t)return null;let r=Qw(n),i=ev(r);if(i)return i;for(let o of r){let s=tc(o,e+1,t);if(s)return s}return null}function Qw(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 ev(n){for(let e of n)if(yo(e))return e;return null}function ft(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(yo(t))return t;let r=t;for(let i=1;i<=3;i++){let o=A.dirname(r);if(o===r)break;if(yo(o))return o;r=o}if(T.statSync(t).isDirectory()){let i=tc(t,0,gu);if(i)return i}return null}function wo(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:yo(t)?t:tc(t,0,gu)}function tv(n){let e=n??rc();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 nc(n){let e=ov(n??""),t=vu(e);return A.join(t,"sdk")}function vo(n){return{sdkPath:nc(n),arktsLangServerPath:tv(n)}}function jr(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 So(n){return T.existsSync(jr(n,!0))}var nv=["default","openharmony","native","llvm","bin","clangd"],rv=[".idea",".deveco","cxx","compile_commands.json"];function bo(n){let e=A.join(n,...nv),t=process.platform==="win32"?e+".exe":e;return T.existsSync(t)?t:null}function Hr(n){return A.join(n,...rv)}function rc(){if(process.platform==="win32"){let n=[A.join("C:\\Program Files",ec,mu),A.join("C:\\Program Files (x86)",ec,mu)];return hu(n)}if(process.platform==="darwin"){let n=["/Applications/DevEco Studio.app",A.join(process.env.HOME??"","Applications","DevEco Studio.app")];return hu(n)}return null}function hu(n){for(let e of n)if(T.existsSync(e))return e;return null}function vu(n){return process.platform==="darwin"?A.join(n,"Contents"):n}function iv(n){if(!n||!T.existsSync(n)||!Su(n))return!1;let e=vu(n);return[A.join(e,"plugins","openharmony"),A.join(e,"sdk"),A.join(e,"tools")].some(r=>T.existsSync(r))}function Su(n){try{return T.statSync(n).isDirectory()}catch{return!1}}function ic(n,e){return!n||!T.existsSync(n)?!1:e===wu.DevEcoStudio?iv(n):!1}function ov(n,e=wu.DevEcoStudio){if(!n)return"";if(ic(n,e))return n;let t=sv(n,e);if(t)return t;let r=av(n,e);return r||n}function sv(n,e){let t=n;for(let r=0;r<yu;r++){let i=A.dirname(t);if(!i||i===t)break;if(ic(i,e))return i;t=i}return null}function av(n,e){if(!T.existsSync(n)||!Su(n))return null;let t=[{p:n,depth:0}];for(;t.length>0;){let{p:r,depth:i}=t.shift();if(i>=yu)continue;let o=cv(r,i,e,t);if(o)return o}return null}function cv(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(ic(s,t))return s;r.push({p:s,depth:e+1})}return null}function bu(n){return new Promise(e=>setTimeout(e,n))}var lv=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function fn(n){let e=A.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&lv.has(e)}function Eo(n){return A.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function ie(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function dv(n){return ie(n)}function mn(n){let e=dv(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function Mt(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??A.join(go.homedir(),"AppData","Local");return A.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?A.join(go.homedir(),"Library","Logs","devecocli-mcp-server"):A.join(go.homedir(),".local","share","devecocli-mcp-server","logs")}function Eu(n,e){let t=uv(e),r=pv(t,n);if(r!==null)return r;let i=Date.now(),s=`${n.replace(/:/g,"\\:")}=${i}`,a=fv(t,n,s);return mv(e,a),i}function uv(n){let e;try{e=T.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function pv(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 fv(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 mv(n,e){try{T.mkdirSync(A.dirname(n),{recursive:!0})}catch{}try{T.writeFileSync(n,e.join(`
9
9
  `)+`
10
- `,"utf8")}catch{}}function Va(n,e,t="[Cleanup]"){try{let r=D.dirname(n);if(!k.existsSync(r))return;let i=Date.now();for(let o of k.readdirSync(r,{withFileTypes:!0}))o.isDirectory()&&Kw(D.join(r,o.name),i,e,t)}catch{}}function Kw(n,e,t,r){try{let{mtimeMs:i}=k.statSync(n);if(e-i<=t)return;k.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 vo(n){let e=n.replace(/sdk\/?$/i,"tools"),t=process.platform==="win32"?"node.exe":"node",r=D.join(e,"node",t);return k.existsSync(r)||process.platform!=="win32"&&(r=D.join(e,"node","bin","node"),k.existsSync(r))?r:process.execPath??"node"}var su="mcp-server.log",Xw="mcp-server",Zw={maxSize:10*1024*1024,maxFiles:4},qa=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={...Zw,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=_t(),this.currentLogFile=Eo.join(this.logDir,su),_.existsSync(this.logDir)||_.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${i}`}getRotatedFileName(e,t){return Eo.join(this.logDir,`${Xw}-${e}.log.${t}`)}fileExists(e){try{return _.accessSync(e,_.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=_.readdirSync(this.logDir),t=[];for(let i of e)if(i===su||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=Eo.join(this.logDir,i),s=_.statSync(o);t.push({name:i,mtime:s.mtime,path:o})}t.sort((i,o)=>o.mtime.getTime()-i.mtime.getTime());let r=1+this.rotationOptions.maxFiles;for(let i=r;i<t.length;i++)try{_.unlinkSync(t[i].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let e=this.getCurrentDateString(),t=this.getRotatedFileName(e,this.rotationOptions.maxFiles);this.fileExists(t)&&_.unlinkSync(t);for(let i=this.rotationOptions.maxFiles-1;i>=1;i--){let o=this.getRotatedFileName(e,i),s=this.getRotatedFileName(e,i+1);this.fileExists(o)&&_.renameSync(o,s)}let r=this.getRotatedFileName(e,1);_.renameSync(this.currentLogFile,r),this.cleanupOrphanLogFiles(),this.openLogFile()}catch{this.openLogFile()}finally{this.isRotating=!1}}}openLogFile(){if(this.currentLogFile){this.currentDate=this.getCurrentDateString();try{if(this.fileExists(this.currentLogFile)){let e=_.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=_.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{_.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...r){if(this.mode==="silent"||n.LEVEL_ORDER[e]<n.LEVEL_ORDER[this.minLevel])return;let i=r.map(c=>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);_.writeSync(this.fd,c),this.checkRotation(c.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(a)}debug(e,...t){this.write("debug",e,...t)}info(e,...t){this.write("info",e,...t)}warn(e,...t){this.write("warn",e,...t)}error(e,...t){this.write("error",e,...t)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{_.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},Oe=null;function mn(n=!1){Oe&&Oe.dispose(),Oe=new qa(n)}function au(){Oe&&(Oe.dispose(),Oe=null)}function cu(){Oe&&Oe.flush()}function lu(){return Oe?.getLogFilePath()??null}function du(){return Oe?.getLogDirectory()??null}function So(){return Oe||mn(!1),Oe}var g={debug:(n,...e)=>So().debug(n,...e),info:(n,...e)=>So().info(n,...e),warn:(n,...e)=>So().warn(n,...e),error:(n,...e)=>So().error(n,...e)};var Ya="";function Po(n){if(!n||n==="auto"||n==="stdout"||n==="none"){Ya="";return}Ya=n}function pu(){return Ya||(du()??"")}function bo(n,...e){if(e.length===0)return n;try{return uu.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var f={info(n,...e){g.info(`[lsp] ${bo(n,...e)}`)},warn(n,...e){g.warn(`[lsp] ${bo(n,...e)}`)},error(n,...e){g.error(`[lsp] ${bo(n,...e)}`)},debug(n,...e){g.debug(`[lsp] ${bo(n,...e)}`)}};import*as Ur from"fs";import*as Br from"os";import*as _n from"path";import Qw 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 fu=8192,Ja=100,mu=.03,hu=.7,Me=900*1e3;function Te(n){if(!Ur.existsSync(n))return null;try{let e=Ur.readFileSync(n,"utf-8");return e.trim()?Qw.parse(e):null}catch{return null}}function Co(n,e){let t=Math.floor(Br.totalmem()/1048576),r=Math.floor(t*hu),i,o;e!==void 0&&Number.isFinite(e)&&e>0?(i=e,o=`override(${e})`):(i=fu,n>Ja&&(i+=(n-Ja)*mu*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 Ke(n){if(n.startsWith("file:"))return n;try{let e=_n.resolve(n),t=new URL(`file://${e}`).toString();if(Br.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 Fn(n){return n&&n.replace(/\\/g,"/")}function H(n){let e=_n.normalize(n).replace(/\\/g,"/");if(Br.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function gu(n){return _n.join(n,"build-profile.json5")}var gt=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=gu(this.projectRoot);try{let t=Te(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 ev}from"child_process";import*as Do from"path";import*as Ao from"fs";var tv=600*1e3;function nv(n,e,t){let r=t.split(/\s+/).filter(i=>i.length>0);return[n,[e,...r]]}function rv(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 Io(n){return n.join("")}function iv(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
10
+ `,"utf8")}catch{}}function oc(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()&&hv(A.join(r,o.name),i,e,t)}catch{}}function hv(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 Po(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 Pu="mcp-server.log",gv="mcp-server",yv={maxSize:10*1024*1024,maxFiles:4},sc=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={...yv,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=Mt(),this.currentLogFile=Io.join(this.logDir,Pu),_.existsSync(this.logDir)||_.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${i}`}getRotatedFileName(e,t){return Io.join(this.logDir,`${gv}-${e}.log.${t}`)}fileExists(e){try{return _.accessSync(e,_.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=_.readdirSync(this.logDir),t=[];for(let i of e)if(i===Pu||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=Io.join(this.logDir,i),s=_.statSync(o);t.push({name:i,mtime:s.mtime,path:o})}t.sort((i,o)=>o.mtime.getTime()-i.mtime.getTime());let r=1+this.rotationOptions.maxFiles;for(let i=r;i<t.length;i++)try{_.unlinkSync(t[i].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let e=this.getCurrentDateString(),t=this.getRotatedFileName(e,this.rotationOptions.maxFiles);this.fileExists(t)&&_.unlinkSync(t);for(let i=this.rotationOptions.maxFiles-1;i>=1;i--){let o=this.getRotatedFileName(e,i),s=this.getRotatedFileName(e,i+1);this.fileExists(o)&&_.renameSync(o,s)}let r=this.getRotatedFileName(e,1);_.renameSync(this.currentLogFile,r),this.cleanupOrphanLogFiles(),this.openLogFile()}catch{this.openLogFile()}finally{this.isRotating=!1}}}openLogFile(){if(this.currentLogFile){this.currentDate=this.getCurrentDateString();try{if(this.fileExists(this.currentLogFile)){let e=_.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=_.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{_.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...r){if(this.mode==="silent"||n.LEVEL_ORDER[e]<n.LEVEL_ORDER[this.minLevel])return;let i=r.map(c=>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);_.writeSync(this.fd,c),this.checkRotation(c.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(a)}debug(e,...t){this.write("debug",e,...t)}info(e,...t){this.write("info",e,...t)}warn(e,...t){this.write("warn",e,...t)}error(e,...t){this.write("error",e,...t)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{_.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},Le=null;function hn(n=!1){Le&&Le.dispose(),Le=new sc(n)}function Cu(){Le&&(Le.dispose(),Le=null)}function Iu(){Le&&Le.flush()}function Au(){return Le?.getLogFilePath()??null}function Du(){return Le?.getLogDirectory()??null}function Co(){return Le||hn(!1),Le}var h={debug:(n,...e)=>Co().debug(n,...e),info:(n,...e)=>Co().info(n,...e),warn:(n,...e)=>Co().warn(n,...e),error:(n,...e)=>Co().error(n,...e)};var ac="";function Do(n){if(!n||n==="auto"||n==="stdout"||n==="none"){ac="";return}ac=n}function Ru(){return ac||(Du()??"")}function Ao(n,...e){if(e.length===0)return n;try{return ku.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] ${Ao(n,...e)}`)},warn(n,...e){h.warn(`[lsp] ${Ao(n,...e)}`)},error(n,...e){h.error(`[lsp] ${Ao(n,...e)}`)},debug(n,...e){h.debug(`[lsp] ${Ao(n,...e)}`)}};import*as $r from"fs";import*as Ur from"os";import*as Mn from"path";import wv 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"},k="2.0";var Tu=8192,cc=100,xu=.03,Lu=.7,Ne=900*1e3;function Ie(n){if(!$r.existsSync(n))return null;try{let e=$r.readFileSync(n,"utf-8");return e.trim()?wv.parse(e):null}catch{return null}}function ko(n,e){let t=Math.floor(Ur.totalmem()/1048576),r=Math.floor(t*Lu),i,o;e!==void 0&&Number.isFinite(e)&&e>0?(i=e,o=`override(${e})`):(i=Tu,n>cc&&(i+=(n-cc)*xu*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 Je(n){if(n.startsWith("file:"))return n;try{let e=Mn.resolve(n),t=new URL(`file://${e}`).toString();if(Ur.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 _n(n){return n&&n.replace(/\\/g,"/")}function H(n){let e=Mn.normalize(n).replace(/\\/g,"/");if(Ur.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function Nu(n){return Mn.join(n,"build-profile.json5")}var mt=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=Nu(this.projectRoot);try{let t=Ie(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 vv}from"child_process";import*as xo from"path";import*as To from"fs";var Sv=600*1e3;function bv(n,e,t){let r=t.split(/\s+/).filter(i=>i.length>0);return[n,[e,...r]]}function Ev(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 Ro(n){return n.join("")}function Pv(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
12
12
  Output so far:
13
- `+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function ov(n,e,t){return new Promise(r=>{let i=ev(n[0],n[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:o,stderr:s}=rv(i),a=setTimeout(()=>{i.kill();let c=[Io(o),Io(s)].filter(Boolean).join(`
13
+ `+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function Cv(n,e,t){return new Promise(r=>{let i=vv(n[0],n[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:o,stderr:s}=Ev(i),a=setTimeout(()=>{i.kill();let c=[Ro(o),Ro(s)].filter(Boolean).join(`
14
14
  `).trim();r({success:!1,output:`Build process timeout after 10 minutes.
15
15
  Output so far:
16
- `+c,exitCode:-1})},tv);i.on("close",(c,l)=>{clearTimeout(a);let d=[Io(o),Io(s)].filter(Boolean).join(`
17
- `).trim()||"";r(iv(c,l,d))}),i.on("error",c=>{clearTimeout(a),r({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function Ka(n,e,t,r,i){let o={...process.env,DEVECO_SDK_HOME:r},s=nv(e,t,i);return await ov(s,n,o)}function sv(n){let e=Do.join(Do.dirname(n),"tools","hvigor","bin","hvigorw.js");return{node_path:vo(n),hvigor_path:e,sdk_path:n}}function av(n){return!n.node_path||!Ao.existsSync(n.node_path)?`Node path not found or invalid: ${n.node_path}`:!n.hvigor_path||!Ao.existsSync(n.hvigor_path)?`Hvigor path not found or invalid: ${n.hvigor_path}`:!n.sdk_path||!Ao.existsSync(n.sdk_path)?`SDK path not found or invalid: ${n.sdk_path}`:null}var cv="--sync -p product=default --analyze=normal --parallel --incremental --no-daemon";async function yu(n,e){try{let t=sv(e),r=av(t);return r!=null?(f.info(`Config validation failed: ${r}`),!1):(await Ka(n,t.node_path,t.hvigor_path,e,cv)).success}catch(t){return f.info(`syncProject failed: ${JSON.stringify(t)}`),!1}}function lv(n){let e=Xe.extname(n).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh","c++","h++"].includes(e)}function dv(n,e){let t=Xe.join(n,e.name);return e.isDirectory()?e.name===".cxx"||wu(t):lv(t)}function wu(n){if(!ke.existsSync(n))return!1;try{return ke.readdirSync(n,{withFileTypes:!0}).some(t=>dv(n,t))}catch{}return!1}function hn(n){let t=new gt(n).getAllModuleInfo(),r=[];for(let i of t){let o=P.resolvePathWithinRoot(n,i.srcPath);wu(o)&&r.push(i)}return r}function uv(n){let e=[],r=new gt(n).getAllModuleInfo();for(let i of r){let o=P.resolvePathWithinRoot(n,i.srcPath),s=Xe.join(o,".cxx");ke.existsSync(s)&&vu(s,e)}return e}function vu(n,e){try{let t=ke.readdirSync(n,{withFileTypes:!0});for(let r of t){let i=Xe.join(n,r.name);r.isDirectory()?vu(i,e):r.name==="compile_commands.json"&&e.push(i)}}catch{}}function pv(n){let e=[];for(let t of n)try{let r=ke.readFileSync(t,"utf8"),i=JSON.parse(r);e.push(...i)}catch{}return e}function fv(n,e){let t=Xe.join(n,...mv.slice(0,-1));ke.mkdirSync(t,{recursive:!0});let r=Xe.join(t,"compile_commands.json");ke.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function Xa(n){let e=uv(n);if(e.length>0){let t=pv(e);fv(n,t),g.info(`[CppCompile] compile_commands.json generated, ${t.length} compile commands`)}else g.warn("[CppCompile] No compile_commands.json files found")}var mv=[".idea",".deveco","cxx","compile_commands.json"];async function hv(n,e,t){let r=Xe.join(ct(e),"sdk"),i=process.execPath||"node",o=Xe.join(ct(e),"tools");g.info(`[CppCompile] devecoPath: ${e}, contentRoot: ${ct(e)}, sdkPath: ${r}, toolsDir: ${o}`);let s=Xe.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(" ");g.info(`[CppCompile] Running compileNative for module: ${a.name}`);let l=await Ka(n,i,s,r,c);l.success?g.info(`[CppCompile] compileNative ${a.name} succeeded`):g.warn(`[CppCompile] compileNative ${a.name} failed: ${l.output}`)}}async function Su(n,e){let t=hn(n);if(t.length===0){g.info("[CppCompile] No C++ modules found, skipping initialization");return}g.info(`[CppCompile] Found ${t.length} C++ module(s): ${t.map(r=>r.name).join(", ")}`),await hv(n,e,t),Xa(n)}function yv(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 wv(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 tc(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 Wr(n,e){let t=e,r=`${n} failed`;console.error(Qa(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 nc(n,e,t,r,i,o){let s=fo(o);console.log(`
18
- [ohpm install] Running...`);try{await n.installAll()}catch(a){Wr("ohpm install",a)}if(s.required){console.log(`
19
- [hvigor sync] Running...`);try{await e.sync(t,r)}catch(a){Wr("hvigor sync",a)}}else console.log(`
16
+ `+c,exitCode:-1})},Sv);i.on("close",(c,l)=>{clearTimeout(a);let p=[Ro(o),Ro(s)].filter(Boolean).join(`
17
+ `).trim()||"";r(Pv(c,l,p))}),i.on("error",c=>{clearTimeout(a),r({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function lc(n,e,t,r,i){let o={...process.env,DEVECO_SDK_HOME:r},s=bv(e,t,i);return await Cv(s,n,o)}function Iv(n){let e=xo.join(xo.dirname(n),"tools","hvigor","bin","hvigorw.js");return{node_path:Po(n),hvigor_path:e,sdk_path:n}}function Av(n){return!n.node_path||!To.existsSync(n.node_path)?`Node path not found or invalid: ${n.node_path}`:!n.hvigor_path||!To.existsSync(n.hvigor_path)?`Hvigor path not found or invalid: ${n.hvigor_path}`:!n.sdk_path||!To.existsSync(n.sdk_path)?`SDK path not found or invalid: ${n.sdk_path}`:null}var Dv="--sync -p product=default --analyze=normal --parallel --incremental --no-daemon";async function Ou(n,e){try{let t=Iv(e),r=Av(t);return r!=null?(f.info(`Config validation failed: ${r}`),!1):(await lc(n,t.node_path,t.hvigor_path,e,Dv)).success}catch(t){return f.info(`syncProject failed: ${JSON.stringify(t)}`),!1}}function kv(n){let e=Oe.extname(n).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh","c++","h++"].includes(e)}function Rv(n,e){let t=Oe.join(n,e.name);return e.isDirectory()?e.name===".cxx"||Mu(t):kv(t)}function Mu(n){if(!Ae.existsSync(n))return!1;try{return Ae.readdirSync(n,{withFileTypes:!0}).some(t=>Rv(n,t))}catch{}return!1}function gn(n){let t=new mt(n).getAllModuleInfo(),r=[];for(let i of t){let o=C.resolvePathWithinRoot(n,i.srcPath);Mu(o)&&r.push(i)}return r}function Tv(n){let e=[],r=new mt(n).getAllModuleInfo();for(let i of r){let o=C.resolvePathWithinRoot(n,i.srcPath),s=Oe.join(o,".cxx");Ae.existsSync(s)&&_u(s,e)}return e}function _u(n,e){try{let t=Ae.readdirSync(n,{withFileTypes:!0});for(let r of t){let i=Oe.join(n,r.name);r.isDirectory()?_u(i,e):r.name==="compile_commands.json"&&e.push(i)}}catch{}}function xv(n){let e=[];for(let t of n)try{let r=Ae.readFileSync(t,"utf8"),i=JSON.parse(r);e.push(...i)}catch{}return e}function Lv(n,e){let t=Oe.join(n,...Nv.slice(0,-1));Ae.mkdirSync(t,{recursive:!0});let r=Oe.join(t,"compile_commands.json");Ae.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function dc(n){let e=Tv(n);if(e.length>0){let t=xv(e);Lv(n,t),h.info(`[CppCompile] compile_commands.json generated, ${t.length} compile commands`)}else h.warn("[CppCompile] No compile_commands.json files found")}var Nv=[".idea",".deveco","cxx","compile_commands.json"];async function Ov(n,e,t){let r=Oe.join(Oe.dirname(e),"tools"),i=Oe.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 lc(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 Fu(n,e){let t=gn(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 Ov(n,e,t),dc(n)}function _v(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 Fv(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 mc(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 Br(n,e){let t=e,r=`${n} failed`;console.error(pc(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 hc(n,e,t,r,i,o){let s=ho(o);console.log(`
18
+ [ohpm install] Running...`);try{await n.installAll()}catch(a){Br("ohpm install",a)}if(s.required){console.log(`
19
+ [hvigor sync] Running...`);try{await e.sync(t,r)}catch(a){Br("hvigor sync",a)}}else console.log(`
20
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){Wr("hvigor build",a)}vv(o)}function vv(n){try{if(hn(n).length===0)return;Xa(n),console.log(Za(`
22
- Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(ec(`
23
- Failed to merge compile_commands.json: ${e.message}`))}}var Eu=new gv("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(ec("Ensure the project source is trustworthy before proceeding."));let r=await I.new();r.assertJava(),yv(t,n);let i=n.product||"default",o=n.buildMode||"debug",s;if(n.product&&!n.modules)s={type:"product"};else{let l=wv(t,n),d=tc(t,l);s={type:"modules",modulesToBuild:l,moduleTasks:d}}let a=new On(r,t.rootDir),c=new mt(r,t.rootDir);await dn(t.rootDir,async()=>nc(a,c,i,o,s,t.rootDir),()=>{console.log("Another build is already running for this project. Waiting for completion...")}),console.log(`
24
- `+Za("Build completed successfully"))}catch(e){console.error(Qa(e.message)),process.exit(1)}});Eu.command("clean").description("Clean HarmonyOS project build outputs").action(async()=>{try{let n=process.cwd(),e=U.discover(n);console.warn(ec("Ensure the project source is trusted before proceeding."));let t=await I.new();t.assertJava();let r=new mt(t,e.rootDir);await dn(e.rootDir,async()=>{console.log(`
25
- [1/2] Running hvigor clean...`);try{await r.clean()}catch(i){Wr("hvigor clean",i)}console.log(`
26
- [2/2] Running hvigor --stop-daemon...`);try{await r.stopDaemon()}catch(i){Wr("hvigor --stop-daemon",i)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
27
- `+Za("Clean completed successfully."))}catch(n){console.error(Qa(n.message)),process.exit(1)}});var bu=Eu;import{Command as Wv}from"commander";import{green as _u,red as Gv,yellow as Oo}from"colorette";import*as Mo from"path";import{randomUUID as Lv}from"crypto";import{execa as Nv}from"execa";import{execa as xv}from"execa";import{execFile as Sv,spawn as Ev}from"child_process";import{promisify as bv}from"util";var Pv=bv(Sv);function Pu(n,e,t){let i=n.replace(/\r\n/g,`
21
+ [hvigor build] Running...`);try{i.type==="product"?await e.buildProduct(t,r):await e.buildModules(t,r,i.modulesToBuild,i.moduleTasks)}catch(a){Br("hvigor build",a)}jv(o)}function jv(n){try{if(gn(n).length===0)return;dc(n),console.log(uc(`
22
+ Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(fc(`
23
+ Failed to merge compile_commands.json: ${e.message}`))}}var ju=new Mv("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(fc("Ensure the project source is trustworthy before proceeding."));let r=await I.new();r.assertJava(),_v(t,n);let i=n.product||"default",o=n.buildMode||"debug",s;if(n.product&&!n.modules)s={type:"product"};else{let l=Fv(t,n),p=mc(t,l);s={type:"modules",modulesToBuild:l,moduleTasks:p}}let a=new On(r,t.rootDir),c=new pt(r,t.rootDir);await un(t.rootDir,async()=>hc(a,c,i,o,s,t.rootDir),()=>{console.log("Another build is already running for this project. Waiting for completion...")}),console.log(`
24
+ `+uc("Build completed successfully"))}catch(e){console.error(pc(e.message)),process.exit(1)}});ju.command("clean").description("Clean HarmonyOS project build outputs").action(async()=>{try{let n=process.cwd(),e=U.discover(n);console.warn(fc("Ensure the project source is trusted before proceeding."));let t=await I.new();t.assertJava();let r=new pt(t,e.rootDir);await un(e.rootDir,async()=>{console.log(`
25
+ [1/2] Running hvigor clean...`);try{await r.clean()}catch(i){Br("hvigor clean",i)}console.log(`
26
+ [2/2] Running hvigor --stop-daemon...`);try{await r.stopDaemon()}catch(i){Br("hvigor --stop-daemon",i)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
27
+ `+uc("Clean completed successfully."))}catch(n){console.error(pc(n.message)),process.exit(1)}});var Hu=ju;import{Command as cS}from"commander";import{green as Qu,red as lS,yellow as jo}from"colorette";import*as Ho from"path";import{randomUUID as Zv}from"crypto";import{execa as Xv}from"execa";import{execa as Kv}from"execa";import{execFile as Hv,spawn as $v}from"child_process";import{promisify as Uv}from"util";var Bv=Uv(Hv);function $u(n,e,t){let i=n.replace(/\r\n/g,`
28
28
  `).split(`
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 Cu(n,e,t){let r=n.endsWith("\r")?n.slice(0,-1):n;r.length>0&&t.onData([r],e)}function Cv(n,e){return{stdout:n.stdoutChunks.join(""),stderr:n.stderrChunks.join(""),exitCode:e??-1}}function Iv(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function Av(n,e,t,r,i){n.stdout?.on("data",o=>{let s=o.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=Pu(e.stdoutLineBuffer+s,"stdout",t)}),n.stderr?.on("data",o=>{let s=o.toString();e.stderrChunks.push(s),e.stderrLineBuffer=Pu(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,Cu(e.stdoutLineBuffer,"stdout",t),Cu(e.stderrLineBuffer,"stderr",t),t.onClose(o);let s=Cv(e,o);r(s)})}async function Gr(n,e=[],t={}){try{let{stdout:r,stderr:i}=await Pv(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 Iu(n,e,t){return await new Promise((r,i)=>{let o=Ev(n,e,{stdio:["inherit","pipe","pipe"]}),s=Iv();Av(o,s,t,r,i)})}function Au(n){let e=n.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var Dv=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],Rv=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function jn(n){return n?Dv.some(e=>e.test(n))?"transient":Rv.some(e=>e.test(n))?"fatal":"ok":"ok"}var rc=[800,1500,2500];function Tv(n){return new Promise(e=>setTimeout(e,n))}async function xe(n,e){let t=1+rc.length,r={stdout:"",stderr:"",exitCode:-1};for(let i=0;i<t;i++){if(r=await Gr(n,e),r.exitCode===0||jn(r.stderr)!=="transient"||i>=t-1)return r;m(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${rc[i]}ms`),await Tv(rc[i])}return r}var Du=/^[\w.-]+$/;async function Ro(n,e,t){if(!Du.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 xe(n,r);if(i.exitCode!==0)return;let o=i.stdout.trim();if(!(!o||jn(o)!=="ok"))return Au(o)}var ic="__DEVECO_PARAM_DELIM__";function kv(n,e){let t=new Map,r=n.split(ic);for(let i=0;i<e.length;i++){let o=(r[i]??"").trim();if(!o||jn(o)!=="ok")continue;let s=Au(o);s&&t.set(e[i],s)}return t}async function Hn(n,e,t){let r=t.filter(a=>Du.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 Ro(n,e,r[0]);return c&&a.set(r[0],c),a}let i=r.map(a=>`param get ${a}`).join(`; echo ${ic}; `)+`; echo ${ic}`,o=await xe(n,["-t",e,"shell",i]);if(o.exitCode===0){let a=kv(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 Ro(n,e,a);c&&s.set(a,c)}return s}function gn(n){return n.startsWith("127.0.0.1:")}var Ru=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],Q=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(" ")}`),xv(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 Hn(this.hdcPath,e,[...Ru]);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:
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 Uu(n,e,t){let r=n.endsWith("\r")?n.slice(0,-1):n;r.length>0&&t.onData([r],e)}function Wv(n,e){return{stdout:n.stdoutChunks.join(""),stderr:n.stderrChunks.join(""),exitCode:e??-1}}function Gv(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function Vv(n,e,t,r,i){n.stdout?.on("data",o=>{let s=o.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=$u(e.stdoutLineBuffer+s,"stdout",t)}),n.stderr?.on("data",o=>{let s=o.toString();e.stderrChunks.push(s),e.stderrLineBuffer=$u(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,Uu(e.stdoutLineBuffer,"stdout",t),Uu(e.stderrLineBuffer,"stderr",t),t.onClose(o);let s=Wv(e,o);r(s)})}async function Wr(n,e=[],t={}){try{let{stdout:r,stderr:i}=await Bv(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 Bu(n,e,t){return await new Promise((r,i)=>{let o=$v(n,e,{stdio:["inherit","pipe","pipe"]}),s=Gv();Vv(o,s,t,r,i)})}function Wu(n){let e=n.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var zv=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],qv=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function Fn(n){return n?zv.some(e=>e.test(n))?"transient":qv.some(e=>e.test(n))?"fatal":"ok":"ok"}var gc=[800,1500,2500];function Yv(n){return new Promise(e=>setTimeout(e,n))}async function De(n,e){let t=1+gc.length,r={stdout:"",stderr:"",exitCode:-1};for(let i=0;i<t;i++){if(r=await Wr(n,e),r.exitCode===0||Fn(r.stderr)!=="transient"||i>=t-1)return r;m(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${gc[i]}ms`),await Yv(gc[i])}return r}var Gu=/^[\w.-]+$/;async function Lo(n,e,t){if(!Gu.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 De(n,r);if(i.exitCode!==0)return;let o=i.stdout.trim();if(!(!o||Fn(o)!=="ok"))return Wu(o)}var yc="__DEVECO_PARAM_DELIM__";function Jv(n,e){let t=new Map,r=n.split(yc);for(let i=0;i<e.length;i++){let o=(r[i]??"").trim();if(!o||Fn(o)!=="ok")continue;let s=Wu(o);s&&t.set(e[i],s)}return t}async function jn(n,e,t){let r=t.filter(a=>Gu.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 Lo(n,e,r[0]);return c&&a.set(r[0],c),a}let i=r.map(a=>`param get ${a}`).join(`; echo ${yc}; `)+`; echo ${yc}`,o=await De(n,["-t",e,"shell",i]);if(o.exitCode===0){let a=Jv(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 Lo(n,e,a);c&&s.set(a,c)}return s}function yn(n){return n.startsWith("127.0.0.1:")}var Vu=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],Q=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(" ")}`),Kv(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 jn(this.hdcPath,e,[...Vu]);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:
31
31
  `+o.map(s=>` - ${s.name} (${s.device.serial})`).join(`
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 Hn(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=gn(e),r,i;try{let o=await Hn(this.hdcPath,e,[...Ru]);r=this.extractDisplayName(o),i=o.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:i}}};var $n=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=Q.from(e)}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;m(`Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await Nv(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/${Lv()}`;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 oc from"fs";import*as sc from"path";function Tu(n,e){if(!oc.existsSync(n))throw new Error(`Apply file list not found: ${n}`);let r=oc.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=sc.resolve(e),o=new Set,s=[];for(let a of r){let c=sc.resolve(i,a),l=P.isPathContainedWithSymlink(a,i);if(!l.contained){if(P.isPathContained(a,i).contained&&!oc.existsSync(c))throw new Error(`File not found: ${a}`);let d=l.reason?`; ${l.reason}`:"";throw new Error(`File path is outside the project directory: ${a}${d}`)}o.has(c)||(o.add(c),s.push(c))}return s}import ac from"fs";import zr from"path";import{execa as _v}from"execa";import ku from"fs";import*as xu from"path";import Ov from"json5";function Mv(n,e){try{let r=Ov.parse(ku.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 To(n,e){let t=xu.join(n,"build-profile.json5");return ku.existsSync(t)?Mv(t,e)??e:e}async function Lu(n,e,t,r){let i=zr.dirname(n.javaPath),o={...process.env,PATH:`${i}${zr.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 _v(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=>jv(e,l,r))}function Nu(n,e,t){let r=To(n,e);return zr.join(n,r,"build",t,"outputs")}function Fv(n,e,t){return zr.join(Nu(n,e,t),`${e}-${t}-signed.hqf`)}function jv(n,e,t){let r=Nu(n,e,t),i=Fv(n,e,t);if(ac.existsSync(i))return i;let o=cc(r,"-signed.hqf")??cc(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 cc(n,e){if(!ac.existsSync(n))return null;for(let t of ac.readdirSync(n,{withFileTypes:!0})){let r=zr.join(n,t.name);if(t.isDirectory()){let i=cc(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 lc from"json5";var Ou="default",ko=class n{static writeChangedFileLists(e,t,r,i){let o=t||Ou,s=n.loadBuildProfile(e);if(!s)return{writtenModules:[],skippedFiles:r};let a=s.modules,c=n.filterRunnableModules(e,a);if(c.length===0)return{writtenModules:[],skippedFiles:r};let l=n.buildReverseDependencyMap(e,a),d=n.createCollectors(c),h=n.collectChanges(r,e,a,l,d);return{writtenModules:n.flushCollectors(e,o,c,d,i),skippedFiles:h}}static initEmptyChangedFileLists(e,t,r){let i=t||Ou,o=n.loadBuildProfile(e);if(!o)return[];let s=o.modules,a=[];for(let c of s){let l=n.getModuleType(e,c.srcPath);if(l!=="entry"&&l!=="shared")continue;let d=!r||c.name===r;n.initEmptyForModule(e,i,c.srcPath,d),a.push(c.name)}return a}static filterRunnableModules(e,t){return t.filter(r=>{let i=n.getModuleType(e,r.srcPath);return i==="entry"||i==="shared"})}static createCollectors(e){let t=new Map;for(let r of e)t.set(r.name,{hotReloadEntries:[],patchEtsFiles:[],patchRawFiles:[],patchResFiles:[]});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 d=n.findModuleByFilePath(c,t,r);if(!d){s.push(c);continue}let h=n.resolveTargetModules(d,t,r,i);if(h.length===0){s.push(c);continue}n.dispatchToCollectors(h,o,c,l,d.srcPath,t)}return s}static resolveTargetModules(e,t,r,i){let o=n.getModuleType(t,e.srcPath);return o==="entry"||o==="shared"?[e.name]:Array.from(n.findTopLevelConsumers(e.name,i,t,r))}static dispatchToCollectors(e,t,r,i,o,s){for(let a of e){let c=t.get(a);c&&n.addFileToCollector(c,r,i.fileClass,o,s)}}static flushCollectors(e,t,r,i,o){let s=[];for(let a of r){let c=i.get(a.name);if(!c||!n.hasAnyChange(c))continue;(!o||a.name===o)&&c.hotReloadEntries.length>0&&n.writeApplyFile(e,a.srcPath,t,c.hotReloadEntries),n.writePatchFile(e,a.srcPath,t,c.patchEtsFiles,c.patchRawFiles,c.patchResFiles),s.push(a.name)}return s}static hasAnyChange(e){return e.hotReloadEntries.length>0||e.patchEtsFiles.length>0||e.patchRawFiles.length>0||e.patchResFiles.length>0}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 lc.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 lc.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=lc.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(h=>h.name===c);if(!l)continue;let d=n.getModuleType(r,l.srcPath);(d==="entry"||d==="shared")&&o.add(c),d==="har"&&s.push(c)}}static addFileToCollector(e,t,r,i,o){let s=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),d=x.join(e,a,"src","main","ets"),h=i.map(xt=>n.resolveRelativePathForPatch(xt,d)),w=n.mergeStrings(l.modifiedFiles,h),E=n.mergePatchResources(l.rawFile,o),N=n.mergePatchResources(l.resFile,s),he=x.dirname(c);B.existsSync(he)||B.mkdirSync(he,{recursive:!0}),B.writeFileSync(c,JSON.stringify({resources:{resFile:N,rawFile:E},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 Hv from"fs";import{randomUUID as $v}from"crypto";import{execa as Uv}from"execa";var xo=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,r){for(let a of t)if(!Hv.existsSync(a)){let c=`Signed hqf file not found: ${a}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}let o=`/data/local/tmp/${$v()}`,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 Uv(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}};var Bv="6.1.1",Lo=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}toolProvider;projectRoot;async execute(e){await dn(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion(Bv);let t=Tu(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=ko.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 Lu(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 xo(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 $n(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 Mu from"fs";import*as j from"path";var No=class n{static generate(e,t,r,i){let o=To(e,t),s=j.join(e,o),a=j.join(s,"build","config"),c=n.buildConfig(e,s,r,i);Mu.mkdirSync(a,{recursive:!0}),Mu.writeFileSync(j.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=j.dirname(i.nodePath)+j.sep,s=j.join(t,"build",r),a=j.join(s,"intermediates"),c=j.join(a,"loader_out",r),l=j.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:o,projectProfilePath:j.join(e,"build-profile.json5"),localPropertiesPath:j.join(e,"local.properties"),appResource:j.join(l,"ResourceTable.txt"),cachePath:j.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:j.join(a,"loader",r,"loader.json"),aceModuleJsonPath:j.join(l,"module.json"),aceSoPath:j.join(c,"nativeDependencies.txt"),aceModuleRoot:j.join(t,"src","main","ets"),aceModuleBuild:j.join(c,"ets"),aceProfilePath:j.join(l,"resources","base","profile"),aceSuperVisualPath:j.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:j.join(c,"ets"),changedFileList:j.join(a,"patch","default","changedFileList.json"),patchAbcPath:j.join(a,"patch","default","ets"),removeChangedFileListInSdk:"true"}}}};function zv(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 Fu(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 Vv(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>...].
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 jn(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=yn(e),r,i;try{let o=await jn(this.hdcPath,e,[...Vu]);r=this.extractDisplayName(o),i=o.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:i}}};var Hn=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=Q.from(e)}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;m(`Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await Xv(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/${Zv()}`;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 wc from"fs";import*as vc from"path";function zu(n,e){if(!wc.existsSync(n))throw new Error(`Apply file list not found: ${n}`);let r=wc.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=vc.resolve(e),o=new Set,s=[];for(let a of r){let c=vc.resolve(i,a),l=C.isPathContainedWithSymlink(a,i);if(!l.contained){if(C.isPathContained(a,i).contained&&!wc.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 Sc from"fs";import Gr from"path";import{execa as tS}from"execa";import qu from"fs";import*as Yu from"path";import Qv from"json5";function eS(n,e){try{let r=Qv.parse(qu.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 No(n,e){let t=Yu.join(n,"build-profile.json5");return qu.existsSync(t)?eS(t,e)??e:e}async function Ju(n,e,t,r){let i=Gr.dirname(n.javaPath),o={...process.env,PATH:`${i}${Gr.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 tS(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=>rS(e,l,r))}function Ku(n,e,t){let r=No(n,e);return Gr.join(n,r,"build",t,"outputs")}function nS(n,e,t){return Gr.join(Ku(n,e,t),`${e}-${t}-signed.hqf`)}function rS(n,e,t){let r=Ku(n,e,t),i=nS(n,e,t);if(Sc.existsSync(i))return i;let o=bc(r,"-signed.hqf")??bc(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 bc(n,e){if(!Sc.existsSync(n))return null;for(let t of Sc.readdirSync(n,{withFileTypes:!0})){let r=Gr.join(n,t.name);if(t.isDirectory()){let i=bc(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 Zu="default",Oo=class n{static writeChangedFileLists(e,t,r,i){let o=t||Zu,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||Zu,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(Tt=>n.resolveRelativePathForPatch(Tt,p)),w=n.mergeStrings(l.modifiedFiles,g),E=n.mergePatchResources(l.rawFile,o),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:O,rawFile:E},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 iS from"fs";import{randomUUID as oS}from"crypto";import{execa as sS}from"execa";var Mo=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,r){for(let a of t)if(!iS.existsSync(a)){let c=`Signed hqf file not found: ${a}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}let o=`/data/local/tmp/${oS()}`,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 sS(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}};var aS="6.1.1",_o=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}toolProvider;projectRoot;async execute(e){await un(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion(aS);let t=zu(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=Oo.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 Ju(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 Mo(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 Hn(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 Xu from"fs";import*as j from"path";var Fo=class n{static generate(e,t,r,i){let o=No(e,t),s=j.join(e,o),a=j.join(s,"build","config"),c=n.buildConfig(e,s,r,i);Xu.mkdirSync(a,{recursive:!0}),Xu.writeFileSync(j.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=j.dirname(i.nodePath)+j.sep,s=j.join(t,"build",r),a=j.join(s,"intermediates"),c=j.join(a,"loader_out",r),l=j.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:o,projectProfilePath:j.join(e,"build-profile.json5"),localPropertiesPath:j.join(e,"local.properties"),appResource:j.join(l,"ResourceTable.txt"),cachePath:j.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:j.join(a,"loader",r,"loader.json"),aceModuleJsonPath:j.join(l,"module.json"),aceSoPath:j.join(c,"nativeDependencies.txt"),aceModuleRoot:j.join(t,"src","main","ets"),aceModuleBuild:j.join(c,"ets"),aceProfilePath:j.join(l,"resources","base","profile"),aceSuperVisualPath:j.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:j.join(c,"ets"),changedFileList:j.join(a,"patch","default","changedFileList.json"),patchAbcPath:j.join(a,"patch","default","ets"),removeChangedFileListInSdk:"true"}}}};function dS(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 ep(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 uS(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>...].
34
34
  Available runnable modules:
35
35
  `+t.map(r=>` - ${r.name}`).join(`
36
- `))}function qv(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 Yv(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(_u(`
36
+ `))}function pS(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 fS(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(Qu(`
38
38
  Application '${t}': ${s}`))}else console.log(`
39
- Application '${t}' installed successfully (no ability to launch).`)}var Jv=new Wv("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 Xv(n)}catch(e){console.error(Gv(e.message)),process.exit(1)}});async function Kv(n,e,t,r,i){let o=new On(e,n.rootDir),s=new mt(e,n.rootDir),a=new Set,c=new Set;for(let{moduleName:w,targetName:E}of t)for(let N of n.collectNonHarDependentModuleList(w))a.add(`${N}@${E}`),c.add(N);let l=[...a],d=tc(n,l),h={type:"modules",modulesToBuild:l,moduleTasks:d};for(let w of c)No.generate(n.rootDir,w,r,e);await dn(n.rootDir,()=>nc(o,s,r,i,h,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion...")),console.log(`
40
- `+_u("Build completed successfully."))}async function Xv(n){let e=U.discover(process.cwd());console.warn(Oo("Ensure the project source is trusted before proceeding."));let t=await I.new();if(n.skipBuild||t.assertJava(),n.apply){await Qv(n,e,t);return}await ju(n,e,t)}function Zv(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 ju(n,e,t){let i=Vv(e,n.module).map(zv);for(let{moduleName:N}of i){let he=e.getModuleType(N);if(he!=="entry"&&he!=="feature"&&he!=="shared")throw new Error(`Module '${N}' '${he}' is not runnable. Specify an entry or feature module.`)}let o=new $n(t),s=Q.from(t),a=await Fu(s,n.device),c=a.includes("127.0.0.1")||a.includes("localhost"),l=n.product||"default";e.validateProduct(l);let d=n.buildMode||"debug";n.skipBuild||await Kv(e,t,i,l,d);let h=Zv(e,i,c,l),w=e.getBundleName(),E=qv(e,i,n.ability);await Yv(o,a,w,h,E,!!n.uninstall)}async function Qv(n,e,t){let r=n.apply;if(!r)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(Mo.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let i=Mo.join(e.rootDir,".hvigor",r),o=Q.from(t),s=await Fu(o,n.device),a=n.product||"default";e.validateProduct(a);let c=e.getBundleName(),l=e.profile.modules.find(w=>e.getModuleType(w.name)==="entry")?.name,d=l?e.getMainAbility(l,n.ability):n.ability||"EntryAbility",h=new Lo(t,e.rootDir);try{await h.execute({applyFile:i,productName:a,targetDeviceId:s,bundleName:c,abilityName:d}),console.log(Oo("[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(Oo(`[Apply] \u5931\u8D25\uFF1A${w.message}`)),console.warn(Oo("[Apply] \u81EA\u52A8\u56DE\u9000\u5230\u5168\u91CF devecocli run..."))}await ju(n,e,t)}var Hu=Jv;import{Command as eS}from"commander";import{green as $u,red as Uu,cyan as dc}from"colorette";import{execa as Bu}from"execa";function tS(){return"latest"}function nS(){return"@deveco-test/deveco-cli"}function rS(){return"1.3.0-Test.8"}var iS=new eS("update").description("Update deveco-cli to latest").action(async()=>{let n=nS(),e=rS(),t=tS();console.log(dc("Checking for updates..."));try{let{stdout:r}=await Bu("npm",["view",n,`dist-tags.${t}`]),i=r.trim();if(!i||i===e){console.log($u(`
41
- ${n} is already up to date (v${e}, tag: ${t})`));return}console.log(dc(`
42
- New version found: ${i} (current: ${e})`)),console.log(dc(`Updating ${n}...`)),await Bu("npm",["install","-g",`${n}@${t}`],{stdio:"inherit"}),console.log(`
43
- `+$u(`${n} updated successfully to version ${i}.`))}catch(r){let i=r;console.error(Uu(`Failed to update ${n}`)),i.message&&console.error(Uu(i.message)),process.exit(1)}}),Wu=iS;import{Command as xS}from"commander";import{execa as Fo}from"execa";function de(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as oS}from"child_process";var sS=2500;function aS(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 cS(n,e,t,r){let i=!1,o=()=>i,s=()=>Buffer.concat(e).toString("utf8").trim(),a=()=>{i||(i=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners(),n.stderr?.destroy(),n.unref(),t())},c=d=>{if(!i){i=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners();try{n.kill()}catch{}r(new Error(d))}},l=setTimeout(a,sS);n.once("error",d=>c(d.message)),aS(n,l,s,a,c,o)}function Gu(n,e,t){return m(`Spawning emulator: ${n} ${t.join(" ")}`),new Promise((r,i)=>{let o=[],s=oS(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)),cS(s,o,r,i)})}import*as Un from"path";function lS(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 dS(n){let e=n.instancePath?.trim();if(e)return Un.dirname(Un.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?Un.dirname(Un.normalize(t)).replace(/\\/g,"/"):""}function uS(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function zu(n,e){return e?[...n,"-bootmode",e]:n}function pS(n,e,t){let r=[zu(["-start",n],t)],i=dS(e);if(i)for(let o of uS(e.imageRoot))r.push(zu(["-hvd",n,"-path",i,...o],t));return lS(r)}async function Vu(n,e,t,r){let i=new Error("No start strategy ran"),o=pS(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 uc(n){return(await Q.withHdcPath(n).listDevices()).map(t=>t.serial).filter(gn)}async function pc(n){let e=await uc(n);return e.length===0?[]:(await Promise.all(e.map(r=>Ro(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function qu(n,e){return(await pc(n)).includes(e)}import*as Wn from"path";import{existsSync as fS,statSync as mS}from"fs";function Bn(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function hS(n){let e=Bn(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 gS(n){return Bn(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function yS(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=Wn.dirname(Wn.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let i=Wn.join(t,r.name);fS(i)&&mS(i).isDirectory()&&(r.instancePath=i.replace(/\\/g,"/"))}}function wS(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=gS(t),i=Bn(t,["deviceType","DeviceType","devicetype"]),o=Bn(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:hS(t),path:Bn(t,["path","Path","hvdPath","hvd_path"]),imageRoot:Bn(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 vS(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 Yu(n){let t=wS(n)??vS(n);return yS(t),t}function fc(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function SS(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function ES(n){if(!SS(n))return null;let e=fc(n,["osVersion","OsVersion","OSVersion"]),t=fc(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=fc(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function _o(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=ES(i);o&&r.push(o)}return r}catch{return[]}}function Ju(n){let t=_o(n).map(r=>r.osVersion).filter(Boolean);return[...new Set(t)]}var Ku=/no images are available/i,bS="7.0.0",PS={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 Ze(n){return n.normalize("NFKC").trim().toLowerCase()}function CS(n,e){let t=n.deviceType?.trim(),r=t?PS[Ze(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 IS(n){let e=n.message||"";return Ku.test(e)}function AS(n){return n.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function Vr(n,e){return`${n} ${e.join(" ")}`.trim()}function DS(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 Gn=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: ${Vr(this.emulatorPath,e)}`),Fo(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return Gu(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return Yu(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 Vu(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:qu(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"&&CS(i,t.state);let o=this.buildControlArgs(i.name,t);m(`[EmulatorManager] control ${DS(t)} -> ${Vr(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: ${Vr(this.emulatorPath,t)}`);let{stdout:r,stderr:i,exitCode:o}=await Fo(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=AS(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,bS)<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)]}}async executeEmulatorInherit(e){m(`Executing: ${Vr(this.emulatorPath,e)}`);let{exitCode:t}=await Fo(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(!IS(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 Ju(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=_o(t),i=Ze(e.deviceType),o=Ze(e.osVersion);return r.filter(s=>Ze(s.deviceType)===i&&(Ze(s.osVersion)===o||Ze(s.softwareVersion)===o))}async hasDownloadedSystemImage(e,t){let r=await this.listEmulatorImages({downloaded:!0}),i=_o(r),o=Ze(t),s=e?.trim()?Ze(e):void 0;return i.some(a=>Ze(a.osVersion)===o||Ze(a.softwareVersion)===o?s===void 0?!0:Ze(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:[Ku]})}async runEmulatorChecked(e,t){m(`Executing: ${Vr(this.emulatorPath,e)}`);let{stdout:r,stderr:i,exitCode:o}=await Fo(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(d=>d.test(s));if(o!==0||a||c)throw new Error(s||`emulator exited with code ${o===null?"null":o}`);if(t?.printOutputOnSuccess!==!1&&s){let d=(t?.transformOutput?t.transformOutput(s):s).trim();d&&console.log(d)}}async checkExistingVirtualDevice(e,t){let r=await this.listEmulators(),i=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(`
39
+ Application '${t}' installed successfully (no ability to launch).`)}var mS=new cS("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 gS(n)}catch(e){console.error(lS(e.message)),process.exit(1)}});async function hS(n,e,t,r,i){let o=new On(e,n.rootDir),s=new pt(e,n.rootDir),a=new Set,c=new Set;for(let{moduleName:w,targetName:E}of t)for(let O of n.collectNonHarDependentModuleList(w))a.add(`${O}@${E}`),c.add(O);let l=[...a],p=mc(n,l),g={type:"modules",modulesToBuild:l,moduleTasks:p};for(let w of c)Fo.generate(n.rootDir,w,r,e);await un(n.rootDir,()=>hc(o,s,r,i,g,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion...")),console.log(`
40
+ `+Qu("Build completed successfully."))}async function gS(n){let e=U.discover(process.cwd());console.warn(jo("Ensure the project source is trusted before proceeding."));let t=await I.new();if(n.skipBuild||t.assertJava(),n.apply){await wS(n,e,t);return}await tp(n,e,t)}function yS(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 tp(n,e,t){let i=uS(e,n.module).map(dS);for(let{moduleName:O}of i){let fe=e.getModuleType(O);if(fe!=="entry"&&fe!=="feature"&&fe!=="shared")throw new Error(`Module '${O}' '${fe}' is not runnable. Specify an entry or feature module.`)}let o=new Hn(t),s=Q.from(t),a=await ep(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 hS(e,t,i,l,p);let g=yS(e,i,c,l),w=e.getBundleName(),E=pS(e,i,n.ability);await fS(o,a,w,g,E,!!n.uninstall)}async function wS(n,e,t){let r=n.apply;if(!r)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(Ho.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let i=Ho.join(e.rootDir,".hvigor",r),o=Q.from(t),s=await ep(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 _o(t,e.rootDir);try{await g.execute({applyFile:i,productName:a,targetDeviceId:s,bundleName:c,abilityName:p}),console.log(jo("[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(jo(`[Apply] \u5931\u8D25\uFF1A${w.message}`)),console.warn(jo("[Apply] \u81EA\u52A8\u56DE\u9000\u5230\u5168\u91CF devecocli run..."))}await tp(n,e,t)}var np=mS;import{Command as DS}from"commander";import*as lp from"path";import{green as ap,red as cp,cyan as Ic}from"colorette";import{execa as Ac}from"execa";import{spawn as PS}from"child_process";import*as sp from"fs";import*as Bo from"path";import{yellow as CS}from"colorette";import IS from"proper-lockfile";import*as _t from"fs";import*as rp from"path";import{homedir as vS}from"os";var SS="deveco-cli",Pc,wn=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function bS(){let n=process.env.DEVECO_CLI_DATA_DIR;return n!==void 0&&co(n)!==""}function ip(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":co(n))||rp.join(vS(),".local","share",SS);try{return lo(t)}catch(r){throw new wn(r instanceof Error?r.message:String(r))}}async function op(){let n=ip();await _t.promises.mkdir(n,{recursive:!0});let e;try{e=await _t.promises.realpath(n)}catch(r){throw new wn(`DEVECO_CLI_DATA_DIR is not usable: ${r instanceof Error?r.message:String(r)}`)}if(!(await _t.promises.stat(e)).isDirectory())throw new wn("DEVECO_CLI_DATA_DIR must be a writable directory.");return Pc=e,e}function $o(n){let e=Me();return bS()?[`Data directory (DEVECO_CLI_DATA_DIR): ${e}`,"If you changed this in System Environment Variables, open a new terminal and retry.",`Log file: ${n}`]:[`Data directory (default): ${e}`,"To use a custom location, set DEVECO_CLI_DATA_DIR and open a new terminal.",`Log file: ${n}`]}function Me(){if(Pc!==void 0)return Pc;let n=ip();try{if(_t.existsSync(n))return _t.realpathSync(n)}catch{}return n}function Uo(){return"@deveco-test/deveco-cli"}function Ft(){return"1.3.0-Test.9"}function $n(){return"tmp"}function Un(){let n=process.env.DEVECO_CLI_DISABLE_UPDATE;return n==="check"||n==="all"?n:"off"}import*as Vr from"fs";import*as zr from"path";var ES={lastCheckedTimestamp:null,latestVersion:null,blockedVersions:[],checkError:null},Cc=new Map,jt=class n{static CHECK_WINDOW_HOUR=21;static ONE_DAY_MS=1440*60*1e3;cacheFilePath;lockFilePath;constructor(e){this.cacheFilePath=zr.join(e,"cache.json"),this.lockFilePath=zr.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=Cc.get(this.cacheFilePath);if(e)return e;try{let t=Vr.readFileSync(this.cacheFilePath,"utf-8"),r=JSON.parse(t);return Cc.set(this.cacheFilePath,r),r}catch{return{...ES}}}async write(e){m(()=>`Writing update cache: lastChecked=${e.lastCheckedTimestamp}, latest=${e.latestVersion}, blocked=[${e.blockedVersions.join(",")}], error=${e.checkError}`),await Vr.promises.mkdir(zr.dirname(this.cacheFilePath),{recursive:!0}),await Vr.promises.writeFile(this.cacheFilePath,JSON.stringify(e,null,2),"utf-8"),Cc.set(this.cacheFilePath,e)}};var qr=class{constructor(e){this.actionCommand=e}actionCommand;cache=new jt(Bo.join(Me(),"update"));async checkAndNotify(){if(!this.shouldSkip())try{let e=Ft(),t=$n(),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&&tu(a,e)>0&&(console.log(),console.log(CS(`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 AS(this.cache.getLockPath(),()=>{let e=[process.argv[1],"update","_check"];m(`Executing: ${process.execPath} ${e.join(" ")}`),PS(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 AS(n,e){await sp.promises.mkdir(Bo.dirname(n),{recursive:!0});let t=await IS.lock(n,{stale:6e4,retries:0,realpath:!1});try{await e()}finally{await t()}}var Dc=new DS("update").description("Update deveco-cli to latest");Dc.command("_check",{hidden:!0}).action(async()=>{let n=new jt(lp.join(Me(),"update"));try{let e=$n(),t=Uo();m(`Executing: npm view ${t}@${e} --json`);let{stdout:r}=await Ac("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,Ft(),e)}catch(e){await n.writeError(e instanceof Error?e.message:String(e))}});Dc.action(async()=>{if(Un()==="all")throw new Error("devecocli update is disabled (DEVECO_CLI_DISABLE_UPDATE=all).");let n=Ft(),e=$n();console.log(Ic("Checking for updates..."));let t=Uo();try{let{stdout:r}=await Ac("npm",["view",t,`dist-tags.${e}`]),i=r.trim();if(!i||i===n){console.log(ap(`
41
+ ${t} is already up to date (v${n}, tag: ${e})`));return}console.log(Ic(`
42
+ New version found: ${i} (current: ${n})`)),console.log(Ic(`Updating ${t}...`)),await Ac("npm",["install","-g",`${t}@${e}`],{stdio:"inherit"}),console.log(`
43
+ `+ap(`${t} updated successfully to version ${i}.`))}catch(r){let i=r;console.error(cp(`Failed to update ${t}`)),i.message&&console.error(cp(i.message)),process.exit(1)}});var dp=Dc;import{Command as eb}from"commander";import{execa as Go}from"execa";function de(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as kS}from"child_process";var RS=2500;function TS(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 xS(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,RS);n.once("error",p=>c(p.message)),TS(n,l,s,a,c,o)}function up(n,e,t){return m(`Spawning emulator: ${n} ${t.join(" ")}`),new Promise((r,i)=>{let o=[],s=kS(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)),xS(s,o,r,i)})}import*as Bn from"path";function LS(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 NS(n){let e=n.instancePath?.trim();if(e)return Bn.dirname(Bn.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?Bn.dirname(Bn.normalize(t)).replace(/\\/g,"/"):""}function OS(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function pp(n,e){return e?[...n,"-bootmode",e]:n}function MS(n,e,t){let r=[pp(["-start",n],t)],i=NS(e);if(i)for(let o of OS(e.imageRoot))r.push(pp(["-hvd",n,"-path",i,...o],t));return LS(r)}async function fp(n,e,t,r){let i=new Error("No start strategy ran"),o=MS(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 kc(n){return(await Q.withHdcPath(n).listDevices()).map(t=>t.serial).filter(yn)}async function Rc(n){let e=await kc(n);return e.length===0?[]:(await Promise.all(e.map(r=>Lo(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function mp(n,e){return(await Rc(n)).includes(e)}import*as Gn from"path";import{existsSync as _S,statSync as FS}from"fs";function Wn(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function jS(n){let e=Wn(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 HS(n){return Wn(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function $S(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=Gn.dirname(Gn.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let i=Gn.join(t,r.name);_S(i)&&FS(i).isDirectory()&&(r.instancePath=i.replace(/\\/g,"/"))}}function US(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=HS(t),i=Wn(t,["deviceType","DeviceType","devicetype"]),o=Wn(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:jS(t),path:Wn(t,["path","Path","hvdPath","hvd_path"]),imageRoot:Wn(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 BS(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 hp(n){let t=US(n)??BS(n);return $S(t),t}function Tc(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function WS(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function GS(n){if(!WS(n))return null;let e=Tc(n,["osVersion","OsVersion","OSVersion"]),t=Tc(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=Tc(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function Wo(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=GS(i);o&&r.push(o)}return r}catch{return[]}}function gp(n){let t=Wo(n).map(r=>r.osVersion).filter(Boolean);return[...new Set(t)]}var yp=/no images are available/i,VS="7.0.0",zS={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 Ke(n){return n.normalize("NFKC").trim().toLowerCase()}function qS(n,e){let t=n.deviceType?.trim(),r=t?zS[Ke(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 YS(n){let e=n.message||"";return yp.test(e)}function JS(n){return n.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function Yr(n,e){return`${n} ${e.join(" ")}`.trim()}function KS(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 Vn=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: ${Yr(this.emulatorPath,e)}`),Go(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return up(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return hp(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 fp(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:mp(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"&&qS(i,t.state);let o=this.buildControlArgs(i.name,t);m(`[EmulatorManager] control ${KS(t)} -> ${Yr(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: ${Yr(this.emulatorPath,t)}`);let{stdout:r,stderr:i,exitCode:o}=await Go(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=JS(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,VS)<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: ${Yr(this.emulatorPath,e)}`);let{exitCode:t}=await Go(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(!YS(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 gp(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=Wo(t),i=Ke(e.deviceType),o=Ke(e.osVersion);return r.filter(s=>Ke(s.deviceType)===i&&(Ke(s.osVersion)===o||Ke(s.softwareVersion)===o))}async hasDownloadedSystemImage(e,t){let r=await this.listEmulatorImages({downloaded:!0}),i=Wo(r),o=Ke(t),s=e?.trim()?Ke(e):void 0;return i.some(a=>Ke(a.osVersion)===o||Ke(a.softwareVersion)===o?s===void 0?!0:Ke(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:[yp]})}async runEmulatorChecked(e,t){m(`Executing: ${Yr(this.emulatorPath,e)}`);let{stdout:r,stderr:i,exitCode:o}=await Go(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
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 mc,yellow as Zu,gray as Qu}from"colorette";import LS from"ora";import{red as RS}from"colorette";function jo(n,e){n?n.fail(e):console.error(RS(e)),process.exit(1)}import{green as TS}from"colorette";function Xu(n,e){return n+" ".repeat(Math.max(0,e-n.length))}function kS(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 yt(n,e){let t=kS(n,e),r=[];r.push(n.map((i,o)=>Xu(i,t[o])).join(" ")),r.push(t.map(i=>"-".repeat(i)).join(" "));for(let i of e){let o=i.cells.map((s,a)=>Xu(s??"",t[a])).join(" ").trimEnd();r.push(i.highlight?TS(o):o)}return r.join(`
50
- `)}function NS(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 OS=["Name","Serial","Kind","Device Type"];function MS(n){return{cells:[n.name??n.serial,n.serial,n.isEmulator?"emulator":"device",n.deviceType??"-"],highlight:!0}}function _S(n,e){return n.isEmulator!==e.isEmulator?n.isEmulator?1:-1:(n.name??n.serial).localeCompare(e.name??e.serial)}function FS(){console.log(Zu(" No active devices.")),console.log(Qu(" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function jS(n){let t=[...n].sort(_S).map(MS);console.log(yt(OS,t))}async function HS(n,e){if(!n.some(i=>i.isEmulator)||!e.emulatorPath)return;let r=await Gn.from(e).getDeviceTypeByName();NS(n,r)}async function $S(n,e,t){try{let r=await n.getConnectedEntries();await HS(r,e),t?.stop(),r.length===0?FS():jS(r)}catch(r){jo(t,`Failed to list devices: ${r.message}`)}}async function US(n,e){let t=await n.listDevices();if(!(t.length<2)){console.error(mc("Multiple devices connected. Specify a device with:"));for(let r of t){let i=await n.getDeviceName(r.serial);console.error(Qu(` ${e} -t ${r.serial} # ${i}`))}process.exit(1)}}async function BS(n,e){try{e||await US(n,"devecocli device view");let t=await n.listDevices(),r=await n.getDeviceInfo(t,e);r||(console.log(Zu("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(mc(`Failed to show device details: ${t.message}`)),process.exit(1)}}async function ep(){try{let n=await I.new();return{manager:Q.from(n),toolProvider:n}}catch(n){console.error(mc(`Failed to initialize device manager: ${n.message}`)),process.exit(1);return}}var hc=new xS("device").description("Manage connected devices");hc.command("list").description("List all connected devices").action(async()=>{let{manager:n,toolProvider:e}=await ep(),t=LS({text:"Querying connected devices\u2026",color:"cyan"}).start();await $S(n,e,t)});hc.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").action(async n=>{let{manager:e}=await ep();await BS(e,n.target)});var tp=hc;import{Argument as bc,Command as Pc,Option as Kr}from"commander";import{green as Xr,cyan as Vn,red as ye,yellow as lt,gray as Jr}from"colorette";import iE from"ora";import WS from"readline/promises";import{execa as rp}from"execa";import*as Ft from"fs/promises";import*as yc from"os";import*as yn from"path";var gc=`1/4:\r
49
+ The device may be running.`);return await this.runEmulatorChecked(["-delete",o,"-force"],{printOutputOnSuccess:!1}),o}};import{red as xc,yellow as vp,gray as Sp}from"colorette";import tb from"ora";import{red as ZS}from"colorette";function Vo(n,e){n?n.fail(e):console.error(ZS(e)),process.exit(1)}import{green as XS}from"colorette";function wp(n,e){return n+" ".repeat(Math.max(0,e-n.length))}function QS(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 ht(n,e){let t=QS(n,e),r=[];r.push(n.map((i,o)=>wp(i,t[o])).join(" ")),r.push(t.map(i=>"-".repeat(i)).join(" "));for(let i of e){let o=i.cells.map((s,a)=>wp(s??"",t[a])).join(" ").trimEnd();r.push(i.highlight?XS(o):o)}return r.join(`
50
+ `)}function nb(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 rb=["Name","Serial","Kind","Device Type"];function ib(n){return{cells:[n.name??n.serial,n.serial,n.isEmulator?"emulator":"device",n.deviceType??"-"],highlight:!0}}function ob(n,e){return n.isEmulator!==e.isEmulator?n.isEmulator?1:-1:(n.name??n.serial).localeCompare(e.name??e.serial)}function sb(){console.log(vp(" No active devices.")),console.log(Sp(" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function ab(n){let t=[...n].sort(ob).map(ib);console.log(ht(rb,t))}async function cb(n,e){if(!n.some(i=>i.isEmulator)||!e.emulatorPath)return;let r=await Vn.from(e).getDeviceTypeByName();nb(n,r)}async function lb(n,e,t){try{let r=await n.getConnectedEntries();await cb(r,e),t?.stop(),r.length===0?sb():ab(r)}catch(r){Vo(t,`Failed to list devices: ${r.message}`)}}async function db(n,e){let t=await n.listDevices();if(!(t.length<2)){console.error(xc("Multiple devices connected. Specify a device with:"));for(let r of t){let i=await n.getDeviceName(r.serial);console.error(Sp(` ${e} -t ${r.serial} # ${i}`))}process.exit(1)}}async function ub(n,e){try{e||await db(n,"devecocli device view");let t=await n.listDevices(),r=await n.getDeviceInfo(t,e);r||(console.log(vp("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(xc(`Failed to show device details: ${t.message}`)),process.exit(1)}}async function bp(){try{let n=await I.new();return{manager:Q.from(n),toolProvider:n}}catch(n){console.error(xc(`Failed to initialize device manager: ${n.message}`)),process.exit(1);return}}var Lc=new eb("device").description("Manage connected devices");Lc.command("list").description("List all connected devices").action(async()=>{let{manager:n,toolProvider:e}=await bp(),t=tb({text:"Querying connected devices\u2026",color:"cyan"}).start();await lb(n,e,t)});Lc.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").action(async n=>{let{manager:e}=await bp();await ub(e,n.target)});var Ep=Lc;import{Argument as Hc,Command as $c,Option as Xr}from"commander";import{green as Qr,cyan as qn,red as me,yellow as at,gray as Zr}from"colorette";import Db from"ora";import pb from"readline/promises";import{execa as Cp}from"execa";import*as Ht from"fs/promises";import*as Oc from"os";import*as vn from"path";var Nc=`1/4:\r
51
51
  ---------------------------------------\r
52
52
  Statement About HarmonyOS and Privacy\r
53
53
  \r
@@ -1217,13 +1217,13 @@ Part I: Chinese mainland.\r
1217
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
1218
1218
  \r
1219
1219
  Part III: Other countries and regions.\r
1220
- ---------------------------------------\r`;var GS=new Set,Ho=new Map,wc="HarmonyOS_Software_Service_Agreement",ip=["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
- `),op=ip,vc="HarmonyOS_SDK_Agreement";function sp(n,e){return`${n}\0${e}`}function ap(){GS.clear(),Ho.clear()}var zS=ip,_e=class extends Error{constructor(e=zS){super(e),this.name="EmulatorLicenseBlockedError"}};function cp(n,e){return[n??"",e??""].join(`
1222
- `)}function lp(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 VS(n){return`Emulator${n.trim()}`}function dp(n){let e=VS(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 yn.join(r,"Huawei",e,".emu_config")}if(process.platform==="darwin")return yn.join(yc.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||yn.join(yc.homedir(),".cache");return yn.join(t,"Huawei",e,".emu_config")}async function qS(n,e,t){let r=sp(n,e),i=Ho.get(r);if(i!==void 0)return i;let o=await rp(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=cp(o.stdout,o.stderr).trim();if(o.exitCode!==0||!s)throw new _e(t);return Ho.set(r,s),s}function YS(n){let e=n[0],t=n[n.length-1];return(e==='"'||e==="'")&&e===t?n.slice(1,-1):n}function JS(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 KS(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=YS(e.slice(r+1).trim());return{key:i,entry:{value:o,delimiter:t}}}}function XS(n){let e={};for(let t of n.split(/\r?\n/)){let r=KS(t);r&&(e[r.key]=r.entry)}return e}function ZS(n){let e=n.trim();if(!e)return{};let t=JS(e);return t||XS(n)}function QS(n){return typeof n!="string"?!1:n.normalize("NFKC").trim().toLowerCase()==="agree"}async function up(n,e,t,r){let i=await qS(n,e,r),o=lp(i);if(!o)throw new _e(r);let s=dp(o),a;try{a=await Ft.readFile(s,"utf8")}catch(d){throw d.code==="ENOENT"?new _e(r):d}let l=ZS(a)[t];if(!l)throw new _e(r);if(l.delimiter==="=")throw new _e(r);if(!QS(l.value))throw new _e(r)}async function Sc(n,e){await up(n,e,wc,op)}async function Ec(n,e){await up(n,e,vc,op)}async function eE(n,e){let t=await rp(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),r=cp(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=sp(n,e);return Ho.set(i,r),r}async function pp(n,e){let t=await eE(n,e),r=lp(t);if(!r)throw new Error(`Cannot parse Emulator major.minor from:
1223
- ${t}.`);return dp(r)}function np(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function tE(n,e,t){if(!t.startsWith("{"))return!1;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return r[wc]="agree",r[vc]="agree",await Ft.writeFile(n,`${JSON.stringify(r,null,2)}
1224
- `,"utf8"),!0}catch{}return!1}async function nE(n,e){let t=wc,r=vc,i=[{k:t,re:new RegExp(`^\\s*${np(t)}\\s*[:=]`)},{k:r,re:new RegExp(`^\\s*${np(r)}\\s*[:=]`)}],o=e.length===0?[]:e.split(/\r?\n/),s=[],a=new Set;for(let c of o){let l=!1;for(let{k:d,re:h}of i)if(h.test(c)){s.push(`${d}:agree`),a.add(d),l=!0;break}l||s.push(c)}a.has(t)||s.push(`${t}:agree`),a.has(r)||s.push(`${r}:agree`),await Ft.writeFile(n,s.join(`
1220
+ ---------------------------------------\r`;var fb=new Set,zo=new Map,Mc="HarmonyOS_Software_Service_Agreement",Ip=["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
+ `),Ap=Ip,_c="HarmonyOS_SDK_Agreement";function Dp(n,e){return`${n}\0${e}`}function kp(){fb.clear(),zo.clear()}var mb=Ip,_e=class extends Error{constructor(e=mb){super(e),this.name="EmulatorLicenseBlockedError"}};function Rp(n,e){return[n??"",e??""].join(`
1222
+ `)}function Tp(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 hb(n){return`Emulator${n.trim()}`}function xp(n){let e=hb(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 vn.join(r,"Huawei",e,".emu_config")}if(process.platform==="darwin")return vn.join(Oc.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||vn.join(Oc.homedir(),".cache");return vn.join(t,"Huawei",e,".emu_config")}async function gb(n,e,t){let r=Dp(n,e),i=zo.get(r);if(i!==void 0)return i;let o=await Cp(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=Rp(o.stdout,o.stderr).trim();if(o.exitCode!==0||!s)throw new _e(t);return zo.set(r,s),s}function yb(n){let e=n[0],t=n[n.length-1];return(e==='"'||e==="'")&&e===t?n.slice(1,-1):n}function wb(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 vb(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=yb(e.slice(r+1).trim());return{key:i,entry:{value:o,delimiter:t}}}}function Sb(n){let e={};for(let t of n.split(/\r?\n/)){let r=vb(t);r&&(e[r.key]=r.entry)}return e}function bb(n){let e=n.trim();if(!e)return{};let t=wb(e);return t||Sb(n)}function Eb(n){return typeof n!="string"?!1:n.normalize("NFKC").trim().toLowerCase()==="agree"}async function Lp(n,e,t,r){let i=await gb(n,e,r),o=Tp(i);if(!o)throw new _e(r);let s=xp(o),a;try{a=await Ht.readFile(s,"utf8")}catch(p){throw p.code==="ENOENT"?new _e(r):p}let l=bb(a)[t];if(!l)throw new _e(r);if(l.delimiter==="=")throw new _e(r);if(!Eb(l.value))throw new _e(r)}async function Fc(n,e){await Lp(n,e,Mc,Ap)}async function jc(n,e){await Lp(n,e,_c,Ap)}async function Pb(n,e){let t=await Cp(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),r=Rp(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=Dp(n,e);return zo.set(i,r),r}async function Np(n,e){let t=await Pb(n,e),r=Tp(t);if(!r)throw new Error(`Cannot parse Emulator major.minor from:
1223
+ ${t}.`);return xp(r)}function Pp(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function Cb(n,e,t){if(!t.startsWith("{"))return!1;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return r[Mc]="agree",r[_c]="agree",await Ht.writeFile(n,`${JSON.stringify(r,null,2)}
1224
+ `,"utf8"),!0}catch{}return!1}async function Ib(n,e){let t=Mc,r=_c,i=[{k:t,re:new RegExp(`^\\s*${Pp(t)}\\s*[:=]`)},{k:r,re:new RegExp(`^\\s*${Pp(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 Ht.writeFile(n,s.join(`
1225
1225
  `)+(s.length>0?`
1226
- `:""),"utf8")}async function fp(n){await Ft.mkdir(yn.dirname(n),{recursive:!0});let e="";try{e=await Ft.readFile(n,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}let t=e.trim();await tE(n,e,t)||await nE(n,e)}async function mp(n,e){return console.log(gc),0}var rE="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function hp(n,e){try{return await Sc(n,e),await Ec(n,e),!0}catch(t){if(t instanceof _e)return!1;throw t}}async function gp(n,e){if(await hp(n,e))return console.log("Emulator license agreements are already accepted."),0;if(console.log(gc),!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=WS.createInterface({input:process.stdin,output:process.stdout}),i;try{i=await r.question(rE)}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 pp(n,e);await fp(s),ap()}catch(s){return console.error(s.message),1}return console.log("Emulator license agreements accepted."),0}async function yp(n,e){if(await hp(n,e))return console.log("Emulator license agreements are already accepted."),0;try{let t=await pp(n,e);await fp(t),ap()}catch(t){return console.error(t.message),1}return console.log("Emulator license agreements accepted."),0}var oE=["ohos.qemu.hvd.name","const.product.name","const.product.model"],wp=["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"],sE=`
1226
+ `:""),"utf8")}async function Op(n){await Ht.mkdir(vn.dirname(n),{recursive:!0});let e="";try{e=await Ht.readFile(n,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}let t=e.trim();await Cb(n,e,t)||await Ib(n,e)}async function Mp(n,e){return console.log(Nc),0}var Ab="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function _p(n,e){try{return await Fc(n,e),await jc(n,e),!0}catch(t){if(t instanceof _e)return!1;throw t}}async function Fp(n,e){if(await _p(n,e))return console.log("Emulator license agreements are already accepted."),0;if(console.log(Nc),!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=pb.createInterface({input:process.stdin,output:process.stdout}),i;try{i=await r.question(Ab)}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 Np(n,e);await Op(s),kp()}catch(s){return console.error(s.message),1}return console.log("Emulator license agreements accepted."),0}async function jp(n,e){if(await _p(n,e))return console.log("Emulator license agreements are already accepted."),0;try{let t=await Np(n,e);await Op(t),kp()}catch(t){return console.error(t.message),1}return console.log("Emulator license agreements accepted."),0}var kb=["ohos.qemu.hvd.name","const.product.name","const.product.model"],Hp=["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"],Rb=`
1227
1227
  Folded state scene mappings:
1228
1228
  foldableFold (3):
1229
1229
  open Fully expanded state
@@ -1246,43 +1246,43 @@ Folded state scene mappings:
1246
1246
  left-half-folded-right-folded
1247
1247
  left-expanded-right-half-folded
1248
1248
  left-half-folded-right-half-folded
1249
- `;function aE(n){let e=n.trim();if(!e)throw new Error("--target must not be empty.");return e}function cE(n){let e=n.trim();if(!wp.includes(e))throw new Error(`Invalid fold state "${n}". Available values: ${wp.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 Ep(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&&!lE(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 lE(n,e){let t=n.split(".")[1];return t===void 0||t.length<=e}function dE(n,e,t,r,i){return Number(Ep(n,e,t,r,i))}function uE(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 pE(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 fE(n,e){let t=i=>i.normalize("NFKC").trim(),r=t(n);if(e.length===0)throw console.error(lt("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(lt("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(ye("--os-version does not match any downloaded image (exact string required).")),console.log(lt("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 mE=["Name","Status","Serial","Device Type","OS Version"];function hE(n,e,t){return{cells:[n.name,t?"running":"stopped",e??"-",n.deviceType??"-",n.osVersion??"-"],highlight:t}}async function gE(n,e){let t=await Promise.all(e.map(async r=>{let i=await Hn(n,r,oE);return[r,i]}));return new Map(t)}async function yE(n){let e=await uc(n),t=await gE(n,e);return{serials:e,params:t}}function wE(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 vE(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&&wE(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 SE(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=>hE(i.emu,i.serial,i.effectiveRunning))}async function EE(n,e,t){try{let[r,i]=await Promise.all([n.listEmulators(),yE(e)]);if(r.length===0){t?.stop(),console.log(lt(" No emulator instances found."));return}let o=r.filter(l=>l.isRunning).map(l=>l.name),{productSerialMap:s,hvdSerialMap:a}=vE(i.serials,i.params,o);t?.stop();let c=SE(r,s,a);console.log(yt(mE,c))}catch(r){jo(t,`Failed to list emulators: ${r.message}`)}}function bp(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(ye(`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 bE=2e3,PE=6e4;async function CE(n,e){let t=de(e);return(await pc(n)).some(i=>de(i)===t)}async function Pp(n,e,t,r=PE,i=bE){let o=Date.now()+r;for(;Date.now()<o;){if(await CE(n,e)===t)return!0;await new Promise(a=>setTimeout(a,i))}return!1}async function IE(n,e,t){if(await n.startEmulator(t)==="already-running"){console.log(lt(`Emulator "${t}" is already running.`));return}console.log(Vn(`Starting emulator "${t}"...`));let i=await Pp(e,t,!0);console.log(i?Xr(`Emulator "${t}" started successfully.`):lt(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function AE(n,e,t){let r=await Promise.allSettled(t.map(o=>IE(n,e,o)));bp(r,t,"start")&&process.exit(1)}async function Cp(n,e){let t=e.trim();if(!gn(t))return t;let r=await Q.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 DE(n,e,t){let r=await Cp(e,t);if(console.log(Vn(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(lt(`Emulator "${r}" is already stopped.`));return}let o=await Pp(e,r,!1);console.log(o?Xr(`Emulator "${r}" stopped successfully.`):lt(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function RE(n,e,t){let r=await Promise.allSettled(t.map(o=>DE(n,e,o)));bp(r,t,"stop")&&process.exit(1)}async function Fe(){try{let n=await I.new();return{manager:Gn.from(n),toolProvider:n}}catch(n){console.error(ye(`Failed to initialize emulator: ${n.message}`)),process.exit(1);return}}async function wt(n,e){try{let t=aE(n.target),r=e(),{manager:i,toolProvider:o}=await Fe(),s=await Cp(o.hdcPath,t);await i.controlEmulator(s,r),console.log(Xr(`Emulator "${t}" operation completed.`))}catch(t){let r=n.target?.trim()||"<unknown>";console.error(ye(`Failed to operate emulator "${r}": ${t.message}`)),process.exit(1)}}function TE(n){let e=[];return $o(e,"longitude",n.longitude,-180,180,8),$o(e,"latitude",n.latitude,-90,90,8),$o(e,"altitude",n.altitude,-1e4,1e4,2),$o(e,"bearing",n.direction,0,359.99,2,"--direction"),Cc(e,"Specify one geolocation option.")}function kE(n){let e=[];return qr(e,"light",n.lightIntensity,0,1e5,!1,"--light-intensity"),qr(e,"humidity",n.humidity,0,100,!1),qr(e,"temperature",n.temperature,-273.1,100,!1),qr(e,"steps",n.steps,0,1e4,!0),qr(e,"heartrate",n.heartrate,0,255,!0),Cc(e,"Specify one sensor option.")}function Cc(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 $o(n,e,t,r,i,o,s=`--${e}`){t!==void 0&&n.push({type:"gps",key:e,value:Ep(s,t,r,i,o)})}function qr(n,e,t,r,i,o,s=`--${e}`){if(t===void 0)return;let a=o?Sp(s,t,r,i):dE(s,t,r,i,1);n.push({type:"sensor",key:e,value:a})}function xE(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}),Cc(e,"Specify --level or --status.")}var se=new Pc("emulator").description("Manage emulator instances"),LE=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function Uo(n){let e=new Kr("--device-type <type>","Emulator device type").choices([...LE]);return n?e.makeOptionMandatory():e}function zn(n,e){for(let t of e)if(t in n)return n[t]}function Yr(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function vp(n){let e=Yr(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var NE=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],OE="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function Ip(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function Ap(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let i=r,o=Yr(zn(i,["osVersion","OsVersion","OSVersion","os_version"])),s=Yr(zn(i,["deviceType","DeviceType","device_type"])),a=vp(zn(i,["downloaded","Downloaded","isDownloaded"])),c=Yr(zn(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=Yr(zn(i,["releaseType","ReleaseType","release_type"])),d=vp(zn(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,l,d,a],highlight:e&&a==="true"})}return t}function ME(n){let e=n.trim();if(!e)return!0;let t=Ip(e);return t===null?!1:t.length===0?!0:Ap(t,!0).length===0}function _E(n,e){let t=n.trim();if(!t)return"";let r=Ip(t);if(!r)return n.trimEnd();let i=Ap(r,e);return yt(NE,i)}var Bo=new Pc("image").description("HarmonyOS emulator system images (download, list, remove)");Bo.command("download").description("Download system image").addOption(Uo(!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 Fe();try{await Ec(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof _e&&(console.error(ye(r.message)),process.exit(1)),r}n.deviceType?.trim()||(console.error(ye("Error: missing required option '--device-type <type>'")),process.exit(1)),n.osVersion?.trim()||(console.error(ye("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(ye(`Failed to download system image: ${r.message}`)),process.exit(1)}});Bo.command("remove").description("Remove a downloaded system image").addOption(Uo(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let{manager:e}=await Fe();try{await e.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})}catch(t){console.error(ye(`Failed to remove system image: ${t.message}`)),process.exit(1)}});Bo.command("list").description("List system images").addOption(Uo(!1)).option("--all","List all images (local and remote)").addOption(new Kr("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let{manager:e}=await Fe();try{let t;n.all?t=void 0:t=!0;let r=await e.listEmulatorImages({deviceType:n.deviceType,downloaded:t});if(ME(r)){console.log(lt(OE));return}if(n.format==="json"){console.log(r.trimEnd());return}let i=_E(r,n.all===!0);console.log(i)}catch(t){console.error(ye(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});se.addCommand(Bo);var Wo=new Pc("license").description("Review and accept emulator license agreements interactively (prints full text + y/N prompt)");Wo.command("view").description("Review agreement text (read-only, no changes)").action(async()=>{let{toolProvider:n}=await Fe(),e=await mp(n.emulatorPath,n.sdkPath);process.exit(e)});Wo.command("accept").description("Accept all emulator license agreements non-interactively (skips review and prompt)").action(async()=>{let{toolProvider:n}=await Fe(),e=await yp(n.emulatorPath,n.sdkPath);process.exit(e)});Wo.action(async()=>{let{toolProvider:n}=await Fe(),e=await gp(n.emulatorPath,n.sdkPath);process.exit(e)});se.addCommand(Wo);se.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>wt(n,()=>({type:"shake"})));se.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>wt(n,()=>({type:"power"})));se.command("rotate").description("Rotate emulator").addOption(new Kr("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new bc("<direction>").choices(["left","right"])).action((n,e)=>wt(e,()=>({type:"rotation",direction:n})));se.command("volume").description("Change volume").addOption(new Kr("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new bc("<direction>").choices(["up","down"])).action((n,e)=>wt(e,()=>({type:"volume",direction:n})));se.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",sE).action((n,e)=>wt(e,()=>({type:"folded-state",state:cE(n)})));se.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 Kr("--status <status>","Charging status").choices(["charging","discharging"])).action(n=>wt(n,()=>xE(n)));se.command("geolocation").description("Inject geographic coordinates and direction").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--longitude <value>","Longitude (-180.0 to 180.0)").option("--latitude <value>","Latitude (-90.0 to 90.0)").option("--altitude <value>","Altitude (-10000.0 to 10000.0)").option("--direction <value>","Heading direction in degrees (0.00 to 359.99)").action(n=>wt(n,()=>TE(n)));se.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new bc("<type>","Motion simulation scene").choices(["outdoorRunning","outdoorCycling","drivingNavigation"])).action((n,e)=>{let t={outdoorRunning:{type:"outdoor-running"},outdoorCycling:{type:"outdoor-cycling"},drivingNavigation:{type:"driving-navigation"}};return wt(e,()=>t[n])});se.command("sensor").description("Inject sensor data").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--light-intensity <value>","Light sensor (0 to 100000)").option("--humidity <value>","Humidity sensor (0 to 100)").option("--temperature <value>","Temperature sensor (-273.1 to 100)").option("--steps <value>","Steps sensor (integer 0 to 10000)").option("--heartrate <value>","Heart rate sensor (integer 0 to 255)").action(n=>wt(n,()=>kE(n)));se.command("list").description("List all emulator instances").action(async()=>{let{manager:n,toolProvider:e}=await Fe(),t=iE({text:"Listing emulators\u2026",color:"cyan"}).start();await EE(n,e.hdcPath,t)});se.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let{manager:e,toolProvider:t}=await Fe();try{await Sc(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof _e&&(console.error(ye(r.message)),process.exit(1)),r}n?.length||(console.error(ye("Error: missing required argument 'names'")),process.exit(1)),await AE(e,t.hdcPath,n)});se.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 Fe();n?.length||(console.error(ye("Error: missing required argument 'names'")),process.exit(1)),await RE(e,t.hdcPath,n)});var Dp=se.command("create <name>").description("Create a local emulator by running emulator -create <name> \u2026; --os-version must match a downloaded image from `emulator image list`.").addOption(Uo(!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");Dp.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
1250
- ${lt("Tip: ")}${Jr("Unquoted --os-version values with spaces/parentheses are split into multiple arguments. Use:")}
1251
- ${Vn('devecocli emulator create 123 --device-type phone --os-version "HarmonyOS 6.0.1(21)"')}
1252
- ${Vn('devecocli emulator create 123 --device-type phone --os-version="HarmonyOS 6.0.1(21)"')}
1253
- `)}});Dp.action(async(n,e)=>{try{uE(n),pE(e.osVersion);let{manager:t}=await Fe(),r=await t.listDownloadedImageOsVersions();fE(e.osVersion,r),console.log(Vn(`Creating emulator "${n}"...`)),await t.createVirtualDevice({name:n,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(Xr(`Emulator "${n}" created successfully.`))}catch(t){console.error(ye(`${t.message}`)),process.exit(1)}});se.command("delete <name>").description("Delete a local emulator instance").action(async n=>{let{manager:e}=await Fe();console.log(Vn(`Deleting emulator "${n}"...`));try{let t=await e.deleteVirtualDevice(n);console.log(Xr(`Emulator "${t}" deleted successfully.`))}catch(t){let r=t;console.error(ye(r.message)),r.stdout&&console.error(Jr(r.stdout)),r.stderr&&console.error(Jr(r.stderr)),process.exit(1)}});var Rp=se;import{Command as eb}from"commander";import{cyan as He}from"colorette";import*as Yp from"readline";import*as zp from"crypto";import*as Tp from"http";import*as kp from"crypto";import{URL as FE}from"url";var Go=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=Tp.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 FE(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 d={tempToken:a,siteId:c,quit:l??void 0};this.resolveCallback?.(d),this.sendSuccessResponse(t)}catch(o){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(o)}}parseParams(e,t){return t&&t.trim()?new URLSearchParams(t):e}validateCode(e){let t=Buffer.from(e||"","utf8"),r=Buffer.from(this.clientSecret,"utf8");return t.length===r.length&&kp.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 Ee from"fs";import*as Yn from"path";import{homedir as GE}from"os";var vt={};pw(vt,{LocalCrypto:()=>vt,decryptForLocalStorage:()=>UE,decryptForLocalStorageFromDirectory:()=>BE,encryptForLocalStorage:()=>$E,isEncryptedBlob:()=>WE});import*as W from"fs";import*as wn from"path";import*as Se from"crypto";import{homedir as xp}from"os";var Zr=ln.ALGORITHM,Lp=ln.IV_LENGTH,Qr=ln.KEY_LENGTH,ei=ln.KEY_LENGTH,ti=ln.KEK_VERSIONS,Ic=process.env.DEVECO_CLI_DATA_DIR||wn.join(xp(),ge.CONFIG_DIR_NAME,ge.APP_NAME),Ac=wn.join(xp(),".local","share",ge.APP_NAME,"keys"),qn=wn.join(Ic,ge.KEY_FILE_NAME);function Dc(n){return wn.join(Ac,`${n}.bin`)}function Np(){W.existsSync(Ic)||W.mkdirSync(Ic,{recursive:!0,mode:448}),W.existsSync(Ac)||W.mkdirSync(Ac,{recursive:!0,mode:448})}function Op(){Np();for(let n of ti){let e=Dc(n);W.existsSync(e)||W.writeFileSync(e,Se.randomBytes(Qr),{mode:384})}}function Mp(n){Op();let e=Dc(n),t=W.readFileSync(e);if(t.length===Qr)return t;let r=Se.randomBytes(Qr);return W.writeFileSync(e,r,{mode:384}),r}function Rc(n,e){let t=Se.randomBytes(Lp),r=Mp(e),i=Se.createCipheriv(Zr,r,t),o=Buffer.concat([i.update(n),i.final()]),s=i.getAuthTag();return{version:1,algorithm:Zr,kekId:e,encryptedDek:o.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function _p(n,e){return Fp(Buffer.from(n.encryptedDek,"base64"),e,n.iv,n.authTag)}function Fp(n,e,t,r){let i=Se.createDecipheriv(Zr,e,Buffer.from(t,"base64"));return i.setAuthTag(Buffer.from(r,"base64")),Buffer.concat([i.update(n),i.final()])}function jp(n,e){return Fp(Buffer.from(n.ciphertext,"base64"),e,n.iv,n.authTag).toString("utf8")}function jE(){if(Op(),W.existsSync(qn))return;let n=Se.randomBytes(ei),e=Rc(n,ti[0]);W.writeFileSync(qn,JSON.stringify(e,null,2),{mode:384})}function Hp(){jE();let n=JSON.parse(W.readFileSync(qn,"utf8")),e=_p(n,Mp(n.kekId));if(e.length===ei)return e;let t=Se.randomBytes(ei),r=Rc(t,ti[0]);return W.writeFileSync(qn,JSON.stringify(r,null,2),{mode:384}),t}function HE(){Np();for(let t of ti){let r=Dc(t);W.existsSync(r)||W.writeFileSync(r,Se.randomBytes(Qr),{mode:384})}if(W.existsSync(qn))return;let n=Se.randomBytes(ei),e=Rc(n,ti[0]);W.writeFileSync(qn,JSON.stringify(e,null,2),{mode:384})}function $E(n){let e=Hp(),t=Se.randomBytes(Lp),r=Se.createCipheriv(Zr,e,t),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o=r.getAuthTag();return{version:1,algorithm:Zr,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:o.toString("base64"),timeStamp:Date.now()}}function UE(n){try{return jp(n,Hp())}catch{throw HE(),new Error("Failed to decrypt local ciphertext")}}function BE(n,e){let t=wn.join(e,ge.KEY_FILE_NAME),r=JSON.parse(W.readFileSync(t,"utf8")),i=wn.join(e,"keys",`${r.kekId}.bin`),o=W.readFileSync(i);if(o.length!==Qr)throw new Error("Invalid external root key");let s=_p(r,o);if(s.length!==ei)throw new Error("Invalid external data encryption key");return jp(n,s)}function WE(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"}var zo=class{tokenFilePath;constructor(e){let t=e||process.env.DEVECO_CLI_DATA_DIR||Yn.join(GE(),ge.CONFIG_DIR_NAME,ge.APP_NAME);this.tokenFilePath=Yn.join(t,ge.TOKEN_FILE_NAME)}ensureConfigDir(){let e=Yn.dirname(this.tokenFilePath);Ee.existsSync(e)||Ee.mkdirSync(e,{recursive:!0,mode:448})}async saveJwtToken(e){if(!e)throw new Error("Token is empty");let t=vt.encryptForLocalStorage(e);this.ensureConfigDir(),Ee.writeFileSync(this.tokenFilePath,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){return(await this.resolveJwtToken())?.token??null}async resolveJwtToken(){let e=this.loadDevecoCodeToken();if(e)return{token:e,source:"deveco-code"};let t=await this.loadLocalJwtToken();return t?{token:t,source:"deveco-cli"}:null}loadDevecoCodeToken(){if(process.env.DEVECO_CLI_AUTH_SOURCE!=="deveco-code")return null;let e=process.env.DEVECO_CODE_AUTH_DIR?.trim();if(!e)return null;try{let t=Yn.join(e,ge.TOKEN_FILE_NAME);if(!Ee.existsSync(t))return null;let r=JSON.parse(Ee.readFileSync(t,"utf8"));return vt.isEncryptedBlob(r)?vt.decryptForLocalStorageFromDirectory(r,e):null}catch{return null}}async loadLocalJwtToken(){try{if(!Ee.existsSync(this.tokenFilePath))return null;let e=JSON.parse(Ee.readFileSync(this.tokenFilePath,"utf8"));return vt.isEncryptedBlob(e)?vt.decryptForLocalStorage(e):null}catch{return await this.clearToken(),null}}async clearToken(){try{Ee.existsSync(this.tokenFilePath)&&Ee.unlinkSync(this.tokenFilePath)}catch(e){throw new Error("Failed to clear token",{cause:e})}}},je=new zo;var dt={CHINA:"CN",RUSSIA:"RU",SINGAPORE:"SG",EUROPE:"EU"},ni={CHINA:"zh_CN",RUSSIA:"ru_RU",EUROPE:"de_DE"},Vo={CHINA:"1",SINGAPORE:"5",EUROPE:"7",RUSSIA:"8"},zE={[dt.CHINA]:ni.CHINA,[dt.RUSSIA]:ni.RUSSIA,[dt.EUROPE]:ni.EUROPE,[dt.SINGAPORE]:ni.CHINA},VE={[Vo.CHINA]:dt.CHINA,[Vo.SINGAPORE]:dt.SINGAPORE,[Vo.EUROPE]:dt.EUROPE,[Vo.RUSSIA]:dt.RUSSIA};function $p(n){return zE[n]??ni.CHINA}function Up(n){return VE[n]??dt.CHINA}function qo(n,e){return n?.toUpperCase()===dt.CHINA?ze.CN_LOGIN_URL:e}import{exec as qE}from"child_process";import{promisify as YE}from"util";var JE=YE(qE);async function Bp(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 JE(t)}catch(r){throw new Error("Failed to open browser",{cause:r})}}import KE from"axios";var Tc=class{client;constructor(){let e={timeout:Fr.HTTP_TIMEOUT_MS,headers:{"User-Agent":co.USER_AGENT,"accept-language":co.ACCEPT_LANGUAGE},transformResponse:[t=>t],proxy:!1};this.client=KE.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 Tc;var kc=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 je.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}}},ri=new kc;function Wp(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 Gp(n){let e=n.split(".");return e.length===3&&e.every(t=>t.length>0)}var xc=class{async getJwtToken(e,t,r,i,o){let s=e.split("&")[0],a=Up(t),c=r(),l={tempToken:s,site:a,version:ge.API_VERSION,appid:o},d=`${c}/${i}`,h=await L.get(d,{params:l});if(h.statusCode!==200)throw new Error(`Failed to get jwtToken: status=${h.statusCode}`);let w=h.data.trim();if(!Gp(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=Wp(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:$p(r.userInfo.nationalCode),isRealName:String(r.userInfo.realName)==="true"}}},Yo=new xc;var Jo=class{config;server=null;constructor(e){this.config={...jr,...e}}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}async login(){try{let e=this.generateClientSecret();this.server=new Go(e,this.getRegionalizedBaseUrl(),this.config.successRedirectUrl,this.config.failedRedirectUrl),await this.server.start(),await this.openLoginPage(this.server.getPort(),e);let t=await this.server.waitForCallback(this.config.timeout);if(t.siteId!=="1")throw new Error("Non-China accounts are not supported.");let r=await Yo.getJwtToken(t.tempToken,t.siteId,()=>this.getRegionalizedBaseUrl(),this.config.tempTokenCheckUrl,this.config.appId),i=await Yo.getUserInfoFromJwt(r,o=>ri.checkJwtToken(o,()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl));return await je.saveJwtToken(r),i}finally{this.server&&(await this.server.stop(),this.server=null)}}async isLoggedIn(){let e=await je.resolveJwtToken();return e==null?!1:(await ri.checkJwtToken(e.token,()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl)).status?!0:(e.source==="deveco-cli"&&await je.clearToken(),!1)}async logout(){let e=await je.resolveJwtToken();if(e==null)return!1;if(e.source==="deveco-code")throw new Error("Login is managed by deveco-code. Log out from deveco-code instead.");let r=`${this.getRegionalizedBaseUrl()}/${this.config.logoutUrl}?jwtToken=${e.token}`;try{await L.post(r,{timeout:5e3})}finally{await je.clearToken()}return!0}async getUserInfo(){let e=await je.loadJwtToken();return e?Yo.getUserInfoFromJwt(e,t=>ri.checkJwtToken(t,()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl)):null}generateClientSecret(){return zp.randomUUID().replace(/-/g,"")}getRegionalizedBaseUrl(){return qo(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 Bp(i)}async refreshToken(){return ri.refreshToken(()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl)}},ne=new Jo;import Vp from"axios";var ZE="No JWT in local storage. Run `devecocli auth login` first.";function QE(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 Ko=class{config;constructor(e){this.config={...jr,...e}}updateConfig(e){this.config={...this.config,...e}}async listTeams(){let e=await je.loadJwtToken();if(!e)throw new Error(ZE);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=QE(i);return{userId:r??"",teamList:o}}async fetchTeamList(e,t){let r=this.config.agcTeamListUrl;m(`Executing: GET ${r}`);let i;try{i=await Vp.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 Vp.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 qo(this.config.countryCode??"",this.config.baseUrl)}},qp=new Ko;async function jt(){return qp.listTeams()}function tb(n){if(n.length===0)return He("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 nb(){return new Promise(n=>{let e=Yp.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),n()})})}var ii=new eb("auth").description("Authentication commands (login, logout, status, team)");ii.command("login").description("Log in to your Huawei Developer account").action(async()=>{try{if(await ne.isLoggedIn()){let t=await ne.getUserInfo();if(t){console.log(He(`Already logged in, User Name:${t.userName}`));return}}console.log(He("Starting login process...")),console.log(He("Press Enter to open browser for login...")),await nb();let e=await ne.login();console.log(He(`Login successful. Logged in as ${e.userName}.`))}catch(n){throw new Error("Login failed",{cause:n})}});ii.command("logout").description("Log out of your Huawei Developer account").action(async()=>{try{let n=await ne.logout();console.log(n?He("Logout successful"):He("Already logged out."))}catch(n){throw new Error("Logout failed",{cause:n})}});ii.command("status").description("Show the currently logged-in user").action(async()=>{try{if(!await ne.isLoggedIn()){console.log(He("Not logged in"));return}let e=await ne.getUserInfo();if(!e){console.log(He("Not logged in"));return}console.log(He(`Current user: ${e.userName}`))}catch{console.log(He("Not logged in"))}});var rb=ii.command("team").description("Team-related commands");rb.command("list").description("List team accounts the current user has joined").option("--json","output as JSON",!1).action(async n=>{try{if(!await ne.isLoggedIn()){console.log(He("Please run `devecocli auth login` first."));return}let t=await jt();if(n.json){console.log(JSON.stringify(t,null,2));return}console.log(tb(t.teamList))}catch(e){throw new Error("Failed to list teams",{cause:e})}});var Jp=ii;import{Command as wb}from"commander";import{green as vb,red as li,cyan as vf,yellow as Sf,dim as Ef}from"colorette";import Sb from"p-limit";import ib from"ora";var Qe=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=ib(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 Kp from"fs";import*as Xp from"path";import{homedir as ob}from"os";var Zp=["DevEco"];async function Xo(){let n=await L.get(Ve.TAGS_API_URL),t=Zo(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 sb(n){let e=[],t=Ve.DEFAULT_PAGE_SIZE,r=1;for(;;){let i=await L.post(Ve.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:r,pageSize:t,tagIds:[n]}}),o=Zo(i,"Skills API");if(e.push(...o.data.list),o.data.list.length<t)break;r++}return e}async function Lc(n){let e=new Map,t=n.map(i=>sb(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=>!Zp.includes(o.name)))}async function ab(n,e){let t=await L.post(Ve.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:Ve.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return Zo(t,"Skills API").data.list}async function Nc(n,e){let t=new Map,r=e.map(o=>ab(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=>!Zp.includes(s.name)))}function Qp(n){let e=[];for(let[,t]of Object.entries(qe)){let r=Xp.join(ob(),t.path,n);Kp.existsSync(r)&&e.push(t.displayName)}return e.sort()}function Zo(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=L.parseJson(n);if(t.code!==Ve.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function ef(n){let e=`${Ve.SKILL_API_BASE}/${n}/checksum`,t=await L.get(e);return Zo(t,"Checksum API").data}import cb from"adm-zip";import lb from"crypto";import nf from"fs";import q from"path";import{fileURLToPath as db}from"url";import{homedir as rf}from"os";import{red as ub}from"colorette";var St=nf.promises;function Oc(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}function tf(n,e){let t=q.resolve(e),r=q.resolve(n),i=q.relative(r,t);if(i.startsWith("..")||q.isAbsolute(i))throw new Error(`Path traversal detected: ${e}.`)}function Mc(n){return q.isAbsolute(n)?n:q.resolve(process.cwd(),n)}function pb(n){return lb.createHash("sha256").update(n).digest("hex")}async function fb(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=pb(n),i=e.sha256.toLowerCase();if(r!==i)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function of(n){let e=`${Ve.SKILL_API_BASE}/${n}/install?format=zip`,t=await L.getBinary(e),r=await ef(n);return await fb(t,r),t}async function mb(n,e,t){Oc(t);let r=new cb(n),i=r.getEntries();try{await St.stat(e)}catch{await St.mkdir(e,{recursive:!0})}let o=q.join(e,t);tf(e,o);for(let s of i){let a=q.join(o,s.entryName);tf(o,a)}r.extractAllTo(o,!0)}async function _c(n){let e=qe[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(qe).join(", ")}`);let t=q.join(rf(),e.path.replace("/skills",""));try{return await St.access(t),!0}catch{return!1}}function Fc(n){let e=qe[n];return q.join(rf(),e.path)}function hb(n){let e=qe[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(qe).join(", ")}`);return e}function jc(n,e){let t=hb(e),r="projectPath"in t?t.projectPath:q.join("."+e,"skills");return q.join(n,r)}async function gb(n,e,t){Oc(e);let r=q.join(n,e);try{if(await St.access(r),t)await St.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 Hc(n,e,t){await mb(n,e,t),console.log(`Skill ${t} installed to ${q.join(e,t)}.`)}async function $c(n,e,t){let r=q.join(e,t);await St.mkdir(r,{recursive:!0});let i=q.join(r,q.basename(n));await St.copyFile(n,i),console.log(`Skill ${t} installed to ${r}.`)}function sf(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(ub(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function Jn(n,e,t,r){try{let i=await e(),{shouldSkip:o}=await gb(i,n,r);return o?{success:!0,skipped:!0}:(await t(i),{success:!0})}catch(i){return sf(n,i,"Installation failed")}}async function Uc(n,e){try{Oc(n);let t=await e(),r=q.join(t,n);try{await St.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await St.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return sf(n,t,"Removal failed")}}async function af(n,e,t,r=!1){return Jn(n,()=>Fc(e),i=>Hc(t,i,n),r)}async function cf(n,e,t,r=!1){return Jn(n,()=>t,i=>Hc(e,i,n),r)}async function lf(n,e,t,r,i=!1){return Jn(n,()=>jc(t,r),o=>Hc(e,o,n),i)}async function df(n,e,t,r=!1){return Jn(n,()=>Fc(t),i=>$c(e,i,n),r)}async function uf(n,e,t,r,i=!1){return Jn(n,()=>jc(t,r),o=>$c(e,o,n),i)}async function pf(n,e,t,r=!1){return Jn(n,()=>t,i=>$c(e,i,n),r)}async function ff(n,e){return Uc(n,()=>Fc(e))}async function mf(n,e){return Uc(n,()=>e)}async function hf(n,e,t){return Uc(n,()=>jc(e,t))}function gf(){let e=q.dirname(db(import.meta.url));for(;;){let t=q.join(e,"SKILL.md");if(nf.existsSync(t))return t;let r=q.dirname(e);if(r===e)break;e=r}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import yf from"fs";import{cyan as yb}from"colorette";async function oi(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await _c(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function si(){let n=[];for(let e of Object.keys(qe))await _c(e)&&n.push(e);return n}function ai(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(yb("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function Ht(n,e,t){if(!yf.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!yf.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function ci(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?Mc(n):void 0,resolvedProject:e?Mc(e):void 0}}async function Qo(n,e,t){let r=[],i=[],o;if(e?o=e:t&&n.agent?i=(await oi(n.agent)).map(a=>({project:t,agent:a})):t?i=(await si()).map(a=>({project:t,agent:a})):n.agent?r=await oi(n.agent):r=await si(),!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 Eb(n){let e=await Xo();if(n.all)return(await Lc(e)).map(r=>r.enName);{let r=(await Nc(n.skill,e)).find(i=>i.enName===n.skill);if(!r)throw new Error(`Skill "${n.skill}" not found`);return[r.enName]}}async function bb(n,e,t,r){let i=[];if(t.customPath){let o=await cf(n,e,t.customPath,r);return i.push(o),i}for(let o of t.agents){let s=await af(n,o,e,r);i.push(s)}for(let{project:o,agent:s}of t.projectAgents){let a=await lf(n,e,o,s,r);i.push(a)}return i}function Pb(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}=ci(n.path,n.project,n.agent);return t&&Ht(t,"Project directory",n.force),e&&Ht(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}async function Cb(n,e,t){let r=await Qo(n,e,t);return{skillNames:await Eb(n),targets:r}}async function Ib(n,e,t,r){let i=[],o=n.length,s=Sb(5),a=n.map(c=>s(()=>Ab(c)));for(let c=0;c<n.length;c++){let l=n[c],d=o>1?` (${c+1}/${o})`:"";r.start(`Installing ${l}${d}...`);let h=await a[c];if(!h.success){r.fail(),console.log(li(`${l}: Download failed - ${h.error}`)),i.push({success:!1});continue}r.stop();let w=await bb(l,h.buffer,e,t);i.push(...w)}return i}async function Ab(n){try{let e=await of(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 Db(n){let e=new Qe;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=Pb(n),{skillNames:i,targets:o}=await Cb(n,t,r),s=await Ib(i,o,n.force||!1,e);e.stop(),ai(s)}catch(t){throw e.stop(),t}}function Rb(n){let{resolvedPath:e,resolvedProject:t}=ci(n.path,n.project,n.agent);return t&&Ht(t,"Project directory"),e&&Ht(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function Tb(n,e){let t=new Qe;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:i}=Rb(e);t.stop();let o=await kb(e,n,r,i);t.stop(),ai(o)}catch(r){throw t.stop(),r}}function wf(n,e=""){if(n.length===0)throw new Error(`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function es(n,e){let t=[];for(let r of e){let i=r.type==="agent"?await ff(n,r.agent):await hf(n,r.project,r.agent);t.push(i)}return t}async function kb(n,e,t,r){if(t)return[await mf(e,t)];if(r&&n.agent){let a=(await oi(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return es(e,a)}if(r){let s=await si();wf(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return es(e,a)}if(n.agent){let a=(await oi(n.agent)).map(c=>({type:"agent",agent:c}));return es(e,a)}let i=await si();wf(i,"or use --path for a custom location.");let o=i.map(s=>({type:"agent",agent:s}));return es(e,o)}var di=new wb("skills").description("Manage HarmonyOS skills");di.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 Qe;try{e.start("Fetching skills...");let t=await Xo(),r=await Lc(t);if(r.length===0){e.stop(),console.log(Sf("No skills available."));return}e.succeed(`Fetched ${r.length} skills`);for(let i of r)if(n.long){console.log(vf(i.enName)),console.log(Ef(i.description));let o=Qp(i.enName);o.length>0&&console.log(vb(`Installed for: ${o.join(", ")}`)),console.log()}else console.log(i.enName)}catch(t){e.stop(),console.error(li(t.message)),process.exit(1)}});di.command("find <keyword>").description("Search skills by keyword").action(async n=>{let e=new Qe;try{e.start("Searching skills...");let t=await Xo(),r=await Nc(n,t);if(r.length===0){console.log(Sf(`No skills found matching '${n}'.`)),e.stop();return}e.succeed(`Found ${r.length} skills.`);for(let i of r)console.log(vf(i.enName)),console.log(Ef(i.description)),console.log()}catch(t){e.stop(),console.error(li(t.message)),process.exit(1)}});di.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 Db(n)}catch(e){console.error(li(e.message)),process.exit(1)}});di.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 Tb(n.skill,n)}catch(e){console.error(li(e.message)),process.exit(1)}});var bf=di;import{Command as Lb,InvalidArgumentError as Cf}from"commander";import{cyan as ts}from"colorette";function vn(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=jn(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 Bc=[800,1500,2500];function xb(n){return new Promise(e=>setTimeout(e,n))}var Kn=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=Q.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(ts(`Using device serial: ${i}`)),i}if(e&&t.includes(e))return m(ts(`Using device serial: ${e}`)),e;let r=await this.loadConnectedDevicesByName();if(e){let i=this.findDeviceByArg(r,e);if(i)return m(ts(`Using device: ${i.name} (${i.serial})`)),i.serial;let o=this.formatConnectedDeviceList(r);throw new Error(`Device '${e}' not found.
1249
+ `;function Tb(n){let e=n.trim();if(!e)throw new Error("--target must not be empty.");return e}function xb(n){let e=n.trim();if(!Hp.includes(e))throw new Error(`Invalid fold state "${n}". Available values: ${Hp.join(", ")}`);return e}function Up(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 Bp(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&&!Lb(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 Lb(n,e){let t=n.split(".")[1];return t===void 0||t.length<=e}function Nb(n,e,t,r,i){return Number(Bp(n,e,t,r,i))}function Ob(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 Mb(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 _b(n,e){let t=i=>i.normalize("NFKC").trim(),r=t(n);if(e.length===0)throw console.error(at("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(at("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(at("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 Fb=["Name","Status","Serial","Device Type","OS Version"];function jb(n,e,t){return{cells:[n.name,t?"running":"stopped",e??"-",n.deviceType??"-",n.osVersion??"-"],highlight:t}}async function Hb(n,e){let t=await Promise.all(e.map(async r=>{let i=await jn(n,r,kb);return[r,i]}));return new Map(t)}async function $b(n){let e=await kc(n),t=await Hb(n,e);return{serials:e,params:t}}function Ub(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 Bb(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&&Ub(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 Wb(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=>jb(i.emu,i.serial,i.effectiveRunning))}async function Gb(n,e,t){try{let[r,i]=await Promise.all([n.listEmulators(),$b(e)]);if(r.length===0){t?.stop(),console.log(at(" No emulator instances found."));return}let o=r.filter(l=>l.isRunning).map(l=>l.name),{productSerialMap:s,hvdSerialMap:a}=Bb(i.serials,i.params,o);t?.stop();let c=Wb(r,s,a);console.log(ht(Fb,c))}catch(r){Vo(t,`Failed to list emulators: ${r.message}`)}}function Wp(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(Zr(s.stdout)),s.stderr&&console.error(Zr(s.stderr))}return r}var Vb=2e3,zb=6e4;async function qb(n,e){let t=de(e);return(await Rc(n)).some(i=>de(i)===t)}async function Gp(n,e,t,r=zb,i=Vb){let o=Date.now()+r;for(;Date.now()<o;){if(await qb(n,e)===t)return!0;await new Promise(a=>setTimeout(a,i))}return!1}async function Yb(n,e,t){if(await n.startEmulator(t)==="already-running"){console.log(at(`Emulator "${t}" is already running.`));return}console.log(qn(`Starting emulator "${t}"...`));let i=await Gp(e,t,!0);console.log(i?Qr(`Emulator "${t}" started successfully.`):at(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function Jb(n,e,t){let r=await Promise.allSettled(t.map(o=>Yb(n,e,o)));Wp(r,t,"start")&&process.exit(1)}async function Vp(n,e){let t=e.trim();if(!yn(t))return t;let r=await Q.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 Kb(n,e,t){let r=await Vp(e,t);if(console.log(qn(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(at(`Emulator "${r}" is already stopped.`));return}let o=await Gp(e,r,!1);console.log(o?Qr(`Emulator "${r}" stopped successfully.`):at(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function Zb(n,e,t){let r=await Promise.allSettled(t.map(o=>Kb(n,e,o)));Wp(r,t,"stop")&&process.exit(1)}async function Fe(){try{let n=await I.new();return{manager:Vn.from(n),toolProvider:n}}catch(n){console.error(me(`Failed to initialize emulator: ${n.message}`)),process.exit(1);return}}async function gt(n,e){try{let t=Tb(n.target),r=e(),{manager:i,toolProvider:o}=await Fe(),s=await Vp(o.hdcPath,t);await i.controlEmulator(s,r),console.log(Qr(`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 Xb(n){let e=[];return qo(e,"longitude",n.longitude,-180,180,8),qo(e,"latitude",n.latitude,-90,90,8),qo(e,"altitude",n.altitude,-1e4,1e4,2),qo(e,"bearing",n.direction,0,359.99,2,"--direction"),Uc(e,"Specify one geolocation option.")}function Qb(n){let e=[];return Jr(e,"light",n.lightIntensity,0,1e5,!1,"--light-intensity"),Jr(e,"humidity",n.humidity,0,100,!1),Jr(e,"temperature",n.temperature,-273.1,100,!1),Jr(e,"steps",n.steps,0,1e4,!0),Jr(e,"heartrate",n.heartrate,0,255,!0),Uc(e,"Specify one sensor option.")}function Uc(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 qo(n,e,t,r,i,o,s=`--${e}`){t!==void 0&&n.push({type:"gps",key:e,value:Bp(s,t,r,i,o)})}function Jr(n,e,t,r,i,o,s=`--${e}`){if(t===void 0)return;let a=o?Up(s,t,r,i):Nb(s,t,r,i,1);n.push({type:"sensor",key:e,value:a})}function eE(n){let e=[];return n.level!==void 0&&e.push({type:"battery",level:Up("--level",n.level,1,100)}),n.status!==void 0&&e.push({type:"battery-status",status:n.status==="charging"?1:0}),Uc(e,"Specify --level or --status.")}var oe=new $c("emulator").description("Manage emulator instances"),tE=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function Yo(n){let e=new Xr("--device-type <type>","Emulator device type").choices([...tE]);return n?e.makeOptionMandatory():e}function zn(n,e){for(let t of e)if(t in n)return n[t]}function Kr(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function $p(n){let e=Kr(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var nE=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],rE="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function zp(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function qp(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let i=r,o=Kr(zn(i,["osVersion","OsVersion","OSVersion","os_version"])),s=Kr(zn(i,["deviceType","DeviceType","device_type"])),a=$p(zn(i,["downloaded","Downloaded","isDownloaded"])),c=Kr(zn(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=Kr(zn(i,["releaseType","ReleaseType","release_type"])),p=$p(zn(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,l,p,a],highlight:e&&a==="true"})}return t}function iE(n){let e=n.trim();if(!e)return!0;let t=zp(e);return t===null?!1:t.length===0?!0:qp(t,!0).length===0}function oE(n,e){let t=n.trim();if(!t)return"";let r=zp(t);if(!r)return n.trimEnd();let i=qp(r,e);return ht(nE,i)}var Jo=new $c("image").description("HarmonyOS emulator system images (download, list, remove)");Jo.command("download").description("Download system image").addOption(Yo(!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 Fe();try{await jc(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof _e&&(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)}});Jo.command("remove").description("Remove a downloaded system image").addOption(Yo(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let{manager:e}=await Fe();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)}});Jo.command("list").description("List system images").addOption(Yo(!1)).option("--all","List all images (local and remote)").addOption(new Xr("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let{manager:e}=await Fe();try{let t;n.all?t=void 0:t=!0;let r=await e.listEmulatorImages({deviceType:n.deviceType,downloaded:t});if(iE(r)){console.log(at(rE));return}if(n.format==="json"){console.log(r.trimEnd());return}let i=oE(r,n.all===!0);console.log(i)}catch(t){console.error(me(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});oe.addCommand(Jo);var Ko=new $c("license").description("Review and accept emulator license agreements interactively (prints full text + y/N prompt)");Ko.command("view").description("Review agreement text (read-only, no changes)").action(async()=>{let{toolProvider:n}=await Fe(),e=await Mp(n.emulatorPath,n.sdkPath);process.exit(e)});Ko.command("accept").description("Accept all emulator license agreements non-interactively (skips review and prompt)").action(async()=>{let{toolProvider:n}=await Fe(),e=await jp(n.emulatorPath,n.sdkPath);process.exit(e)});Ko.action(async()=>{let{toolProvider:n}=await Fe(),e=await Fp(n.emulatorPath,n.sdkPath);process.exit(e)});oe.addCommand(Ko);oe.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>gt(n,()=>({type:"shake"})));oe.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>gt(n,()=>({type:"power"})));oe.command("rotate").description("Rotate emulator").addOption(new Xr("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Hc("<direction>").choices(["left","right"])).action((n,e)=>gt(e,()=>({type:"rotation",direction:n})));oe.command("volume").description("Change volume").addOption(new Xr("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Hc("<direction>").choices(["up","down"])).action((n,e)=>gt(e,()=>({type:"volume",direction:n})));oe.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",Rb).action((n,e)=>gt(e,()=>({type:"folded-state",state:xb(n)})));oe.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 Xr("--status <status>","Charging status").choices(["charging","discharging"])).action(n=>gt(n,()=>eE(n)));oe.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=>gt(n,()=>Xb(n)));oe.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new Hc("<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 gt(e,()=>t[n])});oe.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=>gt(n,()=>Qb(n)));oe.command("list").description("List all emulator instances").action(async()=>{let{manager:n,toolProvider:e}=await Fe(),t=Db({text:"Listing emulators\u2026",color:"cyan"}).start();await Gb(n,e.hdcPath,t)});oe.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let{manager:e,toolProvider:t}=await Fe();try{await Fc(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof _e&&(console.error(me(r.message)),process.exit(1)),r}n?.length||(console.error(me("Error: missing required argument 'names'")),process.exit(1)),await Jb(e,t.hdcPath,n)});oe.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 Fe();n?.length||(console.error(me("Error: missing required argument 'names'")),process.exit(1)),await Zb(e,t.hdcPath,n)});var Yp=oe.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(Yo(!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");Yp.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
1250
+ ${at("Tip: ")}${Zr("Unquoted --os-version values with spaces/parentheses are split into multiple arguments. Use:")}
1251
+ ${qn('devecocli emulator create 123 --device-type phone --os-version "HarmonyOS 6.0.1(21)"')}
1252
+ ${qn('devecocli emulator create 123 --device-type phone --os-version="HarmonyOS 6.0.1(21)"')}
1253
+ `)}});Yp.action(async(n,e)=>{try{Ob(n),Mb(e.osVersion);let{manager:t}=await Fe(),r=await t.listDownloadedImageOsVersions();_b(e.osVersion,r),console.log(qn(`Creating emulator "${n}"...`)),await t.createVirtualDevice({name:n,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(Qr(`Emulator "${n}" created successfully.`))}catch(t){console.error(me(`${t.message}`)),process.exit(1)}});oe.command("delete <name>").description("Delete a local emulator instance").action(async n=>{let{manager:e}=await Fe();console.log(qn(`Deleting emulator "${n}"...`));try{let t=await e.deleteVirtualDevice(n);console.log(Qr(`Emulator "${t}" deleted successfully.`))}catch(t){let r=t;console.error(me(r.message)),r.stdout&&console.error(Zr(r.stdout)),r.stderr&&console.error(Zr(r.stderr)),process.exit(1)}});var Jp=oe;import{Command as PE}from"commander";import{red as qc,cyan as He}from"colorette";import*as wf from"readline";import*as hf from"crypto";import*as Kp from"http";import*as Zp from"crypto";import{URL as sE}from"url";var Zo=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=Kp.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 sE(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&&Zp.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 Jn from"path";import{homedir as fE}from"os";var wt={};Rw(wt,{LocalCrypto:()=>wt,decryptForLocalStorage:()=>dE,decryptForLocalStorageFromDirectory:()=>uE,encryptForLocalStorage:()=>lE,isEncryptedBlob:()=>pE});import*as W from"fs";import*as yt from"path";import*as ye from"crypto";import*as Qp from"os";import{homedir as ef}from"os";var ct=class extends Error{constructor(e){super(e),this.name="DefinedError"}};var ei=dn.ALGORITHM,tf=dn.IV_LENGTH,ti=dn.KEY_LENGTH,ni=dn.KEY_LENGTH,ri=dn.KEK_VERSIONS,Xo=process.env.DEVECO_CLI_DATA_DIR||yt.join(ef(),le.CONFIG_DIR_NAME,le.APP_NAME),Qo=yt.join(ef(),".local","share",le.APP_NAME,"keys"),Yn=yt.join(Xo,le.KEY_FILE_NAME);function Xp(n){return Qp.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 Bc(n){return yt.join(Qo,`${n}.bin`)}function nf(){if(!W.existsSync(Xo))try{W.mkdirSync(Xo,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new ct(Xp(Xo)):n}if(!W.existsSync(Qo))try{W.mkdirSync(Qo,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new ct(Xp(yt.dirname(Qo))):n}}function rf(){nf();for(let n of ri){let e=Bc(n);W.existsSync(e)||W.writeFileSync(e,ye.randomBytes(ti),{mode:384})}}function of(n){rf();let e=Bc(n),t=W.readFileSync(e);if(t.length===ti)return t;let r=ye.randomBytes(ti);return W.writeFileSync(e,r,{mode:384}),r}function Wc(n,e){let t=ye.randomBytes(tf),r=of(e),i=ye.createCipheriv(ei,r,t),o=Buffer.concat([i.update(n),i.final()]),s=i.getAuthTag();return{version:1,algorithm:ei,kekId:e,encryptedDek:o.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function sf(n,e){return af(Buffer.from(n.encryptedDek,"base64"),e,n.iv,n.authTag)}function af(n,e,t,r){let i=ye.createDecipheriv(ei,e,Buffer.from(t,"base64"));return i.setAuthTag(Buffer.from(r,"base64")),Buffer.concat([i.update(n),i.final()])}function cf(n,e){return af(Buffer.from(n.ciphertext,"base64"),e,n.iv,n.authTag).toString("utf8")}function aE(){if(rf(),W.existsSync(Yn))return;let n=ye.randomBytes(ni),e=Wc(n,ri[0]);W.writeFileSync(Yn,JSON.stringify(e,null,2),{mode:384})}function lf(){aE();let n=JSON.parse(W.readFileSync(Yn,"utf8")),e=sf(n,of(n.kekId));if(e.length===ni)return e;let t=ye.randomBytes(ni),r=Wc(t,ri[0]);return W.writeFileSync(Yn,JSON.stringify(r,null,2),{mode:384}),t}function cE(){nf();for(let t of ri){let r=Bc(t);W.existsSync(r)||W.writeFileSync(r,ye.randomBytes(ti),{mode:384})}if(W.existsSync(Yn))return;let n=ye.randomBytes(ni),e=Wc(n,ri[0]);W.writeFileSync(Yn,JSON.stringify(e,null,2),{mode:384})}function lE(n){let e=lf(),t=ye.randomBytes(tf),r=ye.createCipheriv(ei,e,t),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o=r.getAuthTag();return{version:1,algorithm:ei,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:o.toString("base64"),timeStamp:Date.now()}}function dE(n){try{return cf(n,lf())}catch{throw cE(),new Error("Failed to decrypt local ciphertext")}}function uE(n,e){let t=yt.join(e,le.KEY_FILE_NAME),r=JSON.parse(W.readFileSync(t,"utf8")),i=yt.join(e,"keys",`${r.kekId}.bin`),o=W.readFileSync(i);if(o.length!==ti)throw new Error("Invalid external root key");let s=sf(r,o);if(s.length!==ni)throw new Error("Invalid external data encryption key");return cf(n,s)}function pE(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 Ze(){return process.env.DEVECO_CLI_AUTH_SOURCE===le.AUTH_SOURCE_DEVECO_CODE}var es=class{getLocalTokenFilePath(){let e=process.env.DEVECO_CLI_DATA_DIR||Jn.join(fE(),le.CONFIG_DIR_NAME,le.APP_NAME);return Jn.join(e,le.TOKEN_FILE_NAME)}ensureConfigDir(){let e=Jn.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=wt.encryptForLocalStorage(e);this.ensureConfigDir();let r=this.getLocalTokenFilePath();we.writeFileSync(r,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){return Ze()?this.loadDevecoCodeToken():this.loadLocalJwtToken()}loadDevecoCodeToken(){if(!Ze())return null;let e=process.env.DEVECO_CODE_AUTH_DIR?.trim();if(!e)return null;try{let t=Jn.join(e,le.TOKEN_FILE_NAME);if(!we.existsSync(t))return null;let r=JSON.parse(we.readFileSync(t,"utf8"));return wt.isEncryptedBlob(r)?wt.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 wt.isEncryptedBlob(t)?wt.decryptForLocalStorage(t):null}catch{return await this.clearToken(),null}}async clearToken(){if(Ze())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})}}},je=new es;var lt={CHINA:"CN",RUSSIA:"RU",SINGAPORE:"SG",EUROPE:"EU"},ii={CHINA:"zh_CN",RUSSIA:"ru_RU",EUROPE:"de_DE"},ts={CHINA:"1",SINGAPORE:"5",EUROPE:"7",RUSSIA:"8"},mE={[lt.CHINA]:ii.CHINA,[lt.RUSSIA]:ii.RUSSIA,[lt.EUROPE]:ii.EUROPE,[lt.SINGAPORE]:ii.CHINA},hE={[ts.CHINA]:lt.CHINA,[ts.SINGAPORE]:lt.SINGAPORE,[ts.EUROPE]:lt.EUROPE,[ts.RUSSIA]:lt.RUSSIA};function df(n){return mE[n]??ii.CHINA}function uf(n){return hE[n]??lt.CHINA}function ns(n,e){return n?.toUpperCase()===lt.CHINA?Ve.CN_LOGIN_URL:e}import{exec as gE}from"child_process";import{promisify as yE}from"util";var wE=yE(gE);async function pf(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 wE(t)}catch(r){throw new Error("Failed to open browser",{cause:r})}}import vE from"axios";var Gc=class{client;constructor(){let e={timeout:Mr.HTTP_TIMEOUT_MS,headers:{"User-Agent":uo.USER_AGENT,"accept-language":uo.ACCEPT_LANGUAGE},transformResponse:[t=>t],proxy:!1};this.client=vE.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 Gc;var Vc=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 je.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}}},oi=new Vc;function ff(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 mf(n){let e=n.split(".");return e.length===3&&e.every(t=>t.length>0)}var zc=class{async getJwtToken(e,t,r,i,o){let s=e.split("&")[0],a=uf(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(!mf(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=ff(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:df(r.userInfo.nationalCode),isRealName:String(r.userInfo.realName)==="true"}}},rs=new zc;var is=class{config;server=null;constructor(e){this.config={..._r,...e}}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}async login(){try{m(`Login started, isDevecoCodeAuth: ${Ze()}`);let e=this.generateClientSecret();this.server=new Zo(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 ct("Non-China accounts are not supported.");let r=await rs.getJwtToken(t.tempToken,t.siteId,()=>this.getRegionalizedBaseUrl(),this.config.tempTokenCheckUrl,this.config.appId);m("JWT token received");let i=await rs.getUserInfoFromJwt(r,o=>oi.checkJwtToken(o,()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl));return m(`User info received: ${i.userName}`),await je.saveJwtToken(r),m("JWT token saved"),i}finally{this.server&&(await this.server.stop(),this.server=null)}}async isLoggedIn(){let e=await je.loadJwtToken();return e?(await oi.checkJwtToken(e,()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl)).status?!0:(Ze()||await je.clearToken(),!1):!1}async logout(){let e=await je.loadJwtToken();if(!e)return!1;let r=`${this.getRegionalizedBaseUrl()}/${this.config.logoutUrl}?jwtToken=${e}`;try{await L.post(r,{timeout:5e3})}finally{await je.clearToken()}return!0}async getUserInfo(){let e=await je.loadJwtToken();return e?rs.getUserInfoFromJwt(e,t=>oi.checkJwtToken(t,()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl)):null}generateClientSecret(){return hf.randomUUID().replace(/-/g,"")}getRegionalizedBaseUrl(){return ns(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 pf(i)}async refreshToken(){return oi.refreshToken(()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl)}},te=new is;import gf from"axios";var bE="No JWT in local storage. Run `devecocli auth login` first.";function EE(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 os=class{config;constructor(e){this.config={..._r,...e}}updateConfig(e){this.config={...this.config,...e}}async listTeams(){let e=await je.loadJwtToken();if(!e)throw new Error(bE);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=EE(i);return{userId:r??"",teamList:o}}async fetchTeamList(e,t){let r=this.config.agcTeamListUrl;m(`Executing: GET ${r}`);let i;try{i=await gf.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 gf.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 ns(this.config.countryCode??"",this.config.baseUrl)}},yf=new os;async function $t(){return yf.listTeams()}function CE(n){if(n.length===0)return He("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 IE(){return new Promise(n=>{let e=wf.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),n()})})}var si=new PE("auth").description("Authentication commands (login, logout, status, team)");si.command("login").description("Log in to your Huawei Developer account").action(async()=>{if(Ze()){console.log(qc("Login is managed by DevEco Code. Login from DevEco Code instead."));return}try{if(await te.isLoggedIn()){let t=await te.getUserInfo();if(t){console.log(He(`Already logged in, User Name:${t.userName}`));return}}console.log(He("Starting login process...")),console.log(He("Press Enter to open browser for login...")),await IE();let e=await te.login();console.log(He(`Login successful. Logged in as ${e.userName}.`))}catch(n){throw n instanceof ct?n:new Error("Login failed",{cause:n})}});si.command("logout").description("Log out of your Huawei Developer account").action(async()=>{if(Ze()){console.log(qc("Login is managed by DevEco Code. Log out from DevEco Code instead."));return}try{let n=await te.logout();console.log(n?He("Logout successful"):He("Already logged out."))}catch(n){throw new Error("Logout failed",{cause:n})}});si.command("status").description("Show the currently logged-in user").action(async()=>{try{if(!await te.isLoggedIn()){console.log(He("Not logged in"));return}let e=await te.getUserInfo();if(!e){console.log(He("Not logged in"));return}console.log(He(`Current user: ${e.userName}`))}catch{console.log(He("Not logged in"))}});var AE=si.command("team").description("Team-related commands");AE.command("list").description("List team accounts the current user has joined").action(async()=>{try{if(!await te.isLoggedIn()){Ze()?console.log(qc("Not logged in. Please login via DevEco Code first.")):console.log(He("Please run `devecocli auth login` first."));return}let e=await $t();console.log(CE(e.teamList))}catch(n){throw new Error("Failed to list teams",{cause:n})}});var vf=si;import{Command as UE}from"commander";import{green as BE,red as ui,cyan as Bf,yellow as Wf,dim as Gf}from"colorette";import WE from"p-limit";import DE from"ora";var Xe=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=DE(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 Sf from"fs";import*as bf from"path";import{homedir as kE}from"os";var Ef=["DevEco"];async function ss(){let n=await L.get(ze.TAGS_API_URL),t=as(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 RE(n){let e=[],t=ze.DEFAULT_PAGE_SIZE,r=1;for(;;){let i=await L.post(ze.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:r,pageSize:t,tagIds:[n]}}),o=as(i,"Skills API");if(e.push(...o.data.list),o.data.list.length<t)break;r++}return e}async function Yc(n){let e=new Map,t=n.map(i=>RE(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=>!Ef.includes(o.name)))}async function TE(n,e){let t=await L.post(ze.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:ze.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return as(t,"Skills API").data.list}async function Jc(n,e){let t=new Map,r=e.map(o=>TE(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=>!Ef.includes(s.name)))}function Pf(n){let e=[];for(let[,t]of Object.entries(qe)){let r=bf.join(kE(),t.path,n);Sf.existsSync(r)&&e.push(t.displayName)}return e.sort()}function as(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=L.parseJson(n);if(t.code!==ze.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Cf(n){let e=`${ze.SKILL_API_BASE}/${n}/checksum`,t=await L.get(e);return as(t,"Checksum API").data}import xE from"adm-zip";import LE from"crypto";import Af from"fs";import z from"path";import{fileURLToPath as NE}from"url";import{homedir as Df}from"os";import{red as OE}from"colorette";var vt=Af.promises;function Kc(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}function If(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 Zc(n){return z.isAbsolute(n)?n:z.resolve(process.cwd(),n)}function ME(n){return LE.createHash("sha256").update(n).digest("hex")}async function _E(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=ME(n),i=e.sha256.toLowerCase();if(r!==i)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function kf(n){let e=`${ze.SKILL_API_BASE}/${n}/install?format=zip`,t=await L.getBinary(e),r=await Cf(n);return await _E(t,r),t}async function FE(n,e,t){Kc(t);let r=new xE(n),i=r.getEntries();try{await vt.stat(e)}catch{await vt.mkdir(e,{recursive:!0})}let o=z.join(e,t);If(e,o);for(let s of i){let a=z.join(o,s.entryName);If(o,a)}r.extractAllTo(o,!0)}async function Xc(n){let e=qe[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(qe).join(", ")}`);let t=z.join(Df(),e.path.replace("/skills",""));try{return await vt.access(t),!0}catch{return!1}}function Qc(n){let e=qe[n];return z.join(Df(),e.path)}function jE(n){let e=qe[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(qe).join(", ")}`);return e}function el(n,e){let t=jE(e),r="projectPath"in t?t.projectPath:z.join("."+e,"skills");return z.join(n,r)}async function HE(n,e,t){Kc(e);let r=z.join(n,e);try{if(await vt.access(r),t)await vt.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 tl(n,e,t){await FE(n,e,t),console.log(`Skill ${t} installed to ${z.join(e,t)}.`)}async function nl(n,e,t){let r=z.join(e,t);await vt.mkdir(r,{recursive:!0});let i=z.join(r,z.basename(n));await vt.copyFile(n,i),console.log(`Skill ${t} installed to ${r}.`)}function Rf(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(OE(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function Kn(n,e,t,r){try{let i=await e(),{shouldSkip:o}=await HE(i,n,r);return o?{success:!0,skipped:!0}:(await t(i),{success:!0})}catch(i){return Rf(n,i,"Installation failed")}}async function rl(n,e){try{Kc(n);let t=await e(),r=z.join(t,n);try{await vt.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await vt.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return Rf(n,t,"Removal failed")}}async function Tf(n,e,t,r=!1){return Kn(n,()=>Qc(e),i=>tl(t,i,n),r)}async function xf(n,e,t,r=!1){return Kn(n,()=>t,i=>tl(e,i,n),r)}async function Lf(n,e,t,r,i=!1){return Kn(n,()=>el(t,r),o=>tl(e,o,n),i)}async function Nf(n,e,t,r=!1){return Kn(n,()=>Qc(t),i=>nl(e,i,n),r)}async function Of(n,e,t,r,i=!1){return Kn(n,()=>el(t,r),o=>nl(e,o,n),i)}async function Mf(n,e,t,r=!1){return Kn(n,()=>t,i=>nl(e,i,n),r)}async function _f(n,e){return rl(n,()=>Qc(e))}async function Ff(n,e){return rl(n,()=>e)}async function jf(n,e,t){return rl(n,()=>el(e,t))}function Hf(){let e=z.dirname(NE(import.meta.url));for(;;){let t=z.join(e,"SKILL.md");if(Af.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 $f from"fs";import{cyan as $E}from"colorette";async function ai(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await Xc(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function ci(){let n=[];for(let e of Object.keys(qe))await Xc(e)&&n.push(e);return n}function li(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($E("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function Ut(n,e,t){if(!$f.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!$f.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function di(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?Zc(n):void 0,resolvedProject:e?Zc(e):void 0}}async function cs(n,e,t){let r=[],i=[],o;if(e?o=e:t&&n.agent?i=(await ai(n.agent)).map(a=>({project:t,agent:a})):t?i=(await ci()).map(a=>({project:t,agent:a})):n.agent?r=await ai(n.agent):r=await ci(),!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 GE(n){let e=await ss();if(n.all)return(await Yc(e)).map(r=>r.enName);{let r=(await Jc(n.skill,e)).find(i=>i.enName===n.skill);if(!r)throw new Error(`Skill "${n.skill}" not found`);return[r.enName]}}async function VE(n,e,t,r){let i=[];if(t.customPath){let o=await xf(n,e,t.customPath,r);return i.push(o),i}for(let o of t.agents){let s=await Tf(n,o,e,r);i.push(s)}for(let{project:o,agent:s}of t.projectAgents){let a=await Lf(n,e,o,s,r);i.push(a)}return i}function zE(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}=di(n.path,n.project,n.agent);return t&&Ut(t,"Project directory",n.force),e&&Ut(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}async function qE(n,e,t){let r=await cs(n,e,t);return{skillNames:await GE(n),targets:r}}async function YE(n,e,t,r){let i=[],o=n.length,s=WE(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(ui(`${l}: Download failed - ${g.error}`)),i.push({success:!1});continue}r.stop();let w=await VE(l,g.buffer,e,t);i.push(...w)}return i}async function JE(n){try{let e=await kf(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 KE(n){let e=new Xe;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=zE(n),{skillNames:i,targets:o}=await qE(n,t,r),s=await YE(i,o,n.force||!1,e);e.stop(),li(s)}catch(t){throw e.stop(),t}}function ZE(n){let{resolvedPath:e,resolvedProject:t}=di(n.path,n.project,n.agent);return t&&Ut(t,"Project directory"),e&&Ut(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function XE(n,e){let t=new Xe;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:i}=ZE(e);t.stop();let o=await QE(e,n,r,i);t.stop(),li(o)}catch(r){throw t.stop(),r}}function Uf(n,e=""){if(n.length===0)throw new Error(`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function ls(n,e){let t=[];for(let r of e){let i=r.type==="agent"?await _f(n,r.agent):await jf(n,r.project,r.agent);t.push(i)}return t}async function QE(n,e,t,r){if(t)return[await Ff(e,t)];if(r&&n.agent){let a=(await ai(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return ls(e,a)}if(r){let s=await ci();Uf(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return ls(e,a)}if(n.agent){let a=(await ai(n.agent)).map(c=>({type:"agent",agent:c}));return ls(e,a)}let i=await ci();Uf(i,"or use --path for a custom location.");let o=i.map(s=>({type:"agent",agent:s}));return ls(e,o)}var pi=new UE("skills").description("Manage HarmonyOS skills");pi.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 ss(),r=await Yc(t);if(r.length===0){e.stop(),console.log(Wf("No skills available."));return}e.succeed(`Fetched ${r.length} skills`);for(let i of r)if(n.long){console.log(Bf(i.enName)),console.log(Gf(i.description));let o=Pf(i.enName);o.length>0&&console.log(BE(`Installed for: ${o.join(", ")}`)),console.log()}else console.log(i.enName)}catch(t){e.stop(),console.error(ui(t.message)),process.exit(1)}});pi.command("find <keyword>").description("Search skills by keyword").action(async n=>{let e=new Xe;try{e.start("Searching skills...");let t=await ss(),r=await Jc(n,t);if(r.length===0){console.log(Wf(`No skills found matching '${n}'.`)),e.stop();return}e.succeed(`Found ${r.length} skills.`);for(let i of r)console.log(Bf(i.enName)),console.log(Gf(i.description)),console.log()}catch(t){e.stop(),console.error(ui(t.message)),process.exit(1)}});pi.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 KE(n)}catch(e){console.error(ui(e.message)),process.exit(1)}});pi.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 XE(n.skill,n)}catch(e){console.error(ui(e.message)),process.exit(1)}});var Vf=pi;import{Command as tP,InvalidArgumentError as qf}from"commander";import{cyan as ds}from"colorette";function Sn(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=Fn(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 il=[800,1500,2500];function eP(n){return new Promise(e=>setTimeout(e,n))}var Zn=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=Q.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(ds(`Using device serial: ${i}`)),i}if(e&&t.includes(e))return m(ds(`Using device serial: ${e}`)),e;let r=await this.loadConnectedDevicesByName();if(e){let i=this.findDeviceByArg(r,e);if(i)return m(ds(`Using device: ${i.name} (${i.serial})`)),i.serial;let o=this.formatConnectedDeviceList(r);throw new Error(`Device '${e}' not found.
1257
1257
  Available devices:
1258
- ${o}`)}if(r.length===1){let i=r[0];return m(ts(`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 xe(e,["-t",t,"shell","pidof",r]),o=vn(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 xe(e,["-t",t,"shell","hilog","-G",r]),o=vn(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 Iu(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+Bc.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||jn(a.stderr)!=="transient"||c>=s-1)return a;m(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${Bc[c]}ms`),await xb(Bc[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=vn(c,"Failed to get hilog");if(l)throw l;if(c.exitCode!==0&&c.stderr)throw new Error(`Failed to get hilog: ${c.stderr}`);let d=P.filterLogsByRelativeWindow(c.stdout||c.stderr,r.fromSeconds,r.toSeconds);d=P.getLastLines(d,r.tail),d.trim()&&console.log(d)}async getHilogOnce(e,t,r,i){let[o,s]=this.buildHilogCommand(e,t,r,i);m(`Ready to run hilog command: ${o} ${s.join(" ")}`);let a=await this.runHilogStreamingCollect(o,s,"a single hilog streaming read"),c=vn(a,"Failed to get hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to get hilog: ${a.stderr}`);let l=a.stdout||a.stderr,d=P.filterLogsByRelativeWindow(l,r.fromSeconds,r.toSeconds);return d=P.getLastLines(d,r.tail),d}async runHilogFollow(e,t,r,i){try{await this.printTailSnapshotIfNeeded(e,t,r,i)}catch(l){console.error(`Warning: Failed to fetch log snapshot, continuing with live stream: ${l.message}`)}let[o,s]=this.buildHilogCommand(e,t,r,i);m(`Ready to run hilog command which contain \`follow\` and \`tail\`: ${o} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(o,s,this.createFollowLineHandler(),l=>{m(`Spawn error during hilog follow: ${l.message}`)},()=>{}),c=vn(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 d=c.split("-").pop()||"";return(l.split("-").pop()||"").localeCompare(d)})[0],a=await this.fetchCrashLogContent(r,e,s);return`--- Latest Crash Log File: ${s} ---${a}`}async listCrashLogs(e,t,r){let i=["-t",t,"shell","hidumper","-s","1201","-a","-p Faultlogger"];m(`Running command: ${e} ${i.join(" ")}`);let o=await this.runHilogStreamingCollect(e,i,"a crash log list streaming read"),s=vn(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:
1258
+ ${o}`)}if(r.length===1){let i=r[0];return m(ds(`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}`),C.assertBundleName(r);let i=await De(e,["-t",t,"shell","pidof",r]),o=Sn(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 De(e,["-t",t,"shell","hilog","-G",r]),o=Sn(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&&(C.assertHilogToken(e.tag,"tag"),r.push("-T",e.tag)),e.level&&(C.assertHilogLevel(e.level),r.push("-L",e.level)),e.domain&&(C.assertHilogToken(e.domain,"domain"),r.push("-D",e.domain)),t&&r.push("-P",t),e.keyword&&(C.assertHilogKeyword(e.keyword),r.push("-e",C.quotePosixShellArg(e.keyword))),r.join(" ")}async followHilog(e,t,r,i,o){let a=await Bu(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+il.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||Fn(a.stderr)!=="transient"||c>=s-1)return a;m(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${il[c]}ms`),await eP(il[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=Sn(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=C.filterLogsByRelativeWindow(c.stdout||c.stderr,r.fromSeconds,r.toSeconds);p=C.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=Sn(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=C.filterLogsByRelativeWindow(l,r.fromSeconds,r.toSeconds);return p=C.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=Sn(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=Sn(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
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=vn(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 Wc,red as If}from"colorette";import Nb from"ora";function Ob(n){try{return P.parsePositiveInteger(n,"tail")}catch{throw new Cf("`tail` must be a positive integer.")}}function Pf(n,e){try{return P.parseDurationToSeconds(n,e)}catch{throw new Cf(`${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 Mb(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.");P.assertRelativeTimeRange(n.from,n.to)}async function _b(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 Fb(n,e,t,r){let i=P.filterLogsByRelativeWindow(n,t,r);return e.tail?P.getLastLines(i,e.tail):i}var jb=new Lb("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(If(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",Ob).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>Pf(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>Pf(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await Hb(n)});async function Hb(n){let e=Nb({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),Mb(n);let r=n.from,i=n.to,o=await I.new(),s=new Kn(o),a=await s.selectDevice(n.device);a||(t(),process.exit(1)),m(Wc(`deviceId: ${a}`)),m(Wc(`type: ${n.crash?"Crash logs":"Common logs"}`)),m(Wc("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await _b(s,a,n,r,i);t(),n.crash&&c&&(c=Fb(c,n,r,i)),c&&console.log(c)}catch(r){t(),console.error(If(r.message)),process.exit(1)}}var Af=jb;import pi from"path";import Et from"fs";import zc from"process";import Mf from"os";import{Command as Zb}from"commander";import{green as xf,red as Gc,cyan as Qb,yellow as Lf}from"colorette";import re from"fs-extra";import F from"path";import*as Rf from"os";import{fileURLToPath as $b}from"url";var Df={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"}},Ub=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function Bb(){let n=import.meta.url,e=$b(n);if(e.includes("dist")){let o=F.dirname(e),s=F.dirname(o);return F.join(s,"templates","application")}let t=F.dirname(e),r=F.dirname(t),i=F.dirname(r);return F.join(i,"templates","application")}function Tf(n,e){re.mkdirSync(e,{recursive:!0});for(let t of re.readdirSync(n,{withFileTypes:!0})){let r=F.join(n,t.name),i=F.join(e,t.name);if(t.isDirectory()){Tf(r,i);continue}re.existsSync(i)||(re.mkdirSync(F.dirname(i),{recursive:!0}),re.copyFileSync(r,i))}}function ui(n,e){let t=re.readFileSync(n,"utf-8"),r=t;for(let[i,o]of e)r=r.replaceAll(i,o);r!==t&&re.writeFileSync(n,r,"utf-8")}function Wb(n){if(Df[n])return Df[n];if(n>=26){let e=`${n}.0.0`;return{sdkVersion:e,modelVersion:e}}}function Gb(n,e){if(e===22)return;let t=Wb(e);t&&(ui(F.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),ui(F.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),ui(F.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function zb(n){return Ub.filter(t=>!re.existsSync(F.join(n,t))).length===0}function Vb(){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 qb(n){return Rf.platform()==="darwin"?F.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):F.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function Yb(n,e){let t=qb(e);if(!re.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=F.join(t,i),a=F.join(n,o);re.existsSync(s)&&(re.mkdirSync(F.dirname(a),{recursive:!0}),re.copyFileSync(s,a))}return!0}function Jb(n){let e=Vb(),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=F.join(n,r);re.mkdirSync(F.dirname(i),{recursive:!0}),re.writeFileSync(i,e)}}function Kb(n,e){e&&Yb(n,e)||Jb(n)}function Xb(n){let e=[F.join(n,"gitignore.txt"),F.join(n,"entry","gitignore.txt")];for(let t of e)if(re.existsSync(t)){let r=F.dirname(t);re.renameSync(t,F.join(r,".gitignore"))}}function kf(n,e,t,r,i){let o=Bb();if(!re.existsSync(o))throw new Error(`Template directory not found: ${o}`);re.mkdirSync(n,{recursive:!0}),Tf(o,n),Xb(n),Kb(n,i),ui(F.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),ui(F.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),Gb(n,r);let s=zb(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function eP(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 tP(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 _f(n){if(Mf.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function Nf(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=Mf.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=_f(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 nP(n){let e=n,t=pi.parse(n).root;for(;e!==t;){if(Et.existsSync(e))return e;e=pi.dirname(e)}return Et.existsSync(t)?t:null}function Of(n){let e=nP(n);if(!e)throw new Error(`No existing parent directory found for '${n}'. Cannot create project directory.`);try{Et.accessSync(e,Et.constants.W_OK)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}let t=pi.join(e,`.deveco_write_test_${Date.now()}`);try{Et.writeFileSync(t,"test"),Et.unlinkSync(t)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}}function rP(n){return`com.example.${n.toLowerCase()}`}function iP(n,e){if(e){let i=_f(e),o=pi.resolve(i);if(Et.existsSync(o)){if(Et.readdirSync(o).length>0)throw new Error(`Directory '${o}' is not empty. Cannot create project here.`)}else Of(o);return o}let t=zc.cwd(),r=pi.join(t,n);if(Et.existsSync(r))throw new Error(`Directory '${r}' already exists. Cannot create project here.`);return Of(r),r}function oP(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 sP(){try{return await I.new()}catch(n){console.error(Lf(`DevEco Studio not found: ${n.message}`)),console.log(Lf("Use placeholder API level instead."));return}}var aP=new Zb("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(Gc("Error: --app-name is required")),zc.exit(1));let e=n.appName;eP(e);let t=n.bundleName||rP(e);tP(t),n.projectPath&&Nf(n.projectPath);let r=iP(e,n.projectPath);Nf(r),console.log(Qb("Initializing project...")),console.log(`Project path: ${r}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let i=await sP(),o=oP(n,i);console.log(`API level: ${o}`);let s=i?.devecoStudioPath,a=kf(r,e,t,o,s);console.log(`
1261
- `+xf("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(xf("Template integrity check passed."))}catch(e){let t=e;console.error(Gc(`
1262
- Failed to create project.`)),console.error(Gc(t.message)),zc.exit(1)}}),Ff=aP;import{Command as mP}from"commander";import{red as hP,cyan as Gf}from"colorette";import cP from"fs";import ns from"path";import{cyan as lP}from"colorette";import*as rs from"smol-toml";var Xn=cP.promises;async function dP(n){try{let e=await Xn.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 uP(n){try{let e=await Xn.readFile(n,"utf8");return e.trim()===""?{}:rs.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 pP(n,e){let t=ns.dirname(n);await Xn.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await Xn.writeFile(n,r,"utf8")}async function fP(n,e){let t=ns.dirname(n);await Xn.mkdir(t,{recursive:!0});let r=rs.stringify(e);await Xn.writeFile(n,r,"utf8")}function jf(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function Hf(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 $f(n,e){return n.format==="codex"?uP(e):dP(e)}async function Uf(n,e,t){return n.format==="codex"?fP(e,t):pP(e,t)}async function Bf(n,e,t=!1){let r=Ot[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Ot).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 $f(r,r.globalConfigPath);if(jf(i,r.mcpServersKey,at)&&!t)return console.log(`MCP server ${at} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let o=lo(r,void 0);return Hf(i,r.mcpServersKey,at,o,t),await Uf(r,r.globalConfigPath,i),console.log(`MCP server ${at} 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 Vc(n,e,t=!1){let r=Ot[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Ot).join(", ")}`};let i=ns.isAbsolute(r.projectConfigPath)?r.projectConfigPath:ns.join(e,r.projectConfigPath);try{let o=await $f(r,i);if(jf(o,r.mcpServersKey,at)&&!t)return console.log(`MCP server ${at} already configured in ${i}.`),{success:!0,skipped:!0,configPath:i,agentName:n,installType:"project"};let s=lo(r,e);return Hf(o,r.mcpServersKey,at,s,t),await Uf(r,i,o),console.log(`MCP server ${at} 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 Wf(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(lP("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 qc="deveco-cli";async function gP(n,e,t){if(n.customPath)return[await pf(qc,e,n.customPath,t.force)];let r=[...n.projectAgents.map(({project:s,agent:a})=>()=>uf(qc,e,s,a,t.force)),...n.agents.map(s=>()=>df(qc,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 yP(n,e,t){let r=[];for(let{project:i,agent:o}of n.projectAgents){let s=await Vc(o,i,t);r.push(s)}for(let i of n.agents){let o=await Vc(i,e,t);r.push(o)}return r}async function wP(n,e){let t=[];for(let r of n){if(!Ot[r])continue;let o=await Bf(r,process.cwd(),e);t.push(o)}return t}async function vP(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 yP(s,e,r):await wP(s.agents,r);a.length>0&&(console.log(Gf("MCP Configuration:")),Wf(a))}async function SP(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}=ci(n.path,n.project,n.agent);t&&Ht(t,"Project directory",n.force),e&&Ht(e,"Directory",n.force);let r=await Qo(n,e,t);if(n.mcp){await vP(r,t,n);return}let i=gf(),o=await gP(r,i,n);console.log(),o.length>0&&(console.log(Gf("Skill Installation:")),ai(o))}var EP=new mP("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 SP(n)}catch(e){console.error(hP(e.message)),process.exit(1)}}),zf=EP;import{Command as hC}from"commander";import{McpServer as QP}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as eC}from"@modelcontextprotocol/sdk/server/stdio.js";import*as Pn from"path";import*as sm from"fs";import{z as pe}from"zod";var is=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 Yc(){return new is}import*as be from"fs";import*as ue from"path";import{z as Xc}from"zod";function Vf(n){return"method"in n&&!("id"in n)}import{spawn as bP}from"child_process";import{EventEmitter as PP}from"events";import*as Zn from"fs";import*as qf from"path";var $t=class extends PP{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;ensureDirectories(){let t=qf.join(this.config.logPath,"lspLog");return Zn.existsSync(t)||Zn.mkdirSync(t,{recursive:!0}),Zn.existsSync(this.config.indexingDataLocation)||Zn.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){let r=this.ensureDirectories();f.info(`[LspClient] serverMaxSize=${t}MB`);let i=H(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=bP(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
1260
+ `).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>{try{return C.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=Sn(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 ol,red as Yf}from"colorette";import nP from"ora";function rP(n){try{return C.parsePositiveInteger(n,"tail")}catch{throw new qf("`tail` must be a positive integer.")}}function zf(n,e){try{return C.parseDurationToSeconds(n,e)}catch{throw new qf(`${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 iP(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.")}async function oP(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 sP(n,e,t,r){let i=C.filterLogsByRelativeWindow(n,t,r);return e.tail?C.getLastLines(i,e.tail):i}var aP=new tP("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(Yf(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",rP).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>zf(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>zf(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await cP(n)});async function cP(n){let e=nP({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),iP(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(ol(`deviceId: ${a}`)),m(ol(`type: ${n.crash?"Crash logs":"Common logs"}`)),m(ol("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await oP(s,a,n,r,i);t(),n.crash&&c&&(c=sP(c,n,r,i)),c&&console.log(c)}catch(r){t(),console.error(Yf(r.message)),process.exit(1)}}var Jf=aP;import mi from"path";import St from"fs";import al from"process";import im from"os";import{Command as bP}from"commander";import{green as em,red as sl,cyan as EP,yellow as tm}from"colorette";import ne from"fs-extra";import F from"path";import*as Zf from"os";import{fileURLToPath as lP}from"url";var Kf={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"}},dP=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function uP(){let n=import.meta.url,e=lP(n);if(e.includes("dist")){let o=F.dirname(e),s=F.dirname(o);return F.join(s,"templates","application")}let t=F.dirname(e),r=F.dirname(t),i=F.dirname(r);return F.join(i,"templates","application")}function Xf(n,e){ne.mkdirSync(e,{recursive:!0});for(let t of ne.readdirSync(n,{withFileTypes:!0})){let r=F.join(n,t.name),i=F.join(e,t.name);if(t.isDirectory()){Xf(r,i);continue}ne.existsSync(i)||(ne.mkdirSync(F.dirname(i),{recursive:!0}),ne.copyFileSync(r,i))}}function fi(n,e){let t=ne.readFileSync(n,"utf-8"),r=t;for(let[i,o]of e)r=r.replaceAll(i,o);r!==t&&ne.writeFileSync(n,r,"utf-8")}function pP(n){if(Kf[n])return Kf[n];if(n>=26){let e=`${n}.0.0`;return{sdkVersion:e,modelVersion:e}}}function fP(n,e){if(e===22)return;let t=pP(e);t&&(fi(F.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),fi(F.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),fi(F.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function mP(n){return dP.filter(t=>!ne.existsSync(F.join(n,t))).length===0}function hP(){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 gP(n){return Zf.platform()==="darwin"?F.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):F.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function yP(n,e){let t=gP(e);if(!ne.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=F.join(t,i),a=F.join(n,o);ne.existsSync(s)&&(ne.mkdirSync(F.dirname(a),{recursive:!0}),ne.copyFileSync(s,a))}return!0}function wP(n){let e=hP(),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=F.join(n,r);ne.mkdirSync(F.dirname(i),{recursive:!0}),ne.writeFileSync(i,e)}}function vP(n,e){e&&yP(n,e)||wP(n)}function SP(n){let e=[F.join(n,"gitignore.txt"),F.join(n,"entry","gitignore.txt")];for(let t of e)if(ne.existsSync(t)){let r=F.dirname(t);ne.renameSync(t,F.join(r,".gitignore"))}}function Qf(n,e,t,r,i){let o=uP();if(!ne.existsSync(o))throw new Error(`Template directory not found: ${o}`);ne.mkdirSync(n,{recursive:!0}),Xf(o,n),SP(n),vP(n,i),fi(F.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),fi(F.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),fP(n,r);let s=mP(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function PP(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 CP(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 om(n){if(im.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function nm(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=im.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=om(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 IP(n){let e=n,t=mi.parse(n).root;for(;e!==t;){if(St.existsSync(e))return e;e=mi.dirname(e)}return St.existsSync(t)?t:null}function rm(n){let e=IP(n);if(!e)throw new Error(`No existing parent directory found for '${n}'. Cannot create project directory.`);try{St.accessSync(e,St.constants.W_OK)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}let t=mi.join(e,`.deveco_write_test_${Date.now()}`);try{St.writeFileSync(t,"test"),St.unlinkSync(t)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}}function AP(n){return`com.example.${n.toLowerCase()}`}function DP(n,e){if(e){let i=om(e),o=mi.resolve(i);if(St.existsSync(o)){if(St.readdirSync(o).length>0)throw new Error(`Directory '${o}' is not empty. Cannot create project here.`)}else rm(o);return o}let t=al.cwd(),r=mi.join(t,n);if(St.existsSync(r))throw new Error(`Directory '${r}' already exists. Cannot create project here.`);return rm(r),r}function kP(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 RP(){try{return await I.new()}catch(n){console.error(tm(`DevEco Studio not found: ${n.message}`)),console.log(tm("Use placeholder API level instead."));return}}var TP=new bP("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(sl("Error: --app-name is required")),al.exit(1));let e=n.appName;PP(e);let t=n.bundleName||AP(e);CP(t),n.projectPath&&nm(n.projectPath);let r=DP(e,n.projectPath);nm(r),console.log(EP("Initializing project...")),console.log(`Project path: ${r}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let i=await RP(),o=kP(n,i);console.log(`API level: ${o}`);let s=i?.devecoStudioPath,a=Qf(r,e,t,o,s);console.log(`
1261
+ `+em("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(em("Template integrity check passed."))}catch(e){let t=e;console.error(sl(`
1262
+ Failed to create project.`)),console.error(sl(t.message)),al.exit(1)}}),sm=TP;import{Command as FP}from"commander";import{red as jP,cyan as fm}from"colorette";import xP from"fs";import us from"path";import{cyan as LP}from"colorette";import*as ps from"smol-toml";var Xn=xP.promises;async function NP(n){try{let e=await Xn.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 OP(n){try{let e=await Xn.readFile(n,"utf8");return e.trim()===""?{}:ps.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 MP(n,e){let t=us.dirname(n);await Xn.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await Xn.writeFile(n,r,"utf8")}async function _P(n,e){let t=us.dirname(n);await Xn.mkdir(t,{recursive:!0});let r=ps.stringify(e);await Xn.writeFile(n,r,"utf8")}function am(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function cm(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 lm(n,e){return n.format==="codex"?OP(e):NP(e)}async function dm(n,e,t){return n.format==="codex"?_P(e,t):MP(e,t)}async function um(n,e,t=!1){let r=Nt[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Nt).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 lm(r,r.globalConfigPath);if(am(i,r.mcpServersKey,st)&&!t)return console.log(`MCP server ${st} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let o=po(r,void 0);return cm(i,r.mcpServersKey,st,o,t),await dm(r,r.globalConfigPath,i),console.log(`MCP server ${st} 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 cl(n,e,t=!1){let r=Nt[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Nt).join(", ")}`};let i=us.isAbsolute(r.projectConfigPath)?r.projectConfigPath:us.join(e,r.projectConfigPath);try{let o=await lm(r,i);if(am(o,r.mcpServersKey,st)&&!t)return console.log(`MCP server ${st} already configured in ${i}.`),{success:!0,skipped:!0,configPath:i,agentName:n,installType:"project"};let s=po(r,e);return cm(o,r.mcpServersKey,st,s,t),await dm(r,i,o),console.log(`MCP server ${st} 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 pm(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(LP("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 ll="deveco-cli";async function HP(n,e,t){if(n.customPath)return[await Mf(ll,e,n.customPath,t.force)];let r=[...n.projectAgents.map(({project:s,agent:a})=>()=>Of(ll,e,s,a,t.force)),...n.agents.map(s=>()=>Nf(ll,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 $P(n,e,t){let r=[];for(let{project:i,agent:o}of n.projectAgents){let s=await cl(o,i,t);r.push(s)}for(let i of n.agents){let o=await cl(i,e,t);r.push(o)}return r}async function UP(n,e){let t=[];for(let r of n){if(!Nt[r])continue;let o=await um(r,process.cwd(),e);t.push(o)}return t}async function BP(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 $P(s,e,r):await UP(s.agents,r);a.length>0&&(console.log(fm("MCP Configuration:")),pm(a))}async function WP(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}=di(n.path,n.project,n.agent);t&&Ut(t,"Project directory",n.force),e&&Ut(e,"Directory",n.force);let r=await cs(n,e,t);if(n.mcp){await BP(r,t,n);return}let i=Hf(),o=await HP(r,i,n);console.log(),o.length>0&&(console.log(fm("Skill Installation:")),li(o))}var GP=new FP("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 WP(n)}catch(e){console.error(jP(e.message)),process.exit(1)}}),mm=GP;import{Command as jC}from"commander";import{McpServer as EC}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as PC}from"@modelcontextprotocol/sdk/server/stdio.js";import*as qs from"path";import{z as ue}from"zod";var fs=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 dl(){return new fs}import*as Re from"fs";import*as ke from"path";import{z as ml}from"zod";function hm(n){return"method"in n&&!("id"in n)}import{spawn as VP}from"child_process";import{EventEmitter as zP}from"events";import*as Qn from"fs";import*as gm from"path";var Bt=class extends zP{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;ensureDirectories(){let t=gm.join(this.config.logPath,"lspLog");return Qn.existsSync(t)||Qn.mkdirSync(t,{recursive:!0}),Qn.existsSync(this.config.indexingDataLocation)||Qn.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){let r=this.ensureDirectories();f.info(`[LspClient] serverMaxSize=${t}MB`);let i=H(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=VP(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
1263
  \r
1264
1264
  ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this.buffer.indexOf(`\r
1265
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"),d=this.recoverFramedJson(l);if(d&&d.rest.length>0){f.warn(`[LspClient] recovered mixed LSP frame, bodyLen=${l.length}, restLen=${d.rest.length}`),this.emit("message",d.json),this.buffer=Buffer.concat([Buffer.from(d.rest,"utf8"),this.buffer.slice(c)]);continue}this.emit("message",l),this.buffer=this.buffer.slice(c)}}waitForExitOrTimeout(t){let r=this.process;return!r||r.exitCode!==null||r.signalCode!==null?Promise.resolve():new Promise(i=>{let o=!1,s=()=>{o||(o=!0,clearTimeout(c),r.off("exit",a),i())},a=()=>s();r.once("exit",a);let c=setTimeout(s,t)})}recoverFramedJson(t){let r=t.search(/\S/);if(r<0||t[r]!=="{"&&t[r]!=="[")return null;let i=0,o=!1,s=!1;for(let a=r;a<t.length;a++){let c=t[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(o=!1);continue}if(c==='"'){o=!0;continue}if(c==="{"||c==="["){i++;continue}if((c==="}"||c==="]")&&(i--,i===0)){let l=t.slice(r,a+1),d=t.slice(a+1);return{json:l,rest:d}}}return null}stop(){this.isClosing=!0;let t=this.process;if(!t)return;if(this.process=null,t.exitCode===null&&t.signalCode===null)try{t.kill()}catch{}}};var Ut=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 os=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var Qn=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 A(n){return typeof n=="object"&&n!==null}var Yf=20*1e3,CP=30*1e3,ss=class{client;nextRequestId=1;stopOnce=null;callbacks=new Qn;requestCallbacks=new Ut;diagnosticMap=new Map;initProgressReset=null;constructor(e){this.client=new $t(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,Me);return this.client.sendRequest(y.INITIALIZE,e,t),r}sendInitializeResettable(e,t){let r=this.nextRequestId++,i=this.requestCallbacks.registerPending(r,y.INITIALIZE,0);return this.client.sendRequest(y.INITIALIZE,e,r),new Promise((o,s)=>{let a,c=()=>{a=setTimeout(()=>{this.initProgressReset=null,s(new Error(`LSP initialization timeout after ${t}ms`))},t)},l=()=>{clearTimeout(a),c()};this.initProgressReset=l,c(),i.then(()=>{clearTimeout(a),this.initProgressReset=null,o()},d=>{clearTimeout(a),this.initProgressReset=null,s(d)})})}sendInitialized(){this.client.sendNotification(y.INITIALIZED,{})}sendDidOpen(e){let t=e.textDocument.uri;this.diagnosticMap.has(t)||(this.diagnosticMap.set(t,new os(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=CP){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){A(e)&&this.broadcastToClients({jsonrpc:R,method:y.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,y.PUBLISH_DIAGNOSTICS,Yf,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${Yf}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 as=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 Jc(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)}},Jc=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var IP={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"},AP={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"},T={...IP,...AP},Bt={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"},Jf=new Set([1e3,2e3,3e3,3001]);function DP(n){if(!A(n))return!1;let e=n.textDocument;return A(e)&&typeof e.uri=="string"}function RP(n){return A(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function TP(n){return A(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 cs=class n{client;isInitialized=!1;stopOnce=null;callbacks=new Qn;requestCallbacks=new Ut;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;constructor(e){this.client=new $t(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:T.EXIT,params:{}}),Bt.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(T.BROADCAST),this.callbacks.register(T.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(T.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(T.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(T.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:T.INITIALIZED,params:{editors:e}}),Bt.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:R,id:0,result:{}}),Bt.EMPTY)}sendAsyncRequest(e,t,r,i){if(!A(t)){f.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!DP(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=Ke(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(!RP(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:T.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),T.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!A(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:T.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),Bt.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let i=Ke(t);e.textDocument.uri=i,f.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new as(i),this.diagnosticMap.set(i,o),this.registerDiagnosticTimeout(i,T.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(o.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:T.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),Bt.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=Ke(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,T.PUBLISH_DIAGNOSTICS)),f.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:T.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),Bt.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=Ke(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:T.DID_CLOSE,params:{textDocument:{uri:r}}}),Bt.DID_CLOSE)}getDiagnosticMessage(e){let t=Ke(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,T.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:R,method:T.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 T.MODULE_INIT_FINISH:return f.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(T.MODULE_INIT_FINISH),this.callbacks.unregister(T.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case T.INDEXING_PROGRESS_UPDATE:return f.info(`[LSP] onIndexingProgressUpdate: ${TP(t.params)}`),this.callbacks.invoke(T.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case T.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case T.ON_PACKAGE_CHANGE_FINISH:f.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case T.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case T.ON_ASYNC_HOVER:this.handleAsyncResponse(t,T.HOVER);return;case T.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,T.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case T.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,T.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;A(t)&&A(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:T.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(!A(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,T.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(Jf)&&this.finalizeDiagnostic(t,T.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 wi from"path";import*as hs from"path";var ls=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var ds=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var us=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var ps=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var fs=class{typeSetting=new us;parameterNames=new ps};var ms=class{constructor(e,t,r,i){this.rootUri=e;this.lspServerWorkspacePath=H(hs.dirname(t)),this.indexingDataLocation=H(i),this.loggerPath=H(hs.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new ls;gutterIconsSetting=new ds;inlayHintsSetting=new fs;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as Kf from"path";var fi=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(H(Kf.join(e,"src","main","resources")))}};var kP="OS",er=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${kP}`;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 fi(e)):this.buildProfileParam=new fi}toString(){return JSON.stringify(this)}};var tr=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as $e from"path";import*as ir from"fs";var gs=class{modulePath;dependencies={};dynamicDependencies={}};var Sn=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 nr=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 bt from"path";import*as ys from"fs";var rr=class{name="";version="";storePath="";dependencyPath="";path=""};var O={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:Ye.OH_PACKAGE_JSON5},mi=`${O.HVIGOR_CACHE}/${O.DEPENDENCY}`,En=`${O.DEPENDENCY}${O.JSON5}`,_0=Ye.SYNC_OUTPUT_PATH;var hi=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=bt.join(this.dependencyPath,O.OH_PACKAGE_JSON5),r=Te(t);r&&(this.dependencies=this.getDependencyList(r,O.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(r,O.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(r,O.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let r=[];if(!A(e))return r;let i=e[t];if(!A(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 rr;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=bt.normalize(bt.join(this.modulePath,O.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)),bt.isAbsolute(s)){r.dependencyPath=o;return}if(!i){let a=bt.resolve(this.modulePath,s);o=P.ensurePathWithinRoot(this.projectPath,a)}ys.existsSync(o)&&ys.statSync(o).isDirectory()&&(r.dependencyPath=o)}catch(o){f.error("parser dependency path is invalid",o)}}};import*as gi from"fs";import*as yi from"path";import xP from"json5";var ws=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 yi.join(this.projectPath,O.OH_MODULES_PATH,O.OHPM_PATH,O.LOCK_JSON5_FILE)}readLockFile(e){if(!gi.existsSync(e))return f.error("lock file does not exist"),this.clearDependencies(),null;try{let t=gi.readFileSync(e,"utf8"),r=xP.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(!A(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,O.KEY_DEPENDENCY,r),this.finalDevDependencies=this.getDependencyList(e,O.KEY_DEV_DEPENDENCY,r),this.finalDynamicDependencies=this.getDependencyList(e,O.KEY_DYNAMIC_DEPENDENCY,r)}parseStorePathMap(e){let t=new Map;if(!A(e))return t;for(let[r,i]of Object.entries(e)){if(!A(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(!A(e))return[];for(let[i,o]of Object.entries(e))if(A(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(!A(i))return f.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!A(s))return[];for(let[a,c]of Object.entries(s)){if(!A(c))continue;let l=typeof c.specifier=="string"?c.specifier:"",d=typeof c.version=="string"?c.version:"",h=new rr;h.name=a,h.version=d.startsWith(n.FILE_DEPENDENCY_PREFIX)?d.substring(n.FILE_DEPENDENCY_PREFIX.length):d,this.parseDependencyPath(h,r,a,l,d);let w=`${a}@${d}`;this.storePathMap.has(w)&&(h.storePath=this.storePathMap.get(w)||""),o.push(h)}return o}parseDependencyPath(e,t,r,i,o){let s=P.resolvePathWithinRoot(this.projectPath,yi.join(t,O.OH_MODULES_PATH,r));try{let a=o.startsWith(n.FILE_DEPENDENCY_PREFIX)?o.substring(n.FILE_DEPENDENCY_PREFIX.length):o,c=yi.isAbsolute(a)?P.ensurePathWithinRoot(this.projectPath,a):P.resolvePathWithinRoot(this.projectPath,a);gi.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 Xf(n){return A(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var bn=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new gt(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=$e.join(t,mi),i=$e.join(r,En);if(!ir.existsSync(r)||!ir.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 nr(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];Xf(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=$e.join(r,mi),o=$e.join(i,En);if(!ir.existsSync(i)||!ir.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 nr(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(!Xf(l))continue;let d=l.name;if(s&&!s.has(d))continue;let h=P.resolvePathWithinRoot(this.projectPath,l.srcPath),w=$e.join(i,d),E=H(h),N=this.buildModuleDependencies(d,E,w,a);N.moduleName=d,t.push(N)}return t}parseSingleModule(e,t,r,i){let o=e.name,s=P.resolvePathWithinRoot(this.projectPath,e.srcPath),a=$e.join(t,o),c=H(s),l=new er(c),d=this.buildModuleDependencies(o,c,a,r);this.parseModuleJson5(c,l);let h=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=o,l.moduleType=o,l.packageName=o,l.moduleDependencies=d,l.moduleJsonParam=new tr(h),i.push(l)}buildModuleDependencies(e,t,r,i){let o=new nr(this.projectPath,e,t);hi.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 gs;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 Sn(o);for(let o of e.finalDynamicDependencies)i[o.name]=new Sn(o);t.dependencies=r,t.dynamicDependencies=i}parseProjectDependencies(e,t){let r=$e.join(e,O.OH_PACKAGE_JSON5);if(!ir.existsSync(r))return;hi.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 ws(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=$e.join(e,"src","main","module.json5"),i=Te(r);if(!A(i)||!A(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(A(e)&&Array.isArray(e.requestPermissions))for(let r of e.requestPermissions)A(r)&&typeof r.name=="string"&&t.push(r.name);return t}parseMainPages(e){let t=$e.join(e,"src","main","resources","base","profile","main_pages.json"),r=Te(t);return!A(r)||!Array.isArray(r.src)?[]:r.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=this.getSdkPkg();if(!(!A(t)||!A(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=$e.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=Te(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!A(t)||!A(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let r=t.app.products[0];if(!A(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=$e.join(this.projectPath,"build-profile.json5");this.buildProfileCache=Te(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!A(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 vs=class{constructor(e=[]){this.valueSet=e}valueSet};var or=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var Zf=(b=>(b[b.File=1]="File",b[b.Module=2]="Module",b[b.Namespace=3]="Namespace",b[b.Package=4]="Package",b[b.Class=5]="Class",b[b.Method=6]="Method",b[b.Property=7]="Property",b[b.Field=8]="Field",b[b.Constructor=9]="Constructor",b[b.Enum=10]="Enum",b[b.Interface=11]="Interface",b[b.Function=12]="Function",b[b.Variable=13]="Variable",b[b.Constant=14]="Constant",b[b.String=15]="String",b[b.Number=16]="Number",b[b.Boolean=17]="Boolean",b[b.Array=18]="Array",b[b.Object=19]="Object",b[b.Key=20]="Key",b[b.Null=21]="Null",b[b.EnumMember=22]="EnumMember",b[b.Struct=23]="Struct",b[b.Event=24]="Event",b[b.Operator=25]="Operator",b[b.TypeParameter=26]="TypeParameter",b))(Zf||{}),Qf=()=>Object.values(Zf).filter(n=>typeof n=="number");var Ss=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Es=class{applyEdit=!0;workspaceEdit=new Ss;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new vs(Qf());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new or;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var bs=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Ps=class{constructor(e=[]){this.valueSet=e}valueSet};var Cs=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var em=(C=>(C[C.Text=1]="Text",C[C.Method=2]="Method",C[C.Function=3]="Function",C[C.Constructor=4]="Constructor",C[C.Field=5]="Field",C[C.Variable=6]="Variable",C[C.Class=7]="Class",C[C.Interface=8]="Interface",C[C.Module=9]="Module",C[C.Property=10]="Property",C[C.Unit=11]="Unit",C[C.Value=12]="Value",C[C.Enum=13]="Enum",C[C.Keyword=14]="Keyword",C[C.Snippet=15]="Snippet",C[C.Color=16]="Color",C[C.File=17]="File",C[C.Reference=18]="Reference",C[C.Folder=19]="Folder",C[C.EnumMember=20]="EnumMember",C[C.Constant=21]="Constant",C[C.Struct=22]="Struct",C[C.Event=23]="Event",C[C.Operator=24]="Operator",C[C.TypeParameter=25]="TypeParameter",C))(em||{}),tm=()=>Object.values(em).filter(n=>typeof n=="number");var Is=class{completionItemKind=new Ps(tm());completionItem=new Cs;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var As=class{synchronization=new bs;completion=new Is;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 or;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var Ds=class{workspace=new Es;textDocument=new As;notebookDocument=null;window=null;general=null;experimental=null};var Rs=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};var Ts=class{constructor(e,t,r,i,o,s=!0){this.sdkPath=e;this.rootUri=r;this.nodeMaxOldSpaceSize=o;this.useStandardProtocol=s;this.serverPath=this.useStandardProtocol?wi.resolve(t,"ace-server","out","standardIndex","index.js"):wi.resolve(t,"ace-server","out","index.js"),this.logPath=pu(),this.indexLogPath=i||this.logPath;let a={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath};this.messageHandle=this.useStandardProtocol?new ss(a):new cs(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=Ke(this.rootUri),o=new ms(i,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new bn(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),o.modules=s;let l=Co(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(l),this.currentParams=new Rs(i,o,new Ds),this.useStandardProtocol){let d=this.messageHandle;await d.sendInitializeResettable(this.currentParams,Me),f.info("[LSP] initialize response received"),d.broadcastToClients({jsonrpc:R,method:y.ARKTS_INDEXING_PROGRESS,params:{}}),d.sendInitialized()}else await this.startLegacy(this.currentParams,e);r=!0}catch(i){this.lastStartErrorMessage=i instanceof Error?i.message:String(i),f.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(r)}async startLegacy(e,t){let r=this.messageHandle;r.sendInitialize(e,1),r.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:R,method:y.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((i,o)=>{r.onIndexingProgressUpdate(o),r.onInitializationCompleted(i)},"LSP initialization",Me),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=A(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 bn(this.rootUri,this.sdkPath),i=this.getModuleModelsByName();if(t){f.info("[LspServerProxy] Project-level oh-package changed, parsing all modules' dependencies");let l=r.getDependenciesOnly();this.markDependencyTypesIncremental(l);let d=this.mergeDepsOnlyIntoModuleList(l,i);return this.applyModuleModelsUpdate(d),this.sendDidChangeConfiguration({moduleSet:d}),f.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${d.length}`),this.lastDepsOnlyForDiff=l,l}let o=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(o.length===0&&s.size===0)return f.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];f.info(`[LspServerProxy] Module-level deps changed, parsing: [${o.join(", ")}]`);let a=r.getDependenciesOnly(o);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),this.sendDidChangeConfiguration({moduleSet:c}),f.info(`[LspServerProxy] Dependencies only (incremental) reloaded, count: ${c.length}`),this.lastDepsOnlyForDiff=a,a}sendDidChangeConfiguration(e){this.stdHandle.sendDidChangeConfiguration(e)}getModuleModelsByName(){return new Map(this.currentModuleModels.map(e=>[e.moduleName??"",e]))}markDependencyTypesIncremental(e){let t=this.getModuleModelsByName(),r=new Map(this.lastDepsOnlyForDiff.map(i=>[i.moduleName??"",i]));for(let i of e){let o=i.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(o,t,r),c=i.dependencies??{},l=i.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(d,h)=>{(i.dependencies??={})[d]=this.makeDeleteEntry(d,h)}),this.markAddAndDeleteInDeps(a,l,(d,h)=>{(i.dynamicDependencies??={})[d]=this.makeDeleteEntry(d,h)})}}getOldDepsForModule(e,t,r){let i=t.get(e),o=i?.moduleDependencies?.dependencies??{},s=i?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(o).length===0&&Object.keys(s).length===0){let a=r.get(e);a&&(o=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:o,oldDynamic:s}}markAddAndDeleteInDeps(e,t,r){for(let i of Object.keys(t))i in e||(t[i].type="add");for(let i of Object.keys(e))i in t||r(i,e[i])}makeDeleteEntry(e,t){return new Sn({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new er(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new tr([]),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=Fn(wi.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=Fn(wi.join(t,"default/openharmony/ets/api")),o=Fn(wi.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(!Vf(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 Pt from"fs";import*as Wt from"path";import{createHash as NP}from"crypto";import{EventEmitter as OP}from"events";var ks=class extends OP{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(!Pt.existsSync(t)){f.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Pt.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=Te(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=Wt.join(this.projectRoot,O.OH_PACKAGE_JSON5);Pt.existsSync(r)&&t.push(r);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=P.resolvePathWithinRoot(this.projectRoot,o.srcPath),a=Wt.join(s,O.OH_PACKAGE_JSON5);Pt.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return Wt.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Pt.readFileSync(t,"utf-8");return NP("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=Pt.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:Wt.basename(t),relativePath:Wt.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 Gt from"fs";import*as et from"path";import{createHash as MP}from"crypto";import{EventEmitter as _P}from"events";var xs=class extends _P{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=et.join(t,mi)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!Gt.existsSync(this.depMapDir)){f.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=Gt.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 H(et.resolve(t))}onDirEvent(t,r){if(!r||typeof r!="string")return;let i=r.replace(/\\/g,"/"),o;if(i===O.OH_PACKAGE_JSON5)o="root-oh-package";else if(i===En)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=et.join(this.depMapDir,r);Gt.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=et.join(this.depMapDir,O.OH_PACKAGE_JSON5),r=et.join(this.depMapDir,En),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...i.map(s=>({path:et.join(this.depMapDir,s.name,O.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!Gt.existsSync(s))continue;let c=this.canonicalPath(s),l=this.computeFileHash(s);if(!l)continue;let d=this.contentHashes.get(c);if(!this.initialScanDone){this.contentHashes.set(c,l);continue}d!==l&&(this.contentHashes.set(c,l),f.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=et.join(this.depMapDir,En);try{let r=Te(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 H(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=et.join(this.depMapDir,a.name,O.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=et.join(this.depMapDir,o,O.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(i=>i.startsWith("dep-")),r=this.pendingRenames.map(i=>`${i.kind}(${i.info.oldName}\u2192${i.info.newName})`);f.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${r.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:r,bySrcPath:i}=this.buildModuleLookupMaps(this.lastModules),{byName:o,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(i,s,a,c),this.detectModuleMoves(r,o,a,c),this.detectAddedModules(o,r,c),this.detectRemovedModules(r,o,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let r=Gt.readFileSync(t,"utf-8");return MP("sha256").update(r).digest("hex")}catch{return null}}};import{spawn as FP}from"child_process";import*as Kc from"fs";import*as vi from"path";var jP=["install","--all"];function HP(n){let e=n.replace(/sdk\/?$/i,"tools"),t=vi.join(e,"ohpm","bin","pm-cli.js");if(Kc.existsSync(t))return t;let r=n.toLowerCase().endsWith("sdk")?vi.dirname(n):n;return t=vi.join(r,"ohpm","bin","pm-cli.js"),Kc.existsSync(t)?t:null}async function $P(n,e,t,r){return new Promise(i=>{let o=FP(n,[e,...jP],{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(`
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 Wt=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 ms=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var er=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 ym=20*1e3,qP=30*1e3,hs=class{client;nextRequestId=1;stopOnce=null;callbacks=new er;requestCallbacks=new Wt;diagnosticMap=new Map;initProgressReset=null;constructor(e){this.client=new Bt(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,Ne);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 ms(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=qP){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:k,method:y.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,y.PUBLISH_DIAGNOSTICS,ym,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${ym}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:k,method:y.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var gs=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 ul(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)}},ul=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var YP={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"},JP={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"},R={...YP,...JP},Gt={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"},wm=new Set([1e3,2e3,3e3,3001]);function KP(n){if(!D(n))return!1;let e=n.textDocument;return D(e)&&typeof e.uri=="string"}function ZP(n){return D(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function XP(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 ys=class n{client;isInitialized=!1;stopOnce=null;callbacks=new er;requestCallbacks=new Wt;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;constructor(e){this.client=new Bt(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:k,method:R.EXIT,params:{}}),Gt.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(R.BROADCAST),this.callbacks.register(R.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(R.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(R.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(R.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:k,method:R.INITIALIZED,params:{editors:e}}),Gt.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:k,id:0,result:{}}),Gt.EMPTY)}sendAsyncRequest(e,t,r,i){if(!D(t)){f.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!KP(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=Je(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:k,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(!ZP(r)){f.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:k,method:R.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),R.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:k,method:R.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),Gt.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let i=Je(t);e.textDocument.uri=i,f.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new gs(i),this.diagnosticMap.set(i,o),this.registerDiagnosticTimeout(i,R.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(o.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:k,method:R.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),Gt.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=Je(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,R.PUBLISH_DIAGNOSTICS)),f.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:k,method:R.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),Gt.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=Je(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:k,method:R.DID_CLOSE,params:{textDocument:{uri:r}}}),Gt.DID_CLOSE)}getDiagnosticMessage(e){let t=Je(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,R.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:k,method:R.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 R.MODULE_INIT_FINISH:return f.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(R.MODULE_INIT_FINISH),this.callbacks.unregister(R.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case R.INDEXING_PROGRESS_UPDATE:return f.info(`[LSP] onIndexingProgressUpdate: ${XP(t.params)}`),this.callbacks.invoke(R.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case R.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case R.ON_PACKAGE_CHANGE_FINISH:f.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case R.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case R.ON_ASYNC_HOVER:this.handleAsyncResponse(t,R.HOVER);return;case R.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,R.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case R.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,R.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:k,method:R.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,R.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(wm)&&this.finalizeDiagnostic(t,R.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 pl from"path";import*as Cs from"path";var ws=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var vs=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 bs=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var Es=class{typeSetting=new Ss;parameterNames=new bs};var Ps=class{constructor(e,t,r,i){this.rootUri=e;this.lspServerWorkspacePath=H(Cs.dirname(t)),this.indexingDataLocation=H(i),this.loggerPath=H(Cs.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new ws;gutterIconsSetting=new vs;inlayHintsSetting=new Es;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as vm from"path";var hi=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(H(vm.join(e,"src","main","resources")))}};var QP="OS",tr=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${QP}`;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 hi(e)):this.buildProfileParam=new hi}toString(){return JSON.stringify(this)}};var nr=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as $e from"path";import*as or from"fs";var Is=class{modulePath;dependencies={};dynamicDependencies={}};var bn=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 rr=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 bt from"path";import*as As from"fs";var ir=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:Ye.OH_PACKAGE_JSON5},gi=`${N.HVIGOR_CACHE}/${N.DEPENDENCY}`,En=`${N.DEPENDENCY}${N.JSON5}`,HU=Ye.SYNC_OUTPUT_PATH;var yi=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=bt.join(this.dependencyPath,N.OH_PACKAGE_JSON5),r=Ie(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 ir;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=bt.normalize(bt.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)),bt.isAbsolute(s)){r.dependencyPath=o;return}if(!i){let a=bt.resolve(this.modulePath,s);o=C.ensurePathWithinRoot(this.projectPath,a)}As.existsSync(o)&&As.statSync(o).isDirectory()&&(r.dependencyPath=o)}catch(o){f.error("parser dependency path is invalid",o)}}};import*as wi from"fs";import*as vi from"path";import eC from"json5";var Ds=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 vi.join(this.projectPath,N.OH_MODULES_PATH,N.OHPM_PATH,N.LOCK_JSON5_FILE)}readLockFile(e){if(!wi.existsSync(e))return f.error("lock file does not exist"),this.clearDependencies(),null;try{let t=wi.readFileSync(e,"utf8"),r=eC.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 ir;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=C.resolvePathWithinRoot(this.projectPath,vi.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=vi.isAbsolute(a)?C.ensurePathWithinRoot(this.projectPath,a):C.resolvePathWithinRoot(this.projectPath,a);wi.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 Sm(n){return D(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var Pn=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new mt(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=$e.join(t,gi),i=$e.join(r,En);if(!or.existsSync(r)||!or.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 rr(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];Sm(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=$e.join(r,gi),o=$e.join(i,En);if(!or.existsSync(i)||!or.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 rr(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(!Sm(l))continue;let p=l.name;if(s&&!s.has(p))continue;let g=C.resolvePathWithinRoot(this.projectPath,l.srcPath),w=$e.join(i,p),E=H(g),O=this.buildModuleDependencies(p,E,w,a);O.moduleName=p,t.push(O)}return t}parseSingleModule(e,t,r,i){let o=e.name,s=C.resolvePathWithinRoot(this.projectPath,e.srcPath),a=$e.join(t,o),c=H(s),l=new tr(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 nr(g),i.push(l)}buildModuleDependencies(e,t,r,i){let o=new rr(this.projectPath,e,t);yi.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 Is;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 bn(o);for(let o of e.finalDynamicDependencies)i[o.name]=new bn(o);t.dependencies=r,t.dynamicDependencies=i}parseProjectDependencies(e,t){let r=$e.join(e,N.OH_PACKAGE_JSON5);if(!or.existsSync(r))return;yi.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 Ds(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=$e.join(e,"src","main","module.json5"),i=Ie(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=$e.join(e,"src","main","resources","base","profile","main_pages.json"),r=Ie(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=$e.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=Ie(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=$e.join(this.projectPath,"build-profile.json5");this.buildProfileCache=Ie(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 ks=class{constructor(e=[]){this.valueSet=e}valueSet};var sr=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var bm=(b=>(b[b.File=1]="File",b[b.Module=2]="Module",b[b.Namespace=3]="Namespace",b[b.Package=4]="Package",b[b.Class=5]="Class",b[b.Method=6]="Method",b[b.Property=7]="Property",b[b.Field=8]="Field",b[b.Constructor=9]="Constructor",b[b.Enum=10]="Enum",b[b.Interface=11]="Interface",b[b.Function=12]="Function",b[b.Variable=13]="Variable",b[b.Constant=14]="Constant",b[b.String=15]="String",b[b.Number=16]="Number",b[b.Boolean=17]="Boolean",b[b.Array=18]="Array",b[b.Object=19]="Object",b[b.Key=20]="Key",b[b.Null=21]="Null",b[b.EnumMember=22]="EnumMember",b[b.Struct=23]="Struct",b[b.Event=24]="Event",b[b.Operator=25]="Operator",b[b.TypeParameter=26]="TypeParameter",b))(bm||{}),Em=()=>Object.values(bm).filter(n=>typeof n=="number");var Rs=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Ts=class{applyEdit=!0;workspaceEdit=new Rs;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new ks(Em());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new sr;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var xs=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Ls=class{constructor(e=[]){this.valueSet=e}valueSet};var Ns=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var Pm=(P=>(P[P.Text=1]="Text",P[P.Method=2]="Method",P[P.Function=3]="Function",P[P.Constructor=4]="Constructor",P[P.Field=5]="Field",P[P.Variable=6]="Variable",P[P.Class=7]="Class",P[P.Interface=8]="Interface",P[P.Module=9]="Module",P[P.Property=10]="Property",P[P.Unit=11]="Unit",P[P.Value=12]="Value",P[P.Enum=13]="Enum",P[P.Keyword=14]="Keyword",P[P.Snippet=15]="Snippet",P[P.Color=16]="Color",P[P.File=17]="File",P[P.Reference=18]="Reference",P[P.Folder=19]="Folder",P[P.EnumMember=20]="EnumMember",P[P.Constant=21]="Constant",P[P.Struct=22]="Struct",P[P.Event=23]="Event",P[P.Operator=24]="Operator",P[P.TypeParameter=25]="TypeParameter",P))(Pm||{}),Cm=()=>Object.values(Pm).filter(n=>typeof n=="number");var Os=class{completionItemKind=new Ls(Cm());completionItem=new Ns;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var Ms=class{synchronization=new xs;completion=new Os;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 sr;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var _s=class{workspace=new Ts;textDocument=new Ms;notebookDocument=null;window=null;general=null;experimental=null};var Fs=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};var js=class{constructor(e,t,r,i,o,s=!0){this.sdkPath=e;this.rootUri=r;this.nodeMaxOldSpaceSize=o;this.useStandardProtocol=s;this.serverPath=jr(t,this.useStandardProtocol),this.logPath=Ru(),this.indexLogPath=i||this.logPath;let a={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath};this.messageHandle=this.useStandardProtocol?new hs(a):new ys(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=Je(this.rootUri),o=new Ps(i,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new Pn(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),o.modules=s;let l=ko(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(l),this.currentParams=new Fs(i,o,new _s),this.useStandardProtocol){let p=this.messageHandle;await p.sendInitializeResettable(this.currentParams,Ne),f.info("[LSP] initialize response received"),p.broadcastToClients({jsonrpc:k,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:k,method:y.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((i,o)=>{r.onIndexingProgressUpdate(o),r.onInitializationCompleted(i)},"LSP initialization",Ne),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:k,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 Pn(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 bn({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new tr(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new nr([]),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=_n(pl.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=_n(pl.join(t,"default/openharmony/ets/api")),o=_n(pl.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:k,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:k,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:k,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:k,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:k,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:k,id:e.id,error:{code:-32603,message:t.message}}));break;default:f.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!hm(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 Et from"fs";import*as Vt from"path";import{createHash as nC}from"crypto";import{EventEmitter as rC}from"events";var Hs=class extends rC{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(!Et.existsSync(t)){f.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Et.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=C.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=C.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=C.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=C.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=Ie(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=Vt.join(this.projectRoot,N.OH_PACKAGE_JSON5);Et.existsSync(r)&&t.push(r);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=C.resolvePathWithinRoot(this.projectRoot,o.srcPath),a=Vt.join(s,N.OH_PACKAGE_JSON5);Et.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return Vt.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Et.readFileSync(t,"utf-8");return nC("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=Et.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:Vt.basename(t),relativePath:Vt.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 zt from"fs";import*as Qe from"path";import{createHash as iC}from"crypto";import{EventEmitter as oC}from"events";var $s=class extends oC{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=Qe.join(t,gi)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!zt.existsSync(this.depMapDir)){f.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=zt.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 H(Qe.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===En)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=Qe.join(this.depMapDir,r);zt.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=Qe.join(this.depMapDir,N.OH_PACKAGE_JSON5),r=Qe.join(this.depMapDir,En),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...i.map(s=>({path:Qe.join(this.depMapDir,s.name,N.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!zt.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=Qe.join(this.depMapDir,En);try{let r=Ie(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 H(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=Qe.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=Qe.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=zt.readFileSync(t,"utf-8");return iC("sha256").update(r).digest("hex")}catch{return null}}};import{spawn as sC}from"child_process";import*as fl from"fs";import*as Si from"path";var aC=["install","--all"];function cC(n){let e=n.replace(/sdk\/?$/i,"tools"),t=Si.join(e,"ohpm","bin","pm-cli.js");if(fl.existsSync(t))return t;let r=n.toLowerCase().endsWith("sdk")?Si.dirname(n):n;return t=Si.join(r,"ohpm","bin","pm-cli.js"),fl.existsSync(t)?t:null}async function lC(n,e,t,r){return new Promise(i=>{let o=sC(n,[e,...aC],{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
1267
  `);i({exitCode:c??-1,output:l})}),o.on("error",c=>{let l=[s,a].filter(Boolean).join(`
1268
1268
  `);i({exitCode:-1,output:l+`
1269
- `+c.message})})})}function UP(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>f.info("[ohpm] %s",e))}async function nm(n,e){try{let t=vo(e);if(!t)return f.error("node \u8DEF\u5F84\u4E0D\u5B58\u5728"),!1;let r=HP(e);if(!r)return f.error("ohpm (pm-cli.js) \u4E0D\u5B58\u5728"),!1;let{exitCode:i,output:o}=await $P(t,r,n,e);return UP(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 rm={UNINITIALIZED:-32099,UNKNOWN:-32e3},Si=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,rm.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,rm.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var sr=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 uo(e,async()=>await nm(e,t)?i?(f.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await yu(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 Ts(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?Si.uninitialized(t):Si.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 ks(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new xs(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 BP=10080*60*1e3,WP=7200*60*1e3,GP=120*1e3,ar=class n{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:y.HOVER,definition:y.DEFINITION,declaration:y.DECLARATION,references:y.REFERENCES,implementation:y.IMPLEMENTATION,completion:y.COMPLETION,signatureHelp:y.SIGNATURE_HELP,documentHighlight:y.DOCUMENT_HIGHLIGHT};constructor(e,t,r){this.projectPath=e,this.devecoPath=t??"",this.nodeMaxOldSpaceSize=r}setOnConfigChanged(e){this.onConfigChangedCallback=e}static getToolDefinition(){return{name:"check_ets_files",description:"\u5BF9\u4F20\u5165\u7684ets\u6587\u4EF6\u8FDB\u884C\u9759\u6001\u8BED\u6CD5\u68C0\u67E5(ArkTS-Check)\u5E76\u5B9E\u65F6\u8FD4\u56DE\u8BCA\u65AD\u4FE1\u606F\u3002",inputSchema:Xc.object({files:Xc.array(Xc.string()).describe('\u5F85\u68C0\u67E5\u7684 ETS \u6587\u4EF6\u8DEF\u5F84\u5217\u8868\uFF0C\u683C\u5F0F\u4E3A ["file1.ets","file2.ets",...]')})}}isInitializing(){return this.initializing}isInitialized(){return this.initialized}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initializing=!0,this.initPromise=this.doInitialize().then(()=>{this.initialized=!0}).finally(()=>{this.initializing=!1}),await this.initPromise}}async doInitialize(){let{harmonyRoot:e,devecoPath:t,arktsLangServerPath:r,useStandardProtocol:i}=this.resolveProjectAndDeveco();this.useStandardProtocol=i;let o=oe(e),{logPath:s,indexPath:a}=this.getLogAndIndexPath(o);setImmediate(()=>{Va(a,BP,"[ArkTS-Check]"),Va(s,WP,"[ArkTS-Check]")}),Po(s);let c=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,l=Number.isNaN(c)?void 0:c;g.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${l??"undefined \u2192 dynamic formula applies"}`);let d=ue.join(ct(t),"sdk");g.info(`ArktsCheck devecoPath: ${t}, contentRoot: ${ct(t)}, sdkPath: ${d}`),this.manager=new sr({sdkPath:d,arktsLangServerPath:r,workspaceRoot:H(o),indexLogPath:a,nodeMaxOldSpaceSize:l,useStandardProtocol:i}),this.manager.setOnMessage(h=>this.handleLspMessage(h)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((h,w)=>{this.initResolve=h,this.initReject=w,this.armInitTimer(Me),this.manager.start([]).catch(E=>{let N=E instanceof Error?E:new Error(String(E));this.failInit(N)})})}resolveProjectAndDeveco(){let e=ht(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.devecoPath??Je();if(g.debug(`DevEco Studio installation path: ${t}, this.devecoPath: ${this.devecoPath}`),!t)throw new Error("DevEco Studio installation path not found");this.devecoPath=t;let r=Mn(t);if(!r)throw new Error("arkts-lang-server path not found");let i=ue.resolve(r,"ace-server","out","standardIndex","index.js"),o=be.existsSync(i);return g.info(`ArktsCheck protocol: ${o?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${o})`),{harmonyRoot:e,devecoPath:t,arktsLangServerPath:r,useStandardProtocol:o}}armInitTimer(e){this.initDeadlineTimer&&clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=setTimeout(()=>{let t=this.initReject;this.clearInitHandlers(),t?.(new Error("LSP initialize timeout"))},e)}clearInitHandlers(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async checkFile(e){this.initialized||await this.initialize();let t=this.manager;if(!t)throw new Error("ArktsLspManager not initialized");let r=fn(e),i=await be.promises.readFile(e,"utf8"),s=`deveco.apptool.${ue.extname(e).replace(/^\./,"")||"plaintext"}`;return t.useStandardProtocol?this.checkFileStandard(t,r,i,s):this.checkFileLegacy(t,e,r,i,s)}async checkFileStandard(e,t,r,i){g.debug(`textDocument/didOpen uri=${t} content_len=${r.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:r,languageId:i,version:1}});try{g.debug(`textDocument/diagnostic uri=${t}`);let o=await e.diagnostic({textDocument:{uri:t}});return zP(o)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:t}})}}async checkFileLegacy(e,t,r,i,o){let s=r;e.registerDiagnosticCallback(r);let a=new Promise((c,l)=>{let d=setTimeout(()=>{this.diagnosticWaiters.delete(s)&&l(new Error("Wait for diagnostics timeout"))},GP);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:d})});g.debug(`textDocument/didOpen(legacy) uri=${r} content_len=${i.length}`),e.onAsyncOpenFile({textDocument:{uri:r,text:i,languageId:o,version:i.length},editorFiles:[r],isFromEditor:!1});try{return await a}finally{e.closeFileLegacy(r,!1)}}async handleCall(e){if(!this.initialized)return this.buildNotReadyResponse();let t=[],r=[],i=this.collectValidFiles(e.files,t);return i.length===0?{content:[{type:"text",text:t.length>0?t.join(`
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};g.info(`handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(r,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){let s=o instanceof Error?o.message:String(o);return g.error(`handleLspFeature ${e} failed: ${s}`),{content:[{type:"text",text:`${e} failed: ${s}`}],isError:!0}}}async handleWorkspaceSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();g.info(`handleWorkspaceSymbol: query="${e}"`);try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return{content:[{type:"text",text:t==null?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(t,null,2)}`}]}}catch(t){let r=t instanceof Error?t.message:String(t);return g.error(`handleWorkspaceSymbol failed: ${r}`),{content:[{type:"text",text:`workspaceSymbol failed: ${r}`}],isError:!0}}}async handleWorkspaceSymbolRaw(e){if(!this.initialized)return null;try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return g.error(`handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};g.info(`handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){let i=r instanceof Error?r.message:String(r);return g.error(`handleDocumentSymbol failed: ${i}`),{content:[{type:"text",text:`documentSymbol failed: ${i}`}],isError:!0}}}async handleCallHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};g.info(`handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,async o=>{let s=await this.manager.sendFeatureRequest(y.PREPARE_CALL_HIERARCHY,{textDocument:{uri:o},position:{line:e.line,character:e.character}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],calls:[]};let c=e.direction==="incoming"?y.INCOMING_CALLS:y.OUTGOING_CALLS,l=[];for(let d of a){let h=await this.manager.sendFeatureRequest(c,{item:d});Array.isArray(h)?l.push(...h):h&&l.push(h)}return{items:a,calls:l}});return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){let i=r instanceof Error?r.message:String(r);return g.error(`handleCallHierarchy failed: ${i}`),{content:[{type:"text",text:`callHierarchy failed: ${i}`}],isError:!0}}}async handleCodeAction(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};g.info(`handleCodeAction: file=${t} line=${e.line} char=${e.character}`);try{let r=await this.withOpenFile(t,async o=>{let s={line:e.line,character:e.character};return this.manager.sendFeatureRequest(y.CODE_ACTION,{textDocument:{uri:o},range:{start:s,end:s},context:{diagnostics:[]}})});return{content:[{type:"text",text:r==null?"codeAction: no result":`codeAction: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("codeAction",r)}}async handleRename(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};g.info(`handleRename: file=${t} line=${e.line} char=${e.character} newName=${e.newName}`);try{let r=await this.withOpenFile(t,async o=>{let s={line:e.line,character:e.character};if(await this.manager.sendFeatureRequest(y.PREPARE_RENAME,{textDocument:{uri:o},position:s})==null)throw new Error("Symbol at this position cannot be renamed");return this.manager.sendFeatureRequest(y.RENAME,{textDocument:{uri:o},position:s,newName:e.newName})});return{content:[{type:"text",text:r==null?"rename: no result":`rename: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("rename",r)}}async handleTypeHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};g.info(`handleTypeHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,async o=>{let s=await this.manager.sendFeatureRequest(y.PREPARE_TYPE_HIERARCHY,{textDocument:{uri:o},position:{line:e.line,character:e.character}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],results:[]};let c=e.direction==="supertypes"?y.SUPERTYPES:y.SUBTYPES,l=[];for(let d of a){let h=await this.manager.sendFeatureRequest(c,{item:d});Array.isArray(h)?l.push(...h):h&&l.push(h)}return{items:a,results:l}});return{content:[{type:"text",text:`typeHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("typeHierarchy",r)}}async handleCompletionItemResolve(e){if(!this.initialized)return this.buildNotReadyResponse();g.info("handleCompletionItemResolve");try{let t=await this.manager.sendFeatureRequest(y.COMPLETION_ITEM_RESOLVE,{item:e});return{content:[{type:"text",text:t==null?"completionItemResolve: no result":`completionItemResolve: ${JSON.stringify(t,null,2)}`}]}}catch(t){return this.buildErrorResponse("completionItemResolve",t)}}async handleInlayHint(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};try{let i=(await be.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 g.error(`${e} failed: ${r}`),{content:[{type:"text",text:`${e} failed: ${r}`}],isError:!0}}async withOpenFile(e,t){let r=fn(e),i=await be.promises.readFile(e,"utf8"),s=`deveco.apptool.${ue.extname(e).replace(/^\./,"")||"plaintext"}`;g.debug(`withOpenFile didOpen uri=${r} len=${i.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:r,text:i,languageId:s,version:i.length}});try{return await t(r)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:r},isManual:!1})}}resolveSingleFile(e){let t=ue.isAbsolute(e)?e:ue.join(this.projectPath,e);return!be.existsSync(t)||!be.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=ue.isAbsolute(o)?o:ue.join(r,o);if(!be.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!be.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 iu(500);try{let o=await this.checkFile(i);r.push(VP(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(`
1269
+ `+c.message})})})}function dC(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>f.info("[ohpm] %s",e))}async function Im(n,e){try{let t=Po(e);if(!t)return f.error("node \u8DEF\u5F84\u4E0D\u5B58\u5728"),!1;let r=cC(e);if(!r)return f.error("ohpm (pm-cli.js) \u4E0D\u5B58\u5728"),!1;let{exitCode:i,output:o}=await lC(t,r,n,e);return dC(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 Am={UNINITIALIZED:-32099,UNKNOWN:-32e3},bi=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,Am.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,Am.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var ar=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 fo(e,async()=>await Im(e,t)?i?(f.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await Ou(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 js(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:k,method:y.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();f.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?bi.uninitialized(t):bi.unknown();this.onMessage({jsonrpc:k,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:k,method:y.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new Hs(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new $s(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:k,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 uC=10080*60*1e3,pC=7200*60*1e3,fC=120*1e3,cr=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:ml.object({files:ml.array(ml.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=ie(e),{logPath:o,indexPath:s}=this.getLogAndIndexPath(i);setImmediate(()=>{oc(s,uC,"[ArkTS-Check]"),oc(o,pC,"[ArkTS-Check]")}),Do(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 ar({sdkPath:l,arktsLangServerPath:t,workspaceRoot:H(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(Ne),this.manager.start([]).catch(w=>{let E=w instanceof Error?w:new Error(String(w));this.failInit(E)})})}resolveProjectAndDeveco(){let e=ft(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.arktsLangServerPath;if(!t)throw new Error("arkts-lang-server path not found");let r=So(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=mn(e),i=await Re.promises.readFile(e,"utf8"),s=`deveco.apptool.${ke.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 mC(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"))},fC);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=mn(e),i=await Re.promises.readFile(e,"utf8"),s=`deveco.apptool.${ke.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=ke.isAbsolute(e)?e:ke.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=ke.isAbsolute(o)?o:ke.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 bu(500);try{let o=await this.checkFile(i);r.push(hC(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
1272
  `)),t.length>0&&r.push(t.join(`
1273
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){g.warn(`Failed to dispose ArktsLspManager: ${t}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,r=t.method;if(r)switch(r){case"textDocument/publishDiagnostics":{this.handleDiagnosticsNotification(t.params);break}case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(Me),g.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{g.info("Received arkts/initialized");let i=this.initResolve;this.clearInitHandlers(),i?.();break}case"arkts/initializationFailed":{let o=t.params?.message??"unknown";g.error(`LSP initialization failed: ${o}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${o}`));break}case"workspace/didChangeConfiguration":g.info("Received workspace/didChangeConfiguration, sync deferred to next check");break;default:break}}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let r=this.popDiagnosticWaiter(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.popDiagnosticWaiter(s)}if(!r)return;if(typeof e.errorMessage=="string"){g.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),r.resolve({errorMessage:e.errorMessage});return}let i=e.diagnostics,o=Array.isArray(i)?i.length:0;g.debug(`diagnostics received uri=${t} count=${o}`),r.resolve(Array.isArray(i)?i:[])}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}getLogAndIndexPath(e){try{let t=ue.join(_t(),"ArkTSCheck"),r=ue.join(t,"mapping-config.properties"),i=ou(e,r),o=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=ue.join(t,"lsp-log",String(i),o),a=ue.join(t,"lsp-index",String(i));return be.mkdirSync(s,{recursive:!0}),be.mkdirSync(a,{recursive:!0}),{logPath:oe(s),indexPath:oe(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function zP(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 VP(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 zt from"fs";import*as Ns from"path";import{z as Zc}from"zod";function cr(){return{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}}function Ls(n,e){let t=e instanceof Error?e.message:String(e);return g.error(`[CppLsp] ${n} failed: ${t}`),{content:[{type:"text",text:`${n} failed: ${t}`}],isError:!0}}var qP=500,lr=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:Zc.object({files:Zc.array(Zc.string()).describe('List of C/C++ file paths to check, format: ["file1.cpp","file2.hpp",...]')})}}async handleCall(e){if(!this.manager.ready)return cr();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 JP(qP);try{let l=await this.checkFile(c);r.push(YP(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(`
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(Ne),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=ke.join(Mt(),"ArkTSCheck"),r=ke.join(t,"mapping-config.properties"),i=Eu(e,r),o=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=ke.join(t,"lsp-log",String(i),o),a=ke.join(t,"lsp-index",String(i));return Re.mkdirSync(s,{recursive:!0}),Re.mkdirSync(a,{recursive:!0}),{logPath:ie(s),indexPath:ie(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function mC(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 hC(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 qt from"fs";import*as Bs from"path";import{z as hl}from"zod";function lr(){return{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}}function Us(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 gC=500,dr=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:hl.object({files:hl.array(hl.string()).describe('List of C/C++ file paths to check, format: ["file1.cpp","file2.hpp",...]')})}}async handleCall(e){if(!this.manager.ready)return lr();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 wC(gC);try{let l=await this.checkFile(c);r.push(yC(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
1276
  `)),r.length>0&&s.push(r.join(`
1277
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=fn(e),r=await zt.promises.readFile(e,"utf8"),i=wo(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=Ns.isAbsolute(o)?o:Ns.join(r,o);if(!zt.existsSync(s)){t.push(`File does not exist: ${o}`);continue}if(!zt.statSync(s).isFile()){t.push(`Not a regular file: ${o}`);continue}if(!pn(s)){t.push(`Not a supported C/C++ file: ${o}`);continue}try{i.push(zt.realpathSync(s))}catch{i.push(s)}}return i}};function YP(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 JP(n){return new Promise(e=>setTimeout(e,n))}import*as ur from"fs";import*as Os from"path";var dr=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 cr();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${t.file}`}],isError:!0};let i=n.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};g.info(`[ClangdLspTool] handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(r,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){return Ls(e,o)}}async handleWorkspaceSymbolRaw(e){if(!this.manager.ready)return null;try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return g.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return cr();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e}`}],isError:!0};g.info(`[ClangdLspTool] handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){return Ls("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return cr();if(e.direction==="outgoing")return{content:[{type:"text",text:"callHierarchy outgoing is not supported by clangd (incoming only)"}],isError:!0};let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e.file}`}],isError:!0};g.info(`[ClangdLspTool] handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,o=>this.fetchCallHierarchyResult(o,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return Ls("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=fn(e),i=await ur.promises.readFile(e,"utf8"),o=wo(e);g.info(`[ClangdLspTool] withOpenFile didOpen uri=${r} langId=${o} len=${i.length}`),this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:r,text:i,languageId:o,version:i.length}}});try{return await t(r)}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:r}}})}}resolveSingleFile(e){let t=Os.isAbsolute(e)?e:Os.join(this.manager.projectRoot,e);return!ur.existsSync(t)||!ur.statSync(t).isFile()||!pn(t)?null:t}};import{spawn as KP}from"child_process";import*as _s from"fs";import*as im from"path";var XP=30*1e3,ZP=30*1e3,Ms=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new Ut;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 $t(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,Me),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}`))},ZP);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=${H(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];f.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=KP(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=Fn(this.config.workspaceRoot),t=Ke(e),r=im.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.3.0-Test.8"},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=XP){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{_s.existsSync(this.config.logPath)||_s.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)),Ke(r)}}catch{}return e}};import*as Ei from"path";import*as Qc from"fs";var bi=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 devecoPath is empty"),{status:"failed",reason:"workspaceRoot or devecoPath is empty"};if(hn(e).length===0)return f.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let i=await uo(e,async()=>{try{return await Su(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(Me);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=ht(this.config.workspaceRoot);this.resolvedRoot=e?oe(e):oe(this.config.workspaceRoot);let t=this.config.devecoPath??Je();if(!t){this.failInit(new Error("DevEco Studio installation path not found"));return}let r=this.config.logPath??this.getLogPath();Po(r);let i=yo(t);if(!i){let a="clangd executable not found inside DevEco Studio SDK";f.error(`[ClangdLspManager] ${a}`),this.failInit(new Error(a));return}let o=Ei.dirname($r(this.resolvedRoot));try{Qc.mkdirSync(o,{recursive:!0})}catch(a){f.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${a}`)}f.info(`[ClangdLspManager] clangdPath: ${i}`),f.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),f.info(`[ClangdLspManager] compileCommandsDir: ${o}`);let s=new Ms({clangdPath:i,workspaceRoot:this.resolvedRoot,compileCommandsDir:o,logPath:r});s.setOnMessage(a=>this.handleLspMessage(a)),this.proxy=s,s.start(a=>this.handleProxyInitialized(a)).catch(a=>{let c=a instanceof Error?a:new Error(String(a));this.handleProxyInitialized(!1,c.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=Ei.join(_t(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=Ei.join(e,"lsp-log",t);return Qc.mkdirSync(r,{recursive:!0}),oe(r)}catch{return"auto"}}};function om(n){let e=fo(n);return f.info(`[SyncGuard] ${e.reason}`),e}var tl=(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))(tl||{}),am=(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))(am||{}),Vt=3,el=600*1e3,Fs=class{server;toolRouter;config={};arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";sdkPath="";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,mn(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),g.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",g.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,g.info(`Constructor: using configured path as startPath: '${t}'`));let i=ht(t);g.info(`Constructor: findHarmonyProject('${t}') => ${i??"null"}`),this.config.projectPath=i??void 0,this.server=new QP({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=Yc(),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:pe.object({files:pe.array(pe.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){g.info("Skip registering LSP feature tools (hover/definition/declaration/references/implementation, workspaceSymbol, documentSymbol, callHierarchy): standard LSP protocol unavailable (standardIndex/index.js not found). These tools require a DevEco Studio version that ships the standard LSP server entry.");return}let e=pe.object({file:pe.string().describe("Source file path, relative to the project root. Supports .ets (ArkTS) and C/C++ extensions."),line:pe.number().describe("Line number (0-based)"),character:pe.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:pe.object({query:pe.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:pe.object({file:pe.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:pe.object({file:pe.string().describe("Source file path, relative to the project root. Supports .ets and C/C++ extensions."),line:pe.number().describe("Line number (0-based)"),character:pe.number().describe("Character offset in the line (0-based)"),direction:pe.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.config.devecoPath??Je();if(!e)return g.info("Standard LSP protocol unavailable: DevEco Studio installation path not found"),!1;let t=Mn(e);if(!t)return g.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let r=Pn.join(t,"ace-server","out","standardIndex","index.js"),i=sm.existsSync(r);return g.info(`ArktsCheck protocol: ${i?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${i})`),i}catch(e){return g.warn(`Failed to detect standard LSP protocol availability: ${e}`),!1}}validateContainment(e){let t=this.config.projectPath;if(t){let i=[];for(let o of e){let s=P.isPathContainedWithSymlink(o,t);s.contained||(g.warn(`Containment check failed: ${s.reason}`),i.push(s.reason))}return i.length>0?{content:[{type:"text",text:i.join(`
1279
- `)}],isError:!0}:null}let r=e.filter(i=>Pn.isAbsolute(i));return r.length>0?(g.warn(`Absolute paths rejected (no project root): ${r.join(", ")}`),{content:[{type:"text",text:r.map(i=>`Absolute path is not allowed: ${i}`).join(`
1280
- `)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(h=>typeof h=="string"):[];if(t.length===0)return g.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}=tC(t);s.length>0&&g.warn(`Unsupported file types in check request: ${s.join(", ")}`);let a=s.map(h=>`Unsupported file type: ${h} (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(`
1278
+ `).trim();return!o&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:o}}async checkFile(e){let t=mn(e),r=await qt.promises.readFile(e,"utf8"),i=Eo(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=Bs.isAbsolute(o)?o:Bs.join(r,o);if(!qt.existsSync(s)){t.push(`File does not exist: ${o}`);continue}if(!qt.statSync(s).isFile()){t.push(`Not a regular file: ${o}`);continue}if(!fn(s)){t.push(`Not a supported C/C++ file: ${o}`);continue}try{i.push(qt.realpathSync(s))}catch{i.push(s)}}return i}};function yC(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 wC(n){return new Promise(e=>setTimeout(e,n))}import*as pr from"fs";import*as Ws from"path";var ur=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 lr();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 Us(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 lr();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 Us("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return lr();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 Us("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=mn(e),i=await pr.promises.readFile(e,"utf8"),o=Eo(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=Ws.isAbsolute(e)?e:Ws.join(this.manager.projectRoot,e);return!pr.existsSync(t)||!pr.statSync(t).isFile()||!fn(t)?null:t}};import{spawn as vC}from"child_process";import*as Vs from"fs";import*as Dm from"path";var SC=30*1e3,bC=30*1e3,Gs=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new Wt;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 Bt(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,Ne),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}`))},bC);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=${H(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];f.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=vC(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=_n(this.config.workspaceRoot),t=Je(e),r=Dm.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.3.0-Test.9"},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=SC){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:k,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:k,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:k,method:y.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{Vs.existsSync(this.config.logPath)||Vs.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)),Je(r)}}catch{}return e}};import*as Ei from"path";import*as gl from"fs";var Pi=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(gn(e).length===0)return f.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let i=await fo(e,async()=>{try{return await Fu(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(Ne);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=ft(this.config.workspaceRoot);this.resolvedRoot=e?ie(e):ie(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();Do(t);let r=bo(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=Ei.dirname(Hr(this.resolvedRoot));try{gl.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 Gs({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=Ei.join(Mt(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=Ei.join(e,"lsp-log",t);return gl.mkdirSync(r,{recursive:!0}),ie(r)}catch{return"auto"}}};function km(n){let e=ho(n);return f.info(`[SyncGuard] ${e.reason}`),e}var wl=(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))(wl||{}),Rm=(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))(Rm||{}),Yt=3,yl=600*1e3,zs=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,hn(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),h.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",h.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,h.info(`Constructor: using configured path as startPath: '${t}'`));let i=ft(t);h.info(`Constructor: findHarmonyProject('${t}') => ${i??"null"}`),this.config.projectPath=i??void 0;let o=vo(this.config.devecoPath);this.sdkPath=o.sdkPath,this.arktsLangServerPath=o.arktsLangServerPath,h.info(`Constructor: sdkPath='${this.sdkPath}', arktsLangServerPath='${this.arktsLangServerPath??"(null)"}'`),this.server=new EC({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=dl(),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=So(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=C.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=>qs.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}=CC(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(`
1281
1281
  `),a.join(`
1282
- `)].filter(h=>h.trim().length>0).join(`
1283
- `).trim()||"No diagnostics collected"}],isError:l}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return g.warn(`ArkTS check rejected: project is ${tl[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return g.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return this.arktsCheckTool.handleCall({files:e});default:return g.error(`ArkTS check: unknown project state ${this.projectState}, files: ${e.join(", ")}`),{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],isError:!0}}}async handleLspFeatureCall(e,t){let r=t.file,i=t.line,o=t.character;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 g.info(`workspaceSymbol rejected: ArkTS ${a}; C++ ${c}`),{content:[{type:"text",text:`workspaceSymbol: ArkTS ${a}; C++ ${c}`}],isError:!0}}let i=[],o=new Set;if(t)try{this.mergeSymbolItems(await this.arktsCheckTool.handleWorkspaceSymbolRaw(e),o,i)}catch(a){g.warn(`workspaceSymbol ArkTS query failed: ${a.message}`)}if(r)try{this.mergeSymbolItems(await this.cppLspTool.handleWorkspaceSymbolRaw(e),o,i)}catch(a){g.warn(`workspaceSymbol C++ query failed: ${a.message}`)}return{content:[{type:"text",text:i.length===0?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(i,null,2)}`}]}}symbolDedupKey(e){let t=e,r=t?.location?.uri??"",i=t?.location?.range?.start?.line??0,o=t?.location?.range?.start?.character??0;return`${r}:${i}:${o}`}mergeSymbolItems(e,t,r){if(e)for(let i of e){let o=this.symbolDedupKey(i);t.has(o)||(t.add(o),r.push(i))}}describeArktsState(){switch(this.projectState){case 0:return"idle";case 1:return"discovering";case 2:return"syncing (retry 10s)";case 3:return"initializing (retry 10s)";case 5:return`error (${this.initRetryCount}/${Vt})`;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}/${Vt})`;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 g.warn(`ArkTS ${e} rejected: project is ${tl[this.projectState]}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return g.warn(`ArkTS ${e} rejected: LSP is initializing`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return t()}}async handleIdleCheck(){if(this.ensureProjectReady(),this.config.projectPath){let e,t;return this.syncSkippedDueToLock?(e=`Another build process is running, sync deferred (waiting ${this.syncSkipStartedAt>0?Math.round((Date.now()-this.syncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,t="lock contention",this.syncSkippedDueToLock=!1):this.configChangedTriggeredResync?(e="Config file changed, resyncing project, please retry in 10 seconds",t="config changed",this.configChangedTriggeredResync=!1):(e="HarmonyOS project detected, syncing, please retry in 10 seconds",t="initial"),g.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(g.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:"Initializing, please retry in 10 seconds"}],isError:!0}):(g.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"No HarmonyOS project detected. Please verify the project directory or create a project first."}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=Vt?(g.error(`Init retry limit reached (${this.initRetryCount}/${Vt}), will not auto-retry`),{content:[{type:"text",text:"Project initialization failed multiple times. Please check project configuration and restart the MCP Server."}],isError:!0}):(g.info(`Error check: auto-retrying (${this.initRetryCount}/${Vt})`),this.ensureProjectReady(),{content:[{type:"text",text:"Project initialization failed, auto-retrying, please retry in 10 seconds"}],isError:!0})}async routeCppRequest(e,t){switch(this.cppProjectState){case 0:return this.handleCppIdleCheck();case 1:case 2:return g.warn(`C++ ${e} rejected: C++ project is ${am[this.cppProjectState]}`),{content:[{type:"text",text:"C++ project is syncing (compileNative), please retry in 25 seconds"}],isError:!0};case 3:return g.warn(`C++ ${e} rejected: clangd is initializing`),{content:[{type:"text",text:"C++ LSP (clangd) is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleCppErrorCheck();case 4:return this.cppHasNoCppCode?{content:[{type:"text",text:"No C++ code in this project"}],isError:!0}:this.cppLspManager?.ready?t():{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}}}async routeLspRequest(e,t,r){return e.endsWith(".ets")?this.routeArktsRequest(t,r):pn(e)?this.routeCppRequest(t,r):{content:[{type:"text",text:`Unsupported file type: ${e} (only .ets and C/C++ source/header files are supported)`}],isError:!0}}async handleCppIdleCheck(){if(this.ensureCppProjectReady(),this.config.projectPath){let e;return this.cppSyncSkippedDueToLock?(e=`Another build process is running, C++ sync deferred (waiting ${this.cppSyncSkipStartedAt>0?Math.round((Date.now()-this.cppSyncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,this.cppSyncSkippedDueToLock=!1):e="C++ project detected, syncing (compileNative), please retry in 25 seconds",g.info(`C++ idle check: project '${this.config.projectPath}', triggering C++ init`),{content:[{type:"text",text:e}],isError:!0}}return{content:[{type:"text",text:"No HarmonyOS project detected for C++ tools."}],isError:!0}}async handleCppErrorCheck(){return this.cppInitRetryCount>=Vt?(g.error(`C++ init retry limit reached (${this.cppInitRetryCount}/${Vt}), 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}):(g.info(`C++ error check: auto-retrying (${this.cppInitRetryCount}/${Vt})`),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=>{g.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(t=>{g.warn("Failed to dispose ClangdLspManager during setProjectPath:",t)}),this.cppLspManager=null),this.initPromise?(this.needsReinit=!0,g.info("Project path changed while ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{g.warn("Failed to re-init project after setProjectPath:",t)})),this.cppInitPromise?(this.cppNeedsReinit=!0,g.info("Project path changed while C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.cppHasNoCppCode=!1,this.cppInitRetryCount=0,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.ensureCppProjectReady().catch(t=>{g.warn("Failed to re-init C++ project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new eC;if(await this.server.connect(e),g.info("devecocli-mcp-server started"),!this.config.debug){let t=lu();t&&g.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=ht(t);r?(g.info(`Detected project path from client root: ${r}`),this.config.projectPath=r,this.sdkPath=this.computeSdkPath()):g.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?g.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):g.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{g.warn("Background project init failed:",t)})}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return g.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return g.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){g.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,g.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{g.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{g.error("shutdown failed:",r),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{g.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?ht(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=ht(this.originalProjectPath),t&&g.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.ensureCppProjectReady().catch(e=>{g.warn("Background C++ project init failed:",e)}),this.projectState=3,this.arktsCheckTool=new ar(this.config.projectPath,this.config.devecoPath??null,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{g.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,g.info("Project fully initialized, check tool is available")}catch(e){g.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=om(e),r=!t.required;return g.info(`Sync check: skipHvigor=${r}, reason=${t.reason}`),this.runSync(e,{skipHvigorSync:r})}async runSync(e,t){this.projectState=2,g.info("Starting project sync...");let r=await sr.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>=el?(g.error(`Sync skipped for ${o}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(g.warn(`Sync skipped: ${r.reason}, resetting to IDLE for retry (elapsed ${o}s / ${el/1e3}s)`),this.projectState=0,!1)}case"failed":return g.error(`Project sync failed: ${r.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:return g.error(`Project sync: unknown status ${r.status}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}async ensureCppProjectReady(){if(!this.cppInitPromise){this.cppInitPromise=this.doEnsureCppProjectReady();try{await this.cppInitPromise}finally{this.cppInitPromise=null}this.cppNeedsReinit&&(this.cppNeedsReinit=!1,this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>{g.warn("Failed to re-init C++ project after cppNeedsReinit:",e)}))}}async doEnsureCppProjectReady(){let e=this.config.projectPath;if(!e){g.info("[Cpp] No project path, skipping C++ init");return}this.cppProjectState=1;let t=hn(e);if(t.length===0){g.info('[Cpp] No C++ modules found, C++ tools will return "no C++ code"'),this.cppHasNoCppCode=!0,this.cppProjectState=4,this.cppInitRetryCount=0;return}if(this.cppHasNoCppCode=!1,g.info(`[Cpp] Found ${t.length} C++ module(s): ${t.map(r=>r.name).join(", ")}`),!!await this.runSyncCpp(e)){this.cppProjectState=3,this.cppLspManager=new bi({workspaceRoot:e,devecoPath:this.config.devecoPath??null});try{await this.cppLspManager.start(),this.cppCheckTool=new lr(this.cppLspManager),this.cppLspTool=new dr(this.cppLspManager),this.cppProjectState=4,this.cppInitRetryCount=0,g.info("[Cpp] C++ project fully initialized, C++ tools are available")}catch(r){g.error("[Cpp] C++ LSP initialization failed:",r),this.cppLspManager&&this.cppLspManager.dispose().catch(()=>{}),this.cppLspManager=null,this.cppCheckTool=null,this.cppLspTool=null,this.cppInitRetryCount++,this.cppProjectState=5}}}async runSyncCpp(e){this.cppProjectState=2,g.info("[Cpp] Starting C++ project sync (compileNative)...");let t=this.config.devecoPath??Je();if(!t)return g.error("[Cpp] DevEco Studio installation path not found, cannot sync C++ project"),this.cppInitRetryCount++,this.cppProjectState=5,!1;let r=await bi.handleSyncCppProject(e,t);switch(r.status){case"success":return this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,!0;case"skipped":{this.cppSyncSkippedDueToLock=!0,this.cppSyncSkipStartedAt===0&&(this.cppSyncSkipStartedAt=Date.now());let i=Date.now()-this.cppSyncSkipStartedAt,o=Math.round(i/1e3);return i>=el?(g.error(`[Cpp] C++ sync skipped for ${o}s due to lock contention, giving up`),this.cppInitRetryCount++,this.cppSyncSkipStartedAt=0,this.cppProjectState=5,!1):(g.warn(`[Cpp] C++ sync skipped: ${r.reason}, resetting to IDLE_CPP for retry (elapsed ${o}s)`),this.cppProjectState=0,!1)}case"failed":return g.error(`[Cpp] C++ project sync failed: ${r.reason}`),this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitRetryCount++,this.cppProjectState=5,!1}return!1}computeSdkPath(){let e=ru(this.config.devecoPath??""),t=ct(e);return Pn.join(t,"sdk")}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppLspManager&&await this.cppLspManager.dispose(),this.cppCheckTool=null,this.cppLspTool=null;try{await this.server.close()}catch(e){g.warn("Failed to close MCP server connection:",e)}g.info("devecocli-mcp-server stopped"),cu(),au()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function tC(n){let e=[],t=[],r=[];for(let i of n)Pn.extname(i).toLowerCase()===".ets"?e.push(i):pn(i)?t.push(i):r.push(i);return{etsFiles:e,cppFiles:t,unsupported:r}}function nl(n={}){return new Fs(n)}import*as rl from"fs";import*as pr from"path";import{spawn as nC}from"child_process";async function cm(n){mn(!1);let{serverPath:e,logPath:t,projectPath:r,sdkPath:i,serverMaxSize:o}=await rC(n),s=sC(e,t,r,i,o);g.info("ace-server started, bridging stdio (initialize is left to the client)"),cC(s)}async function rC(n){let e=await I.new();e.require({clt:!1});let t;if(n.projectPath)t=oe(pr.resolve(n.projectPath)),g.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let c=go(process.cwd());t=oe(c??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${c??"null, fallback to cwd"}`)}else t=oe(process.cwd()),g.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=e.sdkPath,i=Mn(e.devecoStudioPath);i||(g.error("ace-server not found in DevEco Studio installation."),process.exit(1));let o=pr.resolve(i,"ace-server","out","standardIndex","index.js"),s=pr.join(_t(),"lsp-server",String(Date.now()));rl.mkdirSync(s,{recursive:!0});let a=iC(t,r);return g.info(`projectPath=${t}, sdkPath=${r}, serverPath=${o}, logPath=${s}, serverMaxSize=${a}MB`),{projectPath:t,sdkPath:r,serverPath:o,logPath:s,serverMaxSize:a}}function iC(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=oC(n,e),s=Co(o,i);return g.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${o}, override=${i??"none"})`),s}function oC(n,e){try{let t=[];return new bn(n,e).getAllDependencyMap(t).status==="OK"?t.length:new gt(n).getAllModuleInfo().length}catch{return 0}}function sC(n,e,t,r,i){let o=pr.join(e,"lspLog");rl.mkdirSync(o,{recursive:!0});let s=aC(n,o,t,r,i),a=process.execPath??"node";return g.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),nC(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function aC(n,e,t,r,i){let o=H(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=${H(t)}`,`--sdkPath=${H(r)}`]}function cC(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{g.error(`[ace-server] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{g.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{g.info(`ace-server exited with code ${e}`),process.exit(e??0)})}import*as lm from"fs";import*as Cn from"path";import{spawn as lC}from"child_process";async function dm(n){mn(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await dC(n),i=Cn.join(t,"compile_commands.json");lm.existsSync(i)||g.warn(`compile_commands.json not found at ${i}. Cross-file navigation/completion will be limited. Run \`devecocli build\` first to generate it.`);let o=pC(e,t,r);g.info("clangd started, bridging stdio (initialize is left to the client)"),mC(o)}async function dC(n){let e=await uC();e||(g.error("DevEco Studio not found. Ensure DevEco Studio is installed."),process.exit(1));let t;if(n.projectPath)t=oe(Cn.resolve(n.projectPath)),g.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let s=go(process.cwd());t=oe(s??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${s??"null, fallback to cwd"}`)}else t=oe(Cn.resolve(process.cwd())),g.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=yo(e);r||(g.error("clangd not found in DevEco Studio SDK. Expected at <deveco>/sdk/default/openharmony/native/llvm/bin/clangd"),process.exit(1));let i=$r(t),o=Cn.dirname(i);return g.info(`projectPath=${t}, clangdPath=${r}, compileCommandsDir=${o}`),{projectPath:t,clangdPath:r,compileCommandsDir:o}}function uC(){return I.new().then(n=>n.devecoStudioPath).catch(()=>Je())}function pC(n,e,t){let r=fC(e);return g.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),lC(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function fC(n){return[`--compile-commands-dir=${H(n)}`,"--log=info","--pch-storage=memory"]}function mC(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{g.error(`[clangd] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{g.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{g.info(`clangd exited with code ${e}`),process.exit(e??0)})}async function gC(){let n=process.env.PROJECT_PATH||"",e=process.env.NODE_MAX_OLD_SPACE_SIZE,t=process.env.DEBUG==="true"||process.env.DEBUG==="1",r=await I.new();r.require({clt:!1});let i=n,o=r.devecoStudioPath,s=nl({projectPath:i,devecoPath:o,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 il=new hC("serve").description("Host bundled auxiliary protocol servers");il.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await gC()});il.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 cm({projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await dm({projectPath:n.projectPath,autoDetect:n.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var um=il;import{Command as yD,InvalidArgumentError as Yl}from"commander";import{red as ua,dim as wD}from"colorette";import*as X from"fs";import*as ut from"path";import tD from"adm-zip";import nD from"proper-lockfile";import vg from"ora";import*as tt from"fs";import*as Li from"path";var qt=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],In={"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 fr="1.9.1",Q1=48*1024*1024,pm=280,fm=6,mm=100,hm=3,gm=28,ol=10,ym=/API参考|APIReference/i,Pi=200,wm=12,vm=4,sl=8,Sm=6,js=700,al=250,cl=400,Em=1320,bm=120,Pm=450,Cm=250,Im=500,Am=480,Dm=80,Rm=200,Tm=60,km=200,xm=40,Lm=200,Nm=200,Om=40,mr=500,Mm=Object.fromEntries(qt.map((n,e)=>[In[n],e])),Yt=Object.fromEntries(qt.map((n,e)=>[n,e]));import*as Ci from"fs";import*as M from"path";import{fileURLToPath as Hm}from"url";import*as Jt from"fs";import*as _m from"path";import{homedir as yC}from"os";var wC="deveco-cli",ll,An=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function vC(){let n=process.env.DEVECO_CLI_DATA_DIR;return n!==void 0&&so(n)!==""}function Fm(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":so(n))||_m.join(yC(),".local","share",wC);try{return ao(t)}catch(r){throw new An(r instanceof Error?r.message:String(r))}}async function jm(){let n=Fm();await Jt.promises.mkdir(n,{recursive:!0});let e;try{e=await Jt.promises.realpath(n)}catch(r){throw new An(`DEVECO_CLI_DATA_DIR is not usable: ${r instanceof Error?r.message:String(r)}`)}if(!(await Jt.promises.stat(e)).isDirectory())throw new An("DEVECO_CLI_DATA_DIR must be a writable directory.");return ll=e,e}function Hs(n){let e=hr();return vC()?[`Data directory (DEVECO_CLI_DATA_DIR): ${e}`,"If you changed this in System Environment Variables, open a new terminal and retry.",`Log file: ${n}`]:[`Data directory (default): ${e}`,"To use a custom location, set DEVECO_CLI_DATA_DIR and open a new terminal.",`Log file: ${n}`]}function hr(){if(ll!==void 0)return ll;let n=Fm();try{if(Jt.existsSync(n))return Jt.realpathSync(n)}catch{}return n}var SC="docs";function gr(){return M.join(hr(),SC)}function Y(){return M.join(gr(),".index")}function $s(){return M.join(Y(),"build.lock")}function Ii(){return M.join(Y(),"build-status.json")}function yr(){return M.join(Y(),"build-meta.json")}function Dn(){return M.join(Y(),"search.db")}function Ai(){return M.join(Y(),"sqlite-backend.json")}function Di(){return M.join(Y(),"jieba-backend.json")}function Ct(){return M.join(Y(),".tmp")}function EC(){return M.join(hr(),"logs")}function wr(){return M.join(EC(),"doc-init.log")}function bC(n,e){let t=e;for(;!t.endsWith(`${M.sep}dist`)&&t!==M.dirname(t);)t=M.dirname(t);return t}function $m(n,e){return M.dirname(bC(n,e))}function Um(){let n=Hm(import.meta.url),e=M.dirname(n);return n.includes(`${M.sep}dist${M.sep}`)?$m(n,e):M.join(e,"..","..","..")}function PC(...n){let e=Hm(import.meta.url),t=M.dirname(e);return e.includes(`${M.sep}dist${M.sep}`)?[M.join($m(e,t),...n)]:[M.join(t,"..","..","..",...n)]}function Bm(...n){let e=Um(),t=Ci.realpathSync(e);for(let r of PC(...n))try{let i=Ci.lstatSync(r);if(i.isSymbolicLink()||!i.isFile())throw new Error(`Unsafe documentation package asset: ${n.join("/")} must be a regular file.`);let o=Ci.realpathSync(r);if(!_r(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 Kt(){return Bm("docs.zip")}function dl(){return Bm("index.zip")}function Wm(){return M.join(Um(),"index","data")}import*as It from"fs";import*as Rn from"path";var At=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],Us=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};function Gm(n){return n instanceof Us}var ul=null;function pl(n){ul=n}function fl(){if(ul)return ul;let n=Y();if(At.every(i=>It.existsSync(Rn.join(n,i))))return n;let t=Wm();if(At.every(i=>It.existsSync(Rn.join(t,i))))return t;throw new Us("Lexicon files not found. Install the documentation index first (index.zip).")}function zm(){fl()}function vr(n){let e=Rn.join(fl(),n);return It.readFileSync(e,"utf-8")}function Vm(n,e){return It.readFileSync(Rn.join(e,n),"utf-8")}async function qm(n,e=fl()){await It.promises.mkdir(n,{recursive:!0});for(let t of At){let r=Rn.join(e,t),i=Rn.join(n,t);await It.promises.copyFile(r,i)}}import*as Bs from"fs";import*as Ym from"path";import*as Jm from"yauzl";var Ri=null;function CC(n){return new Promise((e,t)=>{Jm.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 IC(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function AC(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",i=>{let o=IC(i);o.endsWith("/")||e.set(o,i),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function DC(){Ri?.zipfile.close(),Ri=null}async function RC(n){let e=Ym.resolve(n),t=await Bs.promises.stat(e),r=Ri;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;DC();let i=await CC(e),o=await AC(i);return Ri={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:i,entries:o,readChain:Promise.resolve()},Ri}function TC(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 kC(n,e){let t=n.readChain,r;n.readChain=new Promise(i=>{r=i}),await t;try{return await TC(n.zipfile,e)}finally{r()}}function xC(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 LC(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function Km(n){let e=Kt();if(!e)throw new Error("docs.zip not found");let t=await RC(e),r=LC(t.entries,xC(n));if(!r)throw new Error(`Document not found: ${n}`);return(await kC(t,r)).toString("utf-8")}function ml(){let n=Kt();return n!==null&&Bs.existsSync(n)}import*as ae from"fs";import*as Dt from"path";import Xm from"adm-zip";import*as Ti from"fs";import*as Gs from"path";var Ws=class extends Error{constructor(e){super(`Unsafe documentation path: ${e}`),this.name="DocPathSafetyError"}};function ki(n){return n instanceof An||n instanceof Ws||n instanceof Error&&(n.name==="CliDataDirError"||n.name==="DocPathSafetyError")}function yl(n){return new Ws(n)}function NC(){return st(hr())}function gl(n,e,t){let r=oo(n,e);if(r===null)throw yl(`${t} resolves outside the data directory.`);return r}async function hl(n,e){await Ti.promises.mkdir(n,{recursive:!0});let t=gl(n,e,"directory");if(!(await Ti.promises.stat(t)).isDirectory())throw yl("path must be a directory.")}function xi(n){let e=NC();try{let t=gl(n,e,"file");if(!Ti.statSync(t).isFile())throw yl("path must be a regular file.")}catch(t){if(t.code==="ENOENT"){gl(Gs.dirname(n),e,"file parent");return}throw t}}async function Sr(n={}){let e=n.mode??"write",t=await jm();await hl(gr(),t),await hl(Y(),t),e==="write"&&await hl(Ct(),t);for(let r of[Dn(),yr(),Ii(),$s(),Di(),Ai(),...At.map(i=>Gs.join(Y(),i))])xi(r)}var wl=["search.db","build-meta.json",...At],OC=["corpus.json","corpus-offsets.json","orama.dpack"];async function MC(n){for(let e of OC)await ae.promises.rm(Dt.join(n,e),{force:!0})}async function _C(n){let e=await ae.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await ae.promises.rm(Dt.join(n,t.name),{recursive:!0,force:!0})}function Zm(n){let t=new Xm(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 FC(n){let e=Y();await ae.promises.mkdir(e,{recursive:!0});for(let t of wl){let r=Dt.join(e,t);await ae.promises.rm(r,{force:!0}),await ae.promises.rename(Dt.join(n,t),r)}await MC(e),await ae.promises.rm(Ct(),{recursive:!0,force:!0})}function Qm(n){let e=dl();if(!e)return!1;try{let t=Zm(e);return t.indexVersion===fr&&t.docsZipSha256===n&&t.segmentCount>0}catch{return!1}}async function eh(n){await Sr({mode:"write"});let e=dl();if(!e)throw new Error("index.zip not found");let t=Zm(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=Ct();await ae.promises.rm(r,{recursive:!0,force:!0}),await ae.promises.mkdir(r,{recursive:!0});let i=new Xm(e);for(let s of wl){let a=i.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await ae.promises.writeFile(Dt.join(r,s),a.getData())}let o=JSON.parse(await ae.promises.readFile(Dt.join(r,"build-meta.json"),"utf-8"));if(!ae.existsSync(Dt.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await FC(r),await ae.promises.mkdir(gr(),{recursive:!0}),await _C(gr()),o}async function th(){await ae.promises.rm(Ct(),{recursive:!0,force:!0});let n=Y();for(let e of wl)await ae.promises.rm(Dt.join(n,e),{force:!0})}import{createHash as nh}from"crypto";import*as rh from"fs";async function zs(n){return new Promise((e,t)=>{let r=nh("sha256"),i=rh.createReadStream(n);i.on("data",o=>r.update(o)),i.on("error",t),i.on("end",()=>e(r.digest("hex")))})}function ih(n){return nh("sha256").update(n,"utf8").digest("hex")}var vl=null;function jC(){let n=vr("harmonyos-synonyms.json");return JSON.parse(n)}function HC(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 $C(){let n=HC(jC()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function UC(){return vl||(vl=$C()),vl}function Sl(n,e){let t=UC(),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 oh(n,e){let t=e?Vm(n,e):vr(n);return ih(t)}function Vs(n){return oh("harmonyos-synonyms.json",n)}function qs(n){return oh("harmonyos-terms.txt",n)}var BC={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function Ys(){try{let n=await tt.promises.readFile(Ii(),"utf-8");return JSON.parse(n)}catch{return{...BC}}}async function El(n){let e=Ii();await tt.promises.mkdir(Li.dirname(e),{recursive:!0}),await tt.promises.writeFile(e,JSON.stringify(n,null,2))}function sh(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 Xt(n){let t={...await Ys(),...n,updatedAt:Date.now()};return await El(t),t}async function bl(){let n=Kt();return n?zs(n):null}async function Pl(){try{let n=await tt.promises.readFile(yr(),"utf-8");return JSON.parse(n)}catch{return null}}async function Js(n=!1){if(n)return"no-index";let e=await Pl();if(!e||e.segmentCount===0)return"no-index";let t=await bl();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==fr?"engine-upgraded":e.termsHash!==qs()?"terms-changed":e.synonymsHash!==Vs()?"synonyms-changed":null}function Ni(){if(!ml()||!tt.existsSync(Dn())||!tt.existsSync(yr()))return!1;let n=Li.dirname(Dn());if(!At.every(e=>tt.existsSync(Li.join(n,e))))return!1;try{let e=tt.readFileSync(yr(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function Cl(n=!1){return n?!0:ml()?Ni()?await Js()!==null:!0:!1}async function ah(){let n=await Ys();return["installing","indexing","persisting"].includes(n.state)}import*as fe from"fs";import*as pg from"os";import*as Pe from"path";var ch=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),Il=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),lh=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"]),dh=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 WC=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,GC=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,zC=/[A-Z][a-zA-Z0-9]{2,}/g,VC=/@[A-Z][a-zA-Z0-9]*/g,qC=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,uh=6,YC=/^[a-z][a-z0-9]{2,}$/,JC=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,KC=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,XC=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,ZC=/^[A-Z][a-zA-Z0-9]+$/;function QC(n){return`"${n.replace(/"/g,'""')}"`}function Mi(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(QC).join(` ${e} `)}function Oi(n){return Mi(n,"OR")}function ph(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?Oi([...t,...r]):`(${Oi(t)}) AND (${Oi(r)})`}function _i(n){return KC.test(n)}function fh(n){return XC.test(n)&&n.length>=uh}function eI(n){return ZC.test(n)}function Fi(n){return _i(n)||fh(n)||eI(n)}function tI(n){let e=n.trim().toLowerCase();return dh.has(e)?!1:ch.has(e)}function nI(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function Ks(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function Al(n){return[...n.matchAll(WC)].map(e=>e[0])}function Dl(n,e=uh){let t=[];for(let r of n.matchAll(GC))r[0].length>=e&&t.push(r[0]);return t}function Er(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 nt(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function rI(n){let e=new Set;nt(e,n);let t=Ks(n);return t&&nt(e,t),Er([...e])}function Xs(n){if(_i(n))return rI(n);let e=new Set;return nt(e,n),Er([...e])}function Zs(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(JC);if(!t)return null;let r=t[1].toLowerCase(),i=t[2].toLowerCase();if(!YC.test(r)||lh.has(r)||!tI(i))return null;let o=nI(r,i);return{first:r,second:i,camelCase:o,lower:o.toLowerCase()}}function Rl(n){let e=Zs(n.trim());return!e||e.second!=="manager"?null:e}function iI(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function mh(n){let e=n.trim(),t=Rl(e);if(t&&Il.has(t.first))return!0;if(fh(e)){let r=iI(e);return r!==null&&Il.has(r)}return!1}function Tl(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 kl(n){let e=n.trim();if(Fi(e))return Xs(e);let t=new Set;for(let r of Al(n)){nt(t,r);let i=Ks(r);i&&nt(t,i)}for(let r of Dl(n))nt(t,r);for(let r of n.matchAll(VC))t.add(r[0]);for(let r of n.matchAll(qC))t.add(r[0]);for(let r of n.matchAll(zC))r[0].length>=4&&t.add(r[0]);return Er([...t])}function hh(n){let e=n.trim();if(Fi(e))return Xs(e);let t=new Set,r=Zs(e);r&&nt(t,r.camelCase);for(let i of kl(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 Er([...t])}function gh(n){return Fi(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 yh(n){return G.pureApiSymbol.test(n.trim())}function ji(n){let e=n.trim();return G.stageModelExact.test(e)||G.stageModelEnglishExact.test(e)}function wh(n){let e=[];return ji(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 vh(n){return ji(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var oI=[{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=>ji(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!ji(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 sI(n,e){for(let{catalog:t,multiplier:r}of e){let i=Yt[t];n.set(i,(n.get(i)??1)*r)}}function Sh(n,e){for(let t of oI)t.matches(n)&&sI(e,t.weights)}function Eh(n,e){if(e!==void 0)return!1;let t=n.trim();return _i(t)||G.pureApiSymbol.test(t)||mh(t)}function bh(n){let e=n.trim();if(_i(e)||G.pureApiSymbol.test(e))return"harmonyos-references";if(ji(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*as br from"fs";import*as Ch from"path";var Qs=null,xl=null,Ll=null;function aI(){return br.existsSync(Di())}function cI(n){let e=Di(),t={backend:"jieba-wasm",reason:"native-jieba-load-failed",message:n,createdAt:new Date().toISOString()};br.mkdirSync(Ch.dirname(e),{recursive:!0}),xi(e),br.writeFileSync(e,JSON.stringify(t,null,2))}function lI(){if(Qs)return Qs;let n=vr("harmonyos-stopwords.txt");return Qs=new Set(n.split(`
1285
- `).map(e=>e.trim()).filter(Boolean)),Qs}function dI(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 Ih(n){let e=lI(),t=[];for(let r of dI(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 Ah(n){let{dict:e}=await import("@node-rs/jieba/dict.js"),t=n.withDict(e),r=vr("harmonyos-terms.txt");return t.loadDict(Buffer.from(r,"utf-8")),t}async function uI(){let{Jieba:n}=await import("@node-rs/jieba");return Ah(n)}async function Ph(){let{Jieba:n}=await import("@node-rs/jieba-wasm32-wasi");return Ah(n)}async function pI(){if(aI())return await Ph();try{let e=await uI();return m("doc-index: using @node-rs/jieba backend"),e}catch(e){let t=e instanceof Error?e.message:String(e);cI(t),m(`doc-index: @node-rs/jieba unavailable (${t}); falling back to wasm32-wasi`)}let n=await Ph();return m("doc-index: using @node-rs/jieba-wasm32-wasi backend"),n}async function Zt(){return xl||(Ll||(Ll=pI().then(n=>(xl=n,n))),Ll)}async function fI(n){let e=await Zt();return Ih(e.cutForSearch(n,!0))}async function Dh(n){let e=await Zt();return Ih(e.cut(n,!0))}async function ea(n,e){let t=n.trim();if(!t||e<=0)return"";let r=(await fI(t)).join(" ");return r.length<=e?r:r.slice(0,e)}async function mI(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 ta(n){let e=!!n.sectionTitle.trim(),t=n.titleTokens.trim(),r=e?Am:Em,i=e?Rm:Pm,o=e?await mI(n.apiSymbols,i):await ea(n.apiSymbols.join(" "),i),a=(await Promise.all([ea(t,e?Dm:bm),Promise.resolve(o),ea(n.headingsText,e?Tm:Cm),ea(n.bodySample,e?km:Im)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}function hI(n){return n.join(" ").replace(/\s+/g," ").trim().slice(0,Pi)}function Nl(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>=wm))break}return r}function gI(n){return n.length>=2&&n.length<=vm}function yI(n,e){let t=Sl(n,sl),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=Nl(i,o);return{rawQuery:n,expandedQuery:t,tokens:s,preferAnd:!1,ftsMatch:ph(i,o)}}function wI(n,e){let t=Nl(Xs(e),[]);return{rawQuery:n,expandedQuery:n,tokens:t,preferAnd:!1,ftsMatch:Oi(t)}}async function Rh(n){let e=hI(n),t=e.trim(),r=vh(t);if(r)return{rawQuery:e,expandedQuery:r.expandedQuery,tokens:r.tokens,preferAnd:!1};let i=Zs(t);if(i)return yI(e,i);if(Fi(t))return wI(e,t);let o=wh(e),s=[...kl(e),...o],c=gh(t)?e:Sl(e,sl),l=await Dh(c),d=Nl(s,l);return{rawQuery:e,expandedQuery:c,tokens:d,preferAnd:o.length===0&&gI(d)}}var Th=["harmonyos-releases","harmonyos-roadmap"],vI=new Set(Th.map(n=>Yt[n])),SI=Th.map(n=>`${In[n]}/`);function EI(n){return vI.has(n)}function bI(n){return SI.some(e=>n.startsWith(e))}function kh(n){let e=[],t=[];for(let r of n)EI(r.catalog_id)?t.push(r):e.push(r);return[...e,...t]}function xh(n){let e=[],t=[];for(let r of n)bI(r.documentId)?t.push(r):e.push(r);return[...e,...t]}var PI=[{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 Hi(n,e,t){let r=Yt[e];n.set(r,(n.get(r)??1)*t)}function CI(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)){Hi(e,"harmonyos-guides",1.45),Hi(e,"harmonyos-references",1.35);return}(i||o)&&Hi(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(t)&&Hi(e,"harmonyos-references",1.75)}function Lh(n){let e=new Map,t=n.trim();if(!t)return e;let r=yh(t);CI(t,e),Sh(t,e);for(let i of PI)i.pattern.test(t)&&(i.skipForPureApiSymbol&&r||Hi(e,i.catalog,i.multiplier));return e}function Nh(n){return bh(n)}import*as Cr from"fs";import*as Uh from"path";var II=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function Oh(n,e){let t=-1;for(let r of II){let i=n.lastIndexOf(r);i>t&&(t=i)}return t>=e?t:-1}function Mh(n,e){let t=n.trim();if(t.length<=e)return{text:t,excerptTruncated:!1};let r=t.slice(0,e),i=Oh(r,e-20),o=i>=0?i:e;return{text:t.slice(0,o).trimEnd(),excerptTruncated:!0}}function _h(n,e,t={}){let{maxLen:r=Nm,contextChars:i=Om,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(xt=>xt.trim()).filter(Boolean),c=0;for(let xt of a){let Lt=s.toLowerCase().indexOf(xt.toLowerCase());if(Lt>=0){c=Lt;break}}let l=Math.max(0,c-i),d=Math.min(s.length,l+r),h=s.slice(l,d),w=Oh(h,r-25);w>=0&&(d=l+w);let E=s.slice(l,d).trim(),N=l>0?"...":"",he=d<s.length||o?"...":"";return`${N}${E}${he}`}var AI=`
1282
+ `)].filter(g=>g.trim().length>0).join(`
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 ${wl[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}/${Yt})`;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}/${Yt})`;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 ${wl[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>=Yt?(h.error(`Init retry limit reached (${this.initRetryCount}/${Yt}), 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}/${Yt})`),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 ${Rm[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):fn(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>=Yt?(h.error(`C++ init retry limit reached (${this.cppInitRetryCount}/${Yt}), 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}/${Yt})`),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 PC;if(await this.server.connect(e),h.info("devecocli-mcp-server started"),!this.config.debug){let t=Au();t&&h.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=ft(t);r?(h.info(`Detected project path from client root: ${r}`),this.config.projectPath=r):h.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?h.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):h.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{h.warn("Background project init failed:",t)})}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return h.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return h.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){h.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,h.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{h.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{h.error("shutdown failed:",r),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{h.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?ft(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=ft(this.originalProjectPath),t&&h.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(this.discoverProject()&&await this.ensureProjectSynced()){this.ensureCppProjectReady().catch(e=>{h.warn("Background C++ project init failed:",e)}),this.projectState=3,this.arktsCheckTool=new cr(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=km(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 ar.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>=yl?(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 / ${yl/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=gn(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 Pi({workspaceRoot:e,sdkPath:this.sdkPath});try{await this.cppLspManager.start(),this.cppCheckTool=new dr(this.cppLspManager),this.cppLspTool=new ur(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 Pi.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>=yl?(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"),Iu(),Cu()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function CC(n){let e=[],t=[],r=[];for(let i of n)qs.extname(i).toLowerCase()===".ets"?e.push(i):fn(i)?t.push(i):r.push(i);return{etsFiles:e,cppFiles:t,unsupported:r}}function vl(n={}){return new zs(n)}import*as Sl from"fs";import*as Ci from"path";import{spawn as IC}from"child_process";async function Tm(n){hn(!1);let{serverPath:e,logPath:t,projectPath:r,sdkPath:i,serverMaxSize:o}=await AC(n),s=RC(e,t,r,i,o);h.info("ace-server started, bridging stdio (initialize is left to the client)"),xC(s)}async function AC(n){let e=await I.new(),t=e.sourceType==="clt"?e.toolchainRoot:e.devecoStudioPath,r;if(n.projectPath)r=ie(Ci.resolve(n.projectPath)),h.info(`projectPath=specified ('${r}'), no search`);else if(n.autoDetect){let l=wo(process.cwd());r=ie(l??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${l??"null, fallback to cwd"}`)}else r=ie(process.cwd()),h.info(`projectPath=cwd ('${r}'), no search (pass --auto-detect to search subdirs)`);let{sdkPath:i,arktsLangServerPath:o}=vo(t);o||(h.error("ace-server not found (install DevEco Studio / CLT)."),process.exit(1));let s=jr(o,!0),a=Ci.join(Mt(),"lsp-server",String(Date.now()));Sl.mkdirSync(a,{recursive:!0});let c=DC(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 DC(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=kC(n,e),s=ko(o,i);return h.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${o}, override=${i??"none"})`),s}function kC(n,e){try{let t=[];return new Pn(n,e).getAllDependencyMap(t).status==="OK"?t.length:new mt(n).getAllModuleInfo().length}catch{return 0}}function RC(n,e,t,r,i){let o=Ci.join(e,"lspLog");Sl.mkdirSync(o,{recursive:!0});let s=TC(n,o,t,r,i),a=process.execPath??"node";return h.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),IC(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function TC(n,e,t,r,i){let o=H(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=${H(t)}`,`--sdkPath=${H(r)}`]}function xC(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 xm from"fs";import*as Cn from"path";import{spawn as LC}from"child_process";async function Lm(n){hn(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await NC(n),i=Cn.join(t,"compile_commands.json");xm.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=MC(e,t,r);h.info("clangd started, bridging stdio (initialize is left to the client)"),FC(o)}async function NC(n){let e=await OC();e||(h.error("DevEco Studio not found. Ensure DevEco Studio is installed."),process.exit(1));let t;if(n.projectPath)t=ie(Cn.resolve(n.projectPath)),h.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let a=wo(process.cwd());t=ie(a??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${a??"null, fallback to cwd"}`)}else t=ie(Cn.resolve(process.cwd())),h.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=nc(e),i=bo(r);i||(h.error(`clangd not found under sdk '${r}'. Expected at <sdkPath>/default/openharmony/native/llvm/bin/clangd`),process.exit(1));let o=Hr(t),s=Cn.dirname(o);return h.info(`projectPath=${t}, sdkPath=${r}, clangdPath=${i}, compileCommandsDir=${s}`),{projectPath:t,clangdPath:i,compileCommandsDir:s}}function OC(){return I.new().then(n=>n.devecoStudioPath).catch(()=>rc())}function MC(n,e,t){let r=_C(e);return h.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),LC(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function _C(n){return[`--compile-commands-dir=${H(n)}`,"--log=info","--pch-storage=memory"]}function FC(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 HC(){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=vl({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 bl=new jC("serve").description("Host bundled auxiliary protocol servers");bl.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await HC()});bl.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 Tm({projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await Lm({projectPath:n.projectPath,autoDetect:n.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var Nm=bl;import{Command as MD,InvalidArgumentError as pd}from"commander";import{red as Sa,dim as _D}from"colorette";import*as ve from"fs";import*as Ir from"path";import bD from"proper-lockfile";import Mg from"ora";import*as et from"fs";import*as Oi from"path";var Jt=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],In={"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 fr="1.9.1",rV=48*1024*1024,Om=280,Mm=6,_m=100,Fm=3,jm=28,El=10,Hm=/API参考|APIReference/i,Ii=200,$m=12,Um=4,Pl=8,Bm=6,Ys=700,Cl=250,Il=400,Wm=1320,Gm=120,Vm=450,zm=250,qm=500,Ym=480,Jm=80,Km=200,Zm=60,Xm=200,Qm=40,eh=200,th=200,nh=40,mr=500,rh=Object.fromEntries(Jt.map((n,e)=>[In[n],e])),Kt=Object.fromEntries(Jt.map((n,e)=>[n,e]));import*as Ai from"fs";import*as M from"path";import{fileURLToPath as ih}from"url";var $C="docs";function hr(){return M.join(Me(),$C)}function q(){return M.join(hr(),".index")}function Js(){return M.join(q(),"build.lock")}function Di(){return M.join(q(),"build-status.json")}function gr(){return M.join(q(),"build-meta.json")}function An(){return M.join(q(),"search.db")}function ki(){return M.join(q(),"sqlite-backend.json")}function Ri(){return M.join(q(),"jieba-backend.json")}function Pt(){return M.join(q(),".tmp")}function UC(){return M.join(Me(),"logs")}function yr(){return M.join(UC(),"doc-init.log")}function BC(n,e){let t=e;for(;!t.endsWith(`${M.sep}dist`)&&t!==M.dirname(t);)t=M.dirname(t);return t}function oh(n,e){return M.dirname(BC(n,e))}function sh(){let n=ih(import.meta.url),e=M.dirname(n);return n.includes(`${M.sep}dist${M.sep}`)?oh(n,e):M.join(e,"..","..","..")}function WC(...n){let e=ih(import.meta.url),t=M.dirname(e);return e.includes(`${M.sep}dist${M.sep}`)?[M.join(oh(e,t),...n)]:[M.join(t,"..","..","..",...n)]}function ah(...n){let e=sh(),t=Ai.realpathSync(e);for(let r of WC(...n))try{let i=Ai.lstatSync(r);if(i.isSymbolicLink()||!i.isFile())throw new Error(`Unsafe documentation package asset: ${n.join("/")} must be a regular file.`);let o=Ai.realpathSync(r);if(!Ja(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 Zt(){return ah("docs.zip")}function Al(){return ah("index.zip")}function ch(){return M.join(sh(),"index","data")}import*as Ct from"fs";import*as Dn from"path";var It=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],Ks=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};function lh(n){return n instanceof Ks}var Dl=null;function kl(n){Dl=n}function Rl(){if(Dl)return Dl;let n=q();if(It.every(i=>Ct.existsSync(Dn.join(n,i))))return n;let t=ch();if(It.every(i=>Ct.existsSync(Dn.join(t,i))))return t;throw new Ks("Lexicon files not found. Install the documentation index first (index.zip).")}function dh(){Rl()}function wr(n){let e=Dn.join(Rl(),n);return Ct.readFileSync(e,"utf-8")}function uh(n,e){return Ct.readFileSync(Dn.join(e,n),"utf-8")}async function ph(n,e=Rl()){await Ct.promises.mkdir(n,{recursive:!0});for(let t of It){let r=Dn.join(e,t),i=Dn.join(n,t);await Ct.promises.copyFile(r,i)}}import*as Zs from"fs";import*as fh from"path";import*as mh from"yauzl";var Ti=null;function GC(n){return new Promise((e,t)=>{mh.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 VC(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function zC(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",i=>{let o=VC(i);o.endsWith("/")||e.set(o,i),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function qC(){Ti?.zipfile.close(),Ti=null}async function YC(n){let e=fh.resolve(n),t=await Zs.promises.stat(e),r=Ti;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;qC();let i=await GC(e),o=await zC(i);return Ti={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:i,entries:o,readChain:Promise.resolve()},Ti}function JC(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 KC(n,e){let t=n.readChain,r;n.readChain=new Promise(i=>{r=i}),await t;try{return await JC(n.zipfile,e)}finally{r()}}function ZC(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 XC(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function hh(n){let e=Zt();if(!e)throw new Error("docs.zip not found");let t=await YC(e),r=XC(t.entries,ZC(n));if(!r)throw new Error(`Document not found: ${n}`);return(await KC(t,r)).toString("utf-8")}function Tl(){let n=Zt();return n!==null&&Zs.existsSync(n)}import*as se from"fs";import*as At from"path";import gh from"adm-zip";import*as xi from"fs";import*as Qs from"path";var Xs=class extends Error{constructor(e){super(`Unsafe documentation path: ${e}`),this.name="DocPathSafetyError"}};function Li(n){return n instanceof wn||n instanceof Xs||n instanceof Error&&(n.name==="CliDataDirError"||n.name==="DocPathSafetyError")}function Nl(n){return new Xs(n)}function QC(){return ot(Me())}function Ll(n,e,t){let r=ao(n,e);if(r===null)throw Nl(`${t} resolves outside the data directory.`);return r}async function xl(n,e){await xi.promises.mkdir(n,{recursive:!0});let t=Ll(n,e,"directory");if(!(await xi.promises.stat(t)).isDirectory())throw Nl("path must be a directory.")}function Ni(n){let e=QC();try{let t=Ll(n,e,"file");if(!xi.statSync(t).isFile())throw Nl("path must be a regular file.")}catch(t){if(t.code==="ENOENT"){Ll(Qs.dirname(n),e,"file parent");return}throw t}}async function vr(n={}){let e=n.mode??"write",t=await op();await xl(hr(),t),await xl(q(),t),e==="write"&&await xl(Pt(),t);for(let r of[An(),gr(),Di(),Js(),Ri(),ki(),...It.map(i=>Qs.join(q(),i))])Ni(r)}var Ol=["search.db","build-meta.json",...It],eI=["corpus.json","corpus-offsets.json","orama.dpack"];async function tI(n){for(let e of eI)await se.promises.rm(At.join(n,e),{force:!0})}async function nI(n){let e=await se.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await se.promises.rm(At.join(n,t.name),{recursive:!0,force:!0})}function yh(n){let t=new gh(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 rI(n){let e=q();await se.promises.mkdir(e,{recursive:!0});for(let t of Ol){let r=At.join(e,t);await se.promises.rm(r,{force:!0}),await se.promises.rename(At.join(n,t),r)}await tI(e),await se.promises.rm(Pt(),{recursive:!0,force:!0})}function wh(n){let e=Al();if(!e)return!1;try{let t=yh(e);return t.indexVersion===fr&&t.docsZipSha256===n&&t.segmentCount>0}catch{return!1}}async function vh(n){await vr({mode:"write"});let e=Al();if(!e)throw new Error("index.zip not found");let t=yh(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=Pt();await se.promises.rm(r,{recursive:!0,force:!0}),await se.promises.mkdir(r,{recursive:!0});let i=new gh(e);for(let s of Ol){let a=i.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await se.promises.writeFile(At.join(r,s),a.getData())}let o=JSON.parse(await se.promises.readFile(At.join(r,"build-meta.json"),"utf-8"));if(!se.existsSync(At.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await rI(r),await se.promises.mkdir(hr(),{recursive:!0}),await nI(hr()),o}async function Sh(){await se.promises.rm(Pt(),{recursive:!0,force:!0});let n=q();for(let e of Ol)await se.promises.rm(At.join(n,e),{force:!0})}import{createHash as bh}from"crypto";import*as Eh from"fs";async function ea(n){return new Promise((e,t)=>{let r=bh("sha256"),i=Eh.createReadStream(n);i.on("data",o=>r.update(o)),i.on("error",t),i.on("end",()=>e(r.digest("hex")))})}function Ph(n){return bh("sha256").update(n,"utf8").digest("hex")}var Ml=null;function iI(){let n=wr("harmonyos-synonyms.json");return JSON.parse(n)}function oI(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 sI(){let n=oI(iI()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function aI(){return Ml||(Ml=sI()),Ml}function _l(n,e){let t=aI(),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 Ch(n,e){let t=e?uh(n,e):wr(n);return Ph(t)}function ta(n){return Ch("harmonyos-synonyms.json",n)}function na(n){return Ch("harmonyos-terms.txt",n)}var cI={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function ra(){try{let n=await et.promises.readFile(Di(),"utf-8");return JSON.parse(n)}catch{return{...cI}}}async function Fl(n){let e=Di();await et.promises.mkdir(Oi.dirname(e),{recursive:!0}),await et.promises.writeFile(e,JSON.stringify(n,null,2))}function Ih(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 Xt(n){let t={...await ra(),...n,updatedAt:Date.now()};return await Fl(t),t}async function jl(){let n=Zt();return n?ea(n):null}async function Hl(){try{let n=await et.promises.readFile(gr(),"utf-8");return JSON.parse(n)}catch{return null}}async function ia(n=!1){if(n)return"no-index";let e=await Hl();if(!e||e.segmentCount===0)return"no-index";let t=await jl();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==fr?"engine-upgraded":e.termsHash!==na()?"terms-changed":e.synonymsHash!==ta()?"synonyms-changed":null}function Mi(){if(!Tl()||!et.existsSync(An())||!et.existsSync(gr()))return!1;let n=Oi.dirname(An());if(!It.every(e=>et.existsSync(Oi.join(n,e))))return!1;try{let e=et.readFileSync(gr(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function $l(n=!1){return n?!0:Tl()?Mi()?await ia()!==null:!0:!1}async function Ah(){let n=await ra();return["installing","indexing","persisting"].includes(n.state)}import*as sd from"fs";import*as ad from"path";import dD from"adm-zip";var Dh=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),Ul=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),kh=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"]),Rh=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 lI=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,dI=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,uI=/[A-Z][a-zA-Z0-9]{2,}/g,pI=/@[A-Z][a-zA-Z0-9]*/g,fI=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,Th=6,mI=/^[a-z][a-z0-9]{2,}$/,hI=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,gI=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,yI=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,wI=/^[A-Z][a-zA-Z0-9]+$/;function vI(n){return`"${n.replace(/"/g,'""')}"`}function Fi(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(vI).join(` ${e} `)}function _i(n){return Fi(n,"OR")}function xh(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?_i([...t,...r]):`(${_i(t)}) AND (${_i(r)})`}function ji(n){return gI.test(n)}function Lh(n){return yI.test(n)&&n.length>=Th}function SI(n){return wI.test(n)}function Hi(n){return ji(n)||Lh(n)||SI(n)}function bI(n){let e=n.trim().toLowerCase();return Rh.has(e)?!1:Dh.has(e)}function EI(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function oa(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function Bl(n){return[...n.matchAll(lI)].map(e=>e[0])}function Wl(n,e=Th){let t=[];for(let r of n.matchAll(dI))r[0].length>=e&&t.push(r[0]);return t}function Sr(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 tt(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function PI(n){let e=new Set;tt(e,n);let t=oa(n);return t&&tt(e,t),Sr([...e])}function sa(n){if(ji(n))return PI(n);let e=new Set;return tt(e,n),Sr([...e])}function aa(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(hI);if(!t)return null;let r=t[1].toLowerCase(),i=t[2].toLowerCase();if(!mI.test(r)||kh.has(r)||!bI(i))return null;let o=EI(r,i);return{first:r,second:i,camelCase:o,lower:o.toLowerCase()}}function Gl(n){let e=aa(n.trim());return!e||e.second!=="manager"?null:e}function CI(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function Nh(n){let e=n.trim(),t=Gl(e);if(t&&Ul.has(t.first))return!0;if(Lh(e)){let r=CI(e);return r!==null&&Ul.has(r)}return!1}function Vl(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 zl(n){let e=n.trim();if(Hi(e))return sa(e);let t=new Set;for(let r of Bl(n)){tt(t,r);let i=oa(r);i&&tt(t,i)}for(let r of Wl(n))tt(t,r);for(let r of n.matchAll(pI))t.add(r[0]);for(let r of n.matchAll(fI))t.add(r[0]);for(let r of n.matchAll(uI))r[0].length>=4&&t.add(r[0]);return Sr([...t])}function Oh(n){let e=n.trim();if(Hi(e))return sa(e);let t=new Set,r=aa(e);r&&tt(t,r.camelCase);for(let i of zl(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 Sr([...t])}function Mh(n){return Hi(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 _h(n){return G.pureApiSymbol.test(n.trim())}function $i(n){let e=n.trim();return G.stageModelExact.test(e)||G.stageModelEnglishExact.test(e)}function Fh(n){let e=[];return $i(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 jh(n){return $i(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var II=[{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=>$i(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!$i(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 AI(n,e){for(let{catalog:t,multiplier:r}of e){let i=Kt[t];n.set(i,(n.get(i)??1)*r)}}function Hh(n,e){for(let t of II)t.matches(n)&&AI(e,t.weights)}function $h(n,e){if(e!==void 0)return!1;let t=n.trim();return ji(t)||G.pureApiSymbol.test(t)||Nh(t)}function Uh(n){let e=n.trim();if(ji(e)||G.pureApiSymbol.test(e))return"harmonyos-references";if($i(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*as br from"fs";import*as Wh from"path";var ca=null,ql=null,Yl=null;function DI(){return br.existsSync(Ri())}function kI(n){let e=Ri(),t={backend:"jieba-wasm",reason:"native-jieba-load-failed",message:n,createdAt:new Date().toISOString()};br.mkdirSync(Wh.dirname(e),{recursive:!0}),Ni(e),br.writeFileSync(e,JSON.stringify(t,null,2))}function RI(){if(ca)return ca;let n=wr("harmonyos-stopwords.txt");return ca=new Set(n.split(`
1285
+ `).map(e=>e.trim()).filter(Boolean)),ca}function TI(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 Gh(n){let e=RI(),t=[];for(let r of TI(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 Vh(n){let{dict:e}=await import("@node-rs/jieba/dict.js"),t=n.withDict(e),r=wr("harmonyos-terms.txt");return t.loadDict(Buffer.from(r,"utf-8")),t}async function xI(){let{Jieba:n}=await import("@node-rs/jieba");return Vh(n)}async function Bh(){let{Jieba:n}=await import("@node-rs/jieba-wasm32-wasi");return Vh(n)}async function LI(){if(DI())return await Bh();try{let e=await xI();return m("doc-index: using @node-rs/jieba backend"),e}catch(e){let t=e instanceof Error?e.message:String(e);kI(t),m(`doc-index: @node-rs/jieba unavailable (${t}); falling back to wasm32-wasi`)}let n=await Bh();return m("doc-index: using @node-rs/jieba-wasm32-wasi backend"),n}async function Qt(){return ql||(Yl||(Yl=LI().then(n=>(ql=n,n))),Yl)}async function NI(n){let e=await Qt();return Gh(e.cutForSearch(n,!0))}async function zh(n){let e=await Qt();return Gh(e.cut(n,!0))}async function la(n,e){let t=n.trim();if(!t||e<=0)return"";let r=(await NI(t)).join(" ");return r.length<=e?r:r.slice(0,e)}async function OI(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 da(n){let e=!!n.sectionTitle.trim(),t=n.titleTokens.trim(),r=e?Ym:Wm,i=e?Km:Vm,o=e?await OI(n.apiSymbols,i):await la(n.apiSymbols.join(" "),i),a=(await Promise.all([la(t,e?Jm:Gm),Promise.resolve(o),la(n.headingsText,e?Zm:zm),la(n.bodySample,e?Xm:qm)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}function MI(n){return n.join(" ").replace(/\s+/g," ").trim().slice(0,Ii)}function Jl(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>=$m))break}return r}function _I(n){return n.length>=2&&n.length<=Um}function FI(n,e){let t=_l(n,Pl),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=Jl(i,o);return{rawQuery:n,expandedQuery:t,tokens:s,preferAnd:!1,ftsMatch:xh(i,o)}}function jI(n,e){let t=Jl(sa(e),[]);return{rawQuery:n,expandedQuery:n,tokens:t,preferAnd:!1,ftsMatch:_i(t)}}async function qh(n){let e=MI(n),t=e.trim(),r=jh(t);if(r)return{rawQuery:e,expandedQuery:r.expandedQuery,tokens:r.tokens,preferAnd:!1};let i=aa(t);if(i)return FI(e,i);if(Hi(t))return jI(e,t);let o=Fh(e),s=[...zl(e),...o],c=Mh(t)?e:_l(e,Pl),l=await zh(c),p=Jl(s,l);return{rawQuery:e,expandedQuery:c,tokens:p,preferAnd:o.length===0&&_I(p)}}var Yh=["harmonyos-releases","harmonyos-roadmap"],HI=new Set(Yh.map(n=>Kt[n])),$I=Yh.map(n=>`${In[n]}/`);function UI(n){return HI.has(n)}function BI(n){return $I.some(e=>n.startsWith(e))}function Jh(n){let e=[],t=[];for(let r of n)UI(r.catalog_id)?t.push(r):e.push(r);return[...e,...t]}function Kh(n){let e=[],t=[];for(let r of n)BI(r.documentId)?t.push(r):e.push(r);return[...e,...t]}var WI=[{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 Ui(n,e,t){let r=Kt[e];n.set(r,(n.get(r)??1)*t)}function GI(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)){Ui(e,"harmonyos-guides",1.45),Ui(e,"harmonyos-references",1.35);return}(i||o)&&Ui(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(t)&&Ui(e,"harmonyos-references",1.75)}function Zh(n){let e=new Map,t=n.trim();if(!t)return e;let r=_h(t);GI(t,e),Hh(t,e);for(let i of WI)i.pattern.test(t)&&(i.skipForPureApiSymbol&&r||Ui(e,i.catalog,i.multiplier));return e}function Xh(n){return Uh(n)}import*as Pr from"fs";import*as sg from"path";var VI=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function Qh(n,e){let t=-1;for(let r of VI){let i=n.lastIndexOf(r);i>t&&(t=i)}return t>=e?t:-1}function eg(n,e){let t=n.trim();if(t.length<=e)return{text:t,excerptTruncated:!1};let r=t.slice(0,e),i=Qh(r,e-20),o=i>=0?i:e;return{text:t.slice(0,o).trimEnd(),excerptTruncated:!0}}function tg(n,e,t={}){let{maxLen:r=th,contextChars:i=nh,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(Tt=>Tt.trim()).filter(Boolean),c=0;for(let Tt of a){let xt=s.toLowerCase().indexOf(Tt.toLowerCase());if(xt>=0){c=xt;break}}let l=Math.max(0,c-i),p=Math.min(s.length,l+r),g=s.slice(l,p),w=Qh(g,r-25);w>=0&&(p=l+w);let E=s.slice(l,p).trim(),O=l>0?"...":"",fe=p<s.length||o?"...":"";return`${O}${E}${fe}`}var zI=`
1286
1286
  SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
1287
1287
  d.catalog_id, bm25(segments_fts) AS bm25
1288
1288
  FROM segments_fts
@@ -1291,7 +1291,7 @@ ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this
1291
1291
  WHERE segments_fts MATCH ?
1292
1292
  ORDER BY bm25(segments_fts)
1293
1293
  LIMIT ?
1294
- `,DI=`
1294
+ `,qI=`
1295
1295
  SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
1296
1296
  d.catalog_id, bm25(segments_fts) AS bm25
1297
1297
  FROM segments_fts
@@ -1300,7 +1300,7 @@ ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this
1300
1300
  WHERE segments_fts MATCH ? AND d.catalog_id = ?
1301
1301
  ORDER BY bm25(segments_fts)
1302
1302
  LIMIT ?
1303
- `,RI=3.5,TI=1.4,kI=4,xI=1.8,LI=1.35,NI=3.5,OI=1.8,MI=120,Fh=6;function Ml(n){return n.toLowerCase().replace(/[^\p{L}\p{N}@.]+/gu,"")}function _I(n){return n.split(/[^\p{L}\p{N}@.]+/u).map(Ml).filter(e=>e.length>=2)}function FI(n,e){return e.length>1&&e.every(t=>n.includes(t))}function jI(n){return/^[a-z0-9]{1,4}$/.test(n.trim().toLowerCase())}function HI(n,e){return n===e?NI:n.startsWith(e)||n.includes(`@ohos.${e}`)?OI:1}function $I(n,e){let t=Ml(e);if(t.length<2)return 1;let r=Ml(n.doc_title);if(jI(e))return HI(r,t);if(r.includes(t))return kI;if(t.length>=Fh&&r.includes(t.slice(0,Fh)))return xI;let i=_I(e);return FI(r,i)?LI:1}function UI(n,e){return e<=1?n:n<0?n*e:n/e}function na(n,e,t,r){let i=n.bm25/(e.get(n.catalog_id)??1);return i=UI(i,$I(n,t)),r&&Tl(n.doc_title,n.section_title,r)&&(i/=RI,n.catalog_id===Yt["harmonyos-references"]&&(i/=TI)),i}function Ol(n,e,t,r){return n.reduce((i,o)=>na(o,e,t,r)<na(i,e,t,r)?o:i)}function BI(n,e){return e.some(t=>n.section_title.includes(t)||n.doc_title.includes(t))}function WI(n,e,t,r,i){if(i){let o=n.filter(s=>Tl(s.doc_title,s.section_title,i));if(o.length>0)return Ol(o,t,r,i)}if(e.length>0){let o=n.filter(s=>BI(s,e));if(o.length>0)return Ol(o,t,r,i)}return Ol(n,t,r,i)}function jh(n,e,t,r,i){let o=Lh(e),s=hh(e),c=Rl(e)?.camelCase,l=new Map;for(let E of n){let N=l.get(E.document_id)??[];N.push(E),l.set(E.document_id,N)}let d=[];for(let E of l.values())d.push(WI(E,s,o,t,c));let h=d.sort((E,N)=>na(E,o,t,c)-na(N,o,t,c));return(i?kh(h):h).slice(0,r)}function ra(n,e,t,r,i,o){let s=e?Yt[e]:void 0,a=Math.max(t,t*Sm,MI),c=s===void 0?n.all(AI,r,a):n.all(DI,r,s,a);return(s===void 0?jh(c,o,i,t,!0):jh(c,o,i,t,!1)).map(d=>({title:d.doc_title,documentId:d.document_id,sectionTitle:d.section_title||void 0,snippet:_h(d.lead_text,i,{excerptTruncated:!!d.excerpt_truncated})}))}var ia=`
1303
+ `,YI=3.5,JI=1.4,KI=4,ZI=1.8,XI=1.35,QI=3.5,eA=1.8,tA=120,ng=6;function Zl(n){return n.toLowerCase().replace(/[^\p{L}\p{N}@.]+/gu,"")}function nA(n){return n.split(/[^\p{L}\p{N}@.]+/u).map(Zl).filter(e=>e.length>=2)}function rA(n,e){return e.length>1&&e.every(t=>n.includes(t))}function iA(n){return/^[a-z0-9]{1,4}$/.test(n.trim().toLowerCase())}function oA(n,e){return n===e?QI:n.startsWith(e)||n.includes(`@ohos.${e}`)?eA:1}function sA(n,e){let t=Zl(e);if(t.length<2)return 1;let r=Zl(n.doc_title);if(iA(e))return oA(r,t);if(r.includes(t))return KI;if(t.length>=ng&&r.includes(t.slice(0,ng)))return ZI;let i=nA(e);return rA(r,i)?XI:1}function aA(n,e){return e<=1?n:n<0?n*e:n/e}function ua(n,e,t,r){let i=n.bm25/(e.get(n.catalog_id)??1);return i=aA(i,sA(n,t)),r&&Vl(n.doc_title,n.section_title,r)&&(i/=YI,n.catalog_id===Kt["harmonyos-references"]&&(i/=JI)),i}function Kl(n,e,t,r){return n.reduce((i,o)=>ua(o,e,t,r)<ua(i,e,t,r)?o:i)}function cA(n,e){return e.some(t=>n.section_title.includes(t)||n.doc_title.includes(t))}function lA(n,e,t,r,i){if(i){let o=n.filter(s=>Vl(s.doc_title,s.section_title,i));if(o.length>0)return Kl(o,t,r,i)}if(e.length>0){let o=n.filter(s=>cA(s,e));if(o.length>0)return Kl(o,t,r,i)}return Kl(n,t,r,i)}function rg(n,e,t,r,i){let o=Zh(e),s=Oh(e),c=Gl(e)?.camelCase,l=new Map;for(let E of n){let O=l.get(E.document_id)??[];O.push(E),l.set(E.document_id,O)}let p=[];for(let E of l.values())p.push(lA(E,s,o,t,c));let g=p.sort((E,O)=>ua(E,o,t,c)-ua(O,o,t,c));return(i?Jh(g):g).slice(0,r)}function pa(n,e,t,r,i,o){let s=e?Kt[e]:void 0,a=Math.max(t,t*Bm,tA),c=s===void 0?n.all(zI,r,a):n.all(qI,r,s,a);return(s===void 0?rg(c,o,i,t,!0):rg(c,o,i,t,!1)).map(p=>({title:p.doc_title,documentId:p.document_id,sectionTitle:p.section_title||void 0,snippet:tg(p.lead_text,i,{excerptTruncated:!!p.excerpt_truncated})}))}var fa=`
1304
1304
  CREATE TABLE documents (
1305
1305
  id INTEGER PRIMARY KEY,
1306
1306
  document_id TEXT NOT NULL UNIQUE,
@@ -1338,54 +1338,54 @@ CREATE TRIGGER segments_au AFTER UPDATE ON segments BEGIN
1338
1338
  END;
1339
1339
 
1340
1340
  CREATE INDEX segments_doc_id_idx ON segments(doc_id);
1341
- `;var Pr=null,_l=null;function GI(){Pr?.close(),Pr=null,_l=null}function zI(n,e){if(Pr&&_l===e)return Pr;Pr?.close();let t=new n(e,{readonly:!0,fileMustExist:!0});return Pr=t,_l=e,t.pragma("mmap_size = 268435456"),t.pragma("cache_size = -8000"),t.pragma("query_only = ON"),t}function VI(n,e){let t=new n(e);return t.pragma("journal_mode = OFF"),t.pragma("synchronous = OFF"),t.pragma("temp_store = MEMORY"),t.exec(ia),t}function qI(n,e,t){let r=e.get(t.documentId);if(r!==void 0)return r;let o=n.prepare("SELECT id FROM documents WHERE document_id = ?").get(t.documentId);if(o)return e.set(t.documentId,o.id),o.id;let a=n.prepare(`
1341
+ `;var Er=null,Xl=null;function dA(){Er?.close(),Er=null,Xl=null}function uA(n,e){if(Er&&Xl===e)return Er;Er?.close();let t=new n(e,{readonly:!0,fileMustExist:!0});return Er=t,Xl=e,t.pragma("mmap_size = 268435456"),t.pragma("cache_size = -8000"),t.pragma("query_only = ON"),t}function pA(n,e){let t=new n(e);return t.pragma("journal_mode = OFF"),t.pragma("synchronous = OFF"),t.pragma("temp_store = MEMORY"),t.exec(fa),t}function fA(n,e,t){let r=e.get(t.documentId);if(r!==void 0)return r;let o=n.prepare("SELECT id FROM documents WHERE document_id = ?").get(t.documentId);if(o)return e.set(t.documentId,o.id),o.id;let a=n.prepare(`
1342
1342
  INSERT INTO documents(document_id, catalog_id, doc_title)
1343
1343
  VALUES (?, ?, ?)
1344
- `).run(t.documentId,t.catalogId,t.docTitle),c=Number(a.lastInsertRowid);return e.set(t.documentId,c),c}async function YI(n,e,t,r){await Zt();let i=VI(n,e),o=new Map,s=i.prepare(`
1344
+ `).run(t.documentId,t.catalogId,t.docTitle),c=Number(a.lastInsertRowid);return e.set(t.documentId,c),c}async function mA(n,e,t,r){await Qt();let i=pA(n,e),o=new Map,s=i.prepare(`
1345
1345
  INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated)
1346
1346
  VALUES (?, ?, ?, ?, ?)
1347
- `),a=t.length;for(let c=0;c<a;c+=mr){let l=t.slice(c,c+mr),d=await Promise.all(l.map(async w=>({source:w,searchText:await ta(w)})));i.transaction(w=>{for(let E of w){let N=qI(i,o,E.source);s.run(N,E.source.sectionTitle,E.source.leadText,E.searchText,E.source.excerptTruncated?1:0)}})(d),await r?.(Math.min(c+l.length,a),a)}i.exec("ANALYZE"),i.exec("VACUUM"),i.close()}function JI(n,e,t,r,i,o,s){let a=zI(n,e);return ra({all(c,...l){return a.prepare(c).all(...l)}},t,r,i,o,s)}async function Hh(){let e=(await import("better-sqlite3")).default;return{kind:"better-sqlite3",resetCache:GI,buildSearchIndex:(t,r,i)=>YI(e,t,r,i),searchIndex:(t,r,i,o,s,a,c)=>Promise.resolve(JI(e,o,r,i,s,a,c))}}import{readFile as KI,stat as XI,writeFile as ZI}from"fs/promises";var Fl=null,Qt=null;async function jl(){return Fl||(Fl=(async()=>{let n=(await import("@sqlite.org/sqlite-wasm")).default;return n()})()),Fl}function QI(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 eA(n){let e=await XI(n);if(Qt&&Qt.dbPath===n&&Qt.mtimeMs===e.mtimeMs)return Qt.db;Qt?.db.close();let t=await jl(),r=t.capi,i=t.wasm,o=new Uint8Array(await KI(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 $h(){Qt?.db.close(),Qt=null}async function tA(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 nA(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 rA(n,e,t){await Zt();let r=await jl(),i=new r.oo1.DB(":memory:","c");i.exec(ia);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=nA(i,o,s),l=e.length;for(let h=0;h<l;h+=mr){let w=e.slice(h,h+mr),E=await Promise.all(w.map(async N=>({source:N,searchText:await ta(N)})));await tA(i,a,c,E),await t?.(Math.min(h+w.length,l),l)}i.exec("ANALYZE");let d=r.capi.sqlite3_js_db_export(i);await ZI(n,d),i.close(),$h()}async function iA(n,e,t,r,i,o){let s=await eA(n);return ra(QI(s),e,t,r,i,o)}async function Hl(){return await jl(),{kind:"sqlite-wasm",resetCache:$h,buildSearchIndex:rA,searchIndex:(n,e,t,r,i,o,s)=>iA(r,e,t,i,o,s)}}var oa=null,$l=null;function oA(){return Cr.existsSync(Ai())}function sA(n){let e=Ai(),t={backend:"sqlite-wasm",reason:"better-sqlite3-load-failed",message:n,createdAt:new Date().toISOString()};Cr.mkdirSync(Uh.dirname(e),{recursive:!0}),xi(e),Cr.writeFileSync(e,JSON.stringify(t,null,2))}async function aA(){if(oA())return Hl();try{let n=await Hh();return m("doc-index: using better-sqlite3 SQLite backend"),n}catch(n){let e=n instanceof Error?n.message:String(n);sA(e),m(`doc-index: better-sqlite3 unavailable (${e}); falling back to sqlite-wasm`)}return Hl()}async function $i(){return oa||(oa=aA().then(n=>($l=n,n))),oa}function Bh(){$l?.resetCache(),oa=null,$l=null}async function cA(n,e,t,r,i,o,s){let a=await $i(),c=s??Dn();return a.searchIndex(n,e,t,c,r,i,o)}function Ir(){Bh()}async function Gh(n,e,t){await(await $i()).buildSearchIndex(n,e,t)}function zh(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 sa(n,e,t,r,i,o){return cA(n,e,t,i,r.expandedQuery,r.rawQuery,o)}async function lA(n,e,t,r,i){let o=await sa(n,e,t,r,Mi(r.tokens,"AND"),i);if(o.length>=t)return o;let s=await sa(n,e,t,r,Mi(r.tokens,"OR"),i);return zh(o,s,t)}async function Ul(n,e,t,r,i){return r.ftsMatch?sa(n,e,t,r,r.ftsMatch,i):r.preferAnd?lA(n,e,t,r,i):sa(n,e,t,r,Mi(r.tokens,"OR"),i)}async function dA(n,e,t,r){let i=await Ul(n,"harmonyos-references",e,t,r);if(i.length>=e)return i;let o=await Ul(n,void 0,e,t,r);return zh(i,o,e)}function Wh(n,e){return e!==void 0?n:xh(n)}async function Bl(n,e,t=20,r){let i=await Rh(n);if(Eh(i.rawQuery,e)){let a=await dA(n,t,i,r);return Wh(a,e)}let o=e??Nh(i.rawQuery),s=await Ul(n,o,t,i,r);return Wh(s,e)}import{unified as Qh}from"unified";import eg from"remark-parse";import tg from"remark-gfm";import{toString as ca}from"mdast-util-to-string";var uA=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,pA=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,fA=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,mA=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,hA=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function aa(n){let e=n.trim(),t=e.match(mA);return t?t[1]:e}function gA(n){let e=n.match(uA);if(!e)return;let t=aa(e[1].trim());return{displayTitle:n,symbolName:t,searchExtras:[t,e[3]]}}function yA(n){let e=aa(n.replace(/\([^)]*\)$/,""));if(/^[A-Z][A-Za-z0-9]*$/.test(e))return{displayTitle:n,symbolName:e,searchExtras:[e]};if(/^[A-Z][A-Za-z0-9]*(\([^)]*\))?$/.test(n))return{displayTitle:n,symbolName:e,searchExtras:[e]}}function Ui(n){let e=n.trim();return e?gA(e)??(()=>{let t=e.match(pA);if(t){let r=t[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let t=e.match(fA);if(!t)return;let r=t[1].trim(),i=t[2].trim();return{displayTitle:e,symbolName:i,searchExtras:[r,i]}})()??yA(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function wA(n){if(n.length<2||n.length>36||hA.test(n))return!1;let e=[...n.replace(/\s/g,"")];return e.length===0?!1:e.filter(r=>new RegExp("\\p{Script=Han}","u").test(r)).length/e.length>=.4}function Vh(n){for(let e of n){let t=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(wA(t))return t}return""}function qh(n,e,t){let r=[n,...t.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var vA=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,Bi=/@[A-Z][a-zA-Z]+/g,SA=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,EA=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,bA=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,PA=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),CA=new Set(["HAP","HSP","HAR","NAPI","CAPI","NDK","ArkTS","ArkUI","OHPM"]),IA=new Set(["JSON","Object","Array","Promise","console","Math","Date","String","Number","Boolean","Error","Function","Map","Set","RegExp"]);function ng(n,e){let t=new Set,r=[n,...e];for(let i of r){for(let o of Al(i)){nt(t,o);let s=Ks(o);s&&nt(t,s)}for(let o of Dl(i))nt(t,o);for(let o of i.matchAll(vA)){let s=o[0];AA(s)&&t.add(s)}for(let o of i.matchAll(Bi))t.add(o[0])}return Er([...t])}function AA(n){let e=n.trim();if(!e||Bi.test(e))return!!e;if(e.includes(".")){let t=e.split(".")[0]??"";return IA.has(t)?!1:/^[A-Z]/.test(t)}return PA.has(e)?!1:CA.has(e)?!0:e.length<=3?!1:/^[A-Z][a-z]+[A-Z]/.test(e)?!0:e.length>=6&&/^[A-Z][A-Za-z0-9]+$/.test(e)}function Yh(n){let e=n.trim();return!!(!e||bA.test(e)||e.length>28&&!/[A-Z\u4e00-\u9fff]/.test(e)&&/^[a-z0-9_-]+$/.test(e))}function rg(n,e){let t=e.jsonTitle?.trim(),r=kA(n,"").trim(),i=e.fileName.trim();return t&&!Yh(t)?t:r&&!Yh(r)?r:t||r||i}function ig(n){return SA.test(n.trim())}function Wl(n){let e=n.trim().replace(/\([^)]*\)$/,""),t=aa(e);return EA.test(t)}function la(n){let e=n.trim();return e?Bi.test(e)||ig(e)||Wl(e)?!0:!!Ui(e).symbolName:!1}function DA(n){let e=n.trim();return!(!e||ig(e)||Wl(e))}function RA(n){let e=new Set,t=[];for(let r of n){let i=r.trim();!DA(i)||e.has(i)||(e.add(i),t.push(i))}return t}function Jh(n){if(!n.includes("."))return 0;let e=n.split(".").pop()??"";return/^[a-z]/.test(e)?1:2}function TA(n,e){let t=Jh(n)-Jh(e);return t!==0?t:n.localeCompare(e)}function og(n,e=[]){let t=[...new Set(e.map(o=>o.trim()).filter(Boolean))],r=new Set(t),i=[...new Set(n.map(o=>o.trim()).filter(Boolean))].filter(o=>!r.has(o));return i.sort(TA),[...t,...i].slice(0,xm)}function da(n){return n.replace(/\s+/g," ").trim()}function Kh(n){return n.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function kA(n,e=""){let t=n.split(/\r?\n/),r=0;for(;r<t.length&&!t[r].trim();)r+=1;if(r>=t.length)return e;let i=Kh(t[r].trim()),o=i.match(/^#+\s+(.+)$/);if(o)return Kh(o[1].trim());if(r+1<t.length){let s=t[r+1].trim();if(/^=+$/.test(s)||/^-+$/.test(s))return i}return i||e}function sg(n){let e=da(n.join(" "));if(e.length<=js)return e;let t=e.slice(0,js);return e.length<=js+al?t:`${t} ${e.slice(-al)}`}function xA(n){let e=RA(n).join(" ");return e.length<=cl?e:e.slice(0,cl)}function ag(n){let e=da(n),{text:t,excerptTruncated:r}=Mh(e,Lm);return{leadText:t,excerptTruncated:r}}function LA(n,e){let{leadText:t,excerptTruncated:r}=ag(n);return{leadText:t,excerptTruncated:r||!!e.trim()}}function cg(n,e){if(n.type==="code"){e.codeBlocks.push(n.value??"");return}if("children"in n&&Array.isArray(n.children)){for(let r of n.children)cg(r,e);return}let t=da(ca(n));t&&e.bodyParts.push(t)}function NA(n){let e=Qh().use(eg).use(tg).parse(n),t=[],r=null,i=()=>{r&&((r.sectionTitle||r.bodyParts.length||r.codeBlocks.length)&&t.push(r),r=null)},o=()=>{r||(r={sectionTitle:"",bodyParts:[],codeBlocks:[]})};for(let s of e.children){if(s.type==="heading"){let a=s,c=ca(a).trim();if(a.depth>=4&&c&&la(c)){i(),r={sectionTitle:c,bodyParts:[],codeBlocks:[]};continue}o(),c&&r.bodyParts.push(c);continue}o(),cg(s,r)}return i(),t.length===0?[{sectionTitle:"",bodyParts:[],codeBlocks:[]}]:t}function OA(n){return ym.test(n)}function MA(n){return n.filter(e=>e.sectionTitle&&la(e.sectionTitle)).length}function _A(n){return{sectionTitle:n.map(e=>e.sectionTitle.trim()).join(" | "),bodyParts:n.flatMap(e=>e.bodyParts).slice(0,40),codeBlocks:n.flatMap(e=>e.codeBlocks).slice(0,8)}}function Xh(n){let e=n.trim();return!e||Bi.test(e)?Bi.test(e):/对象说明$|枚举说明$/.test(e)?!0:Wl(e)}function FA(n){let e=n.filter(h=>!h.sectionTitle||!la(h.sectionTitle)),t=n.filter(h=>h.sectionTitle&&la(h.sectionTitle)),r=t.filter(h=>Xh(h.sectionTitle)),i=t.filter(h=>!Xh(h.sectionTitle)),o=Math.max(0,gm-r.length),s=i.slice(0,o),a=i.slice(o),c=a.filter(h=>Zh(h.sectionTitle)),l=a.filter(h=>!Zh(h.sectionTitle)),d=[];for(let h=0;h<l.length;h+=ol)d.push(_A(l.slice(h,h+ol)));return[...e,...r,...s,...c,...d]}function jA(n,e,t){let r=n.split(/\r?\n/).length,i=MA(e);return i===0?!1:OA(t)?r>=mm&&i>=hm:r>=pm&&i>=fm}var HA=/^\[h2\][A-Za-z]/;function Zh(n){return HA.test(n.trim())}function lg(n){if(!n.includes(" | ")){let t=Ui(n);return t.symbolName?[t.symbolName]:[]}let e=[];for(let t of n.split(" | ")){let r=Ui(t.trim()).symbolName;r&&e.push(r)}return e}function $A(n,e,t,r){let i=lg(n),o=ng(t,r);return e.symbolName&&o.push(e.symbolName),og([...i,...o],i)}function UA(n,e){let t=sg(n.bodyParts),r=n.sectionTitle.trim(),i=Ui(r),o=Vh(n.bodyParts),s=qh(r,o,i),a=lg(r),c=r?a.length>0?`${e.docTitle} ${a.join(" ")}`:`${e.docTitle} ${i.symbolName??r}`:e.docTitle,l=[e.docTitle,s,...n.bodyParts].join(" "),{leadText:d,excerptTruncated:h}=LA(t,r);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:e.docTitle,sectionTitle:r,titleTokens:c,headingsText:s,apiSymbols:$A(r,i,l,n.codeBlocks),bodySample:t,leadText:d,excerptTruncated:h}}function dg(n,e){for(let t of n){if(t.type==="heading"){let i=ca(t).trim();i&&e.headings.push(i);continue}if(t.type==="code"){e.codeBlocks.push(t.value??"");continue}if("children"in t&&Array.isArray(t.children)){dg(t.children,e);continue}let r=da(ca(t));r&&e.bodyParts.push(r)}}function BA(n){let e=Qh().use(eg).use(tg).parse(n),t={headings:[],bodyParts:[],codeBlocks:[]};return dg(e.children,t),t}function WA(n,e){let t=BA(n),r=e.docTitle?.trim()||e.documentId,i=sg(t.bodyParts),o=[r,...t.headings,i].join(" "),{leadText:s,excerptTruncated:a}=ag(i);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:r,sectionTitle:"",titleTokens:r,headingsText:xA(t.headings),apiSymbols:og(ng(o,t.codeBlocks)),bodySample:i,leadText:s,excerptTruncated:a}}function ug(n,e){let t=e.docTitle?.trim()||e.documentId,r=NA(n);return jA(n,r,e.documentId)?FA(r).filter(i=>i.sectionTitle||i.bodyParts.length>0||i.codeBlocks.length>0).map(i=>UA(i,{...e,docTitle:t})):[WA(n,{...e,docTitle:t})]}async function GA(n){let e=[];async function t(r){let i=await fe.promises.readdir(r,{withFileTypes:!0});for(let o of i){if(o.name.startsWith("."))continue;let s=Pe.join(r,o.name);o.isDirectory()?await t(s):o.isFile()&&o.name.endsWith(".md")&&e.push(s)}}return await t(n),e}function zA(n,e){let t=Pe.relative(e,n).split(Pe.sep).join("/").split("/");if(t[0]==="docs"&&(t=t.slice(1)),t.length<2)return null;let r=t[0],i=Mm[r];if(i===void 0)return null;let o=t[t.length-1].replace(/\.md$/,"");return t[t.length-1]=o,{documentId:t.join("/"),catalogId:i,docTitle:o}}async function VA(n){let e=n.replace(/\.md$/,".json");try{let t=await fe.promises.readFile(e,"utf-8");return JSON.parse(t).title?.trim()||void 0}catch{return}}async function qA(n,e){let t=zA(n,e);if(!t)return[];let r=await fe.promises.readFile(n,"utf-8"),i=rg(r,{jsonTitle:await VA(n),fileName:t.docTitle});return ug(r,{...t,docTitle:i})}async function YA(n,e,t){let r=Pe.join(e,"search.db");return await Gh(r,n,async(i,o)=>{await t?.({current:i,total:o,message:`Building search index\u2026 ${i.toLocaleString()} / ${o.toLocaleString()} segments`})}),n.length}async function JA(n){let e=await GA(n),t=[];for(let r of e){let i=await qA(r,n);t.push(...i)}return t}function KA(n,e){return{indexVersion:fr,docsZipSha256:n.docsZipSha256,termsHash:n.termsHash,synonymsHash:n.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:n.builtBy}}async function fg(n){n.lexiconDir&&pl(n.lexiconDir);try{let e=await JA(n.docsDir);await n.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await fe.promises.mkdir(n.tmpDir,{recursive:!0});let t=await YA(e,n.tmpDir,n.onProgress),r=KA(n,t);return await fe.promises.writeFile(Pe.join(n.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await qm(n.tmpDir),r}finally{n.lexiconDir&&pl(null)}}async function mg(){return fe.promises.mkdtemp(Pe.join(pg.tmpdir(),"deveco-docs-"))}async function XA(n,e){try{await fe.promises.rename(n,e)}catch(t){let r=t.code;if(r!=="EPERM"&&r!=="EXDEV")throw t;await fe.promises.cp(n,e,{recursive:!0}),await fe.promises.rm(n,{recursive:!0,force:!0})}}async function hg(n){let e=Pe.join(n,"docs");try{await fe.promises.access(e)}catch{return}let t=new Set(["docs","docs.zip"]);for(let r of await fe.promises.readdir(e,{withFileTypes:!0})){if(t.has(r.name))continue;let i=Pe.join(e,r.name),o=Pe.join(n,r.name);await fe.promises.rm(o,{recursive:!0,force:!0}),await XA(i,o)}await fe.promises.rm(Pe.join(e,"docs"),{recursive:!0,force:!0}),await fe.promises.rm(Pe.join(e,"docs.zip"),{force:!0}),await fe.promises.rm(e,{recursive:!0,force:!0})}var Wi=class extends Error{constructor(e){super(e),this.name="NativeDepsError"}};function ZA(){let n=wr(),e=Y();return["Documentation search index is not installed yet.","",...Hs(n),`Index directory: ${e}`,"","Try:"," 1. Wait a moment and run the docs command again (postinstall may still be running)"," 2. Reinstall: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>"," 3. Check the log file above for setup errors"].join(`
1348
- `)}function QA(){let n=wr();return["Chinese tokenizer (@node-rs/jieba) failed to load.","",`Node.js: ${process.version} (required: >=18)`,"",...Hs(n),"","Try:"," 1. Reinstall: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>"," 2. Use Node.js 18 or newer"," 3. Configure npm registry/proxy if your network blocks optional platform packages"].join(`
1349
- `)}function eD(n){let e=wr();return[n,"",...Hs(e)].join(`
1350
- `)}async function gg(){try{zm()}catch(n){throw Gm(n)?new Wi(`${ZA()}
1347
+ `),a=t.length;for(let c=0;c<a;c+=mr){let l=t.slice(c,c+mr),p=await Promise.all(l.map(async w=>({source:w,searchText:await da(w)})));i.transaction(w=>{for(let E of w){let O=fA(i,o,E.source);s.run(O,E.source.sectionTitle,E.source.leadText,E.searchText,E.source.excerptTruncated?1:0)}})(p),await r?.(Math.min(c+l.length,a),a)}i.exec("ANALYZE"),i.exec("VACUUM"),i.close()}function hA(n,e,t,r,i,o,s){let a=uA(n,e);return pa({all(c,...l){return a.prepare(c).all(...l)}},t,r,i,o,s)}async function ig(){let e=(await import("better-sqlite3")).default;return{kind:"better-sqlite3",resetCache:dA,buildSearchIndex:(t,r,i)=>mA(e,t,r,i),searchIndex:(t,r,i,o,s,a,c)=>Promise.resolve(hA(e,o,r,i,s,a,c))}}import{readFile as gA,stat as yA,writeFile as wA}from"fs/promises";var Ql=null,en=null;async function ed(){return Ql||(Ql=(async()=>{let n=(await import("@sqlite.org/sqlite-wasm")).default;return n()})()),Ql}function vA(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 SA(n){let e=await yA(n);if(en&&en.dbPath===n&&en.mtimeMs===e.mtimeMs)return en.db;en?.db.close();let t=await ed(),r=t.capi,i=t.wasm,o=new Uint8Array(await gA(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),en={dbPath:n,mtimeMs:e.mtimeMs,db:a},a}function og(){en?.db.close(),en=null}async function bA(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 EA(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 PA(n,e,t){await Qt();let r=await ed(),i=new r.oo1.DB(":memory:","c");i.exec(fa);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=EA(i,o,s),l=e.length;for(let g=0;g<l;g+=mr){let w=e.slice(g,g+mr),E=await Promise.all(w.map(async O=>({source:O,searchText:await da(O)})));await bA(i,a,c,E),await t?.(Math.min(g+w.length,l),l)}i.exec("ANALYZE");let p=r.capi.sqlite3_js_db_export(i);await wA(n,p),i.close(),og()}async function CA(n,e,t,r,i,o){let s=await SA(n);return pa(vA(s),e,t,r,i,o)}async function td(){return await ed(),{kind:"sqlite-wasm",resetCache:og,buildSearchIndex:PA,searchIndex:(n,e,t,r,i,o,s)=>CA(r,e,t,i,o,s)}}var ma=null,nd=null;function IA(){return Pr.existsSync(ki())}function AA(n){let e=ki(),t={backend:"sqlite-wasm",reason:"better-sqlite3-load-failed",message:n,createdAt:new Date().toISOString()};Pr.mkdirSync(sg.dirname(e),{recursive:!0}),Ni(e),Pr.writeFileSync(e,JSON.stringify(t,null,2))}async function DA(){if(IA())return td();try{let n=await ig();return m("doc-index: using better-sqlite3 SQLite backend"),n}catch(n){let e=n instanceof Error?n.message:String(n);AA(e),m(`doc-index: better-sqlite3 unavailable (${e}); falling back to sqlite-wasm`)}return td()}async function Bi(){return ma||(ma=DA().then(n=>(nd=n,n))),ma}function ag(){nd?.resetCache(),ma=null,nd=null}async function kA(n,e,t,r,i,o,s){let a=await Bi(),c=s??An();return a.searchIndex(n,e,t,c,r,i,o)}function Cr(){ag()}async function lg(n,e,t){await(await Bi()).buildSearchIndex(n,e,t)}function dg(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 ha(n,e,t,r,i,o){return kA(n,e,t,i,r.expandedQuery,r.rawQuery,o)}async function RA(n,e,t,r,i){let o=await ha(n,e,t,r,Fi(r.tokens,"AND"),i);if(o.length>=t)return o;let s=await ha(n,e,t,r,Fi(r.tokens,"OR"),i);return dg(o,s,t)}async function rd(n,e,t,r,i){return r.ftsMatch?ha(n,e,t,r,r.ftsMatch,i):r.preferAnd?RA(n,e,t,r,i):ha(n,e,t,r,Fi(r.tokens,"OR"),i)}async function TA(n,e,t,r){let i=await rd(n,"harmonyos-references",e,t,r);if(i.length>=e)return i;let o=await rd(n,void 0,e,t,r);return dg(i,o,e)}function cg(n,e){return e!==void 0?n:Kh(n)}async function id(n,e,t=20,r){let i=await qh(n);if($h(i.rawQuery,e)){let a=await TA(n,t,i,r);return cg(a,e)}let o=e??Xh(i.rawQuery),s=await rd(n,o,t,i,r);return cg(s,e)}import{unified as wg}from"unified";import vg from"remark-parse";import Sg from"remark-gfm";import{toString as ya}from"mdast-util-to-string";var xA=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,LA=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,NA=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,OA=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,MA=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function ga(n){let e=n.trim(),t=e.match(OA);return t?t[1]:e}function _A(n){let e=n.match(xA);if(!e)return;let t=ga(e[1].trim());return{displayTitle:n,symbolName:t,searchExtras:[t,e[3]]}}function FA(n){let e=ga(n.replace(/\([^)]*\)$/,""));if(/^[A-Z][A-Za-z0-9]*$/.test(e))return{displayTitle:n,symbolName:e,searchExtras:[e]};if(/^[A-Z][A-Za-z0-9]*(\([^)]*\))?$/.test(n))return{displayTitle:n,symbolName:e,searchExtras:[e]}}function Wi(n){let e=n.trim();return e?_A(e)??(()=>{let t=e.match(LA);if(t){let r=t[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let t=e.match(NA);if(!t)return;let r=t[1].trim(),i=t[2].trim();return{displayTitle:e,symbolName:i,searchExtras:[r,i]}})()??FA(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function jA(n){if(n.length<2||n.length>36||MA.test(n))return!1;let e=[...n.replace(/\s/g,"")];return e.length===0?!1:e.filter(r=>new RegExp("\\p{Script=Han}","u").test(r)).length/e.length>=.4}function ug(n){for(let e of n){let t=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(jA(t))return t}return""}function pg(n,e,t){let r=[n,...t.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var HA=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,Gi=/@[A-Z][a-zA-Z]+/g,$A=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,UA=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,BA=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,WA=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),GA=new Set(["HAP","HSP","HAR","NAPI","CAPI","NDK","ArkTS","ArkUI","OHPM"]),VA=new Set(["JSON","Object","Array","Promise","console","Math","Date","String","Number","Boolean","Error","Function","Map","Set","RegExp"]);function bg(n,e){let t=new Set,r=[n,...e];for(let i of r){for(let o of Bl(i)){tt(t,o);let s=oa(o);s&&tt(t,s)}for(let o of Wl(i))tt(t,o);for(let o of i.matchAll(HA)){let s=o[0];zA(s)&&t.add(s)}for(let o of i.matchAll(Gi))t.add(o[0])}return Sr([...t])}function zA(n){let e=n.trim();if(!e||Gi.test(e))return!!e;if(e.includes(".")){let t=e.split(".")[0]??"";return VA.has(t)?!1:/^[A-Z]/.test(t)}return WA.has(e)?!1:GA.has(e)?!0:e.length<=3?!1:/^[A-Z][a-z]+[A-Z]/.test(e)?!0:e.length>=6&&/^[A-Z][A-Za-z0-9]+$/.test(e)}function fg(n){let e=n.trim();return!!(!e||BA.test(e)||e.length>28&&!/[A-Z\u4e00-\u9fff]/.test(e)&&/^[a-z0-9_-]+$/.test(e))}function Eg(n,e){let t=e.jsonTitle?.trim(),r=KA(n,"").trim(),i=e.fileName.trim();return t&&!fg(t)?t:r&&!fg(r)?r:t||r||i}function Pg(n){return $A.test(n.trim())}function od(n){let e=n.trim().replace(/\([^)]*\)$/,""),t=ga(e);return UA.test(t)}function wa(n){let e=n.trim();return e?Gi.test(e)||Pg(e)||od(e)?!0:!!Wi(e).symbolName:!1}function qA(n){let e=n.trim();return!(!e||Pg(e)||od(e))}function YA(n){let e=new Set,t=[];for(let r of n){let i=r.trim();!qA(i)||e.has(i)||(e.add(i),t.push(i))}return t}function mg(n){if(!n.includes("."))return 0;let e=n.split(".").pop()??"";return/^[a-z]/.test(e)?1:2}function JA(n,e){let t=mg(n)-mg(e);return t!==0?t:n.localeCompare(e)}function Cg(n,e=[]){let t=[...new Set(e.map(o=>o.trim()).filter(Boolean))],r=new Set(t),i=[...new Set(n.map(o=>o.trim()).filter(Boolean))].filter(o=>!r.has(o));return i.sort(JA),[...t,...i].slice(0,Qm)}function va(n){return n.replace(/\s+/g," ").trim()}function hg(n){return n.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function KA(n,e=""){let t=n.split(/\r?\n/),r=0;for(;r<t.length&&!t[r].trim();)r+=1;if(r>=t.length)return e;let i=hg(t[r].trim()),o=i.match(/^#+\s+(.+)$/);if(o)return hg(o[1].trim());if(r+1<t.length){let s=t[r+1].trim();if(/^=+$/.test(s)||/^-+$/.test(s))return i}return i||e}function Ig(n){let e=va(n.join(" "));if(e.length<=Ys)return e;let t=e.slice(0,Ys);return e.length<=Ys+Cl?t:`${t} ${e.slice(-Cl)}`}function ZA(n){let e=YA(n).join(" ");return e.length<=Il?e:e.slice(0,Il)}function Ag(n){let e=va(n),{text:t,excerptTruncated:r}=eg(e,eh);return{leadText:t,excerptTruncated:r}}function XA(n,e){let{leadText:t,excerptTruncated:r}=Ag(n);return{leadText:t,excerptTruncated:r||!!e.trim()}}function Dg(n,e){if(n.type==="code"){e.codeBlocks.push(n.value??"");return}if("children"in n&&Array.isArray(n.children)){for(let r of n.children)Dg(r,e);return}let t=va(ya(n));t&&e.bodyParts.push(t)}function QA(n){let e=wg().use(vg).use(Sg).parse(n),t=[],r=null,i=()=>{r&&((r.sectionTitle||r.bodyParts.length||r.codeBlocks.length)&&t.push(r),r=null)},o=()=>{r||(r={sectionTitle:"",bodyParts:[],codeBlocks:[]})};for(let s of e.children){if(s.type==="heading"){let a=s,c=ya(a).trim();if(a.depth>=4&&c&&wa(c)){i(),r={sectionTitle:c,bodyParts:[],codeBlocks:[]};continue}o(),c&&r.bodyParts.push(c);continue}o(),Dg(s,r)}return i(),t.length===0?[{sectionTitle:"",bodyParts:[],codeBlocks:[]}]:t}function eD(n){return Hm.test(n)}function tD(n){return n.filter(e=>e.sectionTitle&&wa(e.sectionTitle)).length}function nD(n){return{sectionTitle:n.map(e=>e.sectionTitle.trim()).join(" | "),bodyParts:n.flatMap(e=>e.bodyParts).slice(0,40),codeBlocks:n.flatMap(e=>e.codeBlocks).slice(0,8)}}function gg(n){let e=n.trim();return!e||Gi.test(e)?Gi.test(e):/对象说明$|枚举说明$/.test(e)?!0:od(e)}function rD(n){let e=n.filter(g=>!g.sectionTitle||!wa(g.sectionTitle)),t=n.filter(g=>g.sectionTitle&&wa(g.sectionTitle)),r=t.filter(g=>gg(g.sectionTitle)),i=t.filter(g=>!gg(g.sectionTitle)),o=Math.max(0,jm-r.length),s=i.slice(0,o),a=i.slice(o),c=a.filter(g=>yg(g.sectionTitle)),l=a.filter(g=>!yg(g.sectionTitle)),p=[];for(let g=0;g<l.length;g+=El)p.push(nD(l.slice(g,g+El)));return[...e,...r,...s,...c,...p]}function iD(n,e,t){let r=n.split(/\r?\n/).length,i=tD(e);return i===0?!1:eD(t)?r>=_m&&i>=Fm:r>=Om&&i>=Mm}var oD=/^\[h2\][A-Za-z]/;function yg(n){return oD.test(n.trim())}function kg(n){if(!n.includes(" | ")){let t=Wi(n);return t.symbolName?[t.symbolName]:[]}let e=[];for(let t of n.split(" | ")){let r=Wi(t.trim()).symbolName;r&&e.push(r)}return e}function sD(n,e,t,r){let i=kg(n),o=bg(t,r);return e.symbolName&&o.push(e.symbolName),Cg([...i,...o],i)}function aD(n,e){let t=Ig(n.bodyParts),r=n.sectionTitle.trim(),i=Wi(r),o=ug(n.bodyParts),s=pg(r,o,i),a=kg(r),c=r?a.length>0?`${e.docTitle} ${a.join(" ")}`:`${e.docTitle} ${i.symbolName??r}`:e.docTitle,l=[e.docTitle,s,...n.bodyParts].join(" "),{leadText:p,excerptTruncated:g}=XA(t,r);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:e.docTitle,sectionTitle:r,titleTokens:c,headingsText:s,apiSymbols:sD(r,i,l,n.codeBlocks),bodySample:t,leadText:p,excerptTruncated:g}}function Rg(n,e){for(let t of n){if(t.type==="heading"){let i=ya(t).trim();i&&e.headings.push(i);continue}if(t.type==="code"){e.codeBlocks.push(t.value??"");continue}if("children"in t&&Array.isArray(t.children)){Rg(t.children,e);continue}let r=va(ya(t));r&&e.bodyParts.push(r)}}function cD(n){let e=wg().use(vg).use(Sg).parse(n),t={headings:[],bodyParts:[],codeBlocks:[]};return Rg(e.children,t),t}function lD(n,e){let t=cD(n),r=e.docTitle?.trim()||e.documentId,i=Ig(t.bodyParts),o=[r,...t.headings,i].join(" "),{leadText:s,excerptTruncated:a}=Ag(i);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:r,sectionTitle:"",titleTokens:r,headingsText:ZA(t.headings),apiSymbols:Cg(bg(o,t.codeBlocks)),bodySample:i,leadText:s,excerptTruncated:a}}function Tg(n,e){let t=e.docTitle?.trim()||e.documentId,r=QA(n);return iD(n,r,e.documentId)?rD(r).filter(i=>i.sectionTitle||i.bodyParts.length>0||i.codeBlocks.length>0).map(i=>aD(i,{...e,docTitle:t})):[lD(n,{...e,docTitle:t})]}async function uD(n,e,t){let r=ad.join(e,"search.db");return await lg(r,n,async(i,o)=>{await t?.({current:i,total:o,message:`Building search index\u2026 ${i.toLocaleString()} / ${o.toLocaleString()} segments`})}),n.length}function pD(n){return n.getEntries().filter(e=>e.isDirectory||!e.entryName.endsWith(".md")?!1:e.entryName.split("/").every(r=>!r.startsWith(".")))}function fD(n){let e=n.split("/");if(e[0]==="docs"&&(e=e.slice(1)),e.length<2)return null;let t=e[0],r=rh[t];if(r===void 0)return null;let i=e[e.length-1].replace(/\.md$/,"");return e[e.length-1]=i,{documentId:e.join("/"),catalogId:r,docTitle:i}}function mD(n,e){let t=e.replace(/\.md$/,".json"),r=n.getEntry(t);if(r)try{return JSON.parse(r.getData().toString("utf-8")).title?.trim()||void 0}catch{return}}function hD(n,e){let t=fD(n.entryName);if(!t)return[];let r=n.getData().toString("utf-8"),i=Eg(r,{jsonTitle:mD(e,n.entryName),fileName:t.docTitle});return Tg(r,{...t,docTitle:i})}async function gD(n){let e=new dD(n),t=pD(e),r=[];for(let i of t){let o=hD(i,e);r.push(...o)}return r}function yD(n,e){return{indexVersion:fr,docsZipSha256:n.docsZipSha256,termsHash:n.termsHash,synonymsHash:n.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:n.builtBy}}async function xg(n){n.lexiconDir&&kl(n.lexiconDir);try{let e=await gD(n.docsZipPath);await n.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await sd.promises.mkdir(n.tmpDir,{recursive:!0});let t=await uD(e,n.tmpDir,n.onProgress),r=yD(n,t);return await sd.promises.writeFile(ad.join(n.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await ph(n.tmpDir),r}finally{n.lexiconDir&&kl(null)}}var Vi=class extends Error{constructor(e){super(e),this.name="NativeDepsError"}};function wD(){let n=yr(),e=q();return["Documentation search index is not installed yet.","",...$o(n),`Index directory: ${e}`,"","Try:"," 1. Wait a moment and run the docs command again (postinstall may still be running)"," 2. Reinstall: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>"," 3. Check the log file above for setup errors"].join(`
1348
+ `)}function vD(){let n=yr();return["Chinese tokenizer (@node-rs/jieba) failed to load.","",`Node.js: ${process.version} (required: >=18)`,"",...$o(n),"","Try:"," 1. Reinstall: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>"," 2. Use Node.js 18 or newer"," 3. Configure npm registry/proxy if your network blocks optional platform packages"].join(`
1349
+ `)}function SD(n){let e=yr();return[n,"",...$o(e)].join(`
1350
+ `)}async function Lg(){try{dh()}catch(n){throw lh(n)?new Vi(`${wD()}
1351
1351
 
1352
- Detail: ${n.message}`):n}try{await Zt()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Wi(`${QA()}
1352
+ Detail: ${n.message}`):n}try{await Qt()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Vi(`${vD()}
1353
1353
 
1354
- Detail: ${e}`)}try{await $i()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Wi(eD(e))}}var Gl=class extends Error{constructor(t,r){super(r);this.code=t;this.name="DocNotReadyError"}code};function rD(n){return new Promise(e=>setTimeout(e,n))}async function Sg(n){let e=wr();await X.promises.mkdir(ut.dirname(e),{recursive:!0}),await X.promises.appendFile(e,`${new Date().toISOString()} ${n}
1355
- `)}async function iD(n){let e=Kt();if(!e)throw new Error("docs.zip not found");await X.promises.rm(n,{recursive:!0,force:!0}),await X.promises.mkdir(n,{recursive:!0});let t=ut.resolve(n),r=new tD(e);for(let i of r.getEntries()){let o=ut.resolve(t,i.entryName);if(!_r(o,t))throw new Error(`Unsafe docs.zip entry path: ${i.entryName}`);if(i.isDirectory){await X.promises.mkdir(o,{recursive:!0});continue}await X.promises.mkdir(ut.dirname(o),{recursive:!0}),await X.promises.writeFile(o,i.getData())}await hg(n)}async function oD(){await Sr({mode:"write"});let n=Y(),e=Ct(),t=await X.promises.readdir(e);for(let r of t){let i=ut.join(n,r);await X.promises.rm(i,{force:!0}),await X.promises.rename(ut.join(e,r),i)}await X.promises.rm(e,{recursive:!0,force:!0}),await X.promises.rm(ut.join(n,"orama.dpack"),{force:!0})}async function yg(n,e,t){e?.start(t),await Xt({state:"installing",phase:1,phaseLabel:"Installing index",message:t}),await eh(n),Ir(),e&&(e.text="Documentation index installed.")}async function sD(n,e){try{return await yg(n,e,"Installing documentation index\u2026"),await zl(e),!0}catch(t){if(ki(t))throw t}try{return await th(),Ir(),await yg(n,e,"Retrying documentation index install\u2026"),await zl(e),!0}catch(t){if(ki(t))throw t;let r=t instanceof Error?t.message:String(t);return await Sg(`Bundled index install failed; falling back to local rebuild: ${r}`),!1}}async function aD(n,e,t){let r=Ct(),i=await mg();await X.promises.mkdir(Y(),{recursive:!0}),await X.promises.rm(r,{recursive:!0,force:!0}),t?.start("Building search index\u2026"),await Xt({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"});try{await iD(i),await fg({docsDir:i,tmpDir:r,docsZipSha256:e,termsHash:qs(),synonymsHash:Vs(),builtBy:n.builtBy??"doc-init",onProgress:async o=>{t&&(t.text=o.message),await Xt({state:"indexing",current:o.current,total:o.total,message:o.message})}})}finally{await X.promises.rm(i,{recursive:!0,force:!0})}await Xt({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await oD(),Ir()}async function zl(n){await Xt({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function cD(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 Xt({state:"done",message:t,error:null})}async function lD(n,e){let t=n instanceof Error?n.message:String(n);throw await Xt({state:"error",error:t}),await Sg(`ERROR: ${t}`),e?.fail(t),n}async function dD(){let n=Y();await X.promises.mkdir(n,{recursive:!0});let e=$s();return X.existsSync(e)||await X.promises.writeFile(e,"","utf-8"),e}async function uD(){let n=await dD();return nD.lock(n,{stale:1800*1e3})}async function pD(){let n=Kt(),e=(n?await zs(n):null)??await bl();if(!e)throw new Error("docs.zip not found");return e}async function fD(n,e){let t=await pD(),r=n.force||await Cl(n.force),i=await Js(n.force);if(!r&&!i&&Ni()){await cD(e);return}!n.force&&Qm(t)&&await sD(t,e)||(await aD(n,t,e),await zl(e))}var Gi=class{static async run(e={}){let t=e.background??!1,i=e.quiet??t?void 0:vg({text:"Checking documentation\u2026",color:"cyan"}),o;try{e.assumeStorageSafe||await Sr({mode:"write"}),o=await uD(),await El(sh("Starting documentation setup\u2026")),await fD(e,i)}catch(s){if(o)return lD(s,i);throw s}finally{o&&await o()}}};async function mD(n){for(;;){let e=await Ys();if(e.state==="done"&&Ni())return;if(e.state==="error")throw new Gl("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 rD(500)}}async function wg(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await Gi.run({builtBy:"doc-init",force:e,quiet:!0})}async function hD(){let n=await Js()!==null;if(Ni()&&!n)return;let e=vg({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await ah()){await mD(e),e.succeed("Documentation ready.");return}if(await Cl()){await wg(e),e.succeed("Documentation ready.");return}await wg(e,!0),e.succeed("Documentation ready.")}catch(t){throw e.fail(t.message),t}}async function zi(){await Sr({mode:"read"}),await hD(),await gg()}function gD(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 Vl=class{async search(e,t,r=20){await zi();try{return await Bl(e,t,r)}catch(i){if(!gD(i))throw i;return Ir(),await Gi.run({builtBy:"doc-init",force:!0,quiet:!0,assumeStorageSafe:!0}),Bl(e,t,r)}}async readDocument(e){return await zi(),Km(e)}},ql=new Vl;function Eg(...n){return e=>{if(!n.includes(e))throw new Yl(`Allowed values: ${n.join(", ")}`);return e}}function vD(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new Yl("Must be a positive integer.");return e}var SD=Eg("json","default"),ED=Eg("json","default");function Jl(n){let e=n instanceof Error?n.message:String(n);return ki(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 pa=new yD("docs").description("Search and read HarmonyOS documentation from local docs directory");pa.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",PD,"all").option("--format <fmt>","Output format (default, json)",SD,"default").option("--limit <n>","Max number of results",vD,20).action(async(n,e)=>{try{let t=bD(n),r=e.catalog&&e.catalog!=="all"?e.catalog:void 0,i=await ql.search(t,r,e.limit);e.format==="json"?console.log(JSON.stringify(i,null,2)):CD(i)}catch(t){console.error(ua(Jl(t))),process.exit(1)}});pa.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{try{let e=n.trim();e||(console.error(ua("Document ID cannot be empty.")),process.exit(1));let t=await ql.readDocument(e);console.log(t)}catch(e){console.error(ua(Jl(e))),process.exit(1)}});pa.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",ED,"default").action(async n=>{try{if(await zi(),n.format==="json"){let e=qt.map(t=>({name:t,title:In[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of qt)console.log(` ${e.padEnd(20)} ${wD(In[e])}`)}catch(e){console.error(ua(Jl(e))),process.exit(1)}});function bD(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 PD(n){if(n==="all")return"all";if(!qt.includes(n))throw new Yl(`Invalid catalog "${n}". Allowed: all, ${qt.join(", ")}`);return n}function CD(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 bg=pa;import{Command as RR}from"commander";import{Command as _D,InvalidArgumentError as FD,Option as Xl}from"commander";import{readFileSync as AD,unlinkSync as DD}from"fs";import{tmpdir as RD}from"os";import{join as TD}from"path";var Rt=class{constructor(e,t){this.hdcPath=e;this.serial=t}hdcPath;serial;async listWindows(e){let t=await this.fetchDump(),r=ID(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 xe(this.hdcPath,e);if(t.exitCode!==0)throw new Error(`Failed to query windows: ${(t.stderr||t.stdout).trim()}`);return t.stdout}};function ID(n){let e=n.split(`
1356
- `),t=e.findIndex(s=>s.trimStart().startsWith("WindowName"));if(t===-1)return[];let r=[];for(let s=t+1;s<e.length;s++){let a=e[s].trim();if(!a||/^-+$/.test(a)||a.startsWith("Focus window")||a.startsWith("total window"))break;let c=a.split(/\s+/);if(c.length<5)continue;let l=c[0],d=Number(c[1]),h=Number(c[2]),w=Number(c[3]),E=Number(c[4]);Number.isFinite(w)&&Number.isFinite(d)&&Number.isFinite(h)&&r.push({id:w,name:l,pid:h,displayId:d,type:E})}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 Pg(n){if(!(!n||n==="HitTestMode.Default"))return n.startsWith("HitTestMode.")?n.slice(12):n}function Vi(n){if(!(n==null||n==="")){if(typeof n=="boolean")return n;if(n==="true")return!0;if(n==="false")return!1}}function Cg(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 Ig(n){return n.originalText||void 0}function Ar(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 Ag(n,e){let t=[],r=[{current:n,parent:null,depth:0}];for(;r.length>0;){let{current:i,parent:o,depth:s}=r.pop(),a=o===null,c=!i.id&&!i.text&&!i.clickable&&!i.longClickable&&!i.scrollable&&!i.checkable,l=a||!c,d=o;if(l){let w={...i,children:[]};if(a?t.push(w):o.children.push(w),d=w,e>0&&s+1>=e)continue}if(process.env.DEVECO_CLI_DEBUG){let w=i.type?i.id?`${i.type}#${i.id}`:i.type:"#";m(`collapse ${w} depth=${s} -> ${a?"root":c?"collapsed":"emitted"}`)}let h=l?s+1:s;for(let w=i.children.length-1;w>=0;w--)r.push({current:i.children[w],parent:d,depth:h})}return t}function kD(n){let e=AD(n,"utf-8").trim();if(!e)throw new Error("Empty dumpLayout response from device");return JSON.parse(e)}function xD(n){return n.attributes??{}}function fa(n,e,t){let r=xD(n),i={id:r.id||void 0,type:r.type||void 0,text:Ig(r),bounds:Cg(r.bounds),clickable:Vi(r.clickable)||void 0,longClickable:Vi(r.longClickable)||void 0,scrollable:Vi(r.scrollable)||void 0,checkable:Vi(r.checkable)||void 0,hitTestBehavior:Pg(r.hitTestBehavior),children:[]};return e>0&&t+1>=e||n.children&&(i.children=n.children.map(o=>fa(o,e,t+1))),i}function LD(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 Tn=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 xe(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=TD(RD(),`deveco_cli_dump_${Date.now()}_${process.pid}.json`);try{return await this.recvDumpFile(e,t,r),kD(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 xe(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}`),DD(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 xe(this.hdcPath,i).catch(o=>{m(`Failed to clean remote dump file ${r}: ${o.message}`)})}async dumpRawNodes(e,t,r){let o=await new Rt(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=LD(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=>fa(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:fa(s,t,0)})}return i}async dumpCollapsedTree(e,t,r,i){return(await this.dumpRawNodes(e,r,i)).flatMap(s=>Ag(fa(s,0,0),t))}};var ma={left:"0",right:"1",up:"2",down:"3"};function we(n,e){let t=Number(n);if(!Number.isInteger(t)||t<=0)throw new Error(`${e} must be a positive integer`)}function Kl(n,e){n!==void 0&&we(n,e)}function Dg(n,e){if(n===void 0!=(e===void 0))throw new Error("x and y must be provided together")}function ha(n,e){if(n!==void 0&&n.length===0)throw new Error(`${e} must not be empty`)}function qi(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 Rg(n){if(n!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(n))throw new Error("--window must consist of letters, digits, - or _")}function Tg(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 Dr(n,e,t,r,i=!0){Dg(n,e),ha(t,"--id"),Kl(n,"x"),Kl(e,"y"),Rg(r),Tg(n!==void 0,!!t,!!r,i)}async function Rr(n,e){let r=await new Kn(n).selectDevice(e);if(!r)throw new Error("No device selected. Use `devecocli device list` to see targets.");return r}async function pt(n){let e=await I.new(),t=await Rr(e,n);return{hdcPath:e.hdcPath,deviceId:t}}async function Tr(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 Rt(n,e).listWindows({all:!0}),c=new Tn(n);return ND(c,e,a,i,o)}async function ND(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 MD(s,r)}return OD(n,e,t,r)}async function OD(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 Ar([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 kg(s[0].node,r)}function MD(n,e){let t=Ar(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 kg(t[0],e)}function kg(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 Ue(n,e,t){let r=["-t",e,"shell",...t],i=await xe(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 jD from"ora";function HD(n){let e=parseInt(n,10);if(!Number.isInteger(e)||e<0||String(e)!==n.trim())throw new FD("depth must be a non-negative integer");return e}function $D(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 xg(n,e=0){let t=[],r=" ".repeat(e);for(let i of n)t.push(`${r}${$D(i)}`),i.children.length>0&&t.push(...xg(i.children,e+1).split(`
1354
+ Detail: ${e}`)}try{await Bi()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Vi(SD(e))}}var cd=class extends Error{constructor(t,r){super(r);this.code=t;this.name="DocNotReadyError"}code};function ED(n){return new Promise(e=>setTimeout(e,n))}async function _g(n){let e=yr();await ve.promises.mkdir(Ir.dirname(e),{recursive:!0}),await ve.promises.appendFile(e,`${new Date().toISOString()} ${n}
1355
+ `)}async function PD(){await vr({mode:"write"});let n=q(),e=Pt(),t=await ve.promises.readdir(e);for(let r of t){let i=Ir.join(n,r);await ve.promises.rm(i,{force:!0}),await ve.promises.rename(Ir.join(e,r),i)}await ve.promises.rm(e,{recursive:!0,force:!0}),await ve.promises.rm(Ir.join(n,"orama.dpack"),{force:!0})}async function Ng(n,e,t){e?.start(t),await Xt({state:"installing",phase:1,phaseLabel:"Installing index",message:t}),await vh(n),Cr(),e&&(e.text="Documentation index installed.")}async function CD(n,e){try{return await Ng(n,e,"Installing documentation index\u2026"),await ld(e),!0}catch(t){if(Li(t))throw t}try{return await Sh(),Cr(),await Ng(n,e,"Retrying documentation index install\u2026"),await ld(e),!0}catch(t){if(Li(t))throw t;let r=t instanceof Error?t.message:String(t);return await _g(`Bundled index install failed; falling back to local rebuild: ${r}`),!1}}async function ID(n,e,t){let r=Pt(),i=Zt();if(!i)throw new Error("docs.zip not found");await ve.promises.mkdir(q(),{recursive:!0}),await ve.promises.rm(r,{recursive:!0,force:!0}),t?.start("Building search index\u2026"),await Xt({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"}),await xg({docsZipPath:i,tmpDir:r,docsZipSha256:e,termsHash:na(),synonymsHash:ta(),builtBy:n.builtBy??"doc-init",onProgress:async o=>{t&&(t.text=o.message),await Xt({state:"indexing",current:o.current,total:o.total,message:o.message})}}),await Xt({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await PD(),Cr()}async function ld(n){await Xt({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function AD(n){let e=await Hl(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";n?.succeed(t),await Xt({state:"done",message:t,error:null})}async function DD(n,e){let t=n instanceof Error?n.message:String(n);throw await Xt({state:"error",error:t}),await _g(`ERROR: ${t}`),e?.fail(t),n}async function kD(){let n=q();await ve.promises.mkdir(n,{recursive:!0});let e=Js();return ve.existsSync(e)||await ve.promises.writeFile(e,"","utf-8"),e}async function RD(){let n=await kD();return bD.lock(n,{stale:1800*1e3})}async function TD(){let n=Zt(),e=(n?await ea(n):null)??await jl();if(!e)throw new Error("docs.zip not found");return e}async function xD(n,e){let t=await TD(),r=n.force||await $l(n.force),i=await ia(n.force);if(!r&&!i&&Mi()){await AD(e);return}!n.force&&wh(t)&&await CD(t,e)||(await ID(n,t,e),await ld(e))}var zi=class{static async run(e={}){let t=e.background??!1,i=e.quiet??t?void 0:Mg({text:"Checking documentation\u2026",color:"cyan"}),o;try{e.assumeStorageSafe||await vr({mode:"write"}),o=await RD(),await Fl(Ih("Starting documentation setup\u2026")),await xD(e,i)}catch(s){throw o&&await DD(s,i),s}finally{o&&await o()}}};async function LD(n){for(;;){let e=await ra();if(e.state==="done"&&Mi())return;if(e.state==="error")throw new cd("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 ED(500)}}async function Og(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await zi.run({builtBy:"doc-init",force:e,quiet:!0})}async function ND(){let n=await ia()!==null;if(Mi()&&!n)return;let e=Mg({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await Ah()){await LD(e),e.succeed("Documentation ready.");return}if(await $l()){await Og(e),e.succeed("Documentation ready.");return}await Og(e,!0),e.succeed("Documentation ready.")}catch(t){throw e.fail(t.message),t}}async function qi(){await vr({mode:"read"}),await ND(),await Lg()}function OD(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 dd=class{async search(e,t,r=20){await qi();try{return await id(e,t,r)}catch(i){if(!OD(i))throw i;return Cr(),await zi.run({builtBy:"doc-init",force:!0,quiet:!0,assumeStorageSafe:!0}),id(e,t,r)}}async readDocument(e){return await qi(),hh(e)}},ud=new dd;function Fg(...n){return e=>{if(!n.includes(e))throw new pd(`Allowed values: ${n.join(", ")}`);return e}}function FD(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new pd("Must be a positive integer.");return e}var jD=Fg("json","default"),HD=Fg("json","default");function fd(n){let e=n instanceof Error?n.message:String(n);return Li(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 ba=new MD("docs").description("Search and read HarmonyOS documentation from local docs directory");ba.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",UD,"all").option("--format <fmt>","Output format (default, json)",jD,"default").option("--limit <n>","Max number of results",FD,20).action(async(n,e)=>{try{let t=$D(n),r=e.catalog&&e.catalog!=="all"?e.catalog:void 0,i=await ud.search(t,r,e.limit);e.format==="json"?console.log(JSON.stringify(i,null,2)):BD(i)}catch(t){console.error(Sa(fd(t))),process.exit(1)}});ba.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{try{let e=n.trim();e||(console.error(Sa("Document ID cannot be empty.")),process.exit(1));let t=await ud.readDocument(e);console.log(t)}catch(e){console.error(Sa(fd(e))),process.exit(1)}});ba.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",HD,"default").action(async n=>{try{if(await qi(),n.format==="json"){let e=Jt.map(t=>({name:t,title:In[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of Jt)console.log(` ${e.padEnd(20)} ${_D(In[e])}`)}catch(e){console.error(Sa(fd(e))),process.exit(1)}});function $D(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>Ii)throw new Error(`Query exceeds ${Ii} characters.`);return e}function UD(n){if(n==="all")return"all";if(!Jt.includes(n))throw new pd(`Invalid catalog "${n}". Allowed: all, ${Jt.join(", ")}`);return n}function BD(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 jg=ba;import{Command as qk}from"commander";import{Command as ek,InvalidArgumentError as tk,Option as hd}from"commander";import{readFileSync as GD,unlinkSync as VD}from"fs";import{tmpdir as zD}from"os";import{join as qD}from"path";var Dt=class{constructor(e,t){this.hdcPath=e;this.serial=t}hdcPath;serial;async listWindows(e){let t=await this.fetchDump(),r=WD(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 De(this.hdcPath,e);if(t.exitCode!==0)throw new Error(`Failed to query windows: ${(t.stderr||t.stdout).trim()}`);return t.stdout}};function WD(n){let e=n.split(`
1356
+ `),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]),E=Number(c[4]);Number.isFinite(w)&&Number.isFinite(p)&&Number.isFinite(g)&&r.push({id:w,name:l,pid:g,displayId:p,type:E})}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 Hg(n){if(!(!n||n==="HitTestMode.Default"))return n.startsWith("HitTestMode.")?n.slice(12):n}function Yi(n){if(!(n==null||n==="")){if(typeof n=="boolean")return n;if(n==="true")return!0;if(n==="false")return!1}}function $g(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 Ug(n){return n.originalText||void 0}function Ar(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 Bg(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 YD(n){let e=GD(n,"utf-8").trim();if(!e)throw new Error("Empty dumpLayout response from device");return JSON.parse(e)}function JD(n){return n.attributes??{}}function Ea(n,e,t){let r=JD(n),i={id:r.id||void 0,type:r.type||void 0,text:Ug(r),bounds:$g(r.bounds),clickable:Yi(r.clickable)||void 0,longClickable:Yi(r.longClickable)||void 0,scrollable:Yi(r.scrollable)||void 0,checkable:Yi(r.checkable)||void 0,hitTestBehavior:Hg(r.hitTestBehavior),children:[]};return e>0&&t+1>=e||n.children&&(i.children=n.children.map(o=>Ea(o,e,t+1))),i}function KD(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 kn=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 De(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=qD(zD(),`deveco_cli_dump_${Date.now()}_${process.pid}.json`);try{return await this.recvDumpFile(e,t,r),YD(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 De(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}`),VD(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 De(this.hdcPath,i).catch(o=>{m(`Failed to clean remote dump file ${r}: ${o.message}`)})}async dumpRawNodes(e,t,r){let o=await new Dt(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=KD(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=>Bg(Ea(s,0,0),t))}};var Pa={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 md(n,e){n!==void 0&&he(n,e)}function Wg(n,e){if(n===void 0!=(e===void 0))throw new Error("x and y must be provided together")}function Ca(n,e){if(n!==void 0&&n.length===0)throw new Error(`${e} must not be empty`)}function Ji(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 Gg(n){if(n!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(n))throw new Error("--window must consist of letters, digits, - or _")}function Vg(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 Dr(n,e,t,r,i=!0){Wg(n,e),Ca(t,"--id"),md(n,"x"),md(e,"y"),Gg(r),Vg(n!==void 0,!!t,!!r,i)}async function kr(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 dt(n){let e=await I.new(),t=await kr(e,n);return{hdcPath:e.hdcPath,deviceId:t}}async function Rr(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 Dt(n,e).listWindows({all:!0}),c=new kn(n);return ZD(c,e,a,i,o)}async function ZD(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 QD(s,r)}return XD(n,e,t,r)}async function XD(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 Ar([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 zg(s[0].node,r)}function QD(n,e){let t=Ar(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 zg(t[0],e)}function zg(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 Ue(n,e,t){let r=["-t",e,"shell",t.join(" ")];m(`Executing: ${n} ${r.join(" ")}`);let i=await De(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 nk from"ora";function rk(n){let e=parseInt(n,10);if(!Number.isInteger(e)||e<0||String(e)!==n.trim())throw new tk("depth must be a non-negative integer");return e}function ik(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 qg(n,e=0){let t=[],r=" ".repeat(e);for(let i of n)t.push(`${r}${ik(i)}`),i.children.length>0&&t.push(...qg(i.children,e+1).split(`
1357
1357
  `));return t.join(`
1358
- `)}function UD(n){if(n.allWindows&&n.window)throw new Error("--all-windows and --window are mutually exclusive.")}function BD(n,e){let t=Ar(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 WD(n,e){console.log(e==="json"?JSON.stringify(n,null,2):xg(n))}async function GD(n){UD(n);let e=jD({text:"Dumping layout\u2026",color:"cyan"}).start(),t;try{let r=await I.new(),i=await Rr(r,n.device),o=new Tn(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){BD(t,n.id);return}WD(t,n.format)}var Lg=new _D("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 Xl("--depth <n>","Tree depth limit (0=unlimited, 1=root only, 2=root+children)").argParser(HD).default(0)).addOption(new Xl("--format <format>","Output format").choices(["default","json"]).default("default")).addOption(new Xl("--mode <mode>","Output mode: full | simplified").choices(["full","simplified"]).default("simplified")).action(async n=>{await GD(n)});import{Command as zD,Option as VD}from"commander";import{yellow as qD}from"colorette";import YD from"ora";var JD=["Id","Name","Pid","DisplayId","Focused"];function KD(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(yt(JD,t))}async function XD(n){let e=YD({text:"Listing windows\u2026",color:"cyan"}).start(),t;try{let r=await I.new(),i=await Rr(r,n.device);t=await new Rt(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(qD(" No windows found."));return}KD(t,n.format)}var Zl=new zD("window").description("Manage device windows");Zl.command("list").description("List windows on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new VD("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show all windows including system windows").action(async n=>{await XD(n)});import{Command as ZD}from"commander";import Le from"fs";import Be from"path";import{randomUUID as QD}from"crypto";import{execa as Ng}from"execa";import{green as eR,red as tR}from"colorette";function Ql(){return String(Date.now())}function nR(n){if(!n?.trim())return Be.resolve(`screenshot-${Ql()}.png`);let e=Be.resolve(n.trim());if(Le.existsSync(e)&&Le.statSync(e).isDirectory())return Be.join(e,`screenshot-${Ql()}.png`);if(Be.extname(e).toLowerCase()!==".png"){if(!Le.existsSync(e))throw new Error(`Screenshot directory does not exist: ${e}`);if(!Le.statSync(e).isDirectory())throw new Error(`Screenshot path is not a directory: ${e}`);return Be.join(e,`screenshot-${Ql()}.png`)}let t=Be.dirname(e);if(!Le.existsSync(t))throw new Error(`Screenshot directory does not exist: ${t}`);if(!Le.statSync(t).isDirectory())throw new Error(`Screenshot parent path is not a directory: ${t}`);return e}function Og(n){if(!Le.existsSync(n))throw new Error(`Screenshot file was not created: ${n}`);let e=Le.statSync(n);if(!e.isFile()||e.size===0)throw new Error(`Screenshot file is empty: ${n}`);let t=Le.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 td(n,e,t){m(`Executing: ${n} ${e.join(" ")}`);let{stdout:r}=await Ng(n,e,{env:{...process.env},cwd:t});return r}async function rR(n,e,t){m(`Executing: ${n} ${e.join(" ")}`);let{stdout:r,stderr:i}=await Ng(n,e,{env:{...process.env},cwd:t});return{stdout:r,stderr:i}}async function iR(n,e,t){try{return await td(n,e,t)}catch(r){return r.stdout??""}}async function oR(n,e){let t=Q.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 sR(t,r);throw new Error(`Multiple devices found. Specify a target device using \`--device <name|serial>\`.
1358
+ `)}function ok(n){if(n.allWindows&&n.window)throw new Error("--all-windows and --window are mutually exclusive.")}function sk(n,e){let t=Ar(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 ak(n,e){console.log(e==="json"?JSON.stringify(n,null,2):qg(n))}async function ck(n){ok(n);let e=nk({text:"Dumping layout\u2026",color:"cyan"}).start(),t;try{let r=await I.new(),i=await kr(r,n.device),o=new kn(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){sk(t,n.id);return}ak(t,n.format)}var Yg=new ek("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 hd("--depth <n>","Tree depth limit (0=unlimited, 1=root only, 2=root+children)").argParser(rk).default(0)).addOption(new hd("--format <format>","Output format").choices(["default","json"]).default("default")).addOption(new hd("--mode <mode>","Output mode: full | simplified").choices(["full","simplified"]).default("simplified")).action(async n=>{await ck(n)});import{Command as lk,Option as dk}from"commander";import{yellow as uk}from"colorette";import pk from"ora";var fk=["Id","Name","Pid","DisplayId","Focused"];function mk(n,e){if(e==="json"){let r=n.map(i=>({id:i.id,name:i.name,pid:i.pid,displayId:i.displayId,focused:i.focused}));console.log(JSON.stringify(r,null,2));return}let t=n.map(r=>({cells:[String(r.id),r.name,String(r.pid),String(r.displayId),String(r.focused)],highlight:r.focused}));console.log(ht(fk,t))}async function hk(n){let e=pk({text:"Listing windows\u2026",color:"cyan"}).start(),t;try{let r=await I.new(),i=await kr(r,n.device);t=await new Dt(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(uk(" No windows found."));return}mk(t,n.format)}var gd=new lk("window").description("Manage device windows");gd.command("list").description("List windows on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new dk("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show all windows including system windows").action(async n=>{await hk(n)});import{Command as gk}from"commander";import Te from"fs";import Be from"path";import{randomUUID as yk}from"crypto";import{execa as Jg}from"execa";import{green as wk,red as vk}from"colorette";function yd(){return String(Date.now())}function Sk(n){if(!n?.trim())return Be.resolve(`screenshot-${yd()}.png`);let e=Be.resolve(n.trim());if(Te.existsSync(e)&&Te.statSync(e).isDirectory())return Be.join(e,`screenshot-${yd()}.png`);if(Be.extname(e).toLowerCase()!==".png"){if(!Te.existsSync(e))throw new Error(`Screenshot directory does not exist: ${e}`);if(!Te.statSync(e).isDirectory())throw new Error(`Screenshot path is not a directory: ${e}`);return Be.join(e,`screenshot-${yd()}.png`)}let t=Be.dirname(e);if(!Te.existsSync(t))throw new Error(`Screenshot directory does not exist: ${t}`);if(!Te.statSync(t).isDirectory())throw new Error(`Screenshot parent path is not a directory: ${t}`);return e}function Kg(n){if(!Te.existsSync(n))throw new Error(`Screenshot file was not created: ${n}`);let e=Te.statSync(n);if(!e.isFile()||e.size===0)throw new Error(`Screenshot file is empty: ${n}`);let t=Te.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 vd(n,e,t){m(`Executing: ${n} ${e.join(" ")}`);let{stdout:r}=await Jg(n,e,{env:{...process.env},cwd:t});return r}async function bk(n,e,t){m(`Executing: ${n} ${e.join(" ")}`);let{stdout:r,stderr:i}=await Jg(n,e,{env:{...process.env},cwd:t});return{stdout:r,stderr:i}}async function Ek(n,e,t){try{return await vd(n,e,t)}catch(r){return r.stdout??""}}async function Pk(n,e){let t=Q.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 Ck(t,r);throw new Error(`Multiple devices found. Specify a target device using \`--device <name|serial>\`.
1359
1359
  Available devices:
1360
- ${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 sR(n,e){return(await Promise.all(e.map(async r=>` - ${await n.getDeviceName(r.serial)} (${r.serial})`))).join(`
1361
- `)}function aR(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 cR(n){let e=n.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}function lR(n,e){Le.copyFileSync(n,e),Og(e)}function dR(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 uR(n){let e=await iR(n.hdcPath,["-t",n.serial,"shell","ls","-l",n.remotePath]);return dR(e)}function pR(n){return[n.stdout,n.stderr].filter(Boolean).join(`
1362
- `).trim()}async function fR(n,e){let t;try{t=await rR(n.hdcPath,aR(n,e))}catch(i){t={stdout:i.stdout??"",stderr:i.stderr??i.message}}let r=await uR(n);return{created:r!==void 0&&r>0,output:pR(t)}}async function mR(n){let e=[];for(let t of[void 0,"png"]){let r=await fR(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(`
1363
- `)}`:`Screenshot was not created on device: ${n.remotePath}.`)}function Mg(n){try{return Og(n),!0}catch{return!1}}function _g(n){let e=[];for(let t of Le.readdirSync(n,{withFileTypes:!0})){let r=Be.join(n,t.name);if(t.isDirectory()){e.push(..._g(r));continue}t.isFile()&&Mg(r)&&e.push(r)}return e}function hR(n,e){let t=Be.join(n,Be.basename(e));if(Mg(t))return t;let r=_g(n);if(r.length===1)return r[0];if(r.length>1)throw new Error(`Multiple screenshot files were received in ${n}.`)}async function ed(n,e,t,r){try{await td(n.hdcPath,["-t",n.serial,"file","recv",n.remotePath,t],r)}catch(i){m(`hdc file recv failed: ${i.message}`)}return hR(e,n.remotePath)}async function gR(n){let e=Le.mkdtempSync(Be.join(Be.dirname(n.localPath),".devecocli-screenshot-"));try{let t=await ed(n,e,".",e)??await ed(n,e,e)??await ed(n,e,Be.join(e,"screenshot.png"));if(!t)throw new Error(`Screenshot file was not created in ${e}.`);lR(t,n.localPath)}finally{Le.rmSync(e,{recursive:!0,force:!0})}}async function yR(n){await td(n.hdcPath,["-t",n.serial,"shell","rm","-f",n.remotePath]).catch(()=>{})}async function wR(n){try{await mR(n),await gR(n)}finally{await yR(n)}}async function vR(n){try{let e=n.display!==void 0?cR(n.display):void 0,t=await I.new(),r=await oR(t,n.device),i=nR(n.path),o=`/data/local/tmp/devecocli-${QD()}.png`;await wR({hdcPath:t.hdcPath,serial:r,localPath:i,remotePath:o,display:e}),console.log(eR(`Screenshot saved to ${i}`))}catch(e){console.error(tR(`Failed to capture screenshot: ${e.message}`)),process.exit(1)}}var Fg=new ZD("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(vR);import{Command as en}from"commander";async function tn(n,e,t){let r=new Qe;r.start(n);try{await t(r)}catch(i){throw r.stop(),new Error(`${e}: ${i.message}`,{cause:i})}}async function SR(n,e,t){await tn("Executing click...","click failed",async r=>{Dr(n,e,t.id,t.window);let{hdcPath:i,deviceId:o}=await pt(t.device),{x:s,y:a}=await Tr(i,o,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await Ue(i,o,["uitest","uiInput","click",String(s),String(a)]),r.succeed(`click at (${s}, ${a})`)})}async function ER(n,e,t){await tn("Executing doubleclick...","doubleclick failed",async r=>{Dr(n,e,t.id,t.window);let{hdcPath:i,deviceId:o}=await pt(t.device),{x:s,y:a}=await Tr(i,o,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await Ue(i,o,["uitest","uiInput","doubleClick",String(s),String(a)]),r.succeed(`doubleclick at (${s}, ${a})`)})}async function bR(n,e,t){await tn("Executing longclick...","longclick failed",async r=>{Dr(n,e,t.id,t.window);let{hdcPath:i,deviceId:o}=await pt(t.device),{x:s,y:a}=await Tr(i,o,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await Ue(i,o,["uitest","uiInput","longClick",String(s),String(a)]),r.succeed(`longclick at (${s}, ${a})`)})}async function PR(n,e,t,r,i){await tn("Executing swipe...","swipe failed",async o=>{we(n,"x1"),we(e,"y1"),we(t,"x2"),we(r,"y2");let s=qi(i.speed),{hdcPath:a,deviceId:c}=await pt(i.device),l=["uitest","uiInput","swipe",n,e,t,r];s&&l.push(s),await Ue(a,c,l),o.succeed(`swipe from (${n}, ${e}) to (${t}, ${r})`)})}async function CR(n,e,t,r,i){await tn("Executing fling...","fling failed",async o=>{we(n,"x1"),we(e,"y1"),we(t,"x2"),we(r,"y2");let s=qi(i.speed),{hdcPath:a,deviceId:c}=await pt(i.device),l=["uitest","uiInput","fling",n,e,t,r];s&&l.push(s),await Ue(a,c,l),o.succeed(`fling from (${n}, ${e}) to (${t}, ${r})`)})}async function IR(n,e,t,r,i){await tn("Executing drag...","drag failed",async o=>{we(n,"x1"),we(e,"y1"),we(t,"x2"),we(r,"y2");let s=qi(i.speed),{hdcPath:a,deviceId:c}=await pt(i.device),l=["uitest","uiInput","drag",n,e,t,r];s&&l.push(s),await Ue(a,c,l),o.succeed(`drag from (${n}, ${e}) to (${t}, ${r})`)})}async function AR(n,e){await tn("Executing dircfling...","dircfling failed",async t=>{let r=ma[n];if(r===void 0)throw new Error(`Invalid direction "${n}". Valid values: ${Object.keys(ma).join(", ")}`);let{hdcPath:i,deviceId:o}=await pt(e.device);await Ue(i,o,["uitest","uiInput","dircFling",r]),t.succeed(`dircfling ${n}`)})}async function DR(n,e,t,r){await tn("Executing text input...","input failed",async i=>{Dr(e,t,r.id,r.window,!1),ha(n,"text");let{hdcPath:o,deviceId:s}=await pt(r.device);if(e!==void 0)await Ue(o,s,["uitest","uiInput","inputText",`${e}`,`${t}`,n]),i.succeed(`input ${n} at (${e}, ${t})`);else if(r.id){let{x:a,y:c}=await Tr(o,s,void 0,void 0,r.id,r.window);await Ue(o,s,["uitest","uiInput","inputText",`${a}`,`${c}`,n]),i.succeed(`input ${n} at (${a}, ${c})`)}else await Ue(o,s,["uitest","uiInput","text",n]),i.succeed(`input ${n}`)})}var jg=new en("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(SR),Hg=new en("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(ER),$g=new en("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(bR),Ug=new en("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(PR),Bg=new en("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(CR),Wg=new en("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(IR),Gg=new en("dircfling").argument("<direction>","Direction: up, down, left, right").description("Fling in a specified direction").option("--device <name|serial>","Target device (name or serial)").action(AR),zg=new en("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(DR);var We=new RR("ui").description("Inspect and interact with UI on a connected device");We.addCommand(Lg);We.addCommand(Zl);We.addCommand(Fg);We.addCommand(jg);We.addCommand(Hg);We.addCommand($g);We.addCommand(Ug);We.addCommand(Bg);We.addCommand(Wg);We.addCommand(Gg);We.addCommand(zg);var Vg=We;import{Command as pk}from"commander";import{execa as KR}from"execa";import Tt from"fs";import*as od from"os";import*as z from"path";var TR=new RegExp("\x1B\\[[0-?]*[ -/]*[@-~]","g"),kR=/\r/g,xR=/^(Working|Finished)\.\.\.\[[^\]]*\]\d+%$/,LR=/^<+\s*/,NR=/\s*>+$/,OR=[/^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 nd(n){if(!n)return"";let e=n.replace(TR,"").replace(kR,`
1360
+ ${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 Ck(n,e){return(await Promise.all(e.map(async r=>` - ${await n.getDeviceName(r.serial)} (${r.serial})`))).join(`
1361
+ `)}function Ik(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 Ak(n){let e=n.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}function Dk(n,e){Te.copyFileSync(n,e),Kg(e)}function kk(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 Rk(n){let e=await Ek(n.hdcPath,["-t",n.serial,"shell","ls","-l",n.remotePath]);return kk(e)}function Tk(n){return[n.stdout,n.stderr].filter(Boolean).join(`
1362
+ `).trim()}async function xk(n,e){let t;try{t=await bk(n.hdcPath,Ik(n,e))}catch(i){t={stdout:i.stdout??"",stderr:i.stderr??i.message}}let r=await Rk(n);return{created:r!==void 0&&r>0,output:Tk(t)}}async function Lk(n){let e=[];for(let t of[void 0,"png"]){let r=await xk(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(`
1363
+ `)}`:`Screenshot was not created on device: ${n.remotePath}.`)}function Zg(n){try{return Kg(n),!0}catch{return!1}}function Xg(n){let e=[];for(let t of Te.readdirSync(n,{withFileTypes:!0})){let r=Be.join(n,t.name);if(t.isDirectory()){e.push(...Xg(r));continue}t.isFile()&&Zg(r)&&e.push(r)}return e}function Nk(n,e){let t=Be.join(n,Be.basename(e));if(Zg(t))return t;let r=Xg(n);if(r.length===1)return r[0];if(r.length>1)throw new Error(`Multiple screenshot files were received in ${n}.`)}async function wd(n,e,t,r){try{await vd(n.hdcPath,["-t",n.serial,"file","recv",n.remotePath,t],r)}catch(i){m(`hdc file recv failed: ${i.message}`)}return Nk(e,n.remotePath)}async function Ok(n){let e=Te.mkdtempSync(Be.join(Be.dirname(n.localPath),".devecocli-screenshot-"));try{let t=await wd(n,e,".",e)??await wd(n,e,e)??await wd(n,e,Be.join(e,"screenshot.png"));if(!t)throw new Error(`Screenshot file was not created in ${e}.`);Dk(t,n.localPath)}finally{Te.rmSync(e,{recursive:!0,force:!0})}}async function Mk(n){await vd(n.hdcPath,["-t",n.serial,"shell","rm","-f",n.remotePath]).catch(()=>{})}async function _k(n){try{await Lk(n),await Ok(n)}finally{await Mk(n)}}async function Fk(n){try{let e=n.display!==void 0?Ak(n.display):void 0,t=await I.new(),r=await Pk(t,n.device),i=Sk(n.path),o=`/data/local/tmp/devecocli-${yk()}.png`;await _k({hdcPath:t.hdcPath,serial:r,localPath:i,remotePath:o,display:e}),console.log(wk(`Screenshot saved to ${i}`))}catch(e){console.error(vk(`Failed to capture screenshot: ${e.message}`)),process.exit(1)}}var Qg=new gk("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(Fk);import{Command as tn}from"commander";function jk(n){let t=`"$(printf '%s' '${Buffer.from(n,"utf8").toString("base64")}' | base64 -d)"`;return m(`escapeShellText: ${n} -> ${t}`),t}async function nn(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 Hk(n,e,t){await nn("Executing click...","click failed",async r=>{Dr(n,e,t.id,t.window);let{hdcPath:i,deviceId:o}=await dt(t.device),{x:s,y:a}=await Rr(i,o,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await Ue(i,o,["uitest","uiInput","click",String(s),String(a)]),r.succeed(`click at (${s}, ${a})`)})}async function $k(n,e,t){await nn("Executing doubleclick...","doubleclick failed",async r=>{Dr(n,e,t.id,t.window);let{hdcPath:i,deviceId:o}=await dt(t.device),{x:s,y:a}=await Rr(i,o,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await Ue(i,o,["uitest","uiInput","doubleClick",String(s),String(a)]),r.succeed(`doubleclick at (${s}, ${a})`)})}async function Uk(n,e,t){await nn("Executing longclick...","longclick failed",async r=>{Dr(n,e,t.id,t.window);let{hdcPath:i,deviceId:o}=await dt(t.device),{x:s,y:a}=await Rr(i,o,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await Ue(i,o,["uitest","uiInput","longClick",String(s),String(a)]),r.succeed(`longclick at (${s}, ${a})`)})}async function Bk(n,e,t,r,i){await nn("Executing swipe...","swipe failed",async o=>{he(n,"x1"),he(e,"y1"),he(t,"x2"),he(r,"y2");let s=Ji(i.speed),{hdcPath:a,deviceId:c}=await dt(i.device),l=["uitest","uiInput","swipe",n,e,t,r];s&&l.push(s),await Ue(a,c,l),o.succeed(`swipe from (${n}, ${e}) to (${t}, ${r})`)})}async function Wk(n,e,t,r,i){await nn("Executing fling...","fling failed",async o=>{he(n,"x1"),he(e,"y1"),he(t,"x2"),he(r,"y2");let s=Ji(i.speed),{hdcPath:a,deviceId:c}=await dt(i.device),l=["uitest","uiInput","fling",n,e,t,r];s&&l.push(s),await Ue(a,c,l),o.succeed(`fling from (${n}, ${e}) to (${t}, ${r})`)})}async function Gk(n,e,t,r,i){await nn("Executing drag...","drag failed",async o=>{he(n,"x1"),he(e,"y1"),he(t,"x2"),he(r,"y2");let s=Ji(i.speed),{hdcPath:a,deviceId:c}=await dt(i.device),l=["uitest","uiInput","drag",n,e,t,r];s&&l.push(s),await Ue(a,c,l),o.succeed(`drag from (${n}, ${e}) to (${t}, ${r})`)})}async function Vk(n,e){await nn("Executing dircfling...","dircfling failed",async t=>{let r=Pa[n];if(r===void 0)throw new Error(`Invalid direction "${n}". Valid values: ${Object.keys(Pa).join(", ")}`);let{hdcPath:i,deviceId:o}=await dt(e.device);await Ue(i,o,["uitest","uiInput","dircFling",r]),t.succeed(`dircfling ${n}`)})}async function zk(n,e,t,r){await nn("Executing text input...","input failed",async i=>{Dr(e,t,r.id,r.window,!1),Ca(n,"text");let{hdcPath:o,deviceId:s}=await dt(r.device),a=jk(n);if(e!==void 0)await Ue(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 Rr(o,s,void 0,void 0,r.id,r.window);await Ue(o,s,["uitest","uiInput","inputText",`${c}`,`${l}`,a]),i.succeed(`input ${n} at (${c}, ${l})`)}else await Ue(o,s,["uitest","uiInput","text",a]),i.succeed(`input ${n}`)})}var ey=new tn("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(Hk),ty=new tn("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($k),ny=new tn("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(Uk),ry=new tn("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(Bk),iy=new tn("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(Wk),oy=new tn("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(Gk),sy=new tn("dircfling").argument("<direction>","Direction: up, down, left, right").description("Fling in a specified direction").option("--device <name|serial>","Target device (name or serial)").action(Vk),ay=new tn("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(zk);var We=new qk("ui").description("Inspect and interact with UI on a connected device");We.addCommand(Yg);We.addCommand(gd);We.addCommand(Qg);We.addCommand(ey);We.addCommand(ty);We.addCommand(ny);We.addCommand(ry);We.addCommand(iy);We.addCommand(oy);We.addCommand(sy);We.addCommand(ay);var cy=We;import{Command as xT}from"commander";import{execa as hR}from"execa";import kt from"fs";import*as Pd from"os";import*as V from"path";var Yk=new RegExp("\x1B\\[[0-?]*[ -/]*[@-~]","g"),Jk=/\r/g,Kk=/^(Working|Finished)\.\.\.\[[^\]]*\]\d+%$/,Zk=/^<+\s*/,Xk=/\s*>+$/,Qk=[/^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 Sd(n){if(!n)return"";let e=n.replace(Yk,"").replace(Jk,`
1364
1364
  `).split(`
1365
- `).map(t=>t.trimEnd()).filter(t=>_R(t));return e.length>0?`${e.join(`
1365
+ `).map(t=>t.trimEnd()).filter(t=>tR(t));return e.length>0?`${e.join(`
1366
1366
  `)}
1367
- `:""}function Kg(n){let e=nd(n).trim();if(!e)return{jsonText:void 0,diagnostics:""};if(Xg(e))return{jsonText:e,diagnostics:""};let t=FR(e);if(!t)return{jsonText:void 0,diagnostics:`${e}
1367
+ `:""}function py(n){let e=Sd(n).trim();if(!e)return{jsonText:void 0,diagnostics:""};if(fy(e))return{jsonText:e,diagnostics:""};let t=nR(e);if(!t)return{jsonText:void 0,diagnostics:`${e}
1368
1368
  `};let r=[e.slice(0,t.start).trim(),e.slice(t.end).trim()].filter(Boolean).join(`
1369
1369
  `);return{jsonText:e.slice(t.start,t.end),diagnostics:r?`${r}
1370
- `:""}}function MR(n){return xR.test(n.trim())}function _R(n){let e=n.trim();return!!e&&!MR(e)&&!OR.some(t=>t.test(e))}function Xg(n){try{return JSON.parse(n),!0}catch{return!1}}function FR(n){for(let e=0;e<n.length;e++){if(n[e]!=="["&&n[e]!=="{")continue;let t=jR(n,e);if(t)return t}}function jR(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(Xg(i))return{start:e,end:t}}}var qg=["Error","Warning","Suggestion","Info","Off","Unknown"];function Zg(n){let e=rd(n);return{issues:BR(e),summary:HR(n,e)}}function HR(n,e){let t=GR(e);return{filesChecked:zR(n).size,issues:e.length,errors:t.get("Error")??0,warnings:t.get("Warning")??0,suggestions:t.get("Suggestion")??0}}function rd(n,e=""){if(Array.isArray(n))return n.flatMap(o=>rd(o,e));if(!Qg(n))return[];let t=Yi(n,["filePath","file","path"])??e,r=$R(n,t);if(r.length>0)return r;let i=UR(n,t);return i?[i]:[]}function $R(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=>rd(s,e));if(o.length>0)return o}}return[]}function UR(n,e){let t=Yi(n,["message","description","desc","detail"])??"",r=JR(Yi(n,["rule","ruleId","ruleName"])),i=qR(n,["severity","level"]),o=Yi(n,["filePath","file","path"])??e;if(!(!t&&!r&&i==="Unknown"))return{file:o,line:Jg(n,["line","reportLine"]),column:Jg(n,["column","reportColumn"]),severity:i,rule:r,message:t}}function BR(n){return[...n].sort((e,t)=>{let r=Yg(e.severity)-Yg(t.severity);return r===0?WR(e,t):r})}function WR(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 GR(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 zR(n){let e=new Set;return id(e,n,""),e}function id(n,e,t){if(Array.isArray(e)){for(let i of e)id(n,i,t);return}if(!Qg(e))return;let r=Yi(e,["filePath","file","path"])??t;r&&n.add(r),VR(n,e,r)}function VR(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)id(n,s,t)}}function qR(n,e){for(let t of e){let r=n[t];if(typeof r=="string"||typeof r=="number")return YR(r)}return"Unknown"}function YR(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 JR(n){let e=n?.normalize("NFKC").trim();if(e)return e.replace(LR,"").replace(NR,"").toLowerCase()}function Yg(n){let e=qg.indexOf(n);return e===-1?qg.length:e}function Yi(n,e){for(let t of e){let r=n[t];if(typeof r=="string")return r}}function Jg(n,e){for(let t of e){let r=n[t];if(typeof r=="number")return r}}function Qg(n){return typeof n=="object"&&n!==null}var ey="deveco-codelinter-",Ji=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=Tt.mkdtempSync(z.join(od.tmpdir(),ey)),r=z.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=Kg(c.stdout),d=l.diagnostics+nd(c.stderr);try{let h=this.readJsonReport(r,l.jsonText);return{exitCode:c.exitCode,diagnostics:d,report:Zg(h)}}catch(h){return{exitCode:c.exitCode,diagnostics:d,reportError:h}}}finally{this.removeTempDir(t)}}resolveLintTarget(e,t){let r=e?z.resolve(this.cwd,e):t,i=this.resolveRealPath(r,"Lint path"),o=Tt.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?z.resolve(this.cwd,e):z.join(t.projectRoot??this.cwd,"code-linter.json5"),i=this.resolveRealPath(r,"`--config-path`");if(!Tt.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||z.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:z.dirname(e);try{return Tt.realpathSync(U.discover(r).rootDir)}catch{return}}resolveRealPath(e,t){try{return Tt.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 KR(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??[])Tt.mkdirSync(e,{recursive:!0})}readJsonReport(e,t){let i=(Tt.existsSync(e)?Tt.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=z.resolve(e),r=z.resolve(od.tmpdir());!(t.startsWith(`${r}${z.sep}`)||t===r)||!z.basename(t).startsWith(ey)||Tt.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(z.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=[z.dirname(e.nodePath)];return t==="ide"&&e.javaPath&&r.unshift(z.dirname(e.javaPath)),r}static getResultDirectory(e){return z.resolve(e,"..","linter","result")}static getSource(e){return e.sourceType==="studio"?"ide":"command-line-tools"}};import{red as ya,yellow as aT}from"colorette";import{Argument as cT,Command as lT,InvalidArgumentError as rn}from"commander";import Xi from"fs";import*as Ce from"path";import*as Ki from"path";var ty="n/a",ny=/\\/g,XR=/\|/g,ZR=/\r?\n/g;function ry(n,e){if(n.issues.length===0)return`No defects found.
1371
- ${sd(n.summary)}
1372
- `;let t=e===void 0?n.issues:n.issues.slice(0,e),r=[eT(t),sd(n.summary)];return e!==void 0&&t.length<n.issues.length&&r.push(QR(n.issues.length,t.length)),`${r.join(`
1370
+ `:""}}function eR(n){return Kk.test(n.trim())}function tR(n){let e=n.trim();return!!e&&!eR(e)&&!Qk.some(t=>t.test(e))}function fy(n){try{return JSON.parse(n),!0}catch{return!1}}function nR(n){for(let e=0;e<n.length;e++){if(n[e]!=="["&&n[e]!=="{")continue;let t=rR(n,e);if(t)return t}}function rR(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(fy(i))return{start:e,end:t}}}var ly=["Error","Warning","Suggestion","Info","Off","Unknown"];function my(n){let e=bd(n);return{issues:aR(e),summary:iR(n,e)}}function iR(n,e){let t=lR(e);return{filesChecked:dR(n).size,issues:e.length,errors:t.get("Error")??0,warnings:t.get("Warning")??0,suggestions:t.get("Suggestion")??0}}function bd(n,e=""){if(Array.isArray(n))return n.flatMap(o=>bd(o,e));if(!hy(n))return[];let t=Ki(n,["filePath","file","path"])??e,r=oR(n,t);if(r.length>0)return r;let i=sR(n,t);return i?[i]:[]}function oR(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=>bd(s,e));if(o.length>0)return o}}return[]}function sR(n,e){let t=Ki(n,["message","description","desc","detail"])??"",r=mR(Ki(n,["rule","ruleId","ruleName"])),i=pR(n,["severity","level"]),o=Ki(n,["filePath","file","path"])??e;if(!(!t&&!r&&i==="Unknown"))return{file:o,line:uy(n,["line","reportLine"]),column:uy(n,["column","reportColumn"]),severity:i,rule:r,message:t}}function aR(n){return[...n].sort((e,t)=>{let r=dy(e.severity)-dy(t.severity);return r===0?cR(e,t):r})}function cR(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 lR(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 dR(n){let e=new Set;return Ed(e,n,""),e}function Ed(n,e,t){if(Array.isArray(e)){for(let i of e)Ed(n,i,t);return}if(!hy(e))return;let r=Ki(e,["filePath","file","path"])??t;r&&n.add(r),uR(n,e,r)}function uR(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)Ed(n,s,t)}}function pR(n,e){for(let t of e){let r=n[t];if(typeof r=="string"||typeof r=="number")return fR(r)}return"Unknown"}function fR(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 mR(n){let e=n?.normalize("NFKC").trim();if(e)return e.replace(Zk,"").replace(Xk,"").toLowerCase()}function dy(n){let e=ly.indexOf(n);return e===-1?ly.length:e}function Ki(n,e){for(let t of e){let r=n[t];if(typeof r=="string")return r}}function uy(n,e){for(let t of e){let r=n[t];if(typeof r=="number")return r}}function hy(n){return typeof n=="object"&&n!==null}var gy="deveco-codelinter-",Zi=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=kt.mkdtempSync(V.join(Pd.tmpdir(),gy)),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=py(c.stdout),p=l.diagnostics+Sd(c.stderr);try{let g=this.readJsonReport(r,l.jsonText);return{exitCode:c.exitCode,diagnostics:p,report:my(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=kt.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(!kt.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 kt.realpathSync(U.discover(r).rootDir)}catch{return}}resolveRealPath(e,t){try{return kt.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 hR(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??[])kt.mkdirSync(e,{recursive:!0})}readJsonReport(e,t){let i=(kt.existsSync(e)?kt.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(Pd.tmpdir());!(t.startsWith(`${r}${V.sep}`)||t===r)||!V.basename(t).startsWith(gy)||kt.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 Aa,yellow as AR}from"colorette";import{Argument as DR,Command as kR,InvalidArgumentError as on}from"commander";import Qi from"fs";import*as Se from"path";import*as Xi from"path";var yy="n/a",wy=/\\/g,gR=/\|/g,yR=/\r?\n/g;function vy(n,e){if(n.issues.length===0)return`No defects found.
1371
+ ${Cd(n.summary)}
1372
+ `;let t=e===void 0?n.issues:n.issues.slice(0,e),r=[vR(t),Cd(n.summary)];return e!==void 0&&t.length<n.issues.length&&r.push(wR(n.issues.length,t.length)),`${r.join(`
1373
1373
  `)}
1374
- `}function iy(n,e){return[sd(n.summary),`Full report: ${ad(e)}`,""].join(`
1375
- `)}function oy(n){let e=["# CodeLinter report",""];return n.issues.length===0?e.push("No defects found.",""):e.push(...tT(n.issues),""),e.push("## Summary","",...rT(n.summary),""),e.join(`
1376
- `)}function sy(n){return`${JSON.stringify(n,null,2)}
1377
- `}function sd(n){return`Summary: Issues: ${Ge(n.issues)} | Errors: ${Ge(n.errors)} | Warnings: ${Ge(n.warnings)} | Suggestions: ${Ge(n.suggestions)} | Files checked: ${Ge(n.filesChecked)}`}function QR(n,e){return`Showing ${Ge(e)} of ${Ge(n)} issues. Use --output-path <path> to write all results.`}function eT(n){let e=["No","File","Line","Column","Severity","Rule","Message"],t=n.map((r,i)=>({cells:oT(r,i+1)}));return["CodeLinter report","",yt(e,t)].join(`
1378
- `)}function tT(n){let e=["| No | File | Line | Column | Severity | Rule | Message |","| ---: | --- | ---: | ---: | --- | --- | --- |"];for(let[t,r]of n.entries())e.push(nT(r,t+1));return e}function nT(n,e){return`| ${[String(e),ad(nn(n.file)),ga(n.line),ga(n.column),nn(n.severity),nn(n.rule),nn(n.message)].map(iT).join(" | ")} |`}function rT(n){return[`- Issues: ${Ge(n.issues)}`,`- Errors: ${Ge(n.errors)}`,`- Warnings: ${Ge(n.warnings)}`,`- Suggestions: ${Ge(n.suggestions)}`,`- Files checked: ${Ge(n.filesChecked)}`]}function iT(n){return n.replace(ny,"\\\\").replace(XR,"\\|").replace(ZR,"<br>")}function oT(n,e){return[String(e),ad(nn(sT(n.file))),ga(n.line),ga(n.column),nn(n.severity),nn(n.rule),nn(n.message)]}function sT(n){if(!Ki.isAbsolute(n))return n;let e=Ki.relative(process.cwd(),n);return!e||e.startsWith("..")||Ki.isAbsolute(e)?n:e}function ad(n){return n.replace(ny,"/")}function nn(n){let e=n?.trim();return e||ty}function ga(n){return n===void 0?ty:String(n)}function Ge(n){return n.toLocaleString("en-US")}var dT=/^\d+$/;function cd(){return new lT("lint").description("Run DevEco Code Linter checks for TS/ArkTS code").helpOption("--help","display help for command").addArgument(new cT("[path]","File or directory to lint").argParser(hT)).option("--fix","Auto-fix fixable code issues").option("--incremental","Only check uncommitted files").option("--config-path <path>","Path to lint configuration file",pT).option("--product <product>","Product name defined in build-profile.json5",fT,"default").option("--format <format>","Report format (choices: default, json)",uT,"default").option("--output-path <path>","Complete report file or directory",mT).option("--limit <number>","Maximum terminal issues to display when --output-path is omitted",gT).action(async(n,e)=>{await yT(n,e)})}function uT(n){if(n==="default"||n==="json")return n;throw new rn("Invalid --format. Expected one of: default, json.")}function pT(n){ld(n,"--config-path");let e=Ce.extname(n).toLowerCase();if(e!==".json"&&e!==".json5")throw new rn("`--config-path` must point to a .json or .json5 file.");return n}function fT(n){return ay(n,"product"),n}function mT(n){return ld(n,"--output-path"),n}function hT(n){return ld(n,"path"),n}function gT(n){if(ay(n,"limit"),!dT.test(n))throw new rn("`--limit` must be a positive integer.");let e=Number.parseInt(n,10);if(e<=0||!Number.isSafeInteger(e))throw new rn("`--limit` must be an integer greater than 0.");return e}function ay(n,e){if(n.trim().length===0||dy(n))throw new rn(`Invalid --${e} value.`)}function ld(n,e){let t=`\`${e}\``;if(n.length===0||dy(n))throw new rn(`${t} must be a non-empty path without control characters.`)}async function yT(n,e){let t=process.cwd(),r=bT(e.outputPath,e.format,t);e.fix&&console.warn(aT("Running codelinter with --fix. Ensure your project source is trusted."));let i=await wT(n,e,t);DT(i.diagnostics),process.exitCode=ST(i,r,e.format,e.limit,t)}async function wT(n,e,t){let r=await I.new(),i=new Ji(r,t);return vT(i,{lintPath:n,configPath:e.configPath,product:e.product,fix:e.fix,incremental:e.incremental})}async function vT(n,e){let t=new Qe;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 ST(n,e,t,r,i){if(!n.report)return console.error(ya("Failed to generate Code Linter report.")),console.error(ya(n.reportError?.message??"Native JSON report was not generated.")),n.exitCode===0?1:n.exitCode;try{if(e){ET(e,t,n.report);let o=ly(e,i);process.stdout.write(iy(n.report,o))}else process.stdout.write(ry(n.report,r));return n.exitCode}catch(o){return console.error(ya("Failed to generate Code Linter report.")),console.error(ya(o.message)),n.exitCode===0?1:n.exitCode}}function ET(n,e,t){Xi.mkdirSync(Ce.dirname(n),{recursive:!0});let r=e==="json"?sy(t):oy(t);try{Xi.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 bT(n,e,t){if(!n)return;let r=IT(n,t),i=CT(n,r),o=i?Ce.join(r,AT(e)):r;if(i||PT(n,e),Xi.existsSync(o))throw new rn(`Output file already exists: ${ly(o,t)}`);return o}function PT(n,e){let t=cy(e);if(Ce.extname(n).toLowerCase()!==t)throw new rn(`--output-path must use the ${t} extension for --format ${e}.`)}function CT(n,e){return Xi.existsSync(e)?Xi.statSync(e).isDirectory():n.endsWith("/")||n.endsWith("\\")||Ce.extname(n)===""}function IT(n,e){return Ce.resolve(e,n)}function AT(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}${cy(n)}`}function cy(n){return n==="json"?".json":".md"}function ly(n,e){let t=Ce.relative(e,n);return t&&!t.startsWith("..")&&!Ce.isAbsolute(t)?t:n}function DT(n){n&&process.stderr.write(n)}function dy(n){for(let e of n){let t=e.charCodeAt(0);if(t<=31||t===127)return!0}return!1}import{Command as RT,InvalidArgumentError as my}from"commander";import*as $ from"path";import*as dd from"os";import{readdirSync as TT,existsSync as wa,readFileSync as kT,unlinkSync as xT,copyFileSync as hy,writeFileSync as gy}from"fs";import{execa as LT}from"execa";import{cyan as ce,yellow as yy}from"colorette";import NT from"ora";var uy=["default","csv","json"];function wy(n){if(uy.includes(n))return n;throw new my(`--format must be one of: ${uy.join(", ")} (got "${n}")`)}function OT(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new my(`--limit must be a positive integer (got "${n}")`);return e}function MT(n){return[...n].sort((e,t)=>{let r=py(e),i=py(t);return r.apiVersion-i.apiVersion||r.suffix.localeCompare(i.suffix)})}function py(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 vy(n){let t=TT(n,{withFileTypes:!0}).filter(r=>r.isFile()&&r.name.toLowerCase().endsWith(".json")).map(r=>r.name.slice(0,-5));return MT(t)}function _T(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=wy(i);return o==="default"?"csv":o}}return n}async function FT(n){let e=await I.new(),{apiChangeDir:t}=e.getApiscanPaths();m(ce(`[compat:versions] apiChangeDir: "${t}"`));let r=vy(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(`
1379
- `))}}var fy=new Set([".ets",".c",".cpp"]);function jT(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 HT(n){for(let e of n){let t=$.resolve(e);if(!wa(t))throw new Error(`File "${e}" does not exist.`);let r=$.extname(t).toLowerCase();if(!fy.has(r)){let i=Array.from(fy).join(", ");throw new Error(`Unsupported file extension "${r}" for "${e}". Supported: ${i}.`)}}}function $T(n){let e=[],t=[];for(let r of n)$.extname(r).toLowerCase()===".ets"?e.push(r):t.push(r);return{arkTs:e,cpp:t}}function UT(n){let e=[],t=[],r="",i=!1,o=0;for(;o<n.length;){let s=n[o];i?{field:r,inQuotes:i,i:o}=BT(n,o,s,r,i):s==='"'?(i=!0,o+=1):s===","?(t.push(r),r="",o+=1):s===`
1380
- `?(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 BT(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 WT(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 GT(n){let e=kT(n,"utf8"),t=e.startsWith("\uFEFF")?e.slice(1):e,r=UT(t);if(r.length<2)return[];let[i,...o]=r;return WT(i,o)}function zT(n,e){let t=n.match(/CSV saved to:\s*([^\r\n]+\.csv)/);if(!t)return null;let r=t[1].trim();return $.isAbsolute(r)?r:$.join(e,r)}function VT(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(ce("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 qT(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(ce(`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(yy(` ... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function YT(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(yy(`... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function JT(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($.resolve(n.rootDir,i.srcPath))}return t}function KT(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}=$T(e),a=d=>$.resolve(process.cwd(),d),c=o.map(a),l=s.map(a);c.length>0&&i.push("--arkTsFiles",c.join(",")),l.length>0&&i.push("--cppFiles",l.join(","))}else if(r.modules&&r.modules.length>0){let o=JT(t,r.modules);i.push("--modulePaths",o.join(","))}else i.push("--projectPath",t.rootDir);return i.push("--outputPath",dd.tmpdir()),i}async function XT(n,e){let t=$.dirname(e[0]);try{let i=(await LT(n.nodePath,e,{cwd:t,stdin:"ignore",stdout:"pipe",stderr:"inherit"})).stdout;return process.env.DEVECO_CLI_DEBUG&&(console.log(ce("[compat:check] === scan stdout ===")),process.stdout.write(i),i.endsWith(`
1374
+ `}function Sy(n,e){return[Cd(n.summary),`Full report: ${Id(e)}`,""].join(`
1375
+ `)}function by(n){let e=["# CodeLinter report",""];return n.issues.length===0?e.push("No defects found.",""):e.push(...SR(n.issues),""),e.push("## Summary","",...ER(n.summary),""),e.join(`
1376
+ `)}function Ey(n){return`${JSON.stringify(n,null,2)}
1377
+ `}function Cd(n){return`Summary: Issues: ${Ge(n.issues)} | Errors: ${Ge(n.errors)} | Warnings: ${Ge(n.warnings)} | Suggestions: ${Ge(n.suggestions)} | Files checked: ${Ge(n.filesChecked)}`}function wR(n,e){return`Showing ${Ge(e)} of ${Ge(n)} issues. Use --output-path <path> to write all results.`}function vR(n){let e=["No","File","Line","Column","Severity","Rule","Message"],t=n.map((r,i)=>({cells:CR(r,i+1)}));return["CodeLinter report","",ht(e,t)].join(`
1378
+ `)}function SR(n){let e=["| No | File | Line | Column | Severity | Rule | Message |","| ---: | --- | ---: | ---: | --- | --- | --- |"];for(let[t,r]of n.entries())e.push(bR(r,t+1));return e}function bR(n,e){return`| ${[String(e),Id(rn(n.file)),Ia(n.line),Ia(n.column),rn(n.severity),rn(n.rule),rn(n.message)].map(PR).join(" | ")} |`}function ER(n){return[`- Issues: ${Ge(n.issues)}`,`- Errors: ${Ge(n.errors)}`,`- Warnings: ${Ge(n.warnings)}`,`- Suggestions: ${Ge(n.suggestions)}`,`- Files checked: ${Ge(n.filesChecked)}`]}function PR(n){return n.replace(wy,"\\\\").replace(gR,"\\|").replace(yR,"<br>")}function CR(n,e){return[String(e),Id(rn(IR(n.file))),Ia(n.line),Ia(n.column),rn(n.severity),rn(n.rule),rn(n.message)]}function IR(n){if(!Xi.isAbsolute(n))return n;let e=Xi.relative(process.cwd(),n);return!e||e.startsWith("..")||Xi.isAbsolute(e)?n:e}function Id(n){return n.replace(wy,"/")}function rn(n){let e=n?.trim();return e||yy}function Ia(n){return n===void 0?yy:String(n)}function Ge(n){return n.toLocaleString("en-US")}var RR=/^\d+$/;function Ad(){return new kR("lint").description("Run DevEco Code Linter checks for TS/ArkTS code").helpOption("--help","display help for command").addArgument(new DR("[path]","File or directory to lint").argParser(OR)).option("--fix","Auto-fix fixable code issues").option("--incremental","Only check uncommitted files").option("--config-path <path>","Path to lint configuration file",xR).option("--product <product>","Product name defined in build-profile.json5",LR,"default").option("--format <format>","Report format (choices: default, json)",TR,"default").option("--output-path <path>","Complete report file or directory",NR).option("--limit <number>","Maximum terminal issues to display when --output-path is omitted",MR).action(async(n,e)=>{await _R(n,e)})}function TR(n){if(n==="default"||n==="json")return n;throw new on("Invalid --format. Expected one of: default, json.")}function xR(n){Dd(n,"--config-path");let e=Se.extname(n).toLowerCase();if(e!==".json"&&e!==".json5")throw new on("`--config-path` must point to a .json or .json5 file.");return n}function LR(n){return Py(n,"product"),n}function NR(n){return Dd(n,"--output-path"),n}function OR(n){return Dd(n,"path"),n}function MR(n){if(Py(n,"limit"),!RR.test(n))throw new on("`--limit` must be a positive integer.");let e=Number.parseInt(n,10);if(e<=0||!Number.isSafeInteger(e))throw new on("`--limit` must be an integer greater than 0.");return e}function Py(n,e){if(n.trim().length===0||Ay(n))throw new on(`Invalid --${e} value.`)}function Dd(n,e){let t=`\`${e}\``;if(n.length===0||Ay(n))throw new on(`${t} must be a non-empty path without control characters.`)}async function _R(n,e){let t=process.cwd(),r=UR(e.outputPath,e.format,t);e.fix&&console.warn(AR("Running codelinter with --fix. Ensure your project source is trusted."));let i=await FR(n,e,t);zR(i.diagnostics),process.exitCode=HR(i,r,e.format,e.limit,t)}async function FR(n,e,t){let r=await I.new(),i=new Zi(r,t);return jR(i,{lintPath:n,configPath:e.configPath,product:e.product,fix:e.fix,incremental:e.incremental})}async function jR(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 HR(n,e,t,r,i){if(!n.report)return console.error(Aa("Failed to generate Code Linter report.")),console.error(Aa(n.reportError?.message??"Native JSON report was not generated.")),n.exitCode===0?1:n.exitCode;try{if(e){$R(e,t,n.report);let o=Iy(e,i);process.stdout.write(Sy(n.report,o))}else process.stdout.write(vy(n.report,r));return n.exitCode}catch(o){return console.error(Aa("Failed to generate Code Linter report.")),console.error(Aa(o.message)),n.exitCode===0?1:n.exitCode}}function $R(n,e,t){Qi.mkdirSync(Se.dirname(n),{recursive:!0});let r=e==="json"?Ey(t):by(t);try{Qi.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 UR(n,e,t){if(!n)return;let r=GR(n,t),i=WR(n,r),o=i?Se.join(r,VR(e)):r;if(i||BR(n,e),Qi.existsSync(o))throw new on(`Output file already exists: ${Iy(o,t)}`);return o}function BR(n,e){let t=Cy(e);if(Se.extname(n).toLowerCase()!==t)throw new on(`--output-path must use the ${t} extension for --format ${e}.`)}function WR(n,e){return Qi.existsSync(e)?Qi.statSync(e).isDirectory():n.endsWith("/")||n.endsWith("\\")||Se.extname(n)===""}function GR(n,e){return Se.resolve(e,n)}function VR(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}${Cy(n)}`}function Cy(n){return n==="json"?".json":".md"}function Iy(n,e){let t=Se.relative(e,n);return t&&!t.startsWith("..")&&!Se.isAbsolute(t)?t:n}function zR(n){n&&process.stderr.write(n)}function Ay(n){for(let e of n){let t=e.charCodeAt(0);if(t<=31||t===127)return!0}return!1}import{Command as qR,InvalidArgumentError as Ty}from"commander";import*as $ from"path";import*as kd from"os";import{readdirSync as YR,existsSync as Da,readFileSync as JR,unlinkSync as KR,copyFileSync as xy,writeFileSync as Ly}from"fs";import{execa as ZR}from"execa";import{cyan as ae,yellow as Ny}from"colorette";import XR from"ora";var Dy=["default","csv","json"];function Oy(n){if(Dy.includes(n))return n;throw new Ty(`--format must be one of: ${Dy.join(", ")} (got "${n}")`)}function QR(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new Ty(`--limit must be a positive integer (got "${n}")`);return e}function eT(n){return[...n].sort((e,t)=>{let r=ky(e),i=ky(t);return r.apiVersion-i.apiVersion||r.suffix.localeCompare(i.suffix)})}function ky(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 My(n){let t=YR(n,{withFileTypes:!0}).filter(r=>r.isFile()&&r.name.toLowerCase().endsWith(".json")).map(r=>r.name.slice(0,-5));return eT(t)}function tT(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=Oy(i);return o==="default"?"csv":o}}return n}async function nT(n){let e=await I.new(),{apiChangeDir:t}=e.getApiscanPaths();m(ae(`[compat:versions] apiChangeDir: "${t}"`));let r=My(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(`
1379
+ `))}}var Ry=new Set([".ets",".c",".cpp"]);function rT(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 iT(n){for(let e of n){let t=$.resolve(e);if(!Da(t))throw new Error(`File "${e}" does not exist.`);let r=$.extname(t).toLowerCase();if(!Ry.has(r)){let i=Array.from(Ry).join(", ");throw new Error(`Unsupported file extension "${r}" for "${e}". Supported: ${i}.`)}}}function oT(n){let e=[],t=[];for(let r of n)$.extname(r).toLowerCase()===".ets"?e.push(r):t.push(r);return{arkTs:e,cpp:t}}function sT(n){let e=[],t=[],r="",i=!1,o=0;for(;o<n.length;){let s=n[o];i?{field:r,inQuotes:i,i:o}=aT(n,o,s,r,i):s==='"'?(i=!0,o+=1):s===","?(t.push(r),r="",o+=1):s===`
1380
+ `?(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 aT(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 cT(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 lT(n){let e=JR(n,"utf8"),t=e.startsWith("\uFEFF")?e.slice(1):e,r=sT(t);if(r.length<2)return[];let[i,...o]=r;return cT(i,o)}function dT(n,e){let t=n.match(/CSV saved to:\s*([^\r\n]+\.csv)/);if(!t)return null;let r=t[1].trim();return $.isAbsolute(r)?r:$.join(e,r)}function uT(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 pT(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(Ny(` ... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function fT(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(Ny(`... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function mT(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($.resolve(n.rootDir,i.srcPath))}return t}function hT(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}=oT(e),a=p=>$.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=mT(t,r.modules);i.push("--modulePaths",o.join(","))}else i.push("--projectPath",t.rootDir);return i.push("--outputPath",kd.tmpdir()),i}async function gT(n,e){let t=$.dirname(e[0]);try{let i=(await ZR(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(`
1381
1381
  `)||process.stdout.write(`
1382
- `),console.log(ce("[compat:check] === end stdout ==="))),i}catch(r){let i=r;process.env.DEVECO_CLI_DEBUG&&i.stdout&&(console.log(ce("[compat:check] === scan stdout (on error) ===")),process.stdout.write(i.stdout),i.stdout.endsWith(`
1382
+ `),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(`
1383
1383
  `)||process.stdout.write(`
1384
- `),console.log(ce("[compat:check] === end stdout ===")));let o=new Error(`Compatibility scan failed: ${i.message}`+(i.stderr?`
1385
- ${i.stderr}`:""));throw i.stdout&&(o.stdout=i.stdout),o}}function ZT(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 QT(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.
1386
- 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 ek(n,e,t,r,i){i==="none"&&(t==="json"?YT(n,r):qT(n,r)),VT(n,e)}function tk(n,e){let t=$.dirname(n),r=$.basename(n),i=e.slice(1).map(o=>o.startsWith("--")?o:`"${o}"`).join(" ");m(ce(`[compat:check] command: cd "${t}" && node "${r}" ${i}`))}function nk(n){try{xT(n),m(ce(`[compat:check] cleaned up tmp report: "${n}"`))}catch(e){m(ce(`[compat:check] failed to clean up tmp report: ${e.message}`))}}var rk=[".csv",".json"];function ik(n){return rk.includes(n.toLowerCase())}function ok(n,e){if(!n)return{kind:"none"};let t=$.extname(n).toLowerCase();if(!ik(t))return{kind:"dir",dirPath:$.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:$.resolve(n),ext:t}}function sk(n){if(n.kind==="file"){if(wa(n.filePath))throw new Error(`Target file "${n.filePath}" already exists. Remove it first, or choose a different --output-path.`);let e=$.dirname(n.filePath);if(!wa(e))throw new Error(`Target directory "${e}" does not exist. Create it first, or choose a different --output-path.`)}else if(n.kind==="dir"&&!wa(n.dirPath))throw new Error(`Target directory "${n.dirPath}" does not exist. Create it first, or choose a different --output-path.`)}function Sy(n){return JSON.stringify({count:n.length,records:n},null,2)+`
1387
- `}function ak(n,e,t,r){r===".csv"?hy(n,t):gy(t,Sy(e),"utf8"),m(ce(`[compat:check] saved report: "${t}"`))}function ck(n,e,t,r){if(r==="json"){let o=$.basename(n,".csv"),s=$.join(t,`${o}.json`);return gy(s,Sy(e),"utf8"),m(ce(`[compat:check] saved report: "${s}"`)),s}let i=$.join(t,$.basename(n));return hy(n,i),m(ce(`[compat:check] saved report: "${i}"`)),i}async function lk(n,e){let t=new mt(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 dk(n,e){ZT(n,e);let t=U.discover(process.cwd());e.modules&&e.modules.length>0&&jT(t,e.modules),n.length>0&&HT(n);let r=await I.new(),{apiChangeDir:i,scriptPath:o}=r.getApiscanPaths();m(ce(`[compat:check] script: "${o}"`));let s=vy(i);QT(e,s),e.outputPath&&m(ce(`[compat:check] outputPath: "${e.outputPath}"`));let a=ok(e.outputPath,e.format);return m(ce(`[compat:check] outputTarget: ${a.kind}`)),sk(a),{project:t,scriptPath:o,target:a,toolProvider:r}}async function uk(n,e){let{project:t,scriptPath:r,target:i,toolProvider:o}=await dk(n,e),s=NT({text:"Running compatibility check...",color:"cyan"}).start();try{await lk(o,e);let a=KT(r,n,t,e);tk(r,a);let c=await XT(o,a),l=zT(c,dd.tmpdir());if(!l)throw new Error("Scanner output format unexpected: missing report path.");m(ce(`[compat:check] tmp csv: "${l}"`));let d=GT(l),h=null;if(i.kind==="file")ak(l,d,i.filePath,i.ext),h=i.filePath;else if(i.kind==="dir")h=ck(l,d,i.dirPath,e.format);else if(i.kind!=="none")throw new Error(`Unexpected output target kind: ${i.kind}`);nk(l),s.stop(),ek(d,h,e.format,e.limit,i.kind)}catch(a){throw s.fail("Compatibility check failed"),a}}var ud=new RT("compat").description("Compatibility checking utilities.");ud.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.',wy,"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)",OT,100).action(async(n,e)=>{await uk(n,e)});ud.command("versions").description("List all available target SDK versions for compatibility checking").action(async()=>{let n=_T("csv");await FT(n)});var Ey=ud;var fk=new pk("check").description("Run DevEco project checks").addCommand(Ey).addCommand(cd()),by=fk;import{Command as Qx}from"commander";import{green as Od,red as eL}from"colorette";import Md from"fs";import ow from"path";import sw from"json5";import{readFileSync as $k}from"fs";import{join as mk}from"path";var J={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"},Ie={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:mk(".ohos","config"),DOWNLOAD_CONNECT_TIMEOUT_MS:5e3},le={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"},rt={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."},V={TOOLCHAIN_INIT_FAILED:"Auto-sign failed: unable to initialize toolchain",LOGIN_REQUIRED:"Failed to automatically generate signatures.Run devecocli auth login to sign in.",TEAM_INFO_FAILED:"Failed to obtain user team information.Check the network connection, HTTP proxy, and other configurations.",REALNAME_REQUIRED:"Users without real-name verification are not supported.Complete real-name verification in AppGallery Connect.",SESSION_EXPIRED:"User session expired or token invalid. Please login again.",REGION_CHINA_ONLY:"This feature is only available for accounts registered in Chinese mainland.",DEVICE_MISSING:"Unable to create the profile file due to missing devices.Connect a device through IP or USB, or manually add a device in AppGallery Connect first.If you are installing the HAP package on an emulator, you can skip the signing step.",DEVICE_DETECT_FAILED:"Unable to detect devices. Please check hdc status. If installing HAP on an emulator, signature step can be skipped.",JAVA_PLATFORM_UNSUPPORTED:"Java environment not found (Windows/macOS/Linux only).",JAVA_REQUIRED:"Java runtime is required to run hvigor.Set JAVA_HOME or add Java to PATH.",PROJECT_DIR_MISSING:"Not in a valid project directory (project-level build-profile.json5 not found).",ATOMIC_SERVICE_UNSUPPORTED:"AtomicService projects are not yet supported. Please configure signing manually."};function va(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}function pd(n){let e=n.replace(Ie.TEAM_ID_INVALID_CHARS,"");return`${Ie.CERT_NAME_PREFIX}${e}.cer`}function kr(n,e,t){if(n===rt.FORBIDDEN)return e===le.OPENPROXY_BLOCKED_URL?new Error(v.ERR_CERT_NETWORK_ERROR):new Error(v.ERR_FORBIDDEN);if(n===rt.UNAUTHORIZED)return new Error(v.ERR_UNAUTHORIZED);if(t.includes(le.USER_NOT_HARMONY_CODE))return new Error(v.ERR_USER_NOT_HARMONY);if(t.includes(le.CERT_LIMIT_CODE))return new Error(v.ERR_CERT_LIMIT_REACHED);let r=hk(t);return new Error(r??v.ERR_DOWNLOAD_CER)}function hk(n){let e=Py(n);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let r=typeof t=="string"?Py(t):t;if(r&&typeof r=="object"){let i=r.msg;if(typeof i=="string"&&i.trim()!=="")return i}return null}function Py(n){try{return JSON.parse(n)}catch{return null}}function fd(n){return JSON.parse(n)}async function Cy(n){let e=`${J.BASE_URL}${J.CERT_LIST_PATH}`,t=await L.postAllowFailure(e,{headers:va(n)});if(t.statusCode!==200)throw kr(t.statusCode,t.statusText,t.data);return fd(t.data)?.certList??[]}async function Sa(n,e){return(await Cy(n)).find(r=>r.certName===e)??null}async function md(n,e){let t=`${J.BASE_URL}${J.CERT_DELETE_PATH}`,r=await L.deleteAllowFailure(t,{headers:va(n),params:{certIds:[e]}});if(r.statusCode!==200)throw kr(r.statusCode,r.statusText,r.data);return fd(r.data)?.ret?.code===0}async function hd(n,e,t){let r=`${J.BASE_URL}${J.CERT_ADD_PATH}`,i={csr:e,certName:t,certType:Ie.CERT_TYPE_DEBUG},o=await L.postAllowFailure(r,{headers:va(n),params:i});if(o.statusCode!==200)throw kr(o.statusCode,o.statusText,o.data);if(!o.data.includes(le.SUCCESS_MARKER))throw kr(void 0,o.statusText,o.data)}async function gd(n,e){let t=`${J.BASE_URL}${J.CERT_DOWNLOAD_URL_PATH}`,r=await L.postAllowFailure(t,{headers:va(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw kr(r.statusCode,r.statusText,r.data);return fd(r.data)?.urlsInfo?.[0]?.newUrl??null}import{mkdirSync as gk,writeFileSync as yk,existsSync as wk}from"fs";import{dirname as vk}from"path";async function Zi(n,e){let{statusCode:t,statusText:r,buffer:i}=await L.getBinaryAllowFailure(n,{timeout:Ie.DOWNLOAD_CONNECT_TIMEOUT_MS});if(t!==200)throw t===rt.FORBIDDEN&&r===le.OPENPROXY_BLOCKED_URL?new Error(v.ERR_CERT_NETWORK_ERROR):new Error(v.ERR_DOWNLOAD_CER);let o=vk(e);wk(o)||gk(o,{recursive:!0}),yk(e,i)}import Fk from"fs/promises";import{readFileSync as jk}from"fs";import Ea from"path";import Dy from"crypto";import Sk from"os";import Qi from"fs/promises";var Ry={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},Iy=["ECC","RSA"],Ay=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],Ek={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},bk=8,yd=64,Pk=/[\\:*?"<>|=-]/g,it={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function Ck(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>yd)throw new Error(`The length of keyAlias cannot exceed ${yd}`);if(!Iy.includes(n.keyAlg))throw new Error(`Invalid key algorithm ${n.keyAlg}, available: ${Iy.join(" / ")}`);let e=Ek[n.keyAlg];if(!e.includes(n.keySize))throw new Error(`Key algorithm ${n.keyAlg} does not support size ${n.keySize}, available: ${e.join(", ")}`)}function Ik(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(!Ay.includes(n.signAlg))throw new Error(`Invalid sign algorithm ${n.signAlg}, available: ${Ay.join(" / ")}`)}function Ak(n){return Dy.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function Dk(n){let e=n?.trim()??"";return e&&e.replace(Pk,"_").slice(0,yd)||it.productName}async function Ty(){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=Ea.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");try{await Qi.access(r)}catch(i){throw new Error(`Sign tool jar not found: ${r}`,{cause:i})}return{javaPath:e,jarPath:r}}async function Rk(n){let{javaPath:e,jarPath:t}=await Ty(),r=["-jar",t,Ry.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 Tk(n){let{javaPath:e,jarPath:t}=await Ty(),r=["-jar",t,Ry.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 kk(n){f.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),Ck(n);let e=await Rk(n),t=await Gr(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 xk(n){f.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),Ik(n);let e=await Tk(n),t=await Gr(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 Lk(n=bk){return Dy.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function Nk(){let n=Sk.homedir();try{await Qi.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=Ea.join(n,".ohos","config");try{await Qi.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 me(n,e,t){let r=Dk(n),i=Ea.basename(e),o=Ak(e),s=`${r}_${i}_${o}=.${t}`,a=await Nk();return Ea.join(a,s)}function Ok(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 Mk(n){try{await Qi.access(n)}catch(e){throw new Error(`Project directory ${n} is not accessible, missing read/write permissions`,{cause:e})}}async function _k(n){try{await Qi.access(n)}catch(e){throw new Error(`P12 file ${n} does not exist, terminating CSR generation.`,{cause:e})}}async function wd(n,e,t){let r=process.cwd(),i=Ok(r);await Mk(i),f.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${i}`);let o=Lk(),s=await me(n??"",i,"p12"),a=await me(n??"",i,"csr");return console.log("Start generating p12"),await kk({keyAlias:e?.keyAlias??it.keyAlias,keyPwd:o,keyAlg:e?.keyAlg??it.keyAlg,keySize:e?.keySize??it.keySize,keystoreFile:s,keystorePwd:o}),await _k(s),console.log("Start generating csr"),await xk({subject:t?.subject??it.csrSubject,outFile:a,keyAlias:t?.keyAlias??it.keyAlias,keyPwd:o,signAlg:t?.signAlg??it.signAlg,keystoreFile:s,keystorePwd:o}),{p12FilePath:s,csrFilePath:a,keyPwd:o,keyAlias:e?.keyAlias??it.keyAlias}}var Hk=["p12","cer","csr","p7b"];async function vd(n,e){for(let t of Hk){let r=await me(n,e,t);await Fk.rm(r,{force:!0})}}function Sd(n){let e;try{e=jk(n,"utf-8")}catch{throw new Error(v.ERR_CERT_INVALIDATE)}if(!Ie.CERT_PATTERN.test(e))throw new Error(v.ERR_CERT_INVALIDATE)}async function ky(n,e){return{certPath:await me(n,e,"cer"),csrPath:await me(n,e,"csr"),p12Path:await me(n,e,"p12"),profilePath:await me(n,e,"p7b")}}async function Ed(n,e){let t=e??"",r=U.discover(process.cwd()).rootDir;await vd(t,r);let i=pd(n.teamId),o=await Sa(n,i);if(o&&!await md(n,o.id))throw new Error(v.ERR_DOWNLOAD_CER);let s=await wd(e),a;try{a=$k(s.csrFilePath,"utf-8")}catch{throw new Error(v.ERR_READ_CSR)}console.log("Start generating certificate"),await hd(n,a,i);let c=await Sa(n,i);if(!c)throw new Error(v.ERR_DOWNLOAD_CER);let l=await gd(n,c.certObjectId);if(!l)throw new Error(v.ERR_DOWNLOAD_CER);let d=await me(t,r,"cer");await Zi(l,d),Sd(d);let h=await me(t,r,"p7b");return{p12FilePath:s.p12FilePath,csrFilePath:s.csrFilePath,cerFilePath:d,profileFilePath:h,certId:c.id,keyAlias:s.keyAlias,keyPwd:s.keyPwd,storePassword:s.keyPwd}}import xa from"crypto";import cn from"fs";import*as zy from"path";import cx from"json5";import{execa as By}from"execa";import Wy from"node-forge";import{createCipheriv as Uk,createDecipheriv as Bk,pbkdf2Sync as Wk,randomBytes as Id}from"crypto";import{promises as xn}from"fs";import{dirname as Gk,join as ot}from"path";var ba=3,eo=16,zk=1e4,xy="material",Vk=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),My="aes-128-gcm",kn=12,Pa=16,on=4;function bd(n){return new Uint8Array(Id(n))}function qk(n){return Id(n).toString("hex")}function Yk(...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 Ly(n,e,t=zk,r=eo){let i=[...n,Vk],o=Yk(...i),s=Buffer.from(o).toString("utf8"),a=Buffer.from(s,"utf8"),c=Wk(a,e,t,r,"sha256");return new Uint8Array(c)}function Ny(n,e){let t=Id(kn),r=Uk(My,n,t),i=Buffer.concat([r.update(e),r.final()]),o=r.getAuthTag(),s=Buffer.concat([i,o]),a=s.length,c=Buffer.alloc(on+kn+s.length);return c.writeUInt32BE(a,0),t.copy(c,on),s.copy(c,on+kn),c}function Oy(n,e){if(e.length<on+kn+Pa)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(on,on+kn),i=e.subarray(on+kn,on+kn+t);if(i.length<Pa)throw new Error("Ciphertext too short for auth tag");let o=i.subarray(0,i.length-Pa),s=i.subarray(i.length-Pa),a=Bk(My,n,r);return a.setAuthTag(s),Buffer.concat([a.update(o),a.final()])}async function Jk(n){try{await xn.rm(n,{recursive:!0,force:!0})}catch{}}async function Pd(n){let e=await xn.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 xn.readFile(ot(n,t[0]))}async function Cd(n,e){let t=qk(eo),r=ot(n,t);return await xn.writeFile(r,e),t}var sn=class{static async generateMaterial(e){let t=ot(e,xy);await Jk(t);let r=ot(t,"ac"),i=ot(t,"ce");await xn.mkdir(r,{recursive:!0}),await xn.mkdir(i,{recursive:!0});for(let d=0;d<ba;d++)await xn.mkdir(ot(t,"fd",String(d)),{recursive:!0});let o=bd(eo),s=[];for(let d=0;d<ba;d++)s.push(bd(eo));let a=bd(eo),c=Ly(s,o),l=Ny(c,a);await Cd(r,o),await Cd(i,l);for(let d=0;d<ba;d++){let h=ot(t,"fd",String(d));await Cd(h,s[d])}return a}static async readMaterial(e){let t=ot(e,xy),r=ot(t,"ac"),i=new Uint8Array(await Pd(r)),o=[];for(let d=0;d<ba;d++){let h=ot(t,"fd",String(d)),w=await Pd(h);o.push(new Uint8Array(w))}let s=ot(t,"ce"),a=await Pd(s),c=Ly(o,i),l=Oy(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t=Gk(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 Ny(r,i).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let r=await this.getStoreKey(t),i=Buffer.from(e,"hex");return Oy(r,i).toString("utf8")}};import $y from"fs";import Ta from"path";import tx from"json5";import*as Ca from"fs";import*as _y from"path";function Ia(n){let e=_y.resolve(n);if(!Ca.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=Ca.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 Lr from"fs";import*as Ae from"path";import{debuglog as xr}from"util";var Fy={"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 Kk(n){return Object.prototype.hasOwnProperty.call(Fy,n)}function Aa(n){if(Kk(n))return Fy[n]}var jy={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as Xk}from"url";var Ra=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 Da(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Hy(n){return n==null||n.length===0}function Zk(n){return!Hy(n)}function Ad(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function Qk(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 ex(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 an=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=Ae.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=Ae.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=Ae.join(t.sdkPath,"default","sdk-pkg.json"),a=Ia(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=Ae.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(Lr.existsSync(e))return Lr.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=Xk(e);if(t.includes("dist")){let s=Ae.dirname(t),a=Ae.dirname(s);return Ae.join(a,"src","resources")}let r=Ae.dirname(t),i=Ae.dirname(r),o=Ae.dirname(i);return Ae.join(o,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let r;try{r=this.readBuiltInConfigText()}catch{xr("read builtin acl permission failed.");return}if(r!==void 0)try{let i=JSON.parse(r),s=(Array.isArray(i)?i:Da(i)?Object.values(i):[]).filter(Da).map(a=>new Ra(a));s.forEach(a=>{let c=a.permissionInsteadName;Zk(c)&&(a.permissionInsteadName=Aa(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(i){xr(`failed to parse aclPermissionsInfo.json: ${i}`)}}static initAclPermissionFromSDK(e,t,r){let i=this.parsePermissionDefinitionFile(e);i&&i.forEach(o=>{if(!Da(o))return;let s=o,a=Ad(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(Hy(a)||(this.generateAclInfos(r,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||Ad(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||Ad(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:Qk(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let i=new Ra;i.permissionName=t;let o=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;i.permissionDisplayName=o;let s=ex(r,this.ACL_SINCE_KEY);i.minSupportApiLevel=String(s),this.handleInsteadName(i,o),e.add(i)}static parsePermissionDefinitionFile(e){let t=Ae.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!Lr.existsSync(t))return;let r;try{r=Lr.readFileSync(t,"utf-8")}catch(s){xr(`failed to load permissionDefinitions.json: ${s}`);return}let i;try{let s=JSON.parse(r);if(!Da(s)){xr("json object is null");return}i=s}catch(s){xr(`failed to parse permissionDefinitions.json: ${s}`);return}let o=i[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(o)){xr("definePermissions is not an array");return}return o}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=Aa(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=Aa(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function ka(n,e){let t=new Set,r=new Set;an.handleSpecificAclPermissions(),an.initAclPermission(n,e);for(let i of n.profile.modules){let o=Uy(i,n,e,r,Ta.join("src","main"));for(let a of o)t.add(a);let s=Uy(i,n,e,r,Ta.join("src","ohosTest"));for(let a of s)t.add(a)}return nx(r),t}function nx(n){if(n.size>0)throw new Error(jy.DUPLICATE_PERMISSION)}function Uy(n,e,t,r,i){let o=ix(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 E=rx(w,"name");E&&s.push(E)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=Ta.join(t.sdkPath,"default","sdk-pkg.json"),l=Ia(c),d=an.getAclPermissionInfos(e),h=new Set(Array.from(d).filter(w=>{let E=Number(w.minSupportApiLevel);return Number.isFinite(E)&&E<=l}).map(w=>w.permissionName));for(let w of Array.from(a))h.has(w)||a.delete(w);return a}function rx(n,e){let t=n[e];return typeof t=="string"?t:""}function ix(n,e,t){let r=Ta.join(n,e.srcPath,t,"module.json5"),i=ox(r);if(i==null)return null;let o=sx(i,"module");return o==null?null:ax(o,"requestPermissions")}function ox(n){try{if(!$y.existsSync(n))return null;let e=$y.readFileSync(n,"utf-8");return tx.parse(e)}catch{return null}}function sx(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 ax(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}var Rd=class{verifyStorePassword(e,t){try{let r=cn.readFileSync(e),i=Wy.asn1.fromDer(r.toString("binary"));return Wy.pkcs12.pkcs12FromAsn1(i,t),!0}catch{return!1}}getLocalCerFingerprints(e){let r=cn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(r&&r.length>0)return r.map(i=>this.formatFp(new xa.X509Certificate(i).fingerprint256));try{return[this.formatFp(new xa.X509Certificate(cn.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let i=cn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let o of i)try{let s=new xa.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 lx(n){let e=cn.readFileSync(n,"utf-8"),t=dx(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:ux(r?.validity?.["not-after"]),cerFingerprintInProfile:px(Dd(i["development-certificate"])),deviceUdidsInProfile:fx(r?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:mx(r?.acls?.["allowed-acls"]),teamIdInProfile:Dd(i["developer-id"])}}function dx(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 ux(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function px(n){if(!n)return null;try{let t=new xa.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function fx(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 mx(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 to=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([hx(o,a),yx(t.hdcPath)]),d=null;if(Gy(c).allExist)try{d=lx(c.profileFile)}catch{}return{force:r,teamId:i,productName:o,projectPath:a,materialPaths:c,bundleName:s.getBundleName(),deviceUdids:l,storePassword:await gx(a,o,c.storeFile),localAclPermissions:[...ka(s,t)].sort(),hapSignTool:new Rd,profileInfo:d}}static#t(e){return e.force?(m("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:Ne({force:!0})}):null}static#n(e){let t=Gy(e.materialPaths);return t.allExist?null:(m(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:Ne({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:Ne({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:Ne({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:Ne({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:Ne({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=vx(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:Ne({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return Sx(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(m("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:Ne({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:Ne({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:Ne({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:Ne({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:Ne({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:Ne({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function hx(n,e){let[t,r,i,o]=await Promise.all([me(n,e,"p12"),me(n,e,"csr"),me(n,e,"cer"),me(n,e,"p7b")]);return{storeFile:t,csrFile:r,cerFile:i,profileFile:o}}async function gx(n,e,t){let r=zy.join(n,"build-profile.json5");if(!cn.existsSync(r))return;let i;try{i=cx.parse(cn.readFileSync(r,"utf-8"))}catch{return}let a=(i?.app?.signingConfigs??[]).find(c=>c.name===e)?.material?.storePassword;if(a)try{return await sn.decryptPassword(a,t)}catch{return}}async function yx(n){m(`Executing: ${n} list targets`);let{stdout:e}=await By(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
1388
- `)){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 By(n,["-t",i,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),s=wx(o);s&&r.push(s)}catch{m(`[reGenerateSign] Failed to get UDID for ${i}, skipping`)}return r}function wx(n){let e=n.trim();if(!e)return null;let t=e.split(`
1389
- `);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 Gy(n){let e=[n.storeFile,n.csrFile,n.cerFile,n.profileFile],t=[];for(let r of e)cn.existsSync(r)||t.push(r);return{allExist:t.length===0,missing:t}}function vx(n,e){let t=[];for(let r of e)n.includes(r)||t.push(r);return{allPresent:t.length===0,missing:t}}function Sx(n,e){let t=[...n].sort(),r=[...e].sort();return t.length!==r.length?!1:t.every((i,o)=>i===r[o])}function Ne(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 Td}from"util";import{execa as kd}from"execa";async function qy(n,e){let t=await La(n);if(!t)throw new Error(v.DEVICE_LIST_EMPTY);let r=await Px(e);if(t.length===0)for(let s of r)await Ex(n,s.udid,s.deviceName);else for(let s of r)await bx(n,t,s.udid,s.deviceName);let o=(await La(n)).map(s=>s.id);if(o.length===0)throw new Error(v.DEVICE_LIST_EMPTY);return o}async function Ex(n,e,t){await Ky(n,e,Yy(t))}async function bx(n,e,t,r){for(let i=0;i<e.length;i++){if(t===e[i].udid)return;if(i===e.length-1){await Ky(n,t,Yy(r));return}}}function Yy(n){switch(n){case"liteWearable":return"1";case"wearable":return"2";case"tv":return"3";default:return"4"}}async function Vy(n,e=1,t=100){let r=`${J.BASE_URL}${J.DEVICE_LIST_PATH}?encodeFlag=0&start=${e}&pageSize=${t}`,i=Xy(n),o=await L.get(r,{headers:i});if(!o)throw Td("query devices failed: response is null"),new Error(v.ERROR_WHILE_ADD_DEVICE);if(o.statusCode!==200)throw Jy(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.list)throw Td("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 Jy(n,e,t){return n===rt.FORBIDDEN?e===le.OPENPROXY_BLOCKED_URL?new Error(v.ERR_CERT_NETWORK_ERROR):new Error(v.ERR_FORBIDDEN):n===rt.UNAUTHORIZED?new Error(v.ERR_UNAUTHORIZED):t.includes(le.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(v.DEVICE_LIMIT_REACHED):new Error(v.ERROR_WHILE_ADD_DEVICE)}async function La(n){let t=await Vy(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 Vy(n,s,100);if(!a||!a.deviceList||a.deviceList.length===0)break;r.push(...a.deviceList)}return r}async function Ky(n,e,t){let r=`${J.BASE_URL}${J.DEVICE_ADD_PATH}`,i=Xy(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 Td("add device failed: response is null"),new Error(v.ERROR_WHILE_ADD_DEVICE);if(a.statusCode!==200)throw Jy(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(le.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(v.DEVICE_LIMIT_REACHED):c.includes(le.DEVICE_NAME_REPEAT_CODE)?new Error(v.DEVICE_NAME_REPEAT):new Error(v.ERROR_WHILE_ADD_DEVICE)}function Xy(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}async function Px(n){let{stdout:e}=await kd(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
1390
- `)){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 Cx(i,n),s=await Ix(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 Cx(n,e){let{stdout:t}=await kd(e,["-t",n,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),r=t.trim();if(!r)return"";let i=r.split(`
1391
- `);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 Ix(n,e){let{stdout:t}=await kd(e,["-c","-t",n,"shell","getprop","hw_sc.build.os.deviceType"],{stdio:["ignore","pipe","pipe"]});return Ax(t)}function Ax(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 Ln from"fs";import{createHash as Dx}from"crypto";import{debuglog as kt}from"util";import{Buffer as Qy}from"buffer";import{createPublicKey as Rx,X509Certificate as xd}from"crypto";import{readFileSync as Tx}from"fs";import Nn from"node-forge";async function ew(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 d=`${J.BASE_URL}${J.PROVISION_ADD_TEST_PATH}`,h=kx(t,r),w=await Lx(n,d,a||[],r,s,h,o||[]);if(!w||!w.profileInfo||!w.profileInfo.provisionFileUrl)throw kt("add provision failed, the provision file url is null"),new Error(v.ADD_PROFILE_FAIL);let E=w.profileInfo,he=(await _x(n,E.provisionFileUrl)).urlList,xt=w.profileInfo.id;if(he&&he.length>0){let Lt=await ky(t,i),Nr=Lt.profilePath;if(!await Fx(he,Nr))throw await Zy(n,xt),new Error(v.ERROR_WHILE_DOWNLOAD_PROFILE);if(await Zy(n,xt),Ln.existsSync(Lt.certPath)&&Ln.existsSync(Nr)&&Ln.existsSync(Lt.p12Path)){let lw=Ln.readFileSync(Lt.certPath,"utf8"),dw=Ln.readFileSync(Nr,"utf8");return jx(dw,lw,Lt.p12Path,c,l)||Mx(Nr),Nr}}throw new Error(v.ADD_PROFILE_FAIL)}function kx(n,e){let t=n?`${n}_`:"";return`${xx(`${t}${e}_${e}`)}`}function xx(n){return Dx("sha256").update(n).digest("hex").substring(0,16)}async function Lx(n,e,t,r,i,o,s){Nx(r);let a=Nd(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 kt("add provision failed: response is null"),new Error(v.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw Ld(l.statusCode,l.statusText,l.data);let d=JSON.parse(l.data);if(!d||!d.ret||d.ret.code!==0)throw kt(`add provision fail: ${l.data}`),Ox(l.data,o),new Error(d.ret?.msg||v.ADD_PROFILE_FAIL);let h=d.provisionFileUrl;return{profileInfo:{id:d.id,name:o,provisionFileUrl:h}}}function Ld(n,e,t){return n===rt.FORBIDDEN?e===le.OPENPROXY_BLOCKED_URL?new Error(v.ERR_CERT_NETWORK_ERROR):new Error(v.ERR_FORBIDDEN):n===rt.UNAUTHORIZED?new Error(v.ERR_UNAUTHORIZED):t.includes(le.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(v.TEST_PROVISION_EXCEEDS_LIMIT):new Error(v.ADD_PROFILE_FAIL)}function Nx(n){if(!n||n.trim().length===0)throw new Error(v.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!Ie.BUNDLE_NAME_REGEX.test(n))throw new Error(v.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function Ox(n,e){if(n.includes(le.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(v.TEST_PROVISION_EXCEEDS_LIMIT);if(n.includes(le.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(v.PROFILE_NAME_REPEAT)}async function Zy(n,e){if(!e||e.trim().length===0)return;let t=`${J.BASE_URL}${J.PROVISION_DELETE_PATH}?id=${e}`,r=await L.deleteAllowFailure(t,{headers:Nd(n)});if(r.statusCode!==200)throw Ld(r.statusCode,r.statusText,r.data);let i=JSON.parse(r.data);(!i||!i.ret||i.ret.code!==0)&&kt(`delete provision failed: ${r.data}`)}function Mx(...n){for(let e of n)try{Ln.existsSync(e)&&Ln.unlinkSync(e)}catch(t){kt(`delete local sign file error: ${t.message}`)}}async function _x(n,e){let t=`${J.BASE_URL}${J.CERT_DOWNLOAD_URL_PATH}`,r=Nd(n),i={sourceUrls:e},o=await L.postAllowFailure(t,{headers:r,params:i});if(!o)throw kt("get download list failed: response is null"),new Error(v.ADD_PROFILE_FAIL);if(o.statusCode!==200)throw Ld(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw kt("download: The application does not exist"),new Error(s.ret?.msg||v.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function Fx(n,e){if(!n||n.length===0)return!1;let t=n[0].newUrl;return await Zi(t,e),!0}function jx(n,e,t,r,i){return Hx(n,e),r=r||Ie.TARGET_FRIENDLY_NAME,i=i||"",$x(e,t,r,i),!0}function Hx(n,e){if(e.lastIndexOf(Ie.CERT_BEGIN_HEADER)<0)throw new Error(v.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(Ie.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!n.includes(t))throw new Error(v.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}function $x(n,e,t,r){let i=n.matchAll(Ie.CERTIFICATE_PATTERN_GLOBAL),o=[],s=new Date;for(let c of i)try{let l=c[0],d=Ux(l),h=new Date(d.validFrom),w=new Date(d.validTo);if(s<h||s>w){let E=`Certificate is not valid, Valid from ${h} to ${w}`;throw console.warn(`checkCertificateInValidityPeriod: ${E}`),new Error(v.CERTIFICATE_HAS_EXPIRED)}o.push(d)}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(!Wx(e,t,r,o))throw new Error(v.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function Ux(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new xd(t);let r=Qy.from(t,"base64");return new xd(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}function Bx(n){if(n.cert){let e=Nn.pki.publicKeyToPem(n.cert.publicKey);return Rx(e).export({type:"spki",format:"der"})}if(n.asn1)try{let e=Nn.asn1.toDer(n.asn1).getBytes(),t=Qy.from(e,"binary");return new xd(t).publicKey.export({type:"spki",format:"der"})}catch(e){return kt(`Failed to parse cert from asn1: ${e}`),null}return null}function Wx(n,e,t,r){try{let i=Tx(n),o=Nn.asn1.fromDer(Nn.util.createBuffer(i)),c=Nn.pkcs12.pkcs12FromAsn1(o,t).getBags({bagType:Nn.pki.oids.certBag})[Nn.pki.oids.certBag]||[];for(let l of c){let d=l.attributes?.friendlyName?.[0];if(!d||d.toLowerCase()!==e.toLowerCase())continue;let h=Bx(l);if(!h)continue;if(r.some(E=>{let N=E.publicKey.export({type:"spki",format:"der"});return h.equals(N)}))return!0}return!1}catch(i){let o=i instanceof Error?i.message:String(i);return kt(`Failed to process P12 file: ${n}, error: ${o}`),!1}}function Nd(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var nw="https://developer.huawei.com",Gx={"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"},zx="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function Vx(n){let e=Gx[n];return e?`${nw}${e}`:void 0}function qx(){return`${nw}${zx}`}var Yx={"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 tw(n,e){return(Yx[n]??n).replace(/\{(\d+)\}/g,(r,i)=>String(e[Number(i)]??""))}function Jx(n){return Array.from(n).join(", ")}function rw(n,e){if(n.size===0)return;let t=an.getAclPermissionInfos(e),r=new Set;for(let h of t)n.has(h.permissionName)&&r.add(h);for(let h of r){let w=Vx(h.permissionName);w!=null&&(h.permissionHelpUrlKey=w)}let i=new Set;for(let h of r)i.add(h.permissionDisplayName);let o=new Set;for(let h of r)if(h.permissionHelpUrlKey!=null){let w=h.permissionInsteadName??h.permissionDisplayName;o.add(`${w} (${h.permissionHelpUrlKey})`)}let s=qx(),a=tw("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=o.size>0?Array.from(o).join(", ")+".":"",d=tw("acl.permissions.warn",[Jx(i),l,c]);console.log(d)}var Na=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(V.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:V.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import Kx from"fs";import iw from"path";var Oa=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(V.JAVA_PLATFORM_UNSUPPORTED)}}checkHapSignTools(e){let t=this.toolProvider.sdkPath,r=iw.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");if(!Kx.existsSync(r)){let i=iw.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 Ma=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await ne.getUserInfo()}catch(e){return m(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await ne.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(V.LOGIN_REQUIRED)}catch(t){return m(`[EnvCheck] Login check failed: ${t.message}`),e(V.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(V.TEAM_INFO_FAILED);try{if((await jt()).teamList.length>0)return{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Team API error: ${r.message}`),e(V.TEAM_INFO_FAILED)}return m("[EnvCheck] No teams found for current user"),e(V.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(V.REALNAME_REQUIRED):t.isRealName!==!0?(m("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(V.REALNAME_REQUIRED)):{passed:!0,message:""}:e(V.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let r=e??"";try{let i=await jt();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(V.REGION_CHINA_ONLY):{passed:!0,message:""}:(m("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(V.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function Xx(n){try{let{teamList:e}=await jt();if(e.length>0)return e[0].id}catch(e){m(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function Zx(n){let e=await ne.getUserInfo(),t=await ne.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await Xx(e.userId);if(!r)throw new Error("No team found");let i={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await La(i)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var _a=class{constructor(e){this.toolProvider=e}toolProvider;async checkDevice(e,t){try{let r=await Zx(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 Q.from(this.toolProvider).listDevices();return o.length===0?(m("[EnvCheck] Scenario 4 Device check: no local devices found"),e(V.DEVICE_MISSING)):o.some(a=>gn(a.serial))?{passed:!0,message:""}:(m("[EnvCheck] Scenario 4 Device check: local device found but not an emulator"),e(V.DEVICE_MISSING))}catch(r){return m(`[EnvCheck] Scenario 4 Device check failed: ${r.message}`),e(V.DEVICE_DETECT_FAILED)}}};var Fa=class{projectChecker=new Na;toolchainChecker=null;authChecker=new Ma;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 Oa(e),this.deviceChecker=new _a(e),!0}catch(e){throw m(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(V.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 tL(n){if(Md.existsSync(n)){let e=Md.readFileSync(n,"utf-8");return sw.parse(e)}return{app:{signingConfigs:[],products:[]}}}function nL(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function rL(n){if(n.keyPwd===n.storePassword){let r=await sn.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await sn.encryptedPassword(n.keyPwd,n.p12FilePath),t=await sn.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function iL(n,e,t){let r=ow.join(n,"build-profile.json5"),i=tL(r);nL(i);let o=t??"default",{keyPassword:s,storePassword:a}=await rL(e),c={name:o,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:s,profile:e.profileFilePath,signAlg:it.signAlg,storeFile:e.p12FilePath,storePassword:a}},l=i.app?.signingConfigs?.findIndex(h=>h.name===o);l!==void 0&&l>=0?i.app.signingConfigs[l]=c:i.app.signingConfigs.push(c);let d=i.app?.products?.findIndex(h=>h.name===o);d!==void 0&&d>=0?i.app.products[d].signingConfig=o:i.app.products.push({name:o,signingConfig:o}),Md.writeFileSync(r,sw.stringify(i,null,2),"utf-8")}async function oL(n){let e=await ne.getUserInfo(),t=await ne.refreshToken();if(!e||!t)throw new Error("Failed to obtain login credentials. Run `devecocli login` again.");return{uid:e.userId??"",teamId:n.teamId??e.userId??"",accessToken:t.accessToken??""}}async function sL(n){let e=n.product||"default";await new Fa().preflight({productName:e,teamId:n.teamId}),console.log("Executing signature generate command");let r=await oL(n),i=await I.new(),{shouldRegenerate:o}=await to.shouldRegenerate({force:n.force??!1,teamId:r.teamId,productName:n.product},i);if(!o){console.log(Od("Signature generation completed successfully."));return}await aL(n,r,i),console.log(Od("Signature generation completed successfully."))}async function aL(n,e,t){let r=await Ed(e,n.product),i=cL(n,e,r,t);i.allDeviceIds=await qy(e,t.hdcPath),await ew(e,i);let o=U.discover(process.cwd()).rootDir;await iL(o,r,n.product??"default"),console.log(Od(`Signing config written to ${ow.join(o,"build-profile.json5")}`))}function cL(n,e,t,r){let i=process.cwd(),o=U.discover(i),s=ka(o,r);return rw(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 aw=new Qx("signature").description("Generate application signature.");aw.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 sL(n)}catch(e){console.error(eL(e.message)),process.exit(1)}});var cw=aw;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";lL();ee.name("devecocli").description("HarmonyOS application development command line tool").version("1.3.0-Test.8");ee.addCommand(bu);ee.addCommand(Hu);ee.addCommand(Wu);ee.addCommand(tp);ee.addCommand(Rp);ee.addCommand(Jp);ee.addCommand(bf);ee.addCommand(Af);ee.addCommand(Ff);ee.addCommand(zf);ee.addCommand(um);ee.addCommand(bg);ee.addCommand(Vg);ee.addCommand(by);ee.addCommand(cw);var _d=process.argv.slice(2);_d.length>=2&&_d[_d.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var uL=new Set(["update","auth"]);ee.hook("preAction",async(n,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==ee;)t=t.parent;uL.has(t.name())||await I.checkVersion()});ee.parseAsync(process.argv).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(dL(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
1384
+ `),console.log(ae("[compat:check] === end stdout ===")));let o=new Error(`Compatibility scan failed: ${i.message}`+(i.stderr?`
1385
+ ${i.stderr}`:""));throw i.stdout&&(o.stdout=i.stdout),o}}function yT(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 wT(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.
1386
+ 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 vT(n,e,t,r,i){i==="none"&&(t==="json"?fT(n,r):pT(n,r)),uT(n,e)}function ST(n,e){let t=$.dirname(n),r=$.basename(n),i=e.slice(1).map(o=>o.startsWith("--")?o:`"${o}"`).join(" ");m(ae(`[compat:check] command: cd "${t}" && node "${r}" ${i}`))}function bT(n){try{KR(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 ET=[".csv",".json"];function PT(n){return ET.includes(n.toLowerCase())}function CT(n,e){if(!n)return{kind:"none"};let t=$.extname(n).toLowerCase();if(!PT(t))return{kind:"dir",dirPath:$.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:$.resolve(n),ext:t}}function IT(n){if(n.kind==="file"){if(Da(n.filePath))throw new Error(`Target file "${n.filePath}" already exists. Remove it first, or choose a different --output-path.`);let e=$.dirname(n.filePath);if(!Da(e))throw new Error(`Target directory "${e}" does not exist. Create it first, or choose a different --output-path.`)}else if(n.kind==="dir"&&!Da(n.dirPath))throw new Error(`Target directory "${n.dirPath}" does not exist. Create it first, or choose a different --output-path.`)}function _y(n){return JSON.stringify({count:n.length,records:n},null,2)+`
1387
+ `}function AT(n,e,t,r){r===".csv"?xy(n,t):Ly(t,_y(e),"utf8"),m(ae(`[compat:check] saved report: "${t}"`))}function DT(n,e,t,r){if(r==="json"){let o=$.basename(n,".csv"),s=$.join(t,`${o}.json`);return Ly(s,_y(e),"utf8"),m(ae(`[compat:check] saved report: "${s}"`)),s}let i=$.join(t,$.basename(n));return xy(n,i),m(ae(`[compat:check] saved report: "${i}"`)),i}async function kT(n,e){let t=new pt(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 RT(n,e){yT(n,e);let t=U.discover(process.cwd());e.modules&&e.modules.length>0&&rT(t,e.modules),n.length>0&&iT(n);let r=await I.new(),{apiChangeDir:i,scriptPath:o}=r.getApiscanPaths();m(ae(`[compat:check] script: "${o}"`));let s=My(i);wT(e,s),e.outputPath&&m(ae(`[compat:check] outputPath: "${e.outputPath}"`));let a=CT(e.outputPath,e.format);return m(ae(`[compat:check] outputTarget: ${a.kind}`)),IT(a),{project:t,scriptPath:o,target:a,toolProvider:r}}async function TT(n,e){let{project:t,scriptPath:r,target:i,toolProvider:o}=await RT(n,e),s=XR({text:"Running compatibility check...",color:"cyan"}).start();try{await kT(o,e);let a=hT(r,n,t,e);ST(r,a);let c=await gT(o,a),l=dT(c,kd.tmpdir());if(!l)throw new Error("Scanner output format unexpected: missing report path.");m(ae(`[compat:check] tmp csv: "${l}"`));let p=lT(l),g=null;if(i.kind==="file")AT(l,p,i.filePath,i.ext),g=i.filePath;else if(i.kind==="dir")g=DT(l,p,i.dirPath,e.format);else if(i.kind!=="none")throw new Error(`Unexpected output target kind: ${i.kind}`);bT(l),s.stop(),vT(p,g,e.format,e.limit,i.kind)}catch(a){throw s.fail("Compatibility check failed"),a}}var Rd=new qR("compat").description("Compatibility checking utilities.");Rd.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.',Oy,"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)",QR,100).action(async(n,e)=>{await TT(n,e)});Rd.command("versions").description("List all available target SDK versions for compatibility checking").action(async()=>{let n=tT("csv");await nT(n)});var Fy=Rd;var LT=new xT("check").description("Run DevEco project checks").addCommand(Fy).addCommand(Ad()),jy=LT;import{Command as wL}from"commander";import{green as Xd,red as vL}from"colorette";import Qd from"fs";import bw from"path";import Ew from"json5";import{readFileSync as ox}from"fs";import{join as NT}from"path";var Y={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"},be={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:NT(".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"},nt={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."},K={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 ka(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}function Td(n){let e=n.replace(be.TEAM_ID_INVALID_CHARS,"");return`${be.CERT_NAME_PREFIX}${e}.cer`}function Tr(n,e,t){if(n===nt.FORBIDDEN)return e===ce.OPENPROXY_BLOCKED_URL?new Error(v.ERR_CERT_NETWORK_ERROR):new Error(v.ERR_FORBIDDEN);if(n===nt.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=OT(t);return new Error(r??v.ERR_DOWNLOAD_CER)}function OT(n){let e=Hy(n);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let r=typeof t=="string"?Hy(t):t;if(r&&typeof r=="object"){let i=r.msg;if(typeof i=="string"&&i.trim()!=="")return i}return null}function Hy(n){try{return JSON.parse(n)}catch{return null}}function xd(n){return JSON.parse(n)}async function $y(n){let e=`${Y.BASE_URL}${Y.CERT_LIST_PATH}`,t=await L.postAllowFailure(e,{headers:ka(n)});if(t.statusCode!==200)throw Tr(t.statusCode,t.statusText,t.data);return xd(t.data)?.certList??[]}async function Ra(n,e){return(await $y(n)).find(r=>r.certName===e)??null}async function Ld(n,e){let t=`${Y.BASE_URL}${Y.CERT_DELETE_PATH}`,r=await L.deleteAllowFailure(t,{headers:ka(n),params:{certIds:[e]}});if(r.statusCode!==200)throw Tr(r.statusCode,r.statusText,r.data);return xd(r.data)?.ret?.code===0}async function Nd(n,e,t){let r=`${Y.BASE_URL}${Y.CERT_ADD_PATH}`,i={csr:e,certName:t,certType:be.CERT_TYPE_DEBUG},o=await L.postAllowFailure(r,{headers:ka(n),params:i});if(o.statusCode!==200)throw Tr(o.statusCode,o.statusText,o.data);if(!o.data.includes(ce.SUCCESS_MARKER))throw Tr(void 0,o.statusText,o.data)}async function Od(n,e){let t=`${Y.BASE_URL}${Y.CERT_DOWNLOAD_URL_PATH}`,r=await L.postAllowFailure(t,{headers:ka(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw Tr(r.statusCode,r.statusText,r.data);return xd(r.data)?.urlsInfo?.[0]?.newUrl??null}import{mkdirSync as MT,writeFileSync as _T,existsSync as FT}from"fs";import{dirname as jT}from"path";async function eo(n,e){let{statusCode:t,statusText:r,buffer:i}=await L.getBinaryAllowFailure(n,{timeout:be.DOWNLOAD_CONNECT_TIMEOUT_MS});if(t!==200)throw t===nt.FORBIDDEN&&r===ce.OPENPROXY_BLOCKED_URL?new Error(v.ERR_CERT_NETWORK_ERROR):new Error(v.ERR_DOWNLOAD_CER);let o=jT(e);FT(o)||MT(o,{recursive:!0}),_T(e,i)}import nx from"fs/promises";import{readFileSync as rx}from"fs";import Ta from"path";import Wy from"crypto";import HT from"os";import to from"fs/promises";var Gy={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},Uy=["ECC","RSA"],By=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],$T={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},UT=8,Md=64,BT=/[\\:*?"<>|=-]/g,rt={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function WT(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>Md)throw new Error(`The length of keyAlias cannot exceed ${Md}`);if(!Uy.includes(n.keyAlg))throw new Error(`Invalid key algorithm ${n.keyAlg}, available: ${Uy.join(" / ")}`);let e=$T[n.keyAlg];if(!e.includes(n.keySize))throw new Error(`Key algorithm ${n.keyAlg} does not support size ${n.keySize}, available: ${e.join(", ")}`)}function GT(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(!By.includes(n.signAlg))throw new Error(`Invalid sign algorithm ${n.signAlg}, available: ${By.join(" / ")}`)}function VT(n){return Wy.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function zT(n){let e=n?.trim()??"";return e&&e.replace(BT,"_").slice(0,Md)||rt.productName}async function Vy(){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=Ta.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");try{await to.access(r)}catch(i){throw new Error(`Sign tool jar not found: ${r}`,{cause:i})}return{javaPath:e,jarPath:r}}async function qT(n){let{javaPath:e,jarPath:t}=await Vy(),r=["-jar",t,Gy.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 YT(n){let{javaPath:e,jarPath:t}=await Vy(),r=["-jar",t,Gy.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 JT(n){f.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),WT(n);let e=await qT(n),t=await Wr(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 KT(n){f.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),GT(n);let e=await YT(n),t=await Wr(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 ZT(n=UT){return Wy.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function XT(){let n=HT.homedir();try{await to.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=Ta.join(n,".ohos","config");try{await to.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=zT(n),i=Ta.basename(e),o=VT(e),s=`${r}_${i}_${o}=.${t}`,a=await XT();return Ta.join(a,s)}function QT(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 ex(n){try{await to.access(n)}catch(e){throw new Error(`Project directory ${n} is not accessible, missing read/write permissions`,{cause:e})}}async function tx(n){try{await to.access(n)}catch(e){throw new Error(`P12 file ${n} does not exist, terminating CSR generation.`,{cause:e})}}async function _d(n,e,t){let r=process.cwd(),i=QT(r);await ex(i),f.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${i}`);let o=ZT(),s=await pe(n??"",i,"p12"),a=await pe(n??"",i,"csr");return console.log("Start generating p12"),await JT({keyAlias:e?.keyAlias??rt.keyAlias,keyPwd:o,keyAlg:e?.keyAlg??rt.keyAlg,keySize:e?.keySize??rt.keySize,keystoreFile:s,keystorePwd:o}),await tx(s),console.log("Start generating csr"),await KT({subject:t?.subject??rt.csrSubject,outFile:a,keyAlias:t?.keyAlias??rt.keyAlias,keyPwd:o,signAlg:t?.signAlg??rt.signAlg,keystoreFile:s,keystorePwd:o}),{p12FilePath:s,csrFilePath:a,keyPwd:o,keyAlias:e?.keyAlias??rt.keyAlias}}var ix=["p12","cer","csr","p7b"];async function Fd(n,e){for(let t of ix){let r=await pe(n,e,t);await nx.rm(r,{force:!0})}}function jd(n){let e;try{e=rx(n,"utf-8")}catch{throw new Error(v.ERR_CERT_INVALIDATE)}if(!be.CERT_PATTERN.test(e))throw new Error(v.ERR_CERT_INVALIDATE)}async function zy(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 Hd(n,e){let t=e??"",r=U.discover(process.cwd()).rootDir;await Fd(t,r);let i=Td(n.teamId),o=await Ra(n,i);if(o&&!await Ld(n,o.id))throw new Error(v.ERR_DOWNLOAD_CER);let s=await _d(e),a;try{a=ox(s.csrFilePath,"utf-8")}catch{throw new Error(v.ERR_READ_CSR)}console.log("Start generating certificate"),await Nd(n,a,i);let c=await Ra(n,i);if(!c)throw new Error(v.ERR_DOWNLOAD_CER);let l=await Od(n,c.certObjectId);if(!l)throw new Error(v.ERR_DOWNLOAD_CER);let p=await pe(t,r,"cer");await eo(l,p),jd(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 $a from"crypto";import ln from"fs";import*as aw from"path";import Dx from"json5";import{execa as iw}from"execa";import ow from"node-forge";import{createCipheriv as sx,createDecipheriv as ax,pbkdf2Sync as cx,randomBytes as Wd}from"crypto";import{promises as Tn}from"fs";import{dirname as lx,join as it}from"path";var xa=3,no=16,dx=1e4,qy="material",ux=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Zy="aes-128-gcm",Rn=12,La=16,sn=4;function $d(n){return new Uint8Array(Wd(n))}function px(n){return Wd(n).toString("hex")}function fx(...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 Yy(n,e,t=dx,r=no){let i=[...n,ux],o=fx(...i),s=Buffer.from(o).toString("utf8"),a=Buffer.from(s,"utf8"),c=cx(a,e,t,r,"sha256");return new Uint8Array(c)}function Jy(n,e){let t=Wd(Rn),r=sx(Zy,n,t),i=Buffer.concat([r.update(e),r.final()]),o=r.getAuthTag(),s=Buffer.concat([i,o]),a=s.length,c=Buffer.alloc(sn+Rn+s.length);return c.writeUInt32BE(a,0),t.copy(c,sn),s.copy(c,sn+Rn),c}function Ky(n,e){if(e.length<sn+Rn+La)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(sn,sn+Rn),i=e.subarray(sn+Rn,sn+Rn+t);if(i.length<La)throw new Error("Ciphertext too short for auth tag");let o=i.subarray(0,i.length-La),s=i.subarray(i.length-La),a=ax(Zy,n,r);return a.setAuthTag(s),Buffer.concat([a.update(o),a.final()])}async function mx(n){try{await Tn.rm(n,{recursive:!0,force:!0})}catch{}}async function Ud(n){let e=await Tn.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 Tn.readFile(it(n,t[0]))}async function Bd(n,e){let t=px(no),r=it(n,t);return await Tn.writeFile(r,e),t}var an=class{static async generateMaterial(e){let t=it(e,qy);await mx(t);let r=it(t,"ac"),i=it(t,"ce");await Tn.mkdir(r,{recursive:!0}),await Tn.mkdir(i,{recursive:!0});for(let p=0;p<xa;p++)await Tn.mkdir(it(t,"fd",String(p)),{recursive:!0});let o=$d(no),s=[];for(let p=0;p<xa;p++)s.push($d(no));let a=$d(no),c=Yy(s,o),l=Jy(c,a);await Bd(r,o),await Bd(i,l);for(let p=0;p<xa;p++){let g=it(t,"fd",String(p));await Bd(g,s[p])}return a}static async readMaterial(e){let t=it(e,qy),r=it(t,"ac"),i=new Uint8Array(await Ud(r)),o=[];for(let p=0;p<xa;p++){let g=it(t,"fd",String(p)),w=await Ud(g);o.push(new Uint8Array(w))}let s=it(t,"ce"),a=await Ud(s),c=Yy(o,i),l=Ky(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t=lx(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 Jy(r,i).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let r=await this.getStoreKey(t),i=Buffer.from(e,"hex");return Ky(r,i).toString("utf8")}};import nw from"fs";import ja from"path";import Sx from"json5";import*as Na from"fs";import*as Xy from"path";function Oa(n){let e=Xy.resolve(n);if(!Na.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=Na.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 Lr from"fs";import*as Ee from"path";import{debuglog as xr}from"util";var Qy={"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 hx(n){return Object.prototype.hasOwnProperty.call(Qy,n)}function Ma(n){if(hx(n))return Qy[n]}var ew={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as gx}from"url";var Fa=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 _a(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function tw(n){return n==null||n.length===0}function yx(n){return!tw(n)}function Gd(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function wx(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 vx(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 cn=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=Oa(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(Lr.existsSync(e))return Lr.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=gx(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{xr("read builtin acl permission failed.");return}if(r!==void 0)try{let i=JSON.parse(r),s=(Array.isArray(i)?i:_a(i)?Object.values(i):[]).filter(_a).map(a=>new Fa(a));s.forEach(a=>{let c=a.permissionInsteadName;yx(c)&&(a.permissionInsteadName=Ma(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(i){xr(`failed to parse aclPermissionsInfo.json: ${i}`)}}static initAclPermissionFromSDK(e,t,r){let i=this.parsePermissionDefinitionFile(e);i&&i.forEach(o=>{if(!_a(o))return;let s=o,a=Gd(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(tw(a)||(this.generateAclInfos(r,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||Gd(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||Gd(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:wx(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let i=new Fa;i.permissionName=t;let o=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;i.permissionDisplayName=o;let s=vx(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(!Lr.existsSync(t))return;let r;try{r=Lr.readFileSync(t,"utf-8")}catch(s){xr(`failed to load permissionDefinitions.json: ${s}`);return}let i;try{let s=JSON.parse(r);if(!_a(s)){xr("json object is null");return}i=s}catch(s){xr(`failed to parse permissionDefinitions.json: ${s}`);return}let o=i[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(o)){xr("definePermissions is not an array");return}return o}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=Ma(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=Ma(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function Ha(n,e){let t=new Set,r=new Set;cn.handleSpecificAclPermissions(),cn.initAclPermission(n,e);for(let i of n.profile.modules){let o=rw(i,n,e,r,ja.join("src","main"));for(let a of o)t.add(a);let s=rw(i,n,e,r,ja.join("src","ohosTest"));for(let a of s)t.add(a)}return bx(r),t}function bx(n){if(n.size>0)throw new Error(ew.DUPLICATE_PERMISSION)}function rw(n,e,t,r,i){let o=Px(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 E=Ex(w,"name");E&&s.push(E)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=ja.join(t.sdkPath,"default","sdk-pkg.json"),l=Oa(c),p=cn.getAclPermissionInfos(e),g=new Set(Array.from(p).filter(w=>{let E=Number(w.minSupportApiLevel);return Number.isFinite(E)&&E<=l}).map(w=>w.permissionName));for(let w of Array.from(a))g.has(w)||a.delete(w);return a}function Ex(n,e){let t=n[e];return typeof t=="string"?t:""}function Px(n,e,t){let r=ja.join(n,e.srcPath,t,"module.json5"),i=Cx(r);if(i==null)return null;let o=Ix(i,"module");return o==null?null:Ax(o,"requestPermissions")}function Cx(n){try{if(!nw.existsSync(n))return null;let e=nw.readFileSync(n,"utf-8");return Sx.parse(e)}catch{return null}}function Ix(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 Ax(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}var zd=class{verifyStorePassword(e,t){try{let r=ln.readFileSync(e),i=ow.asn1.fromDer(r.toString("binary"));return ow.pkcs12.pkcs12FromAsn1(i,t),!0}catch{return!1}}getLocalCerFingerprints(e){let r=ln.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(r&&r.length>0)return r.map(i=>this.formatFp(new $a.X509Certificate(i).fingerprint256));try{return[this.formatFp(new $a.X509Certificate(ln.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let i=ln.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let o of i)try{let s=new $a.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 kx(n){let e=ln.readFileSync(n,"utf-8"),t=Rx(e),r=null;if(t)try{r=JSON.parse(t)}catch{r=null}let i=r?.["bundle-info"]??{};return{rawContent:e,bundleNameInProfile:Vd(i["bundle-name"]),expiryDate:Tx(r?.validity?.["not-after"]),cerFingerprintInProfile:xx(Vd(i["development-certificate"])),deviceUdidsInProfile:Lx(r?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:Nx(r?.acls?.["allowed-acls"]),teamIdInProfile:Vd(i["developer-id"])}}function Rx(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 Tx(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function xx(n){if(!n)return null;try{let t=new $a.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function Lx(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 Nx(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 Vd(n){return typeof n=="string"?n:null}var ro=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([Ox(o,a),_x(t.hdcPath)]),p=null;if(sw(c).allExist)try{p=kx(c.profileFile)}catch{}return{force:r,teamId:i,productName:o,projectPath:a,materialPaths:c,bundleName:s.getBundleName(),deviceUdids:l,storePassword:await Mx(a,o,c.storeFile),localAclPermissions:[...Ha(s,t)].sort(),hapSignTool:new zd,profileInfo:p}}static#t(e){return e.force?(m("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:xe({force:!0})}):null}static#n(e){let t=sw(e.materialPaths);return t.allExist?null:(m(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:xe({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:xe({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:xe({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:xe({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:xe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=jx(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:xe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return Hx(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(m("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:xe({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:xe({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:xe({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:xe({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:xe({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:xe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function Ox(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 Mx(n,e,t){let r=aw.join(n,"build-profile.json5");if(!ln.existsSync(r))return;let i;try{i=Dx.parse(ln.readFileSync(r,"utf-8"))}catch{return}let a=(i?.app?.signingConfigs??[]).find(c=>c.name===e)?.material?.storePassword;if(a)try{return await an.decryptPassword(a,t)}catch{return}}async function _x(n){m(`Executing: ${n} list targets`);let{stdout:e}=await iw(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
1388
+ `)){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 iw(n,["-t",i,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),s=Fx(o);s&&r.push(s)}catch{m(`[reGenerateSign] Failed to get UDID for ${i}, skipping`)}return r}function Fx(n){let e=n.trim();if(!e)return null;let t=e.split(`
1389
+ `);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 sw(n){let e=[n.storeFile,n.csrFile,n.cerFile,n.profileFile],t=[];for(let r of e)ln.existsSync(r)||t.push(r);return{allExist:t.length===0,missing:t}}function jx(n,e){let t=[];for(let r of e)n.includes(r)||t.push(r);return{allPresent:t.length===0,missing:t}}function Hx(n,e){let t=[...n].sort(),r=[...e].sort();return t.length!==r.length?!1:t.every((i,o)=>i===r[o])}function xe(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 qd}from"util";import{execa as Yd}from"execa";async function lw(n,e){let t=await Ua(n);if(!t)throw new Error(v.DEVICE_LIST_EMPTY);let r=await Bx(e);if(t.length===0)for(let s of r)await $x(n,s.udid,s.deviceName);else for(let s of r)await Ux(n,t,s.udid,s.deviceName);let o=(await Ua(n)).map(s=>s.id);if(o.length===0)throw new Error(v.DEVICE_LIST_EMPTY);return o}async function $x(n,e,t){await pw(n,e,dw(t))}async function Ux(n,e,t,r){for(let i=0;i<e.length;i++){if(t===e[i].udid)return;if(i===e.length-1){await pw(n,t,dw(r));return}}}function dw(n){switch(n){case"liteWearable":return"1";case"wearable":return"2";case"tv":return"3";default:return"4"}}async function cw(n,e=1,t=100){let r=`${Y.BASE_URL}${Y.DEVICE_LIST_PATH}?encodeFlag=0&start=${e}&pageSize=${t}`,i=fw(n),o=await L.get(r,{headers:i});if(!o)throw qd("query devices failed: response is null"),new Error(v.ERROR_WHILE_ADD_DEVICE);if(o.statusCode!==200)throw uw(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.list)throw qd("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 uw(n,e,t){return n===nt.FORBIDDEN?e===ce.OPENPROXY_BLOCKED_URL?new Error(v.ERR_CERT_NETWORK_ERROR):new Error(v.ERR_FORBIDDEN):n===nt.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 Ua(n){let t=await cw(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 cw(n,s,100);if(!a||!a.deviceList||a.deviceList.length===0)break;r.push(...a.deviceList)}return r}async function pw(n,e,t){let r=`${Y.BASE_URL}${Y.DEVICE_ADD_PATH}`,i=fw(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 qd("add device failed: response is null"),new Error(v.ERROR_WHILE_ADD_DEVICE);if(a.statusCode!==200)throw uw(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 fw(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}async function Bx(n){let{stdout:e}=await Yd(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
1390
+ `)){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 Wx(i,n),s=await Gx(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 Wx(n,e){let{stdout:t}=await Yd(e,["-t",n,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),r=t.trim();if(!r)return"";let i=r.split(`
1391
+ `);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 Gx(n,e){let{stdout:t}=await Yd(e,["-c","-t",n,"shell","getprop","hw_sc.build.os.deviceType"],{stdio:["ignore","pipe","pipe"]});return Vx(t)}function Vx(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 xn from"fs";import{createHash as zx}from"crypto";import{debuglog as Rt}from"util";import{Buffer as hw}from"buffer";import{createPublicKey as qx,X509Certificate as Jd}from"crypto";import{readFileSync as Yx}from"fs";import Ln from"node-forge";async function gw(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=`${Y.BASE_URL}${Y.PROVISION_ADD_TEST_PATH}`,g=Jx(t,r),w=await Zx(n,p,a||[],r,s,g,o||[]);if(!w||!w.profileInfo||!w.profileInfo.provisionFileUrl)throw Rt("add provision failed, the provision file url is null"),new Error(v.ADD_PROFILE_FAIL);let E=w.profileInfo,fe=(await tL(n,E.provisionFileUrl)).urlList,Tt=w.profileInfo.id;if(fe&&fe.length>0){let xt=await zy(t,i),Nr=xt.profilePath;if(!await nL(fe,Nr))throw await mw(n,Tt),new Error(v.ERROR_WHILE_DOWNLOAD_PROFILE);if(await mw(n,Tt),xn.existsSync(xt.certPath)&&xn.existsSync(Nr)&&xn.existsSync(xt.p12Path)){let Aw=xn.readFileSync(xt.certPath,"utf8"),Dw=xn.readFileSync(Nr,"utf8");return rL(Dw,Aw,xt.p12Path,c,l)||eL(Nr),Nr}}throw new Error(v.ADD_PROFILE_FAIL)}function Jx(n,e){let t=n?`${n}_`:"";return`${Kx(`${t}${e}_${e}`)}`}function Kx(n){return zx("sha256").update(n).digest("hex").substring(0,16)}async function Zx(n,e,t,r,i,o,s){Xx(r);let a=Zd(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 Rt("add provision failed: response is null"),new Error(v.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw Kd(l.statusCode,l.statusText,l.data);let p=JSON.parse(l.data);if(!p||!p.ret||p.ret.code!==0)throw Rt(`add provision fail: ${l.data}`),Qx(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 Kd(n,e,t){return n===nt.FORBIDDEN?e===ce.OPENPROXY_BLOCKED_URL?new Error(v.ERR_CERT_NETWORK_ERROR):new Error(v.ERR_FORBIDDEN):n===nt.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 Xx(n){if(!n||n.trim().length===0)throw new Error(v.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!be.BUNDLE_NAME_REGEX.test(n))throw new Error(v.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function Qx(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 mw(n,e){if(!e||e.trim().length===0)return;let t=`${Y.BASE_URL}${Y.PROVISION_DELETE_PATH}?id=${e}`,r=await L.deleteAllowFailure(t,{headers:Zd(n)});if(r.statusCode!==200)throw Kd(r.statusCode,r.statusText,r.data);let i=JSON.parse(r.data);(!i||!i.ret||i.ret.code!==0)&&Rt(`delete provision failed: ${r.data}`)}function eL(...n){for(let e of n)try{xn.existsSync(e)&&xn.unlinkSync(e)}catch(t){Rt(`delete local sign file error: ${t.message}`)}}async function tL(n,e){let t=`${Y.BASE_URL}${Y.CERT_DOWNLOAD_URL_PATH}`,r=Zd(n),i={sourceUrls:e},o=await L.postAllowFailure(t,{headers:r,params:i});if(!o)throw Rt("get download list failed: response is null"),new Error(v.ADD_PROFILE_FAIL);if(o.statusCode!==200)throw Kd(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw Rt("download: The application does not exist"),new Error(s.ret?.msg||v.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function nL(n,e){if(!n||n.length===0)return!1;let t=n[0].newUrl;return await eo(t,e),!0}function rL(n,e,t,r,i){return iL(n,e),r=r||be.TARGET_FRIENDLY_NAME,i=i||"",oL(e,t,r,i),!0}function iL(n,e){if(e.lastIndexOf(be.CERT_BEGIN_HEADER)<0)throw new Error(v.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(be.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!n.includes(t))throw new Error(v.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}function oL(n,e,t,r){let i=n.matchAll(be.CERTIFICATE_PATTERN_GLOBAL),o=[],s=new Date;for(let c of i)try{let l=c[0],p=sL(l),g=new Date(p.validFrom),w=new Date(p.validTo);if(s<g||s>w){let E=`Certificate is not valid, Valid from ${g} to ${w}`;throw console.warn(`checkCertificateInValidityPeriod: ${E}`),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(!cL(e,t,r,o))throw new Error(v.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function sL(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new Jd(t);let r=hw.from(t,"base64");return new Jd(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}function aL(n){if(n.cert){let e=Ln.pki.publicKeyToPem(n.cert.publicKey);return qx(e).export({type:"spki",format:"der"})}if(n.asn1)try{let e=Ln.asn1.toDer(n.asn1).getBytes(),t=hw.from(e,"binary");return new Jd(t).publicKey.export({type:"spki",format:"der"})}catch(e){return Rt(`Failed to parse cert from asn1: ${e}`),null}return null}function cL(n,e,t,r){try{let i=Yx(n),o=Ln.asn1.fromDer(Ln.util.createBuffer(i)),c=Ln.pkcs12.pkcs12FromAsn1(o,t).getBags({bagType:Ln.pki.oids.certBag})[Ln.pki.oids.certBag]||[];for(let l of c){let p=l.attributes?.friendlyName?.[0];if(!p||p.toLowerCase()!==e.toLowerCase())continue;let g=aL(l);if(!g)continue;if(r.some(E=>{let O=E.publicKey.export({type:"spki",format:"der"});return g.equals(O)}))return!0}return!1}catch(i){let o=i instanceof Error?i.message:String(i);return Rt(`Failed to process P12 file: ${n}, error: ${o}`),!1}}function Zd(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var ww="https://developer.huawei.com",lL={"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"},dL="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function uL(n){let e=lL[n];return e?`${ww}${e}`:void 0}function pL(){return`${ww}${dL}`}var fL={"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 yw(n,e){return(fL[n]??n).replace(/\{(\d+)\}/g,(r,i)=>String(e[Number(i)]??""))}function mL(n){return Array.from(n).join(", ")}function vw(n,e){if(n.size===0)return;let t=cn.getAclPermissionInfos(e),r=new Set;for(let g of t)n.has(g.permissionName)&&r.add(g);for(let g of r){let w=uL(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=pL(),a=yw("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=o.size>0?Array.from(o).join(", ")+".":"",p=yw("acl.permissions.warn",[mL(i),l,c]);console.log(p)}var Ba=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(K.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:K.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import hL from"fs";import Sw from"path";var Wa=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=Sw.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");if(!hL.existsSync(r)){let i=Sw.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 Ga=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await te.getUserInfo()}catch(e){return m(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await te.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(K.LOGIN_REQUIRED)}catch(t){return m(`[EnvCheck] Login check failed: ${t.message}`),e(K.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(K.TEAM_INFO_FAILED);try{if((await $t()).teamList.length>0)return{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Team API error: ${r.message}`),e(K.TEAM_INFO_FAILED)}return m("[EnvCheck] No teams found for current user"),e(K.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(K.REALNAME_REQUIRED):t.isRealName!==!0?(m("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(K.REALNAME_REQUIRED)):{passed:!0,message:""}:e(K.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let r=e??"";try{let i=await $t();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(K.REGION_CHINA_ONLY):{passed:!0,message:""}:(m("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(K.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function gL(n){try{let{teamList:e}=await $t();if(e.length>0)return e[0].id}catch(e){m(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function yL(n){let e=await te.getUserInfo(),t=await te.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await gL(e.userId);if(!r)throw new Error("No team found");let i={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await Ua(i)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var Va=class{constructor(e){this.toolProvider=e}toolProvider;async checkDevice(e,t){try{let r=await yL(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 Q.from(this.toolProvider).listDevices();return o.length===0?(m("[EnvCheck] Scenario 4 Device check: no local devices found"),e(K.DEVICE_MISSING)):o.some(a=>yn(a.serial))?{passed:!0,message:""}:(m("[EnvCheck] Scenario 4 Device check: local device found but not an emulator"),e(K.DEVICE_MISSING))}catch(r){return m(`[EnvCheck] Scenario 4 Device check failed: ${r.message}`),e(K.DEVICE_DETECT_FAILED)}}};var za=class{projectChecker=new Ba;toolchainChecker=null;authChecker=new Ga;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 Wa(e),this.deviceChecker=new Va(e),!0}catch(e){throw m(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(K.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 SL(n){if(Qd.existsSync(n)){let e=Qd.readFileSync(n,"utf-8");return Ew.parse(e)}return{app:{signingConfigs:[],products:[]}}}function bL(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function EL(n){if(n.keyPwd===n.storePassword){let r=await an.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await an.encryptedPassword(n.keyPwd,n.p12FilePath),t=await an.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function PL(n,e,t){let r=bw.join(n,"build-profile.json5"),i=SL(r);bL(i);let o=t??"default",{keyPassword:s,storePassword:a}=await EL(e),c={name:o,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:s,profile:e.profileFilePath,signAlg:rt.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}),Qd.writeFileSync(r,Ew.stringify(i,null,2),"utf-8")}async function CL(n){let e=await te.getUserInfo(),t=await te.refreshToken();if(!e||!t)throw new Error("Failed to obtain login credentials. Run `devecocli auth login` again.");return{uid:e.userId??"",teamId:n.teamId??e.userId??"",accessToken:t.accessToken??""}}async function IL(n){let e=n.product||"default";await new za().preflight({productName:e,teamId:n.teamId}),console.log("Executing signature generate command");let r=await CL(n),i=await I.new(),{shouldRegenerate:o}=await ro.shouldRegenerate({force:n.force??!1,teamId:r.teamId,productName:n.product},i);if(!o){console.log(Xd("Signature generation completed successfully."));return}await AL(n,r,i),console.log(Xd("Signature generation completed successfully."))}async function AL(n,e,t){let r=await Hd(e,n.product),i=DL(n,e,r,t);i.allDeviceIds=await lw(e,t.hdcPath),await gw(e,i);let o=U.discover(process.cwd()).rootDir;await PL(o,r,n.product??"default"),console.log(Xd(`Signing config written to ${bw.join(o,"build-profile.json5")}`))}function DL(n,e,t,r){let i=process.cwd(),o=U.discover(i),s=Ha(o,r);return vw(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 Pw=new wL("signature").description("Generate application signature.");Pw.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 IL(n)}catch(e){console.error(vL(e.message)),process.exit(1)}});var Cw=Pw;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";kL();Z.name("devecocli").description("HarmonyOS application development command line tool").version("1.3.0-Test.9");Z.addCommand(Hu);Z.addCommand(np);Z.addCommand(dp);Z.addCommand(Ep);Z.addCommand(Jp);Z.addCommand(vf);Z.addCommand(Vf);Z.addCommand(Jf);Z.addCommand(sm);Z.addCommand(mm);Z.addCommand(Nm);Z.addCommand(jg);Z.addCommand(cy);Z.addCommand(jy);Z.addCommand(Cw);var eu=process.argv.slice(2);eu.length>=2&&eu[eu.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);function TL(n){let e=n;for(;e.parent&&e.parent!==Z;)e=e.parent;return e}var xL=new Set(["update","auth","serve"]);Z.hook("preAction",async(n,e)=>{let t=TL(e),r=Un();if(t.name()==="update")return;let i=new jt(Iw.join(Me(),"update")),o=Ft();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||xL.has(t.name())||await I.checkVersion()});Z.hook("postAction",async(n,e)=>{if(process.exitCode||Un()!=="off")return;await new qr(e).checkAndNotify()});Z.parseAsync(process.argv).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(RL(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});