@deveco-test/deveco-cli 1.3.0-Test.15 → 1.3.0-Test.16
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/README.md +3 -1
- package/SKILL.md +2 -2
- package/THIRD-PARTY-LICENSES +4 -4
- package/dist/cli.js +116 -104
- package/dist/internal/telemetry-upload-background.js +9 -0
- package/index.zip +0 -0
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,61 +1,71 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var cv=Object.defineProperty;var lv=(n,e)=>{for(var t in e)cv(n,t,{get:e[t],enumerable:!0})};import{bootstrap as NL}from"global-agent";import*as ac from"path";import{program as ae}from"commander";import{red as LL}from"colorette";import{Command as OS}from"commander";import{green as xc,red as Ip,yellow as Nc}from"colorette";import le from"fs";import*as W from"path";import Xt from"json5";import*as cc from"fs";import*as ve from"path";function h(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 o=Number.parseInt(r,10);if(!Number.isInteger(o)||o<=0)throw new Error(`${t} must be a positive integer`);return o}static getLastLines(e,t){return!t||t<=0?e:e.split(/\r?\n/).slice(-t).join(`
|
|
3
3
|
`)}static parseDurationToSeconds(e,t="value"){let o=e.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)([sm])?$/);if(!o)throw new Error(`${t} must be like 30s, 5m or 2.5m (only s/m supported).`);let i=o[1];if((o[2]??"s")==="s")return n.parsePositiveInteger(i,t);if(!/^\d+(?:\.\d)?$/.test(i))throw new Error(`${t} supports a maximum of 1 decimal place for minutes (e.g. 2.5m).`);let a=Number.parseFloat(i);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,o=new Date){if(!t&&!r)return e;let[i,s]=n.resolveTimeBounds(t,r,o),a=e.split(/\r?\n/),c=[],l=!1;for(let d of a){let g=n.extractTimestampFromLogLine(d,o);g&&(l=n.isWithinBounds(g,i,s)),l&&c.push(d)}return c.join(`
|
|
4
|
-
`)}static resolveTimeBounds(e,t,r){let o=e?new Date(r.getTime()-e*1e3):null,i=t?new Date(r.getTime()-t*1e3):null;return o&&i?o<i?[o,i]:[i,o]:o?[o,r]:i?[null,i]:[null,null]}static isWithinBounds(e,t,r){let o=e.getTime(),i=t?Math.floor(t.getTime()/1e3)*1e3:null,s=r?Math.floor(r.getTime()/1e3)*1e3+999:null;return!(i!==null&&o<i||s!==null&&o>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 o=t.getFullYear(),i=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",g=Number.parseInt(d.padEnd(3,"0").slice(0,3),10),w=new Date(o,i,s,a,c,l,g);return w.getTime()>t.getTime()+1440*60*1e3&&w.setFullYear(o-1),w}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static assertBundleNameStrict(e){if(e.length<7||e.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${e.length}`);if(e.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example").');let t=e.split(".");if(t.length<3)throw new Error("Bundle name must contain at least 3 dot-separated segments.");let r=/^[a-zA-Z0-9_]+$/;for(let o=0;o<t.length;o++){let i=t[o];if(!r.test(i))throw new Error(`Segment "${i}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(o===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.`)}}static assertModuleName(e){this.assertSafeName(e,"module name")}static assertAbilityName(e){this.assertSafeName(e,"ability name")}static assertSafeName(e,t){if(!/^[A-Za-z0-9_.]+$/.test(e))throw new Error(`Invalid ${t}: ${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 o=r.charCodeAt(0);return o<=n.ASCII_CONTROL_MAX||o===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(pe.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=pe.resolve(pe.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=pe.normalize(e),o=pe.relative(r,t);if(o.split(pe.sep)[0]===".."||pe.isAbsolute(o))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||pe.isAbsolute(e)}static isPathContained(e,t){let r=pe.resolve(t,e),o=pe.relative(t,r);return n.isPathEscaping(o)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){let r=n.isPathContained(e,t);if(!r.contained)return r;let o;try{o=$a.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let i=pe.resolve(o,e),s;try{s=$a.realpathSync(i)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${i}`}}return n.isPathContained(s,o)}};var G=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 o=U.dirname(t);if(o===t)break;t=o}throw new Error("Not in a valid project directory (project-level build-profile.json5 not found).")}static tryLoadProjectProfile(e){let t=U.join(e,"build-profile.json5");if(!re.existsSync(t))return null;try{let r=re.readFileSync(t,"utf-8"),o=Ht.parse(r);return o.app?o: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(i=>i.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let r=b.resolvePathWithinRoot(this.rootDir,t.srcPath),o=U.join(r,"src","main","module.json5");if(!re.existsSync(o))return"entry";try{let i=re.readFileSync(o,"utf-8");return Ht.parse(i)?.module?.type||"entry"}catch(i){return console.warn(`Warning: Failed to parse ${o}:`,i),"entry"}}findOwningModule(e){let t=U.normalize(e);for(let r of this.profile.modules){let o=U.normalize(U.join(this.rootDir,r.srcPath)),i=o+U.sep;if(t.startsWith(i)||t===o)return r.name}return null}getModuleProfile(e){let t=this.profile.modules.find(i=>i.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let r=b.resolvePathWithinRoot(this.rootDir,t.srcPath),o=U.join(r,"build-profile.json5");if(!re.existsSync(o))throw new Error(`Build profile for module '${e}' not found at ${o}.`);try{let i=re.readFileSync(o,"utf-8");return Ht.parse(i)}catch(i){throw new Error(`Failed to parse module build profile at ${o}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}getBundleName(){let e=U.join(this.rootDir,"AppScope","app.json5");if(re.existsSync(e))try{let t=re.readFileSync(e,"utf-8"),r=Ht.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=U.join(this.rootDir,"AppScope","app.json5");if(!re.existsSync(e))return!1;try{let t=re.readFileSync(e,"utf-8");return Ht.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 o=b.resolvePathWithinRoot(this.rootDir,r.srcPath),i=U.join(o,"src","main","module.json5");if(!re.existsSync(i))return"EntryAbility";try{let s=re.readFileSync(i,"utf-8"),c=Ht.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 ${i}:`,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(o=>o.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=b.resolvePathWithinRoot(this.rootDir,t.srcPath),o=U.join(r,"oh-package.json5");if(!re.existsSync(o))return[];let i=[];try{let s=re.readFileSync(o,"utf-8"),c=Ht.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=U.join(t.srcPath,d),P=b.resolvePathWithinRoot(this.rootDir,w),O=this.profile.modules.find(ne=>U.resolve(this.rootDir,ne.srcPath)===P);O&&i.push(O.name)}}catch(s){m(`Failed to get module dependencies: ${s instanceof Error?s.message:String(s)}`)}return i}collectNonHarDependentModuleList(e){let t=[],r=[],o=new Set;for(r.push(e),o.add(e);r.length>0;){let i=r.shift();this.getModuleType(i)!=="har"&&t.push(i);let a=this.getModuleDependencies(i);for(let c of a)o.has(c)||(r.push(c),o.add(c))}return t}resolveModuleMetadata(e,t,r){this.validateProduct(r);let o=this.profile.modules.find(l=>l.name===e);if(!o){let l=this.getRunnableModuleNames();throw new Error(`Module '${e}' not found. Available modules: ${l}`)}let i=this.getModuleType(e)==="shared",s=i?"hspName":"hapName",a=this.buildOutputPath(o.srcPath,r,["intermediates",i?"hsp_metadata":"hap_metadata",t,"output_metadata.json"]);if(!re.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:o,isShared:i,metadataPath:a,metadata:c}}findArtifactPath(e,t,r,o="default"){let{moduleNode:i,isShared:s,metadata:a}=this.resolveModuleMetadata(e,t,o),{packageName:c,isSigned:l}=a,d=c;if(!l){let P=this.getSignedHapName(c,i.srcPath,o,t);P&&(d=P)}let g=s?"-signed.hsp":"-signed.hap";if(!r&&!d.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(i.srcPath,o,["outputs",t,d]);if(!re.existsSync(w))throw new Error(`Generated package file not found in ${w}.`);return w}findRemoteHspPaths(e,t,r="default"){let{moduleNode:o,metadata:i}=this.resolveModuleMetadata(e,t,r),s=[],a=new Set;for(let{hspPath:c}of i.dependRemoteHsps){if(a.has(c))continue;a.add(c);let l=U.isAbsolute(c)?c:this.buildOutputPath(o.srcPath,r,["outputs",t,c]);if(!re.existsSync(l))throw new Error(`Remote HSP dependency not found: ${l}`);s.push(l)}return s}getSignedHapName(e,t,r,o){let i=null;if(e.endsWith("-unsigned.hap")?i=e.replace("-unsigned.hap","-signed.hap"):e.endsWith("-unsigned.hsp")&&(i=e.replace("-unsigned.hsp","-signed.hsp")),!i)return null;let s=this.buildOutputPath(t,r,["outputs",o,i]);return re.existsSync(s)?i:null}buildOutputPath(e,t,r){let o=b.resolvePathWithinRoot(this.rootDir,e),i=U.resolve(o,"build",t,...r);return b.ensurePathWithinRoot(this.rootDir,i)}collectRemoteHsps(e){return e.flatMap(t=>{let r=t.dependRemoteHsps;return Array.isArray(r)?r.filter(o=>!!(o.hspName&&o.hspPath)).map(o=>({hspName:o.hspName,hspPath:o.hspPath})):[]})}parseOutputMetadata(e,t){let r;try{let c=re.readFileSync(e,"utf-8");r=Ht.parse(c)}catch(c){throw new Error(`Failed to parse output metadata at ${e}: ${c instanceof Error?c.message:String(c)}`,{cause:c})}let o,i=!1,s=Array.isArray(r)?r:[r];for(let c of s)o||(o=c[t]),i||(i=c.isSigned===!0);if(!o)throw new Error(`Could not find ${t} in output_metadata.json at ${e}`);this.validatePackageName(o);let a=this.collectRemoteHsps(s);return{packageName:o,isSigned:i,dependRemoteHsps:a}}validatePackageName(e){let t=U.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 ru}from"child_process";import oe from"fs";import*as tt from"os";import*as S from"path";import Xd from"fs";import*as pi from"os";import*as ui from"path";import lw from"regedit";import{execFileSync as aw}from"child_process";import qd from"fs";import*as Yd from"os";import*as Ha from"path";import{compare as sw}from"semver";function zd(n,e){return sw(n,e)}function Kn(n,e){let t=Math.max(n.split(".").length,e.split(".").length);for(let r=0;r<t;r++){let o=Number(n.split(".")[r]??0)-Number(e.split(".")[r]??0);if(o)return o}return 0}function di(n,e){let t=Ha.join(n,"Contents","Info.plist");if(!qd.existsSync(t)){m(`[ToolProvider] Info.plist not found at: ${t}`);return}for(let[r,o]of[["/usr/libexec/PlistBuddy",["-c",`Print :${e}`,t]],["plutil",["-extract",e,"raw","-o","-",t]]])try{let i=aw(r,o,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(i&&!i.includes("Does Not Exist"))return i}catch{}}function cw(n){let e=di(n,"CFBundleShortVersionString");if(!e)return di(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[di(n,"CFBundleVersion"),di(n,"CFBundleGetInfoString")?.match(/DS-[\d.]+/)?.[0]];for(let o of r){let i=o?.split(".").at(-1)?.replace(new RegExp(`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`),"");if(i&&/^\d+$/.test(i))return`${e}.${i}`}return e}function St(n){if(Yd.platform()==="darwin")return cw(n);let e=Ha.join(n,"product-info.json");try{let t=JSON.parse(qd.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}function dw(n){return n.filter(e=>{try{return Xd.statSync(e).isDirectory()}catch{return!1}})}function uw(){let n=[];for(let e of[ui.join(pi.homedir(),"Applications"),"/Applications"])try{n.push(...Xd.readdirSync(e).filter(t=>t.endsWith(".app")&&t.toLowerCase().includes("deveco")).map(t=>ui.join(e,t)))}catch{}return n}function Jd(n){return new Promise((e,t)=>lw.list(n,(r,o)=>r?t(r):e(o)))}async function Kd(n,e,t){let o=((await Jd([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(o.length===0)return[];let i=await Jd(o);return o.flatMap(s=>{let a=i[s]?.values?.[t]?.value;return a?[a]:[]})}async function pw(){let n=[ui.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 Kd(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 Kd(e,()=>!0,""))}catch{}return n}async function Zd(){let n=pi.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"?uw():await pw(),t=dw(e).flatMap(r=>{let o=St(r);return o?(m(`[ToolProvider] ${r} => version ${o}`),[{root:r,version:o}]):(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,o)=>Kn(o.version,r.version)>0?o:r)}import*as Qd from"fs";import*as Ce from"path";function Ua(n,e){let t=Ce.relative(e,n);return t===""||!Ce.isAbsolute(t)&&!t.startsWith(`..${Ce.sep}`)&&t!==".."}function ut(n){let e=Ce.resolve(n),t=[],r=e;for(;;)try{let o=Qd.realpathSync(r);return t.length===0?o:Ce.join(o,...t.reverse())}catch(o){if(o.code!=="ENOENT")throw o;let i=Ce.dirname(r);if(i===r)return e;t.push(Ce.basename(r)),r=i}}function fi(n,e){let t=ut(e),r=ut(n);return Ua(r,t)?r:null}function Ba(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function mi(n){let e=Ba(n);if(!e)throw new Error("Path must not be empty.");return ut(e)}var Jr={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},hi={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 fe={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"},z={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"},Pn={ALGORITHM:"aes-256-gcm",KEY_LENGTH:32,IV_LENGTH:12,KEK_VERSIONS:["kek-v1","kek-v2","kek-v3"]},Kr={baseUrl:z.LOGIN_URL,authUrl:z.AUTH_APPLY_PATH,tempTokenCheckUrl:z.TEMP_TOKEN_CHECK_PATH,jwtTokenCheckUrl:z.JWT_TOKEN_CHECK_PATH,successRedirectUrl:z.LOGIN_SUCCESS_PATH,failedRedirectUrl:z.LOGIN_FAILED_PATH,logoutUrl:z.LOGOUT_PATH,agcTeamListUrl:z.AGC_TEAM_LIST_URL,appId:fe.APP_ID,timeout:Jr.LOGIN_TIMEOUT_MS,countryCode:"CN"};var Wa="https://matrix.openharmony.cn",He={TAGS_API_URL:`${Wa}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${Wa}/api/registry/skill/skills`,SKILL_API_BASE:`${Wa}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,DEFAULT_MAX_PAGES:100,SUCCESS_CODE:"20000"},Qe={"trae-cn":{path:".trae-cn/skills",displayName:"trae-cn"},opencode:{path:".config/opencode/skills",displayName:"opencode"},deveco:{path:".config/deveco/skills",displayName:"deveco"},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"},atomcode:{path:".atomcode/skills",displayName:"atomcode"}};import{homedir as Et}from"os";import Me from"path";var pt="deveco-mcp";var Ut={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:Me.join(Et(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:Me.join(process.platform==="win32"?Me.join(process.env.APPDATA??Me.join(Et(),"AppData","Roaming"),"Trae CN","User"):Me.join(Et(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:Me.join(Et(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:Me.join(Et(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:Me.join(process.platform==="win32"?Me.join(process.env.APPDATA??Me.join(Et(),"AppData","Roaming"),"Qoder","SharedClientCache"):Me.join(Et(),"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:Me.join(Et(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:Me.join(Et(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function tu(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function eu(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function nu(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function gi(n,e){return n.format==="opencode"?tu(e):n.format==="claude-code"||n.format==="codex"?eu(e):nu(e)}var et={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var Va="https://developer.huawei.com/consumer/cn/download/";var fw=/^#\s*Version:\s*(\S+)/,mw="26.0.0.810";function hw(n){try{let e=JSON.parse(oe.readFileSync(n,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch(e){m(`[ToolProvider] Failed to parse API level from ${n}: ${e instanceof Error?e.message:String(e)}`);return}}function gw(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,o,i,s,a,c,l,d){this._sourceType=e;this._toolchainRoot=t;this._devecoStudioPath=r;this._nodePath=o;this._ohpmJsPath=i;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 Kn(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.0.0"){this.assertStudio(),n.assertMinimumVersion(St(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,o,i){if(!e)throw new Error(`Failed to determine ${t} version from ${r} at ${i}`);if(!/^\d+(?:\.\d+){1,3}$/.test(e))throw new Error(`Invalid ${t} version "${e}" from ${r} at ${i}`);if(Kn(e,o)<0)throw new Error(`The detected ${t} version is ${e}, which is below the minimum required version ${o}. Upgrade before using deveco-cli:
|
|
5
|
-
|
|
4
|
+
`)}static resolveTimeBounds(e,t,r){let o=e?new Date(r.getTime()-e*1e3):null,i=t?new Date(r.getTime()-t*1e3):null;return o&&i?o<i?[o,i]:[i,o]:o?[o,r]:i?[null,i]:[null,null]}static isWithinBounds(e,t,r){let o=e.getTime(),i=t?Math.floor(t.getTime()/1e3)*1e3:null,s=r?Math.floor(r.getTime()/1e3)*1e3+999:null;return!(i!==null&&o<i||s!==null&&o>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 o=t.getFullYear(),i=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",g=Number.parseInt(d.padEnd(3,"0").slice(0,3),10),w=new Date(o,i,s,a,c,l,g);return w.getTime()>t.getTime()+1440*60*1e3&&w.setFullYear(o-1),w}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static assertBundleNameStrict(e){if(e.length<7||e.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${e.length}`);if(e.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example").');let t=e.split(".");if(t.length<3)throw new Error("Bundle name must contain at least 3 dot-separated segments.");let r=/^[a-zA-Z0-9_]+$/;for(let o=0;o<t.length;o++){let i=t[o];if(!r.test(i))throw new Error(`Segment "${i}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(o===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.`)}}static assertModuleName(e){this.assertSafeName(e,"module name")}static assertAbilityName(e){this.assertSafeName(e,"ability name")}static assertSafeName(e,t){if(!/^[A-Za-z0-9_.]+$/.test(e))throw new Error(`Invalid ${t}: ${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 o=r.charCodeAt(0);return o<=n.ASCII_CONTROL_MAX||o===n.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let r=`'${e.replace(/'/g,"'\\''")}'`;return h(`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(ve.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=ve.resolve(ve.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=ve.normalize(e),o=ve.relative(r,t);if(o.split(ve.sep)[0]===".."||ve.isAbsolute(o))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||ve.isAbsolute(e)}static isPathContained(e,t){let r=ve.resolve(t,e),o=ve.relative(t,r);return n.isPathEscaping(o)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){let r=n.isPathContained(e,t);if(!r.contained)return r;let o;try{o=cc.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let i=ve.resolve(o,e),s;try{s=cc.realpathSync(i)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${i}`}}return n.isPathContained(s,o)}};import Yu from"crypto";import vt from"fs";import yc from"os";import ur from"path";import Cv from"https";var Pu={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};import*as _ from"fs";import*as Oi from"path";import q from"fs";import*as ki from"os";import*as O from"path";import uv from"json5";var lc="Huawei";var Au=3;function Ti(n){if(!q.existsSync(n)||!q.statSync(n).isDirectory())return!1;let e=q.existsSync(O.join(n,"build-profile.json5")),t=q.existsSync(O.join(n,"hvigorfile.js"))||q.existsSync(O.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=q.readFileSync(O.join(n,"build-profile.json5"),"utf-8");return uv.parse(r).app!==void 0}catch{return!1}}function dc(n,e,t){if(e>=t)return null;let r=pv(n),o=mv(r);if(o)return o;for(let i of r){let s=dc(i,e+1,t);if(s)return s}return null}function pv(n){try{let e=q.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(O.join(n,r.name));return t}catch{return[]}}function mv(n){for(let e of n)if(Ti(e))return e;return null}function xt(n){if(!n||n.trim()==="")return null;let e=O.resolve(n),t;try{t=q.realpathSync(e)}catch{t=e}if(!q.existsSync(t))return null;if(Ti(t))return t;let r=t;for(let o=1;o<=3;o++){let i=O.dirname(r);if(i===r)break;if(Ti(i))return i;r=i}if(q.statSync(t).isDirectory()){let o=dc(t,0,Au);if(o)return o}return null}function Ri(n){if(!n||n.trim()==="")return null;let e=O.resolve(n),t;try{t=q.realpathSync(e)}catch{t=e}return!q.existsSync(t)||!q.statSync(t).isDirectory()?null:Ti(t)?t:dc(t,0,Au)}var Cu="DevEco Studio";function Du(){if(process.platform==="win32"){let n=[O.join("C:\\Program Files",lc,Cu),O.join("C:\\Program Files (x86)",lc,Cu)];return Iu(n)}if(process.platform==="darwin"){let n=["/Applications/DevEco Studio.app",O.join(process.env.HOME??"","Applications","DevEco Studio.app")];return Iu(n)}return null}function Iu(n){for(let e of n)if(q.existsSync(e))return e;return null}function fo(n,e){let t=e?O.join("standardIndex","index.js"):"index.js";return q.existsSync(O.join(n,"ace-server"))?O.join(n,"ace-server","out",t):O.join(n,"out",t)}function xi(n){return q.existsSync(fo(n,!0))}var fv=[".idea",".deveco","cxx","compile_commands.json"];function ho(n){return O.join(n,...fv)}function ku(n){return new Promise(e=>setTimeout(e,n))}var hv=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function _n(n){let e=O.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&hv.has(e)}function Ni(n){return O.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function fe(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function gv(n){return fe(n)}function Fn(n){let e=gv(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function Yt(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??O.join(ki.homedir(),"AppData","Local");return O.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?O.join(ki.homedir(),"Library","Logs","devecocli-mcp-server"):O.join(ki.homedir(),".local","share","devecocli-mcp-server","logs")}function Tu(n,e){let t=yv(e),r=wv(t,n);if(r!==null)return r;let o=Date.now(),s=`${n.replace(/:/g,"\\:")}=${o}`,a=vv(t,n,s);return Sv(e,a),o}function yv(n){let e;try{e=q.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function wv(n,e){for(let t of n){let r=t.indexOf("=");if(r<=0||t.slice(0,r).replace(/\\:/g,":")!==e)continue;let i=parseInt(t.slice(r+1),10);return Number.isFinite(i)&&i>0?i:null}return null}function vv(n,e,t){let r=!1,o=n.map(i=>{if(r)return i;let s=i.indexOf("=");return s<=0?i:i.slice(0,s).replace(/\\:/g,":")===e?(r=!0,t):i});return r||o.push(t),o}function Sv(n,e){try{q.mkdirSync(O.dirname(n),{recursive:!0})}catch{}try{q.writeFileSync(n,e.join(`
|
|
5
|
+
`)+`
|
|
6
|
+
`,"utf8")}catch{}}function uc(n,e,t="[Cleanup]"){try{let r=O.dirname(n);if(!q.existsSync(r))return;let o=Date.now();for(let i of q.readdirSync(r,{withFileTypes:!0}))i.isDirectory()&&bv(O.join(r,i.name),o,e,t)}catch{}}function bv(n,e,t,r){try{let{mtimeMs:o}=q.statSync(n);if(e-o<=t)return;q.rmSync(n,{recursive:!0,force:!0});let i=Math.floor((e-o)/1e3);console.error(`${r} Removed expired dir (age ${Math.floor(i/86400)}d ${Math.floor(i%86400/3600)}h): ${n}`)}catch(o){console.error(`${r} Failed to remove expired dir ${n}: ${o}`)}}var Ru="mcp-server.log",Ev="mcp-server",Pv={maxSize:10*1024*1024,maxFiles:4},pc=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={...Pv,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=Yt(),this.currentLogFile=Oi.join(this.logDir,Ru),_.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"),o=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${o}`}getRotatedFileName(e,t){return Oi.join(this.logDir,`${Ev}-${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 o of e)if(o===Ru||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(o)){let i=Oi.join(this.logDir,o),s=_.statSync(i);t.push({name:o,mtime:s.mtime,path:i})}t.sort((o,i)=>i.mtime.getTime()-o.mtime.getTime());let r=1+this.rotationOptions.maxFiles;for(let o=r;o<t.length;o++)try{_.unlinkSync(t[o].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 o=this.rotationOptions.maxFiles-1;o>=1;o--){let i=this.getRotatedFileName(e,o),s=this.getRotatedFileName(e,o+1);this.fileExists(i)&&_.renameSync(i,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 o=r.map(c=>c instanceof Error?`${c.name}: ${c.message}`:typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),i=o?`${t} ${o}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] ${i}
|
|
7
|
+
`;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}},Ye=null;function jn(n=!1){Ye&&Ye.dispose(),Ye=new pc(n)}function xu(){Ye&&(Ye.dispose(),Ye=null)}function Nu(){Ye&&Ye.flush()}function Lu(){return Ye?.getLogFilePath()??null}function Ou(){return Ye?.getLogDirectory()??null}function Li(){return Ye||jn(!1),Ye}var f={debug:(n,...e)=>Li().debug(n,...e),info:(n,...e)=>Li().info(n,...e),warn:(n,...e)=>Li().warn(n,...e),error:(n,...e)=>Li().error(n,...e)};var Mi=class n{static DEBUG=!0;static ENDPOINT=Pu.devecoApiTraceUpload;static SENDER="deveco-cli";async upload(e,t){let r={"Content-Type":"application/json",sender:n.SENDER,deviceid:t.replace(/-/g,""),"Content-Length":String(Buffer.byteLength(e,"utf8"))};n.log(`upload request: URL=${n.ENDPOINT}`);try{let{code:o,body:i}=await this.httpPost(n.ENDPOINT,r,Buffer.from(e,"utf8"),6e4);return n.log(`upload response: status=${o}, body=${i}`),n.isSuccess(i)}catch(o){return n.log(`upload failed: ${o instanceof Error?o.message:String(o)}`),!1}}static isSuccess(e){try{let t=JSON.parse(e),r=t?.code??t?.errorCode;return String(r)==="200"}catch{return!1}}async httpPost(e,t,r,o){let i=new URL(e);return new Promise((s,a)=>{let c=Cv.request({protocol:i.protocol,hostname:i.hostname,port:i.port||(i.protocol==="https:"?443:80),path:i.pathname+i.search,method:"POST",headers:t,timeout:o},l=>{let d=[];l.on("data",g=>d.push(g)),l.on("end",()=>{s({code:l.statusCode??0,body:Buffer.concat(d).toString("utf8")})})});c.on("timeout",()=>{c.destroy(new Error("request timeout"))}),c.on("error",a),c.write(r),c.end()})}static log(e){n.DEBUG&&f.info("[TRACE]"+e)}};var Mu={identity:n=>n,camelCase:n=>n,snakeCase:n=>n.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()},mc=class{constructor(e={}){this.config=e}config;serialize(e){let t=this.transform(e);return this.config.pretty?JSON.stringify(t,null,2):JSON.stringify(t)}toObject(e){return this.transform(e)}transform(e){if(e==null)return e;if(Array.isArray(e))return e.map(i=>this.transform(i));if(typeof e!="object")return e;let t=this.config.namingStrategy??Mu.identity,r=this.config.fieldNames??{},o={};for(let[i,s]of Object.entries(e)){let a=r[i]??t(i);o[a]=this.transform(s)}return o}},_u=new mc({namingStrategy:Mu.snakeCase,fieldNames:{}});import go from"crypto";import _i from"fs";import Iv from"path";var Fi="aes-256-gcm",Av=12,Dv="deveco-cli-trace-file",kv="trace-file-secret",ju=32;function Fu(n){try{let e=_i.readFileSync(n,"utf8").trim();return e&&Buffer.from(e,"base64").length===ju?e:null}catch{return null}}function $u(n){let e=Iv.join(n,kv),t=Fu(e);if(t)return fc(t);let r=go.randomBytes(ju).toString("base64");try{_i.mkdirSync(n,{recursive:!0});try{_i.writeFileSync(e,r,{flag:"wx"})}catch{let o=Fu(e);if(o)return fc(o);_i.writeFileSync(e,r)}}catch{}return fc(r)}function fc(n){return go.createHash("sha256").update(Dv).update(n).digest()}function hc(n,e){let t=go.randomBytes(Av),r=go.createCipheriv(Fi,e,t),o=Buffer.concat([r.update(n,"utf8"),r.final()]),i={version:1,algorithm:Fi,ciphertext:o.toString("base64"),iv:t.toString("base64"),authTag:r.getAuthTag().toString("base64")};return JSON.stringify(i)}function Hu(n,e){let t;try{t=JSON.parse(n)}catch{return null}if(!Tv(t))return n;try{let r=go.createDecipheriv(Fi,e,Buffer.from(t.iv,"base64"));return r.setAuthTag(Buffer.from(t.authTag,"base64")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"base64")),r.final()]).toString("utf8")}catch{return null}}function Tv(n){if(!n||typeof n!="object")return!1;let e=n;return e.version===1&&e.algorithm===Fi&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}import Uu from"fs";import Rv from"path";var dr=300*1e3;function Kt(){let n=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return n==="1"||n==="true"}var xv="upload-state.json";function Bu(n){return Rv.join(n,xv)}function Nv(){return{firstEventAt:null,lastUploadAt:null}}function gc(n){try{let e=Uu.readFileSync(Bu(n),"utf8"),t=JSON.parse(e);return{firstEventAt:typeof t.firstEventAt=="number"?t.firstEventAt:null,lastUploadAt:typeof t.lastUploadAt=="number"?t.lastUploadAt:null}}catch{return Nv()}}function Wu(n,e){try{Uu.writeFileSync(Bu(n),JSON.stringify(e),"utf8")}catch{}}function Vu(n){let e=gc(n);e.firstEventAt===null&&(e.firstEventAt=Date.now(),Wu(n,e))}function Gu(n){let e=gc(n);e.lastUploadAt=Date.now(),e.firstEventAt=null,Wu(n,e)}function zu(n,e=Date.now()){let t=gc(n);return t.firstEventAt===null?!1:e-t.firstEventAt>=dr}import Lv from"crypto";import ji from"fs";import Ov from"path";var Mv="install-id";function _v(n){return Ov.join(n,Mv)}function qu(n){try{let e=ji.readFileSync(n,"utf8").trim();return Fv(e)?e:null}catch{return null}}function Fv(n){return/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(n)}function Ju(n){let e=_v(n),t=qu(e);if(t)return t;let r=Lv.randomUUID();try{ji.mkdirSync(n,{recursive:!0});try{ji.writeFileSync(e,r,{flag:"wx"})}catch{let o=qu(e);if(o)return o;ji.writeFileSync(e,r)}}catch{}return r}var yo=class n{static MAX_BATCH=200;static MAX_PAYLOAD_BYTES=Math.floor(1.7*1024*1024);static TRACE_OS_VERSION="1.0";static COUNTRY_CODE="CN";static EVENT_PREFIX="devecocli_";uploader=new Mi;storageDir="";failedDir="";installId="";disabled=Kt();traceFileKey=Buffer.alloc(0);sessionId=Yu.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;constructor(){f.info(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=ur.join(e,"failed"),this.cliVersion="1.3.0-Test.16",this.nodeVersion=process.version,this.installId=Ju(e).replace(/-/g,""),this.traceFileKey=$u(e),vt.mkdirSync(e,{recursive:!0}),vt.mkdirSync(this.failedDir,{recursive:!0}),f.info(`[telemetry] init: dir=${e}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(e){this.devecoStudioVersion=e,f.info(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,f.info(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,f.info(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");if(f.info(`[telemetry] track: ${e.event}`),!t){await this.record(e,0,!0,null),f.info(`[telemetry] track recorded: ${e.event} (no measurement)`);return}if(typeof t!="function"){let i=t;await this.record(e,i.duration_ms,i.success,i.error_code),f.info(`[telemetry] track recorded: ${e.event} (measurement: duration=${i.duration_ms}ms, success=${i.success}, code=${i.error_code})`);return}let r=t,o=Date.now();try{let i=await r(),s=Date.now()-o;return await this.record(e,s,!0,null),f.info(`[telemetry] track success: ${e.event}, duration=${s}ms`),i}catch(i){let s=Date.now()-o,a=this.toErrorCode(i);throw await this.record(e,s,!1,a),f.info(`[telemetry] track failed: ${e.event}, duration=${s}ms, code=${a}`),i}}async record(e,t,r,o){let i=this.buildTraceEvent(e,t,r,o);try{let s=hc(JSON.stringify(i),this.traceFileKey);await vt.promises.appendFile(this.currentFile(),s+`
|
|
8
|
+
`,"utf8"),f.info(`[telemetry] event persisted: ${i.properties.trace_uuid}`),Vu(this.storageDir)}catch(s){f.error("[telemetry] track write error:",s)}}buildTraceEvent(e,t,r,o){let i=`${n.EVENT_PREFIX}${e.event}`,s=_u.toObject(e);return s&&typeof s=="object"&&delete s.event,{countryCode:n.COUNTRY_CODE,event:i,eventtime:String(Date.now()),properties:{uid:this.installId,trace_uuid:Yu.randomUUID(),trace_os_version:n.TRACE_OS_VERSION,os_arch:this.resolveOsArch(),action:i,trace_os_name:this.resolveOsName(),version:`${this.cliVersion}_${this.resolveOsSuffix()}`,deveco_studio_version:this.formatVersion(this.devecoStudioVersion),command_line_version:this.formatVersion(this.cltVersion),source_type:this.sourceType,session_id:this.sessionId,node_version:this.nodeVersion,duration_ms:t,success:r,error_code:o,event_detail:s}}}toErrorCode(e){return e instanceof Error?e.code??e.name:"UnknownError"}resolveOsArch(){let e=yc.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=yc.release().split(".");return(parseInt(e[e.length-1],10)||0)>=22e3?"Windows 11":"Windows 10"}case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}resolveOsSuffix(){switch(process.platform){case"win32":return"windows";case"darwin":return yc.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}formatVersion(e){return e?`${e}_${this.resolveOsSuffix()}`:""}dateString(){let e=new Date,t=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0");return`${e.getFullYear()}-${t}-${r}`}currentFile(){return ur.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){f.info("[telemetry] scheduler not started (telemetry disabled)");return}f.info(`[telemetry] scheduler started (first flush in ${dr/1e3}s, then every ${dr/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(e=>f.error("[telemetry] flush error:",e)),this.intervalTimer=setInterval(()=>{this.flush().catch(e=>f.error("[telemetry] flush error:",e))},dr)},dr)}stopScheduler(){this.initialTimer&&(clearTimeout(this.initialTimer),this.initialTimer=null),this.intervalTimer&&(clearInterval(this.intervalTimer),this.intervalTimer=null),f.info("[telemetry] scheduler stopped")}async flush(){if(this.disabled)return!0;if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");f.info("[telemetry] flush start");let e=await this.listPendingFiles();if(e.length===0)return f.info("[telemetry] flush: no event files"),!0;f.info(`[telemetry] flush: ${e.length} file(s) pending`);let t=!0;for(let r of e)await this.flushFile(r)||(t=!1);return f.info(`[telemetry] flush done, allOk=${t}`),Gu(this.storageDir),t}async listPendingFiles(){let e;try{e=await vt.promises.readdir(this.storageDir)}catch{return[]}return e.filter(t=>t.startsWith("telemetry-")&&t.endsWith(".txt")).map(t=>ur.join(this.storageDir,t)).sort()}async flushFile(e){let t=e+".pending";try{await vt.promises.rename(e,t),f.info(`[telemetry] flush: renamed ${ur.basename(e)} \u2192 pending`)}catch{return!1}let r;try{r=await vt.promises.readFile(t,"utf8")}catch{return!1}let o=r.split(`
|
|
9
|
+
`).map(a=>a.trim()).filter(Boolean),i=[],s=0;for(let a of o){let c=Hu(a,this.traceFileKey);if(c===null){s++;continue}i.push(c)}if(s>0&&f.warn(`[telemetry] flush: skipped ${s} undecryptable line(s)`),i.length===0){try{await vt.promises.unlink(t)}catch{}return!0}return this.uploadInBatches(t,i)}async uploadInBatches(e,t){let r=0;for(;r<t.length;){let o=r,i=[],s=16;for(;r<t.length&&i.length<n.MAX_BATCH;){let d=t[r],g=Buffer.byteLength(d,"utf8")+1;if(i.length>0&&s+g>n.MAX_PAYLOAD_BYTES)break;i.push(d),s+=g,r++}let a=this.buildPayloadItems(i),c=JSON.stringify(a);f.info(`[telemetry] flush: uploading batch (${a.length} events, ${Buffer.byteLength(c,"utf8")} bytes)`);let l=!1;try{l=await this.uploader.upload(c,this.installId)}catch(d){f.error("[telemetry] build/upload error:",d)}if(!l){let d=t.slice(o).join(`
|
|
10
|
+
`)+`
|
|
11
|
+
`;return await this.moveToFailed(e,d),!1}}try{await vt.promises.unlink(e)}catch{}return f.info("[telemetry] flush: file done, pending removed"),!0}buildPayloadItems(e){let t=[];for(let r of e)try{let o=JSON.parse(r);t.push({action:o.event,detail:JSON.stringify(o.properties),timestamp:Number(o.eventtime)||Date.now()})}catch{}return t}async moveToFailed(e,t){let r=ur.basename(e,".pending"),o=ur.join(this.failedDir,r);f.info(`[telemetry] moving to failed: ${r}`);try{let i=t.split(`
|
|
12
|
+
`).filter(Boolean).map(s=>hc(s,this.traceFileKey)).join(`
|
|
13
|
+
`)+`
|
|
14
|
+
`;await vt.promises.appendFile(o,i,"utf8")}catch(i){f.error("[telemetry] move to failed error:",i);return}try{await vt.promises.unlink(e)}catch{}}};var k=new yo;import{spawn as jv}from"child_process";import{existsSync as $v}from"fs";import{dirname as Hv,join as Uv}from"path";import{fileURLToPath as Bv}from"url";function Wv(){let n=Hv(Bv(import.meta.url)),e=Uv(n,"internal","telemetry-upload-background.js");return $v(e)?e:null}function wc(n){if(Kt()||!zu(n))return;let e=Wv();if(!e){f.warn("[telemetry] background upload script not found, skipping spawn");return}try{jv(process.execPath,[e],{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1",DEVECO_CLI_TELEMETRY_UPLOAD:"1"}}).unref(),f.info("[telemetry] background upload process spawned")}catch(t){f.warn("[telemetry] failed to spawn background upload:",t)}}var v=class extends Error{traceMessage;constructor(e,t,r){super(e,r),this.name="TraceError",this.traceMessage=t??e}};function ce(n){if(n instanceof v)return n.traceMessage;if(n instanceof Error){let e=n.code;return typeof e=="string"&&e!==""?e:n.name}return"UnknownError"}var E={CommandExecuted:"Command_executed",McpToolCall:"serve_mcp",SkillOperation:"skills",Init:"mcp_config_operation",SkillConfigOperation:"skill_config_operation",DocOperation:"docs",ServeLsp:"serve_lsp",CheckCommand:"check"};var J=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 o=W.dirname(t);if(o===t)break;t=o}throw new Error("Not in a valid project directory (project-level build-profile.json5 not found).")}static tryLoadProjectProfile(e){let t=W.join(e,"build-profile.json5");if(!le.existsSync(t))return null;try{let r=le.readFileSync(t,"utf-8"),o=Xt.parse(r);return o.app?o: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(i=>i.name===e);if(!t)throw new v(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let r=C.resolvePathWithinRoot(this.rootDir,t.srcPath),o=W.join(r,"src","main","module.json5");if(!le.existsSync(o))return"entry";try{let i=le.readFileSync(o,"utf-8");return Xt.parse(i)?.module?.type||"entry"}catch(i){return console.warn(`Warning: Failed to parse ${o}:`,i),"entry"}}findOwningModule(e){let t=W.normalize(e);for(let r of this.profile.modules){let o=W.normalize(W.join(this.rootDir,r.srcPath)),i=o+W.sep;if(t.startsWith(i)||t===o)return r.name}return null}getModuleProfile(e){let t=this.profile.modules.find(i=>i.name===e);if(!t)throw new v(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let r=C.resolvePathWithinRoot(this.rootDir,t.srcPath),o=W.join(r,"build-profile.json5");if(!le.existsSync(o))throw new v(`Build profile for module '${e}' not found at ${o}.`,"Build profile for module not found at ${profilePath}.");try{let i=le.readFileSync(o,"utf-8");return Xt.parse(i)}catch(i){throw new Error(`Failed to parse module build profile at ${o}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}getBundleName(){let e=W.join(this.rootDir,"AppScope","app.json5");if(le.existsSync(e))try{let t=le.readFileSync(e,"utf-8"),r=Xt.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=W.join(this.rootDir,"AppScope","app.json5");if(!le.existsSync(e))return!1;try{let t=le.readFileSync(e,"utf-8");return Xt.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 o=C.resolvePathWithinRoot(this.rootDir,r.srcPath),i=W.join(o,"src","main","module.json5");if(!le.existsSync(i))return"EntryAbility";try{let s=le.readFileSync(i,"utf-8"),c=Xt.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 ${i}:`,s),"EntryAbility"}}validateProduct(e){if(!/^[\da-zA-Z_-]+$/.test(e))throw new v(`Invalid product name '${e}'. Product names must only contain letters, digits, underscores, and hyphens.`,"Invalid product name.");if(!this.profile.app.products?.some(r=>r.name===e)){let r=this.profile.app.products?.map(o=>o.name).join(", ")||"none";throw new v(`Product '${e}' not found in project configuration. Available products: ${r}`,"Productnot found in project configuration.")}}getModuleDependencies(e){let t=this.profile.modules.find(s=>s.name===e);if(!t)return[];let r=C.resolvePathWithinRoot(this.rootDir,t.srcPath),o=W.join(r,"oh-package.json5");if(!le.existsSync(o))return[];let i=[];try{let s=le.readFileSync(o,"utf-8"),c=Xt.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=W.join(t.srcPath,d),b=C.resolvePathWithinRoot(this.rootDir,w),$=this.profile.modules.find(ne=>W.resolve(this.rootDir,ne.srcPath)===b);$&&i.push($.name)}}catch(s){h(`Failed to get module dependencies: ${s instanceof Error?s.message:String(s)}`)}return i}collectNonHarDependentModuleList(e){let t=[],r=[],o=new Set;for(r.push(e),o.add(e);r.length>0;){let i=r.shift();this.getModuleType(i)!=="har"&&t.push(i);let a=this.getModuleDependencies(i);for(let c of a)o.has(c)||(r.push(c),o.add(c))}return t}resolveModuleMetadata(e,t,r){this.validateProduct(r);let o=this.profile.modules.find(l=>l.name===e);if(!o){let l=this.getRunnableModuleNames();throw new v(`Module '${e}' not found. Available modules: ${l}`,"Module not found.")}let i=this.getModuleType(e)==="shared",s=i?"hspName":"hapName",a=this.buildOutputPath(o.srcPath,r,["intermediates",i?"hsp_metadata":"hap_metadata",t,"output_metadata.json"]);if(!le.existsSync(a))throw new v(`Build metadata not found for module '${e}' at ${a}. Build the project first.`,"Build metadata not found for module. Build the project first.");let c=this.parseOutputMetadata(a,s);return{moduleNode:o,isShared:i,metadataPath:a,metadata:c}}findArtifactPath(e,t,r,o="default"){let{moduleNode:i,isShared:s,metadata:a}=this.resolveModuleMetadata(e,t,o),{packageName:c,isSigned:l}=a,d=c;if(!l){let b=this.getSignedHapName(c,i.srcPath,o,t);b&&(d=b)}let g=s?"-signed.hsp":"-signed.hap";if(!r&&!d.endsWith(g))throw new v(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`,"Target device is a real device, but the artifact is not signed.");let w=this.buildOutputPath(i.srcPath,o,["outputs",t,d]);if(!le.existsSync(w))throw new v(`Generated package file not found in ${w}.`,"Generated package file not found.");return w}findRemoteHspPaths(e,t,r="default"){let{moduleNode:o,metadata:i}=this.resolveModuleMetadata(e,t,r),s=[],a=new Set;for(let{hspPath:c}of i.dependRemoteHsps){if(a.has(c))continue;a.add(c);let l=W.isAbsolute(c)?c:this.buildOutputPath(o.srcPath,r,["outputs",t,c]);if(!le.existsSync(l))throw new v(`Remote HSP dependency not found: ${l}`,"Remote HSP dependency not found.");s.push(l)}return s}getSignedHapName(e,t,r,o){let i=null;if(e.endsWith("-unsigned.hap")?i=e.replace("-unsigned.hap","-signed.hap"):e.endsWith("-unsigned.hsp")&&(i=e.replace("-unsigned.hsp","-signed.hsp")),!i)return null;let s=this.buildOutputPath(t,r,["outputs",o,i]);return le.existsSync(s)?i:null}buildOutputPath(e,t,r){let o=C.resolvePathWithinRoot(this.rootDir,e),i=W.resolve(o,"build",t,...r);return C.ensurePathWithinRoot(this.rootDir,i)}collectRemoteHsps(e){return e.flatMap(t=>{let r=t.dependRemoteHsps;return Array.isArray(r)?r.filter(o=>!!(o.hspName&&o.hspPath)).map(o=>({hspName:o.hspName,hspPath:o.hspPath})):[]})}parseOutputMetadata(e,t){let r;try{let c=le.readFileSync(e,"utf-8");r=Xt.parse(c)}catch(c){throw new Error(`Failed to parse output metadata at ${e}: ${c instanceof Error?c.message:String(c)}`,{cause:c})}let o,i=!1,s=Array.isArray(r)?r:[r];for(let c of s)o||(o=c[t]),i||(i=c.isSigned===!0);if(!o)throw new v(`Could not find ${t} in output_metadata.json at ${e}`,"Could not find metadataKey in output_metadata.json at metadataPath.");this.validatePackageName(o);let a=this.collectRemoteHsps(s);return{packageName:o,isSigned:i,dependRemoteHsps:a}}validatePackageName(e){let t=W.basename(e);if(t!==e)throw new v(`Invalid traversal name: '${e}'. It must contain path characters.`,"Invalid traversal name.");if(!t.endsWith(".hap")&&!t.endsWith(".hsp"))throw new v(`Invalid package name '${t}'.It must be a .hap or .hsp file.`,"Invalid package name.")}};import{execFileSync as ap}from"child_process";import re from"fs";import*as Ne from"os";import*as S from"path";import tp from"fs";import*as Ui from"os";import*as Hi from"path";import qv from"regedit";import{execFileSync as Gv}from"child_process";import Xu from"fs";import*as Zu from"os";import*as vc from"path";import{compare as Vv}from"semver";function Ku(n,e){return Vv(n,e)}function pr(n,e){let t=Math.max(n.split(".").length,e.split(".").length);for(let r=0;r<t;r++){let o=Number(n.split(".")[r]??0)-Number(e.split(".")[r]??0);if(o)return o}return 0}function $i(n,e){let t=vc.join(n,"Contents","Info.plist");if(!Xu.existsSync(t)){h(`[ToolProvider] Info.plist not found at: ${t}`);return}for(let[r,o]of[["/usr/libexec/PlistBuddy",["-c",`Print :${e}`,t]],["plutil",["-extract",e,"raw","-o","-",t]]])try{let i=Gv(r,o,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(i&&!i.includes("Does Not Exist"))return i}catch{}}function zv(n){let e=$i(n,"CFBundleShortVersionString");if(!e)return $i(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[$i(n,"CFBundleVersion"),$i(n,"CFBundleGetInfoString")?.match(/DS-[\d.]+/)?.[0]];for(let o of r){let i=o?.split(".").at(-1)?.replace(new RegExp(`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`),"");if(i&&/^\d+$/.test(i))return`${e}.${i}`}return e}function St(n){if(Zu.platform()==="darwin")return zv(n);let e=vc.join(n,"product-info.json");try{let t=JSON.parse(Xu.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}function Jv(n){return n.filter(e=>{try{return tp.statSync(e).isDirectory()}catch{return!1}})}function Yv(){let n=[];for(let e of[Hi.join(Ui.homedir(),"Applications"),"/Applications"])try{n.push(...tp.readdirSync(e).filter(t=>t.endsWith(".app")&&t.toLowerCase().includes("deveco")).map(t=>Hi.join(e,t)))}catch{}return n}function Qu(n){return new Promise((e,t)=>qv.list(n,(r,o)=>r?t(r):e(o)))}async function ep(n,e,t){let o=((await Qu([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(o.length===0)return[];let i=await Qu(o);return o.flatMap(s=>{let a=i[s]?.values?.[t]?.value;return a?[a]:[]})}async function Kv(){let n=[Hi.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 ep(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 ep(e,()=>!0,""))}catch{}return n}async function np(){let n=Ui.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"?Yv():await Kv(),t=Jv(e).flatMap(r=>{let o=St(r);return o?(h(`[ToolProvider] ${r} => version ${o}`),[{root:r,version:o}]):(h(`[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,o)=>pr(o.version,r.version)>0?o:r)}import*as rp from"fs";import*as xe from"path";function Sc(n,e){let t=xe.relative(e,n);return t===""||!xe.isAbsolute(t)&&!t.startsWith(`..${xe.sep}`)&&t!==".."}function bt(n){let e=xe.resolve(n),t=[],r=e;for(;;)try{let o=rp.realpathSync(r);return t.length===0?o:xe.join(o,...t.reverse())}catch(o){if(o.code!=="ENOENT")throw o;let i=xe.dirname(r);if(i===r)return e;t.push(xe.basename(r)),r=i}}function Bi(n,e){let t=bt(e),r=bt(n);return Sc(r,t)?r:null}function bc(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function Wi(n){let e=bc(n);if(!e)throw new Error("Path must not be empty.");return bt(e)}var wo={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},Vi={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 Se={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"},Y={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"},$n={ALGORITHM:"aes-256-gcm",KEY_LENGTH:32,IV_LENGTH:12,KEK_VERSIONS:["kek-v1","kek-v2","kek-v3"]},vo={baseUrl:Y.LOGIN_URL,authUrl:Y.AUTH_APPLY_PATH,tempTokenCheckUrl:Y.TEMP_TOKEN_CHECK_PATH,jwtTokenCheckUrl:Y.JWT_TOKEN_CHECK_PATH,successRedirectUrl:Y.LOGIN_SUCCESS_PATH,failedRedirectUrl:Y.LOGIN_FAILED_PATH,logoutUrl:Y.LOGOUT_PATH,agcTeamListUrl:Y.AGC_TEAM_LIST_URL,appId:Se.APP_ID,timeout:wo.LOGIN_TIMEOUT_MS,countryCode:"CN"};var Ec="https://matrix.openharmony.cn",Ke={TAGS_API_URL:`${Ec}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${Ec}/api/registry/skill/skills`,SKILL_API_BASE:`${Ec}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,DEFAULT_MAX_PAGES:100,SUCCESS_CODE:"20000"},ct={"trae-cn":{path:".trae-cn/skills",displayName:"trae-cn"},opencode:{path:".config/opencode/skills",displayName:"opencode"},deveco:{path:".config/deveco/skills",displayName:"deveco"},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"},atomcode:{path:".atomcode/skills",displayName:"atomcode"}};import{homedir as Nt}from"os";import We from"path";var Et="deveco-mcp";var Zt={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:We.join(Nt(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:We.join(process.platform==="win32"?We.join(process.env.APPDATA??We.join(Nt(),"AppData","Roaming"),"Trae CN","User"):We.join(Nt(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:We.join(Nt(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:We.join(Nt(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:We.join(process.platform==="win32"?We.join(process.env.APPDATA??We.join(Nt(),"AppData","Roaming"),"Qoder","SharedClientCache"):We.join(Nt(),"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:We.join(Nt(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:We.join(Nt(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function ip(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function op(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function sp(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function Gi(n,e){return n.format==="opencode"?ip(e):n.format==="claude-code"||n.format==="codex"?op(e):sp(e)}var lt={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var Pc="https://developer.huawei.com/consumer/cn/download/";var Xv=/^#\s*Version:\s*(\S+)/,Zv="26.0.0.810";function Qv(n){try{let e=JSON.parse(re.readFileSync(n,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch(e){h(`[ToolProvider] Failed to parse API level from ${n}: ${e instanceof Error?e.message:String(e)}`);return}}function eS(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,o,i,s,a,c,l,d){this._sourceType=e;this._toolchainRoot=t;this._devecoStudioPath=r;this._nodePath=o;this._ohpmJsPath=i;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 arktsLangServerPath(){let e=n.buildToolPaths(this._toolchainRoot,this._sourceType).arktsLangServerCandidates;for(let t of e)if(re.existsSync(t.marker))return t.root;return null}get clangdPath(){let e=n.buildToolPaths(this._toolchainRoot,this._sourceType).clangdPath;return re.existsSync(e)?e:null}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 pr(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 getStudioVersion(){try{let e=await n.resolveInstallSource();return St(e.toolchainRoot)}catch{return}}static async getCltVersion(){try{let e=await n.resolveInstallSource();return n.readCltVersion(e.toolchainRoot)}catch{return}}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.0.0"){this.assertStudio(),n.assertMinimumVersion(St(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,o,i){if(!e)throw new v(`Failed to determine ${t} version from ${r} at ${i}`,`Failed to determine ${t} version from ${r}`);if(!/^\d+(?:\.\d+){1,3}$/.test(e))throw new v(`Invalid ${t} version "${e}" from ${r} at ${i}`,`Invalid ${t} version "${e}" from ${r}`);if(pr(e,o)<0)throw new Error(`The detected ${t} version is ${e}, which is below the minimum required version ${o}. Upgrade before using deveco-cli:
|
|
15
|
+
${Pc}`)}static resolveCodelinterPath(e,t){let r=n.buildToolPaths(e,t).codelinterCandidates,o=r.find(n.isFile);if(!o){let a=t==="studio"?"Code Linter not found in DevEco Studio.":"Code Linter not found in DevEco Command Line Tools.";throw new v(`${a}
|
|
6
16
|
Searched paths:
|
|
7
17
|
${r.join(`
|
|
8
|
-
`)}`)}let i=ut(e),s=ut(o);return n.assertInsideRoot(s,i,"codelinter"),s}static getCodelinterCandidates(e,t){if(t==="studio"){let r=tt.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 oe.existsSync(S.join(e,"version.txt"));let r=tt.platform()==="darwin"?S.join(e,"Contents"):e,o=tt.platform()==="darwin"?S.join(r,"Info.plist"):S.join(r,"product-info.json");if(!oe.existsSync(o))return!1;let i=n.buildToolPaths(e,"studio");return[i.nodePath,i.ohpmJsPath,i.hvigorJsPath].every(oe.existsSync)}static buildToolPaths(e,t){return t==="clt"?n.buildCltToolPaths(e):n.buildStudioToolPaths(e)}static buildCltToolPaths(e){let t=S.join(e,"sdk"),r=tt.platform()==="win32",o=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${o}`),emulatorPath:S.join(e,"emulator",r?"Emulator.exe":"Emulator")}}static buildStudioToolPaths(e){let t=tt.platform()==="darwin",r=tt.platform()==="win32",o=t?S.join(e,"Contents"):e,i=S.join(o,"tools"),s=S.join(o,"sdk"),a=r?".exe":"";return{nodePath:r?S.join(i,"node","node.exe"):S.join(i,"node","bin","node"),ohpmJsPath:S.join(i,"ohpm","bin","pm-cli.js"),hvigorJsPath:S.join(i,"hvigor","bin","hvigorw.js"),javaPath:r?S.join(e,"jbr","bin","java.exe"):t?S.join(o,"jbr","Contents","Home","bin","java"):S.join(o,"jbr","bin","java"),sdkPath:s,hdcPath:S.join(s,"default","openharmony","toolchains",`hdc${a}`),emulatorPath:S.join(i,"emulator",r?"Emulator.exe":"Emulator")}}static isFile(e){try{return oe.statSync(e).isFile()}catch{return!1}}static isDirectory(e){try{return oe.existsSync(e)&&oe.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,o,i]of e){let s=process.env[r]?.trim();if(s){let a=n.resolveExplicitRoot(s,o,r);return m(`[ToolProvider] Using ${r} \u2192 ${a}`),{sourceType:i,toolchainRoot:a}}}let t=await Zd();return m(`[ToolProvider] Using auto \u2192 ${t.root} (${t.version})`),{sourceType:"studio",toolchainRoot:t.root}}static resolveExplicitRoot(e,t,r){let o;try{o=mi(e)}catch(i){throw new Error(`Invalid ${r}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return t==="studio"&&tt.platform()==="darwin"&&(o=n.normalizeMacStudioRoot(o)),n.isValidRoot(o,t)?o:n.throwInvalidSource(o,t,r,e)}static assertBuiltPathsInsideRoot(e,t,r){let o=ut(e),i=[["node",t.nodePath],["ohpm",t.ohpmJsPath],["hvigor",t.hvigorJsPath],["sdk",t.sdkPath],["hdc",t.hdcPath],["emulator",t.emulatorPath]];r&&t.javaPath&&i.push(["java",t.javaPath]);for(let[s,a]of i)n.assertInsideRoot(a,o,s)}static assertInsideRoot(e,t,r){if(fi(e,t)===null)throw new Error(`Unsafe toolchain path: ${r} resolves outside the toolchain root`)}static throwInvalidSource(e,t,r,o){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}: ${o}`)}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 oe.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)),o=(process.env.Path??process.env.PATH??"").split(S.delimiter).map(s=>n.javaIn(s.trim())).find(Boolean),i=r??o;if(i)return oe.realpathSync(i);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(tt.platform()==="win32"?["java.exe","java.cmd"]:["java"]).map(r=>S.join(e,r)).find(oe.existsSync)}getMaxApiLevel(){for(let e of gw(this.sdkPath)){let t=hw(e);if(t!==void 0)return t}return 23}getSdkPlatformVersion(){let e=S.join(this.sdkPath,"default","sdk-pkg.json"),t;try{t=JSON.parse(oe.readFileSync(e,"utf8"))}catch(i){throw new Error(`Failed to read SDK metadata: ${e}`,{cause:i})}let r=t.data?.platformVersion,o=typeof r=="string"?r.trim():"";if(!o)throw new Error(`Missing data.platformVersion in SDK metadata: ${e}`);return o}detectApiLevel(){return this.getMaxApiLevel()}_apiscanPaths;getApiscanPaths(){if(this._apiscanPaths)return this._apiscanPaths;let e=tt.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"),o=S.join(r,"resources","apiChange"),i=S.join(r,"api-change-scan.js");if(!oe.existsSync(o)||!oe.existsSync(i)){let s=St(this._toolchainRoot)??"unknown";throw new Error(`A required component is missing. The detected DevEco Studio version is ${s}. The minimum required version is ${mw}. Upgrade before using 'check compat' at ${Va}`)}return this._apiscanPaths={apiChangeDir:o,scriptPath:i},this._apiscanPaths}static verifySignature(e){if(!oe.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=tt.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(!oe.statSync(e).isFile())throw new Error;oe.accessSync(e,oe.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=oe.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=`Get-AuthenticodeSignature -FilePath '${e.replace(/'/g,"''")}' | ConvertTo-Json -Depth 3 -Compress`;try{let o=ru(t,["-NoProfile","-ExecutionPolicy","Bypass","-Command",r],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"],env:{...process.env,PSModulePath:n.powerShellModulesPath}}),i=JSON.parse(o);return{signed:Number(i.Status)===0}}catch(o){return m(`[ToolProvider] verify Windows Signature, error msg: ${o}`),{signed:!1}}}static verifyMacSignature(e){try{return ru("codesign",["-v",e],{encoding:"utf8",timeout:5e3,stdio:["ignore","ignore","ignore"]}),{signed:!0}}catch{return{signed:!1}}}};import{execa as yw}from"execa";import*as Bt from"path";import*as yi from"fs";import*as ou from"os";var Ue=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let o=Bt.dirname(e.javaPath),i=`${o}${Bt.delimiter}${process.env.PATH||""}`,s={...process.env,PATH:i,DEVECO_SDK_HOME:e.sdkPath};e.sourceType==="clt"&&e.javaPath&&(s.JAVA_HOME=Bt.dirname(o)),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,o){let i=[...Array.from(o),"--mode","module","-p",`module=${r.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(i)}async clean(){let e=["clean","--analyze=normal","--parallel","--no-daemon"];await this.runHvigor(e)}async stopDaemon(){await this.runHvigor(["--stop-daemon"])}async ensureDaemonRunning(){if(this.findProjectDaemon()){m("[HvigorAdapter] Daemon already running.");return}m("[HvigorAdapter] No daemon running, starting via --sync --daemon (no hap build)."),await this.runHvigor(["--sync","--daemon"])}isDaemonRunning(e){return this.findProjectDaemon(e)!==null}findProjectDaemon(e){let t=this.getDaemonRegistryPath();if(!yi.existsSync(t))return null;try{let r=yi.readFileSync(t,"utf-8"),o=JSON.parse(r),i=e??this.projectRoot,s=Object.values(o).filter(a=>a.cwdPath===i&&(a.state==="idle"||a.state==="half_busy"||a.state==="busy")&&this.isProcessAlive(a.pid));return s.length>0?s[s.length-1]:null}catch{return null}}getDaemonRegistryPath(){let e=process.env.HVIGOR_USER_HOME||Bt.join(ou.homedir(),".hvigor");return Bt.join(e,"daemon","cache","daemon-sec.json")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}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 o=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit";await yw(t,r,{cwd:this.projectRoot,env:this.env,stdout:o,stderr:o})}};import{execa as ww}from"execa";var Xn=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 ww(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"})}};import{mkdir as vw}from"fs/promises";import{dirname as Sw,resolve as Ew}from"path";import{execa as bw}from"execa";import{lock as Ga,check as sL}from"proper-lockfile";function za(n){return Ew(n,".hvigor",".build-lock")}function Pw(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function iu(n){let e=Sw(za(n));if(await vw(e,{recursive:!0}),process.platform==="win32")try{await bw("attrib",["+h",e])}catch{}}async function Cw(n,e){let t=new AbortController,r=Pw(e);await iu(n);let o={lockfilePath:za(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await Ga(n,{...o,retries:0}),signal:t.signal}}catch(s){if(s&&typeof s=="object"&&"code"in s&&s.code!=="ELOCKED")throw s}return r(),{release:await Ga(n,{...o,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function Cn(n,e,t){let{release:r,signal:o}=await Cw(n,t);try{return await e(o)}finally{await r()}}async function wi(n,e){let t=new AbortController;await iu(n);let r={lockfilePath:za(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},o;try{o=await Ga(n,{...r,retries:0})}catch(i){if(i&&typeof i=="object"&&"code"in i&&i.code==="ELOCKED")return{acquired:!1};throw i}try{return{acquired:!0,result:await e(t.signal)}}finally{await o()}}import*as Wt from"fs";import*as In from"path";import Iw from"json5";var Aw=1e3;function Si(n){m(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=In.join(n,et.SYNC_OUTPUT_PATH);if(!Wt.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return m(`[ProjectCheck] ${l.reason}`),l}let t=Wt.statSync(e).mtimeMs;m(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=Dw(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return m(`[ProjectCheck] ${l.reason}`),l}let o=In.join(n,et.OH_PACKAGE_JSON5),i=vi(o,t,"root");if(i.required)return m(`[ProjectCheck] Root check: ${i.reason}`),i;let s=In.join(n,et.BUILD_PROFILE_JSON5),a=vi(s,t,"build-profile");if(a.required)return m(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let d=In.join(n,l.srcPath,et.OH_PACKAGE_JSON5),g=vi(d,t,l.name);if(g.required)return m(`[ProjectCheck] Module '${l.name}' check: ${g.reason}`),g;let w=In.join(n,l.srcPath,et.BUILD_PROFILE_JSON5),P=vi(w,t,l.name);if(P.required)return m(`[ProjectCheck] Module '${l.name}' build-profile check: ${P.reason}`),P}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return m(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function vi(n,e,t){if(!Wt.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=Wt.statSync(n).mtimeMs;return r-e>Aw?{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 Dw(n){let e=In.join(n,et.BUILD_PROFILE_JSON5);try{let t=Wt.readFileSync(e,"utf-8");if(!t.trim())return null;let r=Iw.parse(t);if(typeof r!="object"||r===null)return null;let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):null}catch{return null}}import*as Fe from"fs";import*as rt from"path";import*as Su from"util";import*as M from"fs";import*as xi from"path";import R from"fs";import*as Ei from"os";import*as A from"path";import Rw from"json5";var qa="Huawei";var cu=3,lu=3,su="DevEco Studio",du={DevEcoStudio:"deveco_studio"};function bi(n){if(!R.existsSync(n)||!R.statSync(n).isDirectory())return!1;let e=R.existsSync(A.join(n,"build-profile.json5")),t=R.existsSync(A.join(n,"hvigorfile.js"))||R.existsSync(A.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=R.readFileSync(A.join(n,"build-profile.json5"),"utf-8");return Rw.parse(r).app!==void 0}catch{return!1}}function Ya(n,e,t){if(e>=t)return null;let r=kw(n),o=Tw(r);if(o)return o;for(let i of r){let s=Ya(i,e+1,t);if(s)return s}return null}function kw(n){try{let e=R.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(A.join(n,r.name));return t}catch{return[]}}function Tw(n){for(let e of n)if(bi(e))return e;return null}function bt(n){if(!n||n.trim()==="")return null;let e=A.resolve(n),t;try{t=R.realpathSync(e)}catch{t=e}if(!R.existsSync(t))return null;if(bi(t))return t;let r=t;for(let o=1;o<=3;o++){let i=A.dirname(r);if(i===r)break;if(bi(i))return i;r=i}if(R.statSync(t).isDirectory()){let o=Ya(t,0,cu);if(o)return o}return null}function Pi(n){if(!n||n.trim()==="")return null;let e=A.resolve(n),t;try{t=R.realpathSync(e)}catch{t=e}return!R.existsSync(t)||!R.statSync(t).isDirectory()?null:bi(t)?t:Ya(t,0,cu)}function xw(n){let e=n??Ka();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 i=A.join(t,"ace-server","out","index.js");if(R.existsSync(i))return t}let r=A.join(e,"arkts-lsp","lib"),o=A.join(r,"out","index.js");return R.existsSync(o)?r:null}function Ja(n){let e=Mw(n??""),t=A.join(e,"sdk");return R.existsSync(t)?t:A.join(uu(e),"sdk")}function Ci(n){let e=A.dirname(n),t=[A.join(e,"tools","hvigor","bin","hvigorw.js"),A.join(e,"hvigor","bin","hvigorw.js")];for(let r of t)if(R.existsSync(r))return r;return null}function Ii(n){return{sdkPath:Ja(n),arktsLangServerPath:xw(n)}}function Xr(n,e){let t=e?A.join("standardIndex","index.js"):"index.js";return R.existsSync(A.join(n,"ace-server"))?A.join(n,"ace-server","out",t):A.join(n,"out",t)}function Ai(n){return R.existsSync(Xr(n,!0))}var Nw=["default","openharmony","native","llvm","bin","clangd"],Lw=[".idea",".deveco","cxx","compile_commands.json"];function Di(n){let e=A.join(n,...Nw),t=process.platform==="win32"?e+".exe":e;return R.existsSync(t)?t:null}function Zr(n){return A.join(n,...Lw)}function Ka(){if(process.platform==="win32"){let n=[A.join("C:\\Program Files",qa,su),A.join("C:\\Program Files (x86)",qa,su)];return au(n)}if(process.platform==="darwin"){let n=["/Applications/DevEco Studio.app",A.join(process.env.HOME??"","Applications","DevEco Studio.app")];return au(n)}return null}function au(n){for(let e of n)if(R.existsSync(e))return e;return null}function uu(n){return process.platform==="darwin"?A.join(n,"Contents"):n}function Ow(n){if(!n||!R.existsSync(n)||!pu(n))return!1;let e=uu(n);return[A.join(e,"plugins","openharmony"),A.join(e,"sdk"),A.join(e,"tools")].some(r=>R.existsSync(r))}function pu(n){try{return R.statSync(n).isDirectory()}catch{return!1}}function Xa(n,e){return!n||!R.existsSync(n)?!1:e===du.DevEcoStudio?Ow(n):!1}function Mw(n,e=du.DevEcoStudio){if(!n)return"";if(Xa(n,e))return n;let t=_w(n,e);if(t)return t;let r=Fw(n,e);return r||n}function _w(n,e){let t=n;for(let r=0;r<lu;r++){let o=A.dirname(t);if(!o||o===t)break;if(Xa(o,e))return o;t=o}return null}function Fw(n,e){if(!R.existsSync(n)||!pu(n))return null;let t=[{p:n,depth:0}];for(;t.length>0;){let{p:r,depth:o}=t.shift();if(o>=lu)continue;let i=jw(r,o,e,t);if(i)return i}return null}function jw(n,e,t,r){let o;try{o=R.readdirSync(n,{withFileTypes:!0})}catch{return null}for(let i of o){if(!i.isDirectory())continue;let s=A.join(n,i.name);if(Xa(s,t))return s;r.push({p:s,depth:e+1})}return null}function fu(n){return new Promise(e=>setTimeout(e,n))}var $w=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function An(n){let e=A.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&$w.has(e)}function Ri(n){return A.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function ce(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function Hw(n){return ce(n)}function Dn(n){let e=Hw(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function Vt(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??A.join(Ei.homedir(),"AppData","Local");return A.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?A.join(Ei.homedir(),"Library","Logs","devecocli-mcp-server"):A.join(Ei.homedir(),".local","share","devecocli-mcp-server","logs")}function mu(n,e){let t=Uw(e),r=Bw(t,n);if(r!==null)return r;let o=Date.now(),s=`${n.replace(/:/g,"\\:")}=${o}`,a=Ww(t,n,s);return Vw(e,a),o}function Uw(n){let e;try{e=R.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function Bw(n,e){for(let t of n){let r=t.indexOf("=");if(r<=0||t.slice(0,r).replace(/\\:/g,":")!==e)continue;let i=parseInt(t.slice(r+1),10);return Number.isFinite(i)&&i>0?i:null}return null}function Ww(n,e,t){let r=!1,o=n.map(i=>{if(r)return i;let s=i.indexOf("=");return s<=0?i:i.slice(0,s).replace(/\\:/g,":")===e?(r=!0,t):i});return r||o.push(t),o}function Vw(n,e){try{R.mkdirSync(A.dirname(n),{recursive:!0})}catch{}try{R.writeFileSync(n,e.join(`
|
|
9
|
-
`)+`
|
|
10
|
-
`,"utf8")}catch{}}function Za(n,e,t="[Cleanup]"){try{let r=A.dirname(n);if(!R.existsSync(r))return;let o=Date.now();for(let i of R.readdirSync(r,{withFileTypes:!0}))i.isDirectory()&&Gw(A.join(r,i.name),o,e,t)}catch{}}function Gw(n,e,t,r){try{let{mtimeMs:o}=R.statSync(n);if(e-o<=t)return;R.rmSync(n,{recursive:!0,force:!0});let i=Math.floor((e-o)/1e3);console.error(`${r} Removed expired dir (age ${Math.floor(i/86400)}d ${Math.floor(i%86400/3600)}h): ${n}`)}catch(o){console.error(`${r} Failed to remove expired dir ${n}: ${o}`)}}function ki(n){let e=n.replace(/sdk\/?$/i,"tools"),t=process.platform==="win32"?"node.exe":"node",r=A.join(e,"node",t);return R.existsSync(r)||process.platform!=="win32"&&(r=A.join(e,"node","bin","node"),R.existsSync(r))?r:process.execPath??"node"}var hu="mcp-server.log",zw="mcp-server",qw={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={...qw,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=Vt(),this.currentLogFile=xi.join(this.logDir,hu),M.existsSync(this.logDir)||M.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"),o=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${o}`}getRotatedFileName(e,t){return xi.join(this.logDir,`${zw}-${e}.log.${t}`)}fileExists(e){try{return M.accessSync(e,M.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=M.readdirSync(this.logDir),t=[];for(let o of e)if(o===hu||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(o)){let i=xi.join(this.logDir,o),s=M.statSync(i);t.push({name:o,mtime:s.mtime,path:i})}t.sort((o,i)=>i.mtime.getTime()-o.mtime.getTime());let r=1+this.rotationOptions.maxFiles;for(let o=r;o<t.length;o++)try{M.unlinkSync(t[o].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)&&M.unlinkSync(t);for(let o=this.rotationOptions.maxFiles-1;o>=1;o--){let i=this.getRotatedFileName(e,o),s=this.getRotatedFileName(e,o+1);this.fileExists(i)&&M.renameSync(i,s)}let r=this.getRotatedFileName(e,1);M.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=M.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=M.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{M.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 o=r.map(c=>c instanceof Error?`${c.name}: ${c.message}`:typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),i=o?`${t} ${o}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] ${i}
|
|
11
|
-
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);M.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{M.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},Be=null;function Rn(n=!1){Be&&Be.dispose(),Be=new Qa(n)}function gu(){Be&&(Be.dispose(),Be=null)}function yu(){Be&&Be.flush()}function wu(){return Be?.getLogFilePath()??null}function vu(){return Be?.getLogDirectory()??null}function Ti(){return Be||Rn(!1),Be}var h={debug:(n,...e)=>Ti().debug(n,...e),info:(n,...e)=>Ti().info(n,...e),warn:(n,...e)=>Ti().warn(n,...e),error:(n,...e)=>Ti().error(n,...e)};var ec="";function Li(n){if(!n||n==="auto"||n==="stdout"||n==="none"){ec="";return}ec=n}function Eu(){return ec||(vu()??"")}function Ni(n,...e){if(e.length===0)return n;try{return Su.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] ${Ni(n,...e)}`)},warn(n,...e){h.warn(`[lsp] ${Ni(n,...e)}`)},error(n,...e){h.error(`[lsp] ${Ni(n,...e)}`)},debug(n,...e){h.debug(`[lsp] ${Ni(n,...e)}`)}};import*as Qr from"fs";import*as eo from"os";import*as Zn from"path";import Yw 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 bu=8192,tc=100,Pu=.03,Cu=.7,We=900*1e3;function _e(n){if(!Qr.existsSync(n))return null;try{let e=Qr.readFileSync(n,"utf-8");return e.trim()?Yw.parse(e):null}catch{return null}}function Oi(n,e){let t=Math.floor(eo.totalmem()/1048576),r=Math.floor(t*Cu),o,i;e!==void 0&&Number.isFinite(e)&&e>0?(o=e,i=`override(${e})`):(o=bu,n>tc&&(o+=(n-tc)*Pu*1024),i=`formula(moduleCount=${n})`);let s=r>0&&o>r;s&&(o=r);let a=Math.round(o);return f.info(`[computeLspServerMaxSize] source=${i}, physicalTotal=${t}MB, physicalCap(70%)=${r}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function nt(n){if(n.startsWith("file:"))return n;try{let e=Zn.resolve(n),t=new URL(`file://${e}`).toString();if(eo.platform()==="win32"){let r=t.match(/^file:\/\/\/([A-Za-z]):/);if(r){let o=r[1].toUpperCase(),i=t.substring(`file:///${r[1]}:`.length);t=`file:///${o}%3A${i}`}}return t}catch{return n}}function Qn(n){return n&&n.replace(/\\/g,"/")}function B(n){let e=Zn.normalize(n).replace(/\\/g,"/");if(eo.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function Iu(n){return Zn.join(n,"build-profile.json5")}var Pt=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=Iu(this.projectRoot);try{let t=_e(e);if(typeof t!="object"||t===null)return[];let r=t.modules;return Array.isArray(r)?r.filter(o=>{if(typeof o!="object"||o===null)return!1;let i=o;return typeof i.name=="string"&&typeof i.srcPath=="string"}):[]}catch(t){return f.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};import{spawn as Jw}from"child_process";import*as _i from"fs";var Kw=600*1e3;function Xw(n,e,t){let r=t.split(/\s+/).filter(o=>o.length>0);return[n,[e,...r]]}function Zw(n){let e=[],t=[];return n.stdout?.on("data",r=>{e.push(r.toString())}),n.stderr?.on("data",r=>{let o=r.toString();t.push(o),o.split(/\r?\n/).filter(Boolean).forEach(i=>f.info("[hvigor:err] %s",i))}),{stdout:e,stderr:t}}function Mi(n){return n.join("")}function Qw(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
|
|
18
|
+
`)}`,a)}let i=bt(e),s=bt(o);return n.assertInsideRoot(s,i,"codelinter"),s}static isValidRoot(e,t){if(!n.isDirectory(e))return!1;if(t==="clt")return re.existsSync(S.join(e,"version.txt"));let r=Ne.platform()==="darwin"?S.join(e,"Contents"):e,o=Ne.platform()==="darwin"?S.join(r,"Info.plist"):S.join(r,"product-info.json");if(!re.existsSync(o))return!1;let i=n.buildToolPaths(e,"studio");return[i.nodePath,i.ohpmJsPath,i.hvigorJsPath].every(re.existsSync)}static buildToolPaths(e,t){return t==="clt"?n.buildCltToolPaths(e):n.buildStudioToolPaths(e)}static buildCltToolPaths(e){let t=Ne.platform()==="win32",r=t?".exe":"",o=S.join(e,"sdk");return{nodePath:t?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:o,hdcPath:S.join(o,"default","openharmony","toolchains",`hdc${r}`),emulatorPath:S.join(e,"emulator",t?"Emulator.exe":"Emulator"),clangdPath:n.clangdPathFor(o),arktsLangServerCandidates:[{root:S.join(e,"arkts-lsp","lib"),marker:S.join(e,"arkts-lsp","lib","out","index.js")}],codelinterCandidates:n.codelinterCandidatesFor(e,"clt")}}static buildStudioToolPaths(e){let t=Ne.platform()==="darwin",r=Ne.platform()==="win32",o=t?S.join(e,"Contents"):e,i=S.join(o,"tools"),s=S.join(o,"sdk"),a=r?".exe":"";return{nodePath:r?S.join(i,"node","node.exe"):S.join(i,"node","bin","node"),ohpmJsPath:S.join(i,"ohpm","bin","pm-cli.js"),hvigorJsPath:S.join(i,"hvigor","bin","hvigorw.js"),javaPath:r?S.join(e,"jbr","bin","java.exe"):t?S.join(o,"jbr","Contents","Home","bin","java"):S.join(o,"jbr","bin","java"),sdkPath:s,hdcPath:S.join(s,"default","openharmony","toolchains",`hdc${a}`),emulatorPath:S.join(i,"emulator",r?"Emulator.exe":"Emulator"),clangdPath:n.clangdPathFor(s),arktsLangServerCandidates:n.studioArktsLangServerCandidates(e),codelinterCandidates:n.codelinterCandidatesFor(e,"studio")}}static codelinterCandidatesFor(e,t){if(t==="clt")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")];let r=Ne.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")]}static studioArktsLangServerCandidates(e){if(Ne.platform()==="linux")return[];let t=Ne.platform()==="darwin"?["Contents"]:[],r=S.join(e,...t,"plugins","openharmony");return[{root:r,marker:S.join(r,"ace-server","out","index.js")}]}static clangdPathFor(e){return S.join(e,"default","openharmony","native","llvm","bin",Ne.platform()==="win32"?"clangd.exe":"clangd")}static isFile(e){try{return re.statSync(e).isFile()}catch{return!1}}static isDirectory(e){try{return re.existsSync(e)&&re.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,o,i]of e){let s=process.env[r]?.trim();if(s){let a=n.resolveExplicitRoot(s,o,r);return h(`[ToolProvider] Using ${r} \u2192 ${a}`),{sourceType:i,toolchainRoot:a}}}let t=await np();return h(`[ToolProvider] Using auto \u2192 ${t.root} (${t.version})`),{sourceType:"studio",toolchainRoot:t.root}}static resolveExplicitRoot(e,t,r){let o;try{o=Wi(e)}catch(i){throw new Error(`Invalid ${r}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return t==="studio"&&Ne.platform()==="darwin"&&(o=n.normalizeMacStudioRoot(o)),n.isValidRoot(o,t)?o:n.throwInvalidSource(o,t,r,e)}static assertBuiltPathsInsideRoot(e,t,r){let o=bt(e),i=[["node",t.nodePath],["ohpm",t.ohpmJsPath],["hvigor",t.hvigorJsPath],["sdk",t.sdkPath],["hdc",t.hdcPath],["emulator",t.emulatorPath]];r&&t.javaPath&&i.push(["java",t.javaPath]);for(let[s,a]of i)n.assertInsideRoot(a,o,s)}static assertInsideRoot(e,t,r){if(Bi(e,t)===null)throw new Error(`Unsafe toolchain path: ${r} resolves outside the toolchain root`)}static throwInvalidSource(e,t,r,o){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}: ${o}`)}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 re.readFileSync(S.join(e,"version.txt"),"utf-8").split(/\r?\n/).map(t=>t.match(Xv)?.[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)),o=(process.env.Path??process.env.PATH??"").split(S.delimiter).map(s=>n.javaIn(s.trim())).find(Boolean),i=r??o;if(i)return re.realpathSync(i);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(Ne.platform()==="win32"?["java.exe","java.cmd"]:["java"]).map(r=>S.join(e,r)).find(re.existsSync)}getMaxApiLevel(){for(let e of eS(this.sdkPath)){let t=Qv(e);if(t!==void 0)return t}return 23}getSdkPlatformVersion(){let e=S.join(this.sdkPath,"default","sdk-pkg.json"),t;try{t=JSON.parse(re.readFileSync(e,"utf8"))}catch(i){throw new Error(`Failed to read SDK metadata: ${e}`,{cause:i})}let r=t.data?.platformVersion,o=typeof r=="string"?r.trim():"";if(!o)throw new Error(`Missing data.platformVersion in SDK metadata: ${e}`);return o}detectApiLevel(){return this.getMaxApiLevel()}_apiscanPaths;getApiscanPaths(){if(this._apiscanPaths)return this._apiscanPaths;let e=Ne.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"),o=S.join(r,"resources","apiChange"),i=S.join(r,"api-change-scan.js");if(!re.existsSync(o)||!re.existsSync(i)){let s=St(this._toolchainRoot)??"unknown";throw new Error(`A required component is missing. The detected DevEco Studio version is ${s}. The minimum required version is ${Zv}. Upgrade before using 'check compat' at ${Pc}`)}return this._apiscanPaths={apiChangeDir:o,scriptPath:i},this._apiscanPaths}static verifySignature(e){if(!re.existsSync(e))throw new v(`executable not found at: ${e}`,"executable not found");let t=Ne.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(!re.statSync(e).isFile())throw new Error;re.accessSync(e,re.constants.X_OK)}catch{throw new v(`executable is not accessible: ${e}`,"executable is not accessible")}}static assertSigned(e,t){if(!e.signed)throw new v(`The executable is not digitally signed: ${t}`,"The executable is not digitally signed")}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=re.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=`Get-AuthenticodeSignature -FilePath '${e.replace(/'/g,"''")}' | ConvertTo-Json -Depth 3 -Compress`;try{let o=ap(t,["-NoProfile","-ExecutionPolicy","Bypass","-Command",r],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"],env:{...process.env,PSModulePath:n.powerShellModulesPath}}),i=JSON.parse(o);return{signed:Number(i.Status)===0}}catch(o){return h(`[ToolProvider] verify Windows Signature, error msg: ${o}`),{signed:!1}}}static verifyMacSignature(e){try{return ap("codesign",["-v",e],{encoding:"utf8",timeout:5e3,stdio:["ignore","ignore","ignore"]}),{signed:!0}}catch{return{signed:!1}}}};import{execa as sS}from"execa";import*as pp from"net";import*as Qt from"path";import*as qi from"fs";import*as mp from"os";import{execFile as lp}from"child_process";import{existsSync as tS}from"fs";var dp="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",Cc;function nS(){return Cc===void 0&&(Cc=tS(dp)),Cc}function Pt(n){return new Promise(e=>{let t=process.platform==="win32",r=t?"tasklist":"ps",o=t?["/fi",`PID eq ${n}`,"/fo","csv","/nh"]:["-o","rss=","-p",String(n)];h(`Executing: ${r} ${o.join(" ")}`),lp(r,o,{timeout:5e3,windowsHide:!0},(i,s)=>{if(i){e(null);return}e(t?iS(s):oS(s))})})}async function rS(n){return new Promise(e=>{let t=process.platform==="win32",r,o;if(t){if(!nS()){e([]);return}r=dp,o=["-NoProfile","-Command",`Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq ${n} } | Select-Object -ExpandProperty ProcessId`]}else r="ps",o=["-o","pid=","--ppid",String(n)];lp(r,o,{timeout:5e3,windowsHide:!0},(i,s)=>{if(i){e([]);return}let a=[],c=s.trim().split(`
|
|
19
|
+
`);for(let l of c){let d=l.trim();d&&/^\d+$/.test(d)&&a.push(Number(d))}e(a)})})}async function up(n){let e=0,t=await Pt(n);t&&(e+=Number(t)*1024);let r=await rS(n);for(let o of r)e+=await up(o);return e}function Ie(n){return`${(n/1024/1024).toFixed(2)}MB`}async function cp(n,e){if(!n)return process.memoryUsage().rss;if(e)return up(n);let t=await Pt(n);return t?Number(t)*1024:0}function zi(n,e=500,t=!1){let r=0,o=!1,i=setInterval(async()=>{if(o)return;let s=await cp(n,t);s>r&&(r=s)},e);return{stop:async()=>{o=!0,clearInterval(i);let s=await cp(n,t);return Math.max(r,s)}}}function oS(n){let e=n.trim().match(/^(\d+)$/);return e?e[1]:null}function iS(n){let e=n.match(/"([^"]+?)\s*K"/i);return e&&e[1].replace(/\D/g,"")||null}var Ve=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let o=Qt.dirname(e.javaPath),i=`${o}${Qt.delimiter}${process.env.PATH||""}`,s={...process.env,PATH:i,DEVECO_SDK_HOME:e.sdkPath};e.sourceType==="clt"&&e.javaPath&&(s.JAVA_HOME=Qt.dirname(o)),this.env=s}async sync(e,t){let r=["--sync","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(r)}async buildProduct(e,t){let r=["assembleApp","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(r)}async buildModules(e,t,r,o){let i=[...Array.from(o),"--mode","module","-p",`module=${r.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(i)}async clean(){let e=["clean","--analyze=normal","--parallel","--no-daemon"];return this.runHvigor(e)}async stopDaemon(){return this.runHvigor(["--stop-daemon"])}async ensureDaemonRunning(){if(this.findProjectDaemon()){h("[HvigorAdapter] Daemon already running.");return}h("[HvigorAdapter] No daemon running, starting via --sync --daemon (no hap build)."),await this.runHvigor(["--sync","--daemon"])}isDaemonRunning(e){return this.findProjectDaemon(e)!==null}async isDaemonAlive(e){let t=this.findProjectDaemon(e);return t?this.isPortListening(t.port):!1}isPortListening(e){return new Promise(t=>{let r=new pp.Socket;r.setTimeout(2e3),r.once("connect",()=>{r.destroy(),t(!0)}),r.once("error",()=>t(!1)),r.once("timeout",()=>{r.destroy(),t(!1)}),r.connect(e,"127.0.0.1")})}findProjectDaemon(e){let t=this.getDaemonRegistryPath();if(!qi.existsSync(t))return null;try{let r=qi.readFileSync(t,"utf-8"),o=JSON.parse(r),i=e??this.projectRoot,s=Object.values(o).filter(a=>a.cwdPath===i&&(a.state==="idle"||a.state==="half_busy"||a.state==="busy")&&this.isProcessAlive(a.pid));return s.length>0?s[s.length-1]:null}catch{return null}}getDaemonRegistryPath(){let e=process.env.HVIGOR_USER_HOME||Qt.join(mp.homedir(),".hvigor");return Qt.join(e,"daemon","cache","daemon-sec.json")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}async compileNative(e,t){let r=["--mode","module"];return t&&r.push("-p",`module=${t}`),r.push("-p",`product=${e}`,"compileNative","--analyze=normal"),this.runHvigor(r)}async runHvigor(e){let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];h(`Executing: ${t} ${r.join(" ")}`);let o=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit",i=sS(t,r,{cwd:this.projectRoot,env:this.env,stdout:o,stderr:o}),s=zi(i.pid,500,!0),a="";try{await i}finally{let c=await s.stop();c>0&&(a=Ie(c),h(`Hvigor peak memory: ${a}`))}return a}};import{execa as aS}from"execa";var mr=class{toolProvider;projectRoot;peakMemoryMb="";constructor(e,t){this.toolProvider=e,this.projectRoot=t}async installAll(){let e=this.toolProvider.nodePath,t=[this.toolProvider.ohpmJsPath,"install","--all"];h(`Executing: ${e} ${t.join(" ")}`);let r=aS(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"}),o=zi(r.pid);try{await r}finally{let i=await o.stop();i>0&&(this.peakMemoryMb=Ie(i))}}};import{mkdir as cS}from"fs/promises";import{dirname as lS,resolve as dS}from"path";import{execa as uS}from"execa";import{lock as Ic,check as T_}from"proper-lockfile";function Ac(n){return dS(n,".hvigor",".build-lock")}function pS(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function fp(n){let e=lS(Ac(n));if(await cS(e,{recursive:!0}),process.platform==="win32")try{await uS("attrib",["+h",e])}catch{}}async function mS(n,e){let t=new AbortController,r=pS(e);await fp(n);let o={lockfilePath:Ac(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await Ic(n,{...o,retries:0}),signal:t.signal}}catch(s){if(s&&typeof s=="object"&&"code"in s&&s.code!=="ELOCKED")throw s}return r(),{release:await Ic(n,{...o,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function Hn(n,e,t){let{release:r,signal:o}=await mS(n,t);try{return await e(o)}finally{await r()}}async function Ji(n,e){let t=new AbortController;await fp(n);let r={lockfilePath:Ac(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},o;try{o=await Ic(n,{...r,retries:0})}catch(i){if(i&&typeof i=="object"&&"code"in i&&i.code==="ELOCKED")return{acquired:!1};throw i}try{return{acquired:!0,result:await e(t.signal)}}finally{await o()}}import*as en from"fs";import*as Un from"path";import fS from"json5";var hS=1e3;function Ki(n){h(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=Un.join(n,lt.SYNC_OUTPUT_PATH);if(!en.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return h(`[ProjectCheck] ${l.reason}`),l}let t=en.statSync(e).mtimeMs;h(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=gS(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return h(`[ProjectCheck] ${l.reason}`),l}let o=Un.join(n,lt.OH_PACKAGE_JSON5),i=Yi(o,t,"root");if(i.required)return h(`[ProjectCheck] Root check: ${i.reason}`),i;let s=Un.join(n,lt.BUILD_PROFILE_JSON5),a=Yi(s,t,"build-profile");if(a.required)return h(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let d=Un.join(n,l.srcPath,lt.OH_PACKAGE_JSON5),g=Yi(d,t,l.name);if(g.required)return h(`[ProjectCheck] Module '${l.name}' check: ${g.reason}`),g;let w=Un.join(n,l.srcPath,lt.BUILD_PROFILE_JSON5),b=Yi(w,t,l.name);if(b.required)return h(`[ProjectCheck] Module '${l.name}' build-profile check: ${b.reason}`),b}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return h(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function Yi(n,e,t){if(!en.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=en.statSync(n).mtimeMs;return r-e>hS?{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 gS(n){let e=Un.join(n,lt.BUILD_PROFILE_JSON5);try{let t=en.readFileSync(e,"utf-8");if(!t.trim())return null;let r=fS.parse(t);if(typeof r!="object"||r===null)return null;let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):null}catch{return null}}import*as ze from"fs";import*as ut from"path";import*as hp from"util";var Dc="";function Zi(n){if(!n||n==="auto"||n==="stdout"||n==="none"){Dc="";return}Dc=n}function gp(){return Dc||(Ou()??"")}function Xi(n,...e){if(e.length===0)return n;try{return hp.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var m={info(n,...e){f.info(`[lsp] ${Xi(n,...e)}`)},warn(n,...e){f.warn(`[lsp] ${Xi(n,...e)}`)},error(n,...e){f.error(`[lsp] ${Xi(n,...e)}`)},debug(n,...e){f.debug(`[lsp] ${Xi(n,...e)}`)}};import*as So from"fs";import*as bo from"os";import*as fr from"path";import yS 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 yp=8192,kc=100,wp=.03,vp=.7,Xe=900*1e3;function Ge(n){if(!So.existsSync(n))return null;try{let e=So.readFileSync(n,"utf-8");return e.trim()?yS.parse(e):null}catch{return null}}function Qi(n,e){let t=Math.floor(bo.totalmem()/1048576),r=Math.floor(t*vp),o,i;e!==void 0&&Number.isFinite(e)&&e>0?(o=e,i=`override(${e})`):(o=yp,n>kc&&(o+=(n-kc)*wp*1024),i=`formula(moduleCount=${n})`);let s=r>0&&o>r;s&&(o=r);let a=Math.round(o);return m.info(`[computeLspServerMaxSize] source=${i}, physicalTotal=${t}MB, physicalCap(70%)=${r}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function dt(n){if(n.startsWith("file:"))return n;try{let e=fr.resolve(n),t=new URL(`file://${e}`).toString();if(bo.platform()==="win32"){let r=t.match(/^file:\/\/\/([A-Za-z]):/);if(r){let o=r[1].toUpperCase(),i=t.substring(`file:///${r[1]}:`.length);t=`file:///${o}%3A${i}`}}return t}catch{return n}}function hr(n){return n&&n.replace(/\\/g,"/")}function V(n){let e=fr.normalize(n).replace(/\\/g,"/");if(bo.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function Sp(n){return fr.join(n,"build-profile.json5")}var Lt=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=Sp(this.projectRoot);try{let t=Ge(e);if(typeof t!="object"||t===null)return[];let r=t.modules;return Array.isArray(r)?r.filter(o=>{if(typeof o!="object"||o===null)return!1;let i=o;return typeof i.name=="string"&&typeof i.srcPath=="string"}):[]}catch(t){return m.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};import{spawn as wS}from"child_process";import*as ts from"fs";var vS=600*1e3;function SS(n,e,t){let r=t.split(/\s+/).filter(o=>o.length>0);return[n,[e,...r]]}function bS(n){let e=[],t=[];return n.stdout?.on("data",r=>{e.push(r.toString())}),n.stderr?.on("data",r=>{let o=r.toString();t.push(o),o.split(/\r?\n/).filter(Boolean).forEach(i=>m.info("[hvigor:err] %s",i))}),{stdout:e,stderr:t}}function es(n){return n.join("")}function ES(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
|
|
12
20
|
Output so far:
|
|
13
|
-
`+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function
|
|
21
|
+
`+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function PS(n,e,t){return new Promise(r=>{let o=wS(n[0],n[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:i,stderr:s}=bS(o),a=setTimeout(()=>{o.kill();let c=[es(i),es(s)].filter(Boolean).join(`
|
|
14
22
|
`).trim();r({success:!1,output:`Build process timeout after 10 minutes.
|
|
15
23
|
Output so far:
|
|
16
|
-
`+c,exitCode:-1})},
|
|
17
|
-
`).trim()||"";r(
|
|
18
|
-
[ohpm install] Running...`);try{await n.installAll()}catch(
|
|
19
|
-
[hvigor sync] Running...`);try{await e.sync(t,r)}catch(
|
|
24
|
+
`+c,exitCode:-1})},vS);o.on("close",(c,l)=>{clearTimeout(a);let d=[es(i),es(s)].filter(Boolean).join(`
|
|
25
|
+
`).trim()||"";r(ES(c,l,d))}),o.on("error",c=>{clearTimeout(a),r({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function Tc(n,e,t,r,o){let i={...process.env,DEVECO_SDK_HOME:r},s=SS(e,t,o);return await PS(s,n,i)}function CS(n,e,t){return{node_path:e,hvigor_path:t,sdk_path:n}}function IS(n){return!n.node_path||!ts.existsSync(n.node_path)?`Node path not found or invalid: ${n.node_path}`:!n.hvigor_path||!ts.existsSync(n.hvigor_path)?`Hvigor path not found or invalid: ${n.hvigor_path}`:!n.sdk_path||!ts.existsSync(n.sdk_path)?`SDK path not found or invalid: ${n.sdk_path}`:null}var AS="--sync -p product=default --analyze=normal --parallel --incremental --no-daemon";async function bp(n,e,t,r){try{let o=CS(e,t,r),i=IS(o);if(i!=null)return m.info(`Config validation failed: ${i}`),!1;let s=await Tc(n,o.node_path,o.hvigor_path,e,AS);return m.info(`[hvigor] sync finished: success=${s.success}, exitCode=${s.exitCode}`),s.success}catch(o){return m.info(`syncProject failed: ${JSON.stringify(o)}`),!1}}function DS(n){let e=ut.extname(n).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh","c++","h++"].includes(e)}function kS(n,e){let t=ut.join(n,e.name);return e.isDirectory()?e.name===".cxx"||Ep(t):DS(t)}function Ep(n){if(!ze.existsSync(n))return!1;try{return ze.readdirSync(n,{withFileTypes:!0}).some(t=>kS(n,t))}catch{}return!1}function Bn(n){try{let t=new Lt(n).getAllModuleInfo(),r=[];for(let o of t){let i=ut.resolve(n,o.srcPath);Ep(i)&&r.push(o)}return r}catch(e){throw f.error(`[CppCompile] findCppModules threw: ${e instanceof Error?e.message:String(e)}`),e}}function TS(n){let e=[],r=new Lt(n).getAllModuleInfo();for(let o of r){let i=ut.resolve(n,o.srcPath),s=ut.join(i,".cxx");ze.existsSync(s)&&Pp(s,e)}return e}function Pp(n,e){try{let t=ze.readdirSync(n,{withFileTypes:!0});for(let r of t){let o=ut.join(n,r.name);r.isDirectory()?Pp(o,e):r.name==="compile_commands.json"&&e.push(o)}}catch{}}function RS(n){let e=[];for(let t of n)try{let r=ze.readFileSync(t,"utf8"),o=JSON.parse(r);e.push(...o)}catch{}return e}function xS(n,e){let t=ut.join(n,...NS.slice(0,-1));ze.mkdirSync(t,{recursive:!0});let r=ut.join(t,"compile_commands.json");ze.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function Rc(n){let e=TS(n);if(e.length>0){let t=RS(e);xS(n,t),f.info(`[CppCompile] compile_commands.json generated, ${t.length} compile commands`)}else f.warn("[CppCompile] No compile_commands.json files found")}var NS=[".idea",".deveco","cxx","compile_commands.json"];async function LS(n,e,t,r,o){if(!r){f.warn(`[CppCompile] hvigorw.js path not injected (sdk '${e}')`);return}f.info(`[CppCompile] sdkPath: ${e}, hvigorPath: ${r}`);for(let i of o){let s=i.name;try{C.assertModuleName(s)}catch{f.warn(`[CppCompile] Skipping module with invalid name: ${s}`);continue}let a=["--mode","module","-p",`module=${i.name}`,"-p","product=default","compileNative","--analyze=normal","--parallel","--incremental","--no-daemon"].join(" ");f.info(`[CppCompile] Running compileNative for module: ${i.name}`);let c=await Tc(n,t,r,e,a);c.success?f.info(`[CppCompile] compileNative ${i.name} succeeded`):f.warn(`[CppCompile] compileNative ${i.name} failed: ${c.output}`)}}async function Cp(n,e,t,r){let o=Bn(n);if(o.length===0){f.info("[CppCompile] No C++ modules found, skipping initialization");return}f.info(`[CppCompile] Found ${o.length} C++ module(s): ${o.map(i=>i.name).join(", ")}`),await LS(n,e,t,r,o),Rc(n)}function MS(n,e){if(e.product&&n.validateProduct(e.product),e.buildMode){let t=["debug","release"],r=(n.profile.app.buildModeSet?.map(i=>i.name)??[]).filter(i=>!t.includes(i)),o=[...t,...r];if(!o.includes(e.buildMode))throw new Error(`Build mode '${e.buildMode}' not found. Available modes: ${o.join(", ")}`)}}function _S(n,e){let t=n.profile.modules.map(o=>o.name),r=new Set(t);for(let o of e){let i=o.split("@",1)[0];if(!r.has(i))throw new Error(`Module '${i}' not found in project-level build-profile.json5. Available modules: ${t.join(", ")||"none"}`)}}function FS(n,e){let t;if(e.modules&&e.modules.length>0)t=e.modules,_S(n,t);else{let o=n.profile.modules,i=o.filter(s=>n.getModuleType(s.name)==="entry");if(o.length===1)t=[o[0].name];else if(i.length===1)t=[i[0].name];else throw i.length>1?new v(`Multiple entry modules found (${i.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`,"Multiple entry modules found."):new v(`No entry module found and multiple modules available (${o.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`,"No entry module found and multiple modules available.")}let r=new Set;for(let o of t){let i=o.indexOf("@"),s=i!==-1?o.substring(0,i):o,a=i!==-1?o.substring(i+1):"default";r.add(`${s}@${a}`)}return Array.from(r)}function Lc(n,e){let t=new Set;for(let r of e){let o=r.indexOf("@"),i=o!==-1?r.substring(0,o):r,s=n.getModuleType(i);s==="shared"?t.add("assembleHsp"):s==="har"?t.add("assembleHar"):t.add("assembleHap")}return t}function Eo(n,e){let t=e,r=`${n} failed`;console.error(Ip(r));let o=t.stdout||t.message;throw o&&console.error(o),t.stderr&&console.error(t.stderr),new Error(r,{cause:e})}async function Oc(n,e,t,r,o,i){let s=Ki(i);console.log(`
|
|
26
|
+
[ohpm install] Running...`);try{await n.installAll()}catch(l){Eo("ohpm install",l)}let a="";if(s.required){console.log(`
|
|
27
|
+
[hvigor sync] Running...`);try{a=await e.sync(t,r)}catch(l){Eo("hvigor sync",l)}}else console.log(`
|
|
20
28
|
[hvigor sync] Skipped (configurations unchanged)`);console.log(`
|
|
21
|
-
[hvigor build] Running...`);try{o.type==="product"?await e.buildProduct(t,r):await e.buildModules(t,r,o.modulesToBuild,o.moduleTasks)}catch(
|
|
22
|
-
Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(
|
|
23
|
-
Failed to merge compile_commands.json: ${e.message}`))}}
|
|
24
|
-
`+
|
|
25
|
-
[1/2] Running hvigor clean...`);try{await r.clean()}catch(o){
|
|
26
|
-
[2/2] Running hvigor --stop-daemon...`);try{await r.stopDaemon()}catch(o){
|
|
27
|
-
`+
|
|
29
|
+
[hvigor build] Running...`);let c="";try{o.type==="product"?c=await e.buildProduct(t,r):c=await e.buildModules(t,r,o.modulesToBuild,o.moduleTasks)}catch(l){Eo("hvigor build",l)}return jS(i),{ohpmMemoryMb:n.peakMemoryMb,syncMemoryMb:a,buildMemoryMb:c}}function jS(n){try{if(Bn(n).length===0)return;Rc(n),console.log(xc(`
|
|
30
|
+
Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(Nc(`
|
|
31
|
+
Failed to merge compile_commands.json: ${e.message}`))}}async function Ap(n,e){let t=Date.now(),r=!0,o=null;try{await e()}catch(i){r=!1,o=ce(i),console.error(Ip(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await k.track(n,i)}}function $S(n){let e={event:E.CommandExecuted,args:["build",...n.product?["--product"]:[],...n.modules?["--modules"]:[],...n.buildMode?["--build-mode"]:[]]};return n.buildMode&&(e.build_mode=n.buildMode),n.modules&&(e.module_count=n.modules.length),e}function HS(){return{event:E.CommandExecuted,args:["build","clean"]}}async function US(n){let e=process.cwd(),t=J.discover(e);console.warn(Nc("Ensure the project source is trustworthy before proceeding."));let r=await I.new();r.assertJava(),MS(t,n);let o=n.product||"default",i=n.buildMode||"debug",s;if(n.product&&!n.modules)s={type:"product"};else{let d=FS(t,n),g=Lc(t,d);s={type:"modules",modulesToBuild:d,moduleTasks:g}}let a=new mr(r,t.rootDir),c=new Ve(r,t.rootDir),l=await Hn(t.rootDir,async()=>Oc(a,c,o,i,s,t.rootDir),()=>{console.log("Another build is already running for this project. Waiting for completion...")});return console.log(`
|
|
32
|
+
`+xc("Build completed successfully")),{bundleName:t.getBundleName(),ohpmMemoryMb:l.ohpmMemoryMb,syncMemoryMb:l.syncMemoryMb,buildMemoryMb:l.buildMemoryMb}}async function BS(){let n=process.cwd(),e=J.discover(n);console.warn(Nc("Ensure the project source is trusted before proceeding."));let t=await I.new();t.assertJava();let r=new Ve(t,e.rootDir);return await Hn(e.rootDir,async()=>{console.log(`
|
|
33
|
+
[1/2] Running hvigor clean...`);try{await r.clean()}catch(o){Eo("hvigor clean",o)}console.log(`
|
|
34
|
+
[2/2] Running hvigor --stop-daemon...`);try{await r.stopDaemon()}catch(o){Eo("hvigor --stop-daemon",o)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
|
|
35
|
+
`+xc("Clean completed successfully.")),e.getBundleName()}var Dp=new OS("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=>{let e=$S(n);await Ap(e,async()=>{let t=await US(n);e.bundle_name=t.bundleName,t.ohpmMemoryMb&&(e.ohpm_install_memory=t.ohpmMemoryMb),t.syncMemoryMb&&(e.hvigor_sync_memory=t.syncMemoryMb),t.buildMemoryMb&&(e.hvigor_build_memory=t.buildMemoryMb)})});Dp.command("clean").description("Clean HarmonyOS project build outputs").action(async()=>{let n=HS();await Ap(n,async()=>{n.bundle_name=await BS()})});var kp=Dp;import{Command as Db}from"commander";import{green as Ao,red as kb,yellow as ds}from"colorette";import*as Do from"path";import{randomUUID as tb}from"crypto";import{execa as nb}from"execa";import{execa as eb}from"execa";import{execFile as WS,spawn as VS}from"child_process";import{promisify as GS}from"util";var zS=GS(WS);function Tp(n,e,t){let o=n.replace(/\r\n/g,`
|
|
28
36
|
`).split(`
|
|
29
|
-
`),i=o.pop()??"",s=o.map(a=>a.endsWith("\r")?a.slice(0,-1):a).filter(a=>a.length>0);return s.length>0&&t.onData(s,e),i}function
|
|
30
|
-
`)){let o=r.trim();if(!o||o.startsWith("[Empty]"))continue;let i=o.split(/\s+/),s=i[0];if(!s||s.startsWith("[Empty]"))continue;let a=i.length>=2?i[1]:"device";if(a.toLowerCase()==="unauthorized"){
|
|
37
|
+
`),i=o.pop()??"",s=o.map(a=>a.endsWith("\r")?a.slice(0,-1):a).filter(a=>a.length>0);return s.length>0&&t.onData(s,e),i}function Rp(n,e,t){let r=n.endsWith("\r")?n.slice(0,-1):n;r.length>0&&t.onData([r],e)}function qS(n,e){return{stdout:n.stdoutChunks.join(""),stderr:n.stderrChunks.join(""),exitCode:e??-1}}function JS(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function YS(n,e,t,r,o){n.stdout?.on("data",i=>{let s=i.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=Tp(e.stdoutLineBuffer+s,"stdout",t)}),n.stderr?.on("data",i=>{let s=i.toString();e.stderrChunks.push(s),e.stderrLineBuffer=Tp(e.stderrLineBuffer+s,"stderr",t)}),n.on("error",i=>{e.settled||(e.settled=!0,t.onError(i),o(i))}),n.on("close",i=>{if(e.settled)return;e.settled=!0,Rp(e.stdoutLineBuffer,"stdout",t),Rp(e.stderrLineBuffer,"stderr",t),t.onClose(i);let s=qS(e,i);r(s)})}async function Po(n,e=[],t={}){try{let{stdout:r,stderr:o}=await zS(n,e,t);return{stdout:typeof r=="string"?r.trim():"",stderr:typeof o=="string"?o.trim():"",exitCode:0}}catch(r){let o=r;return{stdout:o.stdout?.trim()||"",stderr:o.stderr?.trim()||o.message,exitCode:typeof o.code=="number"?o.code:1}}}async function xp(n,e,t){return await new Promise((r,o)=>{let i=VS(n,e,{stdio:["inherit","pipe","pipe"]}),s=JS();YS(i,s,t,r,o)})}function Np(n){let e=n.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var KS=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],XS=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function gr(n){return n?KS.some(e=>e.test(n))?"transient":XS.some(e=>e.test(n))?"fatal":"ok":"ok"}var Mc=[800,1500,2500];function ZS(n){return new Promise(e=>setTimeout(e,n))}async function oe(n,e){let t=1+Mc.length,r={stdout:"",stderr:"",exitCode:-1};for(let o=0;o<t;o++){if(r=await Po(n,e),r.exitCode===0||gr(r.stderr)!=="transient"||o>=t-1)return r;h(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${Mc[o]}ms`),await ZS(Mc[o])}return r}var Lp=/^[\w.-]+$/;async function ns(n,e,t){if(!Lp.test(t)){h(`Skipping invalid param key: ${JSON.stringify(t)}`);return}let r=["-t",e,"shell","param","get",t];h(`Executing: ${n} ${r.join(" ")}`);let o=await oe(n,r);if(o.exitCode!==0)return;let i=o.stdout.trim();if(!(!i||gr(i)!=="ok"))return Np(i)}var _c="__DEVECO_PARAM_DELIM__";function QS(n,e){let t=new Map,r=n.split(_c);for(let o=0;o<e.length;o++){let i=(r[o]??"").trim();if(!i||gr(i)!=="ok")continue;let s=Np(i);s&&t.set(e[o],s)}return t}async function yr(n,e,t){let r=t.filter(a=>Lp.test(a)?!0:(h(`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 ns(n,e,r[0]);return c&&a.set(r[0],c),a}let o=r.map(a=>`param get ${a}`).join(`; echo ${_c}; `)+`; echo ${_c}`,i=await oe(n,["-t",e,"shell",o]);if(i.exitCode===0){let a=QS(i.stdout,r);if(a.size>0)return a}h(`Batched param fetch failed (exit=${i.exitCode}), falling back to individual calls for ${e}`);let s=new Map;for(let a of r){let c=await ns(n,e,a);c&&s.set(a,c)}return s}function Ct(n){return n.startsWith("127.0.0.1:")}var Op=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],ie=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(),o=t?.trim();if(!r||!o)return r;let i=new RegExp(`^${this.escapeRegExp(o)}(\\s+|[-_]+)?`,"i");return r.replace(i,"").trim()||r}async executeHdc(e){return h(`Executing: ${this.hdcPath} ${e.join(" ")}`),eb(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let r of e.split(`
|
|
38
|
+
`)){let o=r.trim();if(!o||o.startsWith("[Empty]"))continue;let i=o.split(/\s+/),s=i[0];if(!s||s.startsWith("[Empty]"))continue;let a=i.length>=2?i[1]:"device";if(a.toLowerCase()==="unauthorized"){h(`[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 o=e.get("const.product.model");if(o&&o!=="emulator"){let s=e.get("const.product.brand");return this.stripBrandPrefix(o,s)}let i=e.get("const.build.product");if(i&&i!=="emulator")return i}async getDeviceName(e){let t=await yr(this.hdcPath,e,[...Op]);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 o=t.toLowerCase(),i=[];for(let s of e){let a=await this.getDeviceName(s.serial);a.toLowerCase()===o&&i.push({device:s,name:a})}if(i.length===1)return i[0].device;throw i.length>1?new v(`Multiple devices match "${t}". Use a serial instead:
|
|
31
39
|
`+i.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 tr(this.hdcPath,e,["const.product.devicetype","const.ohos.apiversion","const.ohos.releasetype"]);t.deviceType=r.get("const.product.devicetype");let o=r.get("const.ohos.apiversion"),i=r.get("const.ohos.releasetype");o&&(t.osVersion=i?`API ${o} (${i})`:`API ${o}`)}catch{}return t}async listDevicesWithName(){let e=await this.listDevices();return Promise.all(e.map(async t=>({serial:t.serial,name:await this.getDeviceName(t.serial)})))}async getConnectedEntries(){let e=await this.listDevices();return Promise.all(e.map(t=>this.buildConnectedEntry(t.serial)))}async buildConnectedEntry(e){let t=ft(e),r,o;try{let i=await tr(this.hdcPath,e,[...Fu]);r=this.extractDisplayName(i),o=i.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:o}}};var Gt=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:o}=await kv(r,e,{env:{...process.env}});return o}catch(o){if(t)throw o;return o.stdout||""}}async listTargets(){return(await this.deviceManager.listDevicesWithName()).map(t=>({name:t.name,id:t.serial}))}async uninstallApp(e,t){b.assertBundleNameStrict(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 o=`/data/local/tmp/${Rv()}`;try{await this.runHdc(["-t",e,"shell","mkdir",o]);for(let s of t){let a=await this.runHdc(["-t",e,"file","send",s,o+"/"]);if(!a.startsWith("FileTransfer finish"))throw new Error(a)}let i=await this.runHdc(["-t",e,"shell","bm","install","-p",o]);if(!i.includes("install bundle successfully."))throw new Error(i);console.log("App installed successfully")}finally{await this.runHdc(["-t",e,"shell","rm","-rf",o],!1)}}async launchApp(e,t,r){b.assertBundleNameStrict(t),b.assertAbilityName(r);let o=["-t",e,"shell","aa","start","-a",r,"-b",t];return await this.runHdc(o)}async forceStopApp(e,t){b.assertBundleNameStrict(t);let r=["-t",e,"shell","aa","force-stop",t];return await this.runHdc(r,!1)}};import uc from"fs";import*as Tn from"path";function ro(n,e){if(!uc.existsSync(n))throw new Error(`Apply file list not found: ${n}`);let r=uc.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 o=Tn.resolve(e),i=new Set,s=[];for(let a of r){let c=Tn.resolve(o,a),l=Tn.isAbsolute(a)?Tn.relative(o,a):a;if(l.startsWith(".."))throw new Error(`File path is outside the project directory: ${a}`);let d=b.isPathContainedWithSymlink(l,o);if(!d.contained){if(!uc.existsSync(c))throw new Error(`File not found: ${a}`);let g=d.reason?`; ${d.reason}`:"";throw new Error(`File path is outside the project directory: ${a}${g}`)}i.has(c)||(i.add(c),s.push(c))}return s}import pc from"fs";import oo from"path";import{execa as Nv}from"execa";import ju from"fs";import*as $u from"path";import Tv from"json5";function xv(n,e){try{let r=Tv.parse(ju.readFileSync(n,"utf-8")).modules?.find(o=>o.name===e);return r?.srcPath?r.srcPath.replace(/^\.\//,""):null}catch(t){return m(`[apply] resolveModuleSrcPath fallback (module=${e}): ${t.message}`),null}}function mt(n,e){let t=$u.join(n,"build-profile.json5");return ju.existsSync(t)?xv(t,e)??e:e}async function Hu(n,e,t,r){let o=oo.dirname(n.javaPath),i={...process.env,PATH:`${o}${oo.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 Nv(n.nodePath,s,{cwd:e,env:i,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=>Ov(e,l,r))}function Uu(n,e,t){let r=mt(n,e);return oo.join(n,r,"build",t,"outputs")}function Lv(n,e,t){return oo.join(Uu(n,e,t),`${e}-${t}-signed.hqf`)}function Ov(n,e,t){let r=Uu(n,e,t),o=Lv(n,e,t);if(pc.existsSync(o))return o;let i=fc(r,"-signed.hqf")??fc(r,".hqf");if(!i)throw new Error(`Signed hqf not found at ${o} (and no *.hqf under ${r})`);return m(`[buildSignedHqf] signed hqf not at exact path, using fallback: ${i}`),i}function fc(n,e){if(!pc.existsSync(n))return null;for(let t of pc.readdirSync(n,{withFileTypes:!0})){let r=oo.join(n,t.name);if(t.isDirectory()){let o=fc(r,e);if(o)return o}else if(t.isFile()&&t.name.endsWith(e))return r}return null}import q from"fs";import*as N from"path";import mc from"json5";var Bu="default",nr=class n{static writeChangedFileLists(e,t,r,o){let i=t||Bu,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),g=n.collectChanges(r,e,a,l,d);return{writtenModules:n.flushCollectors(e,i,c,d,o),skippedFiles:g}}static initEmptyChangedFileLists(e,t,r){let o=t||Bu,i=n.loadBuildProfile(e);if(!i)return[];let s=i.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,o,c.srcPath,d),a.push(c.name)}return a}static filterRunnableModules(e,t){return t.filter(r=>{let o=n.getModuleType(e,r.srcPath);return o==="entry"||o==="shared"})}static createCollectors(e){let t=new Map;for(let r of e)t.set(r.name,{hotReloadEntries:[],patchEtsFiles:[],patchRawFiles:[],patchResFiles:[],nativeFiles:[]});return t}static collectChanges(e,t,r,o,i){let s=[];for(let a of e){let c=N.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 g=n.resolveTargetModules(d,t,r,o);if(g.length===0){s.push(c);continue}n.dispatchToCollectors(g,i,c,l,d.srcPath,t)}return s}static resolveTargetModules(e,t,r,o){let i=n.getModuleType(t,e.srcPath);return i==="entry"||i==="shared"?[e.name]:Array.from(n.findTopLevelConsumers(e.name,o,t,r))}static dispatchToCollectors(e,t,r,o,i,s){for(let a of e){let c=t.get(a);c&&n.addFileToCollector(c,r,o.fileClass,i,s)}}static flushCollectors(e,t,r,o,i){let s=[];for(let a of r){let c=o.get(a.name);if(!c||!n.hasAnyChange(c))continue;(!i||a.name===i)&&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||e.nativeFiles.length>0}static initEmptyForModule(e,t,r,o){let i=N.join(e,r,"build",t,"intermediates","patch","default"),s=N.join(i,"changedFileList.json");if(q.existsSync(s)||(q.mkdirSync(i,{recursive:!0}),q.writeFileSync(s,JSON.stringify({resources:{resFile:[],rawFile:[]},modifiedFiles:[]}),"utf-8")),!o)return;let a=N.join(e,r,"build",t,"intermediates","hotReload"),c=N.join(a,"changedFileList.json");q.existsSync(c)||(q.mkdirSync(a,{recursive:!0}),q.writeFileSync(c,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=N.join(e,"build-profile.json5");if(!q.existsSync(t))return null;try{let r=q.readFileSync(t,"utf-8");return mc.parse(r)}catch{return null}}static classifyFile(e,t,r){let o=N.extname(e).toLowerCase();if(o===".ets"||o===".ts")return{fileClass:"ets_ts",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""};if(o===".cpp"||o===".cc"||o===".c"||o===".h"||o===".hpp")return{fileClass:"native",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""};let i=e.replace(/\\/g,"/");return i.includes("/resources/rawfile/")?{fileClass:"raw_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:i.includes("/resources/resfile/")?{fileClass:"res_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:{fileClass:"unknown",moduleSrcPath:""}}static findModuleByFilePath(e,t,r){let o=N.normalize(e);for(let i of r){let s=N.normalize(N.join(t,i.srcPath)),a=s+N.sep;if(o.startsWith(a)||o===s)return i}return null}static getModuleType(e,t){let r=N.join(e,t,"src","main","module.json5");if(!q.existsSync(r))return"entry";try{let o=q.readFileSync(r,"utf-8");return mc.parse(o)?.module?.type||"entry"}catch{return"entry"}}static buildReverseDependencyMap(e,t){let r=new Map;for(let o of t){let i=n.readLocalDependencies(e,o.srcPath);for(let s of i){let a=r.get(s)||[];a.includes(o.name)||a.push(o.name),r.set(s,a)}}return r}static readLocalDependencies(e,t){let r=N.join(e,t,"oh-package.json5");if(!q.existsSync(r))return[];try{let o=q.readFileSync(r,"utf-8"),i=mc.parse(o);return n.resolveDepModuleNames(e,t,i.dependencies||{})}catch{return[]}}static resolveDepModuleNames(e,t,r){let o=n.loadBuildProfile(e);if(!o)return[];let i=o.modules,s=[];for(let a of Object.values(r)){if(typeof a!="string")continue;let c=n.tryResolveDepModule(e,t,a,i);c&&s.push(c)}return s}static tryResolveDepModule(e,t,r,o){let i=r;if(!(i.startsWith("file:")||i.startsWith(".")||i.startsWith("..")))return null;i.startsWith("file:")&&(i=i.substring(5));let a=N.resolve(e,t,i);return o.find(l=>N.resolve(e,l.srcPath)===a)?.name??null}static findTopLevelConsumers(e,t,r,o){let i=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,o,i,a))}return i}static processDependents(e,t,r,o,i,s){let a=t.get(e)||[];for(let c of a){let l=o.find(g=>g.name===c);if(!l)continue;let d=n.getModuleType(r,l.srcPath);(d==="entry"||d==="shared")&&i.add(c),d==="har"&&s.push(c)}}static addFileToCollector(e,t,r,o,i){let s=N.join(i,o,"src","main","resources");r==="ets_ts"?(e.hotReloadEntries.push({filePath:t,belongProjectPath:i}),e.patchEtsFiles.push(t)):r==="raw_file"?e.patchRawFiles.push({filePath:t,resourcePath:s}):r==="res_file"?e.patchResFiles.push({filePath:t,resourcePath:s}):r==="native"&&e.nativeFiles.push(t)}static writeApplyFile(e,t,r,o){let i=t.replace(/^\.\//,""),s=N.join(e,i,"build",r,"intermediates","hotReload","changedFileList.json"),a=n.readExistingApply(s),c=n.mergeApplyEntries(a,o),l=N.dirname(s);q.existsSync(l)||q.mkdirSync(l,{recursive:!0}),q.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),m(`[ChangedFileListWriter] Written hotReload: ${s} (${c.length} entries)`)}static readExistingApply(e){if(!q.existsSync(e))return[];try{let t=q.readFileSync(e,"utf-8");return JSON.parse(t)?.modifiedFilesV2||[]}catch{return[]}}static writePatchFile(e,t,r,o,i,s){let a=t.replace(/^\.\//,""),c=N.join(e,a,"build",r,"intermediates","patch","default","changedFileList.json"),l=n.readExistingPatch(c),d=N.join(e,a,"src","main","ets"),g=o.map(Ze=>n.resolveRelativePathForPatch(Ze,d)),w=n.mergeStrings(l.modifiedFiles,g),P=n.mergePatchResources(l.rawFile,i),O=n.mergePatchResources(l.resFile,s),ne=N.dirname(c);q.existsSync(ne)||q.mkdirSync(ne,{recursive:!0}),q.writeFileSync(c,JSON.stringify({resources:{resFile:O,rawFile:P},modifiedFiles:w}),"utf-8"),m(`[ChangedFileListWriter] Written patch: ${c}`)}static readExistingPatch(e){if(!q.existsSync(e))return{modifiedFiles:[],rawFile:[],resFile:[]};try{let t=q.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 N.relative(N.normalize(t),N.normalize(e)).replace(/\\/g,"/")}static mergeApplyEntries(e,t){let r=new Set,o=[];for(let i of[...e,...t])r.has(i.filePath)||(r.add(i.filePath),o.push(i));return o}static mergeStrings(e,t){let r=new Set,o=[];for(let i of[...e,...t])r.has(i)||(r.add(i),o.push(i));return o}static mergePatchResources(e,t){let r=new Set,o=[];for(let i of[...e,...t])r.has(i.filePath)||(r.add(i.filePath),o.push(i));return o}};import Mv from"fs";import{randomUUID as _v}from"crypto";import{execa as Fv}from"execa";var rr=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,r){for(let a of t)if(!Mv.existsSync(a)){let c=`Signed hqf file not found: ${a}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}b.assertBundleName(r);let i=`/data/local/tmp/${_v()}`,s=[];try{for(let a=0;a<t.length;a++){let c=`${i}/${r}_${a}.hqf`;s.push(c),await this.pushHqf(e,t[a],i,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",i],!1)}}async pushHqf(e,t,r,o){console.log(`[Apply] Pushing hqf to device ${e}: ${t}`),await this.runHdc(["-t",e,"shell","mkdir","-p",r]);let i=await this.runHdc(["-t",e,"file","send",t,o]);if(!i.startsWith("FileTransfer finish"))throw new Error(`Failed to send hqf: ${i}`)}async executeQuickfix(e,t){console.log(`[Apply] Installing ${t.length} hqf patch(es) via quickfix...`);let r=["-t",e,"shell","bm","quickfix","-a","-f",...t,"-d"];await this.getApiVersion(e)>17&&r.push("-o");let i=await this.runHdc(r,!1);if(m(`[InstallHqf] quickfix output: ${i}`),/succe(?:ed|ss)/i.test(i))return console.log("[Apply] hqf installed successfully."),{success:!0,message:"hqf quickfix installed successfully."};let s=`hqf quickfix install failed. Device response: ${i||"(empty)"}. Please try reinstalling the application.`;return console.error(`[Apply] ${s}`),{success:!1,message:s}}async getApiVersion(e){try{let t=await this.runHdc(["-t",e,"shell","param","get","const.ohos.apiversion"],!1),r=parseInt(t.trim(),10);if(!isNaN(r))return console.log(`[InstallHqf] device API version: ${r}`),r}catch{}return 0}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;m(`[InstallHqf] Executing: ${r} ${e.join(" ")}`);try{let{stdout:o}=await Fv(r,e,{env:{...process.env}});return o}catch(o){if(t)throw o;return o.stdout||""}}};var jv="6.1.1",ji=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}toolProvider;projectRoot;async execute(e){await Cn(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion(jv);let t=ro(e.applyFile,this.projectRoot);console.log(`[Apply] Parsed ${t.length} changed file(s)`);let r=this.writeChangeFileList(e,t),o=await this.buildHqf(e,r);await this.stopApp(e),await this.installHqf(e,o),await this.launchApp(e),console.log("[Apply] Apply complete")}writeChangeFileList(e,t){let r=nr.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 Hu(this.toolProvider,this.projectRoot,t,e.productName)}async installHqf(e,t){console.log(`[Apply] Installing ${t.length} hqf(s) to ${e.targetDeviceId}`);let o=await new rr(this.toolProvider).install(e.targetDeviceId,t,e.bundleName);if(!o.success)throw new Error(`hqf install failed: ${o.message}`);console.log("[Apply] hqf installed")}async stopApp(e){let t=new Gt(this.toolProvider);try{await t.forceStopApp(e.targetDeviceId,e.bundleName),console.log("[Apply] app stopped")}catch(r){console.warn(`[Apply] stop app failed: ${r.message}`)}}async launchApp(e){let t=new Gt(this.toolProvider);try{await t.launchApp(e.targetDeviceId,e.bundleName,e.abilityName),console.log("[Apply] app launched")}catch(r){console.warn(`[Apply] launch app failed: ${r.message}`)}}};import Wu from"fs";import*as j from"path";var $i=class n{static generate(e,t,r,o){let i=mt(e,t),s=j.join(e,i),a=j.join(s,"build","config"),c=n.buildConfig(e,s,r,o);Wu.mkdirSync(a,{recursive:!0}),Wu.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,o){let i=j.dirname(o.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:i,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"}}}};import Vu from"fs";import*as $ from"path";var Hi=class n{static generate(e,t,r,o){let i=mt(e,t),s=$.join(e,i),a=$.join(s,"build","config"),c=n.buildConfig(e,s,r,o);Vu.mkdirSync(a,{recursive:!0}),Vu.writeFileSync($.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),m(`[HotReloadBuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,o){let i=$.dirname(o.nodePath)+$.sep,s=$.join(t,"build",r),a=$.join(s,"intermediates"),c=$.join(a,"loader_out",r),l=$.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:i,projectProfilePath:$.join(e,"build-profile.json5"),localPropertiesPath:$.join(e,"local.properties"),appResource:$.join(l,"ResourceTable.txt"),cachePath:$.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:$.join(a,"loader",r,"loader.json"),aceModuleJsonPath:$.join(l,"module.json"),aceSoPath:$.join(c,"nativeDependencies.txt"),aceModuleRoot:$.join(t,"src","main","ets"),aceModuleBuild:$.join(c,"ets"),aceProfilePath:$.join(l,"resources","base","profile"),aceSuperVisualPath:$.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:$.join(c,"ets"),changedFileList:$.join(a,"hotReload","changedFileList.json"),patchAbcPath:$.join(a,"hotReload","patchAbcPath","ets"),removeChangedFileListInSdk:"true"}}}};import Gu from"crypto";import Ve from"fs";import Ge from"path";import zu from"os";import{io as $v}from"socket.io-client";var Hv=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),or=class n{projectRoot;toolProvider;cachedSocket=null;cachedDaemonPort=0;constructor(e,t){this.projectRoot=e,this.toolProvider=t}async sendHotCompile(e){await this.waitForDaemonReady();let t=this.findProjectDaemon();if(!t?.sessionId)throw new Error("No running hvigor daemon with sessionId found. Run `devecocli run --hotreload` first.");return this.sendViaSocket(t,e)}async startWatchSession(e){await this.waitForDaemonReady(),console.log(`[DaemonClient] Compiling, build with: ${JSON.stringify(e)}`);let t=this.findProjectDaemon();if(!t?.sessionId)throw new Error("No running hvigor daemon with sessionId found. Build the hap first.");let r=await this.getOrCreateSocket(t),o=this.watchLogPath;Ve.mkdirSync(Ge.dirname(o),{recursive:!0}),Ve.writeFileSync(o,"");let i=this.createWatchLogBuffer(o);r.on("WatchLog",i.onWatchLog),r.on("WatchResult",i.onWatchResult),await this.awaitInitialBuild(r,e)}createWatchLogBuffer(e){let r=[];return{onWatchLog:s=>{let a=n.extractText(s);a.trim()&&(r.push(a.endsWith(`
|
|
40
|
+
`),"Multiple devices match."):new v(`Device "${t}" not found. Use \`devecocli device list\` to see available targets.`,"Device not found.")}return e[0]}async getDeviceDetail(e){let t={serial:e,status:"device"};try{let r=await yr(this.hdcPath,e,["const.product.devicetype","const.ohos.apiversion","const.ohos.releasetype"]);t.deviceType=r.get("const.product.devicetype");let o=r.get("const.ohos.apiversion"),i=r.get("const.ohos.releasetype");o&&(t.osVersion=i?`API ${o} (${i})`:`API ${o}`)}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=Ct(e),r,o;try{let i=await yr(this.hdcPath,e,[...Op]);r=this.extractDisplayName(i),o=i.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:o}}};var tn=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=ie.from(e)}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;h(`Executing: ${r} ${e.join(" ")}`);try{let{stdout:o}=await nb(r,e,{env:{...process.env}});return o}catch(o){if(t)throw o;return o.stdout||""}}async listTargets(){return(await this.deviceManager.listDevicesWithName()).map(t=>({name:t.name,id:t.serial}))}async uninstallApp(e,t){C.assertBundleNameStrict(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 o=`/data/local/tmp/${tb()}`;try{await this.runHdc(["-t",e,"shell","mkdir",o]);for(let s of t){let a=await this.runHdc(["-t",e,"file","send",s,o+"/"]);if(!a.startsWith("FileTransfer finish"))throw new Error(a)}let i=await this.runHdc(["-t",e,"shell","bm","install","-p",o]);if(!i.includes("install bundle successfully."))throw new Error(i);console.log("App installed successfully")}finally{await this.runHdc(["-t",e,"shell","rm","-rf",o],!1)}}async launchApp(e,t,r){C.assertBundleNameStrict(t),C.assertAbilityName(r);let o=["-t",e,"shell","aa","start","-a",r,"-b",t];return await this.runHdc(o)}async forceStopApp(e,t){C.assertBundleNameStrict(t);let r=["-t",e,"shell","aa","force-stop",t];return await this.runHdc(r,!1)}};import Fc from"fs";import*as Wn from"path";function Co(n,e){if(!Fc.existsSync(n))throw new Error(`Apply file list not found: ${n}`);let r=Fc.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 o=Wn.resolve(e),i=new Set,s=[];for(let a of r){let c=Wn.resolve(o,a),l=Wn.isAbsolute(a)?Wn.relative(o,a):a;if(l.startsWith(".."))throw new Error(`File path is outside the project directory: ${a}`);let d=C.isPathContainedWithSymlink(l,o);if(!d.contained){if(!Fc.existsSync(c))throw new Error(`File not found: ${a}`);let g=d.reason?`; ${d.reason}`:"";throw new Error(`File path is outside the project directory: ${a}${g}`)}i.has(c)||(i.add(c),s.push(c))}return s}import jc from"fs";import Io from"path";import{execa as ib}from"execa";import Mp from"fs";import*as _p from"path";import rb from"json5";function ob(n,e){try{let r=rb.parse(Mp.readFileSync(n,"utf-8")).modules?.find(o=>o.name===e);return r?.srcPath?r.srcPath.replace(/^\.\//,""):null}catch(t){return h(`[apply] resolveModuleSrcPath fallback (module=${e}): ${t.message}`),null}}function It(n,e){let t=_p.join(n,"build-profile.json5");return Mp.existsSync(t)?ob(t,e)??e:e}async function Fp(n,e,t,r){let o=Io.dirname(n.javaPath),i={...process.env,PATH:`${o}${Io.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"];h(`[buildSignedHqf] ${n.nodePath} ${s.join(" ")}`);let a=await ib(n.nodePath,s,{cwd:e,env:i,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=>ab(e,l,r))}function jp(n,e,t){let r=It(n,e);return Io.join(n,r,"build",t,"outputs")}function sb(n,e,t){return Io.join(jp(n,e,t),`${e}-${t}-signed.hqf`)}function ab(n,e,t){let r=jp(n,e,t),o=sb(n,e,t);if(jc.existsSync(o))return o;let i=$c(r,"-signed.hqf")??$c(r,".hqf");if(!i)throw new Error(`Signed hqf not found at ${o} (and no *.hqf under ${r})`);return h(`[buildSignedHqf] signed hqf not at exact path, using fallback: ${i}`),i}function $c(n,e){if(!jc.existsSync(n))return null;for(let t of jc.readdirSync(n,{withFileTypes:!0})){let r=Io.join(n,t.name);if(t.isDirectory()){let o=$c(r,e);if(o)return o}else if(t.isFile()&&t.name.endsWith(e))return r}return null}import K from"fs";import*as L from"path";import Hc from"json5";var $p="default",wr=class n{static writeChangedFileLists(e,t,r,o){let i=t||$p,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),g=n.collectChanges(r,e,a,l,d);return{writtenModules:n.flushCollectors(e,i,c,d,o),skippedFiles:g}}static initEmptyChangedFileLists(e,t,r){let o=t||$p,i=n.loadBuildProfile(e);if(!i)return[];let s=i.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,o,c.srcPath,d),a.push(c.name)}return a}static filterRunnableModules(e,t){return t.filter(r=>{let o=n.getModuleType(e,r.srcPath);return o==="entry"||o==="shared"})}static createCollectors(e){let t=new Map;for(let r of e)t.set(r.name,{hotReloadEntries:[],patchEtsFiles:[],patchRawFiles:[],patchResFiles:[],nativeFiles:[]});return t}static collectChanges(e,t,r,o,i){let s=[];for(let a of e){let c=L.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 g=n.resolveTargetModules(d,t,r,o);if(g.length===0){s.push(c);continue}n.dispatchToCollectors(g,i,c,l,d.srcPath,t)}return s}static resolveTargetModules(e,t,r,o){let i=n.getModuleType(t,e.srcPath);return i==="entry"||i==="shared"?[e.name]:Array.from(n.findTopLevelConsumers(e.name,o,t,r))}static dispatchToCollectors(e,t,r,o,i,s){for(let a of e){let c=t.get(a);c&&n.addFileToCollector(c,r,o.fileClass,i,s)}}static flushCollectors(e,t,r,o,i){let s=[];for(let a of r){let c=o.get(a.name);if(!c||!n.hasAnyChange(c))continue;(!i||a.name===i)&&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||e.nativeFiles.length>0}static initEmptyForModule(e,t,r,o){let i=L.join(e,r,"build",t,"intermediates","patch","default"),s=L.join(i,"changedFileList.json");if(K.existsSync(s)||(K.mkdirSync(i,{recursive:!0}),K.writeFileSync(s,JSON.stringify({resources:{resFile:[],rawFile:[]},modifiedFiles:[]}),"utf-8")),!o)return;let a=L.join(e,r,"build",t,"intermediates","hotReload"),c=L.join(a,"changedFileList.json");K.existsSync(c)||(K.mkdirSync(a,{recursive:!0}),K.writeFileSync(c,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=L.join(e,"build-profile.json5");if(!K.existsSync(t))return null;try{let r=K.readFileSync(t,"utf-8");return Hc.parse(r)}catch{return null}}static classifyFile(e,t,r){let o=L.extname(e).toLowerCase();if(o===".ets"||o===".ts")return{fileClass:"ets_ts",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""};if(o===".cpp"||o===".cc"||o===".c"||o===".h"||o===".hpp")return{fileClass:"native",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""};let i=e.replace(/\\/g,"/");return i.includes("/resources/rawfile/")?{fileClass:"raw_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:i.includes("/resources/resfile/")?{fileClass:"res_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:{fileClass:"unknown",moduleSrcPath:""}}static findModuleByFilePath(e,t,r){let o=L.normalize(e);for(let i of r){let s=L.normalize(L.join(t,i.srcPath)),a=s+L.sep;if(o.startsWith(a)||o===s)return i}return null}static getModuleType(e,t){let r=L.join(e,t,"src","main","module.json5");if(!K.existsSync(r))return"entry";try{let o=K.readFileSync(r,"utf-8");return Hc.parse(o)?.module?.type||"entry"}catch{return"entry"}}static buildReverseDependencyMap(e,t){let r=new Map;for(let o of t){let i=n.readLocalDependencies(e,o.srcPath);for(let s of i){let a=r.get(s)||[];a.includes(o.name)||a.push(o.name),r.set(s,a)}}return r}static readLocalDependencies(e,t){let r=L.join(e,t,"oh-package.json5");if(!K.existsSync(r))return[];try{let o=K.readFileSync(r,"utf-8"),i=Hc.parse(o);return n.resolveDepModuleNames(e,t,i.dependencies||{})}catch{return[]}}static resolveDepModuleNames(e,t,r){let o=n.loadBuildProfile(e);if(!o)return[];let i=o.modules,s=[];for(let a of Object.values(r)){if(typeof a!="string")continue;let c=n.tryResolveDepModule(e,t,a,i);c&&s.push(c)}return s}static tryResolveDepModule(e,t,r,o){let i=r;if(!(i.startsWith("file:")||i.startsWith(".")||i.startsWith("..")))return null;i.startsWith("file:")&&(i=i.substring(5));let a=L.resolve(e,t,i);return o.find(l=>L.resolve(e,l.srcPath)===a)?.name??null}static findTopLevelConsumers(e,t,r,o){let i=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,o,i,a))}return i}static processDependents(e,t,r,o,i,s){let a=t.get(e)||[];for(let c of a){let l=o.find(g=>g.name===c);if(!l)continue;let d=n.getModuleType(r,l.srcPath);(d==="entry"||d==="shared")&&i.add(c),d==="har"&&s.push(c)}}static addFileToCollector(e,t,r,o,i){let s=L.join(i,o,"src","main","resources");r==="ets_ts"?(e.hotReloadEntries.push({filePath:t,belongProjectPath:i}),e.patchEtsFiles.push(t)):r==="raw_file"?e.patchRawFiles.push({filePath:t,resourcePath:s}):r==="res_file"?e.patchResFiles.push({filePath:t,resourcePath:s}):r==="native"&&e.nativeFiles.push(t)}static writeApplyFile(e,t,r,o){let i=t.replace(/^\.\//,""),s=L.join(e,i,"build",r,"intermediates","hotReload","changedFileList.json"),a=n.readExistingApply(s),c=n.mergeApplyEntries(a,o),l=L.dirname(s);K.existsSync(l)||K.mkdirSync(l,{recursive:!0}),K.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),h(`[ChangedFileListWriter] Written hotReload: ${s} (${c.length} entries)`)}static readExistingApply(e){if(!K.existsSync(e))return[];try{let t=K.readFileSync(e,"utf-8");return JSON.parse(t)?.modifiedFilesV2||[]}catch{return[]}}static writePatchFile(e,t,r,o,i,s){let a=t.replace(/^\.\//,""),c=L.join(e,a,"build",r,"intermediates","patch","default","changedFileList.json"),l=n.readExistingPatch(c),d=L.join(e,a,"src","main","ets"),g=o.map(we=>n.resolveRelativePathForPatch(we,d)),w=n.mergeStrings(l.modifiedFiles,g),b=n.mergePatchResources(l.rawFile,i),$=n.mergePatchResources(l.resFile,s),ne=L.dirname(c);K.existsSync(ne)||K.mkdirSync(ne,{recursive:!0}),K.writeFileSync(c,JSON.stringify({resources:{resFile:$,rawFile:b},modifiedFiles:w}),"utf-8"),h(`[ChangedFileListWriter] Written patch: ${c}`)}static readExistingPatch(e){if(!K.existsSync(e))return{modifiedFiles:[],rawFile:[],resFile:[]};try{let t=K.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 L.relative(L.normalize(t),L.normalize(e)).replace(/\\/g,"/")}static mergeApplyEntries(e,t){let r=new Set,o=[];for(let i of[...e,...t])r.has(i.filePath)||(r.add(i.filePath),o.push(i));return o}static mergeStrings(e,t){let r=new Set,o=[];for(let i of[...e,...t])r.has(i)||(r.add(i),o.push(i));return o}static mergePatchResources(e,t){let r=new Set,o=[];for(let i of[...e,...t])r.has(i.filePath)||(r.add(i.filePath),o.push(i));return o}};import cb from"fs";import{randomUUID as lb}from"crypto";import{execa as db}from"execa";var vr=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,r){for(let a of t)if(!cb.existsSync(a)){let c=`Signed hqf file not found: ${a}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}C.assertBundleName(r);let i=`/data/local/tmp/${lb()}`,s=[];try{for(let a=0;a<t.length;a++){let c=`${i}/${r}_${a}.hqf`;s.push(c),await this.pushHqf(e,t[a],i,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",i],!1)}}async pushHqf(e,t,r,o){console.log(`[Apply] Pushing hqf to device ${e}: ${t}`),await this.runHdc(["-t",e,"shell","mkdir","-p",r]);let i=await this.runHdc(["-t",e,"file","send",t,o]);if(!i.startsWith("FileTransfer finish"))throw new Error(`Failed to send hqf: ${i}`)}async executeQuickfix(e,t){console.log(`[Apply] Installing ${t.length} hqf patch(es) via quickfix...`);let r=["-t",e,"shell","bm","quickfix","-a","-f",...t,"-d"];await this.getApiVersion(e)>17&&r.push("-o");let i=await this.runHdc(r,!1);if(h(`[InstallHqf] quickfix output: ${i}`),/succe(?:ed|ss)/i.test(i))return console.log("[Apply] hqf installed successfully."),{success:!0,message:"hqf quickfix installed successfully."};let s=`hqf quickfix install failed. Device response: ${i||"(empty)"}. Please try reinstalling the application.`;return console.error(`[Apply] ${s}`),{success:!1,message:s}}async getApiVersion(e){try{let t=await this.runHdc(["-t",e,"shell","param","get","const.ohos.apiversion"],!1),r=parseInt(t.trim(),10);if(!isNaN(r))return console.log(`[InstallHqf] device API version: ${r}`),r}catch{}return 0}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;h(`[InstallHqf] Executing: ${r} ${e.join(" ")}`);try{let{stdout:o}=await db(r,e,{env:{...process.env}});return o}catch(o){if(t)throw o;return o.stdout||""}}};var ub="6.1.1",rs=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}toolProvider;projectRoot;async execute(e){await Hn(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion(ub);let t=Co(e.applyFile,this.projectRoot);console.log(`[Apply] Parsed ${t.length} changed file(s)`);let r=this.writeChangeFileList(e,t),o=await this.buildHqf(e,r);await this.stopApp(e),await this.installHqf(e,o),await this.launchApp(e),console.log("[Apply] Apply complete")}writeChangeFileList(e,t){let r=wr.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 h(`[Apply] hvigor assembleDevHqf --no-daemon (modules=${t.join(",")})`),await Fp(this.toolProvider,this.projectRoot,t,e.productName)}async installHqf(e,t){console.log(`[Apply] Installing ${t.length} hqf(s) to ${e.targetDeviceId}`);let o=await new vr(this.toolProvider).install(e.targetDeviceId,t,e.bundleName);if(!o.success)throw new Error(`hqf install failed: ${o.message}`);console.log("[Apply] hqf installed")}async stopApp(e){let t=new tn(this.toolProvider);try{await t.forceStopApp(e.targetDeviceId,e.bundleName),console.log("[Apply] app stopped")}catch(r){console.warn(`[Apply] stop app failed: ${r.message}`)}}async launchApp(e){let t=new tn(this.toolProvider);try{await t.launchApp(e.targetDeviceId,e.bundleName,e.abilityName),console.log("[Apply] app launched")}catch(r){console.warn(`[Apply] launch app failed: ${r.message}`)}}};import Hp from"fs";import*as H from"path";var os=class n{static generate(e,t,r,o){let i=It(e,t),s=H.join(e,i),a=H.join(s,"build","config"),c=n.buildConfig(e,s,r,o);Hp.mkdirSync(a,{recursive:!0}),Hp.writeFileSync(H.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),h(`[BuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,o){let i=H.dirname(o.nodePath)+H.sep,s=H.join(t,"build",r),a=H.join(s,"intermediates"),c=H.join(a,"loader_out",r),l=H.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:i,projectProfilePath:H.join(e,"build-profile.json5"),localPropertiesPath:H.join(e,"local.properties"),appResource:H.join(l,"ResourceTable.txt"),cachePath:H.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:H.join(a,"loader",r,"loader.json"),aceModuleJsonPath:H.join(l,"module.json"),aceSoPath:H.join(c,"nativeDependencies.txt"),aceModuleRoot:H.join(t,"src","main","ets"),aceModuleBuild:H.join(c,"ets"),aceProfilePath:H.join(l,"resources","base","profile"),aceSuperVisualPath:H.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:H.join(c,"ets"),changedFileList:H.join(a,"patch","default","changedFileList.json"),patchAbcPath:H.join(a,"patch","default","ets"),removeChangedFileListInSdk:"true"}}}};import Up from"fs";import*as U from"path";var is=class n{static generate(e,t,r,o){let i=It(e,t),s=U.join(e,i),a=U.join(s,"build","config"),c=n.buildConfig(e,s,r,o);Up.mkdirSync(a,{recursive:!0}),Up.writeFileSync(U.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),h(`[HotReloadBuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,o){let i=U.dirname(o.nodePath)+U.sep,s=U.join(t,"build",r),a=U.join(s,"intermediates"),c=U.join(a,"loader_out",r),l=U.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:i,projectProfilePath:U.join(e,"build-profile.json5"),localPropertiesPath:U.join(e,"local.properties"),appResource:U.join(l,"ResourceTable.txt"),cachePath:U.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:U.join(a,"loader",r,"loader.json"),aceModuleJsonPath:U.join(l,"module.json"),aceSoPath:U.join(c,"nativeDependencies.txt"),aceModuleRoot:U.join(t,"src","main","ets"),aceModuleBuild:U.join(c,"ets"),aceProfilePath:U.join(l,"resources","base","profile"),aceSuperVisualPath:U.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:U.join(c,"ets"),changedFileList:U.join(a,"hotReload","changedFileList.json"),patchAbcPath:U.join(a,"hotReload","patchAbcPath","ets"),removeChangedFileListInSdk:"true"}}}};import Bp from"crypto";import Ze from"fs";import Qe from"path";import Wp from"os";import{io as pb}from"socket.io-client";var mb=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Sr=class n{projectRoot;toolProvider;cachedSocket=null;cachedDaemonPort=0;constructor(e,t){this.projectRoot=e,this.toolProvider=t}async sendHotCompile(e){await this.waitForDaemonReady();let t=this.findProjectDaemon();if(!t?.sessionId)throw new Error("No running hvigor daemon with sessionId found. Run `devecocli run --hotreload` first.");return this.sendViaSocket(t,e)}async startWatchSession(e){await this.waitForDaemonReady(),console.log(`[DaemonClient] Compiling, build with: ${JSON.stringify(e)}`);let t=this.findProjectDaemon();if(!t?.sessionId)throw new Error("No running hvigor daemon with sessionId found. Build the hap first.");let r=await this.getOrCreateSocket(t),o=this.watchLogPath;Ze.mkdirSync(Qe.dirname(o),{recursive:!0}),Ze.writeFileSync(o,"");let i=this.createWatchLogBuffer(o);r.on("WatchLog",i.onWatchLog),r.on("WatchResult",i.onWatchResult),await this.awaitInitialBuild(r,e)}createWatchLogBuffer(e){let r=[];return{onWatchLog:s=>{let a=n.extractText(s);a.trim()&&(r.push(a.endsWith(`
|
|
33
41
|
`)?a:a+`
|
|
34
|
-
`),r.length>100&&r.shift())},onWatchResult:s=>{let a=n.extractText(s);if(!a.trim())return;let c=`[WatchResult] ${a}`;console.log(c),
|
|
35
|
-
`].join("")),r.length=0}}}awaitInitialBuild(e,t){return new Promise((r,o)=>{let i=!1,s=this.createOutputHandler(),a=l=>{!l?.status||i||(l.status==="finish"?(i=!0,e.off("disconnect",c),e.off("Output",s),e.off("BuildStatus",a),r()):(l.status==="reject"||l.status==="close")&&(i=!0,e.off("disconnect",c),e.off("Output",s),e.off("BuildStatus",a),this.invalidateSocket(),o(new Error(l.reason||`Watch-session build ${l.status}`))))},c=l=>{i||(i=!0,o(new Error(`Socket disconnected: ${l}`)))};e.on("disconnect",c),e.on("Output",s),e.on("BuildStatus",a),e.emit("CommonBuild",this.buildStartOptions(t)),console.log("[DaemonClient] Compiling, waiting for build to finish...")})}getWatchLogPath(){return this.watchLogPath}get watchLogPath(){return
|
|
42
|
+
`),r.length>100&&r.shift())},onWatchResult:s=>{let a=n.extractText(s);if(!a.trim())return;let c=`[WatchResult] ${a}`;console.log(c),Ze.writeFileSync(e,[...r,c+`
|
|
43
|
+
`].join("")),r.length=0}}}awaitInitialBuild(e,t){return new Promise((r,o)=>{let i=!1,s=this.createOutputHandler(),a=l=>{!l?.status||i||(l.status==="finish"?(i=!0,e.off("disconnect",c),e.off("Output",s),e.off("BuildStatus",a),r()):(l.status==="reject"||l.status==="close")&&(i=!0,e.off("disconnect",c),e.off("Output",s),e.off("BuildStatus",a),this.invalidateSocket(),o(new Error(l.reason||`Watch-session build ${l.status}`))))},c=l=>{i||(i=!0,o(new Error(`Socket disconnected: ${l}`)))};e.on("disconnect",c),e.on("Output",s),e.on("BuildStatus",a),e.emit("CommonBuild",this.buildStartOptions(t)),console.log("[DaemonClient] Compiling, waiting for build to finish...")})}getWatchLogPath(){return this.watchLogPath}get watchLogPath(){return Qe.join(this.projectRoot,".hvigor","hotreload-watch.log")}buildStartOptions(e){let t={_:["assembleHap"],daemon:!0,watch:!0,hotReloadBuild:!0,mode:"module",prop:[`module=${e.moduleSpecs.join(",")}`,`product=${e.productName}`,"debuggable=true","hotReload=true","requiredDeviceType=phone"],parallel:!0,incremental:!0,analyze:"normal",env:{DEVECO_SDK_HOME:this.toolProvider.sdkPath}};return console.log("[DaemonClient] buildStartOptions:",JSON.stringify(t,null,2)),t}disconnect(){this.invalidateSocket()}onSocketDisconnect(e){this.cachedSocket&&this.cachedSocket.on("disconnect",e)}async getOrCreateSocket(e){if(this.cachedSocket&&this.cachedDaemonPort===e.port){if(this.cachedSocket.connected)return this.cachedSocket;this.invalidateSocket()}let t=this.decryptSessionId(e.sessionId);console.log(`[DaemonClient] Socket.IO connect: ws://127.0.0.1:${e.port} (${e.state})`);let r=pb(`ws://127.0.0.1:${e.port}`,{transports:["websocket"],path:`/${t}`});return await new Promise((o,i)=>{let s=setTimeout(()=>{i(new Error("Socket connect timeout (10s)"))},1e4);r.once("connect",()=>{clearTimeout(s),o()}),r.once("connect_error",a=>{clearTimeout(s),i(new Error(`Socket connect error: ${a.message}`))})}),this.cachedSocket=r,this.cachedDaemonPort=e.port,r}invalidateSocket(){this.cachedSocket&&(this.cachedSocket.removeAllListeners(),this.cachedSocket.disconnect(),this.cachedSocket=null,this.cachedDaemonPort=0)}async sendViaSocket(e,t){let r=await this.getOrCreateSocket(e);return new Promise((o,i)=>{let s=!1,a=Date.now(),c=this.createHotCompileHandlers(r,()=>s,d=>s=d,i),l=d=>{!d?.status||s||(d.status==="finish"?(s=!0,c.detach(),r.off("BuildStatus",l),console.log(`[Timing] abc compile: ${Date.now()-a}ms`),o(d.exitCode??0)):(d.status==="reject"||d.status==="close")&&(s=!0,c.detach(),r.off("BuildStatus",l),this.invalidateSocket(),i(new Error(`Hot compile ${d.status}: ${d.reason||"see WatchLog/Output above for compile errors"}`))))};r.on("disconnect",c.onDisconnect),r.on("Output",c.onOutput),r.on("BuildStatus",l),r.on("WatchLog",c.onWatchLog),r.on("WatchResult",c.onWatchResult),r.on("WatchCompileResult",c.onWatchCompileResult),r.on("WatchCompileData",c.onWatchCompileData),r.emit("CommonBuild",this.buildCompileOptions(t)),console.log("[DaemonClient] Compiling, waiting for hot compile to finish...")})}static extractText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="object"){let t=e;if(typeof t.text=="string")return t.text;if(typeof t.msg=="string")return t.msg;if(typeof t.message=="string")return t.message}return JSON.stringify(e)}createHotCompileHandlers(e,t,r,o){let i=w=>{t()||(r(!0),g(),this.invalidateSocket(),o(new Error(`Socket disconnected: ${w}`)))},s=this.createOutputHandler(),{onWatchLog:a,onWatchResult:c,onWatchCompileResult:l,onWatchCompileData:d}=this.getDataHandler(),g=()=>{e.off("disconnect",i),e.off("Output",s),e.off("WatchLog",a),e.off("WatchResult",c),e.off("WatchCompileResult",l),e.off("WatchCompileData",d)};return{onDisconnect:i,onOutput:s,onWatchLog:a,onWatchResult:c,onWatchCompileResult:l,onWatchCompileData:d,detach:g}}getDataHandler(){let e=n.extractText;return{onWatchLog:s=>{let a=e(s);a.trim()&&process.stdout.write(a+(a.endsWith(`
|
|
36
44
|
`)?"":`
|
|
37
|
-
`))},onWatchResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchResult] ${a}`)},onWatchCompileResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileResult] ${a}`)},onWatchCompileData:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileData] ${a}`)}}}createOutputHandler(){return e=>{let t=typeof e.text=="string"?e.text:Buffer.from(e.text).toString(e.encoding??"utf-8");t.trim()&&(e.type==="stderr"?process.stderr.write(t):process.stdout.write(t))}}buildCompileOptions(e){let t={_:["assembleDevHqf"],daemon:!0,hotCompile:!0,mode:"module",prop:[`module=${e.moduleSpecs.join(",")}`,`product=${e.productName}`,"debuggable=true","hotReload=true","requiredDeviceType=phone"],parallel:!0,incremental:!0,analyze:"normal",env:{DEVECO_SDK_HOME:this.toolProvider.sdkPath}};return console.log("[DaemonClient] buildCompileOptions:",JSON.stringify(t,null,2)),t}async waitForDaemonReady(){let r=Date.now();for(;Date.now()-r<3e4;){let o=this.findProjectDaemon();if(o&&(o.state==="half_busy"||o.state==="idle"))return;await new Promise(i=>setTimeout(i,1e3))}throw new Error("No running hvigor daemon found. Run `devecocli run --hotreload` first.")}findProjectDaemon(){let e=this.getRegistryPath();if(!Ve.existsSync(e))return null;try{let t=Ve.readFileSync(e,"utf-8"),r=JSON.parse(t),o=Object.values(r).filter(i=>i.cwdPath===this.projectRoot&&(i.state==="idle"||i.state==="half_busy"||i.state==="busy")&&this.isProcessAlive(i.pid));return o.length>0?o[o.length-1]:null}catch{return null}}decryptSessionId(e){let t=this.getMetaDir(),r=Ge.join(t,"fd"),o=Ge.join(t,"ac"),i=Ge.join(t,"ce"),s=this.readComponents(r),a=this.xorBuffers([s[0],s[1],s[2],Buffer.from(Hv)]),c=this.readSingleFile(o),l=Gu.pbkdf2Sync(Buffer.from(a).toString(),c,1e4,16,"sha256"),d=this.readSingleFile(i),g=this.aesGcmDecrypt(l,d),w=Buffer.from(e,"hex");return this.aesGcmDecrypt(g,w).toString("utf-8")}aesGcmDecrypt(e,t){let r=0,o=t.readUInt32BE(r);r+=4;let i=t.subarray(r,r+12);r+=12;let s=o-16,a=t.subarray(r,r+s);r+=s;let c=t.subarray(r,r+16),l=Gu.createDecipheriv("aes-128-gcm",e,i);return l.setAuthTag(c),Buffer.concat([l.update(a),l.final()])}readComponents(e){let t=Ve.readdirSync(e).map(r=>Ge.join(e,r)).filter(r=>Ve.statSync(r).isDirectory()).sort();if(t.length<3)throw new Error(`Expected 3 subdirectories in ${e}, found ${t.length}`);return t.slice(0,3).map(r=>{let o=Ve.readdirSync(r);if(o.length===0)throw new Error(`No file in ${r}`);return Ve.readFileSync(Ge.join(r,o[0]))})}readSingleFile(e){let t=Ve.readdirSync(e).map(r=>Ge.join(e,r)).filter(r=>Ve.statSync(r).isFile());if(t.length===0)throw new Error(`No file in ${e}`);return Ve.readFileSync(t[0])}xorBuffers(e){let t=Buffer.alloc(e[0].length);t.set(e[0]);for(let r=1;r<e.length;r++){let o=Buffer.isBuffer(e[r])?e[r]:Buffer.from(e[r]);for(let i=0;i<t.length;i++)t[i]^=o[i]}return t}getRegistryPath(){let e=process.env.HVIGOR_USER_HOME||Ge.join(zu.homedir(),".hvigor");return Ge.join(e,"daemon","cache","daemon-sec.json")}getMetaDir(){let e=process.env.HVIGOR_USER_HOME||Ge.join(zu.homedir(),".hvigor");return Ge.join(e,"meta")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}};import Ju from"fs";import*as Ct from"path";import{green as Vi,yellow as hc}from"colorette";import xn from"fs";import*as Nn from"path";import Uv from"json5";var Bv=2e6,Wv=1e6,Vv="hotreload",Ui=class n{static generateOrUpdate(e,t,r){let o=n.readAppConfig(e),i=Nn.resolve(e,t),s=Nn.join(i,"patch.json"),a;return xn.existsSync(s)?(m(`[PatchManager] patch.json found at ${s}, incrementing patchVersionCode`),a=n.readExistingPatch(s),a.app.patchVersionCode+=1):(m(`[PatchManager] patch.json not found, generating new one at ${s}`),a={app:{bundleName:o.bundleName,patchVersionCode:Bv,versionCode:o.versionCode},module:{name:r,type:Vv}}),n.writePatchJson(s,a),a}static readAppConfig(e){let t=Nn.join(e,"AppScope","app.json5");if(!xn.existsSync(t))throw new Error(`AppScope/app.json5 not found at ${t}. Unable to read bundleName and versionCode.`);let r=xn.readFileSync(t,"utf-8"),o=Uv.parse(r),i=o?.app?.bundleName;if(!i)throw new Error("bundleName is missing in AppScope/app.json5");let s=o?.app?.versionCode??Wv;return{bundleName:i,versionCode:s}}static readExistingPatch(e){let t=xn.readFileSync(e,"utf-8"),r=JSON.parse(t);if(!r?.app?.patchVersionCode)throw new Error(`Invalid patch.json at ${e}: missing app.patchVersionCode`);return r}static writePatchJson(e,t){let r=Nn.dirname(e);xn.existsSync(r)||xn.mkdirSync(r,{recursive:!0});let o=JSON.stringify(t,null,2);xn.writeFileSync(e,o,"utf-8"),m(`[PatchManager] patch.json written to ${e}`),m(`[PatchManager] Content: ${o}`)}};import le from"fs";import*as H from"path";import qu from"crypto";import Gv from"json5";import{execa as Yu}from"execa";var Bi=class n{static COMPONENT=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]);static DIRS=["fd","ac","ce"];static decryptPwd(e,t,r){if(t.length<32||t.length%2!==0)throw new Error(`Invalid encrypted password for ${r}`);m(`[DecipherUtil] Decrypting ${r}, encrypted length: ${t.length}`);let o=H.resolve(e,"material"),i=n.getKey(o,r),s=new Int8Array(Buffer.from(t,"hex"));return m(`[DecipherUtil] Data length: ${s.length}, key length: ${i.length}`),n.decrypt(i,s).toString("utf-8")}static getKey(e,t){let r=H.resolve(e,n.DIRS[0]),o=n.readFd(r,t),i=n.readDirBytes(H.resolve(e,n.DIRS[1]),t),s=n.getRootKey(o,i,t),a=n.readDirBytes(H.resolve(e,n.DIRS[2]),t);return new Int8Array(n.decrypt(s,a))}static getRootKey(e,t,r){if(!e.every(a=>a.length===16))throw new Error(`Signing material data error for ${r}`);let o=[...e,n.COMPONENT],i=n.xor(o[0],o[1],r);for(let a=2;a<o.length;a++)i=n.xor(i,o[a],r);let s=qu.pbkdf2Sync(Buffer.from(i).toString(),Buffer.from(t),1e4,16,"sha256");return new Int8Array(s)}static xor(e,t,r){if(e.byteLength!==t.byteLength)throw new Error(`Signing material data error for ${r}`);let o=new Int8Array(e.byteLength);for(let i=0;i<e.byteLength;i++)o[i]=e[i]^t[i];return o}static decrypt(e,t){let r=(255&t[0])<<24|(255&t[1])<<16|(255&t[2])<<8|255&t[3],o=t.length-4-r,i=t.slice(4,4+o),s=t.slice(t.length-16),a=qu.createDecipheriv("aes-128-gcm",Buffer.from(e),Buffer.from(i));a.setAuthTag(Buffer.from(s));let c=a.update(Buffer.from(t.subarray(4+o,t.length-16))),l=a.final();return Buffer.concat([c,l])}static readFd(e,t){let r=le.readdirSync(e).filter(i=>i!==".DS_Store");if(r.length!==3)throw new Error(`fd directory must have 3 entries for ${t}`);let o=[];for(let i of r){let s=H.join(e,i);o.push(n.readDirBytes(s,t))}return o}static readDirBytes(e,t){if(le.statSync(e).isDirectory()){let o=le.readdirSync(e).filter(i=>i!==".DS_Store");if(o.length!==1)throw new Error(`Expected exactly 1 file in ${e} for ${t}`);return new Int8Array(le.readFileSync(H.join(e,o[0])))}return new Int8Array(le.readFileSync(e))}},Wi=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let o=`${H.dirname(e.javaPath)}${H.delimiter}${process.env.PATH||""}`;this.env={...process.env,PATH:o,DEVECO_SDK_HOME:e.sdkPath}}async generateAndSign(e,t,r,o,i=!1){let s=this.checkAbcExists(t);if(!s.exists)return{signedHqfPaths:[],message:s.message};let a=this.resolveHqfPaths(e,o);return await this.generateHqf(r,s.abcPath,a.unsignedHqfPath)?i?{success:!0,signedHqfPaths:[a.unsignedHqfPath],unsignedHqfPath:a.unsignedHqfPath,message:"Unsigned hqf generated (signing skipped for emulator)."}:this.signHqfDirect(a.unsignedHqfPath,a.signedHqfPath):{signedHqfPaths:[],unsignedHqfPath:a.unsignedHqfPath,message:"Failed to generate unsigned hqf."}}checkAbcExists(e){let t=H.join(e,"ets","modules.abc");if(le.existsSync(t))return{exists:!0,abcPath:t,message:"abc file exists."};let r=this.findFirstAbc(e);return r?{exists:!0,abcPath:r,message:"abc file exists."}:{exists:!1,abcPath:"",message:`abc file not found in ${e}.`}}findFirstAbc(e){if(!le.existsSync(e))return null;let t=le.readdirSync(e,{withFileTypes:!0});for(let r of t){let o=H.join(e,r.name);if(r.isDirectory()){let i=this.findFirstAbc(o);if(i)return i}else if(r.isFile()&&r.name.endsWith(".abc"))return o}return null}resolveHqfPaths(e,t){let r=mt(this.projectRoot,e),o=H.join(this.projectRoot,r,"build",t,"outputs","default");return le.existsSync(o)||le.mkdirSync(o,{recursive:!0}),{unsignedHqfPath:H.join(o,`${e}-default-unsigned.hqf`),signedHqfPath:H.join(o,`${e}-default-signed.hqf`)}}async generateHqf(e,t,r){let o=this.resolvePackingTool();if(!o)return console.error("[HotReload] app_packing_tool.jar not found in SDK."),!1;let i=H.dirname(t),s=this.toolProvider.javaPath,a=["-jar",o,"--mode","hqf","--json-path",e,"--ets-path",i,"--out-path",r,"--force","true"];m(`[GenSignHqf] Packing: ${s} ${a.join(" ")}`);try{let c=Date.now(),l=await Yu(s,a,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] pack (JVM#1): ${Date.now()-c}ms`),l.stdout&&console.log(l.stdout),l.stderr&&console.error(l.stderr),l.exitCode!==0?(console.error(`[HotReload] app_packing_tool failed with exit code ${l.exitCode}`),!1):le.existsSync(r)?(console.log(`[HotReload] Unsigned hqf generated: ${r}`),!0):(console.error(`[HotReload] hqf not generated at ${r}`),!1)}catch(c){return console.error(`[HotReload] Packing hqf failed: ${c.message}`),!1}}async signHqfDirect(e,t){let r=this.resolveSignConfig();if(!r)return this.signFailResult(e,"Signing prerequisites not met.");let o=this.buildSignArgs(r,e,t),i=this.toolProvider.javaPath,s=o.map((a,c)=>c>0&&["-keyPwd","-keystorePwd"].includes(o[c-1])?"******":a);m(`[GenSignHqf] Signing: ${i} ${s.join(" ")}`);try{let a=Date.now(),c=await Yu(i,o,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] sign (JVM#2): ${Date.now()-a}ms`),c.stdout&&console.log(c.stdout),c.stderr&&console.error(c.stderr),c.exitCode!==0?this.signFailResult(e,`hqf signing failed with exit code ${c.exitCode}`):le.existsSync(t)?(console.log(`[HotReload] Signed hqf generated: ${t}`),{success:!0,signedHqfPaths:[t],unsignedHqfPath:e,message:"hqf generated and signed successfully."}):this.signFailResult(e,`Signed hqf not generated at ${t}`)}catch(a){return this.signFailResult(e,`hqf signing failed: ${a.message}`)}}resolveSignConfig(){let e=this.resolveSignTool();if(!e)return null;let t=this.readSigningConfig("default");if(!t?.storeFile||!t?.certpath||!t?.profile)return null;let r=this.resolveMaterialDir();if(!r)return null;try{let o=Bi.decryptPwd(r,t.storePassword,"storePassword"),i=Bi.decryptPwd(r,t.keyPassword,"keyPassword");return{signToolPath:e,storePwd:o,keyPwd:i,signingConfig:t}}catch{return null}}buildSignArgs(e,t,r){return["-jar",e.signToolPath,"sign-app","-mode","localSign","-keyAlias",e.signingConfig.keyAlias||"debugKey","-keyPwd",e.keyPwd,"-keystoreFile",e.signingConfig.storeFile,"-keystorePwd",e.storePwd,"-appCertFile",e.signingConfig.certpath,"-profileFile",e.signingConfig.profile,"-inFile",t,"-outFile",r,"-signAlg",e.signingConfig.signAlg||"SHA256withECDSA"]}resolveMaterialDir(){let e=this.readSigningConfig("default");if(!e?.storeFile)return null;let t=H.resolve(e.storeFile,".."),r=H.join(t,"material");return le.existsSync(r)?t:null}readSigningConfig(e){let t=H.join(this.projectRoot,"build-profile.json5");if(!le.existsSync(t))return null;try{let r=le.readFileSync(t,"utf-8"),o=Gv.parse(r),s=o.app?.products?.find(a=>a.name===e)?.signingConfig;return s?o.app?.signingConfigs?.find(a=>a.name===s)?.material??null:null}catch{return null}}resolveSignTool(){let e=this.toolProvider.sdkPath,t=[H.join(e,"default","openharmony","toolchains","lib","hap-sign-tool.jar"),H.join(e,"toolchains","lib","hap-sign-tool.jar")];for(let r of t)if(le.existsSync(r))return r;return null}signFailResult(e,t){return console.error(`[HotReload] ${t}`),{success:!1,signedHqfPaths:[],unsignedHqfPath:e,message:t}}resolvePackingTool(){let e=this.toolProvider.sdkPath,t=[H.join(e,"default","openharmony","toolchains","lib","app_packing_tool.jar"),H.join(e,"toolchains","lib","app_packing_tool.jar")];for(let r of t)if(le.existsSync(r))return r;return null}};async function Ku(n){let e=Date.now(),t=mt(n.projectPath,n.moduleName),r=zv(n);console.log(hc("[HotReload] Ensure the project source is trusted before proceeding."));let o=qv(n),i=ro(r,n.projectPath);console.log(`[HotReload] Parsed ${i.length} changed file(s) from ${n.applyFileName}`),Yv(n,i),Jv(n,t),await Kv(n,o);let s=Ct.join(n.projectPath,t,"patch.json"),a=await Zv(n,t,s);return await Qv(n,a),console.log(Vi("[HotReload] hot reload applied successfully (app not restarted).")),console.log(`[Timing] TOTAL executeHotReloadApply: ${Date.now()-e}ms`),{success:!0,message:"Hot reload applied successfully."}}function zv(n){if(Ct.basename(n.applyFileName)!==n.applyFileName)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${n.applyFileName}`);return Ct.join(n.projectPath,".hvigor",n.applyFileName)}function qv(n){let{projectPath:e,toolProvider:t}=n,r=new or(e,t);if(!r.findProjectDaemon())throw new Error("No running hvigor daemon found. Run `devecocli run --hotreload` first to start the daemon.");return r}function Yv(n,e){let t=nr.writeChangedFileLists(n.projectPath,n.productName,e,n.moduleName);if(t.writtenModules.length===0)throw new Error("No changed files belong to a runnable module");console.log(Vi(`[HotReload] changedFileList written for: ${t.writtenModules.join(", ")}`)),t.skippedFiles.length>0&&console.warn(hc(`[HotReload] skipped ${t.skippedFiles.length} file(s)`))}function Jv(n,e){let t=Ui.generateOrUpdate(n.projectPath,e,n.moduleName);console.log(Vi(`[HotReload] patch.json ready (patchVersionCode=${t.app.patchVersionCode})`))}async function Kv(n,e){let t=Date.now(),r=e.getWatchLogPath();try{console.log("[HotReload] Daemon hot compile (socket short connection)...");let o=await e.sendHotCompile({moduleSpecs:n.moduleSpecs,productName:n.productName});if(o!==0){let i=Xv(r);throw new Error(`Daemon hot compile exited with code ${o}`+(i?`
|
|
45
|
+
`))},onWatchResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchResult] ${a}`)},onWatchCompileResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileResult] ${a}`)},onWatchCompileData:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileData] ${a}`)}}}createOutputHandler(){return e=>{let t=typeof e.text=="string"?e.text:Buffer.from(e.text).toString(e.encoding??"utf-8");t.trim()&&(e.type==="stderr"?process.stderr.write(t):process.stdout.write(t))}}buildCompileOptions(e){let t={_:["assembleDevHqf"],daemon:!0,hotCompile:!0,mode:"module",prop:[`module=${e.moduleSpecs.join(",")}`,`product=${e.productName}`,"debuggable=true","hotReload=true","requiredDeviceType=phone"],parallel:!0,incremental:!0,analyze:"normal",env:{DEVECO_SDK_HOME:this.toolProvider.sdkPath}};return console.log("[DaemonClient] buildCompileOptions:",JSON.stringify(t,null,2)),t}async waitForDaemonReady(){let r=Date.now();for(;Date.now()-r<3e4;){let o=this.findProjectDaemon();if(o&&(o.state==="half_busy"||o.state==="idle"))return;await new Promise(i=>setTimeout(i,1e3))}throw new Error("No running hvigor daemon found. Run `devecocli run --hotreload` first.")}findProjectDaemon(){let e=this.getRegistryPath();if(!Ze.existsSync(e))return null;try{let t=Ze.readFileSync(e,"utf-8"),r=JSON.parse(t),o=Object.values(r).filter(i=>i.cwdPath===this.projectRoot&&(i.state==="idle"||i.state==="half_busy"||i.state==="busy")&&this.isProcessAlive(i.pid));return o.length>0?o[o.length-1]:null}catch{return null}}decryptSessionId(e){let t=this.getMetaDir(),r=Qe.join(t,"fd"),o=Qe.join(t,"ac"),i=Qe.join(t,"ce"),s=this.readComponents(r),a=this.xorBuffers([s[0],s[1],s[2],Buffer.from(mb)]),c=this.readSingleFile(o),l=Bp.pbkdf2Sync(Buffer.from(a).toString(),c,1e4,16,"sha256"),d=this.readSingleFile(i),g=this.aesGcmDecrypt(l,d),w=Buffer.from(e,"hex");return this.aesGcmDecrypt(g,w).toString("utf-8")}aesGcmDecrypt(e,t){let r=0,o=t.readUInt32BE(r);r+=4;let i=t.subarray(r,r+12);r+=12;let s=o-16,a=t.subarray(r,r+s);r+=s;let c=t.subarray(r,r+16),l=Bp.createDecipheriv("aes-128-gcm",e,i);return l.setAuthTag(c),Buffer.concat([l.update(a),l.final()])}readComponents(e){let t=Ze.readdirSync(e).map(r=>Qe.join(e,r)).filter(r=>Ze.statSync(r).isDirectory()).sort();if(t.length<3)throw new Error(`Expected 3 subdirectories in ${e}, found ${t.length}`);return t.slice(0,3).map(r=>{let o=Ze.readdirSync(r);if(o.length===0)throw new Error(`No file in ${r}`);return Ze.readFileSync(Qe.join(r,o[0]))})}readSingleFile(e){let t=Ze.readdirSync(e).map(r=>Qe.join(e,r)).filter(r=>Ze.statSync(r).isFile());if(t.length===0)throw new Error(`No file in ${e}`);return Ze.readFileSync(t[0])}xorBuffers(e){let t=Buffer.alloc(e[0].length);t.set(e[0]);for(let r=1;r<e.length;r++){let o=Buffer.isBuffer(e[r])?e[r]:Buffer.from(e[r]);for(let i=0;i<t.length;i++)t[i]^=o[i]}return t}getRegistryPath(){let e=process.env.HVIGOR_USER_HOME||Qe.join(Wp.homedir(),".hvigor");return Qe.join(e,"daemon","cache","daemon-sec.json")}getMetaDir(){let e=process.env.HVIGOR_USER_HOME||Qe.join(Wp.homedir(),".hvigor");return Qe.join(e,"meta")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}};import zp from"fs";import*as Ot from"path";import{green as ls,yellow as Uc}from"colorette";import Vn from"fs";import*as Gn from"path";import fb from"json5";var hb=2e6,gb=1e6,yb="hotreload",ss=class n{static generateOrUpdate(e,t,r){let o=n.readAppConfig(e),i=Gn.resolve(e,t),s=Gn.join(i,"patch.json"),a;return Vn.existsSync(s)?(h(`[PatchManager] patch.json found at ${s}, incrementing patchVersionCode`),a=n.readExistingPatch(s),a.app.patchVersionCode+=1):(h(`[PatchManager] patch.json not found, generating new one at ${s}`),a={app:{bundleName:o.bundleName,patchVersionCode:hb,versionCode:o.versionCode},module:{name:r,type:yb}}),n.writePatchJson(s,a),a}static readAppConfig(e){let t=Gn.join(e,"AppScope","app.json5");if(!Vn.existsSync(t))throw new Error(`AppScope/app.json5 not found at ${t}. Unable to read bundleName and versionCode.`);let r=Vn.readFileSync(t,"utf-8"),o=fb.parse(r),i=o?.app?.bundleName;if(!i)throw new Error("bundleName is missing in AppScope/app.json5");let s=o?.app?.versionCode??gb;return{bundleName:i,versionCode:s}}static readExistingPatch(e){let t=Vn.readFileSync(e,"utf-8"),r=JSON.parse(t);if(!r?.app?.patchVersionCode)throw new Error(`Invalid patch.json at ${e}: missing app.patchVersionCode`);return r}static writePatchJson(e,t){let r=Gn.dirname(e);Vn.existsSync(r)||Vn.mkdirSync(r,{recursive:!0});let o=JSON.stringify(t,null,2);Vn.writeFileSync(e,o,"utf-8"),h(`[PatchManager] patch.json written to ${e}`),h(`[PatchManager] Content: ${o}`)}};import he from"fs";import*as B from"path";import Vp from"crypto";import wb from"json5";import{execa as Gp}from"execa";var as=class n{static COMPONENT=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]);static DIRS=["fd","ac","ce"];static decryptPwd(e,t,r){if(t.length<32||t.length%2!==0)throw new Error(`Invalid encrypted password for ${r}`);h(`[DecipherUtil] Decrypting ${r}, encrypted length: ${t.length}`);let o=B.resolve(e,"material"),i=n.getKey(o,r),s=new Int8Array(Buffer.from(t,"hex"));return h(`[DecipherUtil] Data length: ${s.length}, key length: ${i.length}`),n.decrypt(i,s).toString("utf-8")}static getKey(e,t){let r=B.resolve(e,n.DIRS[0]),o=n.readFd(r,t),i=n.readDirBytes(B.resolve(e,n.DIRS[1]),t),s=n.getRootKey(o,i,t),a=n.readDirBytes(B.resolve(e,n.DIRS[2]),t);return new Int8Array(n.decrypt(s,a))}static getRootKey(e,t,r){if(!e.every(a=>a.length===16))throw new Error(`Signing material data error for ${r}`);let o=[...e,n.COMPONENT],i=n.xor(o[0],o[1],r);for(let a=2;a<o.length;a++)i=n.xor(i,o[a],r);let s=Vp.pbkdf2Sync(Buffer.from(i).toString(),Buffer.from(t),1e4,16,"sha256");return new Int8Array(s)}static xor(e,t,r){if(e.byteLength!==t.byteLength)throw new Error(`Signing material data error for ${r}`);let o=new Int8Array(e.byteLength);for(let i=0;i<e.byteLength;i++)o[i]=e[i]^t[i];return o}static decrypt(e,t){let r=(255&t[0])<<24|(255&t[1])<<16|(255&t[2])<<8|255&t[3],o=t.length-4-r,i=t.slice(4,4+o),s=t.slice(t.length-16),a=Vp.createDecipheriv("aes-128-gcm",Buffer.from(e),Buffer.from(i));a.setAuthTag(Buffer.from(s));let c=a.update(Buffer.from(t.subarray(4+o,t.length-16))),l=a.final();return Buffer.concat([c,l])}static readFd(e,t){let r=he.readdirSync(e).filter(i=>i!==".DS_Store");if(r.length!==3)throw new Error(`fd directory must have 3 entries for ${t}`);let o=[];for(let i of r){let s=B.join(e,i);o.push(n.readDirBytes(s,t))}return o}static readDirBytes(e,t){if(he.statSync(e).isDirectory()){let o=he.readdirSync(e).filter(i=>i!==".DS_Store");if(o.length!==1)throw new Error(`Expected exactly 1 file in ${e} for ${t}`);return new Int8Array(he.readFileSync(B.join(e,o[0])))}return new Int8Array(he.readFileSync(e))}},cs=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let o=`${B.dirname(e.javaPath)}${B.delimiter}${process.env.PATH||""}`;this.env={...process.env,PATH:o,DEVECO_SDK_HOME:e.sdkPath}}async generateAndSign(e,t,r,o,i=!1){let s=this.checkAbcExists(t);if(!s.exists)return{signedHqfPaths:[],message:s.message};let a=this.resolveHqfPaths(e,o);return await this.generateHqf(r,s.abcPath,a.unsignedHqfPath)?i?{success:!0,signedHqfPaths:[a.unsignedHqfPath],unsignedHqfPath:a.unsignedHqfPath,message:"Unsigned hqf generated (signing skipped for emulator)."}:this.signHqfDirect(a.unsignedHqfPath,a.signedHqfPath):{signedHqfPaths:[],unsignedHqfPath:a.unsignedHqfPath,message:"Failed to generate unsigned hqf."}}checkAbcExists(e){let t=B.join(e,"ets","modules.abc");if(he.existsSync(t))return{exists:!0,abcPath:t,message:"abc file exists."};let r=this.findFirstAbc(e);return r?{exists:!0,abcPath:r,message:"abc file exists."}:{exists:!1,abcPath:"",message:`abc file not found in ${e}.`}}findFirstAbc(e){if(!he.existsSync(e))return null;let t=he.readdirSync(e,{withFileTypes:!0});for(let r of t){let o=B.join(e,r.name);if(r.isDirectory()){let i=this.findFirstAbc(o);if(i)return i}else if(r.isFile()&&r.name.endsWith(".abc"))return o}return null}resolveHqfPaths(e,t){let r=It(this.projectRoot,e),o=B.join(this.projectRoot,r,"build",t,"outputs","default");return he.existsSync(o)||he.mkdirSync(o,{recursive:!0}),{unsignedHqfPath:B.join(o,`${e}-default-unsigned.hqf`),signedHqfPath:B.join(o,`${e}-default-signed.hqf`)}}async generateHqf(e,t,r){let o=this.resolvePackingTool();if(!o)return console.error("[HotReload] app_packing_tool.jar not found in SDK."),!1;let i=B.dirname(t),s=this.toolProvider.javaPath,a=["-jar",o,"--mode","hqf","--json-path",e,"--ets-path",i,"--out-path",r,"--force","true"];h(`[GenSignHqf] Packing: ${s} ${a.join(" ")}`);try{let c=Date.now(),l=await Gp(s,a,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] pack (JVM#1): ${Date.now()-c}ms`),l.stdout&&console.log(l.stdout),l.stderr&&console.error(l.stderr),l.exitCode!==0?(console.error(`[HotReload] app_packing_tool failed with exit code ${l.exitCode}`),!1):he.existsSync(r)?(console.log(`[HotReload] Unsigned hqf generated: ${r}`),!0):(console.error(`[HotReload] hqf not generated at ${r}`),!1)}catch(c){return console.error(`[HotReload] Packing hqf failed: ${c.message}`),!1}}async signHqfDirect(e,t){let r=this.resolveSignConfig();if(!r)return this.signFailResult(e,"Signing prerequisites not met.");let o=this.buildSignArgs(r,e,t),i=this.toolProvider.javaPath,s=o.map((a,c)=>c>0&&["-keyPwd","-keystorePwd"].includes(o[c-1])?"******":a);h(`[GenSignHqf] Signing: ${i} ${s.join(" ")}`);try{let a=Date.now(),c=await Gp(i,o,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] sign (JVM#2): ${Date.now()-a}ms`),c.stdout&&console.log(c.stdout),c.stderr&&console.error(c.stderr),c.exitCode!==0?this.signFailResult(e,`hqf signing failed with exit code ${c.exitCode}`):he.existsSync(t)?(console.log(`[HotReload] Signed hqf generated: ${t}`),{success:!0,signedHqfPaths:[t],unsignedHqfPath:e,message:"hqf generated and signed successfully."}):this.signFailResult(e,`Signed hqf not generated at ${t}`)}catch(a){return this.signFailResult(e,`hqf signing failed: ${a.message}`)}}resolveSignConfig(){let e=this.resolveSignTool();if(!e)return null;let t=this.readSigningConfig("default");if(!t?.storeFile||!t?.certpath||!t?.profile)return null;let r=this.resolveMaterialDir();if(!r)return null;try{let o=as.decryptPwd(r,t.storePassword,"storePassword"),i=as.decryptPwd(r,t.keyPassword,"keyPassword");return{signToolPath:e,storePwd:o,keyPwd:i,signingConfig:t}}catch{return null}}buildSignArgs(e,t,r){return["-jar",e.signToolPath,"sign-app","-mode","localSign","-keyAlias",e.signingConfig.keyAlias||"debugKey","-keyPwd",e.keyPwd,"-keystoreFile",e.signingConfig.storeFile,"-keystorePwd",e.storePwd,"-appCertFile",e.signingConfig.certpath,"-profileFile",e.signingConfig.profile,"-inFile",t,"-outFile",r,"-signAlg",e.signingConfig.signAlg||"SHA256withECDSA"]}resolveMaterialDir(){let e=this.readSigningConfig("default");if(!e?.storeFile)return null;let t=B.resolve(e.storeFile,".."),r=B.join(t,"material");return he.existsSync(r)?t:null}readSigningConfig(e){let t=B.join(this.projectRoot,"build-profile.json5");if(!he.existsSync(t))return null;try{let r=he.readFileSync(t,"utf-8"),o=wb.parse(r),s=o.app?.products?.find(a=>a.name===e)?.signingConfig;return s?o.app?.signingConfigs?.find(a=>a.name===s)?.material??null:null}catch{return null}}resolveSignTool(){let e=this.toolProvider.sdkPath,t=[B.join(e,"default","openharmony","toolchains","lib","hap-sign-tool.jar"),B.join(e,"toolchains","lib","hap-sign-tool.jar")];for(let r of t)if(he.existsSync(r))return r;return null}signFailResult(e,t){return console.error(`[HotReload] ${t}`),{success:!1,signedHqfPaths:[],unsignedHqfPath:e,message:t}}resolvePackingTool(){let e=this.toolProvider.sdkPath,t=[B.join(e,"default","openharmony","toolchains","lib","app_packing_tool.jar"),B.join(e,"toolchains","lib","app_packing_tool.jar")];for(let r of t)if(he.existsSync(r))return r;return null}};async function qp(n){let e=Date.now(),t=It(n.projectPath,n.moduleName),r=vb(n);console.log(Uc("[HotReload] Ensure the project source is trusted before proceeding."));let o=Sb(n),i=Co(r,n.projectPath);console.log(`[HotReload] Parsed ${i.length} changed file(s) from ${n.applyFileName}`),bb(n,i),Eb(n,t),await Pb(n,o);let s=Ot.join(n.projectPath,t,"patch.json"),a=await Ib(n,t,s);return await Ab(n,a),console.log(ls("[HotReload] hot reload applied successfully (app not restarted).")),console.log(`[Timing] TOTAL executeHotReloadApply: ${Date.now()-e}ms`),{success:!0,message:"Hot reload applied successfully."}}function vb(n){if(Ot.basename(n.applyFileName)!==n.applyFileName)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${n.applyFileName}`);return Ot.join(n.projectPath,".hvigor",n.applyFileName)}function Sb(n){let{projectPath:e,toolProvider:t}=n,r=new Sr(e,t);if(!r.findProjectDaemon())throw new Error("No running hvigor daemon found. Run `devecocli run --hotreload` first to start the daemon.");return r}function bb(n,e){let t=wr.writeChangedFileLists(n.projectPath,n.productName,e,n.moduleName);if(t.writtenModules.length===0)throw new Error("No changed files belong to a runnable module");console.log(ls(`[HotReload] changedFileList written for: ${t.writtenModules.join(", ")}`)),t.skippedFiles.length>0&&console.warn(Uc(`[HotReload] skipped ${t.skippedFiles.length} file(s)`))}function Eb(n,e){let t=ss.generateOrUpdate(n.projectPath,e,n.moduleName);console.log(ls(`[HotReload] patch.json ready (patchVersionCode=${t.app.patchVersionCode})`))}async function Pb(n,e){let t=Date.now(),r=e.getWatchLogPath();try{console.log("[HotReload] Daemon hot compile (socket short connection)...");let o=await e.sendHotCompile({moduleSpecs:n.moduleSpecs,productName:n.productName});if(o!==0){let i=Cb(r);throw new Error(`Daemon hot compile exited with code ${o}`+(i?`
|
|
38
46
|
--- compile output (from watch session) ---
|
|
39
|
-
${i}`:""))}}finally{e.disconnect()}console.log(`[Timing] daemon hot compile: ${Date.now()-t}ms`)}function
|
|
40
|
-
`):""}catch{return""}}async function
|
|
41
|
-
`))}let r=await n.getDeviceInfo(t,e);if(!r)throw new Error("No active devices found.");if(!e){let o=await n.getDeviceName(r.serial);console.log(`Auto-selected device: ${o} (${r.serial})`)}return r.serial}function
|
|
47
|
+
${i}`:""))}}finally{e.disconnect()}console.log(`[Timing] daemon hot compile: ${Date.now()-t}ms`)}function Cb(n){try{return zp.existsSync(n)?zp.readFileSync(n,"utf8").split(/\r?\n/).filter(t=>t.trim()).slice(-40).join(`
|
|
48
|
+
`):""}catch{return""}}async function Ib(n,e,t){let r=Ot.join(n.projectPath,e,"build",n.productName,"intermediates"),o=[Ot.join(r,"hotReload","patchAbcPath"),Ot.join(r,"patch","default")],i=Date.now(),s=new cs(n.toolProvider,n.projectPath),a=n.targetDeviceId.includes("127.0.0.1")||n.targetDeviceId.includes("localhost"),c=null;for(let l of o){let d=await s.generateAndSign(n.moduleName,l,t,n.productName,a);if(d.success&&d.signedHqfPaths.length>0){c=d;break}c=d}if(console.log(`[Timing] gen+sign hqf: ${Date.now()-i}ms`),!c?.success||c.signedHqfPaths.length===0)throw new Error(`hqf generation/signing failed (no abc found in any candidate). Last: ${c?.message??"unknown"}`);return c.signedHqfPaths}async function Ab(n,e){let t=Date.now(),o=await new vr(n.toolProvider).install(n.targetDeviceId,e,n.bundleName);if(console.log(`[Timing] quickfix install: ${Date.now()-t}ms`),!o.success)throw new Error(`hqf install failed: ${o.message}`)}function Bc(n,e){if(!n||n.length===0)throw new Error(`Hot reload requires --module <name> (a single target module; har deps are fine). Got: '${e??""}' (no --module passed).`)}function Jp(n,e,t){let r=Ot.join(n.rootDir,".hvigor",t),o;try{o=Co(r,n.rootDir)}catch{return}let i=new Set;for(let s of o){let a=n.findOwningModule(s);if(!a||a===e)continue;let c=n.getModuleType(a);(c==="feature"||c==="shared")&&i.add(`${a} (${c})`)}i.size>0&&console.warn(Uc(`[HotReload] Changed files belong to feature/hsp dependency module(s): ${[...i].join(", ")}. These are NOT hot-reloadable \u2014 run \`devecocli run\` (full redeploy) for them. Only the target module (+ har deps) will be hot-reloaded this time.`))}function Yp(n,e,t,r,o){let i=new Set,s=n.collectNonHarDependentModuleList(e);for(let a of s)i.add(n.findArtifactPath(a,t,r,o));return i.add(n.findArtifactPath(e,t,r,o)),[...i]}async function Kp(n,e){await new Ve(n,e.rootDir).stopDaemon(),console.log(ls("Hvigor daemon stopped."))}function Wc(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 us(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 o=await n.listDevicesWithName();throw new v("Multiple devices found. Specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+o.map(i=>` - ${i.name} (${i.serial})`).join(`
|
|
49
|
+
`),"Multiple devices found.")}let r=await n.getDeviceInfo(t,e);if(!r)throw new Error("No active devices found.");if(!e){let o=await n.getDeviceName(r.serial);console.log(`Auto-selected device: ${o} (${r.serial})`)}return r.serial}function Vc(n,e){if(e&&e.length>0)return e;let t=n.profile.modules.filter(r=>{let o=n.getModuleType(r.name);return o==="entry"||o==="feature"||o==="shared"});if(t.length===1){let r=t[0].name;return console.log(`Auto-selected module: ${r}`),[r]}throw new v(`Specify module(s) using --module <name> [<name>...].
|
|
42
50
|
Available runnable modules:
|
|
43
51
|
`+t.map(r=>` - ${r.name}`).join(`
|
|
44
|
-
`))}function
|
|
45
|
-
Installing artifacts to device ${e}...`),await n.installApp(e,r),o){console.log(`Launching ${t}/${o}...`);let s=await n.launchApp(e,t,o);console.log(
|
|
52
|
+
`),"Specify module error.")}function Xp(n,e,t){if(t)return t;let r=e.find(({moduleName:i})=>n.getModuleType(i)==="entry");if(r)return n.getMainAbility(r.moduleName);let o=e.find(({moduleName:i})=>n.getModuleType(i)==="feature");if(o)return n.getMainAbility(o.moduleName)}async function Zp(n,e,t,r,o,i){if(i&&(console.log(`Uninstalling ${t}...`),await n.uninstallApp(e,t)||console.log(`App ${t} not installed; skipping uninstallation.`)),console.log(`
|
|
53
|
+
Installing artifacts to device ${e}...`),await n.installApp(e,r),o){console.log(`Launching ${t}/${o}...`);let s=await n.launchApp(e,t,o);console.log(Ao(`
|
|
46
54
|
Application '${t}': ${s}`))}else console.log(`
|
|
47
|
-
Application '${t}' installed successfully (no ability to launch).`)}var
|
|
48
|
-
`+
|
|
49
|
-
${
|
|
50
|
-
New version found: ${
|
|
51
|
-
`+
|
|
52
|
-
Last error: ${s.lastError.message||"unknown"}
|
|
53
|
-
`)
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
`)
|
|
57
|
-
|
|
58
|
-
|
|
55
|
+
Application '${t}' installed successfully (no ability to launch).`)}function Tb(n){let e={event:E.CommandExecuted,args:["run",...n.module?["--module"]:[],...n.device?["--device"]:[],...n.product?["--product"]:[],...n.buildMode?["--build-mode"]:[],...n.ability?["--ability"]:[],...n.uninstall?["--uninstall"]:[],...n.skipBuild?["--skip-build"]:[],...n.apply?["--apply"]:[]]};return n.buildMode&&(e.build_mode=n.buildMode),n.module&&(e.module_count=n.module.length),e}var Rb=new Db("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/").option("--hotreload [action]",'Start hot-reload mode (build+deploy with daemon, then exit). Use "stop" to shut down the hvigor daemon.').option("--hotreload-apply <fileName>","Hot-reload changed files (.hvigor/<fileName> list) via daemon hot compile + signed hqf + quickfix, without restarting the app.").action(async n=>{let e=Tb(n),t=Date.now(),r=!0,o=null;try{let i=await Nb(n,e);i&&(i.ohpmMemoryMb&&(e.ohpm_install_memory=i.ohpmMemoryMb),i.syncMemoryMb&&(e.hvigor_sync_memory=i.syncMemoryMb),i.buildMemoryMb&&(e.hvigor_build_memory=i.buildMemoryMb))}catch(i){r=!1,o=ce(i),console.error(kb(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await k.track(e,i)}});async function xb(n,e,t,r,o){let i=new mr(e,n.rootDir),s=new Ve(e,n.rootDir),a=new Set,c=new Set;for(let{moduleName:b,targetName:$}of t)for(let ne of n.collectNonHarDependentModuleList(b))a.add(`${ne}@${$}`),c.add(ne);let l=[...a],d=Lc(n,l),g={type:"modules",modulesToBuild:l,moduleTasks:d};for(let b of c)os.generate(n.rootDir,b,r,e);let w=await Hn(n.rootDir,()=>Oc(i,s,r,o,g,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion..."));return console.log(`
|
|
56
|
+
`+Ao("Build completed successfully.")),w}async function Nb(n,e){let t=J.discover(process.cwd());console.warn(ds("Ensure the project source is trusted before proceeding."));let r=await I.new();if(n.skipBuild||r.assertJava(),e.bundle_name=t.getBundleName(),n.hotreloadApply){await Mb(n,t,r);return}if(n.hotreload){await Ob(n,t,r);return}if(n.apply){await Fb(n,t,r);return}return Qp(n,t,r)}async function Lb(n,e,t){n.onSocketDisconnect(()=>{console.log("Daemon disconnected (likely via --hotreload stop). Exiting watch session."),process.exit(0)});let r=new Ve(e,t.rootDir),o=setInterval(async()=>{await r.isDaemonAlive()||(clearInterval(o),console.log("Daemon stopped (via --hotreload stop). Exiting watch session."),process.exit(0))},3e3);await new Promise(()=>{})}async function Ob(n,e,t){if(n.hotreload==="stop"){await Kp(t,e);return}let o=Vc(e,n.module).map(Wc),{moduleName:i,targetName:s}=o[0];Bc(n.module,i);let a=new tn(t),c=ie.from(t),l=await us(c,n.device),d=l.includes("127.0.0.1")||l.includes("localhost"),g=n.product||"default";e.validateProduct(g);let w=e.getBundleName(),b=Xp(e,o,n.ability);is.generate(e.rootDir,i,g,t);let $=new Ve(t,e.rootDir);console.log(Ao("Ensuring hvigor daemon is running (via --sync --daemon, no hap build)...")),await $.ensureDaemonRunning();let ne=[`${i}@${g}`];for(let Jt of e.collectNonHarDependentModuleList(i))ne.includes(`${Jt}@${g}`)||ne.push(`${Jt}@${g}`);console.log(Ao("Building hap + starting watch session (socket -> CommonBuild assembleHap --hot-reload-build --watch, kept open)..."));let we=new Sr(e.rootDir,t);await we.startWatchSession({moduleSpecs:ne,productName:g});let wt=Yp(e,i,s,d,g);await Zp(a,l,w,wt,b,!!n.uninstall),console.log(Ao("Hot-reload watch session active (socket persistent). Edit code, write .hvigor/<file>, then `devecocli run --hotreload-apply <file>` in another terminal. Ctrl+C here to stop.")),await Lb(we,t,e)}async function Mb(n,e,t){let r=n.hotreloadApply;if(!r)throw new Error("hotreload-apply requires --hotreload-apply <fileName> (under .hvigor/)");if(Do.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let o=Vc(e,n.module),{moduleName:i}=Wc(o[0]);Bc(n.module,i);let s=ie.from(t),a=await us(s,n.device),c=n.product||"default";e.validateProduct(c);let l=e.getBundleName();Jp(e,i,r);let d=[`${i}@${c}`],g=await qp({applyFileName:r,projectPath:e.rootDir,moduleName:i,productName:c,bundleName:l,toolProvider:t,targetDeviceId:a,moduleSpecs:d});if(!g.success)throw new Error(g.message)}function _b(n,e,t,r){let o=new Set;for(let{moduleName:i,targetName:s}of e)for(let a of n.collectNonHarDependentModuleList(i)){o.add(n.findArtifactPath(a,s,t,r));for(let c of n.findRemoteHspPaths(a,s,r))o.add(c)}return[...o]}async function Qp(n,e,t){let o=Vc(e,n.module).map(Wc);for(let{moduleName:ne}of o){let we=e.getModuleType(ne);if(we!=="entry"&&we!=="feature"&&we!=="shared")throw new v(`Module '${ne}' '${we}' is not runnable. Specify an entry or feature module.`,"Module is not runnable.")}let i=new tn(t),s=ie.from(t),a=await us(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",g;n.skipBuild||(g=await xb(e,t,o,l,d));let w=_b(e,o,c,l),b=e.getBundleName(),$=Xp(e,o,n.ability);return await Zp(i,a,b,w,$,!!n.uninstall),g}async function Fb(n,e,t){let r=n.apply;if(!r)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(Do.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let o=Do.join(e.rootDir,".hvigor",r),i=ie.from(t),s=await us(i,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",g=new rs(t,e.rootDir);try{await g.execute({applyFile:o,productName:a,targetDeviceId:s,bundleName:c,abilityName:d}),console.log(ds("[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(ds(`[Apply] \u5931\u8D25\uFF1A${w.message}`)),console.warn(ds("[Apply] \u81EA\u52A8\u56DE\u9000\u5230\u5168\u91CF devecocli run..."))}await Qp(n,e,t)}var em=Rb;import{Command as Gb}from"commander";import*as am from"path";import{green as im,red as sm,cyan as qc}from"colorette";import{execa as Yc}from"execa";import{spawn as Ub}from"child_process";import*as om from"fs";import*as ms from"path";import{yellow as Bb}from"colorette";import Wb from"proper-lockfile";import*as nn from"fs";import*as tm from"path";import{homedir as jb}from"os";var $b="deveco-cli",Gc,zn=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function nm(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":bc(n))||tm.join(jb(),".local","share",$b);try{return Wi(t)}catch(r){throw new zn(r instanceof Error?r.message:String(r))}}async function rm(){let n=nm();await nn.promises.mkdir(n,{recursive:!0});let e;try{e=await nn.promises.realpath(n)}catch(r){throw new zn(`DEVECO_CLI_DATA_DIR is not usable: ${r instanceof Error?r.message:String(r)}`)}if(!(await nn.promises.stat(e)).isDirectory())throw new zn("DEVECO_CLI_DATA_DIR must be a writable directory.");return Gc=e,e}function et(){if(Gc!==void 0)return Gc;let n=nm();try{if(nn.existsSync(n))return nn.realpathSync(n)}catch{}return n}function ps(){return"@deveco-test/deveco-cli"}function rn(){return"1.3.0-Test.16"}function br(){return"daily"}function Er(){let n=process.env.DEVECO_CLI_DISABLE_UPDATE;return n==="check"||n==="all"?n:"off"}import*as ko from"fs";import*as To from"path";var Hb={lastCheckedTimestamp:null,latestVersion:null,blockedVersions:[],checkError:null},zc=new Map,on=class n{static CHECK_WINDOW_HOUR=21;static ONE_DAY_MS=1440*60*1e3;cacheFilePath;lockFilePath;constructor(e){this.cacheFilePath=To.join(e,"cache.json"),this.lockFilePath=To.join(e,"check.lock")}async writeSuccess(e,t=[],r,o){await this.write({lastCheckedTimestamp:Date.now(),latestVersion:e,blockedVersions:t,checkError:null,checkedAgainstVersion:r,checkedAgainstTag:o})}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=zc.get(this.cacheFilePath);if(e)return e;try{let t=ko.readFileSync(this.cacheFilePath,"utf-8"),r=JSON.parse(t);return zc.set(this.cacheFilePath,r),r}catch{return{...Hb}}}async write(e){h(()=>`Writing update cache: lastChecked=${e.lastCheckedTimestamp}, latest=${e.latestVersion}, blocked=[${e.blockedVersions.join(",")}], error=${e.checkError}`),await ko.promises.mkdir(To.dirname(this.cacheFilePath),{recursive:!0}),await ko.promises.writeFile(this.cacheFilePath,JSON.stringify(e,null,2),"utf-8"),zc.set(this.cacheFilePath,e)}};var Ro=class{constructor(e){this.actionCommand=e}actionCommand;cache=new on(ms.join(et(),"update"));async checkAndNotify(){if(!this.shouldSkip())try{let e=rn(),t=br(),r=this.cache.getCheckedAgainstVersion(),o=this.cache.getCheckedAgainstTag(),i=o!=null&&o!==t,s=r!=null&&r!==e,a=i?null:this.cache.getLatestVersion();a&&Ku(a,e)>0&&(console.log(),console.log(Bb(`New version ${a} available, run \`devecocli update\` to upgrade`))),(i||s||this.cache.isCheckNeeded())&&await this.spawnBackgroundCheck()}catch(e){h(`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 Vb(this.cache.getLockPath(),()=>{let e=[process.argv[1],"update","_check"];h(`Executing: ${process.execPath} ${e.join(" ")}`),Ub(process.execPath,e,{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1"}}).unref()})}catch{h("Update check lock held by another process, skipping")}}};async function Vb(n,e){await om.promises.mkdir(ms.dirname(n),{recursive:!0});let t=await Wb.lock(n,{stale:6e4,retries:0,realpath:!1});try{await e()}finally{await t()}}var Kc=new Gb("update").description("Update deveco-cli to latest");Kc.command("_check",{hidden:!0}).action(async()=>{let n=new on(am.join(et(),"update"));try{let e=br(),t=ps();h(`Executing: npm view ${t}@${e} --json`);let{stdout:r}=await Yc("npm",["view",`${t}@${e}`,"--json"]),o=JSON.parse(r),i=typeof o.version=="string"?o.version.trim():null,s=Array.isArray(o.blockedVersions)?o.blockedVersions:[];await n.writeSuccess(i,s,rn(),e)}catch(e){await n.writeError(e instanceof Error?e.message:String(e))}});var zb={event:E.CommandExecuted,args:["update"]};async function Jc(n,e,t){let r={duration_ms:Date.now()-n,success:e,error_code:t};await k.track(zb,r).catch(()=>{})}Kc.action(async()=>{if(Er()==="all")throw new Error("devecocli update is disabled (DEVECO_CLI_DISABLE_UPDATE=all).");let n=Date.now(),e=rn(),t=br();console.log(qc("Checking for updates..."));let r=ps();try{let{stdout:o}=await Yc("npm",["view",r,`dist-tags.${t}`]),i=o.trim();if(!i||i===e){console.log(im(`
|
|
57
|
+
${r} is already up to date (v${e}, tag: ${t})`)),await Jc(n,!0,null);return}console.log(qc(`
|
|
58
|
+
New version found: ${i} (current: ${e})`)),console.log(qc(`Updating ${r}...`)),await Yc("npm",["install","-g",`${r}@${t}`],{stdio:"inherit"}),console.log(`
|
|
59
|
+
`+im(`${r} updated successfully to version ${i}.`)),await Jc(n,!0,null)}catch(o){let i=o,s=i.code??i.name??"UnknownError";console.error(sm(`Failed to update ${r}`)),i.message&&console.error(sm(i.message)),await Jc(n,!1,s),process.exit(1)}});var cm=Kc;import{Command as bE,Option as Em}from"commander";import{execa as hs}from"execa";function be(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as qb}from"child_process";var Jb=2500;function Yb(n,e,t,r,o,i){n.once("exit",s=>{if(i())return;clearTimeout(e);let a=t();s===0||s===null?r():o(a||`Emulator process exited with code ${s}`)})}function Kb(n,e,t,r){let o=!1,i=()=>o,s=()=>Buffer.concat(e).toString("utf8").trim(),a=()=>{o||(o=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners(),n.stderr?.destroy(),n.unref(),t())},c=d=>{if(!o){o=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners();try{n.kill()}catch{}r(new Error(d))}},l=setTimeout(a,Jb);n.once("error",d=>c(d.message)),Yb(n,l,s,a,c,i)}function lm(n,e,t){return h(`Spawning emulator: ${n} ${t.join(" ")}`),new Promise((r,o)=>{let i=[],s=qb(n,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});s.stderr?.on("data",a=>i.push(a)),Kb(s,i,r,o)})}import*as Pr from"path";function Xb(n){let e=new Set,t=[];for(let r of n){let o=JSON.stringify(r);e.has(o)||(e.add(o),t.push(r))}return t}function Zb(n){let e=n.instancePath?.trim();if(e)return Pr.dirname(Pr.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?Pr.dirname(Pr.normalize(t)).replace(/\\/g,"/"):""}function Qb(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function dm(n,e){return e?[...n,"-bootmode",e]:n}function eE(n,e,t){let r=[dm(["-start",n],t)],o=Zb(e);if(o)for(let i of Qb(e.imageRoot))r.push(dm(["-hvd",n,"-path",o,...i],t));return Xb(r)}async function um(n,e,t,r){let o=new Error("No start strategy ran"),i=eE(n,e,r);for(let s of i)try{return await t(s),{ok:!0}}catch(a){o=a}return{ok:!1,lastError:o}}function tE(n){let e=n.normalize("NFKC").match(/^\s*chargingStatus\s*:\s*(\d+)\s*$/im);if(!e)return;let t=Number(e[1]);if(t===1||t===3)return!0;if(t===0||t===2)return!1}async function Xc(n){return(await ie.withHdcPath(n).listDevices()).map(t=>t.serial).filter(Ct)}async function Zc(n){let e=await Xc(n);return e.length===0?[]:(await Promise.all(e.map(r=>ns(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function pm(n,e){return(await Zc(n)).includes(e)}async function mm(n,e){let t=await ie.withHdcPath(n).listDevicesWithName(),r=e.normalize("NFKC").replace(/\s+/g," ").trim(),o=t.find(a=>a.name.normalize("NFKC").replace(/\s+/g," ").trim()===r);if(!o||!Ct(o.serial))throw new Error(`Cannot resolve the running emulator serial for "${e}".`);let i=["-t",o.serial,"shell","hidumper","-s","3302","-a","-i"];h(`Executing: ${n} ${i.join(" ")}`);let s=await oe(n,i);if(s.exitCode===0){let a=tE(s.stdout);if(a!==void 0)return a}throw new Error(`Cannot determine the battery charging state for emulator "${e}".`)}import*as Ir from"path";import{existsSync as nE,statSync as rE}from"fs";function Cr(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function oE(n){let e=Cr(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 o=t.toLowerCase();if(o.includes("instance")&&(o.includes("path")||o.includes("dir"))||o==="deployedpath")return r.trim()}return""}function iE(n){return Cr(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function sE(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=Ir.dirname(Ir.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let o=C.ensurePathWithinRoot(t,Ir.join(t,r.name));nE(o)&&rE(o).isDirectory()&&(r.instancePath=o.replace(/\\/g,"/"))}}function aE(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=iE(t),o=Cr(t,["deviceType","DeviceType","devicetype"]),i=Cr(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:oE(t),path:Cr(t,["path","Path","hvdPath","hvd_path"]),imageRoot:Cr(t,["imageRoot","image_root","ImageRoot"]),uuid:r||void 0,deviceType:o||void 0,osVersion:i||void 0}}).filter(t=>t.name):null}catch{return null}}function cE(n){let e=[],t=/^(name|isrunning|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,r=null,o;for(;(o=t.exec(n))!==null;){let[,i,s]=o;if(i.toLowerCase()==="name")r&&e.push(r),r={name:s.trim()};else if(r){let a=i.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 fm(n){let t=aE(n)??cE(n);return sE(t),t}function Qc(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function lE(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function dE(n){let e=Qc(n,["osVersion","OsVersion","OSVersion"]),t=Qc(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=Qc(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function hm(n,e=()=>!0){let t=n.trim();if(!t)return[];try{let r=JSON.parse(t);if(!Array.isArray(r))return[];let o=[];for(let i of r){if(!i||typeof i!="object")continue;let s=i;if(!e(s))continue;let a=dE(s);a&&o.push(a)}return o}catch{return[]}}function gm(n){return hm(n)}function fs(n){return hm(n,lE)}function ym(n){let t=fs(n).map(r=>r.osVersion).filter(Boolean);return[...new Set(t)]}var wm=/no images are available/i,uE=/Scenario simulation failed\s*[::]/i,pE="7.0.0";function Le(n){return n.normalize("NFKC").trim().toLowerCase()}function mE(n){let e=n.message||"";return wm.test(e)}function fE(n){return n.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function xo(n,e){return`${n} ${e.join(" ")}`.trim()}function hE(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 Ar=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 h(`Executing: ${xo(this.emulatorPath,e)}`),hs(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return lm(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return fm(e)}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let r of t)r.name&&r.deviceType&&e.set(be(r.name),r.deviceType)}catch{}return e}async startEmulator(e){let t=await this.listEmulators(),r=be(e),o=t.find(a=>be(a.name)===r);if(!o)throw new v(`Emulator "${e}" not found.`,"Emulator not found.");let i=o.name;if(await this.isAlreadyRunning(i,o))return"already-running";await this.assertSystemImageAvailable(o);let s=await um(i,o,a=>this.executeEmulatorDetached(a),"snapshot");if(s.ok)return"started";if(await this.isAlreadyRunning(i))return"already-running";throw new v(`Unable to start emulator "${e}". All methods failed.
|
|
60
|
+
Last error: ${s.lastError.message||"unknown"}`,`Unable to start emulator. All methods failed.
|
|
61
|
+
Last error: ${s.lastError.message||"unknown"}`)}async isAlreadyRunning(e,t){return t?.isRunning===!0||t===void 0&&(await this.listEmulators()).find(o=>o.name===e)?.isRunning===!0?!0:pm(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),r=be(e),o=t.find(a=>be(a.name)===r);if(!o)throw new v(`Emulator "${e}" not found.`,"Emulator not found.");let i=o.name;return await this.isAlreadyRunning(i,o)?(await this.executeEmulator(["-stop",i]),"stopped"):"already-stopped"}async controlEmulator(e,t){await this.assertControlCommandSupported();let o=(await this.listEmulators()).find(s=>s.name===e);if(!o)throw new v(`Emulator "${e}" not found.`,"Emulator instance not found.");if(!await this.isAlreadyRunning(o.name,o))throw new v(`Emulator "${e}" is not running.`,"Emulator instance is not running.");if(t.type==="battery"&&!await mm(this.hdcPath,o.name)&&t.level===0)throw new Error("Battery level must be an integer in [1, 100] while the emulator is not charging.");let i=this.buildControlArgs(o.name,t);h(`[EmulatorManager] control ${hE(t)} -> ${xo(this.emulatorPath,i)}`),await this.runEmulatorChecked(i,{extraReject:t.type==="folded-state"?[uE]:void 0,printOutputOnSuccess:!1})}async assertControlCommandSupported(){let e=this.emulatorPath;if(n.supportedControlPaths.has(e))return;let t=["-version"];h(`Executing: ${xo(this.emulatorPath,t)}`);let{stdout:r,stderr:o,exitCode:i}=await hs(this.emulatorPath,t,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:1024*1024}),s=[r,o].filter(Boolean).join(`
|
|
62
|
+
`).trim(),a=fE(s);if(i!==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,pE)<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){h(`Executing: ${xo(this.emulatorPath,e)}`);let{exitCode:t}=await hs(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 hasAvailableEmulatorImage(e){let t=await this.listEmulatorImages({deviceType:e.deviceType}),r=Le(e.deviceType),o=Le(e.osVersion);return gm(t).some(i=>Le(i.deviceType)===r&&Le(i.osVersion)===o)}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(i){if(!mE(i))throw i;r=i}(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 ym(e)}async hasMatchingDownloadedImage(e){return(await this.findMatchingDownloadedImages(e)).length>0}async runSoftwareVersionFallback(e,t,r){try{for(let o of t)await this.runUninstallImageChecked(e.deviceType,o)}catch(o){let i=r!==void 0?`Primary uninstall failed: ${r.message}
|
|
63
|
+
`:"";throw new Error(`${i}Fallback uninstall failed: ${o.message}`,{cause:o})}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=fs(t),o=Le(e.deviceType),i=Le(e.osVersion);return r.filter(s=>Le(s.deviceType)===o&&(Le(s.osVersion)===i||Le(s.softwareVersion)===i))}async hasDownloadedSystemImage(e,t){let r=await this.listEmulatorImages({downloaded:!0}),o=fs(r),i=Le(t),s=e?.trim()?Le(e):void 0;return o.some(a=>Le(a.osVersion)===i||Le(a.softwareVersion)===i?s===void 0?!0:Le(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:[wm]})}async runEmulatorChecked(e,t){h(`Executing: ${xo(this.emulatorPath,e)}`);let{stdout:r,stderr:o,exitCode:i}=await hs(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:20*1024*1024}),s=[r,o].filter(Boolean).join(`
|
|
64
|
+
`).trim(),a=/Invalid command|无效命令|鏃犳晥鍛戒护/i.test(s)||/please attach the correct parameter/i.test(s),c=(t?.extraReject??[]).some(d=>d.test(s));if(i!==0||a||c)throw new Error(s||`emulator exited with code ${i===null?"null":i}`);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(),o=be(e),i=r.find(s=>be(s.name)===o);if(i)if(t)await this.deleteVirtualDevice(i.name);else throw new v(`Emulator "${e}" already exists. Use \`--force\` to overwrite.`,"Emulator already exists.");return o}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:i=>i.split(/\r?\n/).map(s=>s.trim().startsWith("Device create success.")?"Device create success.":s).join(`
|
|
65
|
+
`)}),!await this.waitForEmulatorPresenceByList(t))throw new v(`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.`,"Emulator was reported as created, but it did not appear in the emulator list within the waiting period.")}async waitForEmulatorPresenceByList(e,t=1e4,r=500){let o=Date.now()+t;for(;Date.now()<o;){if((await this.listEmulators()).some(a=>be(a.name)===e))return!0;await new Promise(a=>setTimeout(a,r))}return!1}async deleteVirtualDevice(e){let t=await this.listEmulators(),r=be(e),o=t.find(s=>be(s.name)===r);if(!o)throw new v(`Emulator "${e}" not found.`,"Emulator not found.");let i=o.name;if(o.isRunning===!0||await this.isAlreadyRunning(i,o))throw new v(`Failed to delete device: ${i}
|
|
66
|
+
The device may be running.`,"Failed to delete device, The device may be running.");return await this.runEmulatorChecked(["-delete",i,"-force"],{printOutputOnSuccess:!1}),i}};import{red as EE,yellow as PE,gray as CE}from"colorette";import IE from"ora";import{green as gE}from"colorette";var yE=[[4352,4447],[9001,9002],[11904,42191],[43360,43388],[44032,55203],[63744,64255],[65040,65049],[65072,65135],[65281,65376],[65504,65510],[127744,129535],[131072,173791],[173824,177983],[177984,178207],[178208,183983],[183984,191456]],wE=[[0,31],[127,159],[768,879],[6832,6911],[7616,7679],[8203,8207],[8400,8447],[65024,65039],[65056,65071],[8205,8205]],vE=new RegExp("\x1B\\[([0-9;]*)[a-zA-Z]","g");function vm(n,e){for(let[t,r]of e)if(n>=t&&n<=r)return!0;return!1}function el(n){let e=n.replace(vE,""),t=0,r=0;for(;r<e.length;){let o=e.codePointAt(r);if(o===void 0)break;vm(o,wE)||(vm(o,yE)?t+=2:t+=1),r+=o>65535?2:1}return t}function Sm(n,e){let t=el(n);return n+" ".repeat(Math.max(0,e-t))}function SE(n,e){return n.map((t,r)=>{let o=el(t);for(let i of e){let s=i.cells[r]??"";o=Math.max(o,el(s))}return o})}function Mt(n,e){let t=SE(n,e),r=[];r.push(n.map((o,i)=>Sm(o,t[i])).join(" ")),r.push(t.map(o=>"-".repeat(o)).join(" "));for(let o of e){let i=o.cells.map((s,a)=>Sm(s??"",t[a])).join(" ").trimEnd();r.push(o.highlight?gE(i):i)}return r.join(`
|
|
67
|
+
`)}async function Pm(n,e){let t=Date.now(),r=!0,o=null;try{await e()}catch(i){r=!1,o=ce(i),console.error(EE(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await k.track(n,i)}}function AE(n,e){if(e.size!==0)for(let t of n){if(!t.isEmulator||!t.name)continue;let r=e.get(be(t.name));r&&(t.deviceType=r)}}var DE=["Name","Serial","Kind","Device Type"];function kE(n){return{cells:[n.name??n.serial,n.serial,n.isEmulator?"emulator":"device",n.deviceType??"-"],highlight:!0}}function Cm(n,e){return n.isEmulator!==e.isEmulator?n.isEmulator?1:-1:(n.name??n.serial).localeCompare(e.name??e.serial)}function TE(){console.log(PE(" No active devices.")),console.log(CE(" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function RE(n){let t=[...n].sort(Cm).map(kE);console.log(Mt(DE,t))}function xE(n){return{name:n.name??n.serial,serial:n.serial,kind:n.isEmulator?"emulator":"device",deviceType:n.deviceType}}function NE(n){let e=[...n].sort(Cm);console.log(JSON.stringify(e.map(xE),null,2))}async function LE(n,e){if(!n.some(o=>o.isEmulator)||!e.emulatorPath)return;let r=await Ar.from(e).getDeviceTypeByName();AE(n,r)}async function bm(n,e,t,r="table"){try{let o=await n.getConnectedEntries();if(await LE(o,e),t?.stop(),r==="json"){NE(o);return}o.length===0?TE():RE(o)}catch(o){throw new v(`Failed to list devices: ${o.message}`,"Failed to list devices.")}finally{t?.stop()}}async function OE(n,e){let t=await n.listDevices();if(t.length<2)return;let r=["Multiple devices connected. Specify a device with:"];for(let o of t){let i=await n.getDeviceName(o.serial);r.push(` ${e} -t ${o.serial} # ${i}`)}throw new v(r.join(`
|
|
68
|
+
`),"Multiple devices connected.")}async function ME(n,e,t="table"){e||await OE(n,"devecocli device view");let r=await n.listDevices(),o=await n.getDeviceInfo(r,e);if(!o){if(t==="json"){console.error("No connected device found."),process.exitCode=1;return}throw new v("No connected device found.")}let i=await n.getDeviceDetail(o.serial),s=await n.getDeviceName(o.serial);if(t==="json"){let a={name:s,serial:o.serial,kind:Ct(o.serial)?"emulator":"device",deviceType:i.deviceType,osVersion:i.osVersion};console.log(JSON.stringify(a,null,2));return}console.log(` Serial: ${o.serial}`),console.log(` Device Name: ${s}`),i.deviceType&&console.log(` Device Type: ${i.deviceType}`),i.osVersion&&console.log(` OS Version: ${i.osVersion}`)}async function Im(){try{let n=await I.new();return{manager:ie.from(n),toolProvider:n}}catch(n){throw new v(`Failed to initialize device manager: ${n.message}`,"Failed to initialize device manager.")}}var tl=new bE("device").description("Manage connected devices");tl.command("list").description("List all connected devices").addOption(new Em("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let e={event:E.CommandExecuted,args:["device","list",...n.format==="json"?["--format","json"]:[]]};await Pm(e,async()=>{let{manager:t,toolProvider:r}=await Im();if(n.format==="json"){await bm(t,r,void 0,"json");return}let o=IE({text:"Querying connected devices\u2026",color:"cyan"}).start();await bm(t,r,o,"table")})});tl.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").addOption(new Em("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let e={event:E.CommandExecuted,args:["device","view",...n.target?["--target"]:[],...n.format==="json"?["--format","json"]:[]]};await Pm(e,async()=>{let{manager:t}=await Im();await ME(t,n.target,n.format)})});var Am=tl;import{Argument as ll,Command as dl,Option as Tr}from"commander";import{green as Oo,cyan as kr,red as an,yellow as At,gray as cl}from"colorette";import XE from"ora";import _E from"readline/promises";import{execa as km}from"execa";import*as sn from"fs/promises";import*as rl from"os";import*as qn from"path";var nl=`1/4:\r
|
|
59
69
|
---------------------------------------\r
|
|
60
70
|
Statement About HarmonyOS and Privacy\r
|
|
61
71
|
\r
|
|
@@ -1225,13 +1235,13 @@ Part I: Chinese mainland.\r
|
|
|
1225
1235
|
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
|
|
1226
1236
|
\r
|
|
1227
1237
|
Part III: Other countries and regions.\r
|
|
1228
|
-
---------------------------------------\r`;var
|
|
1229
|
-
`),
|
|
1230
|
-
`)}function
|
|
1231
|
-
${t}.`);return
|
|
1232
|
-
`,"utf8"),!0}catch{}return!1}async function
|
|
1238
|
+
---------------------------------------\r`;var FE=new Set,gs=new Map,ol="HarmonyOS_Software_Service_Agreement",Tm=["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(`
|
|
1239
|
+
`),Rm=Tm,il="HarmonyOS_SDK_Agreement";function xm(n,e){return`${n}\0${e}`}function Nm(){FE.clear(),gs.clear()}var jE=Tm,tt=class extends Error{constructor(e=jE){super(e),this.name="EmulatorLicenseBlockedError"}};function Lm(n,e){return[n??"",e??""].join(`
|
|
1240
|
+
`)}function Om(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 $E(n){return`Emulator${n.trim()}`}function Mm(n){let e=$E(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 qn.join(r,"Huawei",e,".emu_config")}if(process.platform==="darwin")return qn.join(rl.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||qn.join(rl.homedir(),".cache");return qn.join(t,"Huawei",e,".emu_config")}async function HE(n,e,t){let r=xm(n,e),o=gs.get(r);if(o!==void 0)return o;let i=await km(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=Lm(i.stdout,i.stderr).trim();if(i.exitCode!==0||!s)throw new tt(t);return gs.set(r,s),s}function UE(n){let e=n[0],t=n[n.length-1];return(e==='"'||e==="'")&&e===t?n.slice(1,-1):n}function BE(n){try{let e=JSON.parse(n);if(e&&typeof e=="object"&&!Array.isArray(e)){let t={};for(let[r,o]of Object.entries(e))t[r]={value:typeof o=="string"?o:String(o),delimiter:"json"};return t}}catch{return}}function WE(n){let e=n.trim();if(!(!e||e.startsWith("#")))for(let t of["=",":"]){let r=e.indexOf(t);if(r<=0)continue;let o=e.slice(0,r).trim();if(!o||t===":"&&o.includes("//"))continue;let i=UE(e.slice(r+1).trim());return{key:o,entry:{value:i,delimiter:t}}}}function VE(n){let e={};for(let t of n.split(/\r?\n/)){let r=WE(t);r&&(e[r.key]=r.entry)}return e}function GE(n){let e=n.trim();if(!e)return{};let t=BE(e);return t||VE(n)}function zE(n){return typeof n!="string"?!1:n.normalize("NFKC").trim().toLowerCase()==="agree"}async function _m(n,e,t,r){let o=await HE(n,e,r),i=Om(o);if(!i)throw new tt(r);let s=Mm(i),a;try{a=await sn.readFile(s,"utf8")}catch(d){throw d.code==="ENOENT"?new tt(r):d}let l=GE(a)[t];if(!l)throw new tt(r);if(l.delimiter==="=")throw new tt(r);if(!zE(l.value))throw new tt(r)}async function sl(n,e){await _m(n,e,ol,Rm)}async function al(n,e){await _m(n,e,il,Rm)}async function qE(n,e){let t=await km(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),r=Lm(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 o=xm(n,e);return gs.set(o,r),r}async function Fm(n,e){let t=await qE(n,e),r=Om(t);if(!r)throw new Error(`Cannot parse Emulator major.minor from:
|
|
1241
|
+
${t}.`);return Mm(r)}function Dm(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function JE(n,e,t){if(!t.startsWith("{"))return!1;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return r[ol]="agree",r[il]="agree",await sn.writeFile(n,`${JSON.stringify(r,null,2)}
|
|
1242
|
+
`,"utf8"),!0}catch{}return!1}async function YE(n,e){let t=ol,r=il,o=[{k:t,re:new RegExp(`^\\s*${Dm(t)}\\s*[:=]`)},{k:r,re:new RegExp(`^\\s*${Dm(r)}\\s*[:=]`)}],i=e.length===0?[]:e.split(/\r?\n/),s=[],a=new Set;for(let c of i){let l=!1;for(let{k:d,re:g}of o)if(g.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 sn.writeFile(n,s.join(`
|
|
1233
1243
|
`)+(s.length>0?`
|
|
1234
|
-
`:""),"utf8")}async function
|
|
1244
|
+
`:""),"utf8")}async function jm(n){await sn.mkdir(qn.dirname(n),{recursive:!0});let e="";try{e=await sn.readFile(n,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}let t=e.trim();await JE(n,e,t)||await YE(n,e)}async function $m(n,e){return console.log(nl),0}var KE="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function Hm(n,e){try{return await sl(n,e),await al(n,e),!0}catch(t){if(t instanceof tt)return!1;throw t}}async function Um(n,e){if(await Hm(n,e))return console.log("Emulator license agreements are already accepted."),0;if(console.log(nl),!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=_E.createInterface({input:process.stdin,output:process.stdout}),o;try{o=await r.question(KE)}finally{r.close()}let i=o.trim().toLowerCase();if(i!=="y"&&i!=="yes")return console.error("Agreements not accepted. Emulator features will remain blocked until accepted."),1;try{let s=await Fm(n,e);await jm(s),Nm()}catch(s){return console.error(s.message),1}return console.log("Emulator license agreements accepted."),0}async function Bm(n,e){if(await Hm(n,e))return console.log("Emulator license agreements are already accepted."),0;try{let t=await Fm(n,e);await jm(t),Nm()}catch(t){return console.error(t.message),1}return console.log("Emulator license agreements accepted."),0}async function nt(n,e){let t=Date.now(),r=!0,o=null;try{await e()}catch(i){r=!1,o=ce(i),console.error(an(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await k.track(n,i)}}var ZE=["ohos.qemu.hvd.name","const.product.name","const.product.model"],Wm=["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"],QE=`
|
|
1235
1245
|
Folded state scene mappings:
|
|
1236
1246
|
foldableFold (3):
|
|
1237
1247
|
open Fully expanded state
|
|
@@ -1254,44 +1264,46 @@ Folded state scene mappings:
|
|
|
1254
1264
|
left-half-folded-right-folded
|
|
1255
1265
|
left-expanded-right-half-folded
|
|
1256
1266
|
left-half-folded-right-half-folded
|
|
1257
|
-
`,
|
|
1258
|
-
Run \`devecocli emulator image list --all\` and use an exact OS Version value.`)}function
|
|
1259
|
-
${
|
|
1260
|
-
${
|
|
1261
|
-
${
|
|
1262
|
-
`)}});rf.action(async(n,e)=>{try{DE(n),RE(e.osVersion);let{manager:t}=await qe(),r=await t.listDownloadedImageOsVersions();kE(e.osVersion,r),console.log(pr(`Creating emulator "${n}"...`)),await t.createVirtualDevice({name:n,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(ho(`Emulator "${n}" created successfully.`))}catch(t){console.error(we(`${t.message}`)),process.exit(1)}});ie.command("delete <name>").description("Delete a local emulator instance").action(async n=>{let{manager:e}=await qe();console.log(pr(`Deleting emulator "${n}"...`));try{let t=await e.deleteVirtualDevice(n);console.log(ho(`Emulator "${t}" deleted successfully.`))}catch(t){let r=t;console.error(we(r.message)),r.stdout&&console.error(mo(r.stdout)),r.stderr&&console.error(mo(r.stderr)),process.exit(1)}});var of=ie;import{Command as yb}from"commander";import{red as Vc,cyan as Tt}from"colorette";import*as Af from"readline";import*as Cf from"crypto";import*as sf from"http";import*as af from"crypto";import{URL as eb}from"url";var ns=class{server=null;port=0;clientSecret;callbackPath="/callback";resolveCallback=null;rejectCallback=null;timeoutId=null;baseUrl;successRedirectUrl;failedRedirectUrl;constructor(e,t,r,o){this.clientSecret=e,this.baseUrl=t,this.successRedirectUrl=r,this.failedRedirectUrl=o}async start(){return new Promise((e,t)=>{let r=sf.createServer((o,i)=>{this.handleRequest(o,i)});r.keepAliveTimeout=1,r.on("error",o=>{t(new Error("Failed to start local auth server",{cause:o}))}),r.listen(0,"127.0.0.1",()=>{this.server=r;let o=r.address();this.port=o.port,e()})})}async waitForCallback(e=3e4){return new Promise((t,r)=>{this.resolveCallback=o=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),t(o)},this.rejectCallback=o=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),r(o)},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 i=new eb(e.url??"",`http://${r}`);if(i.pathname!==this.callbackPath){t.writeHead(404),t.end("Not Found");return}try{let s=i.searchParams;e.method==="POST"?this.readBody(e,t,s):this.handleCallbackRequest(e,t,s,"")}catch(s){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(s)}}readBody(e,t,r){let o="",i=0,s=65536;e.on("data",a=>{if(i+=a.length,i>s){e.destroy(new Error("Request body too large"));return}o+=a.toString()}),e.on("end",()=>{this.handleCallbackRequest(e,t,r,o)})}handleCallbackRequest(e,t,r,o){try{let i=this.parseParams(r,o),s=i.get("code"),a=i.get("tempToken"),c=i.get("siteId"),l=i.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(i){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(i)}}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&&af.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 De from"fs";import*as Kt from"path";import{homedir as ab}from"os";var Dt={};iw(Dt,{LocalCrypto:()=>Dt,decryptForLocalStorage:()=>ob,decryptForLocalStorageFromDirectory:()=>ib,encryptForLocalStorage:()=>rb,isEncryptedBlob:()=>sb});import*as Y from"fs";import*as Se from"path";import*as Ae from"crypto";import*as lf from"os";import{homedir as df}from"os";var ve=class extends Error{constructor(e){super(e),this.name="DefinedError"}};var go=Pn.ALGORITHM,uf=Pn.IV_LENGTH,yo=Pn.KEY_LENGTH,wo=Pn.KEY_LENGTH,Mn=Pn.KEK_VERSIONS,rs=process.env.DEVECO_CLI_DATA_DIR||Se.join(df(),fe.CONFIG_DIR_NAME,fe.APP_NAME),os=Se.join(df(),".local","share",fe.APP_NAME,"keys"),mr=Se.join(rs,fe.KEY_FILE_NAME);function cf(n){return lf.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 $c(n){return Se.join(os,`${n}.bin`)}function pf(){if(!Y.existsSync(rs))try{Y.mkdirSync(rs,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new ve(cf(rs)):n}if(!Y.existsSync(os))try{Y.mkdirSync(os,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new ve(cf(Se.dirname(os))):n}}function ff(){pf();for(let n of Mn){let e=$c(n);Y.existsSync(e)||Y.writeFileSync(e,Ae.randomBytes(yo),{mode:384})}}function mf(n){if(!Mn.includes(n))throw new Error(`Invalid kekId: ${n}`);ff();let e=$c(n),t=Y.readFileSync(e);if(t.length===yo)return t;let r=Ae.randomBytes(yo);return Y.writeFileSync(e,r,{mode:384}),r}function Hc(n,e){let t=Ae.randomBytes(uf),r=mf(e),o=Ae.createCipheriv(go,r,t),i=Buffer.concat([o.update(n),o.final()]),s=o.getAuthTag();return{version:1,algorithm:go,kekId:e,encryptedDek:i.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function hf(n,e){return gf(Buffer.from(n.encryptedDek,"base64"),e,n.iv,n.authTag)}function gf(n,e,t,r){let o=Ae.createDecipheriv(go,e,Buffer.from(t,"base64"));return o.setAuthTag(Buffer.from(r,"base64")),Buffer.concat([o.update(n),o.final()])}function yf(n,e){return gf(Buffer.from(n.ciphertext,"base64"),e,n.iv,n.authTag).toString("utf8")}function tb(){if(ff(),Y.existsSync(mr))return;let n=Ae.randomBytes(wo),e=Hc(n,Mn[0]);Y.writeFileSync(mr,JSON.stringify(e,null,2),{mode:384})}function wf(){tb();let n=JSON.parse(Y.readFileSync(mr,"utf8")),e=hf(n,mf(n.kekId));if(e.length===wo)return e;let t=Ae.randomBytes(wo),r=Hc(t,Mn[0]);return Y.writeFileSync(mr,JSON.stringify(r,null,2),{mode:384}),t}function nb(){pf();for(let t of Mn){let r=$c(t);Y.existsSync(r)||Y.writeFileSync(r,Ae.randomBytes(yo),{mode:384})}if(Y.existsSync(mr))return;let n=Ae.randomBytes(wo),e=Hc(n,Mn[0]);Y.writeFileSync(mr,JSON.stringify(e,null,2),{mode:384})}function rb(n){let e=wf(),t=Ae.randomBytes(uf),r=Ae.createCipheriv(go,e,t),o=Buffer.concat([r.update(n,"utf8"),r.final()]),i=r.getAuthTag();return{version:1,algorithm:go,ciphertext:o.toString("base64"),iv:t.toString("base64"),authTag:i.toString("base64"),timeStamp:Date.now()}}function ob(n){try{return yf(n,wf())}catch{throw nb(),new Error("Failed to decrypt local ciphertext")}}function ib(n,e){let t=Se.join(e,fe.KEY_FILE_NAME),r=JSON.parse(Y.readFileSync(t,"utf8"));if(!Mn.includes(r.kekId))throw new Error(`Invalid kekId: ${r.kekId}`);let o=Se.join(e,"keys",`${r.kekId}.bin`),i=Se.resolve(o),s=Se.resolve(Se.join(e,"keys"));if(!i.startsWith(s+Se.sep)&&i!==s)throw new Error("kekId resolves outside the keys directory");let a=Y.readFileSync(i);if(a.length!==yo)throw new Error("Invalid external root key");let c=hf(r,a);if(c.length!==wo)throw new Error("Invalid external data encryption key");return yf(n,c)}function sb(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 Re(){return process.env.DEVECO_CLI_AUTH_SOURCE===fe.AUTH_SOURCE_DEVECO_CODE}var is=class{getLocalTokenFilePath(){let e=process.env.DEVECO_CLI_DATA_DIR||Kt.join(ab(),fe.CONFIG_DIR_NAME,fe.APP_NAME);return Kt.join(e,fe.TOKEN_FILE_NAME)}ensureConfigDir(){let e=Kt.dirname(this.getLocalTokenFilePath());De.existsSync(e)||De.mkdirSync(e,{recursive:!0,mode:448})}async saveJwtToken(e){if(!e)throw new Error("Token is empty");let t=Dt.encryptForLocalStorage(e);this.ensureConfigDir();let r=this.getLocalTokenFilePath();De.writeFileSync(r,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){return Re()?this.loadDevecoCodeToken():this.loadLocalJwtToken()}loadDevecoCodeToken(){if(!Re())return null;let e=process.env.DEVECO_CODE_AUTH_DIR?.trim();if(!e)return null;let t=Kt.resolve(e);try{let r=Kt.join(t,fe.TOKEN_FILE_NAME);if(!De.existsSync(r))return null;let o=JSON.parse(De.readFileSync(r,"utf8"));return Dt.isEncryptedBlob(o)?Dt.decryptForLocalStorageFromDirectory(o,e):null}catch{return null}}async loadLocalJwtToken(){let e=this.getLocalTokenFilePath();try{if(!De.existsSync(e))return null;let t=JSON.parse(De.readFileSync(e,"utf8"));return Dt.isEncryptedBlob(t)?Dt.decryptForLocalStorage(t):null}catch(t){let r=t.code;return r==="EACCES"||r==="EPERM"||r==="ENOENT"||await this.clearToken(),null}}async clearToken(){if(Re()){m("clearToken: skipped, session managed by DevEco Code");return}let e=this.getLocalTokenFilePath();try{De.existsSync(e)&&De.unlinkSync(e)}catch(t){throw new Error("Failed to clear token",{cause:t})}}},Rt=new is;import{spawn as cb}from"child_process";function lb(n){try{let e=new URL(n);return!(!["http:","https:"].includes(e.protocol)||e.hostname===""||n.includes('"'))}catch{return!1}}function db(n){return n.replace(/[&|<>()^%!]/g,e=>`^${e}`)}async function vf(n){if(!lb(n))throw new Error(`Invalid URL: ${JSON.stringify(n)}`);let e,t;switch(process.platform){case"win32":e="cmd",t=["/c","start",'""',db(n)];break;case"darwin":e="open",t=[n];break;default:e="xdg-open",t=[n];break}let r=cb(e,t,{stdio:"ignore",shell:!1,windowsHide:!0});return new Promise((o,i)=>{r.on("error",s=>{i(new Error("Failed to open browser",{cause:s}))}),r.on("close",s=>{s===0?o():i(new Error(`Browser process exited with code ${s}`))})})}import ub from"axios";var Uc=class{client;constructor(){let e={timeout:Jr.HTTP_TIMEOUT_MS,headers:{"User-Agent":hi.USER_AGENT,"accept-language":hi.ACCEPT_LANGUAGE},transformResponse:[t=>t],proxy:!1};this.client=ub.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}
|
|
1263
|
-
${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){try{return JSON.parse(e.data)}catch(t){throw new Error(`Failed to parse JSON response: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}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}),o=Buffer.from(r.data),i=o.toString("utf8");return{statusCode:r.status,statusText:r.statusText??"",buffer:o,body:i}}},
|
|
1264
|
-
`)}function vb(){return new Promise(n=>{let e=Af.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),n()})})}var vo=new yb("auth").description("Authentication commands (login, logout, status, team)");vo.command("login").description("Log in to your Huawei Developer account").action(async()=>{if(Re()){console.log(Vc("Login is managed by DevEco Code. Login from DevEco Code instead."));return}try{let n=await Ee.getUserInfo();if(n){console.log(Tt(`Already logged in, User Name:${n.userName}`));return}console.log(Tt("Starting login process...")),console.log(Tt("Press Enter to open browser for login...")),await vb();let e=await Ee.login();console.log(Tt(`Login successful. Logged in as ${e.userName}.`))}catch(n){throw n instanceof ve||(n instanceof Error?n.message:String(n)).includes("Network connection failed")?n:new Error("Login failed",{cause:n})}});vo.command("logout").description("Log out of your Huawei Developer account").action(async()=>{if(Re()){console.log(Vc("Login is managed by DevEco Code. Log out from DevEco Code instead."));return}try{let n=await Ee.logout();console.log(n?Tt("Logout successful"):Tt("Already logged out."))}catch(n){throw new Error("Logout failed",{cause:n})}});vo.command("status").description("Show the currently logged-in user").action(async()=>{let n=await Ee.getUserInfo();if(!n){console.log(Tt("Not logged in"));return}console.log(Tt(`Current user: ${n.userName}`))});var Sb=vo.command("team").description("Team-related commands");Sb.command("list").description("List team accounts the current user has joined").action(async()=>{try{let n=await Xt();console.log(wb(n.teamList))}catch(n){if(n instanceof ve){console.log(Vc(n.message));return}throw n}});var Df=vo;import{Command as Mb}from"commander";import{green as _b,red as Co,cyan as Jf,yellow as Kf,dim as Xf}from"colorette";import Fb from"p-limit";import Eb from"ora";var ot=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=Eb(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 kf from"fs";import*as Gc from"path";import{homedir as Rf}from"os";function Zt(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}var Tf=["DevEco"];async function ls(){let n=await x.get(He.TAGS_API_URL),t=ds(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 bb(n){let e=[],t=He.DEFAULT_PAGE_SIZE,r=He.DEFAULT_MAX_PAGES,o=1;for(;o<=r;){let i=await x.post(He.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:o,pageSize:t,tagIds:[n]}}),s=ds(i,"Skills API");if(e.push(...s.data.list),s.data.list.length<t)break;o++}return e}async function zc(n){let e=new Map,t=n.map(o=>bb(o)),r=await Promise.all(t);for(let o of r)for(let i of o)e.has(i.id)||e.set(i.id,i);return Array.from(e.values()).filter(o=>o.tags?.every(i=>!Tf.includes(i.name)))}async function Pb(n,e){let t=await x.post(He.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:He.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return ds(t,"Skills API").data.list}async function qc(n,e){let t=new Map,r=e.map(i=>Pb(n,i)),o=await Promise.all(r);for(let i of o)for(let s of i)t.has(s.id)||t.set(s.id,s);return Array.from(t.values()).filter(i=>i.tags?.every(s=>!Tf.includes(s.name)))}function xf(n){Zt(n);let e=[];for(let[,t]of Object.entries(Qe)){let r=b.ensurePathWithinRoot(Gc.join(Rf(),t.path),Gc.join(Rf(),t.path,n));kf.existsSync(r)&&e.push(t.displayName)}return e.sort()}function ds(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=x.parseJson(n);if(t.code!==He.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Nf(n){Zt(n);let e=`${He.SKILL_API_BASE}/${n}/checksum`,t=await x.get(e);return ds(t,"Checksum API").data}import Cb from"adm-zip";import Ib from"crypto";import{timingSafeEqual as Ab}from"crypto";import Of from"fs";import K from"path";import{fileURLToPath as Db}from"url";import{homedir as Mf}from"os";import{red as Rb}from"colorette";var xt=Of.promises;function Lf(n,e){let t=K.resolve(e),r=K.resolve(n),o=K.relative(r,t);if(o.startsWith("..")||K.isAbsolute(o))throw new Error(`Path traversal detected: ${e}.`)}function Yc(n){return K.isAbsolute(n)?n:K.resolve(process.cwd(),n)}function kb(n){return Ib.createHash("sha256").update(n).digest("hex")}async function Tb(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=kb(n),o=e.sha256.toLowerCase(),i=Buffer.from(r,"hex"),s=Buffer.from(o,"hex");if(i.length!==s.length||!Ab(i,s))throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function _f(n){Zt(n);let e=`${He.SKILL_API_BASE}/${n}/install?format=zip`,t=await x.getBinary(e),r=await Nf(n);return await Tb(t,r),t}async function xb(n,e,t){Zt(t);let r=new Cb(n),o=r.getEntries();try{await xt.stat(e)}catch{await xt.mkdir(e,{recursive:!0})}let i=K.join(e,t);Lf(e,i);for(let s of o){let a=K.join(i,s.entryName);Lf(i,a)}r.extractAllTo(i,!0)}async function Jc(n){let e=Qe[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(Qe).join(", ")}`);let t=K.join(Mf(),e.path.replace("/skills",""));try{return await xt.access(t),!0}catch{return!1}}function Kc(n){let e=Qe[n];return K.join(Mf(),e.path)}function Nb(n){let e=Qe[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(Qe).join(", ")}`);return e}function Xc(n,e){let t=Nb(e),r="projectPath"in t?t.projectPath:K.join("."+e,"skills");return K.join(n,r)}async function Lb(n,e,t){Zt(e);let r=K.join(n,e);try{if(await xt.access(r),t)await xt.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 Zc(n,e,t){await xb(n,e,t),console.log(`Skill ${t} installed to ${K.join(e,t)}.`)}async function Qc(n,e,t){let r=K.join(e,t);await xt.mkdir(r,{recursive:!0});let o=K.join(r,K.basename(n));await xt.copyFile(n,o),console.log(`Skill ${t} installed to ${r}.`)}function Ff(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(Rb(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function gr(n,e,t,r){try{let o=await e(),{shouldSkip:i}=await Lb(o,n,r);return i?{success:!0,skipped:!0}:(await t(o),{success:!0})}catch(o){return Ff(n,o,"Installation failed")}}async function el(n,e){try{Zt(n);let t=await e(),r=K.join(t,n);try{await xt.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await xt.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return Ff(n,t,"Removal failed")}}async function jf(n,e,t,r=!1){return gr(n,()=>Kc(e),o=>Zc(t,o,n),r)}async function $f(n,e,t,r=!1){return gr(n,()=>t,o=>Zc(e,o,n),r)}async function Hf(n,e,t,r,o=!1){return gr(n,()=>Xc(t,r),i=>Zc(e,i,n),o)}async function Uf(n,e,t,r=!1){return gr(n,()=>Kc(t),o=>Qc(e,o,n),r)}async function Bf(n,e,t,r,o=!1){return gr(n,()=>Xc(t,r),i=>Qc(e,i,n),o)}async function Wf(n,e,t,r=!1){return gr(n,()=>t,o=>Qc(e,o,n),r)}async function tl(n,e){return el(n,()=>Kc(e))}async function Vf(n,e){return el(n,()=>e)}async function Gf(n,e,t){return el(n,()=>Xc(e,t))}function zf(){let e=K.dirname(Db(import.meta.url));for(;;){let t=K.join(e,"SKILL.md");if(Of.existsSync(t))return t;let r=K.dirname(e);if(r===e)break;e=r}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import qf from"fs";import{cyan as Ob}from"colorette";async function So(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await Jc(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function Eo(){let n=[];for(let e of Object.keys(Qe))await Jc(e)&&n.push(e);return n}function bo(n){let e=n.filter(o=>o.success&&!o.skipped).length,t=n.filter(o=>o.skipped).length,r=n.filter(o=>!o.success).length;console.log(),console.log(Ob("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function Qt(n,e,t){if(!qf.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!qf.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function Po(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?Yc(n):void 0,resolvedProject:e?Yc(e):void 0}}async function us(n,e,t){let r=[],o=[],i;if(e?i=e:t&&n.agent?o=(await So(n.agent)).map(a=>({project:t,agent:a})):t?o=(await Eo()).map(a=>({project:t,agent:a})):n.agent?r=await So(n.agent):r=await Eo(),!i&&r.length===0&&o.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:o,customPath:i}}var Zf="deveco";async function jb(n){let e=await ls();if(n.all)return(await zc(e)).map(r=>r.enName);{let r=(await qc(n.skill,e)).find(o=>o.enName===n.skill);if(!r)throw new Error(`Skill "${n.skill}" not found`);return[r.enName]}}async function $b(n,e,t,r){let o=[];if(t.customPath){let i=await $f(n,e,t.customPath,r);return o.push(i),o}for(let i of t.agents){let s=await jf(n,i,e,r);o.push(s)}for(let{project:i,agent:s}of t.projectAgents){let a=await Hf(n,e,i,s,r);o.push(a)}return o}function Hb(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}=Po(n.path,n.project,n.agent);return t&&Qt(t,"Project directory",n.force),e&&Qt(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}function Ub(n,e,t){return!!(e||t||n.path||n.project||n.agent)}function Bb(){return{agents:[Zf],projectAgents:[],customPath:void 0}}async function Wb(n,e,t){let r=Re()&&!Ub(n,e,t)?Bb():await us(n,e,t);return{skillNames:await jb(n),targets:r}}async function Vb(n,e,t,r){let o=[],i=n.length,s=Fb(5),a=n.map(c=>s(()=>Gb(c)));for(let c=0;c<n.length;c++){let l=n[c],d=i>1?` (${c+1}/${i})`:"";r.start(`Installing ${l}${d}...`);let g=await a[c];if(!g.success){r.fail(),console.log(Co(`${l}: Download failed - ${g.error}`)),o.push({success:!1});continue}r.stop();let w=await $b(l,g.buffer,e,t);o.push(...w)}return o}async function Gb(n){try{let e=await _f(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 zb(n){let e=new ot;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=Hb(n),{skillNames:o,targets:i}=await Wb(n,t,r),s=await Vb(o,i,n.force||!1,e);e.stop(),bo(s)}catch(t){throw e.stop(),t}}function qb(n){let{resolvedPath:e,resolvedProject:t}=Po(n.path,n.project,n.agent);return t&&Qt(t,"Project directory"),e&&Qt(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function Yb(n,e){let t=new ot;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:o}=qb(e);t.stop();let i=await Jb(e,n,r,o);t.stop(),bo(i)}catch(r){throw t.stop(),r}}function Yf(n,e=""){if(n.length===0)throw new Error(`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function ps(n,e){let t=[];for(let r of e){let o=r.type==="agent"?await tl(n,r.agent):await Gf(n,r.project,r.agent);t.push(o)}return t}async function Jb(n,e,t,r){if(t)return[await Vf(e,t)];if(r&&n.agent){let a=(await So(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return ps(e,a)}if(r){let s=await Eo();Yf(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return ps(e,a)}if(n.agent){let a=(await So(n.agent)).map(c=>({type:"agent",agent:c}));return ps(e,a)}if(Re())return[await tl(e,Zf)];let o=await Eo();Yf(o,"or use --path for a custom location.");let i=o.map(s=>({type:"agent",agent:s}));return ps(e,i)}var Io=new Mb("skills").description("Manage HarmonyOS skills");Io.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 ot;try{e.start("Fetching skills...");let t=await ls(),r=await zc(t);if(r.length===0){e.stop(),console.log(Kf("No skills available."));return}e.succeed(`Fetched ${r.length} skills`);for(let o of r)if(n.long){console.log(Jf(o.enName)),console.log(Xf(o.description));let i=xf(o.enName);i.length>0&&console.log(_b(`Installed for: ${i.join(", ")}`)),console.log()}else console.log(o.enName)}catch(t){e.stop(),console.error(Co(t.message)),process.exit(1)}});Io.command("find <keyword>").description("Search skills by keyword").action(async n=>{let e=new ot;try{e.start("Searching skills...");let t=await ls(),r=await qc(n,t);if(r.length===0){console.log(Kf(`No skills found matching '${n}'.`)),e.stop();return}e.succeed(`Found ${r.length} skills.`);for(let o of r)console.log(Jf(o.enName)),console.log(Xf(o.description)),console.log()}catch(t){e.stop(),console.error(Co(t.message)),process.exit(1)}});Io.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 zb(n)}catch(e){console.error(Co(e.message)),process.exit(1)}});Io.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 Yb(n.skill,n)}catch(e){console.error(Co(e.message)),process.exit(1)}});var Qf=Io;import{Command as Xb,InvalidArgumentError as ms}from"commander";import{cyan as fs}from"colorette";function Fn(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=er(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 nl=[800,1500,2500];function Kb(n){return new Promise(e=>setTimeout(e,n))}var yr=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(`
|
|
1265
|
-
`)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let o=t[0];return
|
|
1267
|
+
`,eP="6.1.0";function tP(n){let e=n.trim();if(!e)throw new Error("--target must not be empty.");return e}function nP(n){let e=n.trim();if(!Wm.includes(e))throw new Error(`Invalid fold state "${n}". Available values: ${Wm.join(", ")}`);return e}function Gm(n,e,t,r){let o=e.trim();if(!/^-?\d+$/.test(o))throw new Error(`${n} must be an integer in [${t}, ${r}].`);let i=Number(o);if(i<t||i>r)throw new Error(`${n} must be in [${t}, ${r}].`);return i}function zm(n,e,t,r,o){let i=e.trim(),s=Number(i);if(!i||Number.isNaN(s))throw new Error(`${n} must be a number in [${t}, ${r}].`);if(o!==void 0&&!rP(i,o))throw new Error(`${n} supports at most ${o} decimal place(s).`);if(s<t||s>r)throw new Error(`${n} must be in [${t}, ${r}].`);return i}function rP(n,e){let t=n.split(".")[1];return t===void 0||t.length<=e}function oP(n,e,t,r,o){return Number(zm(n,e,t,r,o))}function iP(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 sP(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 aP(n,e){let t=o=>o.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(o=>t(o)===r)){console.error(an("--os-version does not match any downloaded image (exact string required).")),console.log(At("Use one of these --os-version values:"));for(let o of e)console.log(` ${o}`);throw new Error(`No downloaded image matches --os-version "${n}".`)}}var cP=["Name","Status","Serial","Device Type","OS Version"];function lP(n){return{cells:[n.name,n.status,n.serial??"-",n.deviceType??"-",n.osVersion??"-"],highlight:n.status==="running"}}async function dP(n,e){let t=await Promise.all(e.map(async r=>{let o=await yr(n,r,ZE);return[r,o]}));return new Map(t)}async function uP(n){let e=await Xc(n),t=await dP(n,e);return{serials:e,params:t}}function pP(n,e,t,r,o){if(e)for(let i of["const.product.name","const.product.model"]){let s=e.get(i);if(!s)continue;let a=t.indexOf(s);if(a===-1)continue;t.splice(a,1),o.set(s,n);let c=r.indexOf(n);c!==-1&&r.splice(c,1);return}}function mP(n,e,t){let r=new Map,o=new Map,i=[...n],s=[...t];for(let a of n){let c=e.get(a),l=c?.get("ohos.qemu.hvd.name");l&&o.set(l,a),t.length>0&&pP(a,c,s,i,r)}for(let a=0;a<s.length&&a<i.length;a++)r.set(s[a],i[a]);return{productSerialMap:r,hvdSerialMap:o}}function fP(n,e,t){let r=n.map(o=>({emu:o,serial:e.get(o.name)??t.get(o.name),effectiveRunning:o.isRunning===!0||t.has(o.name)}));return r.sort((o,i)=>o.effectiveRunning!==i.effectiveRunning?o.effectiveRunning?-1:1:o.emu.name.localeCompare(i.emu.name)),r.map(({emu:o,serial:i,effectiveRunning:s})=>({name:o.name,status:s?"running":"stopped",serial:i??null,deviceType:o.deviceType??null,osVersion:o.osVersion??null}))}async function hP(n,e,t,r){try{let[o,i]=await Promise.all([n.listEmulators(),uP(e)]);if(o.length===0){r?.stop(),console.log(t==="json"?"[]":At(" No emulator instances found."));return}let s=o.filter(g=>g.isRunning).map(g=>g.name),{productSerialMap:a,hvdSerialMap:c}=mP(i.serials,i.params,s);r?.stop();let l=fP(o,a,c);if(t==="json"){console.log(JSON.stringify(l,null,2));return}let d=l.map(lP);console.log(Mt(cP,d))}catch(o){throw r?.stop(),new Error(`Failed to list emulators: ${o.message}`,{cause:o})}}function qm(n,e,t){let r=!1;for(let o=0;o<n.length;o++){let i=n[o];if(i.status!=="rejected")continue;r=!0;let s=i.reason;console.error(an(`Failed to ${t} emulator "${e[o]}": ${s.message}`)),s.stdout&&console.error(cl(s.stdout)),s.stderr&&console.error(cl(s.stderr))}return r}var gP=2e3,yP=6e4;async function wP(n,e){let t=be(e);return(await Zc(n)).some(o=>be(o)===t)}async function Jm(n,e,t,r=yP,o=gP){let i=Date.now()+r;for(;Date.now()<i;){if(await wP(n,e)===t)return!0;await new Promise(a=>setTimeout(a,o))}return!1}async function vP(n,e,t){if(await n.startEmulator(t)==="already-running"){console.log(At(`Emulator "${t}" is already running.`));return}console.log(kr(`Starting emulator "${t}"...`));let o=await Jm(e,t,!0);console.log(o?Oo(`Emulator "${t}" started successfully.`):At(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function SP(n,e,t){let r=await Promise.allSettled(t.map(o=>vP(n,e,o)));qm(r,t,"start")}async function Ym(n,e){let t=e.trim();if(!Ct(t))return t;let r=await ie.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 bP(n,e,t){let r=await Ym(e,t);if(console.log(kr(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(At(`Emulator "${r}" is already stopped.`));return}let i=await Jm(e,r,!1);console.log(i?Oo(`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 EP(n,e,t){let r=await Promise.allSettled(t.map(o=>bP(n,e,o)));qm(r,t,"stop")}async function rt(){let n=await I.new();return{manager:Ar.from(n),toolProvider:n}}async function _t(n,e,t){let r={event:E.CommandExecuted,args:["emulator",t,"--target"]};await nt(r,async()=>{let o=tP(n.target),i=e(),{manager:s,toolProvider:a}=await rt(),c=await Ym(a.hdcPath,o);await s.controlEmulator(c,i),console.log(Oo(`Emulator "${o}" operation completed.`))})}function PP(n){let e=[];return ys(e,"longitude",n.longitude,-180,180,8),ys(e,"latitude",n.latitude,-90,90,8),ys(e,"altitude",n.altitude,-1e4,1e4,2),ys(e,"bearing",n.direction,0,359.99,2,"--direction"),ul(e,"Specify one geolocation option.")}function CP(n){let e=[];return No(e,"light",n.lightIntensity,0,1e5,!1,"--light-intensity"),No(e,"humidity",n.humidity,0,100,!1),No(e,"temperature",n.temperature,-273.1,100,!1),No(e,"steps",n.steps,0,1e4,!0),No(e,"heartrate",n.heartrate,0,255,!0),ul(e,"Specify one sensor option.")}function ul(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 ys(n,e,t,r,o,i,s=`--${e}`){t!==void 0&&n.push({type:"gps",key:e,value:zm(s,t,r,o,i)})}function No(n,e,t,r,o,i,s=`--${e}`){if(t===void 0)return;let a=i?Gm(s,t,r,o):oP(s,t,r,o,1);n.push({type:"sensor",key:e,value:a})}function IP(n){let e=[];return n.level!==void 0&&e.push({type:"battery",level:Gm("--level",n.level,0,100)}),n.status!==void 0&&e.push({type:"battery-status",status:n.status==="charging"?1:0}),ul(e,"Specify --level or --status.")}var de=new dl("emulator").description("Manage emulator instances");de.hook("preAction",async()=>{(await I.new()).require({studio:eP})});var AP=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function ws(n){let e=new Tr("--device-type <type>","Emulator device type").choices([...AP]);return n?e.makeOptionMandatory():e}function Dr(n,e){for(let t of e)if(t in n)return n[t]}function Lo(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function Vm(n){let e=Lo(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var DP=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],kP="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";async function TP(n,e,t){if(!await n.hasAvailableEmulatorImage({deviceType:e,osVersion:t}))throw new Error(`Invalid --os-version value "${t}".
|
|
1268
|
+
Run \`devecocli emulator image list --all\` and use an exact OS Version value.`)}function Km(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function Xm(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let o=r,i=Lo(Dr(o,["osVersion","OsVersion","OSVersion","os_version"])),s=Lo(Dr(o,["deviceType","DeviceType","device_type"])),a=Vm(Dr(o,["downloaded","Downloaded","isDownloaded"])),c=Lo(Dr(o,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=Lo(Dr(o,["releaseType","ReleaseType","release_type"])),d=Vm(Dr(o,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[i,s,c,l,d,a],highlight:e&&a==="true"})}return t}function RP(n){let e=n.trim();if(!e)return!0;let t=Km(e);return t===null?!1:t.length===0?!0:Xm(t,!0).length===0}function xP(n,e){let t=n.trim();if(!t)return"";let r=Km(t);if(!r)return n.trimEnd();let o=Xm(r,e);return Mt(DP,o)}var vs=new dl("image").description("HarmonyOS emulator system images (download, list, remove)");vs.command("download").description("Download system image").addOption(ws(!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 e={event:E.CommandExecuted,args:["emulator","image","download",...n.deviceType?["--device-type"]:[],...n.osVersion?["--os-version"]:[],...n.force?["--force"]:[]]};await nt(e,async()=>{let{manager:t,toolProvider:r}=await rt();try{await al(r.emulatorPath,r.sdkPath)}catch(s){if(s instanceof tt){console.error(an(s.message)),process.exitCode=1;return}throw s}let o=n.deviceType?.trim(),i=n.osVersion?.trim();if(!o||!i){console.error(an(o?"Error: misssing required option '--os-version <version>'":"Error: missing required option '--device-type <type>'")),process.exitCode=1;return}await TP(t,o,i),await t.installEmulatorImage({deviceType:o,osVersion:i,force:n.force===!0})})});vs.command("remove").description("Remove a downloaded system image").addOption(ws(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let e={event:E.CommandExecuted,args:["emulator","image","remove","--device-type","--os-version"]};await nt(e,async()=>{let{manager:t}=await rt();await t.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})})});vs.command("list").description("List system images").addOption(ws(!1)).option("--all","List all images (local and remote)").addOption(new Tr("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let e={event:E.CommandExecuted,args:["emulator","image","list",...n.deviceType?["--device-type"]:[],...n.all?["--all"]:[],...n.format!=="table"?["--format"]:[]]};await nt(e,async()=>{let{manager:t}=await rt(),r;n.all?r=void 0:r=!0;let o=await t.listEmulatorImages({deviceType:n.deviceType,downloaded:r});if(RP(o)){console.log(At(kP));return}if(n.format==="json"){console.log(o.trimEnd());return}let i=xP(o,n.all===!0);console.log(i)})});de.addCommand(vs);var Ss=new dl("license").description("Review and accept emulator license agreements interactively (prints full text + y/N prompt)");Ss.command("view").description("Review agreement text (read-only, no changes)").action(async()=>{let n={event:E.CommandExecuted,args:["emulator","license","view"]};await nt(n,async()=>{let{toolProvider:e}=await rt(),t=await $m(e.emulatorPath,e.sdkPath);process.exitCode=t})});Ss.command("accept").description("Accept all emulator license agreements non-interactively (skips review and prompt)").action(async()=>{let n={event:E.CommandExecuted,args:["emulator","license","accept"]};await nt(n,async()=>{let{toolProvider:e}=await rt(),t=await Bm(e.emulatorPath,e.sdkPath);process.exitCode=t})});Ss.action(async()=>{let n={event:E.CommandExecuted,args:["emulator","license"]};await nt(n,async()=>{let{toolProvider:e}=await rt(),t=await Um(e.emulatorPath,e.sdkPath);process.exitCode=t})});de.addCommand(Ss);de.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>_t(n,()=>({type:"shake"}),"shake"));de.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>_t(n,()=>({type:"power"}),"power"));de.command("rotate").description("Rotate emulator").addOption(new Tr("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new ll("<direction>").choices(["left","right"])).action((n,e)=>_t(e,()=>({type:"rotation",direction:n}),"rotate"));de.command("volume").description("Change volume").addOption(new Tr("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new ll("<direction>").choices(["up","down"])).action((n,e)=>_t(e,()=>({type:"volume",direction:n}),"volume"));de.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",QE).action((n,e)=>_t(e,()=>({type:"folded-state",state:nP(n)}),"fold"));de.command("battery").description("Set battery level or charging status").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--level <0-100>","Battery level, SOC (charging: 0-100; not charging: 1-100)").addOption(new Tr("--status <status>","Charging status").choices(["charging","discharging"])).action(n=>_t(n,()=>IP(n),"battery"));de.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=>_t(n,()=>PP(n),"geolocation"));de.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new ll("<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 _t(e,()=>t[n],"scene")});de.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=>_t(n,()=>CP(n),"sensor"));de.command("list").description("List all emulator instances").addOption(new Tr("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let e={event:E.CommandExecuted,args:["emulator","list"]};await nt(e,async()=>{let{manager:t,toolProvider:r}=await rt(),o=n.format==="table"?XE({text:"Listing emulators\u2026",color:"cyan"}).start():void 0;await hP(t,r.hdcPath,n.format,o)})});de.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let e={event:E.CommandExecuted,args:["emulator","start"]};await nt(e,async()=>{let{manager:t,toolProvider:r}=await rt();try{await sl(r.emulatorPath,r.sdkPath)}catch(o){if(o instanceof tt){console.error(an(o.message)),process.exitCode=1;return}throw o}if(!n?.length){console.error(an("Error: missing required argument 'names'")),process.exitCode=1;return}await SP(t,r.hdcPath,n)})});de.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 e={event:E.CommandExecuted,args:["emulator","stop"]};await nt(e,async()=>{let{manager:t,toolProvider:r}=await rt();if(!n?.length){console.error(an("Error: missing required argument 'names'")),process.exitCode=1;return}await EP(t,r.hdcPath,n)})});var Zm=de.command("create <name>").description("Create a local emulator instance.").addOption(ws(!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");Zm.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
|
|
1269
|
+
${At("Tip: ")}${cl("Unquoted --os-version values with spaces/parentheses are split into multiple arguments. Use:")}
|
|
1270
|
+
${kr('devecocli emulator create 123 --device-type phone --os-version "HarmonyOS 6.0.1(21)"')}
|
|
1271
|
+
${kr('devecocli emulator create 123 --device-type phone --os-version="HarmonyOS 6.0.1(21)"')}
|
|
1272
|
+
`)}});Zm.action(async(n,e)=>{let t={event:E.CommandExecuted,args:["emulator","create","--device-type","--os-version",...e.force?["--force"]:[]]};await nt(t,async()=>{iP(n),sP(e.osVersion);let{manager:r}=await rt(),o=await r.listDownloadedImageOsVersions();aP(e.osVersion,o),console.log(kr(`Creating emulator "${n}"...`)),await r.createVirtualDevice({name:n,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(Oo(`Emulator "${n}" created successfully.`))})});de.command("delete <name>").description("Delete a local emulator instance").action(async n=>{let e={event:E.CommandExecuted,args:["emulator","delete"]};await nt(e,async()=>{let{manager:t}=await rt();console.log(kr(`Deleting emulator "${n}"...`));let r=await t.deleteVirtualDevice(n);console.log(Oo(`Emulator "${r}" deleted successfully.`))})});var Qm=de;import{Command as YP}from"commander";import{red as yl,cyan as Dt}from"colorette";import*as bf from"readline";import*as vf from"crypto";import*as ef from"http";import*as tf from"crypto";import{URL as NP}from"url";var bs=class{server=null;port=0;clientSecret;callbackPath="/callback";resolveCallback=null;rejectCallback=null;timeoutId=null;baseUrl;successRedirectUrl;failedRedirectUrl;constructor(e,t,r,o){this.clientSecret=e,this.baseUrl=t,this.successRedirectUrl=r,this.failedRedirectUrl=o}async start(){return new Promise((e,t)=>{let r=ef.createServer((o,i)=>{this.handleRequest(o,i)});r.keepAliveTimeout=1,r.on("error",o=>{t(new Error("Failed to start local auth server",{cause:o}))}),r.listen(0,"127.0.0.1",()=>{this.server=r;let o=r.address();this.port=o.port,e()})})}async waitForCallback(e=3e4){return new Promise((t,r)=>{this.resolveCallback=o=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),t(o)},this.rejectCallback=o=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),r(o)},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 i=new NP(e.url??"",`http://${r}`);if(i.pathname!==this.callbackPath){t.writeHead(404),t.end("Not Found");return}try{let s=i.searchParams;e.method==="POST"?this.readBody(e,t,s):this.handleCallbackRequest(e,t,s,"")}catch(s){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(s)}}readBody(e,t,r){let o="",i=0,s=65536;e.on("data",a=>{if(i+=a.length,i>s){e.destroy(new Error("Request body too large"));return}o+=a.toString()}),e.on("end",()=>{this.handleCallbackRequest(e,t,r,o)})}handleCallbackRequest(e,t,r,o){try{let i=this.parseParams(r,o),s=i.get("code"),a=i.get("tempToken"),c=i.get("siteId"),l=i.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(i){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(i)}}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&&tf.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 Me from"fs";import*as cn from"path";import{homedir as $P}from"os";var Ft={};lv(Ft,{LocalCrypto:()=>Ft,decryptForLocalStorage:()=>_P,decryptForLocalStorageFromDirectory:()=>FP,encryptForLocalStorage:()=>MP,isEncryptedBlob:()=>jP});import*as X from"fs";import*as De from"path";import*as Oe from"crypto";import*as rf from"os";import{homedir as of}from"os";var Ae=class extends Error{constructor(e){super(e),this.name="DefinedError"}};var Mo=$n.ALGORITHM,sf=$n.IV_LENGTH,_o=$n.KEY_LENGTH,Fo=$n.KEY_LENGTH,Jn=$n.KEK_VERSIONS,Es=process.env.DEVECO_CLI_DATA_DIR||De.join(of(),Se.CONFIG_DIR_NAME,Se.APP_NAME),Ps=De.join(of(),".local","share",Se.APP_NAME,"keys"),Rr=De.join(Es,Se.KEY_FILE_NAME);function nf(n){return rf.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 pl(n){return De.join(Ps,`${n}.bin`)}function af(){if(!X.existsSync(Es))try{X.mkdirSync(Es,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new Ae(nf(Es)):n}if(!X.existsSync(Ps))try{X.mkdirSync(Ps,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new Ae(nf(De.dirname(Ps))):n}}function cf(){af();for(let n of Jn){let e=pl(n);X.existsSync(e)||X.writeFileSync(e,Oe.randomBytes(_o),{mode:384})}}function lf(n){if(!Jn.includes(n))throw new Error(`Invalid kekId: ${n}`);cf();let e=pl(n),t=X.readFileSync(e);if(t.length===_o)return t;let r=Oe.randomBytes(_o);return X.writeFileSync(e,r,{mode:384}),r}function ml(n,e){let t=Oe.randomBytes(sf),r=lf(e),o=Oe.createCipheriv(Mo,r,t),i=Buffer.concat([o.update(n),o.final()]),s=o.getAuthTag();return{version:1,algorithm:Mo,kekId:e,encryptedDek:i.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function df(n,e){return uf(Buffer.from(n.encryptedDek,"base64"),e,n.iv,n.authTag)}function uf(n,e,t,r){let o=Oe.createDecipheriv(Mo,e,Buffer.from(t,"base64"));return o.setAuthTag(Buffer.from(r,"base64")),Buffer.concat([o.update(n),o.final()])}function pf(n,e){return uf(Buffer.from(n.ciphertext,"base64"),e,n.iv,n.authTag).toString("utf8")}function LP(){if(cf(),X.existsSync(Rr))return;let n=Oe.randomBytes(Fo),e=ml(n,Jn[0]);X.writeFileSync(Rr,JSON.stringify(e,null,2),{mode:384})}function mf(){LP();let n=JSON.parse(X.readFileSync(Rr,"utf8")),e=df(n,lf(n.kekId));if(e.length===Fo)return e;let t=Oe.randomBytes(Fo),r=ml(t,Jn[0]);return X.writeFileSync(Rr,JSON.stringify(r,null,2),{mode:384}),t}function OP(){af();for(let t of Jn){let r=pl(t);X.existsSync(r)||X.writeFileSync(r,Oe.randomBytes(_o),{mode:384})}if(X.existsSync(Rr))return;let n=Oe.randomBytes(Fo),e=ml(n,Jn[0]);X.writeFileSync(Rr,JSON.stringify(e,null,2),{mode:384})}function MP(n){let e=mf(),t=Oe.randomBytes(sf),r=Oe.createCipheriv(Mo,e,t),o=Buffer.concat([r.update(n,"utf8"),r.final()]),i=r.getAuthTag();return{version:1,algorithm:Mo,ciphertext:o.toString("base64"),iv:t.toString("base64"),authTag:i.toString("base64"),timeStamp:Date.now()}}function _P(n){try{return pf(n,mf())}catch{throw OP(),new Error("Failed to decrypt local ciphertext")}}function FP(n,e){let t=De.join(e,Se.KEY_FILE_NAME),r=JSON.parse(X.readFileSync(t,"utf8"));if(!Jn.includes(r.kekId))throw new Error(`Invalid kekId: ${r.kekId}`);let o=De.join(e,"keys",`${r.kekId}.bin`),i=De.resolve(o),s=De.resolve(De.join(e,"keys"));if(!i.startsWith(s+De.sep)&&i!==s)throw new Error("kekId resolves outside the keys directory");let a=X.readFileSync(i);if(a.length!==_o)throw new Error("Invalid external root key");let c=df(r,a);if(c.length!==Fo)throw new Error("Invalid external data encryption key");return pf(n,c)}function jP(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 _e(){return process.env.DEVECO_CLI_AUTH_SOURCE===Se.AUTH_SOURCE_DEVECO_CODE}var Cs=class{getLocalTokenFilePath(){let e=process.env.DEVECO_CLI_DATA_DIR||cn.join($P(),Se.CONFIG_DIR_NAME,Se.APP_NAME);return cn.join(e,Se.TOKEN_FILE_NAME)}ensureConfigDir(){let e=cn.dirname(this.getLocalTokenFilePath());Me.existsSync(e)||Me.mkdirSync(e,{recursive:!0,mode:448})}async saveJwtToken(e){if(!e)throw new Error("Token is empty");let t=Ft.encryptForLocalStorage(e);this.ensureConfigDir();let r=this.getLocalTokenFilePath();Me.writeFileSync(r,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){return _e()?this.loadDevecoCodeToken():this.loadLocalJwtToken()}loadDevecoCodeToken(){if(!_e())return null;let e=process.env.DEVECO_CODE_AUTH_DIR?.trim();if(!e)return null;let t=cn.resolve(e);try{let r=cn.join(t,Se.TOKEN_FILE_NAME);if(!Me.existsSync(r))return null;let o=JSON.parse(Me.readFileSync(r,"utf8"));return Ft.isEncryptedBlob(o)?Ft.decryptForLocalStorageFromDirectory(o,e):null}catch{return null}}async loadLocalJwtToken(){let e=this.getLocalTokenFilePath();try{if(!Me.existsSync(e))return null;let t=JSON.parse(Me.readFileSync(e,"utf8"));return Ft.isEncryptedBlob(t)?Ft.decryptForLocalStorage(t):null}catch(t){let r=t.code;return r==="EACCES"||r==="EPERM"||r==="ENOENT"||await this.clearToken(),null}}async clearToken(){if(_e()){h("clearToken: skipped, session managed by DevEco Code");return}let e=this.getLocalTokenFilePath();try{Me.existsSync(e)&&Me.unlinkSync(e)}catch(t){throw new Error("Failed to clear token",{cause:t})}}},jt=new Cs;import{spawn as HP}from"child_process";function UP(n){try{let e=new URL(n);return!(!["http:","https:"].includes(e.protocol)||e.hostname===""||n.includes('"'))}catch{return!1}}function BP(n){return n.replace(/[&|<>()^%!]/g,e=>`^${e}`)}async function ff(n){if(!UP(n))throw new Error(`Invalid URL: ${JSON.stringify(n)}`);let e,t;switch(process.platform){case"win32":e="cmd",t=["/c","start",'""',BP(n)];break;case"darwin":e="open",t=[n];break;default:e="xdg-open",t=[n];break}let r=HP(e,t,{stdio:"ignore",shell:!1,windowsHide:!0});return new Promise((o,i)=>{r.on("error",s=>{i(new Error("Failed to open browser",{cause:s}))}),r.on("close",s=>{s===0?o():i(new Error(`Browser process exited with code ${s}`))})})}import WP from"axios";var fl=class{client;constructor(){let e={timeout:wo.HTTP_TIMEOUT_MS,headers:{"User-Agent":Vi.USER_AGENT,"accept-language":Vi.ACCEPT_LANGUAGE},transformResponse:[t=>t],proxy:!1};this.client=WP.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}
|
|
1273
|
+
${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){try{return JSON.parse(e.data)}catch(t){throw new Error(`Failed to parse JSON response: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}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}),o=Buffer.from(r.data),i=o.toString("utf8");return{statusCode:r.status,statusText:r.statusText??"",buffer:o,body:i}}},N=new fl;function hf(n){let e=n.split(".");return e.length===3&&e.every(t=>t.length>0)}var $t={CHINA:"CN",RUSSIA:"RU",SINGAPORE:"SG",EUROPE:"EU"},Yn={CHINA:"zh_CN",RUSSIA:"ru_RU",EUROPE:"de_DE"},Is={CHINA:"1",SINGAPORE:"5",EUROPE:"7",RUSSIA:"8"},VP={[$t.CHINA]:Yn.CHINA,[$t.RUSSIA]:Yn.RUSSIA,[$t.EUROPE]:Yn.EUROPE,[$t.SINGAPORE]:Yn.CHINA},GP={[Is.CHINA]:$t.CHINA,[Is.SINGAPORE]:$t.SINGAPORE,[Is.EUROPE]:$t.EUROPE,[Is.RUSSIA]:$t.RUSSIA};function gf(n){return VP[n]??Yn.CHINA}function yf(n){return GP[n]??$t.CHINA}var hl=class{async getJwtToken(e,t,r,o,i){let s=e.split("&")[0],a=yf(t),c={tempToken:s,site:a,version:Se.API_VERSION,appid:i},l=`${r}/${o}`,d=await N.get(l,{params:c});if(d.statusCode!==200)throw new Error(`Failed to get jwtToken: status=${d.statusCode}`);let g=d.data.trim();if(!hf(g))throw new Error("Invalid jwtToken format");return g}},wf=new hl;var gl=class{async checkJwtToken(e,t,r=!1){let o={refresh:String(r),jwtToken:e},i=`${t}/${Y.JWT_TOKEN_CHECK_PATH}`,s=await N.get(i,{headers:o});if(s.statusCode!==200)throw new Error(`Failed to check jwtToken: ${s.statusCode}`);return N.parseJson(s)}async refreshToken(e){let t=await jt.loadJwtToken();return t?this.refreshTokenWithToken(t,e):null}async refreshTokenWithToken(e,t){try{let r={refresh:"true",jwtToken:e},o=`${t}/${Y.JWT_TOKEN_CHECK_PATH}`,i=await N.get(o,{headers:r});if(i.statusCode!==200)return null;let s=N.parseJson(i);return!s.status||!s.userInfo?null:{accessToken:s.userInfo.accessToken,refreshToken:s.userInfo.refreshToken??""}}catch(r){let o=r;return console.error(`Failed to refresh token: ${o.code??""} ${o.message??""}`),null}}async getUserInfoFromJwt(e,t,r=!1){let o=await this.checkJwtToken(e,t,r);return!o.status||!o.userInfo||!o.userInfo.accessToken?(h("jwtToken invalid."),await jt.clearToken(),null):{userId:o.userInfo.userId??"",userName:o.userInfo.name??"",accessToken:o.userInfo.accessToken,refreshToken:o.userInfo.refreshToken??"",jwtToken:e,countryCode:o.userInfo.nationalCode,language:gf(o.userInfo.nationalCode),isRealName:String(o.userInfo.realName)==="true"}}async fetchUserInfo(e,t){let r=await jt.loadJwtToken();return r?this.getUserInfoFromJwt(r,e,t):null}},xr=new gl;var As=class{config;server=null;constructor(e){this.config={...vo,...e}}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}async login(){try{h(`Login started, isDevecoCodeAuth: ${_e()}`);let e=this.generateClientSecret();this.server=new bs(e,Y.CN_LOGIN_URL,this.config.successRedirectUrl,this.config.failedRedirectUrl),await this.server.start(),h(`Local auth server started on port ${this.server.getPort()}`),await this.openLoginPage(this.server.getPort(),e),h("Browser opened for authentication");let t=await this.server.waitForCallback(this.config.timeout);if(h(`Callback received: siteId=${t.siteId}`),t.siteId!=="1")throw new Ae("Non-China accounts are not supported.");let r=await wf.getJwtToken(t.tempToken,t.siteId,Y.CN_LOGIN_URL,this.config.tempTokenCheckUrl,this.config.appId);h("JWT token received");let o=await xr.getUserInfoFromJwt(r,Y.CN_LOGIN_URL);if(!o)throw new Ae("Login failed: failed to get user info");return h(`User info received: ${o.userName}`),await jt.saveJwtToken(r),h("JWT token saved"),o}finally{this.server&&(await this.server.stop(),this.server=null)}}async isLoggedIn(){return await this.getUserInfo(!0)!==null}async logout(){let e=await jt.loadJwtToken();if(!e)return!1;let r=`${Y.CN_LOGIN_URL}/${this.config.logoutUrl}?jwtToken=${e}`;try{await N.post(r,{timeout:5e3})}catch{h("Logout: server notification failed, local token cleared")}finally{await jt.clearToken()}return!0}async getUserInfo(e=!0){return xr.fetchUserInfo(Y.CN_LOGIN_URL,e)}generateClientSecret(){return vf.randomUUID().replace(/-/g,"")}async openLoginPage(e,t){let o=`${Y.CN_LOGIN_URL}/${this.config.authUrl}?port=${e}&appid=${this.config.appId}&code=${t}`;await ff(o)}async refreshToken(){return xr.refreshToken(Y.CN_LOGIN_URL)}},ke=new As;function qP(){return _e()?"Not logged in. Please login via DevEco Code first.":"Please run `devecocli auth login` first."}function JP(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 Ds=class{config;constructor(e){this.config={...vo,...e}}updateConfig(e){this.config={...this.config,...e}}async listTeams(){let e=await xr.fetchUserInfo(Y.CN_LOGIN_URL,!0);if(!e)throw new Ae(qP());let t=await this.fetchTeamList(e.accessToken,e.userId),r=JP(t);return{userId:e.userId,teamList:r}}async fetchTeamList(e,t){let r=this.config.agcTeamListUrl,o;try{o=await N.get(r,{headers:{oauth2Token:e,uid:t,source:"cli",lang:Yn.CHINA},timeout:15e3})}catch(i){let s=i.message;throw s.includes("401")?new Ae("Token expired. Run `devecocli auth login` again."):new Error(`Network error while listing teams: ${s}`,{cause:i})}if(o.statusCode!==200)throw new Error(`Failed to list teams: HTTP ${o.statusCode}`);return typeof o.data=="string"?JSON.parse(o.data):o.data}},Sf=new Ds;async function ln(){return Sf.listTeams()}async function ks(n,e,t){let r=Date.now(),o=!0,i=null;try{await e()}catch(s){o=!1,i=ce(s);let a=t?.(s);if(a)throw a}finally{let s={duration_ms:Date.now()-r,success:o,error_code:i};await k.track(n,s)}}function KP(n){if(n.length===0)return Dt("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))),o=s=>s.map((a,c)=>a.padEnd(r[c])).join(" "),i=r.map(s=>"-".repeat(s)).join(" ");return[o(e),i,...t.map(o)].join(`
|
|
1274
|
+
`)}function XP(){return new Promise(n=>{let e=bf.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),n()})})}var jo=new YP("auth").description("Authentication commands (login, logout, status, team)");jo.command("login").description("Log in to your Huawei Developer account").action(async()=>{if(_e()){console.log(yl("Login is managed by DevEco Code. Login from DevEco Code instead."));return}let n={event:E.CommandExecuted,args:["auth","login"]};await ks(n,async()=>{let e=await ke.getUserInfo();if(e){console.log(Dt(`Already logged in, User Name:${e.userName}`));return}console.log(Dt("Starting login process...")),console.log(Dt("Press Enter to open browser for login...")),await XP();let t=await ke.login();console.log(Dt(`Login successful. Logged in as ${t.userName}.`))},e=>{throw e instanceof Ae||(e instanceof Error?e.message:String(e)).includes("Network connection failed")?e:new Error("Login failed",{cause:e})})});jo.command("logout").description("Log out of your Huawei Developer account").action(async()=>{if(_e()){console.log(yl("Login is managed by DevEco Code. Log out from DevEco Code instead."));return}let n={event:E.CommandExecuted,args:["auth","logout"]};await ks(n,async()=>{let e=await ke.logout();console.log(e?Dt("Logout successful"):Dt("Already logged out."))},e=>new Error("Logout failed",{cause:e}))});jo.command("status").description("Show the currently logged-in user").action(async()=>{let n={event:E.CommandExecuted,args:["auth","status"]};await ks(n,async()=>{let e=await ke.getUserInfo();if(!e){console.log(Dt("Not logged in"));return}console.log(Dt(`Current user: ${e.userName}`))},()=>{console.log(Dt("Not logged in"))})});var ZP=jo.command("team").description("Team-related commands");ZP.command("list").description("List team accounts the current user has joined").action(async()=>{let n={event:E.CommandExecuted,args:["auth","team","list"]};await ks(n,async()=>{let e=await ln();console.log(KP(e.teamList))},e=>{if(e instanceof Ae){console.log(yl(e.message));return}throw new Error("Failed to list teams",{cause:e})})});var Ef=jo;import{Command as mC}from"commander";import{green as fC,red as Wo,cyan as Vf,yellow as Gf,dim as zf}from"colorette";import hC from"p-limit";import QP from"ora";var pt=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=QP(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 Cf from"fs";import*as wl from"path";import{homedir as Pf}from"os";function dn(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}var If=["DevEco"];async function Ts(){let n=await N.get(Ke.TAGS_API_URL),t=Rs(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 eC(n){let e=[],t=Ke.DEFAULT_PAGE_SIZE,r=Ke.DEFAULT_MAX_PAGES,o=1;for(;o<=r;){let i=await N.post(Ke.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:o,pageSize:t,tagIds:[n]}}),s=Rs(i,"Skills API");if(e.push(...s.data.list),s.data.list.length<t)break;o++}return e}async function vl(n){let e=new Map,t=n.map(o=>eC(o)),r=await Promise.all(t);for(let o of r)for(let i of o)e.has(i.id)||e.set(i.id,i);return Array.from(e.values()).filter(o=>o.tags?.every(i=>!If.includes(i.name)))}async function tC(n,e){let t=await N.post(Ke.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:Ke.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return Rs(t,"Skills API").data.list}async function Sl(n,e){let t=new Map,r=e.map(i=>tC(n,i)),o=await Promise.all(r);for(let i of o)for(let s of i)t.has(s.id)||t.set(s.id,s);return Array.from(t.values()).filter(i=>i.tags?.every(s=>!If.includes(s.name)))}function Af(n){dn(n);let e=[];for(let[,t]of Object.entries(ct)){let r=C.ensurePathWithinRoot(wl.join(Pf(),t.path),wl.join(Pf(),t.path,n));Cf.existsSync(r)&&e.push(t.displayName)}return e.sort()}function Rs(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=N.parseJson(n);if(t.code!==Ke.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Df(n){dn(n);let e=`${Ke.SKILL_API_BASE}/${n}/checksum`,t=await N.get(e);return Rs(t,"Checksum API").data}import nC from"adm-zip";import rC from"crypto";import{timingSafeEqual as oC}from"crypto";import Tf from"fs";import ee from"path";import{fileURLToPath as iC}from"url";import{homedir as Rf}from"os";import{red as sC}from"colorette";var Ht=Tf.promises;function kf(n,e){let t=ee.resolve(e),r=ee.resolve(n),o=ee.relative(r,t);if(o.startsWith("..")||ee.isAbsolute(o))throw new Error(`Path traversal detected: ${e}.`)}function bl(n){return ee.isAbsolute(n)?n:ee.resolve(process.cwd(),n)}function aC(n){return rC.createHash("sha256").update(n).digest("hex")}async function cC(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=aC(n),o=e.sha256.toLowerCase(),i=Buffer.from(r,"hex"),s=Buffer.from(o,"hex");if(i.length!==s.length||!oC(i,s))throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function xf(n){dn(n);let e=`${Ke.SKILL_API_BASE}/${n}/install?format=zip`,t=await N.getBinary(e),r=await Df(n);return await cC(t,r),t}async function lC(n,e,t){dn(t);let r=new nC(n),o=r.getEntries();try{await Ht.stat(e)}catch{await Ht.mkdir(e,{recursive:!0})}let i=ee.join(e,t);kf(e,i);for(let s of o){let a=ee.join(i,s.entryName);kf(i,a)}r.extractAllTo(i,!0)}async function El(n){let e=ct[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(ct).join(", ")}`);let t=ee.join(Rf(),e.path.replace("/skills",""));try{return await Ht.access(t),!0}catch{return!1}}function Pl(n){let e=ct[n];return ee.join(Rf(),e.path)}function dC(n){let e=ct[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(ct).join(", ")}`);return e}function Cl(n,e){let t=dC(e),r="projectPath"in t?t.projectPath:ee.join("."+e,"skills");return ee.join(n,r)}async function uC(n,e,t){dn(e);let r=ee.join(n,e);try{if(await Ht.access(r),t)await Ht.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 Il(n,e,t){await lC(n,e,t),console.log(`Skill ${t} installed to ${ee.join(e,t)}.`)}async function Al(n,e,t){let r=ee.join(e,t);await Ht.mkdir(r,{recursive:!0});let o=ee.join(r,ee.basename(n));await Ht.copyFile(n,o),console.log(`Skill ${t} installed to ${r}.`)}function Nf(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(sC(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function Nr(n,e,t,r){try{let o=await e(),{shouldSkip:i}=await uC(o,n,r);return i?{success:!0,skipped:!0}:(await t(o),{success:!0})}catch(o){return Nf(n,o,"Installation failed")}}async function Dl(n,e){try{dn(n);let t=await e(),r=ee.join(t,n);try{await Ht.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await Ht.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return Nf(n,t,"Removal failed")}}async function Lf(n,e,t,r=!1){return Nr(n,()=>Pl(e),o=>Il(t,o,n),r)}async function Of(n,e,t,r=!1){return Nr(n,()=>t,o=>Il(e,o,n),r)}async function Mf(n,e,t,r,o=!1){return Nr(n,()=>Cl(t,r),i=>Il(e,i,n),o)}async function _f(n,e,t,r=!1){return Nr(n,()=>Pl(t),o=>Al(e,o,n),r)}async function Ff(n,e,t,r,o=!1){return Nr(n,()=>Cl(t,r),i=>Al(e,i,n),o)}async function jf(n,e,t,r=!1){return Nr(n,()=>t,o=>Al(e,o,n),r)}async function kl(n,e){return Dl(n,()=>Pl(e))}async function $f(n,e){return Dl(n,()=>e)}async function Hf(n,e,t){return Dl(n,()=>Cl(e,t))}function Uf(){let e=ee.dirname(iC(import.meta.url));for(;;){let t=ee.join(e,"SKILL.md");if(Tf.existsSync(t))return t;let r=ee.dirname(e);if(r===e)break;e=r}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import Bf from"fs";import{cyan as pC}from"colorette";async function $o(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await El(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function Ho(){let n=[];for(let e of Object.keys(ct))await El(e)&&n.push(e);return n}function Uo(n){let e=n.filter(o=>o.success&&!o.skipped).length,t=n.filter(o=>o.skipped).length,r=n.filter(o=>!o.success).length;console.log(),console.log(pC("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function un(n,e,t){if(!Bf.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!Bf.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function Bo(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?bl(n):void 0,resolvedProject:e?bl(e):void 0}}async function xs(n,e,t){let r=[],o=[],i;if(e?i=e:t&&n.agent?o=(await $o(n.agent)).map(a=>({project:t,agent:a})):t?o=(await Ho()).map(a=>({project:t,agent:a})):n.agent?r=await $o(n.agent):r=await Ho(),!i&&r.length===0&&o.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:o,customPath:i}}var qf="deveco";async function gC(n){let e=await Ts();if(n.all)return(await vl(e)).map(r=>r.enName);{let r=(await Sl(n.skill,e)).find(o=>o.enName===n.skill);if(!r)throw new Kn("errorCode",`Skill "${n.skill}" not found`);return[r.enName]}}async function yC(n,e,t,r){let o=[];if(t.customPath){let i=await Of(n,e,t.customPath,r);return o.push(i),o}for(let i of t.agents){let s=await Lf(n,i,e,r);o.push(s)}for(let{project:i,agent:s}of t.projectAgents){let a=await Mf(n,e,i,s,r);o.push(a)}return o}function wC(n){if(n.all&&n.skill)throw new Kn("errorCode","`--all` and `--skill` cannot be specified together.");if(!n.all&&!n.skill)throw new Kn("errorCode","Must specify `--all` or `--skill`");let{resolvedPath:e,resolvedProject:t}=Bo(n.path,n.project,n.agent);return t&&un(t,"Project directory",n.force),e&&un(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}function vC(n,e,t){return!!(e||t||n.path||n.project||n.agent)}function SC(){return{agents:[qf],projectAgents:[],customPath:void 0}}async function bC(n,e,t){let r=_e()&&!vC(n,e,t)?SC():await xs(n,e,t);return{skillNames:await gC(n),targets:r}}async function EC(n,e,t,r){let o=[],i=0,s=n.length,a=hC(5),c=n.map(l=>a(()=>PC(l)));for(let l=0;l<n.length;l++){let d=n[l],g=s>1?` (${l+1}/${s})`:"";r.start(`Installing ${d}${g}...`);let w=await c[l];if(!w.success){r.fail(),console.log(Wo(`${d}: Download failed - ${w.error}`)),o.push({success:!1});continue}i+=w.buffer.length,r.stop();let b=await yC(d,w.buffer,e,t);o.push(...b)}return{results:o,diskBytes:i}}async function PC(n){try{let e=await xf(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 CC(n){let e=new pt;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=wC(n),{skillNames:o,targets:i}=await bC(n,t,r),{results:s,diskBytes:a}=await EC(o,i,n.force||!1,e);return e.stop(),Uo(s),{diskBytes:a,results:s}}catch(t){throw e.stop(),t}}function Jf(n){let e=n.length,t=n.filter(s=>s.success&&!s.skipped).length,r=n.filter(s=>s.skipped).length,o=n.filter(s=>!s.success).length,i=[...new Set(n.filter(s=>!s.success&&typeof s.error=="string").map(s=>IC(s.error)))];return{opTotal:e,opSuccess:t,opFailed:o,opSkipped:r,...i.length>0?{failedErrors:i}:{}}}function IC(n){let e=/^([A-Za-z_][A-Za-z0-9_-]*)/.exec(n.trim());return e?e[1].slice(0,32):"error"}var Kn=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function AC(n){let e=n;return n instanceof Kn?n.code:e.code??e.name??"UnknownError"}async function Ls(n,e){let t=Date.now(),r=!0,o=null,i={};try{i=await e()}catch(s){throw r=!1,o=AC(s),s}finally{let s={event:E.SkillOperation,subAction:n,args:process.argv.slice(2).filter(a=>a.startsWith("-")),...i};await k.track(s,{duration_ms:Date.now()-t,success:r,error_code:o})}}function DC(n){return Ls("add",async()=>{let{diskBytes:e,results:t}=await CC(n);return{diskUsage:Ie(e),...Jf(t)}})}function kC(n){let{resolvedPath:e,resolvedProject:t}=Bo(n.path,n.project,n.agent);return t&&un(t,"Project directory"),e&&un(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function TC(n,e){let t=new pt;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:o}=kC(e);t.stop();let i=await RC(e,n,r,o);return t.stop(),Uo(i),i}catch(r){throw t.stop(),r}}function Wf(n,e=""){if(n.length===0)throw new Kn("errorCode",`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function Ns(n,e){let t=[];for(let r of e){let o=r.type==="agent"?await kl(n,r.agent):await Hf(n,r.project,r.agent);t.push(o)}return t}async function RC(n,e,t,r){if(t)return[await $f(e,t)];if(r&&n.agent){let a=(await $o(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return Ns(e,a)}if(r){let s=await Ho();Wf(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return Ns(e,a)}if(n.agent){let a=(await $o(n.agent)).map(c=>({type:"agent",agent:c}));return Ns(e,a)}if(_e())return[await kl(e,qf)];let o=await Ho();Wf(o,"or use --path for a custom location.");let i=o.map(s=>({type:"agent",agent:s}));return Ns(e,i)}var Vo=new mC("skills").description("Manage HarmonyOS skills");Vo.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async n=>{try{await Ls("list",async()=>{let e=new pt;try{e.start("Fetching skills...");let t=await Ts(),r=await vl(t);if(r.length===0)return e.stop(),console.log(Gf("No skills available.")),{resultTotal:0};e.succeed(`Fetched ${r.length} skills`);for(let o of r)if(n.long){console.log(Vf(o.enName)),console.log(zf(o.description));let i=Af(o.enName);i.length>0&&console.log(fC(`Installed for: ${i.join(", ")}`)),console.log()}else console.log(o.enName);return{resultTotal:r.length}}finally{e.stop()}})}catch(e){console.error(Wo(e.message)),process.exit(1)}});Vo.command("find <keyword>").description("Search skills by keyword").action(async n=>{try{await Ls("find",async()=>{let e=new pt;try{e.start("Searching skills...");let t=await Ts(),r=await Sl(n,t);if(r.length===0)return console.log(Gf(`No skills found matching '${n}'.`)),e.stop(),{resultTotal:0,queryLen:n.length};e.succeed(`Found ${r.length} skills.`);for(let o of r)console.log(Vf(o.enName)),console.log(zf(o.description)),console.log();return{resultTotal:r.length,queryLen:n.length}}finally{e.stop()}})}catch(e){console.error(Wo(e.message)),process.exit(1)}});Vo.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 DC(n)}catch(e){console.error(Wo(e.message)),process.exit(1)}});Vo.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 Ls("remove",async()=>{let e=await TC(n.skill,n);return Jf(e)})}catch(e){console.error(Wo(e.message)),process.exit(1)}});var Yf=Vo;import{Command as NC,InvalidArgumentError as Ms}from"commander";import{cyan as Os}from"colorette";function Xn(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=gr(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 Tl=[800,1500,2500];function xC(n){return new Promise(e=>setTimeout(e,n))}var Lr=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=ie.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(`
|
|
1275
|
+
`)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let o=t[0];return h(Os(`Using device serial: ${o}`)),o}if(e&&t.includes(e))return h(Os(`Using device serial: ${e}`)),e;let r=await this.loadConnectedDevicesByName();if(e){let o=this.findDeviceByArg(r,e);if(o)return h(Os(`Using device: ${o.name} (${o.serial})`)),o.serial;let i=this.formatConnectedDeviceList(r);throw new v(`Device '${e}' not found.
|
|
1266
1276
|
Available devices:
|
|
1267
|
-
${i}
|
|
1277
|
+
${i}`,"Device not found.")}if(r.length===1){let o=r[0];return h(Os(`Using device: ${o.name} (${o.serial})`)),o.serial}throw new v("Multiple devices found. Specify a target device using `--device <name>` or `--device <serial>`.\nAvailable devices:\n"+this.formatConnectedDeviceList(r),"Multiple devices found.")}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){h(`Retrieving PID for bundle ${r}`),C.assertBundleNameStrict(r);let o=await oe(e,["-t",t,"shell","pidof",r]),i=Xn(o,"Failed to look up PID");if(i)throw i;if(o.exitCode===0&&o.stdout.trim()){let s=o.stdout.trim(),a=s.split(/\s+/)[0]||s;return h(`Found PID for ${r}: ${a}`),a}return h(`No PID found for bundle: ${r}`),null}async resizeHilogBuffer(e,t,r){if(h(`Setting hilog buffer size to: ${r}`),!/^\d+[KMG]?$/.test(r))throw new Error(`Invalid hilog buffer size: ${JSON.stringify(r)}. Expected format: <number>[K|M|G], e.g. "4M", "16M"`);let o=await oe(e,["-t",t,"shell","hilog","-G",r]),i=Xn(o,"Failed to resize hilog buffer");if(i)throw i;o.exitCode!==0&&console.error(`Failed to resize hilog buffer: ${o.stderr||o.stdout}`)}buildHilogCommand(e,t,r,o){let i=this.buildHilogShellCommand(r,o);return[e,["-t",t,"shell",i]]}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,o,i){let a=await xp(e,t,{onData:r,onError:o,onClose:i});return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}async runHilogWithSpawnRetry(e,t,r,o,i){let s=1+Tl.length,a={stdout:"",stderr:"",exitCode:-1};for(let c=0;c<s;c++){if(a=await this.followHilog(e,t,r,o,i),a.exitCode===0||gr(a.stderr)!=="transient"||c>=s-1)return a;h(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${Tl[c]}ms`),await xC(Tl[c])}return a}async runHilogStreamingCollect(e,t,r){return this.runHilogWithSpawnRetry(e,t,()=>{},o=>{h(`Callback triggered when an error occurs during ${r}: ${o.message}`)},()=>{})}async printTailSnapshotIfNeeded(e,t,r,o){if(!r.tail&&!r.fromSeconds&&!r.toSeconds)return;let i={...r,isFollow:!1},[s,a]=this.buildHilogCommand(e,t,i,o);h(`Ready to run hilog snapshot command: ${s} ${a.join(" ")}`);let c=await this.runHilogStreamingCollect(s,a,"a hilog snapshot streaming read"),l=Xn(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=C.filterLogsByRelativeWindow(c.stdout||c.stderr,r.fromSeconds,r.toSeconds);d=C.getLastLines(d,r.tail),d.trim()&&console.log(d)}async getHilogOnce(e,t,r,o){let[i,s]=this.buildHilogCommand(e,t,r,o);h(`Ready to run hilog command: ${i} ${s.join(" ")}`);let a=await this.runHilogStreamingCollect(i,s,"a single hilog streaming read"),c=Xn(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=C.filterLogsByRelativeWindow(l,r.fromSeconds,r.toSeconds);return d=C.getLastLines(d,r.tail),d}async runHilogFollow(e,t,r,o){try{await this.printTailSnapshotIfNeeded(e,t,r,o)}catch(l){console.error(`Warning: Failed to fetch log snapshot, continuing with live stream: ${l.message}`)}let[i,s]=this.buildHilogCommand(e,t,r,o);h(`Ready to run hilog command which contain \`follow\` and \`tail\`: ${i} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(i,s,this.createFollowLineHandler(),l=>{h(`Spawn error during hilog follow: ${l.message}`)},()=>{}),c=Xn(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,o=t.bundleName?await this.getPidForBundle(r,e,t.bundleName):void 0;if(t.bundleName&&!o)throw new v(`No running process found for bundle '${t.bundleName}'. Ensure the app is launched on the device before fetching logs.`,"No running process found for bundle.");return t.logSize&&await this.resizeHilogBuffer(r,e,t.logSize),t.isFollow?await this.runHilogFollow(r,e,t,o||""):await this.getHilogOnce(r,e,t,o||"")}async getCrashLog(e,t){h(`Fetching crash logs from device: ${e}`);let r=this.toolProvider.hdcPath,o=await this.listCrashLogs(r,e,t);if(o.length===0)return t?`No crash logs found for bundle '${t}'.`:"No crash logs found.";let s=[...o].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 o=["-t",t,"shell","hidumper","-s","1201","-a","-p Faultlogger"];h(`Running command: ${e} ${o.join(" ")}`);let i=await this.runHilogStreamingCollect(e,o,"a crash log list streaming read"),s=Xn(i,"Failed to list crash logs");if(s)throw s;if(i.exitCode!==0)throw new Error(`Failed to list crash logs: ${i.stderr||i.stdout}`);return h(`Crash logs list output:
|
|
1268
1278
|
${i.stdout}`),this.parseCrashLogFilenames(i.stdout,r)}parseCrashLogFilenames(e,t){return e.split(`
|
|
1269
|
-
`).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>{try{return b.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 o=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];m(`Executing command: ${e} ${o.join(" ")}`);let i=await this.runHilogStreamingCollect(e,o,"a crash log streaming read"),s=Fn(i,"Failed to fetch crash log content");if(s)throw s;return i.exitCode!==0&&i.stderr&&console.error(`Warning: Failed to fetch crash logs: ${i.stderr}`),i.stdout+i.stderr}};import{cyan as rl,red as tm}from"colorette";import Zb from"ora";function Qb(n){try{return b.parsePositiveInteger(n,"tail")}catch{throw new ms("`tail` must be a positive integer.")}}function em(n,e){try{return b.parseDurationToSeconds(n,e)}catch{throw new ms(`${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 eP(n){try{return b.assertHilogLevel(n),n}catch{throw new ms("`level` must be one of: D, I, W, E, F.")}}function tP(n){try{return b.assertBundleNameStrict(n),n}catch(e){throw new ms(e.message)}}function nP(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.")}async function rP(n,e,t,r,o){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:o})}function oP(n,e,t,r){let o=b.filterLogsByRelativeWindow(n,t,r);return e.tail?b.getLastLines(o,e.tail):o}var iP=new Xb("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(tm(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",eP).option("--bundle-name <bundle-name>","Filter by application bundle name",tP).option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",Qb).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>em(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>em(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await sP(n)});async function sP(n){let e=Zb({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),nP(n);let r=n.from,o=n.to,i=await I.new(),s=new yr(i),a=await s.selectDevice(n.device);a||(t(),process.exit(1)),m(rl(`deviceId: ${a}`)),m(rl(`type: ${n.crash?"Crash logs":"Common logs"}`)),m(rl("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await rP(s,a,n,r,o);t(),n.crash&&c&&(c=oP(c,n,r,o)),c&&console.log(c)}catch(r){t(),console.error(tm(r.message)),process.exit(1)}}var nm=iP;import Do from"path";import Nt from"fs";import il from"process";import um from"os";import{Command as vP}from"commander";import{green as am,red as ol,cyan as SP,yellow as cm}from"colorette";import se from"fs-extra";import _ from"path";import*as om from"os";import{fileURLToPath as aP}from"url";var rm={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"}},cP=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function lP(){let n=import.meta.url,e=aP(n);if(e.includes("dist")){let i=_.dirname(e),s=_.dirname(i);return _.join(s,"templates","application")}let t=_.dirname(e),r=_.dirname(t),o=_.dirname(r);return _.join(o,"templates","application")}function im(n,e){se.mkdirSync(e,{recursive:!0});for(let t of se.readdirSync(n,{withFileTypes:!0})){let r=_.join(n,t.name),o=_.join(e,t.name);if(t.isDirectory()){im(r,o);continue}se.existsSync(o)||(se.mkdirSync(_.dirname(o),{recursive:!0}),se.copyFileSync(r,o))}}function Ao(n,e){let t=se.readFileSync(n,"utf-8"),r=t;for(let[o,i]of e)r=r.replaceAll(o,i);r!==t&&se.writeFileSync(n,r,"utf-8")}function dP(n){if(rm[n])return rm[n];if(n>=26){let e=`${n}.0.0`;return{sdkVersion:e,modelVersion:e}}}function uP(n,e){if(e===22)return;let t=dP(e);t&&(Ao(_.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),Ao(_.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),Ao(_.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function pP(n){return cP.filter(t=>!se.existsSync(_.join(n,t))).length===0}function fP(){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 mP(n){return om.platform()==="darwin"?_.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):_.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function hP(n,e){let t=mP(e);if(!se.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[o,i]of r){let s=_.join(t,o),a=_.join(n,i);se.existsSync(s)&&(se.mkdirSync(_.dirname(a),{recursive:!0}),se.copyFileSync(s,a))}return!0}function gP(n){let e=fP(),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 o=_.join(n,r);se.mkdirSync(_.dirname(o),{recursive:!0}),se.writeFileSync(o,e)}}function yP(n,e){e&&hP(n,e)||gP(n)}function wP(n){let e=[_.join(n,"gitignore.txt"),_.join(n,"entry","gitignore.txt")];for(let t of e)if(se.existsSync(t)){let r=_.dirname(t);se.renameSync(t,_.join(r,".gitignore"))}}function sm(n,e,t,r,o){let i=lP();if(!se.existsSync(i))throw new Error(`Template directory not found: ${i}`);se.mkdirSync(n,{recursive:!0}),im(i,n),wP(n),yP(n,o),Ao(_.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),Ao(_.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),uP(n,r);let s=pP(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 pm(n){if(um.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function lm(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=um.platform();if(!(e==="win32"?/^[a-zA-Z0-9._\-:\\/]+$/:/^[a-zA-Z0-9._\-/]+$/).test(n)){let i=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 ${i}.`)}let r=pm(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 bP(n){let e=n,t=Do.parse(n).root;for(;e!==t;){if(Nt.existsSync(e))return e;e=Do.dirname(e)}return Nt.existsSync(t)?t:null}function dm(n){let e=bP(n);if(!e)throw new Error(`No existing parent directory found for '${n}'. Cannot create project directory.`);try{Nt.accessSync(e,Nt.constants.W_OK)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}let t=Do.join(e,`.deveco_write_test_${Date.now()}`);try{Nt.writeFileSync(t,"test"),Nt.unlinkSync(t)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}}function PP(n){return`com.example.${n.toLowerCase()}`}function CP(n,e){if(e){let o=pm(e),i=Do.resolve(o);if(Nt.existsSync(i)){if(Nt.readdirSync(i).length>0)throw new Error(`Directory '${i}' is not empty. Cannot create project here.`)}else dm(i);return i}let t=il.cwd(),r=Do.join(t,n);if(Nt.existsSync(r))throw new Error(`Directory '${r}' already exists. Cannot create project here.`);return dm(r),r}function IP(n,e){let t=e?.getMaxApiLevel(),r=23;if(n.apiLevel){let o=Number(n.apiLevel);if(!Number.isInteger(o)||o<17)throw new Error(`Invalid API version ${n.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(o>t)throw new Error(`Invalid API version ${n.apiLevel}. Your SDK supports API version 17-${t}`)}else if(o>r)throw new Error(`Invalid API version ${n.apiLevel}. Without DevEco Studio, supported range is API version 17-${r}`);return o}return t!==void 0?t:23}async function AP(){try{return await I.new()}catch(n){console.error(cm(`DevEco Studio not found: ${n.message}`)),console.log(cm("Use placeholder API level instead."));return}}var DP=new vP("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(ol("Error: --app-name is required")),il.exit(1));let e=n.appName;EP(e);let t=n.bundleName||PP(e);b.assertBundleNameStrict(t),n.projectPath&&lm(n.projectPath);let r=CP(e,n.projectPath);lm(r),console.log(SP("Initializing project...")),console.log(`Project path: ${r}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let o=await AP(),i=IP(n,o);console.log(`API level: ${i}`);let s=o?.devecoStudioPath,a=sm(r,e,t,i,s);console.log(`
|
|
1270
|
-
`+
|
|
1271
|
-
Failed to create project.`)),console.error(
|
|
1279
|
+
`).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){h(`Fetching latest crash log file: ${r}`);let o=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];h(`Executing command: ${e} ${o.join(" ")}`);let i=await this.runHilogStreamingCollect(e,o,"a crash log streaming read"),s=Xn(i,"Failed to fetch crash log content");if(s)throw s;return i.exitCode!==0&&i.stderr&&console.error(`Warning: Failed to fetch crash logs: ${i.stderr}`),i.stdout+i.stderr}};import{cyan as Rl,red as Xf}from"colorette";import LC from"ora";function OC(n){try{return C.parsePositiveInteger(n,"tail")}catch{throw new Ms("`tail` must be a positive integer.")}}function Kf(n,e){try{return C.parseDurationToSeconds(n,e)}catch{throw new Ms(`${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 MC(n){try{return C.assertHilogLevel(n),n}catch{throw new Ms("`level` must be one of: D, I, W, E, F.")}}function _C(n){try{return C.assertBundleNameStrict(n),n}catch(e){throw new Ms(e.message)}}function FC(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.")}async function jC(n,e,t,r,o){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:o})}function $C(n,e,t,r){let o=C.filterLogsByRelativeWindow(n,t,r);return e.tail?C.getLastLines(o,e.tail):o}var HC=new NC("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(Xf(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",MC).option("--bundle-name <bundle-name>","Filter by application bundle name",_C).option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",OC).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>Kf(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>Kf(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await UC(n)});async function UC(n){let e=LC({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),FC(n);let r=n.from,o=n.to,i=await I.new(),s=new Lr(i),a=await s.selectDevice(n.device);a||(t(),process.exit(1)),h(Rl(`deviceId: ${a}`)),h(Rl(`type: ${n.crash?"Crash logs":"Common logs"}`)),h(Rl("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await jC(s,a,n,r,o);t(),n.crash&&c&&(c=$C(c,n,r,o)),c&&console.log(c)}catch(r){t(),console.error(Xf(r.message)),process.exit(1)}}var Zf=HC;import zo from"path";import Ut from"fs";import Ll from"process";import ah from"os";import{Command as eI}from"commander";import{green as rh,red as xl,cyan as tI,yellow as oh}from"colorette";import ue from"fs-extra";import F from"path";import*as eh from"os";import{fileURLToPath as BC}from"url";var Qf={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"}},WC=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function VC(){let n=import.meta.url,e=BC(n);if(e.includes("dist")){let i=F.dirname(e),s=F.dirname(i);return F.join(s,"templates","application")}let t=F.dirname(e),r=F.dirname(t),o=F.dirname(r);return F.join(o,"templates","application")}function th(n,e){ue.mkdirSync(e,{recursive:!0});for(let t of ue.readdirSync(n,{withFileTypes:!0})){let r=F.join(n,t.name),o=F.join(e,t.name);if(t.isDirectory()){th(r,o);continue}ue.existsSync(o)||(ue.mkdirSync(F.dirname(o),{recursive:!0}),ue.copyFileSync(r,o))}}function Go(n,e){let t=ue.readFileSync(n,"utf-8"),r=t;for(let[o,i]of e)r=r.replaceAll(o,i);r!==t&&ue.writeFileSync(n,r,"utf-8")}function GC(n){if(Qf[n])return Qf[n];if(n>=26){let e=`${n}.0.0`;return{sdkVersion:e,modelVersion:e}}}function zC(n,e){if(e===22)return;let t=GC(e);t&&(Go(F.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),Go(F.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),Go(F.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function qC(n){return WC.filter(t=>!ue.existsSync(F.join(n,t))).length===0}function JC(){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 YC(n){return eh.platform()==="darwin"?F.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):F.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function KC(n,e){let t=YC(e);if(!ue.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[o,i]of r){let s=F.join(t,o),a=F.join(n,i);ue.existsSync(s)&&(ue.mkdirSync(F.dirname(a),{recursive:!0}),ue.copyFileSync(s,a))}return!0}function XC(n){let e=JC(),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 o=F.join(n,r);ue.mkdirSync(F.dirname(o),{recursive:!0}),ue.writeFileSync(o,e)}}function ZC(n,e){e&&KC(n,e)||XC(n)}function QC(n){let e=[F.join(n,"gitignore.txt"),F.join(n,"entry","gitignore.txt")];for(let t of e)if(ue.existsSync(t)){let r=F.dirname(t);ue.renameSync(t,F.join(r,".gitignore"))}}function nh(n,e,t,r,o){let i=VC();if(!ue.existsSync(i))throw new Error(`Template directory not found: ${i}`);ue.mkdirSync(n,{recursive:!0}),th(i,n),QC(n),ZC(n,o),Go(F.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),Go(F.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),zC(n,r);let s=qC(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function nI(n){if(n.length<1||n.length>200)throw new pe("errorCode",`App name length must be 1-200 characters. Current: ${n.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(n))throw new pe("errorCode","Application name must start with a letter (a-z, A-Z) and contain only letters, digits, and underscores")}function ch(n){if(ah.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function ih(n){if(n.length===0)throw new pe("errorCode","Project path cannot be empty.");if(n.length>120)throw new pe("errorCode",`Project path cannot exceed 120 characters (current: ${n.length}).`);let e=ah.platform();if(!(e==="win32"?/^[a-zA-Z0-9._\-:\\/]+$/:/^[a-zA-Z0-9._\-/]+$/).test(n)){let i=e==="win32"?"letters, digits, dots, underscores, hyphens, colons, slashes (/) or backslashes (\\)":"letters, digits, dots, underscores, hyphens or slashes (/)";throw new pe("errorCode",`Project path can only contain ${i}.`)}let r=ch(n);if(/[\u4e00-\u9fff]/.test(r))throw new pe("errorCode","Project path cannot contain Chinese characters.");if(r.endsWith("."))throw new pe("errorCode","Project path cannot end with a dot (.)")}function rI(n){let e=n,t=zo.parse(n).root;for(;e!==t;){if(Ut.existsSync(e))return e;e=zo.dirname(e)}return Ut.existsSync(t)?t:null}function sh(n){let e=rI(n);if(!e)throw new pe("errorCode",`No existing parent directory found for '${n}'. Cannot create project directory.`);try{Ut.accessSync(e,Ut.constants.W_OK)}catch{throw new pe("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}let t=zo.join(e,`.deveco_write_test_${Date.now()}`);try{Ut.writeFileSync(t,"test"),Ut.unlinkSync(t)}catch{throw new pe("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}}function oI(n){return`com.example.${n.toLowerCase()}`}function iI(n,e){if(e){let o=ch(e),i=zo.resolve(o);if(Ut.existsSync(i)){if(Ut.readdirSync(i).length>0)throw new pe("errorCode",`Directory '${i}' is not empty. Cannot create project here.`)}else sh(i);return i}let t=Ll.cwd(),r=zo.join(t,n);if(Ut.existsSync(r))throw new pe("errorCode",`Directory '${r}' already exists. Cannot create project here.`);return sh(r),r}function sI(n,e){let t=e?.getMaxApiLevel(),r=23;if(n.apiLevel){let o=Number(n.apiLevel);if(!Number.isInteger(o)||o<17)throw new pe("errorCode",`Invalid API version ${n.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(o>t)throw new pe("errorCode",`Invalid API version ${n.apiLevel}. Your SDK supports API version 17-${t}`)}else if(o>r)throw new pe("errorCode",`Invalid API version ${n.apiLevel}. Without DevEco Studio, supported range is API version 17-${r}`);return o}return t!==void 0?t:23}async function aI(){try{return await I.new()}catch(n){console.error(oh(`DevEco Studio not found: ${n.message}`)),console.log(oh("Use placeholder API level instead."));return}}var pe=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};async function Nl(n,e,t,r){let o={event:E.CommandExecuted,args:["create"],apiLevel:r?.apiLevel??null},i={duration_ms:Date.now()-n,success:e,error_code:t};await k.track(o,i).catch(()=>{})}function cI(n){console.log(`
|
|
1280
|
+
`+rh("Project created successfully.")),console.log(`Project root: ${n.projectRoot}`),console.log(`App name: ${n.appName}`),console.log(`Bundle name: ${n.bundleName}`),console.log(`API level: ${n.apiLevel}`),console.log(rh("Template integrity check passed."))}var lI=new eI("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=>{let e=Date.now();try{n.appName||(console.error(xl("Error: --app-name is required")),await Nl(e,!1,"errorCode",n),Ll.exit(1));let t=n.appName;nI(t);let r=n.bundleName||oI(t);C.assertBundleNameStrict(r),n.projectPath&&ih(n.projectPath);let o=iI(t,n.projectPath);ih(o),console.log(tI("Initializing project...")),console.log(`Project path: ${o}`),console.log(`App name: ${t}`),console.log(`Bundle name: ${r}`);let i=await aI(),s=sI(n,i);console.log(`API level: ${s}`);let a=i?.devecoStudioPath,c=nh(o,t,r,s,a);cI(c),await Nl(e,!0,null,n)}catch(t){let r=t,i=t instanceof pe?t.code:r.code??r.name??"UnknownError";console.error(xl(`
|
|
1281
|
+
Failed to create project.`)),console.error(xl(r.message)),await Nl(e,!1,i,n),Ll.exit(1)}}),lh=lI;import{Command as gI}from"commander";import{red as yI,cyan as yh}from"colorette";import dI from"fs";import _s from"path";import{cyan as uI}from"colorette";import*as Fs from"smol-toml";var Or=dI.promises;async function pI(n){try{let e=await Or.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 mI(n){try{let e=await Or.readFile(n,"utf8");return e.trim()===""?{}:Fs.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 fI(n,e){let t=_s.dirname(n);await Or.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await Or.writeFile(n,r,"utf8")}async function hI(n,e){let t=_s.dirname(n);await Or.mkdir(t,{recursive:!0});let r=Fs.stringify(e);await Or.writeFile(n,r,"utf8")}function dh(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function uh(n,e,t,r,o){(!n[e]||typeof n[e]!="object")&&(n[e]={});let i=n[e];return t in i&&!o?!1:(i[t]=r,!0)}async function ph(n,e){return n.format==="codex"?mI(e):pI(e)}async function mh(n,e,t){return n.format==="codex"?hI(e,t):fI(e,t)}async function fh(n,e,t=!1){let r=Zt[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Zt).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 o=await ph(r,r.globalConfigPath);if(dh(o,r.mcpServersKey,Et)&&!t)return console.log(`MCP server ${Et} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let i=Gi(r,void 0);return uh(o,r.mcpServersKey,Et,i,t),await mh(r,r.globalConfigPath,o),console.log(`MCP server ${Et} configured in ${r.globalConfigPath}.`),{success:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${o.message}`}}}async function Ol(n,e,t=!1){let r=Zt[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Zt).join(", ")}`};let o=_s.isAbsolute(r.projectConfigPath)?r.projectConfigPath:_s.join(e,r.projectConfigPath);try{let i=await ph(r,o);if(dh(i,r.mcpServersKey,Et)&&!t)return console.log(`MCP server ${Et} already configured in ${o}.`),{success:!0,skipped:!0,configPath:o,agentName:n,installType:"project"};let s=Gi(r,e);return uh(i,r.mcpServersKey,Et,s,t),await mh(r,o,i),console.log(`MCP server ${Et} configured in ${o}.`),{success:!0,configPath:o,agentName:n,installType:"project"}}catch(i){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${i.message}`}}}function hh(n){let e=n.filter(o=>o.success&&!o.skipped).length,t=n.filter(o=>o.skipped).length,r=n.filter(o=>!o.success).length;console.log(),console.log(uI("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`);for(let o of n)!o.success&&o.error&&console.error(` - ${o.agentName??"unknown"}: ${o.error}`);r>0&&(process.exitCode=1)}var Ml="deveco-cli";async function wI(n,e,t){if(n.customPath)return[await jf(Ml,e,n.customPath,t.force)];let r=[...n.projectAgents.map(({project:s,agent:a})=>()=>Ff(Ml,e,s,a,t.force)),...n.agents.map(s=>()=>_f(Ml,e,s,t.force))],o=5,i=[];for(let s=0;s<r.length;s+=o){let a=r.slice(s,s+o);i.push(...await Promise.all(a.map(c=>c())))}return i}function vI(n){return[...new Set([...n.agents,...n.projectAgents.map(({agent:e})=>e)])]}async function gh(n,e,t,r){await k.track(n,{duration_ms:Date.now()-e,success:t,error_code:r}).catch(()=>{})}async function SI(n,e,t,r,o){let i={event:E.SkillConfigOperation,subAction:"install",targetType:r?"path":o?"project":"global",agents:vI(n)},s=Date.now();try{let a=await wI(n,e,t),c=a.every(l=>l.success||l.skipped);return await gh(i,s,c,c?null:"SKILL_INSTALL_FAILED"),a}catch(a){let c=a instanceof Error?a.code??a.name:"UnknownError";throw await gh(i,s,!1,c),a}}async function bI(n,e,t){let r=[];for(let{project:o,agent:i}of n.projectAgents){let s=await Ol(i,o,t);r.push(s)}for(let o of n.agents){let i=await Ol(o,e,t);r.push(i)}return r}async function EI(n,e){let t=[];for(let r of n){if(!Zt[r])continue;let i=await fh(r,process.cwd(),e);t.push(i)}return t}async function PI(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,o=n.projectAgents.filter(c=>c.agent!=="qoder"),i=n.agents.filter(c=>c!=="qoder"),s={...n,projectAgents:o,agents:i},a=e?await bI(s,e,r):await EI(s.agents,r);a.length>0&&(console.log(yh("MCP Configuration:")),hh(a))}async function CI(n,e,t){let r={event:E.Init,subAction:"install",targetType:e?"project":"global",agentName:t.agent},o=Date.now(),i=!0,s=null;try{await PI(n,e,t)}catch(a){throw i=!1,s=a instanceof Error?a.code??a.name:"UnknownError",a}finally{let a={duration_ms:Date.now()-o,success:i,error_code:s};await k.track(r,a)}}async function II(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}=Bo(n.path,n.project,n.agent);t&&un(t,"Project directory",n.force),e&&un(e,"Directory",n.force);let r=await xs(n,e,t);if(n.mcp){await CI(r,t,n);return}let o=Uf(),i=await SI(r,o,n,e,t);console.log(),i.length>0&&(console.log(yh("Skill Installation:")),Uo(i))}var AI=new gI("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 II(n)}catch(e){console.error(yI(e instanceof Error?e.message:String(e))),process.exit(1)}}),wh=AI;import{Command as TA}from"commander";import{McpServer as pA}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as mA}from"@modelcontextprotocol/sdk/server/stdio.js";import*as va from"path";import{z as me}from"zod";import js from"path";function bh(n,e,t,r,o){if(e.isError)return{};let i=e.content?.[0]?.text??"";if(!i)return{};let s;switch(n){case"check":s=DI(i);break;case"hover":s={hit:Mr(i)!=null};break;case"definition":case"declaration":s=vh(i,t,r,o,!0);break;case"references":s=TI(i);break;case"implementation":s=vh(i,t,r,o,!1);break;case"documentSymbol":s=RI(i);break;case"callHierarchy":s=xI(i,t,r,o);break;case"workspaceSymbol":s=NI(i,t);break;default:s={}}return s}function Eh(n){let e=Array.isArray(n.files)?n.files[0]:n.file;return typeof e!="string"||!e?void 0:js.extname(e).toLowerCase().replace(/^\./,"")||void 0}function Mr(n){let e=n.indexOf(": ");if(e<0)return;let t=n.slice(e+2).trim();if(!(!t||t==="no result"))try{return JSON.parse(t)}catch{return}}function DI(n){let e={total:0,error:0,warn:0,info:0},t=new Set,r=" => Diagnostic: ";for(let i of n.split(`
|
|
1282
|
+
`)){let s=i.indexOf(r);if(s<0)continue;let a;try{a=JSON.parse(i.slice(s+r.length))}catch{continue}if(Array.isArray(a))for(let c of a)c&&typeof c=="object"&&kI(c,e,t)}let o={diagTotal:e.total,diagError:e.error,diagWarn:e.warn,diagInfo:e.info};return t.size>0&&(o.rules=[...t]),o}function kI(n,e,t){e.total++;let r=n.severity;r===1?e.error++:r===2?e.warn++:(r===3||r===4)&&e.info++,typeof n.source=="string"&&t.add(n.source)}function TI(n){let e=Mr(n),t=Array.isArray(e)?e:[],r=new Set;for(let o of t){let i=o?.uri;typeof i=="string"&&r.add(i)}return{refTotal:t.length,fileCount:r.size}}function vh(n,e,t,r,o){let i=Mr(n);if(i==null)return{found:!1};let s=Array.isArray(i)?i:[i],a=s[0]?.uri;return o?{found:!0,sameFile:LI(a,e),sourceType:Ch(a,t,r)}:{implTotal:s.length,found:!0}}function RI(n){let e=Mr(n),t=Array.isArray(e)?e:[],r=0,o=new Map,i=s=>{for(let a of s){if(!a||typeof a!="object")continue;r++;let c=a.kind;typeof c=="number"&&o.set(c,(o.get(c)??0)+1);let l=a.children;Array.isArray(l)&&i(l)}};return i(t),{symbolTotal:r,kindDist:_l(o)}}function xI(n,e,t,r){let i=Mr(n)?.calls,s=Array.isArray(i)?i:[],a=e.direction,c=new Map;for(let l of s){if(!l||typeof l!="object")continue;let g=(a==="incoming"?l.from:l.to)?.uri,w=Ch(g,t,r);c.set(w,(c.get(w)??0)+1)}return{callsTotal:s.length,calleeSrcDist:_l(c)}}function NI(n,e){let t=Mr(n),r=Array.isArray(t)?t:[],o=new Map,i=0;for(let c of r){if(!c||typeof c!="object")continue;let l=c.kind;typeof l=="number"&&o.set(l,(o.get(l)??0)+1);let d=c.tags;(Array.isArray(d)&&d.includes(1)||c.deprecated===!0)&&i++}let s={resultTotal:r.length,kindDist:_l(o),deprecatedHit:i},a=e.query;return typeof a=="string"&&(s.queryLen=a.length),s}function Ph(n){if(typeof n!="string"||!n)return null;let e=n;return e.startsWith("file://")&&(e=e.slice(7),process.platform==="win32"&&e.startsWith("/")&&(e=e.slice(1))),e}function Ch(n,e,t){let r=Ph(n);return r?e&&Sh(r,e)?"user_project":t&&Sh(r,t)?"sdk":"system":"unknown"}function LI(n,e){let t=Ph(n),r=e.file;return!t||typeof r!="string"?!1:$s(t)===$s(r)}function $s(n){try{return js.resolve(n).replace(/\\/g,"/").toLowerCase()}catch{return n.replace(/\\/g,"/").toLowerCase()}}function Sh(n,e){let t=js.relative($s(e),$s(n));return t!==""&&!t.startsWith("..")&&!js.isAbsolute(t)}function _l(n){let e={};for(let[t,r]of n)e[String(t)]=r;return e}var Hs=class{constructor(e,t,r,o){this.telemetry=e;this.getAceServerPid=t;this.getProjectPath=r;this.getSdkPath=o}telemetry;getAceServerPid;getProjectPath;getSdkPath;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 o=>this.invokeTool(t.name,o,r)))}async invokeTool(e,t,r){if(f.info(`[telemetry] mcp tool call: ${e}`),!this.telemetry)return r(t);let o=Ie(process.memoryUsage().rss),i=await this.resolveLspMemory(),s=Date.now(),a=!0,c=null,l;try{l=await r(t)}catch(d){throw a=!1,c=d instanceof Error?d.code??d.name:"UnknownError",d}finally{await this.trackToolCall(e,t,l,s,o,i,a,c)}return l}async trackToolCall(e,t,r,o,i,s,a,c){if(!this.telemetry)return;let l=r?.isError===!0,d=r&&!l?bh(e,r,t,this.getProjectPath?.()??"",this.getSdkPath?.()??""):{},g=l?!1:a,w=l&&r?OI(r):c,b={event:E.McpToolCall,subAction:e,mcpMemory:i,lspMemory:s,fileExt:Eh(t),...d};typeof t.direction=="string"&&(b.direction=t.direction),await this.telemetry.track(b,{duration_ms:Date.now()-o,success:g,error_code:w})}async resolveLspMemory(){let e=this.getAceServerPid?.()??null;if(e===null)return"unknown";let t=await Pt(e);return t===null?"unknown":Ie(Number(t)*1024)}};function OI(n){let e=n.content.map(t=>t.text).join(`
|
|
1283
|
+
`);return/not ready|未初始化|初始中|稍后重试|please retry|retry \d+s|syncing|initializing|初始化失败|C\+\+ project initialization failed/i.test(e)?"NotReady":/No project detected|PROJECT_PATH|工程路径/i.test(e)?"NoProject":/Missing.*parameter|invalid parameters|Unknown feature|must be|不能同时|Must specify|无效/i.test(e)?"BadRequest":/Too many files|Maximum allowed/i.test(e)?"TooManyFiles":/不存在|does not exist|not exist|not found|No valid|不是 \.ets|not a supported|Unsupported/i.test(e)?"InvalidFile":"ToolError"}function Fl(n,e,t,r){return new Hs(n,e,t,r)}import*as qe from"fs";import*as Ee from"path";import{z as Hl}from"zod";function Ih(n){return"method"in n&&!("id"in n)}import{spawn as MI}from"child_process";import{EventEmitter as _I}from"events";import*as _r from"fs";import*as Ah from"path";var FI=50*1024*1024,pn=class extends _I{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;get pid(){return this.process?.pid??null}ensureDirectories(){let t=Ah.join(this.config.logPath,"lspLog");return _r.existsSync(t)||_r.mkdirSync(t,{recursive:!0}),_r.existsSync(this.config.indexingDataLocation)||_r.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){let r=this.ensureDirectories();m.info(`[LspClient] serverMaxSize=${t}MB`);let o=V(r),i=["--expose-gc",`--max-old-space-size=${t}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${o}`,this.config.serverPath,"--stdio",`--logger-path=${o}`,"--logger-level=TRACE"];m.info(`[LspClient] Starting process: node ${i.join(" ")}`);let s=process.execPath??"node";m.info(`[LspClient] nodePath: ${s}`),this.process=MI(s,i,{cwd:this.config.cwd||process.cwd(),stdio:["pipe","pipe","pipe"],windowsHide:!0}),this.bindProcessEvents(),await new Promise(a=>setTimeout(a,500)),m.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),m.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 o=r.toString("utf8").trim();m.error(`[LspClient] stderr: ${o}`),!this.isClosing&&t&&this.emit("error",new Error(`[LspClient] stderr: ${o}`))}),this.process.on("exit",r=>{m.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){m.warn("[LspClient] Cannot send message, stdin not writable");return}m.info(`[LspClient] send message: ${r}`);let o=this.buildLspMessage(t);this.process.stdin.write(o,"utf8")}send(t,r,o){let i={jsonrpc:"2.0",method:t,params:r};o!==void 0&&(i.id=o),this.sendRaw(JSON.stringify(i),t)}sendNotification(t,r){this.sendRaw(JSON.stringify({jsonrpc:"2.0",method:t,params:r}),t)}sendRequest(t,r,o){this.sendRaw(JSON.stringify({jsonrpc:"2.0",id:o,method:t,params:r}),t)}buildLspMessage(t){return`Content-Length: ${Buffer.from(t,"utf8").length}\r
|
|
1272
1284
|
\r
|
|
1273
1285
|
${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this.buffer.indexOf(`\r
|
|
1274
1286
|
\r
|
|
1275
|
-
`);if(r===-1)break;let i=this.buffer.slice(0,r).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!i){f.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(r+4);continue}let s=parseInt(i[1],10);if(!Number.isFinite(s)||s<0||s>VP){f.warn(`[LspClient] Invalid Content-Length: ${i[1]}, drop until next packet`),this.buffer=this.buffer.slice(r+4);continue}let 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(o=>{let i=!1,s=()=>{i||(i=!0,clearTimeout(c),r.off("exit",a),o())},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 o=0,i=!1,s=!1;for(let a=r;a<t.length;a++){let c=t[a];if(i){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(i=!1);continue}if(c==='"'){i=!0;continue}if(c==="{"||c==="["){o++;continue}if((c==="}"||c==="]")&&(o--,o===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 tn=class{callbacks=new Map;pending=new Map;timeouts=new Map;registerPending(e,t,r){return new Promise((o,i)=>{let s;r>0&&(s=setTimeout(()=>{this.pending.delete(e),this.timeouts.delete(e),i(new Error(`LSP request '${t}' (id=${e}) timeout after ${r}ms`))},r),this.timeouts.set(e,s)),this.pending.set(e,{resolve:o,reject:i,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 o=this.callbacks.get(e);if(o)try{o(t,r)}finally{this.callbacks.delete(e)}else{let i=[...this.callbacks.keys()].map(s=>String(s));f.info(`[RequestCallbackManager] emit: NO callback for key='${e}', registered keys=[${i.join(",")}]`)}}registerTimeout(e,t,r,o){let i=this.timeouts.get(e);i&&clearTimeout(i);let s=setTimeout(()=>{f.info(`[RequestCallbackManager] timeout, key=${e}, method=${t}`);try{o()}finally{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 ws=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var Sr=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 o of r)try{o(...t)}catch(i){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,i)}}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 Cm=20*1e3,GP=30*1e3,vs=class{client;nextRequestId=1;stopOnce=null;callbacks=new Sr;requestCallbacks=new tn;diagnosticMap=new Map;initProgressReset=null;constructor(e){this.client=new en(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{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,We);return this.client.sendRequest(y.INITIALIZE,e,t),r}sendInitializeResettable(e,t){let r=this.nextRequestId++,o=this.requestCallbacks.registerPending(r,y.INITIALIZE,0);return this.client.sendRequest(y.INITIALIZE,e,r),new Promise((i,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(),o.then(()=>{clearTimeout(a),this.initProgressReset=null,i()},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 ws(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=GP){let o=this.nextRequestId++,i=this.requestCallbacks.registerPending(o,e,r);return this.client.sendRequest(e,t,o),i}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 o=r instanceof Error?r.message:String(r);f.error(`[LSP] JSON parse error: ${o}, 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 o=new Error(`LSP error ${e.error.code}: ${e.error.message}`);this.requestCallbacks.rejectPending(r,o)}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 o=e.diagnostics||[];this.normalizeDiagnostics(o),r.set(o),this.finalizeDiagnostic(t,o)}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,Cm,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${Cm}ms, uri: ${e}`)})}finalizeDiagnostic(e,t,r){let o={uri:e,diagnostics:t,...r?{errorMessage:r}:{}};this.requestCallbacks.emit(e,y.PUBLISH_DIAGNOSTICS,o),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 o of t)this.finalizeDiagnostic(o,[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 Ss=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 ll(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)}},ll=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var zP={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"},qP={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={...zP,...qP},nn={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"},Im=new Set([1e3,2e3,3e3,3001]);function YP(n){if(!D(n))return!1;let e=n.textDocument;return D(e)&&typeof e.uri=="string"}function JP(n){return D(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function KP(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 Es=class n{client;isInitialized=!1;stopOnce=null;callbacks=new Sr;requestCallbacks=new tn;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;constructor(e){this.client=new en(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{f.info("[LegacyClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:k,method:T.EXIT,params:{}}),nn.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:k,method:T.INITIALIZED,params:{editors:e}}),nn.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:k,id:0,result:{}}),nn.EMPTY)}sendAsyncRequest(e,t,r,o){if(!D(t)){f.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!YP(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 i=t.textDocument.uri,s=nt(i);t.textDocument.uri=s,delete t.requestId;let a=o??e;f.info(`[LSP] sendAsyncRequest ${a}, filePath: ${i}`),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(!JP(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:T.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),T.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:T.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),nn.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let o=nt(t);e.textDocument.uri=o,f.info(`[LSP] onAsyncOpenFile, uri: ${o}`);let i=this.diagnosticMap.get(o);i||(i=new Ss(o),this.diagnosticMap.set(o,i),this.registerDiagnosticTimeout(o,T.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(i.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:k,method:T.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),nn.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=nt(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:k,method:T.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),nn.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=nt(e);f.info(`[LSP] didClose, uri: ${r}`);let o=this.diagnosticMap.get(r);if(!t&&(!o||o.isFromEditor)){f.info(`[LSP] closeFile skip, !diagnostic: ${!o}, isFromEditor: ${o?.isFromEditor}`);return}this.cleanupDiagnosticState(r),this.client.sendRaw(JSON.stringify({jsonrpc:k,method:T.DID_CLOSE,params:{textDocument:{uri:r}}}),nn.DID_CLOSE)}getDiagnosticMessage(e){let t=nt(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 o of t)this.finalizeDiagnostic(o,T.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:k,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: ${KP(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;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: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(!D(r)){f.warn("[LSP] aceProject/onAsyncHover message invalid");return}let o=r.requestId;if(typeof o!="number"){f.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(o,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 o=this.diagnosticMap.get(t);if(!o){f.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let i=e.diagnostics||[];i.length!==0?i.forEach(s=>{this.normalizeDiagnostic(s),o.addMessage(r,JSON.stringify(s))}):o.setReceivedType(r),o.hasReceivedAllTypes(Im)&&this.finalizeDiagnostic(t,T.PUBLISH_DIAGNOSTICS,o.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),i={1:"Error",2:"Warning",3:"Information",4:"Hint"}[r]||"Unknown";t.severityStr=i,t.severity=i}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),o=r?r.getMessages():[];this.finalizeDiagnostic(e,t,o,o.length>0?void 0:`received no diagnostics within ${n.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,r,o){let i={uri:e,diagnostics:r,...o?{errorMessage:o}:{}};this.requestCallbacks.emit(e,t,i),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 dl from"path";import*as Rs from"path";var bs=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var Ps=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var Cs=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var Is=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var As=class{typeSetting=new Cs;parameterNames=new Is};var Ds=class{constructor(e,t,r,o){this.rootUri=e;this.lspServerWorkspacePath=B(Rs.dirname(t)),this.indexingDataLocation=B(o),this.loggerPath=B(Rs.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new bs;gutterIconsSetting=new Ps;inlayHintsSetting=new As;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as Am from"path";var Ro=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(B(Am.join(e,"src","main","resources")))}};var XP="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${XP}`;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 Ro(e)):this.buildProfileParam=new Ro}toString(){return JSON.stringify(this)}};var br=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as be from"path";import*as Ir from"fs";var ks=class{modulePath;dependencies={};dynamicDependencies={}};var jn=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 Pr=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 Lt from"path";import*as Ts from"fs";var Cr=class{name="";version="";storePath="";dependencyPath="";path=""};var L={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:et.OH_PACKAGE_JSON5},ko=`${L.HVIGOR_CACHE}/${L.DEPENDENCY}`,$n=`${L.DEPENDENCY}${L.JSON5}`,BU=et.SYNC_OUTPUT_PATH;var To=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 o=this.PACKAGE_JSON_PARSER_MAP.get(e);return o||(o=new n(e,t,r),this.PACKAGE_JSON_PARSER_MAP.set(e,o)),o}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=Lt.join(this.dependencyPath,L.OH_PACKAGE_JSON5),r=_e(t);r&&(this.dependencies=this.getDependencyList(r,L.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(r,L.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(r,L.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 o=e[t];if(!D(o))return r;for(let[i,s]of Object.entries(o)){if(typeof s!="string"){f.error(`${i} package dependency value is not String ${t}`);continue}let a=new Cr;a.name=i;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(n.PARAMETER_PREFIX)||this.parseDependencyPath(i,c,a,!1),r.push(a)}return r}parseDependencyPath(e,t,r,o){if(!(!e||!t))try{let i=Lt.normalize(Lt.join(this.modulePath,L.OH_MODULES_PATH,e));if(!(t.startsWith(n.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){r.dependencyPath=i;return}if(r.path=t,this.fileNameForOhpm.test(t)){r.dependencyPath=i;return}let s=t;if(t.startsWith(n.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(n.FILE_DEPENDENCY_PREFIX.length)),Lt.isAbsolute(s)){r.dependencyPath=i;return}o||(i=Lt.resolve(this.modulePath,s)),Ts.existsSync(i)&&Ts.statSync(i).isDirectory()&&(r.dependencyPath=i)}catch(i){f.error("parser dependency path is invalid",i)}}};import*as Hn from"fs";import*as rn from"path";import ZP from"json5";var xs=class n{projectPath;static FILE_DEPENDENCY_PREFIX="file:";static MAX_LOCK_FILE_SIZE=20*1024*1024;static MAX_KEYS_PER_OBJECT=5e4;static MAX_JSON_DEPTH=50;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 rn.join(this.projectPath,L.OH_MODULES_PATH,L.OHPM_PATH,L.LOCK_JSON5_FILE)}static checkObjectDepth(e,t,r=0){if(r>t)return!1;if(typeof e!="object"||e===null)return!0;if(Array.isArray(e)){for(let o of e)if(!n.checkObjectDepth(o,t,r+1))return!1;return!0}for(let o in e)if(Object.prototype.hasOwnProperty.call(e,o)&&!n.checkObjectDepth(e[o],t,r+1))return!1;return!0}readLockFile(e){if(!Hn.existsSync(e))return f.error("lock file does not exist"),this.clearDependencies(),null;try{let t=Hn.statSync(e);if(t.size>n.MAX_LOCK_FILE_SIZE)return f.error(`lock file is too large (${t.size} bytes), read aborted`),this.clearDependencies(),null}catch(t){return f.error(`Failed to stat lock file: ${t instanceof Error?t.message:String(t)}`),this.clearDependencies(),null}try{let t=Hn.readFileSync(e,"utf8"),r=ZP.parse(t);return r?n.checkObjectDepth(r,n.MAX_JSON_DEPTH)?r:(f.error("lock.json5 nesting depth exceeds limit"),this.clearDependencies(),null):(f.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return f.error(`Error parsing lock.json5: ${t instanceof Error?t.message:String(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,L.KEY_DEPENDENCY,r),this.finalDevDependencies=this.getDependencyList(e,L.KEY_DEV_DEPENDENCY,r),this.finalDynamicDependencies=this.getDependencyList(e,L.KEY_DYNAMIC_DEPENDENCY,r)}parseStorePathMap(e){let t=new Map;if(!D(e))return t;let r=0;for(let o in e){if(!Object.prototype.hasOwnProperty.call(e,o))continue;let i=e[o];if(!D(i)){f.error(`${o} value is not json object`);continue}if(++r>n.MAX_KEYS_PER_OBJECT){f.warn("lock.json5 packages object exceeds key limit, truncating");break}typeof i.storePath=="string"&&t.set(o,i.storePath)}return t}getDependencyList(e,t,r){if(!D(e))return[];let o=0;for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;if(++o>n.MAX_KEYS_PER_OBJECT){f.warn("lock.json5 modules object exceeds key limit, truncating");break}let s=e[i];if(D(s)){let a=typeof s.name=="string"?s.name:"";if(r==="."&&a===""||a===r)return this.getFinalDependencyList(e,t,i)}}return[]}getFinalDependencyList(e,t,r){let o=e[r];if(!D(o))return f.error("moduleJsonObject is null"),[];let i=[],s=o[t];if(!D(s))return[];let a=0;for(let c in s){if(!Object.prototype.hasOwnProperty.call(s,c))continue;if(++a>n.MAX_KEYS_PER_OBJECT){f.warn("lock.json5 dependencies object exceeds key limit, truncating");break}let l=s[c];if(!D(l))continue;let d=typeof l.specifier=="string"?l.specifier:"",g=typeof l.version=="string"?l.version:"",w=new Cr;w.name=c,w.version=g.startsWith(n.FILE_DEPENDENCY_PREFIX)?g.substring(n.FILE_DEPENDENCY_PREFIX.length):g,this.parseDependencyPath(w,r,c,d,g);let P=`${c}@${g}`;this.storePathMap.has(P)&&(w.storePath=this.storePathMap.get(P)||""),i.push(w)}return i}parseDependencyPath(e,t,r,o,i){let s=rn.resolve(this.projectPath,rn.join(t,L.OH_MODULES_PATH,r));try{let a=i.startsWith(n.FILE_DEPENDENCY_PREFIX)?i.substring(n.FILE_DEPENDENCY_PREFIX.length):i,c=rn.isAbsolute(a)?a:rn.resolve(this.projectPath,a);Hn.existsSync(c)?(e.path=o,e.dependencyPath=this.fileNameForOhpm.test(i)?s:c):e.dependencyPath=s}catch(a){f.error("Invalid dependency path in lock.json5, msg:",a instanceof Error?a.message:String(a))}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};function Dm(n){return D(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var Un=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new Pt(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=be.join(t,ko),o=be.join(r,$n);if(!Ir.existsSync(r)||!Ir.existsSync(o)){let c="Dependency map or JSON not found";return f.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let i=new Pr(this.projectPath,".",this.projectPath);this.parseProjectDependencies(r,i),this.parseLockJson(i);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];Dm(l)&&(this.parseSingleModule(l,r,i,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,o=be.join(r,ko),i=be.join(o,$n);if(!Ir.existsSync(o)||!Ir.existsSync(i))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 Pr(this.projectPath,".",this.projectPath);this.parseProjectDependencies(o,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(!Dm(l))continue;let d=l.name;if(s&&!s.has(d))continue;let g=be.resolve(this.projectPath,l.srcPath),w=be.join(o,d),P=B(g),O=this.buildModuleDependencies(d,P,w,a);O.moduleName=d,t.push(O)}return t}parseSingleModule(e,t,r,o){let i=e.name,s=be.resolve(this.projectPath,e.srcPath),a=be.join(t,i),c=B(s),l=new Er(c),d=this.buildModuleDependencies(i,c,a,r);this.parseModuleJson5(c,l);let g=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=i,l.moduleType=i,l.packageName=i,l.moduleDependencies=d,l.moduleJsonParam=new br(g),o.push(l)}buildModuleDependencies(e,t,r,o){let i=new Pr(this.projectPath,e,t);To.getInstance(r,t,this.projectPath).parseDependency(i),this.parseLockJson(i),i.finalDependencies.push(...o.finalDependencies),i.finalDevDependencies.push(...o.finalDevDependencies),i.finalDynamicDependencies.push(...o.finalDynamicDependencies),i.finalDependencies.push(...i.finalDevDependencies);let a=new ks;return a.modulePath=t,this.toModuleDependencies(i,a),a}toModuleDependencies(e,t){let r={},o={};for(let i of e.finalDependencies)r[i.name]=new jn(i);for(let i of e.finalDynamicDependencies)o[i.name]=new jn(i);t.dependencies=r,t.dynamicDependencies=o}parseProjectDependencies(e,t){let r=be.join(e,L.OH_PACKAGE_JSON5);if(!Ir.existsSync(r))return;To.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 xs(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=be.join(e,"src","main","module.json5"),o=_e(r);if(!D(o)||!D(o.module))return;let i=o.module;t.permissions=this.parseRequestPermissions(i),t.deviceType=this.parseDeviceTypes(i)}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=be.join(e,"src","main","resources","base","profile","main_pages.json"),r=_e(t);return!D(r)||!Array.isArray(r.src)?[]:r.src.filter(o=>typeof o=="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=be.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=_e(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[o,i]=this.parseBySplit(r.compatibleSdkVersion);e.compatibleSdkVersion=o,e.compatibleSdkLevel=i}getBuildProfile(){if(this.buildProfileCache===void 0){let e=be.join(this.projectPath,"build-profile.json5");this.buildProfileCache=_e(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,e];let r=e.substring(0,t),o=e.substring(t+1,e.length-1);return[r,o]}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 Ns=class{constructor(e=[]){this.valueSet=e}valueSet};var Ar=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var Rm=(E=>(E[E.File=1]="File",E[E.Module=2]="Module",E[E.Namespace=3]="Namespace",E[E.Package=4]="Package",E[E.Class=5]="Class",E[E.Method=6]="Method",E[E.Property=7]="Property",E[E.Field=8]="Field",E[E.Constructor=9]="Constructor",E[E.Enum=10]="Enum",E[E.Interface=11]="Interface",E[E.Function=12]="Function",E[E.Variable=13]="Variable",E[E.Constant=14]="Constant",E[E.String=15]="String",E[E.Number=16]="Number",E[E.Boolean=17]="Boolean",E[E.Array=18]="Array",E[E.Object=19]="Object",E[E.Key=20]="Key",E[E.Null=21]="Null",E[E.EnumMember=22]="EnumMember",E[E.Struct=23]="Struct",E[E.Event=24]="Event",E[E.Operator=25]="Operator",E[E.TypeParameter=26]="TypeParameter",E))(Rm||{}),km=()=>Object.values(Rm).filter(n=>typeof n=="number");var Ls=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Os=class{applyEdit=!0;workspaceEdit=new Ls;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new Ns(km());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Ar;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Ms=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var _s=class{constructor(e=[]){this.valueSet=e}valueSet};var Fs=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var Tm=(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))(Tm||{}),xm=()=>Object.values(Tm).filter(n=>typeof n=="number");var js=class{completionItemKind=new _s(xm());completionItem=new Fs;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var $s=class{synchronization=new Ms;completion=new js;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 Ar;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var Hs=class{workspace=new Os;textDocument=new $s;notebookDocument=null;window=null;general=null;experimental=null};var Us=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};var Bs=class{constructor(e,t,r,o,i,s=!0){this.sdkPath=e;this.rootUri=r;this.nodeMaxOldSpaceSize=i;this.useStandardProtocol=s;this.serverPath=Xr(t,this.useStandardProtocol),this.logPath=Eu(),this.indexLogPath=o||this.logPath;let a={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath};this.messageHandle=this.useStandardProtocol?new vs(a):new Es(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 o=nt(this.rootUri),i=new Ds(o,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new Un(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),i.modules=s;let l=Oi(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(l),this.currentParams=new Us(o,i,new Hs),this.useStandardProtocol){let d=this.messageHandle;await d.sendInitializeResettable(this.currentParams,We),f.info("[LSP] initialize response received"),d.broadcastToClients({jsonrpc:k,method:y.ARKTS_INDEXING_PROGRESS,params:{}}),d.sendInitialized()}else await this.startLegacy(this.currentParams,e);r=!0}catch(o){this.lastStartErrorMessage=o instanceof Error?o.message:String(o),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((o,i)=>{r.onIndexingProgressUpdate(i),r.onInitializationCompleted(o)},"LSP initialization",We),r.sendInitialized(t)}withResettableTimeout(e,t,r){return new Promise((o,i)=>{let s,a=()=>{s=setTimeout(()=>{i(new Error(`${t} timeout after ${r}ms`))},r)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),o()},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 o=D(r)?r:{};f.info(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let i={jsonrpc:k,method:t,params:{uri:typeof o.uri=="string"?o.uri:e,diagnostics:Array.isArray(o.diagnostics)?o.diagnostics:[],...typeof o.errorMessage=="string"?{errorMessage:o.errorMessage}:{}}};this.onLspMessage(i)})}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 Un(this.rootUri,this.sdkPath),o=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,o);return this.applyModuleModelsUpdate(d),this.sendDidChangeConfiguration({moduleSet:d}),f.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${d.length}`),this.lastDepsOnlyForDiff=l,l}let i=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(i.length===0&&s.size===0)return f.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];f.info(`[LspServerProxy] Module-level deps changed, parsing: [${i.join(", ")}]`);let a=r.getDependenciesOnly(i);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(o=>[o.moduleName??"",o]));for(let o of e){let i=o.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(i,t,r),c=o.dependencies??{},l=o.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(d,g)=>{(o.dependencies??={})[d]=this.makeDeleteEntry(d,g)}),this.markAddAndDeleteInDeps(a,l,(d,g)=>{(o.dynamicDependencies??={})[d]=this.makeDeleteEntry(d,g)})}}getOldDepsForModule(e,t,r){let o=t.get(e),i=o?.moduleDependencies?.dependencies??{},s=o?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(i).length===0&&Object.keys(s).length===0){let a=r.get(e);a&&(i=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:i,oldDynamic:s}}markAddAndDeleteInDeps(e,t,r){for(let o of Object.keys(t))o in e||(t[o].type="add");for(let o of Object.keys(e))o in t||r(o,e[o])}makeDeleteEntry(e,t){return new jn({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 br([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let r=[];for(let o of e){let i=o.moduleName??"",s=t.get(i);s?(s.modulePath=o.modulePath,s.moduleDependencies=o):s=this.createMinimalModelFromDepsItem(o),r.push(s)}return r}mergeIncrementalDeps(e,t,r){let o=new Map(r.map(s=>[s.moduleName??"",s])),i=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=o.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,o.delete(a)),i.push(s)}for(let[,s]of o)i.push(this.createMinimalModelFromDepsItem(s));return i}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,r=Qn(dl.join(t,"default/openharmony/ets/build-tools/ets-loader")),o=Qn(dl.join(t,"default/openharmony/ets/api")),i=Qn(dl.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=o,s.hosSdkPath=i}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(!bm(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 Ot from"fs";import*as ke from"path";import{createHash as eC}from"crypto";import{EventEmitter as tC}from"events";var Ws=class extends tC{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 o of t)r.has(o)||this.watchFile(o);for(let o of r)t.has(o)||(this.unwatchFile(o),f.info(`[ConfigFileWatcher] Stopped watching: ${o}`));f.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!Ot.existsSync(t)){f.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Ot.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 o of t){let i=ke.resolve(this.projectRoot,o.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:i,relativePath:o.srcPath,timestamp:r,moduleName:o.name})}}emitModuleRemovedEvents(t,r){for(let o of t){let i=ke.resolve(this.projectRoot,o.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:i,relativePath:o.srcPath,timestamp:r,removedModuleName:o.name})}}emitModuleRenamedEvents(t,r){for(let o of t){let i=ke.resolve(this.projectRoot,o.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:i,relativePath:o.after.srcPath,timestamp:r,moduleName:o.after.name,removedModuleName:o.before.name})}}emitModuleMovedEvents(t,r){for(let o of t){let i=ke.resolve(this.projectRoot,o.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:i,relativePath:o.after.srcPath,timestamp:r,moduleName:o.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 o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(i);if(s===this.lastModulesSnapshot){f.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,i);this.lastModules=i,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,o)}computeModulesSnapshot(t){return t.map(o=>`${o.name}::${o.srcPath}`).sort().join("|")}diffModules(t,r){let o=this.buildModuleMatchState(r),i={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,o),this.matchRenamedModules(t,o,i),this.matchMovedModules(t,o,i),this.collectRemovedModules(t,o,i),this.collectAddedModules(r,o,i),i}buildModuleMatchState(t){let r=new Map,o=new Map;for(let i of t)r.set(i.srcPath,i),o.set(i.name,i);return{matchedOld:new Set,matchedNew:new Set,newBySrc:r,newByName:o}}matchExactModules(t,r){for(let o of t){let i=r.newBySrc.get(o.srcPath);i&&i.name===o.name&&(r.matchedOld.add(o),r.matchedNew.add(i))}}matchRenamedModules(t,r,o){for(let i of t){if(r.matchedOld.has(i))continue;let s=r.newBySrc.get(i.srcPath);s&&!r.matchedNew.has(s)&&s.name!==i.name&&(o.renamed.push({before:i,after:s}),r.matchedOld.add(i),r.matchedNew.add(s))}}matchMovedModules(t,r,o){for(let i of t){if(r.matchedOld.has(i))continue;let s=r.newByName.get(i.name);s&&!r.matchedNew.has(s)&&s.srcPath!==i.srcPath&&(o.moved.push({before:i,after:s}),r.matchedOld.add(i),r.matchedNew.add(s))}}collectRemovedModules(t,r,o){for(let i of t)r.matchedOld.has(i)||o.removed.push(i)}collectAddedModules(t,r,o){for(let i of t)r.matchedNew.has(i)||o.added.push(i)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let r=_e(t);if(typeof r!="object"||r===null)return[];let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;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=ke.join(this.projectRoot,L.OH_PACKAGE_JSON5);Ot.existsSync(r)&&t.push(r);let o=this.parseModulesFromBuildProfile();for(let i of o){let s=ke.resolve(this.projectRoot,i.srcPath),a=ke.join(s,L.OH_PACKAGE_JSON5);Ot.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return ke.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Ot.readFileSync(t,"utf-8");return eC("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 o=Ot.watch(t,i=>{i==="change"&&this.onFileChanged(t)});o.on("error",i=>{f.error(`[ConfigFileWatcher] Watch error for ${t}: ${i.message}`)}),this.watchers.set(t,o)}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 o=this.debounceTimers.get(t);o&&(clearTimeout(o),this.debounceTimers.delete(t))}onFileChanged(t){let r=this.debounceTimers.get(t);r&&clearTimeout(r);let o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.computeFileHash(t);if(!i){f.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===i){f.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,i),f.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:ke.basename(t),relativePath:ke.relative(this.projectRoot,t),timestamp:Date.now()};this.emit("configChanged",a)},this.debounceMs);this.debounceTimers.set(t,o)}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 on from"fs";import*as it from"path";import{createHash as nC}from"crypto";import{EventEmitter as rC}from"events";var Vs=class extends rC{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=it.join(t,ko)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!on.existsSync(this.depMapDir)){f.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=on.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 B(it.resolve(t))}onDirEvent(t,r){if(!r||typeof r!="string")return;let o=r.replace(/\\/g,"/"),i;if(o===L.OH_PACKAGE_JSON5)i="root-oh-package";else if(o===$n)i="dep-map-json";else{let a=o.match(/^([^/]+)\/oh-package\.json5$/);i=a?`module:${a[1]}`:""}if(!i)return;let s=it.join(this.depMapDir,r);on.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=it.join(this.depMapDir,L.OH_PACKAGE_JSON5),r=it.join(this.depMapDir,$n),o=this.parseModulesFromDepMap(),i=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...o.map(s=>({path:(b.assertModuleName(s.name),it.join(this.depMapDir,s.name,L.OH_PACKAGE_JSON5)),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of i){if(!on.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=it.join(this.depMapDir,$n);try{let r=_e(t);if(typeof r!="object"||r===null)return[];let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;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,o,i){for(let s of t)s.startsWith("module:")?(o.add(s.substring(7)),r.add("moduleDepsChanged")):s.startsWith("dep-added:")?(o.add(s.substring(10)),r.add("moduleAdded")):s.startsWith("dep-removed:")&&(i.add(s.substring(12)),r.add("moduleRemoved"))}processRenameEntries(t,r,o,i,s){for(let a of t)s.push(a.info),o.add(a.info.newName),i.add(a.info.oldName),r.add(a.kind)}buildAddedNamesSet(t,r){let o=new Set;for(let i of t)i.startsWith("dep-added:")&&o.add(i.substring(10));for(let i of r)o.add(i.info.newName);return o}emitIncrementalReload(t,r,o,i,s){f.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...r].join(",")}], removed=[${[...o].join(",")}], added=[${[...i].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...r],removedModuleNames:[...o],addedModuleNames:[...i],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 o=new Set,i=new Set,s=new Set,a=[];this.processTagsIntoSets(t,o,i,s),this.processRenameEntries(r,o,i,s,a);for(let l of i)s.delete(l);if(i.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(o,i,s,c,a)}normalizeSrcPath(t){return B(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let r=new Map(t.map(i=>[i.name,i])),o=new Map(t.map(i=>[this.normalizeSrcPath(i.srcPath),i]));return{byName:r,bySrcPath:o}}detectModuleRenames(t,r,o,i){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"}}),o.add(a.name),i.add(c.name);let l=(b.assertModuleName(a.name),it.join(this.depMapDir,a.name,L.OH_PACKAGE_JSON5));this.contentHashes.delete(this.canonicalPath(l)),f.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,r,o,i){for(let[s,a]of t){if(o.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"}}),o.add(s),i.add(s),f.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,r,o){for(let[i]of t)o.has(i)||r.has(i)||(this.pendingTags.push(`dep-added:${i}`),o.add(i))}detectRemovedModules(t,r,o){for(let[i]of t)if(!o.has(i)&&!r.has(i)){this.pendingTags.push(`dep-removed:${i}`),o.add(i);let s=(b.assertModuleName(i),it.join(this.depMapDir,i,L.OH_PACKAGE_JSON5));this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(o=>o.startsWith("dep-")),r=this.pendingRenames.map(o=>`${o.kind}(${o.info.oldName}\u2192${o.info.newName})`);f.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${r.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:r,bySrcPath:o}=this.buildModuleLookupMaps(this.lastModules),{byName:i,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(o,s,a,c),this.detectModuleMoves(r,i,a,c),this.detectAddedModules(i,r,c),this.detectRemovedModules(r,i,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let r=on.readFileSync(t,"utf-8");return nC("sha256").update(r).digest("hex")}catch{return null}}};import{spawn as oC}from"child_process";import*as ul from"fs";import*as xo from"path";var iC=["install","--all"];function sC(n){let e=n.replace(/sdk\/?$/i,"tools"),t=xo.join(e,"ohpm","bin","pm-cli.js");if(ul.existsSync(t))return t;let r=n.toLowerCase().endsWith("sdk")?xo.dirname(n):n;return t=xo.join(r,"ohpm","bin","pm-cli.js"),ul.existsSync(t)?t:null}async function aC(n,e,t,r){return new Promise(o=>{let i=oC(n,[e,...iC],{cwd:t,env:{...process.env,DEVECO_SDK_HOME:r},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),s="",a="";i.stdout?.on("data",c=>{s+=c.toString()}),i.stderr?.on("data",c=>{a+=c.toString()}),i.on("close",c=>{let l=[s,a].filter(Boolean).join(`
|
|
1287
|
+
`);if(r===-1)break;let i=this.buffer.slice(0,r).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!i){m.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(r+4);continue}let s=parseInt(i[1],10);if(!Number.isFinite(s)||s<0||s>FI){m.warn(`[LspClient] Invalid Content-Length: ${i[1]}, drop until next packet`),this.buffer=this.buffer.slice(r+4);continue}let 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){m.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(o=>{let i=!1,s=()=>{i||(i=!0,clearTimeout(c),r.off("exit",a),o())},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 o=0,i=!1,s=!1;for(let a=r;a<t.length;a++){let c=t[a];if(i){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(i=!1);continue}if(c==='"'){i=!0;continue}if(c==="{"||c==="["){o++;continue}if((c==="}"||c==="]")&&(o--,o===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 mn=class{callbacks=new Map;pending=new Map;timeouts=new Map;registerPending(e,t,r){return new Promise((o,i)=>{let s;r>0&&(s=setTimeout(()=>{this.pending.delete(e),this.timeouts.delete(e),i(new Error(`LSP request '${t}' (id=${e}) timeout after ${r}ms`))},r),this.timeouts.set(e,s)),this.pending.set(e,{resolve:o,reject:i,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){m.info(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let o=this.callbacks.get(e);if(o)try{o(t,r)}finally{this.callbacks.delete(e)}else{let i=[...this.callbacks.keys()].map(s=>String(s));m.info(`[RequestCallbackManager] emit: NO callback for key='${e}', registered keys=[${i.join(",")}]`)}}registerTimeout(e,t,r,o){let i=this.timeouts.get(e);i&&clearTimeout(i);let s=setTimeout(()=>{m.info(`[RequestCallbackManager] timeout, key=${e}, method=${t}`);try{o()}finally{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 Us=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var Fr=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 o of r)try{o(...t)}catch(i){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,i)}}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 T(n){return typeof n=="object"&&n!==null}var Dh=20*1e3,jI=30*1e3,Bs=class{client;nextRequestId=1;stopOnce=null;callbacks=new Fr;requestCallbacks=new mn;diagnosticMap=new Map;initProgressReset=null;get lspPid(){return this.client.pid}constructor(e){this.client=new pn(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{m.info("[ClientMessageHandle] Sending shutdown request"),this.client.sendRequest(y.SHUTDOWN,null,this.nextRequestId++),m.info("[ClientMessageHandle] Sending exit notification"),this.client.sendNotification(y.EXIT,null),m.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),m.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,Xe);return this.client.sendRequest(y.INITIALIZE,e,t),r}sendInitializeResettable(e,t){let r=this.nextRequestId++,o=this.requestCallbacks.registerPending(r,y.INITIALIZE,0);return this.client.sendRequest(y.INITIALIZE,e,r),new Promise((i,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(),o.then(()=>{clearTimeout(a),this.initProgressReset=null,i()},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 Us(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=jI){let o=this.nextRequestId++,i=this.requestCallbacks.registerPending(o,e,r);return this.client.sendRequest(e,t,o),i}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 o=r instanceof Error?r.message:String(r);m.error(`[LSP] JSON parse error: ${o}, raw: ${e}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotificationOrRequest(t):m.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 o=new Error(`LSP error ${e.error.code}: ${e.error.message}`);this.requestCallbacks.rejectPending(r,o)}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:m.info(`[LSP] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:m.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 o=e.diagnostics||[];this.normalizeDiagnostics(o),r.set(o),this.finalizeDiagnostic(t,o)}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){T(e)&&this.broadcastToClients({jsonrpc:R,method:y.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,y.PUBLISH_DIAGNOSTICS,Dh,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${Dh}ms, uri: ${e}`)})}finalizeDiagnostic(e,t,r){let o={uri:e,diagnostics:t,...r?{errorMessage:r}:{}};this.requestCallbacks.emit(e,y.PUBLISH_DIAGNOSTICS,o),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 o of t)this.finalizeDiagnostic(o,[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 Ws=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)){m.info(`[LegacyDiagnostic] addMessage: duplicate message=${r}`);return}this.uniqueMessages.add(r),this.messages.push(new jl(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)}},jl=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var $I={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"},HI={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"},x={...$I,...HI},fn={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"},kh=new Set([1e3,2e3,3e3,3001]);function UI(n){if(!T(n))return!1;let e=n.textDocument;return T(e)&&typeof e.uri=="string"}function BI(n){return T(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function WI(n){return T(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 Vs=class n{client;isInitialized=!1;stopOnce=null;callbacks=new Fr;requestCallbacks=new mn;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;get lspPid(){return this.client.pid}constructor(e){this.client=new pn(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{m.info("[LegacyClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:x.EXIT,params:{}}),fn.EXIT),m.info("[LegacyClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),m.info("[LegacyClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(x.BROADCAST),this.callbacks.register(x.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(x.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(x.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(x.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:x.INITIALIZED,params:{editors:e}}),fn.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:R,id:0,result:{}}),fn.EMPTY)}sendAsyncRequest(e,t,r,o){if(!T(t)){m.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!UI(t)){m.warn(`[LSP] sendAsyncRequest missing textDocument.uri, method=${e}, params=${JSON.stringify(t)}`);return}if(typeof r!="number"){m.warn(`[LSP] sendAsyncRequest invalid requestId, method=${e}, requestId=${String(r)}`);return}let i=t.textDocument.uri,s=dt(i);t.textDocument.uri=s,delete t.requestId;let a=o??e;m.info(`[LSP] sendAsyncRequest ${a}, filePath: ${i}`),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:e,params:{params:t,requestId:r}}),a)}onDidChangeWatchedFiles(e){if(m.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let r of e){if(!BI(r)){m.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:R,method:x.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),x.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!T(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){m.warn("[LSP] sendModuleDependencyUpdate, moduleSet is empty or null");return}let t=e.moduleSet;m.info(`[LSP] sending module dependency updated, count: ${t.length}`),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:x.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),fn.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let o=dt(t);e.textDocument.uri=o,m.info(`[LSP] onAsyncOpenFile, uri: ${o}`);let i=this.diagnosticMap.get(o);i||(i=new Ws(o),this.diagnosticMap.set(o,i),this.registerDiagnosticTimeout(o,x.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(i.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:x.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),fn.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=dt(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,x.PUBLISH_DIAGNOSTICS)),m.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:x.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),fn.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=dt(e);m.info(`[LSP] didClose, uri: ${r}`);let o=this.diagnosticMap.get(r);if(!t&&(!o||o.isFromEditor)){m.info(`[LSP] closeFile skip, !diagnostic: ${!o}, isFromEditor: ${o?.isFromEditor}`);return}this.cleanupDiagnosticState(r),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:x.DID_CLOSE,params:{textDocument:{uri:r}}}),fn.DID_CLOSE)}getDiagnosticMessage(e){let t=dt(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);m.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 o of t)this.finalizeDiagnostic(o,x.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:R,method:x.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 x.MODULE_INIT_FINISH:return m.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(x.MODULE_INIT_FINISH),this.callbacks.unregister(x.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case x.INDEXING_PROGRESS_UPDATE:return m.info(`[LSP] onIndexingProgressUpdate: ${WI(t.params)}`),this.callbacks.invoke(x.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case x.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case x.ON_PACKAGE_CHANGE_FINISH:m.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case x.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case x.ON_ASYNC_HOVER:this.handleAsyncResponse(t,x.HOVER);return;case x.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,x.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case x.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,x.REFERENCES);return;default:m.warn(`[LSP] handleLspMessage: no handler for notification, ignoring, method: ${e}, initialized: ${this.isInitialized}`)}}handleOnForceOpenFile(e){m.info("[LSP] handleLspMessage, receive onForceOpenFile");let t=e.params;T(t)&&T(t.result)&&typeof t.result.uri=="string"&&this.handleForceOpenFile(t.result.uri)}handlePublishDiagnostics(e){m.info("[LSP] handleLspMessage, receive publishDiagnostics");let t=e.params;t&&this.parseDiagnostics(t)}handlePackageChangeFinish(e){let t=e.params,r={jsonrpc:R,method:x.ON_PACKAGE_CHANGE_FINISH,params:[!1]};if(!t||!Array.isArray(t)){m.warn("[LSP] aceProject/onPackageChangeFinish params invalid"),this.broadcastToClients(r);return}if(!(t.length>0&&t[0]===!0)){m.warn("[LSP] aceProject/onPackageChangeFinish: package request failed"),this.broadcastToClients(r);return}m.info("[LSP] aceProject/onPackageChangeFinish: success"),this.broadcastToClients(e)}handleAsyncResponse(e,t){m.info(`[LSP] handleAsyncResponse\uFF0C method: ${t}`);let r=e.params;if(!T(r)){m.warn("[LSP] aceProject/onAsyncHover message invalid");return}let o=r.requestId;if(typeof o!="number"){m.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(o,t,r)}handleForceOpenFile(e){if(!e){m.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,x.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){m.info("[LSP] publishDiagnostics uri is null");return}let r=e.version??-1;if(r===-1)return;let o=this.diagnosticMap.get(t);if(!o){m.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let i=e.diagnostics||[];i.length!==0?i.forEach(s=>{this.normalizeDiagnostic(s),o.addMessage(r,JSON.stringify(s))}):o.setReceivedType(r),o.hasReceivedAllTypes(kh)&&this.finalizeDiagnostic(t,x.PUBLISH_DIAGNOSTICS,o.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),i={1:"Error",2:"Warning",3:"Information",4:"Hint"}[r]||"Unknown";t.severityStr=i,t.severity=i}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),o=r?r.getMessages():[];this.finalizeDiagnostic(e,t,o,o.length>0?void 0:`received no diagnostics within ${n.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,r,o){let i={uri:e,diagnostics:r,...o?{errorMessage:o}:{}};this.requestCallbacks.emit(e,t,i),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 $l from"path";import*as Xs from"path";var Gs=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var zs=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var qs=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var Js=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var Ys=class{typeSetting=new qs;parameterNames=new Js};var Ks=class{constructor(e,t,r,o){this.rootUri=e;this.lspServerWorkspacePath=V(Xs.dirname(t)),this.indexingDataLocation=V(o),this.loggerPath=V(Xs.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new Gs;gutterIconsSetting=new zs;inlayHintsSetting=new Ys;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as Th from"path";var qo=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(V(Th.join(e,"src","main","resources")))}};var VI="OS",jr=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${VI}`;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 qo(e)):this.buildProfileParam=new qo}toString(){return JSON.stringify(this)}};var $r=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as Te from"path";import*as Br from"fs";var Zs=class{modulePath;dependencies={};dynamicDependencies={}};var Zn=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 Hr=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 Qs from"fs";var Ur=class{name="";version="";storePath="";dependencyPath="";path=""};var M={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:lt.OH_PACKAGE_JSON5},Jo=`${M.HVIGOR_CACHE}/${M.DEPENDENCY}`,Qn=`${M.DEPENDENCY}${M.JSON5}`,yV=lt.SYNC_OUTPUT_PATH;var Yo=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 o=this.PACKAGE_JSON_PARSER_MAP.get(e);return o||(o=new n(e,t,r),this.PACKAGE_JSON_PARSER_MAP.set(e,o)),o}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,M.OH_PACKAGE_JSON5),r=Ge(t);r&&(this.dependencies=this.getDependencyList(r,M.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(r,M.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(r,M.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let r=[];if(!T(e))return r;let o=e[t];if(!T(o))return r;for(let[i,s]of Object.entries(o)){if(typeof s!="string"){m.error(`${i} package dependency value is not String ${t}`);continue}let a=new Ur;a.name=i;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(n.PARAMETER_PREFIX)||this.parseDependencyPath(i,c,a,!1),r.push(a)}return r}parseDependencyPath(e,t,r,o){if(!(!e||!t))try{let i=Bt.normalize(Bt.join(this.modulePath,M.OH_MODULES_PATH,e));if(!(t.startsWith(n.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){r.dependencyPath=i;return}if(r.path=t,this.fileNameForOhpm.test(t)){r.dependencyPath=i;return}let s=t;if(t.startsWith(n.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(n.FILE_DEPENDENCY_PREFIX.length)),Bt.isAbsolute(s)){r.dependencyPath=i;return}o||(i=Bt.resolve(this.modulePath,s)),Qs.existsSync(i)&&Qs.statSync(i).isDirectory()&&(r.dependencyPath=i)}catch(i){m.error("parser dependency path is invalid",i)}}};import*as er from"fs";import*as hn from"path";import GI from"json5";var ea=class n{projectPath;static FILE_DEPENDENCY_PREFIX="file:";static MAX_LOCK_FILE_SIZE=20*1024*1024;static MAX_KEYS_PER_OBJECT=5e4;static MAX_JSON_DEPTH=50;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 hn.join(this.projectPath,M.OH_MODULES_PATH,M.OHPM_PATH,M.LOCK_JSON5_FILE)}static checkObjectDepth(e,t,r=0){if(r>t)return!1;if(typeof e!="object"||e===null)return!0;if(Array.isArray(e)){for(let o of e)if(!n.checkObjectDepth(o,t,r+1))return!1;return!0}for(let o in e)if(Object.prototype.hasOwnProperty.call(e,o)&&!n.checkObjectDepth(e[o],t,r+1))return!1;return!0}readLockFile(e){if(!er.existsSync(e))return m.error("lock file does not exist"),this.clearDependencies(),null;try{let t=er.statSync(e);if(t.size>n.MAX_LOCK_FILE_SIZE)return m.error(`lock file is too large (${t.size} bytes), read aborted`),this.clearDependencies(),null}catch(t){return m.error(`Failed to stat lock file: ${t instanceof Error?t.message:String(t)}`),this.clearDependencies(),null}try{let t=er.readFileSync(e,"utf8"),r=GI.parse(t);return r?n.checkObjectDepth(r,n.MAX_JSON_DEPTH)?r:(m.error("lock.json5 nesting depth exceeds limit"),this.clearDependencies(),null):(m.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return m.error(`Error parsing lock.json5: ${t instanceof Error?t.message:String(t)}`),this.clearDependencies(),null}}validateLockFile(e){if(!T(e))return m.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return m.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let r=e.packages;return r?{valid:!0,modules:t,packages:r}:(m.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,r){this.storePathMap=t,this.finalDependencies=this.getDependencyList(e,M.KEY_DEPENDENCY,r),this.finalDevDependencies=this.getDependencyList(e,M.KEY_DEV_DEPENDENCY,r),this.finalDynamicDependencies=this.getDependencyList(e,M.KEY_DYNAMIC_DEPENDENCY,r)}parseStorePathMap(e){let t=new Map;if(!T(e))return t;let r=0;for(let o in e){if(!Object.prototype.hasOwnProperty.call(e,o))continue;let i=e[o];if(!T(i)){m.error(`${o} value is not json object`);continue}if(++r>n.MAX_KEYS_PER_OBJECT){m.warn("lock.json5 packages object exceeds key limit, truncating");break}typeof i.storePath=="string"&&t.set(o,i.storePath)}return t}getDependencyList(e,t,r){if(!T(e))return[];let o=0;for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;if(++o>n.MAX_KEYS_PER_OBJECT){m.warn("lock.json5 modules object exceeds key limit, truncating");break}let s=e[i];if(T(s)){let a=typeof s.name=="string"?s.name:"";if(r==="."&&a===""||a===r)return this.getFinalDependencyList(e,t,i)}}return[]}getFinalDependencyList(e,t,r){let o=e[r];if(!T(o))return m.error("moduleJsonObject is null"),[];let i=[],s=o[t];if(!T(s))return[];let a=0;for(let c in s){if(!Object.prototype.hasOwnProperty.call(s,c))continue;if(++a>n.MAX_KEYS_PER_OBJECT){m.warn("lock.json5 dependencies object exceeds key limit, truncating");break}let l=s[c];if(!T(l))continue;let d=typeof l.specifier=="string"?l.specifier:"",g=typeof l.version=="string"?l.version:"",w=new Ur;w.name=c,w.version=g.startsWith(n.FILE_DEPENDENCY_PREFIX)?g.substring(n.FILE_DEPENDENCY_PREFIX.length):g,this.parseDependencyPath(w,r,c,d,g);let b=`${c}@${g}`;this.storePathMap.has(b)&&(w.storePath=this.storePathMap.get(b)||""),i.push(w)}return i}parseDependencyPath(e,t,r,o,i){let s=hn.resolve(this.projectPath,hn.join(t,M.OH_MODULES_PATH,r));try{let a=i.startsWith(n.FILE_DEPENDENCY_PREFIX)?i.substring(n.FILE_DEPENDENCY_PREFIX.length):i,c=hn.isAbsolute(a)?a:hn.resolve(this.projectPath,a);er.existsSync(c)?(e.path=o,e.dependencyPath=this.fileNameForOhpm.test(i)?s:c):e.dependencyPath=s}catch(a){m.error("Invalid dependency path in lock.json5, msg:",a instanceof Error?a.message:String(a))}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};function Rh(n){return T(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var tr=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new Lt(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=Te.join(t,Jo),o=Te.join(r,Qn);if(!Br.existsSync(r)||!Br.existsSync(o)){let c="Dependency map or JSON not found";return m.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let i=new Hr(this.projectPath,".",this.projectPath);this.parseProjectDependencies(r,i),this.parseLockJson(i);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let c="No modules found in build-profile.json5";return m.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];Rh(l)&&(this.parseSingleModule(l,r,i,e),(c+1)%100===0&&m.info(`[Parser] getAllDependencyMap progress: ${c+1}/${s.length} (${Date.now()-a}ms)`))}return m.info(`[Parser] getAllDependencyMap parsed ${e.length} modules in ${Date.now()-a}ms`),{status:"OK"}}getDependenciesOnly(e){let t=[],r=this.projectPath,o=Te.join(r,Jo),i=Te.join(o,Qn);if(!Br.existsSync(o)||!Br.existsSync(i))return m.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 Hr(this.projectPath,".",this.projectPath);this.parseProjectDependencies(o,a),this.parseLockJson(a);let c=this.moduleInfoParse.getAllModuleInfo();if(c.length===0)return m.warn("[Parser] getAllDependencyMap failed: No modules found in build-profile.json5."),t;for(let l of c){if(!Rh(l))continue;let d=l.name;if(s&&!s.has(d))continue;let g=Te.resolve(this.projectPath,l.srcPath),w=Te.join(o,d),b=V(g),$=this.buildModuleDependencies(d,b,w,a);$.moduleName=d,t.push($)}return t}parseSingleModule(e,t,r,o){let i=e.name,s=Te.resolve(this.projectPath,e.srcPath),a=Te.join(t,i),c=V(s),l=new jr(c),d=this.buildModuleDependencies(i,c,a,r);this.parseModuleJson5(c,l);let g=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=i,l.moduleType=i,l.packageName=i,l.moduleDependencies=d,l.moduleJsonParam=new $r(g),o.push(l)}buildModuleDependencies(e,t,r,o){let i=new Hr(this.projectPath,e,t);Yo.getInstance(r,t,this.projectPath).parseDependency(i),this.parseLockJson(i),i.finalDependencies.push(...o.finalDependencies),i.finalDevDependencies.push(...o.finalDevDependencies),i.finalDynamicDependencies.push(...o.finalDynamicDependencies),i.finalDependencies.push(...i.finalDevDependencies);let a=new Zs;return a.modulePath=t,this.toModuleDependencies(i,a),a}toModuleDependencies(e,t){let r={},o={};for(let i of e.finalDependencies)r[i.name]=new Zn(i);for(let i of e.finalDynamicDependencies)o[i.name]=new Zn(i);t.dependencies=r,t.dynamicDependencies=o}parseProjectDependencies(e,t){let r=Te.join(e,M.OH_PACKAGE_JSON5);if(!Br.existsSync(r))return;Yo.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 ea(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=Te.join(e,"src","main","module.json5"),o=Ge(r);if(!T(o)||!T(o.module))return;let i=o.module;t.permissions=this.parseRequestPermissions(i),t.deviceType=this.parseDeviceTypes(i)}parseRequestPermissions(e){let t=[];if(T(e)&&Array.isArray(e.requestPermissions))for(let r of e.requestPermissions)T(r)&&typeof r.name=="string"&&t.push(r.name);return t}parseMainPages(e){let t=Te.join(e,"src","main","resources","base","profile","main_pages.json"),r=Ge(t);return!T(r)||!Array.isArray(r.src)?[]:r.src.filter(o=>typeof o=="string")}parseSdkJson(e){let t=this.getSdkPkg();if(!(!T(t)||!T(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=Te.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=Ge(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!T(t)||!T(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let r=t.app.products[0];if(!T(r)||typeof r.compatibleSdkVersion!="string")return;let[o,i]=this.parseBySplit(r.compatibleSdkVersion);e.compatibleSdkVersion=o,e.compatibleSdkLevel=i}getBuildProfile(){if(this.buildProfileCache===void 0){let e=Te.join(this.projectPath,"build-profile.json5");this.buildProfileCache=Ge(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,e];let r=e.substring(0,t),o=e.substring(t+1,e.length-1);return[r,o]}parseDeviceTypes(e){return!T(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 ta=class{constructor(e=[]){this.valueSet=e}valueSet};var Wr=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var xh=(A=>(A[A.File=1]="File",A[A.Module=2]="Module",A[A.Namespace=3]="Namespace",A[A.Package=4]="Package",A[A.Class=5]="Class",A[A.Method=6]="Method",A[A.Property=7]="Property",A[A.Field=8]="Field",A[A.Constructor=9]="Constructor",A[A.Enum=10]="Enum",A[A.Interface=11]="Interface",A[A.Function=12]="Function",A[A.Variable=13]="Variable",A[A.Constant=14]="Constant",A[A.String=15]="String",A[A.Number=16]="Number",A[A.Boolean=17]="Boolean",A[A.Array=18]="Array",A[A.Object=19]="Object",A[A.Key=20]="Key",A[A.Null=21]="Null",A[A.EnumMember=22]="EnumMember",A[A.Struct=23]="Struct",A[A.Event=24]="Event",A[A.Operator=25]="Operator",A[A.TypeParameter=26]="TypeParameter",A))(xh||{}),Nh=()=>Object.values(xh).filter(n=>typeof n=="number");var na=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var ra=class{applyEdit=!0;workspaceEdit=new na;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new ta(Nh());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Wr;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var oa=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var ia=class{constructor(e=[]){this.valueSet=e}valueSet};var sa=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var Lh=(D=>(D[D.Text=1]="Text",D[D.Method=2]="Method",D[D.Function=3]="Function",D[D.Constructor=4]="Constructor",D[D.Field=5]="Field",D[D.Variable=6]="Variable",D[D.Class=7]="Class",D[D.Interface=8]="Interface",D[D.Module=9]="Module",D[D.Property=10]="Property",D[D.Unit=11]="Unit",D[D.Value=12]="Value",D[D.Enum=13]="Enum",D[D.Keyword=14]="Keyword",D[D.Snippet=15]="Snippet",D[D.Color=16]="Color",D[D.File=17]="File",D[D.Reference=18]="Reference",D[D.Folder=19]="Folder",D[D.EnumMember=20]="EnumMember",D[D.Constant=21]="Constant",D[D.Struct=22]="Struct",D[D.Event=23]="Event",D[D.Operator=24]="Operator",D[D.TypeParameter=25]="TypeParameter",D))(Lh||{}),Oh=()=>Object.values(Lh).filter(n=>typeof n=="number");var aa=class{completionItemKind=new ia(Oh());completionItem=new sa;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var ca=class{synchronization=new oa;completion=new aa;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 Wr;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var la=class{workspace=new ra;textDocument=new ca;notebookDocument=null;window=null;general=null;experimental=null};var da=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};var ua=class{constructor(e,t,r,o,i,s=!0){this.sdkPath=e;this.rootUri=r;this.nodeMaxOldSpaceSize=i;this.useStandardProtocol=s;this.serverPath=fo(t,this.useStandardProtocol),this.logPath=gp(),this.indexLogPath=o||this.logPath;let a={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath};this.messageHandle=this.useStandardProtocol?new Bs(a):new Vs(a),this.messageHandle.setBroadcastToClients(c=>this.onLspMessage(c))}sdkPath;rootUri;nodeMaxOldSpaceSize;useStandardProtocol;messageHandle;get stdHandle(){return this.messageHandle}get legacyHandle(){return this.messageHandle}get lspPid(){return this.messageHandle.lspPid}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{m.info(`serverPath: ${this.serverPath}`),m.info(`rootUri: ${this.rootUri}`),m.info(`sdkPath: ${this.sdkPath}`),m.info(`logPath: ${this.logPath}`);let o=dt(this.rootUri),i=new Ks(o,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new tr(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),i.modules=s;let l=Qi(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(l),this.currentParams=new da(o,i,new la),this.useStandardProtocol){let d=this.messageHandle;await d.sendInitializeResettable(this.currentParams,Xe),m.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(o){this.lastStartErrorMessage=o instanceof Error?o.message:String(o),m.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((o,i)=>{r.onIndexingProgressUpdate(i),r.onInitializationCompleted(o)},"LSP initialization",Xe),r.sendInitialized(t)}withResettableTimeout(e,t,r){return new Promise((o,i)=>{let s,a=()=>{s=setTimeout(()=>{i(new Error(`${t} timeout after ${r}ms`))},r)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),o()},c)})}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){m.info(`[LSP] registerDiagnosticCallback uri='${e}', useStandardProtocol=${this.useStandardProtocol}`),this.messageHandle.registerRequestCallback(e,(t,r)=>{let o=T(r)?r:{};m.info(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let i={jsonrpc:R,method:t,params:{uri:typeof o.uri=="string"?o.uri:e,diagnostics:Array.isArray(o.diagnostics)?o.diagnostics:[],...typeof o.errorMessage=="string"?{errorMessage:o.errorMessage}:{}}};this.onLspMessage(i)})}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 tr(this.rootUri,this.sdkPath),o=this.getModuleModelsByName();if(t){m.info("[LspServerProxy] Project-level oh-package changed, parsing all modules' dependencies");let l=r.getDependenciesOnly();this.markDependencyTypesIncremental(l);let d=this.mergeDepsOnlyIntoModuleList(l,o);return this.applyModuleModelsUpdate(d),this.sendDidChangeConfiguration({moduleSet:d}),m.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${d.length}`),this.lastDepsOnlyForDiff=l,l}let i=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(i.length===0&&s.size===0)return m.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];m.info(`[LspServerProxy] Module-level deps changed, parsing: [${i.join(", ")}]`);let a=r.getDependenciesOnly(i);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),this.sendDidChangeConfiguration({moduleSet:c}),m.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(o=>[o.moduleName??"",o]));for(let o of e){let i=o.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(i,t,r),c=o.dependencies??{},l=o.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(d,g)=>{(o.dependencies??={})[d]=this.makeDeleteEntry(d,g)}),this.markAddAndDeleteInDeps(a,l,(d,g)=>{(o.dynamicDependencies??={})[d]=this.makeDeleteEntry(d,g)})}}getOldDepsForModule(e,t,r){let o=t.get(e),i=o?.moduleDependencies?.dependencies??{},s=o?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(i).length===0&&Object.keys(s).length===0){let a=r.get(e);a&&(i=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:i,oldDynamic:s}}markAddAndDeleteInDeps(e,t,r){for(let o of Object.keys(t))o in e||(t[o].type="add");for(let o of Object.keys(e))o in t||r(o,e[o])}makeDeleteEntry(e,t){return new Zn({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new jr(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new $r([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let r=[];for(let o of e){let i=o.moduleName??"",s=t.get(i);s?(s.modulePath=o.modulePath,s.moduleDependencies=o):s=this.createMinimalModelFromDepsItem(o),r.push(s)}return r}mergeIncrementalDeps(e,t,r){let o=new Map(r.map(s=>[s.moduleName??"",s])),i=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=o.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,o.delete(a)),i.push(s)}for(let[,s]of o)i.push(this.createMinimalModelFromDepsItem(s));return i}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,r=hr($l.join(t,"default/openharmony/ets/build-tools/ets-loader")),o=hr($l.join(t,"default/openharmony/ets/api")),i=hr($l.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=o,s.hosSdkPath=i}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:m.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!Ih(e)){m.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:m.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){m.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"){m.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"){m.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 Wt from"fs";import*as Fe from"path";import{createHash as qI}from"crypto";import{EventEmitter as JI}from"events";var pa=class extends JI{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 o of t)r.has(o)||this.watchFile(o);for(let o of r)t.has(o)||(this.unwatchFile(o),m.info(`[ConfigFileWatcher] Stopped watching: ${o}`));m.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!Wt.existsSync(t)){m.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Wt.watch(t,r=>{r==="change"&&this.onBuildProfileChanged()}),this.buildProfileWatcher.on("error",r=>{m.error(`[ConfigFileWatcher] build-profile.json5 watch error: ${r.message}`)}),m.info(`[ConfigFileWatcher] Watching module registry: ${t}`)}catch(r){m.error(`[ConfigFileWatcher] Failed to watch build-profile.json5: ${r instanceof Error?r.message:String(r)}`)}}emitModuleAddedEvents(t,r){for(let o of t){let i=Fe.resolve(this.projectRoot,o.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:i,relativePath:o.srcPath,timestamp:r,moduleName:o.name})}}emitModuleRemovedEvents(t,r){for(let o of t){let i=Fe.resolve(this.projectRoot,o.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:i,relativePath:o.srcPath,timestamp:r,removedModuleName:o.name})}}emitModuleRenamedEvents(t,r){for(let o of t){let i=Fe.resolve(this.projectRoot,o.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:i,relativePath:o.after.srcPath,timestamp:r,moduleName:o.after.name,removedModuleName:o.before.name})}}emitModuleMovedEvents(t,r){for(let o of t){let i=Fe.resolve(this.projectRoot,o.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:i,relativePath:o.after.srcPath,timestamp:r,moduleName:o.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 o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(i);if(s===this.lastModulesSnapshot){m.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,i);this.lastModules=i,this.lastModulesSnapshot=s,m.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,o)}computeModulesSnapshot(t){return t.map(o=>`${o.name}::${o.srcPath}`).sort().join("|")}diffModules(t,r){let o=this.buildModuleMatchState(r),i={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,o),this.matchRenamedModules(t,o,i),this.matchMovedModules(t,o,i),this.collectRemovedModules(t,o,i),this.collectAddedModules(r,o,i),i}buildModuleMatchState(t){let r=new Map,o=new Map;for(let i of t)r.set(i.srcPath,i),o.set(i.name,i);return{matchedOld:new Set,matchedNew:new Set,newBySrc:r,newByName:o}}matchExactModules(t,r){for(let o of t){let i=r.newBySrc.get(o.srcPath);i&&i.name===o.name&&(r.matchedOld.add(o),r.matchedNew.add(i))}}matchRenamedModules(t,r,o){for(let i of t){if(r.matchedOld.has(i))continue;let s=r.newBySrc.get(i.srcPath);s&&!r.matchedNew.has(s)&&s.name!==i.name&&(o.renamed.push({before:i,after:s}),r.matchedOld.add(i),r.matchedNew.add(s))}}matchMovedModules(t,r,o){for(let i of t){if(r.matchedOld.has(i))continue;let s=r.newByName.get(i.name);s&&!r.matchedNew.has(s)&&s.srcPath!==i.srcPath&&(o.moved.push({before:i,after:s}),r.matchedOld.add(i),r.matchedNew.add(s))}}collectRemovedModules(t,r,o){for(let i of t)r.matchedOld.has(i)||o.removed.push(i)}collectAddedModules(t,r,o){for(let i of t)r.matchedNew.has(i)||o.added.push(i)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let r=Ge(t);if(typeof r!="object"||r===null)return[];let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return m.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${r instanceof Error?r.message:String(r)}`),[]}}collectWatchTargets(){let t=[],r=Fe.join(this.projectRoot,M.OH_PACKAGE_JSON5);Wt.existsSync(r)&&t.push(r);let o=this.parseModulesFromBuildProfile();for(let i of o){let s=Fe.resolve(this.projectRoot,i.srcPath),a=Fe.join(s,M.OH_PACKAGE_JSON5);Wt.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return Fe.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Wt.readFileSync(t,"utf-8");return qI("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 o=Wt.watch(t,i=>{i==="change"&&this.onFileChanged(t)});o.on("error",i=>{m.error(`[ConfigFileWatcher] Watch error for ${t}: ${i.message}`)}),this.watchers.set(t,o)}catch(r){m.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 o=this.debounceTimers.get(t);o&&(clearTimeout(o),this.debounceTimers.delete(t))}onFileChanged(t){let r=this.debounceTimers.get(t);r&&clearTimeout(r);let o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.computeFileHash(t);if(!i){m.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===i){m.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,i),m.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:Fe.basename(t),relativePath:Fe.relative(this.projectRoot,t),timestamp:Date.now()};this.emit("configChanged",a)},this.debounceMs);this.debounceTimers.set(t,o)}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(),m.info("[ConfigFileWatcher] All watchers stopped")}};import*as gn from"fs";import*as mt from"path";import{createHash as YI}from"crypto";import{EventEmitter as KI}from"events";var ma=class extends KI{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=mt.join(t,Jo)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!gn.existsSync(this.depMapDir)){m.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=gn.watch(this.depMapDir,{recursive:!0},(t,r)=>this.onDirEvent(t,r)),this.dirWatcher.on("error",t=>{m.error(`[DependencyMapWatcher] Directory watch error for ${this.depMapDir}: ${t.message}`)})}catch(t){m.error(`[DependencyMapWatcher] Failed to watch directory ${this.depMapDir}: ${t instanceof Error?t.message:String(t)}`);return}this.pollInterval=setInterval(()=>this.scanAllCacheFiles(),2500),m.info(`[DependencyMapWatcher] Started, watching directory (recursive): ${this.depMapDir}, modules: [${this.lastModules.map(t=>t.name).join(", ")}]`)}canonicalPath(t){return V(mt.resolve(t))}onDirEvent(t,r){if(!r||typeof r!="string")return;let o=r.replace(/\\/g,"/"),i;if(o===M.OH_PACKAGE_JSON5)i="root-oh-package";else if(o===Qn)i="dep-map-json";else{let a=o.match(/^([^/]+)\/oh-package\.json5$/);i=a?`module:${a[1]}`:""}if(!i)return;let s=mt.join(this.depMapDir,r);gn.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,m.info("[DependencyMapWatcher] All watchers stopped")}scheduleDebouncedFullScan(){this.fullScanTimer&&clearTimeout(this.fullScanTimer),this.fullScanTimer=setTimeout(()=>{this.fullScanTimer=null,this.scanAllCacheFiles()},this.debounceMs)}scanAllCacheFiles(){let t=mt.join(this.depMapDir,M.OH_PACKAGE_JSON5),r=mt.join(this.depMapDir,Qn),o=this.parseModulesFromDepMap(),i=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...o.map(s=>({path:(C.assertModuleName(s.name),mt.join(this.depMapDir,s.name,M.OH_PACKAGE_JSON5)),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of i){if(!gn.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),m.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=mt.join(this.depMapDir,Qn);try{let r=Ge(t);if(typeof r!="object"||r===null)return[];let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return m.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,o,i){for(let s of t)s.startsWith("module:")?(o.add(s.substring(7)),r.add("moduleDepsChanged")):s.startsWith("dep-added:")?(o.add(s.substring(10)),r.add("moduleAdded")):s.startsWith("dep-removed:")&&(i.add(s.substring(12)),r.add("moduleRemoved"))}processRenameEntries(t,r,o,i,s){for(let a of t)s.push(a.info),o.add(a.info.newName),i.add(a.info.oldName),r.add(a.kind)}buildAddedNamesSet(t,r){let o=new Set;for(let i of t)i.startsWith("dep-added:")&&o.add(i.substring(10));for(let i of r)o.add(i.info.newName);return o}emitIncrementalReload(t,r,o,i,s){m.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...r].join(",")}], removed=[${[...o].join(",")}], added=[${[...i].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...r],removedModuleNames:[...o],addedModuleNames:[...i],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:r}=this.collectPendingState();if(t.length===0&&r.length===0)return;if(m.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${r.length}`),t.includes("root-oh-package")){m.info("[DependencyMapWatcher] Root oh-package.json5 in batch \u2192 full reload"),this.emit("reload",{fullReload:!0,kinds:["projectDepsChanged"]});return}let o=new Set,i=new Set,s=new Set,a=[];this.processTagsIntoSets(t,o,i,s),this.processRenameEntries(r,o,i,s,a);for(let l of i)s.delete(l);if(i.size===0&&s.size===0&&a.length===0){m.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,r);this.emitIncrementalReload(o,i,s,c,a)}normalizeSrcPath(t){return V(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let r=new Map(t.map(i=>[i.name,i])),o=new Map(t.map(i=>[this.normalizeSrcPath(i.srcPath),i]));return{byName:r,bySrcPath:o}}detectModuleRenames(t,r,o,i){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"}}),o.add(a.name),i.add(c.name);let l=(C.assertModuleName(a.name),mt.join(this.depMapDir,a.name,M.OH_PACKAGE_JSON5));this.contentHashes.delete(this.canonicalPath(l)),m.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,r,o,i){for(let[s,a]of t){if(o.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"}}),o.add(s),i.add(s),m.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,r,o){for(let[i]of t)o.has(i)||r.has(i)||(this.pendingTags.push(`dep-added:${i}`),o.add(i))}detectRemovedModules(t,r,o){for(let[i]of t)if(!o.has(i)&&!r.has(i)){this.pendingTags.push(`dep-removed:${i}`),o.add(i);let s=(C.assertModuleName(i),mt.join(this.depMapDir,i,M.OH_PACKAGE_JSON5));this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(o=>o.startsWith("dep-")),r=this.pendingRenames.map(o=>`${o.kind}(${o.info.oldName}\u2192${o.info.newName})`);m.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${r.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:r,bySrcPath:o}=this.buildModuleLookupMaps(this.lastModules),{byName:i,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(o,s,a,c),this.detectModuleMoves(r,i,a,c),this.detectAddedModules(i,r,c),this.detectRemovedModules(r,i,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let r=gn.readFileSync(t,"utf-8");return YI("sha256").update(r).digest("hex")}catch{return null}}};import{spawn as XI}from"child_process";var ZI=["install","--all"];async function QI(n,e,t,r){return new Promise(o=>{let i=XI(n,[e,...ZI],{cwd:t,env:{...process.env,DEVECO_SDK_HOME:r},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),s="",a="";i.stdout?.on("data",c=>{s+=c.toString()}),i.stderr?.on("data",c=>{a+=c.toString()}),i.on("close",c=>{let l=[s,a].filter(Boolean).join(`
|
|
1276
1288
|
`);o({exitCode:c??-1,output:l})}),i.on("error",c=>{let l=[s,a].filter(Boolean).join(`
|
|
1277
1289
|
`);o({exitCode:-1,output:l+`
|
|
1278
|
-
`+c.message})})})}function cC(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>f.info("[ohpm] %s",e))}async function Nm(n,e){try{let t=ki(e);if(!t)return f.error("node \u8DEF\u5F84\u4E0D\u5B58\u5728"),!1;let r=sC(e);if(!r)return f.error("ohpm (pm-cli.js) \u4E0D\u5B58\u5728"),!1;let{exitCode:o,output:i}=await aC(t,r,n,e);return cC(i),o===0?(f.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(f.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",o),f.error("ohpm \u8F93\u51FA: %s",i),!1)}catch(t){return f.error("ohpm \u5B89\u88C5\u5F02\u5E38",t),!1}}var Lm={UNINITIALIZED:-32099,UNKNOWN:-32e3},No=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,Lm.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,Lm.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var Dr=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;try{this.startConfigWatcher(),this.startLspProxy(e)}catch(t){throw f.error(`[ArktsLspManager] start() synchronous failure: ${t instanceof Error?t.message:String(t)}`),t}}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 o=r?.skipHvigorSync===!0,i=await wi(e,async()=>await Nm(e,t)?o?(f.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await Au(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 i.acquired?i.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 Bs(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?No.uninitialized(t):No.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 Ws(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new Vs(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(o=>({modulePath:o.modulePath??"",dependencies:o.dependencies??{},dynamicDependencies:o.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 lC=10080*60*1e3,dC=7200*60*1e3,uC=120*1e3,Rr=class n{manager=null;initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;sdkPath;arktsLangServerPath;nodeMaxOldSpaceSize;onConfigChangedCallback=null;useStandardProtocol=!0;diagnosticWaiters=new Map;static FEATURE_METHOD_MAP={hover:y.HOVER,definition:y.DEFINITION,declaration:y.DECLARATION,references:y.REFERENCES,implementation:y.IMPLEMENTATION,completion:y.COMPLETION,signatureHelp:y.SIGNATURE_HELP,documentHighlight:y.DOCUMENT_HIGHLIGHT};constructor(e,t,r,o){this.projectPath=e,this.sdkPath=t,this.arktsLangServerPath=r,this.nodeMaxOldSpaceSize=o}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:pl.object({files:pl.array(pl.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 o=ce(e),{logPath:i,indexPath:s}=this.getLogAndIndexPath(o);setImmediate(()=>{Za(s,lC,"[ArkTS-Check]"),Za(i,dC,"[ArkTS-Check]")}),Li(i);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 Dr({sdkPath:l,arktsLangServerPath:t,workspaceRoot:B(o),indexLogPath:s,nodeMaxOldSpaceSize:c,useStandardProtocol:r}),this.manager.setOnMessage(d=>this.handleLspMessage(d)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((d,g)=>{this.initResolve=d,this.initReject=g,this.armInitTimer(We),this.manager.start([]).catch(w=>{let P=w instanceof Error?w:new Error(String(w));this.failInit(P)})})}resolveProjectAndDeveco(){let e=bt(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=Ai(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=Dn(e),o=await je.promises.readFile(e,"utf8"),s=`deveco.apptool.${he.extname(e).replace(/^\./,"")||"plaintext"}`;return t.useStandardProtocol?this.checkFileStandard(t,r,o,s):this.checkFileLegacy(t,e,r,o,s)}async checkFileStandard(e,t,r,o){h.debug(`textDocument/didOpen uri=${t} content_len=${r.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:r,languageId:o,version:1}});try{h.debug(`textDocument/diagnostic uri=${t}`);let i=await e.diagnostic({textDocument:{uri:t}});return pC(i)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:t}})}}async checkFileLegacy(e,t,r,o,i){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"))},uC);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:d})});h.debug(`textDocument/didOpen(legacy) uri=${r} content_len=${o.length}`),e.onAsyncOpenFile({textDocument:{uri:r,text:o,languageId:i,version:o.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=[],o=this.collectValidFiles(e.files,t);return o.length===0?{content:[{type:"text",text:t.length>0?t.join(`
|
|
1279
|
-
`):"\u6CA1\u6709\u6709\u6548\u7684 .ets \u6587\u4EF6"}],isError:!0}:(await this.runDiagnosticsForFiles(o,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 o=n.FEATURE_METHOD_MAP[e];if(!o)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};
|
|
1280
|
-
`).length,i=await this.withOpenFile(t,async a=>this.manager.sendFeatureRequest(y.INLAY_HINT,{textDocument:{uri:a},range:{start:{line:0,character:0},end:{line:o,character:0}}}));return{content:[{type:"text",text:i==null?"inlayHint: no result":`inlayHint: ${JSON.stringify(i,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 i=>this.manager.sendFeatureRequest(y.DOCUMENT_LINK,{textDocument:{uri:i}}));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
|
|
1290
|
+
`+c.message})})})}function eA(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>m.info("[ohpm] %s",e))}async function Mh(n,e,t,r){try{if(!t)return m.error("node \u8DEF\u5F84\u4E0D\u5B58\u5728"),!1;if(!r)return m.error("ohpm (pm-cli.js) \u4E0D\u5B58\u5728"),!1;let{exitCode:o,output:i}=await QI(t,r,n,e);return eA(i),o===0?(m.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(m.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",o),m.error("ohpm \u8F93\u51FA: %s",i),!1)}catch(o){return m.error("ohpm \u5B89\u88C5\u5F02\u5E38",o),!1}}var _h={UNINITIALIZED:-32099,UNKNOWN:-32e3},Ko=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,_h.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,_h.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var Vr=class{config;lspProxy=null;configWatcher=null;depMapWatcher=null;isInitialized=!1;lastEditorOpenFiles=[];onMessage=()=>{};onConfigChanged=null;disposeOnce=null;get aceServerPid(){return this.lspProxy?.lspPid??null}constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}async start(e=[]){this.lastEditorOpenFiles=e;try{this.startConfigWatcher(),this.startLspProxy(e)}catch(t){throw m.error(`[ArktsLspManager] start() synchronous failure: ${t instanceof Error?t.message:String(t)}`),t}}sendNotification(e){if(!this.lspProxy){m.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){m.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,o,i,s){if(m.info("[ArktsLspManager] Received arkts/syncProject"),!e||!t)return m.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let a=s?.skipHvigorSync===!0,c=await Ji(e,async()=>await Mh(e,t,r??"",o??"")?a?(m.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await bp(e,t,r??"",i??"")?(m.info("[ArktsLspManager] syncProject completed successfully"),{status:"success"}):(m.error("[ArktsLspManager] syncProject failed"),{status:"failed",reason:"hvigor sync failed"}):(m.error("[ArktsLspManager] ohpm install failed"),{status:"failed",reason:"ohpm install failed"}));return c.acquired?c.result:(m.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){m.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){m.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){m.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e){let t=new ua(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)m.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:R,method:y.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();m.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?Ko.uninitialized(t):Ko.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||(m.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 pa(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new ma(this.config.workspaceRoot),this.depMapWatcher.on("reload",e=>{if(!this.lspProxy){m.warn("[ArktsLspManager] LspServerProxy not initialized, skip reload");return}let r=this.lspProxy.reloadDependenciesOnly(e).map(o=>({modulePath:o.modulePath??"",dependencies:o.dependencies??{},dynamicDependencies:o.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){m.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),this.onConfigChanged?.()}};var tA=10080*60*1e3,nA=7200*60*1e3,rA=120*1e3,Gr=class n{manager=null;get aceServerPid(){return this.manager?.aceServerPid??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,o){this.projectPath=e,this.sdkPath=t,this.arktsLangServerPath=r,this.nodeMaxOldSpaceSize=o}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:Hl.object({files:Hl.array(Hl.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 o=fe(e),{logPath:i,indexPath:s}=this.getLogAndIndexPath(o);setImmediate(()=>{uc(s,tA,"[ArkTS-Check]"),uc(i,nA,"[ArkTS-Check]")}),Zi(i);let a=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,c=Number.isNaN(a)?void 0:a;f.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${c??"undefined \u2192 dynamic formula applies"}`);let l=this.sdkPath;f.info(`[ArktsCheck] sdkPath=${l}, arktsLangServerPath=${t}, useStandardProtocol=${r}`),this.manager=new Vr({sdkPath:l,arktsLangServerPath:t,workspaceRoot:V(o),indexLogPath:s,nodeMaxOldSpaceSize:c,useStandardProtocol:r}),this.manager.setOnMessage(d=>this.handleLspMessage(d)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((d,g)=>{this.initResolve=d,this.initReject=g,this.armInitTimer(Xe),this.manager.start([]).catch(w=>{let b=w instanceof Error?w:new Error(String(w));this.failInit(b)})})}resolveProjectAndDeveco(){let e=xt(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=xi(t);return f.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=Fn(e),o=await qe.promises.readFile(e,"utf8"),s=`deveco.apptool.${Ee.extname(e).replace(/^\./,"")||"plaintext"}`;return t.useStandardProtocol?this.checkFileStandard(t,r,o,s):this.checkFileLegacy(t,e,r,o,s)}async checkFileStandard(e,t,r,o){f.debug(`textDocument/didOpen uri=${t} content_len=${r.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:r,languageId:o,version:1}});try{f.debug(`textDocument/diagnostic uri=${t}`);let i=await e.diagnostic({textDocument:{uri:t}});return oA(i)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:t}})}}async checkFileLegacy(e,t,r,o,i){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"))},rA);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:d})});f.debug(`textDocument/didOpen(legacy) uri=${r} content_len=${o.length}`),e.onAsyncOpenFile({textDocument:{uri:r,text:o,languageId:i,version:o.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=[],o=this.collectValidFiles(e.files,t);return o.length===0?{content:[{type:"text",text:t.length>0?t.join(`
|
|
1291
|
+
`):"\u6CA1\u6709\u6709\u6548\u7684 .ets \u6587\u4EF6"}],isError:!0}:(await this.runDiagnosticsForFiles(o,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 o=n.FEATURE_METHOD_MAP[e];if(!o)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};f.info(`handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let i=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(o,c)});return{content:[{type:"text",text:i==null?`${e}: no result`:`${e}: ${JSON.stringify(i,null,2)}`}]}}catch(i){let s=i instanceof Error?i.message:String(i);return f.error(`handleLspFeature ${e} failed: ${s}`),{content:[{type:"text",text:`${e} failed: ${s}`}],isError:!0}}}async handleWorkspaceSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();f.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 f.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 f.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};f.info(`handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async i=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:i}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){let o=r instanceof Error?r.message:String(r);return f.error(`handleDocumentSymbol failed: ${o}`),{content:[{type:"text",text:`documentSymbol failed: ${o}`}],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};f.info(`handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,async i=>{let s=await this.manager.sendFeatureRequest(y.PREPARE_CALL_HIERARCHY,{textDocument:{uri:i},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 g=await this.manager.sendFeatureRequest(c,{item:d});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 o=r instanceof Error?r.message:String(r);return f.error(`handleCallHierarchy failed: ${o}`),{content:[{type:"text",text:`callHierarchy failed: ${o}`}],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};f.info(`handleCodeAction: file=${t} line=${e.line} char=${e.character}`);try{let r=await this.withOpenFile(t,async i=>{let s={line:e.line,character:e.character};return this.manager.sendFeatureRequest(y.CODE_ACTION,{textDocument:{uri:i},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};f.info(`handleRename: file=${t} line=${e.line} char=${e.character} newName=${e.newName}`);try{let r=await this.withOpenFile(t,async i=>{let s={line:e.line,character:e.character};if(await this.manager.sendFeatureRequest(y.PREPARE_RENAME,{textDocument:{uri:i},position:s})==null)throw new Error("Symbol at this position cannot be renamed");return this.manager.sendFeatureRequest(y.RENAME,{textDocument:{uri:i},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};f.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();f.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,o){return this.withOpenFile(e,async i=>{let s=await this.manager.sendFeatureRequest(y.PREPARE_TYPE_HIERARCHY,{textDocument:{uri:i},position:{line:t,character:r}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],results:[]};let c=o==="supertypes"?y.SUPERTYPES:y.SUBTYPES,l=await this.collectHierarchyItems(c,a);return{items:a,results:l}})}async collectHierarchyItems(e,t){let r=[];for(let o of t){let i=await this.manager.sendFeatureRequest(e,{item:o});Array.isArray(i)?r.push(...i):i&&r.push(i)}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 o=(await qe.promises.readFile(t,"utf8")).split(`
|
|
1292
|
+
`).length,i=await this.withOpenFile(t,async a=>this.manager.sendFeatureRequest(y.INLAY_HINT,{textDocument:{uri:a},range:{start:{line:0,character:0},end:{line:o,character:0}}}));return{content:[{type:"text",text:i==null?"inlayHint: no result":`inlayHint: ${JSON.stringify(i,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 i=>this.manager.sendFeatureRequest(y.DOCUMENT_LINK,{textDocument:{uri:i}}));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 f.error(`${e} failed: ${r}`),{content:[{type:"text",text:`${e} failed: ${r}`}],isError:!0}}async withOpenFile(e,t){let r=Fn(e),o=await qe.promises.readFile(e,"utf8"),s=`deveco.apptool.${Ee.extname(e).replace(/^\./,"")||"plaintext"}`;f.debug(`withOpenFile didOpen uri=${r} len=${o.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:r,text:o,languageId:s,version:o.length}});try{return await t(r)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:r},isManual:!1})}}resolveSingleFile(e){let t=Ee.isAbsolute(e)?e:Ee.join(this.projectPath,e);return!qe.existsSync(t)||!qe.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=Ee.resolve(this.projectPath),o=[];for(let i of e){let s=Ee.resolve(Ee.isAbsolute(i)?i:Ee.join(r,i));if(!qe.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${i}`);continue}if(!qe.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${i}`);continue}if(!s.endsWith(".ets")){t.push(`\u4E0D\u662F .ets \u6587\u4EF6: ${i}`);continue}o.push(s)}return o}async runDiagnosticsForFiles(e,t,r){for(let o of e){await ku(500);try{let i=await this.checkFile(o);r.push(iA(o,i))}catch(i){t.push(`${o} => wait for diagnostics failed: ${i.message}`)}}}formatCallResult(e,t){let r=[];e.length>0&&r.push(e.join(`
|
|
1281
1293
|
`)),t.length>0&&r.push(t.join(`
|
|
1282
1294
|
`));let o=r.join(`
|
|
1283
|
-
`).trim(),i=e.length>0;return!i&&t.length===0&&(o="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:o}],isError:i}}async shutdown(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(t){
|
|
1284
|
-
`):"No valid C/C++ files"}],isError:!0};for(let c of o){await
|
|
1295
|
+
`).trim(),i=e.length>0;return!i&&t.length===0&&(o="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:o}],isError:i}}async shutdown(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(t){f.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(Xe),f.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{f.info("Received arkts/initialized");let o=this.initResolve;this.clearInitHandlers(),o?.();break}case"arkts/initializationFailed":{let i=t.params?.message??"unknown";f.error(`LSP initialization failed: ${i}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${i}`));break}case"workspace/didChangeConfiguration":f.info("Received workspace/didChangeConfiguration, sync deferred to next check");break;default:break}}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let 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"){f.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),r.resolve({errorMessage:e.errorMessage});return}let o=e.diagnostics,i=Array.isArray(o)?o.length:0;f.debug(`diagnostics received uri=${t} count=${i}`),r.resolve(Array.isArray(o)?o:[])}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}getLogAndIndexPath(e){try{let t=Ee.join(Yt(),"ArkTSCheck"),r=Ee.join(t,"mapping-config.properties"),o=Tu(e,r),i=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=Ee.join(t,"lsp-log",String(o),i),a=Ee.join(t,"lsp-index",String(o));return qe.mkdirSync(s,{recursive:!0}),qe.mkdirSync(a,{recursive:!0}),{logPath:fe(s),indexPath:fe(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function oA(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 iA(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 yn from"fs";import*as nr from"path";import{z as Ul}from"zod";function zr(){return{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}}function fa(n,e){let t=e instanceof Error?e.message:String(e);return f.error(`[CppLsp] ${n} failed: ${t}`),{content:[{type:"text",text:`${n} failed: ${t}`}],isError:!0}}var sA=500,qr=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:Ul.object({files:Ul.array(Ul.string()).describe('List of C/C++ file paths to check, format: ["file1.cpp","file2.hpp",...]')})}}async handleCall(e){if(!this.manager.ready)return zr();let t=[],r=[],o=this.collectValidFiles(e.files,t);if(o.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
|
|
1296
|
+
`):"No valid C/C++ files"}],isError:!0};for(let c of o){await cA(sA);try{let l=await this.checkFile(c);r.push(aA(c,l))}catch(l){t.push(`${c} => wait for diagnostics failed: ${l.message}`)}}let i=t.length>0,s=[];t.length>0&&s.push(t.join(`
|
|
1285
1297
|
`)),r.length>0&&s.push(r.join(`
|
|
1286
1298
|
`));let a=s.join(`
|
|
1287
|
-
`).trim();return!i&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:i}}async checkFile(e){let t=Dn(e),r=await sn.promises.readFile(e,"utf8"),o=Ri(e),i=this.manager.registerDiagnosticCallback(t);this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:t,text:r,languageId:o,version:r.length}}});try{return await i}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:t}}})}}collectValidFiles(e,t){let r=Bn.resolve(this.manager.projectRoot),o=[];for(let i of e){let s=Bn.resolve(Bn.isAbsolute(i)?i:Bn.join(r,i));if(!sn.existsSync(s)){t.push(`File does not exist: ${i}`);continue}if(!sn.statSync(s).isFile()){t.push(`Not a regular file: ${i}`);continue}if(!An(s)){t.push(`Not a supported C/C++ file: ${i}`);continue}try{o.push(sn.realpathSync(s))}catch{o.push(s)}}return o}};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)}`}function gC(n){return new Promise(e=>setTimeout(e,n))}import*as Nr from"fs";import*as zs from"path";var xr=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 kr();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 o=n.FEATURE_METHOD_MAP[e];if(!o)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 i=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(o,c)});return{content:[{type:"text",text:i==null?`${e}: no result`:`${e}: ${JSON.stringify(i,null,2)}`}]}}catch(i){return Gs(e,i)}}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 kr();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 i=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:i}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){return Gs("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return kr();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,i=>this.fetchCallHierarchyResult(i,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return Gs("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}}),o=this.normalizeCallHierarchyItems(r);if(o.length===0)return{items:[],calls:[]};let i=await this.collectIncomingCalls(o);return{items:o,calls:i}}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=Dn(e),o=await Nr.promises.readFile(e,"utf8"),i=Ri(e);h.info(`[ClangdLspTool] withOpenFile didOpen uri=${r} langId=${i} len=${o.length}`),this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:r,text:o,languageId:i,version:o.length}}});try{return await t(r)}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:r}}})}}resolveSingleFile(e){let t=zs.isAbsolute(e)?e:zs.join(this.manager.projectRoot,e);return!Nr.existsSync(t)||!Nr.statSync(t).isFile()||!An(t)?null:t}};import{spawn as yC}from"child_process";import*as Ys from"fs";import*as Om from"path";var wC=30*1e3,vC=30*1e3,qs=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new tn;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 en(r),this.client.on("message",i=>this.handleRawMessage(i)),this.client.on("error",i=>this.handleError(i)),this.client.attachProcess(this.clangdProcess,{stderrAsError:!1});let o=this.buildInitializeParams();await this.sendLspRequest(y.INITIALIZE,o,We),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,o)=>{let i=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&o(new Error(`Wait for clangd diagnostics timeout, uri: ${t}`))},vC);this.diagnosticWaiters.set(t,{resolve:r,reject:o,timer:i})})}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=${B(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];f.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=yC(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=Qn(this.config.workspaceRoot),t=nt(e),r=Om.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.3.0-Test.15"},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=wC){if(!this.client)return Promise.reject(new Error("[ClangdLspProxy] client not ready"));let o=this.nextRequestId++,i=this.requestCallbacks.registerPending(o,e,r);return this.client.sendRequest(e,t,o),i}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let o=r instanceof Error?r.message:String(r);f.error(`[ClangdLspProxy] JSON parse error: ${o}, 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&&e.error!==null){let o=e.error;f.warn(`[ClangdLspProxy] LSP error id=${r}: code=${o.code??-1} message=${o.message??"unknown"}`),this.requestCallbacks.rejectPending(r,new Error(`LSP error ${o.code??-1}: ${o.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 o=Array.isArray(e.diagnostics)?e.diagnostics:[],i=o.length;f.info(`[ClangdLspProxy] diagnostics received uri=${t} count=${i}`),r.resolve(o)}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{Ys.existsSync(this.config.logPath)||Ys.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)),nt(r)}}catch{}return e}};import*as Lo from"path";import*as ml from"fs";var Oo=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(kn(e).length===0)return f.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let o=await wi(e,async()=>{try{return await ku(e,t),f.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(i){let s=i instanceof Error?i.message:String(i);return f.error(`[ClangdLspManager] compileNative failed: ${s}`),{status:"failed",reason:s}}});return o.acquired?o.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(We);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=bt(this.config.workspaceRoot);this.resolvedRoot=e?ce(e):ce(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();Li(t);let r=Di(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 o=Lo.dirname(Zr(this.resolvedRoot));try{ml.mkdirSync(o,{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: ${o}`);let i=new qs({clangdPath:r,workspaceRoot:this.resolvedRoot,compileCommandsDir:o,logPath:t});i.setOnMessage(s=>this.handleLspMessage(s)),this.proxy=i,i.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 o=this.initReject;this.clearInitHandlers(),o?.(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 o=t.params;switch(r){case y.DID_OPEN:this.proxy.sendDidOpen(o);break;case y.DID_CHANGE:this.proxy.sendDidChange(o);break;case y.DID_CLOSE:this.proxy.sendDidClose(o);break;default:this.proxy.sendNotification(r,o)}}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=Lo.join(Vt(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=Lo.join(e,"lsp-log",t);return ml.mkdirSync(r,{recursive:!0}),ce(r)}catch{return"auto"}}};function Mm(n){let e=Si(n);return f.info(`[SyncGuard] ${e.reason}`),e}var yl=(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))(yl||{}),_m=(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))(_m||{}),yt=3,hl=600*1e3,gl=100,Js=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,Rn(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 o=bt(t);h.info(`Constructor: findHarmonyProject('${t}') => ${o??"null"}`),this.config.projectPath=o??void 0;let i=Ii(this.config.devecoPath);this.sdkPath=i.sdkPath,this.arktsLangServerPath=i.arktsLangServerPath,h.info(`Constructor: sdkPath='${this.sdkPath}', arktsLangServerPath='${this.arktsLangServerPath??"(null)"}'`),this.server=new SC({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=cl(),this.standardProtocolAvailable=this.detectStandardProtocolAvailable(),this.registerTools()}registerTools(){this.registerCheckTool(),this.registerLspFeatureTools(),this.registerRestartTool()}registerRestartTool(){this.toolRouter.add({name:"restart",description:"Restart the MCP server in-place: re-sync the project and re-initialize the LSP, without dropping the client connection. Use to recover from a stuck/ERROR state after fixing the root cause, instead of exiting and reopening the agent. Use target to restart one side only (arkts/cpp) or both (all, default). Caution: if initialization fails again after a restart, the cause is likely a persistent project/SDK configuration issue\u2014do not call restart repeatedly; ask the user to fix the project first.",inputSchema:ae.object({target:ae.enum(["arkts","cpp","all"]).default("all").describe('Which backend to restart: "arkts" (ArkTS ace-server), "cpp" (C++ clangd), or "all" (both, default).')})},async e=>this.handleRestartCall(e))}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:ae.object({files:ae.array(ae.string()).min(1).describe("List of source file paths to check, relative to the project root (absolute paths within the project are also accepted). 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=ae.object({file:ae.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets (ArkTS) and C/C++ extensions."),line:ae.number().describe("Line number (0-based)"),character:ae.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:r,feature:o}of this.getPositionFeatures())this.toolRouter.add({name:t,description:r,inputSchema:e},async i=>this.handleLspFeatureCall(o,i));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:ae.object({query:ae.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:ae.object({file:ae.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). 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:ae.object({file:ae.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets and C/C++ extensions."),line:ae.number().describe("Line number (0-based)"),character:ae.number().describe("Character offset in the line (0-based)"),direction:ae.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=Ai(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 o=[];for(let i of e){let s=b.isPathContainedWithSymlink(i,t);s.contained||(h.warn(`Containment check failed: ${s.reason}`),o.push(s.reason))}return o.length>0?{content:[{type:"text",text:o.join(`
|
|
1288
|
-
`)}],isError:!0}:null}let r=e.filter(o=>
|
|
1289
|
-
`)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(d=>typeof d=="string"):[];if(t.length===0)return
|
|
1299
|
+
`).trim();return!i&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:i}}async checkFile(e){let t=Fn(e),r=await yn.promises.readFile(e,"utf8"),o=Ni(e),i=this.manager.registerDiagnosticCallback(t);this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:t,text:r,languageId:o,version:r.length}}});try{return await i}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:t}}})}}collectValidFiles(e,t){let r=nr.resolve(this.manager.projectRoot),o=[];for(let i of e){let s=nr.resolve(nr.isAbsolute(i)?i:nr.join(r,i));if(!yn.existsSync(s)){t.push(`File does not exist: ${i}`);continue}if(!yn.statSync(s).isFile()){t.push(`Not a regular file: ${i}`);continue}if(!_n(s)){t.push(`Not a supported C/C++ file: ${i}`);continue}try{o.push(yn.realpathSync(s))}catch{o.push(s)}}return o}};function aA(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 cA(n){return new Promise(e=>setTimeout(e,n))}import*as Yr from"fs";import*as ha from"path";var Jr=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 zr();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 o=n.FEATURE_METHOD_MAP[e];if(!o)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};f.info(`[ClangdLspTool] handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let i=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(o,c)});return{content:[{type:"text",text:i==null?`${e}: no result`:`${e}: ${JSON.stringify(i,null,2)}`}]}}catch(i){return fa(e,i)}}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 f.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return zr();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};f.info(`[ClangdLspTool] handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async i=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:i}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){return fa("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return zr();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};f.info(`[ClangdLspTool] handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,i=>this.fetchCallHierarchyResult(i,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return fa("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}}),o=this.normalizeCallHierarchyItems(r);if(o.length===0)return{items:[],calls:[]};let i=await this.collectIncomingCalls(o);return{items:o,calls:i}}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),o=await Yr.promises.readFile(e,"utf8"),i=Ni(e);f.info(`[ClangdLspTool] withOpenFile didOpen uri=${r} langId=${i} len=${o.length}`),this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:r,text:o,languageId:i,version:o.length}}});try{return await t(r)}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:r}}})}}resolveSingleFile(e){let t=ha.isAbsolute(e)?e:ha.join(this.manager.projectRoot,e);return!Yr.existsSync(t)||!Yr.statSync(t).isFile()||!_n(t)?null:t}};import{spawn as lA}from"child_process";import*as ya from"fs";import*as Fh from"path";var dA=30*1e3,uA=30*1e3,ga=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new mn;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{m.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),m.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),m.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 pn(r),this.client.on("message",i=>this.handleRawMessage(i)),this.client.on("error",i=>this.handleError(i)),this.client.attachProcess(this.clangdProcess,{stderrAsError:!1});let o=this.buildInitializeParams();await this.sendLspRequest(y.INITIALIZE,o,Xe),m.info("[ClangdLspProxy] initialize response received"),this.sendNotification(y.INITIALIZED,{}),t=!0}catch(r){this.lastStartErrorMessage=r instanceof Error?r.message:String(r),m.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){m.warn("[ClangdLspProxy] sendNotification before ready, dropped");return}this.client.sendNotification(e,t)}registerDiagnosticCallback(e){let t=this.normalizeClangdUri(e);if(this.diagnosticWaiters.has(t)){m.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,o)=>{let i=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&o(new Error(`Wait for clangd diagnostics timeout, uri: ${t}`))},uA);this.diagnosticWaiters.set(t,{resolve:r,reject:o,timer:i})})}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=>{m.warn(`[ClangdLspProxy] shutdown request failed: ${e}`)}),this.sendNotification(y.EXIT,null),await this.client.waitForExitOrTimeout(300)}catch(e){m.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=${V(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];m.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=lA(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=hr(this.config.workspaceRoot),t=dt(e),r=Fh.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.3.0-Test.16"},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=dA){if(!this.client)return Promise.reject(new Error("[ClangdLspProxy] client not ready"));let o=this.nextRequestId++,i=this.requestCallbacks.registerPending(o,e,r);return this.client.sendRequest(e,t,o),i}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let o=r instanceof Error?r.message:String(r);m.error(`[ClangdLspProxy] JSON parse error: ${o}, raw: ${e.slice(0,200)}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotification(t):m.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&&e.error!==null){let o=e.error;m.warn(`[ClangdLspProxy] LSP error id=${r}: code=${o.code??-1} message=${o.message??"unknown"}`),this.requestCallbacks.rejectPending(r,new Error(`LSP error ${o.code??-1}: ${o.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:m.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:m.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 o=Array.isArray(e.diagnostics)?e.diagnostics:[],i=o.length;m.info(`[ClangdLspProxy] diagnostics received uri=${t} count=${i}`),r.resolve(o)}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{ya.existsSync(this.config.logPath)||ya.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)),dt(r)}}catch{}return e}};import*as Xo from"path";import*as Bl from"fs";var Zo=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){m.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,r,o){if(m.info("[ClangdLspManager] Received cpp/syncProject"),!e||!t)return m.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};if(Bn(e).length===0)return m.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let s=await Ji(e,async()=>{try{return await Cp(e,t,r,o),m.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(a){let c=a instanceof Error?a.message:String(a);return m.error(`[ClangdLspManager] compileNative failed: ${c}`),{status:"failed",reason:c}}});return s.acquired?s.result:(m.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(Xe);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=xt(this.config.workspaceRoot);this.resolvedRoot=e?fe(e):fe(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();Zi(t);let r=this.config.clangdPath;if(!r){let s="clangd not found (install DevEco Studio / CLT)";m.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let o=Xo.dirname(ho(this.resolvedRoot));try{Bl.mkdirSync(o,{recursive:!0})}catch(s){m.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${s}`)}m.info(`[ClangdLspManager] clangdPath: ${r}`),m.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),m.info(`[ClangdLspManager] compileCommandsDir: ${o}`);let i=new ga({clangdPath:r,workspaceRoot:this.resolvedRoot,compileCommandsDir:o,logPath:t});i.setOnMessage(s=>this.handleLspMessage(s)),this.proxy=i,i.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,m.info("[ClangdLspManager] clangd initialized");let r=this.initResolve;this.clearInitHandlers(),r?.()}else{let r=t??this.proxy?.consumeStartErrorMessage()??"unknown error";m.error(`[ClangdLspManager] clangd initialization failed: ${r}`),this.isInitialized=!1,this.proxy=null;let o=this.initReject;this.clearInitHandlers(),o?.(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){m.warn("[ClangdLspManager] dispatchNotification: missing method");return}let o=t.params;switch(r){case y.DID_OPEN:this.proxy.sendDidOpen(o);break;case y.DID_CHANGE:this.proxy.sendDidChange(o);break;case y.DID_CLOSE:this.proxy.sendDidClose(o);break;default:this.proxy.sendNotification(r,o)}}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){m.warn(`[ClangdLspManager] proxy dispose error: ${t}`)}this.proxy=null}this.isInitialized=!1,this.initPromise=null}getLogPath(){try{let e=Xo.join(Yt(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=Xo.join(e,"lsp-log",t);return Bl.mkdirSync(r,{recursive:!0}),fe(r)}catch{return"auto"}}};function jh(n){let e=Ki(n);return m.info(`[SyncGuard] ${e.reason}`),e}var Gl=(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))(Gl||{}),$h=(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))($h||{}),kt=3,Wl=600*1e3,Vl=100,wa=class{server;toolRouter;config={};arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";sdkPath="";arktsLangServerPath=null;nodePath="";ohpmJsPath="";hvigorJsPath="";clangdPath=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,jn(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),f.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",f.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,f.info(`Constructor: using configured path as startPath: '${t}'`));let o=xt(t);f.info(`Constructor: findHarmonyProject('${t}') => ${o??"null"}`),this.config.projectPath=o??void 0,this.sdkPath=this.config.sdkPath??"",this.arktsLangServerPath=this.config.arktsLangServerPath??null,this.nodePath=this.config.nodePath??"",this.ohpmJsPath=this.config.ohpmJsPath??"",this.hvigorJsPath=this.config.hvigorJsPath??"",this.clangdPath=this.config.clangdPath??null,f.info(`Constructor: sdkPath='${this.sdkPath}', arktsLangServerPath='${this.arktsLangServerPath??"(null)"}'`),this.server=new pA({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=Fl(e.telemetry,()=>this.arktsCheckTool?.aceServerPid??null,()=>this.config.projectPath??"",()=>this.sdkPath??""),this.standardProtocolAvailable=this.detectStandardProtocolAvailable(),this.registerTools()}registerTools(){this.registerCheckTool(),this.registerLspFeatureTools(),this.registerRestartTool()}registerRestartTool(){this.toolRouter.add({name:"restart",description:"Restart the MCP server in-place: re-sync the project and re-initialize the LSP, without dropping the client connection. Use to recover from a stuck/ERROR state after fixing the root cause, instead of exiting and reopening the agent. Use target to restart one side only (arkts/cpp) or both (all, default). Caution: if initialization fails again after a restart, the cause is likely a persistent project/SDK configuration issue\u2014do not call restart repeatedly; ask the user to fix the project first.",inputSchema:me.object({target:me.enum(["arkts","cpp","all"]).default("all").describe('Which backend to restart: "arkts" (ArkTS ace-server), "cpp" (C++ clangd), or "all" (both, default).')})},async e=>this.handleRestartCall(e))}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:me.object({files:me.array(me.string()).min(1).describe("List of source file paths to check, relative to the project root (absolute paths within the project are also accepted). Supports ArkTS and C/C++ files in the same call.")})},async e=>this.handleCheckCall(e))}registerLspFeatureTools(){if(!this.standardProtocolAvailable){f.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=me.object({file:me.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets (ArkTS) and C/C++ extensions."),line:me.number().describe("Line number (0-based)"),character:me.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:r,feature:o}of this.getPositionFeatures())this.toolRouter.add({name:t,description:r,inputSchema:e},async i=>this.handleLspFeatureCall(o,i));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:me.object({query:me.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:me.object({file:me.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). 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:me.object({file:me.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets and C/C++ extensions."),line:me.number().describe("Line number (0-based)"),character:me.number().describe("Character offset in the line (0-based)"),direction:me.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 f.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=xi(e);return f.info(`ArktsCheck protocol: ${t?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${t})`),t}catch(e){return f.warn(`Failed to detect standard LSP protocol availability: ${e}`),!1}}validateContainment(e){let t=this.config.projectPath;if(t){let o=[];for(let i of e){let s=C.isPathContainedWithSymlink(i,t);s.contained||(f.warn(`Containment check failed: ${s.reason}`),o.push(s.reason))}return o.length>0?{content:[{type:"text",text:o.join(`
|
|
1300
|
+
`)}],isError:!0}:null}let r=e.filter(o=>va.isAbsolute(o));return r.length>0?(f.warn(`Absolute paths rejected (no project root): ${r.join(", ")}`),{content:[{type:"text",text:r.map(o=>`Absolute path is not allowed: ${o}`).join(`
|
|
1301
|
+
`)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(d=>typeof d=="string"):[];if(t.length===0)return f.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};if(t.length>Vl)return f.warn(`check tool called with ${t.length} files (max: ${Vl})`),{content:[{type:"text",text:`Too many files: ${t.length}. Maximum allowed is ${Vl}.`}],isError:!0};let{etsFiles:r,cppFiles:o,unsupported:i}=fA(t);i.length>0&&f.warn(`Unsupported file types in check request: ${i.join(", ")}`);let s=i.map(d=>`Unsupported file type: ${d} (only .ets and C/C++ source/header files are supported)`),a=[];r.length>0&&this.mergeCheckResult(await this.callArktsCheck(r),s,a),o.length>0&&this.mergeCheckResult(await this.callCppCheck(o),s,a);let c=s.length>0;return{content:[{type:"text",text:[a.join(`
|
|
1290
1302
|
`),s.join(`
|
|
1291
1303
|
`)].filter(d=>d.trim().length>0).join(`
|
|
1292
|
-
`).trim()||"No diagnostics collected"}],isError:c}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return h.warn(`ArkTS check rejected: project is ${yl[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,o=t.line,i=t.character;return typeof r!="string"||typeof o!="number"||typeof i!="number"?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}:this.routeLspRequest(r,e,async()=>{if(r.endsWith(".ets"))return this.arktsCheckTool.handleLspFeature(e,{file:r,line:o,character:i});let s=e;return this.cppLspTool.handleLspFeature(s,{file:r,line:o,character:i})})}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 o=[],i=new Set;if(t)try{this.mergeSymbolItems(await this.arktsCheckTool.handleWorkspaceSymbolRaw(e),i,o)}catch(a){h.warn(`workspaceSymbol ArkTS query failed: ${a.message}`)}if(r)try{this.mergeSymbolItems(await this.cppLspTool.handleWorkspaceSymbolRaw(e),i,o)}catch(a){h.warn(`workspaceSymbol C++ query failed: ${a.message}`)}return{content:[{type:"text",text:o.length===0?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(o,null,2)}`}]}}symbolDedupKey(e){let t=e,r=t?.location?.uri??"",o=t?.location?.range?.start?.line??0,i=t?.location?.range?.start?.character??0;return`${r}:${o}:${i}`}mergeSymbolItems(e,t,r){if(e)for(let o of e){let i=this.symbolDedupKey(o);t.has(i)||(t.add(i),r.push(o))}}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;return typeof t!="string"?{content:[{type:"text",text:"Missing or invalid parameter: file (string required)."}],isError:!0}: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,o=e.character,i=e.direction;return typeof t!="string"||typeof r!="number"||typeof o!="number"?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}:i!=="incoming"&&i!=="outgoing"?{content:[{type:"text",text:'Parameter direction must be "incoming" or "outgoing".'}],isError:!0}:this.routeLspRequest(t,`callHierarchy(${i})`,async()=>t.endsWith(".ets")?this.arktsCheckTool.handleCallHierarchy({file:t,line:r,character:o,direction:i}):this.cppLspTool.handleCallHierarchy({file:t,line:r,character:o,direction:i}))}async handleCodeActionCall(e){let{file:t,line:r,character:o}=this.extractPositionArgs(e);return t?this.routeArktsRequest("codeAction",()=>this.arktsCheckTool.handleCodeAction({file:t,line:r,character:o})):{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}}async handleRenameCall(e){let{file:t,line:r,character:o}=this.extractPositionArgs(e),i=e.newName;return!t||typeof i!="string"||i.trim().length===0?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number), newName (non-empty string)."}],isError:!0}:this.routeArktsRequest("rename",()=>this.arktsCheckTool.handleRename({file:t,line:r,character:o,newName:i}))}async handleTypeHierarchyCall(e){let{file:t,line:r,character:o}=this.extractPositionArgs(e),i=e.direction;return t?i!=="supertypes"&&i!=="subtypes"?{content:[{type:"text",text:'Parameter direction must be "supertypes" or "subtypes".'}],isError:!0}:this.routeArktsRequest(`typeHierarchy(${i})`,()=>this.arktsCheckTool.handleTypeHierarchy({file:t,line:r,character:o,direction:i})):{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}}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,o=e.character;return typeof t!="string"||typeof r!="number"||typeof o!="number"?{file:null,line:0,character:0}:{file:t,line:r,character:o}}async routeArktsRequest(e,t){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return h.warn(`ArkTS ${e} rejected: project is ${yl[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 repeatedly (auto-retry exhausted: ${this.initRetryCount}/${yt}). Ask the user to investigate and confirm \`ohpm install\` + \`hvigor\` sync succeed manually. Do NOT call the \`restart\` tool repeatedly \u2014 call it at most once after the user fixes the root cause; if it fails again, stop retrying and escalate to the user.`}],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 ${_m[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):An(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 repeatedly (auto-retry exhausted: ${this.cppInitRetryCount}/${yt}). Ask the user to investigate and confirm \`hvigor compileNative\` succeeds manually. Do NOT call the \`restart\` tool repeatedly \u2014 call it at most once after the user fixes the root cause; if it fails again, stop retrying and escalate to the user.`}],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 o=e.content.map(i=>i.text).filter(i=>i&&i.trim().length>0).join(`
|
|
1293
|
-
`);o&&(e.isError?t.push(o):r.push(o))}async handleRestartCall(e){let t=e.target,r=t==="cpp"?"cpp":t==="arkts"?"arkts":"all";return this.restartProject(r),{content:[{type:"text",text:`MCP server is restarting in-place (${r==="all"?"ArkTS + C++":r==="cpp"?"C++":"ArkTS"}): re-sync project + re-initialize LSP. Client connection preserved\u2014no need to exit the agent. Please retry tools in ~10 seconds.`}]}}restartProject(e){h.info(`[restart] resetting tools + state, re-init (target=${e})`),(e==="arkts"||e==="all")&&this.restartArkts(),(e==="cpp"||e==="all")&&this.restartCpp()}restartArkts(){this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(e=>h.warn("Failed to shutdown ArktsCheckTool during restart:",e)),this.arktsCheckTool=null),this.initRetryCount=0,this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.configChangedTriggeredResync=!1,this.initPromise?(this.needsReinit=!0,h.info("[restart] ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(e=>h.warn("Failed to re-init ArkTS project during restart:",e)))}restartCpp(){this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(e=>h.warn("Failed to dispose ClangdLspManager during restart:",e)),this.cppLspManager=null),this.cppInitRetryCount=0,this.cppHasNoCppCode=!1,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitPromise?(this.cppNeedsReinit=!0,h.info("[restart] C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>h.warn("Failed to re-init C++ project during restart:",e)))}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 EC;if(await this.server.connect(e),h.info("devecocli-mcp-server started"),!this.config.debug){let t=wu();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=bt(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?bt(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=bt(this.originalProjectPath),t&&h.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(this.discoverProject()&&await this.ensureProjectSynced()){this.ensureCppProjectReady().catch(e=>{h.warn("Background C++ project init failed:",e)}),this.projectState=3,this.arktsCheckTool=new Rr(this.config.projectPath,this.sdkPath,this.arktsLangServerPath,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{h.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,h.info("Project fully initialized, check tool is available")}catch(e){h.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=Mm(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 Dr.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 o=Date.now()-this.syncSkipStartedAt,i=Math.round(o/1e3);return o>=hl?(h.error(`Sync skipped for ${i}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 ${i}s / ${hl/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=kn(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 Oo({workspaceRoot:e,sdkPath:this.sdkPath});try{await this.cppLspManager.start(),this.cppCheckTool=new Tr(this.cppLspManager),this.cppLspTool=new xr(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 Oo.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,o=Math.round(r/1e3);return r>=hl?(h.error(`[Cpp] C++ sync skipped for ${o}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 ${o}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"),yu(),gu()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function bC(n){let e=[],t=[],r=[];for(let o of n)Ks.extname(o).toLowerCase()===".ets"?e.push(o):An(o)?t.push(o):r.push(o);return{etsFiles:e,cppFiles:t,unsupported:r}}function wl(n={}){return new Js(n)}import*as vl from"fs";import*as Mo from"path";import{spawn as PC}from"child_process";async function Fm(n){Rn(!1);let{serverPath:e,logPath:t,projectPath:r,sdkPath:o,serverMaxSize:i}=await CC(n),s=DC(e,t,r,o,i);h.info("ace-server started, bridging stdio (initialize is left to the client)"),kC(s)}async function CC(n){let e=await I.new(),t=e.sourceType==="clt"?e.toolchainRoot:e.devecoStudioPath,r;if(n.projectPath)r=ce(Mo.resolve(n.projectPath)),h.info(`projectPath=specified ('${r}'), no search`);else if(n.autoDetect){let l=Pi(process.cwd());r=ce(l??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${l??"null, fallback to cwd"}`)}else r=ce(process.cwd()),h.info(`projectPath=cwd ('${r}'), no search (pass --auto-detect to search subdirs)`);let{sdkPath:o,arktsLangServerPath:i}=Ii(t);i||(h.error("ace-server not found (install DevEco Studio / CLT)."),process.exit(1));let s=Xr(i,!0),a=Mo.join(Vt(),"lsp-server",String(Date.now()));vl.mkdirSync(a,{recursive:!0});let c=IC(r,o);return h.info(`projectPath=${r}, sdkPath=${o}, arktsLangServerPath=${i}, serverPath=${s}, logPath=${a}, serverMaxSize=${c}MB`),{projectPath:r,sdkPath:o,serverPath:s,logPath:a,serverMaxSize:c}}function IC(n,e){let t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=t?parseInt(t,10):NaN,o=Number.isFinite(r)&&r>0?r:void 0,i=AC(n,e),s=Oi(i,o);return h.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${i}, override=${o??"none"})`),s}function AC(n,e){try{let t=[];return new Un(n,e).getAllDependencyMap(t).status==="OK"?t.length:new Pt(n).getAllModuleInfo().length}catch{return 0}}function DC(n,e,t,r,o){let i=Mo.join(e,"lspLog");vl.mkdirSync(i,{recursive:!0});let s=RC(n,i,t,r,o),a=process.execPath??"node";return h.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),PC(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function RC(n,e,t,r,o){let i=B(e);return["--expose-gc",`--max-old-space-size=${o}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${i}`,n,"--stdio",`--logger-path=${i}`,"--logger-level=TRACE",`--projectPath=${B(t)}`,`--sdkPath=${B(r)}`]}function kC(n){n.on("error",e=>{h.error(`[ace-server] spawn error: ${e.message}`),process.exit(1)}),n.stdout?.on("error",e=>{h.error(`[ace-server] stdout error: ${e.message}`)}),n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("error",e=>{h.error(`[ace-server] stderr error: ${e.message}`)}),n.stderr?.on("data",e=>{h.error(`[ace-server] ${e.toString("utf8").trim()}`)}),n.stdin?.on("error",e=>{h.error(`[ace-server] stdin error: ${e.message}`)}),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 jm from"fs";import*as Wn from"path";import{spawn as TC}from"child_process";async function $m(n){Rn(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await xC(n),o=Wn.join(t,"compile_commands.json");jm.existsSync(o)||h.warn(`compile_commands.json not found at ${o}. Cross-file navigation/completion will be limited. Run \`devecocli build\` first to generate it.`);let i=LC(e,t,r);h.info("clangd started, bridging stdio (initialize is left to the client)"),MC(i)}async function xC(n){let e=await NC();e||(h.error("DevEco Studio not found. Ensure DevEco Studio is installed."),process.exit(1));let t;if(n.projectPath)t=ce(Wn.resolve(n.projectPath)),h.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let a=Pi(process.cwd());t=ce(a??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${a??"null, fallback to cwd"}`)}else t=ce(Wn.resolve(process.cwd())),h.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=Ja(e),o=Di(r);o||(h.error(`clangd not found under sdk '${r}'. Expected at <sdkPath>/default/openharmony/native/llvm/bin/clangd`),process.exit(1));let i=Zr(t),s=Wn.dirname(i);return h.info(`projectPath=${t}, sdkPath=${r}, clangdPath=${o}, compileCommandsDir=${s}`),{projectPath:t,clangdPath:o,compileCommandsDir:s}}function NC(){return I.new().then(n=>n.devecoStudioPath).catch(()=>Ka())}function LC(n,e,t){let r=OC(e);return h.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),TC(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function OC(n){return[`--compile-commands-dir=${B(n)}`,"--log=info","--pch-storage=memory"]}function MC(n){n.on("error",e=>{h.error(`[clangd] spawn error: ${e.message}`),process.exit(1)}),n.stdout?.on("error",e=>{h.error(`[clangd] stdout error: ${e.message}`)}),n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("error",e=>{h.error(`[clangd] stderr error: ${e.message}`)}),n.stderr?.on("data",e=>{h.error(`[clangd] ${e.toString("utf8").trim()}`)}),n.stdin?.on("error",e=>{h.error(`[clangd] stdin error: ${e.message}`)}),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 FC(){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,o=await I.new(),i=o.sourceType==="clt"?o.toolchainRoot:o.devecoStudioPath??null,s=wl({projectPath:r,devecoPath:i??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 instanceof Error?c.message:String(c)),process.exit(1)}}var Sl=new _C("serve").description("Host bundled auxiliary protocol servers");Sl.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await FC()});Sl.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 Fm({projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await $m({projectPath:n.projectPath,autoDetect:n.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var Hm=Sl;import{Command as MA,InvalidArgumentError as od}from"commander";import{red as pa,dim as _A}from"colorette";var Mt=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],an={"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"};import*as Qo from"fs";import PA from"proper-lockfile";import ag from"ora";import*as st from"fs";import*as Bo from"path";var Lr="1.9.1",jC=48*1024*1024;var Or=200,Um=12,Bm=4,El=8,Wm=6;var Vm=1320,Gm=120,zm=450,qm=250,Ym=500,Jm=480,Km=80,Xm=200,Zm=60,Qm=200;var eh=200,th=40,bl=500,$C=Object.fromEntries(Mt.map((n,e)=>[an[n],e])),cn=Object.fromEntries(Mt.map((n,e)=>[n,e]));import*as _o from"fs";import*as W from"path";import{fileURLToPath as nh}from"url";var HC="docs";function Pl(){return W.join(ht(),HC)}function ge(){return W.join(Pl(),".index")}function Xs(){return W.join(ge(),"build.lock")}function Fo(){return W.join(ge(),"build-status.json")}function Mr(){return W.join(ge(),"build-meta.json")}function ln(){return W.join(ge(),"search.db")}function _r(){return W.join(ge(),".tmp")}function UC(n,e){let t=e;for(;!t.endsWith(`${W.sep}dist`)&&t!==W.dirname(t);)t=W.dirname(t);return t}function rh(n,e){return W.dirname(UC(n,e))}function oh(){let n=nh(import.meta.url),e=W.dirname(n);return n.includes(`${W.sep}dist${W.sep}`)?rh(n,e):W.join(e,"..","..","..")}function BC(...n){let e=nh(import.meta.url),t=W.dirname(e);return e.includes(`${W.sep}dist${W.sep}`)?[W.join(rh(e,t),...n)]:[W.join(t,"..","..","..",...n)]}function ih(...n){let e=oh(),t=_o.realpathSync(e);for(let r of BC(...n))try{let o=_o.lstatSync(r);if(o.isSymbolicLink()||!o.isFile())throw new Error(`Unsafe documentation package asset: ${n.join("/")} must be a regular file.`);let i=_o.realpathSync(r);if(!Ua(i,t))throw new Error(`Unsafe documentation package asset: ${n.join("/")} is outside the package.`);return i}catch(o){if(o.code!=="ENOENT")throw o}return null}function dn(){return ih("docs.zip")}function Cl(){return ih("index.zip")}function sh(){return W.join(oh(),"index","data")}import*as Vn from"fs";import*as jo from"path";var _t=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],Il=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};var ah=null;function WC(){if(ah)return ah;let n=ge();if(_t.every(o=>Vn.existsSync(jo.join(n,o))))return n;let t=sh();if(_t.every(o=>Vn.existsSync(jo.join(t,o))))return t;throw new Il("Lexicon files not found. Install the documentation index first (index.zip).")}function Fr(n){let e=jo.join(WC(),n);return Vn.readFileSync(e,"utf-8")}function ch(n,e){return Vn.readFileSync(jo.join(e,n),"utf-8")}import*as Zs from"fs";import*as lh from"path";import*as dh from"yauzl";var $o=null;function VC(n){return new Promise((e,t)=>{dh.open(n,{lazyEntries:!0,decodeStrings:!1,autoClose:!1},(r,o)=>{if(r||!o){t(r??new Error(`Failed to open zip: ${n}`));return}e(o)})})}function GC(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",o=>{let i=GC(o);i.endsWith("/")||e.set(i,o),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function qC(){$o?.zipfile.close(),$o=null}async function YC(n){let e=lh.resolve(n),t=await Zs.promises.stat(e),r=$o;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;qC();let o=await VC(e),i;try{i=await zC(o)}catch(s){throw o.close(),new Error(`Failed to read entries from zip: ${e}`,{cause:s})}return $o={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:o,entries:i,readChain:Promise.resolve()},$o}function JC(n,e){return new Promise((t,r)=>{n.openReadStream(e,(o,i)=>{if(o||!i){r(o??new Error(`Failed to read zip entry: ${e.fileName}`));return}let s=[];i.on("data",a=>{s.push(Buffer.isBuffer(a)?a:Buffer.from(a))}),i.on("end",()=>{t(Buffer.concat(s))}),i.on("error",r)})})}async function KC(n,e){let t=n.readChain,r;n.readChain=new Promise(o=>{r=o}),await t;try{return await JC(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 ZC(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function Al(n){let e=dn();if(!e)throw new Error("docs.zip not found");let t=await YC(e),r=ZC(t.entries,XC(n));if(!r)throw new Error(`Document not found: ${n}`);return(await KC(t,r)).toString("utf-8")}function Dl(){let n=dn();return n!==null&&Zs.existsSync(n)}import*as Te from"fs";import*as un from"path";import uh from"adm-zip";import*as Ho from"fs";import*as ea from"path";var Qs=class extends Error{constructor(e){super(`Unsafe documentation path: ${e}`),this.name="DocPathSafetyError"}};function jr(n){return n instanceof Ln||n instanceof Qs||n instanceof Error&&(n.name==="CliDataDirError"||n.name==="DocPathSafetyError")}function Tl(n){return new Qs(n)}function QC(){return ut(ht())}function kl(n,e,t){let r=fi(n,e);if(r===null)throw Tl(`${t} resolves outside the data directory.`);return r}async function Rl(n,e){await Ho.promises.mkdir(n,{recursive:!0});let t=kl(n,e,"directory");if(!(await Ho.promises.stat(t)).isDirectory())throw Tl("path must be a directory.")}function eI(n){let e=QC();try{let t=kl(n,e,"file");if(!Ho.statSync(t).isFile())throw Tl("path must be a regular file.")}catch(t){if(t.code==="ENOENT"){kl(ea.dirname(n),e,"file parent");return}throw t}}async function $r(n={}){let e=n.mode??"write",t=await sp();await Rl(Pl(),t),await Rl(ge(),t),e==="write"&&await Rl(_r(),t);for(let r of[ln(),Mr(),Fo(),Xs(),..._t.map(o=>ea.join(ge(),o))])eI(r)}var xl=["search.db","build-meta.json",..._t],tI=["corpus.json","corpus-offsets.json","orama.dpack"];async function nI(n){for(let e of tI)await Te.promises.rm(un.join(n,e),{force:!0})}function ph(n){let t=new uh(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=ge();await Te.promises.mkdir(e,{recursive:!0});for(let t of xl){let r=un.join(e,t);await Te.promises.rm(r,{force:!0}),await Te.promises.rename(un.join(n,t),r)}await nI(e),await Te.promises.rm(_r(),{recursive:!0,force:!0})}function fh(n){let e=Cl();if(!e)return!1;try{let t=ph(e);return t.indexVersion===Lr&&t.docsZipSha256===n&&t.segmentCount>0}catch{return!1}}async function mh(n){await $r({mode:"write"});let e=Cl();if(!e)throw new Error("index.zip not found");let t=ph(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=_r();await Te.promises.rm(r,{recursive:!0,force:!0}),await Te.promises.mkdir(r,{recursive:!0});let o=new uh(e);for(let s of xl){let a=o.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await Te.promises.writeFile(un.join(r,s),a.getData())}let i=JSON.parse(await Te.promises.readFile(un.join(r,"build-meta.json"),"utf-8"));if(!Te.existsSync(un.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await rI(r),i}async function hh(){await Te.promises.rm(_r(),{recursive:!0,force:!0});let n=ge();for(let e of xl)await Te.promises.rm(un.join(n,e),{force:!0})}import{createHash as gh}from"crypto";import*as yh from"fs";async function Uo(n){return new Promise((e,t)=>{let r=gh("sha256"),o=yh.createReadStream(n);o.on("data",i=>r.update(i)),o.on("error",t),o.on("end",()=>e(r.digest("hex")))})}function wh(n){return gh("sha256").update(n,"utf8").digest("hex")}var Nl=null;function oI(){let n=Fr("harmonyos-synonyms.json");return JSON.parse(n)}function iI(n){let e=new Map;for(let t of n){let r=t.map(o=>o.trim()).filter(Boolean);for(let o of r){let i=r.filter(s=>s!==o);e.set(o.toLowerCase(),i),o!==o.toLowerCase()&&e.set(o,i)}}return e}function sI(){let n=iI(oI()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function aI(){return Nl||(Nl=sI()),Nl}function Ll(n,e){let t=aI(),r=n.split(/\s+/).filter(Boolean),o=new Set,i=Number.isFinite(e)?e:r.length;for(let s=0;s<r.length&&o.size<i;s+=1){let a=r[s];o.add(a);let c=t.get(a)??t.get(a.toLowerCase());if(c)for(let l of c){if(o.size>=i)break;o.add(l)}}return[...o].join(" ")}function vh(n,e){let t=e?ch(n,e):Fr(n);return wh(t)}function Ol(n){return vh("harmonyos-synonyms.json",n)}function Ml(n){return vh("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 ta(){try{let n=await st.promises.readFile(Fo(),"utf-8");return JSON.parse(n)}catch{return{...cI}}}async function _l(n){let e=Fo();await st.promises.mkdir(Bo.dirname(e),{recursive:!0}),await st.promises.writeFile(e,JSON.stringify(n,null,2))}function Sh(n){let e=Date.now();return{state:"installing",phase:1,phaseLabel:"Preparing documentation index",current:0,total:0,message:n,startedAt:e,updatedAt:e,error:null}}async function Wo(n){let t={...await ta(),...n,updatedAt:Date.now()};return await _l(t),t}async function Fl(){let n=dn();return n?Uo(n):null}async function jl(){try{let n=await st.promises.readFile(Mr(),"utf-8");return JSON.parse(n)}catch{return null}}async function na(n=!1){if(n)return"no-index";let e=await jl();if(!e||e.segmentCount===0)return"no-index";let t=await Fl();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==Lr?"engine-upgraded":e.termsHash!==Ml()?"terms-changed":e.synonymsHash!==Ol()?"synonyms-changed":null}function Vo(){if(!Dl()||!st.existsSync(ln())||!st.existsSync(Mr()))return!1;let n=Bo.dirname(ln());if(!_t.every(e=>st.existsSync(Bo.join(n,e))))return!1;try{let e=st.readFileSync(Mr(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function $l(n=!1){return n?!0:Dl()?Vo()?await na()!==null:!0:!1}async function Eh(){let n=await ta();return["installing","indexing","persisting"].includes(n.state)}var bh=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),Hl=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),Ph=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"]),Ch=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,Ih=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 zo(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(vI).join(` ${e} `)}function Go(n){return zo(n,"OR")}function Ah(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?Go([...t,...r]):`(${Go(t)}) AND (${Go(r)})`}function qo(n){return gI.test(n)}function Dh(n){return yI.test(n)&&n.length>=Ih}function SI(n){return wI.test(n)}function Yo(n){return qo(n)||Dh(n)||SI(n)}function EI(n){let e=n.trim().toLowerCase();return Ch.has(e)?!1:bh.has(e)}function bI(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function Ul(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function Rh(n){return[...n.matchAll(lI)].map(e=>e[0])}function kh(n,e=Ih){let t=[];for(let r of n.matchAll(dI))r[0].length>=e&&t.push(r[0]);return t}function Jo(n){return n.filter(e=>{let t=e.toLowerCase();return!n.some(r=>{if(r===e)return!1;let o=r.toLowerCase();return o.length>t.length&&o.endsWith(t)&&t.length>=4})})}function pn(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;pn(e,n);let t=Ul(n);return t&&pn(e,t),Jo([...e])}function ra(n){if(qo(n))return PI(n);let e=new Set;return pn(e,n),Jo([...e])}function oa(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(),o=t[2].toLowerCase();if(!mI.test(r)||Ph.has(r)||!EI(o))return null;let i=bI(r,o);return{first:r,second:o,camelCase:i,lower:i.toLowerCase()}}function Bl(n){let e=oa(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 Th(n){let e=n.trim(),t=Bl(e);if(t&&Hl.has(t.first))return!0;if(Dh(e)){let r=CI(e);return r!==null&&Hl.has(r)}return!1}function Wl(n,e,t){let r=t.toLowerCase(),o=new RegExp(`@ohos\\.[^\\s(]*${t}`,"i");for(let i of[n,e])if(i&&(i.toLowerCase().includes(r)||o.test(i)))return!0;return!1}function Vl(n){let e=n.trim();if(Yo(e))return ra(e);let t=new Set;for(let r of Rh(n)){pn(t,r);let o=Ul(r);o&&pn(t,o)}for(let r of kh(n))pn(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 Jo([...t])}function xh(n){let e=n.trim();if(Yo(e))return ra(e);let t=new Set,r=oa(e);r&&pn(t,r.camelCase);for(let o of Vl(e))t.add(o);for(let o of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let i=o[0];i!==i.toLowerCase()&&t.add(i)}return Jo([...t])}function Nh(n){return Yo(n)}var J={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 Lh(n){return J.pureApiSymbol.test(n.trim())}function Ko(n){let e=n.trim();return J.stageModelExact.test(e)||J.stageModelEnglishExact.test(e)}function Oh(n){let e=[];return Ko(n.trim())&&e.push("Stage\u6A21\u578B","Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0"),J.declarePermissionTokens.test(n)&&e.push("\u58F0\u660E\u6743\u9650"),J.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 Mh(n){return Ko(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=>J.uiAbilityLifecycleBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:n=>Ko(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!Ko(n)&&J.stageModel.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:n=>J.entryAbilityPage.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:n=>J.declarePermissionBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:n=>J.stateDecoratorBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:n=>J.stateManagement.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:n=>J.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=>J.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 o=cn[t];n.set(o,(n.get(o)??1)*r)}}function _h(n,e){for(let t of II)t.matches(n)&&AI(e,t.weights)}function Fh(n,e){if(e!==void 0)return!1;let t=n.trim();return qo(t)||J.pureApiSymbol.test(t)||Th(t)}function jh(n){let e=n.trim();if(qo(e)||J.pureApiSymbol.test(e))return"harmonyos-references";if(Ko(e)||J.uiAbilityLifecycleCatalog.test(e)||J.stateDecoratorCatalog.test(e)||J.stateManagement.test(e)||J.declarePermissionCatalog.test(e)||J.stageModelEntryPage.test(e)||J.routerRoute.test(e)||J.dialogPopupExact.test(e))return"harmonyos-guides"}import{createRequire as DI}from"module";var RI=DI(import.meta.url),ia=null,Gl=null,zl=null;function kI(){if(ia)return ia;let n=Fr("harmonyos-stopwords.txt");return ia=new Set(n.split(`
|
|
1294
|
-
`).map(e=>e.trim()).filter(Boolean)),
|
|
1304
|
+
`).trim()||"No diagnostics collected"}],isError:c}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return f.warn(`ArkTS check rejected: project is ${Gl[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return f.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return this.arktsCheckTool.handleCall({files:e});default:return f.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,o=t.line,i=t.character;return typeof r!="string"||typeof o!="number"||typeof i!="number"?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}:this.routeLspRequest(r,e,async()=>{if(r.endsWith(".ets"))return this.arktsCheckTool.handleLspFeature(e,{file:r,line:o,character:i});let s=e;return this.cppLspTool.handleLspFeature(s,{file:r,line:o,character:i})})}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 f.info(`workspaceSymbol rejected: ArkTS ${a}; C++ ${c}`),{content:[{type:"text",text:`workspaceSymbol: ArkTS ${a}; C++ ${c}`}],isError:!0}}let o=[],i=new Set;if(t)try{this.mergeSymbolItems(await this.arktsCheckTool.handleWorkspaceSymbolRaw(e),i,o)}catch(a){f.warn(`workspaceSymbol ArkTS query failed: ${a.message}`)}if(r)try{this.mergeSymbolItems(await this.cppLspTool.handleWorkspaceSymbolRaw(e),i,o)}catch(a){f.warn(`workspaceSymbol C++ query failed: ${a.message}`)}return{content:[{type:"text",text:o.length===0?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(o,null,2)}`}]}}symbolDedupKey(e){let t=e,r=t?.location?.uri??"",o=t?.location?.range?.start?.line??0,i=t?.location?.range?.start?.character??0;return`${r}:${o}:${i}`}mergeSymbolItems(e,t,r){if(e)for(let o of e){let i=this.symbolDedupKey(o);t.has(i)||(t.add(i),r.push(o))}}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}/${kt})`;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}/${kt})`;case 4:return this.cppHasNoCppCode?"ready (no C++ code)":"ready";default:return"unknown"}}async handleDocumentSymbolCall(e){let t=e.file;return typeof t!="string"?{content:[{type:"text",text:"Missing or invalid parameter: file (string required)."}],isError:!0}: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,o=e.character,i=e.direction;return typeof t!="string"||typeof r!="number"||typeof o!="number"?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}:i!=="incoming"&&i!=="outgoing"?{content:[{type:"text",text:'Parameter direction must be "incoming" or "outgoing".'}],isError:!0}:this.routeLspRequest(t,`callHierarchy(${i})`,async()=>t.endsWith(".ets")?this.arktsCheckTool.handleCallHierarchy({file:t,line:r,character:o,direction:i}):this.cppLspTool.handleCallHierarchy({file:t,line:r,character:o,direction:i}))}async handleCodeActionCall(e){let{file:t,line:r,character:o}=this.extractPositionArgs(e);return t?this.routeArktsRequest("codeAction",()=>this.arktsCheckTool.handleCodeAction({file:t,line:r,character:o})):{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}}async handleRenameCall(e){let{file:t,line:r,character:o}=this.extractPositionArgs(e),i=e.newName;return!t||typeof i!="string"||i.trim().length===0?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number), newName (non-empty string)."}],isError:!0}:this.routeArktsRequest("rename",()=>this.arktsCheckTool.handleRename({file:t,line:r,character:o,newName:i}))}async handleTypeHierarchyCall(e){let{file:t,line:r,character:o}=this.extractPositionArgs(e),i=e.direction;return t?i!=="supertypes"&&i!=="subtypes"?{content:[{type:"text",text:'Parameter direction must be "supertypes" or "subtypes".'}],isError:!0}:this.routeArktsRequest(`typeHierarchy(${i})`,()=>this.arktsCheckTool.handleTypeHierarchy({file:t,line:r,character:o,direction:i})):{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}}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,o=e.character;return typeof t!="string"||typeof r!="number"||typeof o!="number"?{file:null,line:0,character:0}:{file:t,line:r,character:o}}async routeArktsRequest(e,t){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return f.warn(`ArkTS ${e} rejected: project is ${Gl[this.projectState]}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return f.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 f.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"),f.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(f.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:"Initializing, please retry in 10 seconds"}],isError:!0}):(f.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"No HarmonyOS project detected. Please verify the project directory or create a project first."}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=kt?(f.error(`Init retry limit reached (${this.initRetryCount}/${kt}), will not auto-retry`),{content:[{type:"text",text:`Project initialization failed repeatedly (auto-retry exhausted: ${this.initRetryCount}/${kt}). Ask the user to investigate and confirm \`ohpm install\` + \`hvigor\` sync succeed manually. Do NOT call the \`restart\` tool repeatedly \u2014 call it at most once after the user fixes the root cause; if it fails again, stop retrying and escalate to the user.`}],isError:!0}):(f.info(`Error check: auto-retrying (${this.initRetryCount}/${kt})`),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 f.warn(`C++ ${e} rejected: C++ project is ${$h[this.cppProjectState]}`),{content:[{type:"text",text:"C++ project is syncing (compileNative), please retry in 25 seconds"}],isError:!0};case 3:return f.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 f.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):_n(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",f.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>=kt?(f.error(`C++ init retry limit reached (${this.cppInitRetryCount}/${kt}), will not auto-retry`),{content:[{type:"text",text:`C++ project initialization failed repeatedly (auto-retry exhausted: ${this.cppInitRetryCount}/${kt}). Ask the user to investigate and confirm \`hvigor compileNative\` succeeds manually. Do NOT call the \`restart\` tool repeatedly \u2014 call it at most once after the user fixes the root cause; if it fails again, stop retrying and escalate to the user.`}],isError:!0}):(f.info(`C++ error check: auto-retrying (${this.cppInitRetryCount}/${kt})`),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 o=e.content.map(i=>i.text).filter(i=>i&&i.trim().length>0).join(`
|
|
1305
|
+
`);o&&(e.isError?t.push(o):r.push(o))}async handleRestartCall(e){let t=e.target,r=t==="cpp"?"cpp":t==="arkts"?"arkts":"all";return this.restartProject(r),{content:[{type:"text",text:`MCP server is restarting in-place (${r==="all"?"ArkTS + C++":r==="cpp"?"C++":"ArkTS"}): re-sync project + re-initialize LSP. Client connection preserved\u2014no need to exit the agent. Please retry tools in ~10 seconds.`}]}}restartProject(e){f.info(`[restart] resetting tools + state, re-init (target=${e})`),(e==="arkts"||e==="all")&&this.restartArkts(),(e==="cpp"||e==="all")&&this.restartCpp()}restartArkts(){this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(e=>f.warn("Failed to shutdown ArktsCheckTool during restart:",e)),this.arktsCheckTool=null),this.initRetryCount=0,this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.configChangedTriggeredResync=!1,this.initPromise?(this.needsReinit=!0,f.info("[restart] ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(e=>f.warn("Failed to re-init ArkTS project during restart:",e)))}restartCpp(){this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(e=>f.warn("Failed to dispose ClangdLspManager during restart:",e)),this.cppLspManager=null),this.cppInitRetryCount=0,this.cppHasNoCppCode=!1,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitPromise?(this.cppNeedsReinit=!0,f.info("[restart] C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>f.warn("Failed to re-init C++ project during restart:",e)))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{f.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(t=>{f.warn("Failed to dispose ClangdLspManager during setProjectPath:",t)}),this.cppLspManager=null),this.initPromise?(this.needsReinit=!0,f.info("Project path changed while ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{f.warn("Failed to re-init project after setProjectPath:",t)})),this.cppInitPromise?(this.cppNeedsReinit=!0,f.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=>{f.warn("Failed to re-init C++ project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new mA;if(await this.server.connect(e),f.info("devecocli-mcp-server started"),!this.config.debug){let t=Lu();t&&f.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=xt(t);r?(f.info(`Detected project path from client root: ${r}`),this.config.projectPath=r):f.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?f.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):f.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{f.warn("Background project init failed:",t)})}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return f.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return f.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){f.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,f.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{f.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{f.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=>{f.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?xt(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=xt(this.originalProjectPath),t&&f.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=>{f.warn("Background C++ project init failed:",e)}),this.projectState=3,this.arktsCheckTool=new Gr(this.config.projectPath,this.sdkPath,this.arktsLangServerPath,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{f.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,f.info("Project fully initialized, check tool is available")}catch(e){f.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=jh(e),r=!t.required;return f.info(`Sync check: skipHvigor=${r}, reason=${t.reason}`),this.runSync(e,{skipHvigorSync:r})}async runSync(e,t){this.projectState=2,f.info("Starting project sync...");let r=await Vr.handleSyncProject(e,this.sdkPath,this.nodePath,this.ohpmJsPath,this.hvigorJsPath,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 o=Date.now()-this.syncSkipStartedAt,i=Math.round(o/1e3);return o>=Wl?(f.error(`Sync skipped for ${i}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(f.warn(`Sync skipped: ${r.reason}, resetting to IDLE for retry (elapsed ${i}s / ${Wl/1e3}s)`),this.projectState=0,!1)}case"failed":return f.error(`Project sync failed: ${r.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:return f.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=>{f.warn("Failed to re-init C++ project after cppNeedsReinit:",e)}))}}async doEnsureCppProjectReady(){let e=this.config.projectPath;if(!e){f.info("[Cpp] No project path, skipping C++ init");return}this.cppProjectState=1;let t=Bn(e);if(t.length===0){f.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,f.info(`[Cpp] Found ${t.length} C++ module(s): ${t.map(r=>r.name).join(", ")}`),!!await this.runSyncCpp(e)){this.cppProjectState=3,this.cppLspManager=new Zo({workspaceRoot:e,clangdPath:this.clangdPath??""});try{await this.cppLspManager.start(),this.cppCheckTool=new qr(this.cppLspManager),this.cppLspTool=new Jr(this.cppLspManager),this.cppProjectState=4,this.cppInitRetryCount=0,f.info("[Cpp] C++ project fully initialized, C++ tools are available")}catch(r){f.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,f.info("[Cpp] Starting C++ project sync (compileNative)...");let t=await Zo.handleSyncCppProject(e,this.sdkPath,this.nodePath,this.hvigorJsPath);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,o=Math.round(r/1e3);return r>=Wl?(f.error(`[Cpp] C++ sync skipped for ${o}s due to lock contention, giving up`),this.cppInitRetryCount++,this.cppSyncSkipStartedAt=0,this.cppProjectState=5,!1):(f.warn(`[Cpp] C++ sync skipped: ${t.reason}, resetting to IDLE_CPP for retry (elapsed ${o}s)`),this.cppProjectState=0,!1)}case"failed":return f.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){f.warn("Failed to close MCP server connection:",e)}f.info("devecocli-mcp-server stopped"),Nu(),xu()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function fA(n){let e=[],t=[],r=[];for(let o of n)va.extname(o).toLowerCase()===".ets"?e.push(o):_n(o)?t.push(o):r.push(o);return{etsFiles:e,cppFiles:t,unsupported:r}}function zl(n={}){return new wa(n)}import*as ql from"fs";import*as Qo from"path";import{spawn as hA}from"child_process";async function Hh(n){jn(!1);let{serverPath:e,logPath:t,projectPath:r,sdkPath:o,serverMaxSize:i}=await yA(n),s=SA(e,t,r,o,i);f.info("ace-server started, bridging stdio (initialize is left to the client)"),EA(s),await gA(s.pid)}async function gA(n){let e="unknown";if(n!==null){let r=await Pt(n);r!==null&&(e=Ie(Number(r)*1024))}let t={event:E.ServeLsp,args:process.argv.slice(2),lspMemory:e};await k.track(t)}async function yA(n){let e=await I.new(),t;if(n.projectPath)t=fe(Qo.resolve(n.projectPath)),f.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let c=Ri(process.cwd());t=fe(c??process.cwd()),f.info(`findHarmonyProjectInDir('${process.cwd()}') => ${c??"null, fallback to cwd"}`)}else t=fe(process.cwd()),f.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=e.sdkPath,o=e.arktsLangServerPath;o||(f.error("ace-server not found (install DevEco Studio / CLT)."),process.exit(1));let i=fo(o,!0),s=Qo.join(Yt(),"lsp-server",String(Date.now()));ql.mkdirSync(s,{recursive:!0});let a=wA(t,r);return f.info(`projectPath=${t}, sdkPath=${r}, arktsLangServerPath=${o}, serverPath=${i}, logPath=${s}, serverMaxSize=${a}MB`),{projectPath:t,sdkPath:r,serverPath:i,logPath:s,serverMaxSize:a}}function wA(n,e){let t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=t?parseInt(t,10):NaN,o=Number.isFinite(r)&&r>0?r:void 0,i=vA(n,e),s=Qi(i,o);return f.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${i}, override=${o??"none"})`),s}function vA(n,e){try{let t=[];return new tr(n,e).getAllDependencyMap(t).status==="OK"?t.length:new Lt(n).getAllModuleInfo().length}catch{return 0}}function SA(n,e,t,r,o){let i=Qo.join(e,"lspLog");ql.mkdirSync(i,{recursive:!0});let s=bA(n,i,t,r,o),a=process.execPath??"node";return f.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),hA(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function bA(n,e,t,r,o){let i=V(e);return["--expose-gc",`--max-old-space-size=${o}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${i}`,n,"--stdio",`--logger-path=${i}`,"--logger-level=TRACE",`--projectPath=${V(t)}`,`--sdkPath=${V(r)}`]}function EA(n){n.on("error",e=>{f.error(`[ace-server] spawn error: ${e.message}`),process.exit(1)}),n.stdout?.on("error",e=>{f.error(`[ace-server] stdout error: ${e.message}`)}),n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("error",e=>{f.error(`[ace-server] stderr error: ${e.message}`)}),n.stderr?.on("data",e=>{f.error(`[ace-server] ${e.toString("utf8").trim()}`)}),n.stdin?.on("error",e=>{f.error(`[ace-server] stdin error: ${e.message}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{f.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{f.info(`ace-server exited with code ${e}`),process.exit(e??0)})}import*as Uh from"fs";import*as rr from"path";import{spawn as PA}from"child_process";async function Bh(n){jn(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await CA(n),o=rr.join(t,"compile_commands.json");Uh.existsSync(o)||f.warn(`compile_commands.json not found at ${o}. Cross-file navigation/completion will be limited. Run \`devecocli build\` first to generate it.`);let i=AA(e,t,r);f.info("clangd started, bridging stdio (initialize is left to the client)"),kA(i)}async function CA(n){let e=await IA();e?.clangdPath||(f.error("clangd not found. Ensure DevEco Studio / CLT is installed."),process.exit(1));let t;if(n.projectPath)t=fe(rr.resolve(n.projectPath)),f.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let a=Ri(process.cwd());t=fe(a??process.cwd()),f.info(`findHarmonyProjectInDir('${process.cwd()}') => ${a??"null, fallback to cwd"}`)}else t=fe(rr.resolve(process.cwd())),f.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=e.sdkPath,o=e.clangdPath,i=ho(t),s=rr.dirname(i);return f.info(`projectPath=${t}, sdkPath=${r}, clangdPath=${o}, compileCommandsDir=${s}`),{projectPath:t,clangdPath:o,compileCommandsDir:s}}async function IA(){try{return await I.new()}catch{let n=Du();if(!n)return null;try{return I.fromIDE(n)}catch{return null}}}function AA(n,e,t){let r=DA(e);return f.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),PA(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function DA(n){return[`--compile-commands-dir=${V(n)}`,"--log=info","--pch-storage=memory"]}function kA(n){n.on("error",e=>{f.error(`[clangd] spawn error: ${e.message}`),process.exit(1)}),n.stdout?.on("error",e=>{f.error(`[clangd] stdout error: ${e.message}`)}),n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("error",e=>{f.error(`[clangd] stderr error: ${e.message}`)}),n.stderr?.on("data",e=>{f.error(`[clangd] ${e.toString("utf8").trim()}`)}),n.stdin?.on("error",e=>{f.error(`[clangd] stdin error: ${e.message}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{f.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{f.info(`clangd exited with code ${e}`),process.exit(e??0)})}async function RA(){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,o=await I.new(),i=zl({projectPath:r,sdkPath:o.sdkPath,arktsLangServerPath:o.arktsLangServerPath??void 0,nodePath:o.nodePath,ohpmJsPath:o.ohpmJsPath,hvigorJsPath:o.hvigorJsPath,clangdPath:o.clangdPath??void 0,nodeMaxOldSpaceSize:e,debug:t,telemetry:k}),s,a=new Promise(l=>{s=l}),c=async()=>{await i.shutdown(),s()};process.once("SIGINT",c),process.once("SIGTERM",c),process.platform==="win32"&&process.once("SIGBREAK",c);try{await i.start()}catch(l){console.error("Failed to start MCP server:",l instanceof Error?l.message:String(l)),process.exit(1)}await a}var Jl=new TA("serve").description("Host bundled auxiliary protocol servers");Jl.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await RA()});Jl.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 Hh({projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await Bh({projectPath:n.projectPath,autoDetect:n.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var Wh=Jl;import{Command as kk,InvalidArgumentError as Nd}from"commander";import{red as Tk,dim as Rk}from"colorette";var Vt=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],wn={"harmonyos-guides":"\u5F00\u53D1\u6307\u5357","harmonyos-references":"API\u53C2\u8003","best-practices":"\u6700\u4F73\u5B9E\u8DF5","harmonyos-faqs":"FAQ","harmonyos-releases":"\u7248\u672C\u8BF4\u660E","harmonyos-roadmap":"\u53D8\u66F4\u9884\u544A"};import*as yi from"fs";import gk from"proper-lockfile";import dy from"ora";import*as ft from"fs";import*as si from"path";var Kr="1.9.1",xA=48*1024*1024;var Xr=200,Vh=12,Gh=4,Yl=8,zh=6;var qh=1320,Jh=120,Yh=450,Kh=250,Xh=500,Zh=480,Qh=80,eg=200,tg=60,ng=200;var rg=200,og=40,Kl=500,NA=Object.fromEntries(Vt.map((n,e)=>[wn[n],e])),vn=Object.fromEntries(Vt.map((n,e)=>[n,e]));import*as ei from"fs";import*as G from"path";import{fileURLToPath as ig}from"url";var LA="docs";function Xl(){return G.join(et(),LA)}function Pe(){return G.join(Xl(),".index")}function Sa(){return G.join(Pe(),"build.lock")}function ti(){return G.join(Pe(),"build-status.json")}function Zr(){return G.join(Pe(),"build-meta.json")}function Sn(){return G.join(Pe(),"search.db")}function Qr(){return G.join(Pe(),".tmp")}function OA(n,e){let t=e;for(;!t.endsWith(`${G.sep}dist`)&&t!==G.dirname(t);)t=G.dirname(t);return t}function sg(n,e){return G.dirname(OA(n,e))}function ag(){let n=ig(import.meta.url),e=G.dirname(n);return n.includes(`${G.sep}dist${G.sep}`)?sg(n,e):G.join(e,"..","..","..")}function MA(...n){let e=ig(import.meta.url),t=G.dirname(e);return e.includes(`${G.sep}dist${G.sep}`)?[G.join(sg(e,t),...n)]:[G.join(t,"..","..","..",...n)]}function cg(...n){let e=ag(),t=ei.realpathSync(e);for(let r of MA(...n))try{let o=ei.lstatSync(r);if(o.isSymbolicLink()||!o.isFile())throw new Error(`Unsafe documentation package asset: ${n.join("/")} must be a regular file.`);let i=ei.realpathSync(r);if(!Sc(i,t))throw new Error(`Unsafe documentation package asset: ${n.join("/")} is outside the package.`);return i}catch(o){if(o.code!=="ENOENT")throw o}return null}function bn(){return cg("docs.zip")}function Zl(){return cg("index.zip")}function lg(){return G.join(ag(),"index","data")}import*as or from"fs";import*as ni from"path";var Gt=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],Ql=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};var dg=null;function _A(){if(dg)return dg;let n=Pe();if(Gt.every(o=>or.existsSync(ni.join(n,o))))return n;let t=lg();if(Gt.every(o=>or.existsSync(ni.join(t,o))))return t;throw new Ql("Lexicon files not found. Install the documentation index first (index.zip).")}function eo(n){let e=ni.join(_A(),n);return or.readFileSync(e,"utf-8")}function ug(n,e){return or.readFileSync(ni.join(e,n),"utf-8")}import*as ba from"fs";import*as pg from"path";import*as mg from"yauzl";var ri=null;function FA(n){return new Promise((e,t)=>{mg.open(n,{lazyEntries:!0,decodeStrings:!1,autoClose:!1},(r,o)=>{if(r||!o){t(r??new Error(`Failed to open zip: ${n}`));return}e(o)})})}function jA(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function $A(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",o=>{let i=jA(o);i.endsWith("/")||e.set(i,o),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function HA(){ri?.zipfile.close(),ri=null}async function UA(n){let e=pg.resolve(n),t=await ba.promises.stat(e),r=ri;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;HA();let o=await FA(e),i;try{i=await $A(o)}catch(s){throw o.close(),new Error(`Failed to read entries from zip: ${e}`,{cause:s})}return ri={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:o,entries:i,readChain:Promise.resolve()},ri}function BA(n,e){return new Promise((t,r)=>{n.openReadStream(e,(o,i)=>{if(o||!i){r(o??new Error(`Failed to read zip entry: ${e.fileName}`));return}let s=[];i.on("data",a=>{s.push(Buffer.isBuffer(a)?a:Buffer.from(a))}),i.on("end",()=>{t(Buffer.concat(s))}),i.on("error",r)})})}async function WA(n,e){let t=n.readChain,r;n.readChain=new Promise(o=>{r=o}),await t;try{return await BA(n.zipfile,e)}finally{r()}}function VA(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 GA(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function ed(n){let e=bn();if(!e)throw new Error("docs.zip not found");let t=await UA(e),r=GA(t.entries,VA(n));if(!r)throw new Error(`Document not found: ${n}`);return(await WA(t,r)).toString("utf-8")}function td(){let n=bn();return n!==null&&ba.existsSync(n)}import*as je from"fs";import*as En from"path";import fg from"adm-zip";import*as oi from"fs";import*as Pa from"path";var Ea=class extends Error{constructor(e){super(`Unsafe documentation path: ${e}`),this.name="DocPathSafetyError"}};function to(n){return n instanceof zn||n instanceof Ea||n instanceof Error&&(n.name==="CliDataDirError"||n.name==="DocPathSafetyError")}function od(n){return new Ea(n)}function zA(){return bt(et())}function rd(n,e,t){let r=Bi(n,e);if(r===null)throw od(`${t} resolves outside the data directory.`);return r}async function nd(n,e){await oi.promises.mkdir(n,{recursive:!0});let t=rd(n,e,"directory");if(!(await oi.promises.stat(t)).isDirectory())throw od("path must be a directory.")}function qA(n){let e=zA();try{let t=rd(n,e,"file");if(!oi.statSync(t).isFile())throw od("path must be a regular file.")}catch(t){if(t.code==="ENOENT"){rd(Pa.dirname(n),e,"file parent");return}throw t}}async function no(n={}){let e=n.mode??"write",t=await rm();await nd(Xl(),t),await nd(Pe(),t),e==="write"&&await nd(Qr(),t);for(let r of[Sn(),Zr(),ti(),Sa(),...Gt.map(o=>Pa.join(Pe(),o))])qA(r)}var id=["search.db","build-meta.json",...Gt],JA=["corpus.json","corpus-offsets.json","orama.dpack"];async function YA(n){for(let e of JA)await je.promises.rm(En.join(n,e),{force:!0})}function hg(n){let t=new fg(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 KA(n){let e=Pe();await je.promises.mkdir(e,{recursive:!0});for(let t of id){let r=En.join(e,t);await je.promises.rm(r,{force:!0}),await je.promises.rename(En.join(n,t),r)}await YA(e),await je.promises.rm(Qr(),{recursive:!0,force:!0})}function gg(n){let e=Zl();if(!e)return!1;try{let t=hg(e);return t.indexVersion===Kr&&t.docsZipSha256===n&&t.segmentCount>0}catch{return!1}}async function yg(n){await no({mode:"write"});let e=Zl();if(!e)throw new Error("index.zip not found");let t=hg(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=Qr();await je.promises.rm(r,{recursive:!0,force:!0}),await je.promises.mkdir(r,{recursive:!0});let o=new fg(e);for(let s of id){let a=o.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await je.promises.writeFile(En.join(r,s),a.getData())}let i=JSON.parse(await je.promises.readFile(En.join(r,"build-meta.json"),"utf-8"));if(!je.existsSync(En.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await KA(r),i}async function wg(){await je.promises.rm(Qr(),{recursive:!0,force:!0});let n=Pe();for(let e of id)await je.promises.rm(En.join(n,e),{force:!0})}import{createHash as vg}from"crypto";import*as Sg from"fs";async function ii(n){return new Promise((e,t)=>{let r=vg("sha256"),o=Sg.createReadStream(n);o.on("data",i=>r.update(i)),o.on("error",t),o.on("end",()=>e(r.digest("hex")))})}function bg(n){return vg("sha256").update(n,"utf8").digest("hex")}var sd=null;function XA(){let n=eo("harmonyos-synonyms.json");return JSON.parse(n)}function ZA(n){let e=new Map;for(let t of n){let r=t.map(o=>o.trim()).filter(Boolean);for(let o of r){let i=r.filter(s=>s!==o);e.set(o.toLowerCase(),i),o!==o.toLowerCase()&&e.set(o,i)}}return e}function QA(){let n=ZA(XA()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function eD(){return sd||(sd=QA()),sd}function ad(n,e){let t=eD(),r=n.split(/\s+/).filter(Boolean),o=new Set,i=Number.isFinite(e)?e:r.length;for(let s=0;s<r.length&&o.size<i;s+=1){let a=r[s];o.add(a);let c=t.get(a)??t.get(a.toLowerCase());if(c)for(let l of c){if(o.size>=i)break;o.add(l)}}return[...o].join(" ")}function Eg(n,e){let t=e?ug(n,e):eo(n);return bg(t)}function cd(n){return Eg("harmonyos-synonyms.json",n)}function ld(n){return Eg("harmonyos-terms.txt",n)}var tD={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function Ca(){try{let n=await ft.promises.readFile(ti(),"utf-8");return JSON.parse(n)}catch{return{...tD}}}async function dd(n){let e=ti();await ft.promises.mkdir(si.dirname(e),{recursive:!0}),await ft.promises.writeFile(e,JSON.stringify(n,null,2))}function Pg(n){let e=Date.now();return{state:"installing",phase:1,phaseLabel:"Preparing documentation index",current:0,total:0,message:n,startedAt:e,updatedAt:e,error:null}}async function ai(n){let t={...await Ca(),...n,updatedAt:Date.now()};return await dd(t),t}async function ud(){let n=bn();return n?ii(n):null}async function pd(){try{let n=await ft.promises.readFile(Zr(),"utf-8");return JSON.parse(n)}catch{return null}}async function Ia(n=!1){if(n)return"no-index";let e=await pd();if(!e||e.segmentCount===0)return"no-index";let t=await ud();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==Kr?"engine-upgraded":e.termsHash!==ld()?"terms-changed":e.synonymsHash!==cd()?"synonyms-changed":null}function ci(){if(!td()||!ft.existsSync(Sn())||!ft.existsSync(Zr()))return!1;let n=si.dirname(Sn());if(!Gt.every(e=>ft.existsSync(si.join(n,e))))return!1;try{let e=ft.readFileSync(Zr(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function md(n=!1){return n?!0:td()?ci()?await Ia()!==null:!0:!1}async function Cg(){let n=await Ca();return["installing","indexing","persisting"].includes(n.state)}var Ig=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),fd=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),Ag=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"]),Dg=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 nD=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,rD=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,oD=/[A-Z][a-zA-Z0-9]{2,}/g,iD=/@[A-Z][a-zA-Z0-9]*/g,sD=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,kg=6,aD=/^[a-z][a-z0-9]{2,}$/,cD=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,lD=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,dD=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,uD=/^[A-Z][a-zA-Z0-9]+$/;function pD(n){return`"${n.replace(/"/g,'""')}"`}function di(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(pD).join(` ${e} `)}function li(n){return di(n,"OR")}function Tg(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?li([...t,...r]):`(${li(t)}) AND (${li(r)})`}function ui(n){return lD.test(n)}function Rg(n){return dD.test(n)&&n.length>=kg}function mD(n){return uD.test(n)}function pi(n){return ui(n)||Rg(n)||mD(n)}function fD(n){let e=n.trim().toLowerCase();return Dg.has(e)?!1:Ig.has(e)}function hD(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function hd(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function xg(n){return[...n.matchAll(nD)].map(e=>e[0])}function Ng(n,e=kg){let t=[];for(let r of n.matchAll(rD))r[0].length>=e&&t.push(r[0]);return t}function mi(n){return n.filter(e=>{let t=e.toLowerCase();return!n.some(r=>{if(r===e)return!1;let o=r.toLowerCase();return o.length>t.length&&o.endsWith(t)&&t.length>=4})})}function Pn(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function gD(n){let e=new Set;Pn(e,n);let t=hd(n);return t&&Pn(e,t),mi([...e])}function Aa(n){if(ui(n))return gD(n);let e=new Set;return Pn(e,n),mi([...e])}function Da(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(cD);if(!t)return null;let r=t[1].toLowerCase(),o=t[2].toLowerCase();if(!aD.test(r)||Ag.has(r)||!fD(o))return null;let i=hD(r,o);return{first:r,second:o,camelCase:i,lower:i.toLowerCase()}}function gd(n){let e=Da(n.trim());return!e||e.second!=="manager"?null:e}function yD(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function Lg(n){let e=n.trim(),t=gd(e);if(t&&fd.has(t.first))return!0;if(Rg(e)){let r=yD(e);return r!==null&&fd.has(r)}return!1}function yd(n,e,t){let r=t.toLowerCase(),o=new RegExp(`@ohos\\.[^\\s(]*${t}`,"i");for(let i of[n,e])if(i&&(i.toLowerCase().includes(r)||o.test(i)))return!0;return!1}function wd(n){let e=n.trim();if(pi(e))return Aa(e);let t=new Set;for(let r of xg(n)){Pn(t,r);let o=hd(r);o&&Pn(t,o)}for(let r of Ng(n))Pn(t,r);for(let r of n.matchAll(iD))t.add(r[0]);for(let r of n.matchAll(sD))t.add(r[0]);for(let r of n.matchAll(oD))r[0].length>=4&&t.add(r[0]);return mi([...t])}function Og(n){let e=n.trim();if(pi(e))return Aa(e);let t=new Set,r=Da(e);r&&Pn(t,r.camelCase);for(let o of wd(e))t.add(o);for(let o of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let i=o[0];i!==i.toLowerCase()&&t.add(i)}return mi([...t])}function Mg(n){return pi(n)}var Z={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 _g(n){return Z.pureApiSymbol.test(n.trim())}function fi(n){let e=n.trim();return Z.stageModelExact.test(e)||Z.stageModelEnglishExact.test(e)}function Fg(n){let e=[];return fi(n.trim())&&e.push("Stage\u6A21\u578B","Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0"),Z.declarePermissionTokens.test(n)&&e.push("\u58F0\u660E\u6743\u9650"),Z.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 jg(n){return fi(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var wD=[{matches:n=>Z.uiAbilityLifecycleBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:n=>fi(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!fi(n)&&Z.stageModel.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:n=>Z.entryAbilityPage.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:n=>Z.declarePermissionBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:n=>Z.stateDecoratorBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:n=>Z.stateManagement.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:n=>Z.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=>Z.dialogPopupBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function vD(n,e){for(let{catalog:t,multiplier:r}of e){let o=vn[t];n.set(o,(n.get(o)??1)*r)}}function $g(n,e){for(let t of wD)t.matches(n)&&vD(e,t.weights)}function Hg(n,e){if(e!==void 0)return!1;let t=n.trim();return ui(t)||Z.pureApiSymbol.test(t)||Lg(t)}function Ug(n){let e=n.trim();if(ui(e)||Z.pureApiSymbol.test(e))return"harmonyos-references";if(fi(e)||Z.uiAbilityLifecycleCatalog.test(e)||Z.stateDecoratorCatalog.test(e)||Z.stateManagement.test(e)||Z.declarePermissionCatalog.test(e)||Z.stageModelEntryPage.test(e)||Z.routerRoute.test(e)||Z.dialogPopupExact.test(e))return"harmonyos-guides"}import{createRequire as SD}from"module";var bD=SD(import.meta.url),ka=null,vd=null,Sd=null;function ED(){if(ka)return ka;let n=eo("harmonyos-stopwords.txt");return ka=new Set(n.split(`
|
|
1306
|
+
`).map(e=>e.trim()).filter(Boolean)),ka}function PD(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t]?.trim();if(!r)continue;let o=n[t+1]?.trim();if(r==="@"&&o&&/^[A-Z][a-zA-Z0-9]*$/.test(o)){e.push(`@${o}`),t+=1;continue}e.push(r)}return e}function Bg(n){let e=ED(),t=[];for(let r of PD(n)){let o=r.trim();!o||e.has(o)||(t.push(o.toLowerCase()),/[A-Z]/.test(o)&&/[a-zA-Z]/.test(o)&&t.push(o))}return t}async function CD(){let{cut:n,cut_for_search:e,with_dict:t}=bD("jieba-wasm"),r=eo("harmonyos-terms.txt");return t(r),h("doc-index: using jieba-wasm backend"),{cut:(o,i)=>n(o,i),cutForSearch:(o,i)=>e(o,i)}}async function hi(){return vd||(Sd||(Sd=CD().then(n=>(vd=n,n))),Sd)}async function ID(n){let e=await hi();return Bg(e.cutForSearch(n,!0))}async function Wg(n){let e=await hi();return Bg(e.cut(n,!0))}async function Ta(n,e){let t=n.trim();if(!t||e<=0)return"";let r=(await ID(t)).join(" ");return r.length<=e?r:r.slice(0,e)}async function AD(n,e){let t=[];for(let o of n){let i=o.trim();i&&(t.push(i.toLowerCase()),/[A-Z]/.test(i)&&t.push(i))}let r=[...new Set(t)].join(" ");return r.length<=e?r:r.slice(0,e)}async function Vg(n){let e=!!n.sectionTitle.trim(),t=n.titleTokens.trim(),r=e?Zh:qh,o=e?eg:Yh,i=e?await AD(n.apiSymbols,o):await Ta(n.apiSymbols.join(" "),o),a=(await Promise.all([Ta(t,e?Qh:Jh),Promise.resolve(i),Ta(n.headingsText,e?tg:Kh),Ta(n.bodySample,e?ng:Xh)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}function DD(n){return n.join(" ").replace(/\s+/g," ").trim().slice(0,Xr)}function bd(n,e){let t=new Set,r=[];for(let o of[...n,...e]){let i=o.toLowerCase();if(!(!o||t.has(i))&&(t.add(i),r.push(o),r.length>=Vh))break}return r}function kD(n){return n.length>=2&&n.length<=Gh}function TD(n,e){let t=ad(n,Yl),r=t.split(/\s+/).filter(Boolean),o=[e.first,...r.filter(a=>a!==e.second),e.lower,e.camelCase],i=[e.second,e.lower,e.camelCase],s=bd(o,i);return{rawQuery:n,expandedQuery:t,tokens:s,preferAnd:!1,ftsMatch:Tg(o,i)}}function RD(n,e){let t=bd(Aa(e),[]);return{rawQuery:n,expandedQuery:n,tokens:t,preferAnd:!1,ftsMatch:li(t)}}async function Gg(n){let e=DD(n),t=e.trim(),r=jg(t);if(r)return{rawQuery:e,expandedQuery:r.expandedQuery,tokens:r.tokens,preferAnd:!1};let o=Da(t);if(o)return TD(e,o);if(pi(t))return RD(e,t);let i=Fg(e),s=[...wd(e),...i],c=Mg(t)?e:ad(e,Yl),l=await Wg(c),d=bd(s,l);return{rawQuery:e,expandedQuery:c,tokens:d,preferAnd:i.length===0&&kD(d)}}var zg=["harmonyos-releases","harmonyos-roadmap"],xD=new Set(zg.map(n=>vn[n])),ND=zg.map(n=>`${wn[n]}/`);function LD(n){return xD.has(n)}function OD(n){return ND.some(e=>n.startsWith(e))}function qg(n){let e=[],t=[];for(let r of n)LD(r.catalog_id)?t.push(r):e.push(r);return[...e,...t]}function Jg(n){let e=[],t=[];for(let r of n)OD(r.documentId)?t.push(r):e.push(r);return[...e,...t]}var MD=[{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 gi(n,e,t){let r=vn[e];n.set(r,(n.get(r)??1)*t)}function _D(n,e){let t=n.trim(),r=/[\u4e00-\u9fff]/.test(t),o=/\b[A-Z][a-zA-Z0-9]{2,}\b/.test(t),i=/\b[a-z][a-zA-Z0-9]{3,}\b/.test(t);if(r&&(o||i)){gi(e,"harmonyos-guides",1.45),gi(e,"harmonyos-references",1.35);return}(o||i)&&gi(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(t)&&gi(e,"harmonyos-references",1.75)}function Yg(n){let e=new Map,t=n.trim();if(!t)return e;let r=_g(t);_D(t,e),$g(t,e);for(let o of MD)o.pattern.test(t)&&(o.skipForPureApiSymbol&&r||gi(e,o.catalog,o.multiplier));return e}function Kg(n){return Ug(n)}import{readFile as rk,stat as ok,writeFile as ik}from"fs/promises";var FD=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function jD(n,e){let t=-1;for(let r of FD){let o=n.lastIndexOf(r);o>t&&(t=o)}return t>=e?t:-1}function Xg(n,e,t={}){let{maxLen:r=rg,contextChars:o=og,excerptTruncated:i=!1}=t,s=n.replace(/\s+/g," ").trim();if(!s)return"";if(s.length<=r)return i?`${s}...`:s;let a=e.split(/\s+/).map(we=>we.trim()).filter(Boolean),c=0;for(let we of a){let wt=s.toLowerCase().indexOf(we.toLowerCase());if(wt>=0){c=wt;break}}let l=Math.max(0,c-o),d=Math.min(s.length,l+r),g=s.slice(l,d),w=jD(g,r-25);w>=0&&(d=l+w);let b=s.slice(l,d).trim(),$=l>0?"...":"",ne=d<s.length||i?"...":"";return`${$}${b}${ne}`}var $D=`
|
|
1295
1307
|
SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
|
|
1296
1308
|
d.catalog_id, bm25(segments_fts) AS bm25
|
|
1297
1309
|
FROM segments_fts
|
|
@@ -1300,7 +1312,7 @@ ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this
|
|
|
1300
1312
|
WHERE segments_fts MATCH ?
|
|
1301
1313
|
ORDER BY bm25(segments_fts)
|
|
1302
1314
|
LIMIT ?
|
|
1303
|
-
`,
|
|
1315
|
+
`,HD=`
|
|
1304
1316
|
SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
|
|
1305
1317
|
d.catalog_id, bm25(segments_fts) AS bm25
|
|
1306
1318
|
FROM segments_fts
|
|
@@ -1309,7 +1321,7 @@ ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this
|
|
|
1309
1321
|
WHERE segments_fts MATCH ? AND d.catalog_id = ?
|
|
1310
1322
|
ORDER BY bm25(segments_fts)
|
|
1311
1323
|
LIMIT ?
|
|
1312
|
-
`,
|
|
1324
|
+
`,UD=3.5,BD=1.4,WD=4,VD=1.8,GD=1.35,zD=3.5,qD=1.8,JD=120,Zg=6;function Pd(n){return n.toLowerCase().replace(/[^\p{L}\p{N}@.]+/gu,"")}function YD(n){return n.split(/[^\p{L}\p{N}@.]+/u).map(Pd).filter(e=>e.length>=2)}function KD(n,e){return e.length>1&&e.every(t=>n.includes(t))}function XD(n){return/^[a-z0-9]{1,4}$/.test(n.trim().toLowerCase())}function ZD(n,e){return n===e?zD:n.startsWith(e)||n.includes(`@ohos.${e}`)?qD:1}function QD(n,e){let t=Pd(e);if(t.length<2)return 1;let r=Pd(n.doc_title);if(XD(e))return ZD(r,t);if(r.includes(t))return WD;if(t.length>=Zg&&r.includes(t.slice(0,Zg)))return VD;let o=YD(e);return KD(r,o)?GD:1}function ek(n,e){return e<=1?n:n<0?n*e:n/e}function Ra(n,e,t,r){let o=n.bm25/(e.get(n.catalog_id)??1);return o=ek(o,QD(n,t)),r&&yd(n.doc_title,n.section_title,r)&&(o/=UD,n.catalog_id===vn["harmonyos-references"]&&(o/=BD)),o}function Ed(n,e,t,r){return n.reduce((o,i)=>Ra(i,e,t,r)<Ra(o,e,t,r)?i:o)}function tk(n,e){return e.some(t=>n.section_title.includes(t)||n.doc_title.includes(t))}function nk(n,e,t,r,o){if(o){let i=n.filter(s=>yd(s.doc_title,s.section_title,o));if(i.length>0)return Ed(i,t,r,o)}if(e.length>0){let i=n.filter(s=>tk(s,e));if(i.length>0)return Ed(i,t,r,o)}return Ed(n,t,r,o)}function Qg(n,e,t,r,o){let i=Yg(e),s=Og(e),c=gd(e)?.camelCase,l=new Map;for(let b of n){let $=l.get(b.document_id)??[];$.push(b),l.set(b.document_id,$)}let d=[];for(let b of l.values())d.push(nk(b,s,i,t,c));let g=d.sort((b,$)=>Ra(b,i,t,c)-Ra($,i,t,c));return(o?qg(g):g).slice(0,r)}function ey(n,e,t,r,o,i){let s=e?vn[e]:void 0,a=Math.max(t,t*zh,JD),c=s===void 0?n.all($D,r,a):n.all(HD,r,s,a);return(s===void 0?Qg(c,i,o,t,!0):Qg(c,i,o,t,!1)).map(d=>({title:d.doc_title,documentId:d.document_id,sectionTitle:d.section_title||void 0,snippet:Xg(d.lead_text,o,{excerptTruncated:!!d.excerpt_truncated})}))}var ty=`
|
|
1313
1325
|
CREATE TABLE documents (
|
|
1314
1326
|
id INTEGER PRIMARY KEY,
|
|
1315
1327
|
document_id TEXT NOT NULL UNIQUE,
|
|
@@ -1347,43 +1359,43 @@ CREATE TRIGGER segments_au AFTER UPDATE ON segments BEGIN
|
|
|
1347
1359
|
END;
|
|
1348
1360
|
|
|
1349
1361
|
CREATE INDEX segments_doc_id_idx ON segments(doc_id);
|
|
1350
|
-
`;var Kl=null,fn=null,Qh=Promise.resolve();async function Xl(){return Kl||(Kl=(async()=>{let n=(await import("@sqlite.org/sqlite-wasm")).default;return n()})()),Kl}function fA(n){return{all(e,...t){let r=n.prepare(e);t.length>0&&r.bind(t);let o=[];for(;r.step();)o.push(r.get({}));return r.finalize(),o}}}async function mA(n){let e=await uA(n);if(fn&&fn.dbPath===n&&fn.mtimeMs===e.mtimeMs)return fn.db;fn?.db.close();let t=await Xl(),r=t.capi,o=t.wasm,i=new Uint8Array(await dA(n)),s=o.allocFromTypedArray(i),a,c=!1;try{a=new t.oo1.DB(":memory:");let l=r.SQLITE_DESERIALIZE_READONLY|r.SQLITE_DESERIALIZE_RESIZEABLE|r.SQLITE_DESERIALIZE_FREEONCLOSE,d=r.sqlite3_deserialize(a.pointer,"main",s,i.byteLength,i.byteLength,l);if(d!==r.SQLITE_OK)throw new Error(`Failed to open readonly database: sqlite3_deserialize returned code ${d} for: ${n}`);return fn={dbPath:n,mtimeMs:e.mtimeMs,db:a},c=!0,a}finally{c||(a?.close(),o.dealloc(s))}}async function hA(n){let e,t=Qh;Qh=new Promise(r=>{e=r}),await t;try{return await mA(n)}finally{e()}}function eg(){fn?.db.close(),fn=null}async function gA(n,e,t,r){n.exec("BEGIN");for(let o of r){let i=t(o.source);e.bind([i,o.source.sectionTitle,o.source.leadText,o.searchText,o.source.excerptTruncated?1:0]),e.step(),e.reset()}n.exec("COMMIT")}function yA(n,e,t){return r=>{let o=e.get(r.documentId);if(o!==void 0)return o;let i=n.selectValue("SELECT id FROM documents WHERE document_id = ?",[r.documentId]);if(i!=null){let a=Number(i);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 wA(n,e,t){await Xo();let r=await Xl(),o=new r.oo1.DB(":memory:","c");o.exec(Zh);let i=new Map,s=o.prepare("INSERT INTO documents(document_id, catalog_id, doc_title) VALUES (?, ?, ?)"),a=o.prepare("INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated) VALUES (?, ?, ?, ?, ?)"),c=yA(o,i,s),l=e.length;for(let g=0;g<l;g+=bl){let w=e.slice(g,g+bl),P=await Promise.all(w.map(async O=>({source:O,searchText:await Uh(O)})));await gA(o,a,c,P),await t?.(Math.min(g+w.length,l),l)}o.exec("ANALYZE");let d=r.capi.sqlite3_js_db_export(o);await pA(n,d),o.close(),eg()}async function vA(n,e,t,r,o,i){let s=await hA(n);return Xh(fA(s),e,t,r,o,i)}async function tg(){return await Xl(),{resetCache:eg,buildSearchIndex:wA,searchIndex:(n,e,t,r,o,i,s)=>vA(r,e,t,o,i,s)}}var ca=null,Zl=null;async function Ql(){return ca||(ca=tg().then(n=>(Zl=n,n))),ca}function ed(){Zl?.resetCache(),ca=null,Zl=null}async function SA(n,e,t,r,o,i,s){let a=await Ql(),c=s??ln();return a.searchIndex(n,e,t,c,r,o,i)}function Hr(){ed()}function rg(n,e,t){let r=new Set,o=[];for(let i of[...n,...e])if(!r.has(i.documentId)&&(r.add(i.documentId),o.push(i),o.length>=t))break;return o}function la(n,e,t,r,o,i){return SA(n,e,t,o,r.expandedQuery,r.rawQuery,i)}async function EA(n,e,t,r,o){let i=await la(n,e,t,r,zo(r.tokens,"AND"),o);if(i.length>=t)return i;let s=await la(n,e,t,r,zo(r.tokens,"OR"),o);return rg(i,s,t)}async function td(n,e,t,r,o){return r.ftsMatch?la(n,e,t,r,r.ftsMatch,o):r.preferAnd?EA(n,e,t,r,o):la(n,e,t,r,zo(r.tokens,"OR"),o)}async function bA(n,e,t,r){let o=await td(n,"harmonyos-references",e,t,r);if(o.length>=e)return o;let i=await td(n,void 0,e,t,r);return rg(o,i,e)}function ng(n,e){return e!==void 0?n:Gh(n)}async function nd(n,e,t=10,r){let o=await Bh(n);if(Fh(o.rawQuery,e)){let a=await bA(n,t,o,r);return ng(a,e)}let i=e??qh(o.rawQuery),s=await td(n,i,t,o,r);return ng(s,e)}var da=class extends Error{constructor(t,r){super(r);this.code=t;this.name="DocNotReadyError"}code};function CA(n){return new Promise(e=>setTimeout(e,n))}async function og(n,e,t){e?.start(t),await Wo({state:"installing",phase:1,phaseLabel:"Installing index",message:t}),await mh(n),Hr(),e&&(e.text="Documentation index installed.")}async function IA(n,e){try{return await og(n,e,"Installing documentation index\u2026"),await ig(e),!0}catch(t){if(jr(t))throw t}try{return await hh(),Hr(),await og(n,e,"Retrying documentation index install\u2026"),await ig(e),!0}catch(t){if(jr(t))throw t;return!1}}async function ig(n){await Wo({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function AA(n){let e=await jl(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";n?.succeed(t),await Wo({state:"done",message:t,error:null})}async function DA(n,e){let t=n instanceof Error?n.message:String(n);throw await Wo({state:"error",error:t}),e?.fail(t),n}async function RA(){let n=ge();await Qo.promises.mkdir(n,{recursive:!0});let e=Xs();return Qo.existsSync(e)||await Qo.promises.writeFile(e,"","utf-8"),e}async function kA(){let n=await RA();return PA.lock(n,{stale:1800*1e3})}async function TA(){let n=dn(),e=(n?await Uo(n):null)??await Fl();if(!e)throw new Error("docs.zip not found");return e}async function xA(n,e){let t=await TA(),r=n.force||await $l(n.force),o=await na(n.force);if(!r&&!o&&Vo()){await AA(e);return}if(!(fh(t)&&await IA(t,e)))throw new Error("Documentation index bundle is unavailable or corrupted. Reinstall the package with: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>")}var Ur=class{static async run(e={}){let t=e.background??!1,o=e.quiet??t?void 0:ag({text:"Checking documentation\u2026",color:"cyan"}),i;try{e.assumeStorageSafe||await $r({mode:"write"}),i=await kA(),await _l(Sh("Starting documentation setup\u2026")),await xA(e,o)}catch(s){throw i&&await DA(s,o),s}finally{i&&await i()}}};async function NA(n){for(;;){let e=await ta();if(e.state==="done"&&Vo())return;if(e.state==="error")throw new da("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 CA(500)}}async function sg(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await Ur.run({builtBy:"doc-init",force:e,quiet:!0})}async function LA(){let n=await na()!==null;if(Vo()&&!n)return;let e=ag({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await Eh()){await NA(e),e.succeed("Documentation ready.");return}if(await $l()){await sg(e),e.succeed("Documentation ready.");return}await sg(e,!0),e.succeed("Documentation ready.")}catch(t){throw e.fail(t.message),t}}async function Br(){await $r({mode:"read"}),await LA()}function OA(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 rd=class{async search(e,t,r=10){await Br();try{return await nd(e,t,r)}catch(o){if(!OA(o))throw o;return Hr(),await Ur.run({builtBy:"doc-init",force:!0,quiet:!0,assumeStorageSafe:!0}),nd(e,t,r)}}async readDocument(e){return await Br(),Al(e)}},ua=new rd;import Yz from"adm-zip";import{unified as kz}from"unified";import xz from"remark-parse";import Lz from"remark-gfm";import{toString as Mz}from"mdast-util-to-string";function cg(...n){return e=>{if(!n.includes(e))throw new od(`Allowed values: ${n.join(", ")}`);return e}}function FA(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new od("Must be a positive integer.");return e}var jA=cg("json","default"),$A=cg("json","default");function id(n){let e=n instanceof Error?n.message:String(n);return jr(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 fa=new MA("docs").description("Search and read HarmonyOS documentation from local docs directory");fa.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",UA,"all").option("--format <fmt>","Output format (default, json)",jA,"default").option("--limit <n>","Max number of results",FA,10).action(async(n,e)=>{try{let t=HA(n),r=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=await ua.search(t,r,e.limit);e.format==="json"?console.log(JSON.stringify(o,null,2)):BA(o)}catch(t){console.error(pa(id(t))),process.exit(1)}});fa.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{try{let e=n.trim();e||(console.error(pa("Document ID cannot be empty.")),process.exit(1));let t=await ua.readDocument(e);console.log(t)}catch(e){console.error(pa(id(e))),process.exit(1)}});fa.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",$A,"default").action(async n=>{try{if(await Br(),n.format==="json"){let e=Mt.map(t=>({name:t,title:an[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of Mt)console.log(` ${e.padEnd(20)} ${_A(an[e])}`)}catch(e){console.error(pa(id(e))),process.exit(1)}});function HA(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>Or)throw new Error(`Query exceeds ${Or} characters.`);return e}function UA(n){if(n==="all")return"all";if(!Mt.includes(n))throw new od(`Invalid catalog "${n}". Allowed: all, ${Mt.join(", ")}`);return n}function BA(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 lg=fa;import{Command as GD}from"commander";import{Command as eD,InvalidArgumentError as tD,Option as ad}from"commander";import{readFileSync as VA,unlinkSync as GA}from"fs";import{tmpdir as zA}from"os";import{join as qA}from"path";var Ft=class{constructor(e,t){this.hdcPath=e;this.serial=t}hdcPath;serial;async listWindows(e){let t=await this.fetchDump(),r=WA(t);return e?.all||(r=r.filter(o=>o.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 Z(this.hdcPath,e);if(t.exitCode!==0)throw new Error(`Failed to query windows: ${(t.stderr||t.stdout).trim()}`);return t.stdout}};function WA(n){let e=n.split(`
|
|
1351
|
-
`),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]),g=Number(c[2]),w=Number(c[3]),
|
|
1362
|
+
`;var Cd=null,Cn=null,ny=Promise.resolve();async function Id(){return Cd||(Cd=(async()=>{let n=(await import("@sqlite.org/sqlite-wasm")).default;return n()})()),Cd}function sk(n){return{all(e,...t){let r=n.prepare(e);t.length>0&&r.bind(t);let o=[];for(;r.step();)o.push(r.get({}));return r.finalize(),o}}}async function ak(n){let e=await ok(n);if(Cn&&Cn.dbPath===n&&Cn.mtimeMs===e.mtimeMs)return Cn.db;Cn?.db.close();let t=await Id(),r=t.capi,o=t.wasm,i=new Uint8Array(await rk(n)),s=o.allocFromTypedArray(i),a,c=!1;try{a=new t.oo1.DB(":memory:");let l=r.SQLITE_DESERIALIZE_READONLY|r.SQLITE_DESERIALIZE_RESIZEABLE|r.SQLITE_DESERIALIZE_FREEONCLOSE,d=r.sqlite3_deserialize(a.pointer,"main",s,i.byteLength,i.byteLength,l);if(d!==r.SQLITE_OK)throw new Error(`Failed to open readonly database: sqlite3_deserialize returned code ${d} for: ${n}`);return Cn={dbPath:n,mtimeMs:e.mtimeMs,db:a},c=!0,a}finally{c||(a?.close(),o.dealloc(s))}}async function ck(n){let e,t=ny;ny=new Promise(r=>{e=r}),await t;try{return await ak(n)}finally{e()}}function ry(){Cn?.db.close(),Cn=null}async function lk(n,e,t,r){n.exec("BEGIN");for(let o of r){let i=t(o.source);e.bind([i,o.source.sectionTitle,o.source.leadText,o.searchText,o.source.excerptTruncated?1:0]),e.step(),e.reset()}n.exec("COMMIT")}function dk(n,e,t){return r=>{let o=e.get(r.documentId);if(o!==void 0)return o;let i=n.selectValue("SELECT id FROM documents WHERE document_id = ?",[r.documentId]);if(i!=null){let a=Number(i);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 uk(n,e,t){await hi();let r=await Id(),o=new r.oo1.DB(":memory:","c");o.exec(ty);let i=new Map,s=o.prepare("INSERT INTO documents(document_id, catalog_id, doc_title) VALUES (?, ?, ?)"),a=o.prepare("INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated) VALUES (?, ?, ?, ?, ?)"),c=dk(o,i,s),l=e.length;for(let g=0;g<l;g+=Kl){let w=e.slice(g,g+Kl),b=await Promise.all(w.map(async $=>({source:$,searchText:await Vg($)})));await lk(o,a,c,b),await t?.(Math.min(g+w.length,l),l)}o.exec("ANALYZE");let d=r.capi.sqlite3_js_db_export(o);await ik(n,d),o.close(),ry()}async function pk(n,e,t,r,o,i){let s=await ck(n);return ey(sk(s),e,t,r,o,i)}async function oy(){return await Id(),{resetCache:ry,buildSearchIndex:uk,searchIndex:(n,e,t,r,o,i,s)=>pk(r,e,t,o,i,s)}}var xa=null,Ad=null;async function Dd(){return xa||(xa=oy().then(n=>(Ad=n,n))),xa}function kd(){Ad?.resetCache(),xa=null,Ad=null}async function mk(n,e,t,r,o,i,s){let a=await Dd(),c=s??Sn();return a.searchIndex(n,e,t,c,r,o,i)}function ro(){kd()}function sy(n,e,t){let r=new Set,o=[];for(let i of[...n,...e])if(!r.has(i.documentId)&&(r.add(i.documentId),o.push(i),o.length>=t))break;return o}function Na(n,e,t,r,o,i){return mk(n,e,t,o,r.expandedQuery,r.rawQuery,i)}async function fk(n,e,t,r,o){let i=await Na(n,e,t,r,di(r.tokens,"AND"),o);if(i.length>=t)return i;let s=await Na(n,e,t,r,di(r.tokens,"OR"),o);return sy(i,s,t)}async function Td(n,e,t,r,o){return r.ftsMatch?Na(n,e,t,r,r.ftsMatch,o):r.preferAnd?fk(n,e,t,r,o):Na(n,e,t,r,di(r.tokens,"OR"),o)}async function hk(n,e,t,r){let o=await Td(n,"harmonyos-references",e,t,r);if(o.length>=e)return o;let i=await Td(n,void 0,e,t,r);return sy(o,i,e)}function iy(n,e){return e!==void 0?n:Jg(n)}async function Rd(n,e,t=10,r){let o=await Gg(n);if(Hg(o.rawQuery,e)){let a=await hk(n,t,o,r);return iy(a,e)}let i=e??Kg(o.rawQuery),s=await Td(n,i,t,o,r);return iy(s,e)}var La=class extends Error{constructor(t,r){super(r);this.code=t;this.name="DocNotReadyError"}code};function yk(n){return new Promise(e=>setTimeout(e,n))}async function ay(n,e,t){e?.start(t),await ai({state:"installing",phase:1,phaseLabel:"Installing index",message:t}),await yg(n),ro(),e&&(e.text="Documentation index installed.")}async function wk(n,e){try{return await ay(n,e,"Installing documentation index\u2026"),await cy(e),!0}catch(t){if(to(t))throw t}try{return await wg(),ro(),await ay(n,e,"Retrying documentation index install\u2026"),await cy(e),!0}catch(t){if(to(t))throw t;return!1}}async function cy(n){await ai({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function vk(n){let e=await pd(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";n?.succeed(t),await ai({state:"done",message:t,error:null})}async function Sk(n,e){let t=n instanceof Error?n.message:String(n);throw await ai({state:"error",error:t}),e?.fail(t),n}async function bk(){let n=Pe();await yi.promises.mkdir(n,{recursive:!0});let e=Sa();return yi.existsSync(e)||await yi.promises.writeFile(e,"","utf-8"),e}async function Ek(){let n=await bk();return gk.lock(n,{stale:1800*1e3})}async function Pk(){let n=bn(),e=(n?await ii(n):null)??await ud();if(!e)throw new Error("docs.zip not found");return e}async function Ck(n,e){let t=await Pk(),r=n.force||await md(n.force),o=await Ia(n.force);if(!r&&!o&&ci()){await vk(e);return}if(!(gg(t)&&await wk(t,e)))throw new Error("Documentation index bundle is unavailable or corrupted. Reinstall the package with: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>")}var oo=class{static async run(e={}){let t=e.background??!1,o=e.quiet??t?void 0:dy({text:"Checking documentation\u2026",color:"cyan"}),i;try{e.assumeStorageSafe||await no({mode:"write"}),i=await Ek(),await dd(Pg("Starting documentation setup\u2026")),await Ck(e,o)}catch(s){throw i&&await Sk(s,o),s}finally{i&&await i()}}};async function Ik(n){for(;;){let e=await Ca();if(e.state==="done"&&ci())return;if(e.state==="error")throw new La("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 yk(500)}}async function ly(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await oo.run({builtBy:"doc-init",force:e,quiet:!0})}async function Ak(){let n=await Ia()!==null;if(ci()&&!n)return;let e=dy({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await Cg()){await Ik(e),e.succeed("Documentation ready.");return}if(await md()){await ly(e),e.succeed("Documentation ready.");return}await ly(e,!0),e.succeed("Documentation ready.")}catch(t){throw e.fail(t.message),t}}async function io(){await no({mode:"read"}),await Ak()}function Dk(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 xd=class{async search(e,t,r=10){await io();try{return await Rd(e,t,r)}catch(o){if(!Dk(o))throw o;return ro(),await oo.run({builtBy:"doc-init",force:!0,quiet:!0,assumeStorageSafe:!0}),Rd(e,t,r)}}async readDocument(e){return await io(),ed(e)}},Oa=new xd;import IK from"adm-zip";import{unified as sK}from"unified";import cK from"remark-parse";import dK from"remark-gfm";import{toString as pK}from"mdast-util-to-string";async function Ld(n,e){let t=Date.now();try{let r=await e();return await uy(n,Date.now()-t,!0,null),r}catch(r){let o=r instanceof Error?r.code??r.name:"UnknownError";throw await uy(n,Date.now()-t,!1,o),r}}async function uy(n,e,t,r){await k.track(n,{duration_ms:e,success:t,error_code:r}).catch(()=>{})}function Od(n){console.error(Tk(Ok(n))),process.exitCode=1}function py(...n){return e=>{if(!n.includes(e))throw new Nd(`Allowed values: ${n.join(", ")}`);return e}}function xk(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new Nd("Must be a positive integer.");return e}var Nk=py("json","default"),Lk=py("json","default");function Ok(n){let e=n instanceof Error?n.message:String(n);return to(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 Ma=new kk("docs").description("Search and read HarmonyOS documentation from local docs directory");Ma.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",_k,"all").option("--format <fmt>","Output format (default, json)",Nk,"default").option("--limit <n>","Max number of results",xk,10).action(async(n,e)=>{let t=n.map(o=>o.trim()).filter(Boolean),r={event:E.DocOperation,subAction:"search",queryLen:t.join(" ").length,catalog:e.catalog??"all"};try{await Ld(r,async()=>{let o=Mk(n),i=e.catalog&&e.catalog!=="all"?e.catalog:void 0,s=await Oa.search(o,i,e.limit);e.format==="json"?console.log(JSON.stringify(s,null,2)):Fk(s)})}catch(o){Od(o)}});Ma.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{let e=n.trim(),t={event:E.DocOperation,subAction:"read",documentId:e};try{await Ld(t,async()=>{if(!e)throw new Error("Document ID cannot be empty.");let r=await Oa.readDocument(e);console.log(r)})}catch(r){Od(r)}});Ma.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",Lk,"default").action(async n=>{let e={event:E.DocOperation,subAction:"catalog",fmt:n.format??"default"};try{await Ld(e,async()=>{if(await io(),n.format==="json"){let t=Vt.map(r=>({name:r,title:wn[r]}));console.log(JSON.stringify(t,null,2))}else for(let t of Vt)console.log(` ${t.padEnd(20)} ${Rk(wn[t])}`)})}catch(t){Od(t)}});function Mk(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>Xr)throw new Error(`Query exceeds ${Xr} characters.`);return e}function _k(n){if(n==="all")return"all";if(!Vt.includes(n))throw new Nd(`Invalid catalog "${n}". Allowed: all, ${Vt.join(", ")}`);return n}function Fk(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 my=Ma;import{Command as WT}from"commander";import{Command as Yk,InvalidArgumentError as Kk,Option as _d}from"commander";import{readFileSync as $k,unlinkSync as Hk}from"fs";import{tmpdir as Uk}from"os";import{join as Bk}from"path";var zt=class{constructor(e,t){this.hdcPath=e;this.serial=t}hdcPath;serial;async listWindows(e){let t=await this.fetchDump(),r=jk(t);return e?.all||(r=r.filter(o=>o.type===1)),r}async fetchDump(){let e=["-t",this.serial,"shell","hidumper","-s","WindowManagerService","-a","-a"];h(`Executing: ${this.hdcPath} ${e.join(" ")}`);let t=await oe(this.hdcPath,e);if(t.exitCode!==0)throw new Error(`Failed to query windows: ${(t.stderr||t.stdout).trim()}`);return t.stdout}};function jk(n){let e=n.split(`
|
|
1363
|
+
`),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]),g=Number(c[2]),w=Number(c[3]),b=Number(c[4]);Number.isFinite(w)&&Number.isFinite(d)&&Number.isFinite(g)&&r.push({id:w,name:l,pid:g,displayId:d,type:b})}let o=e.find(s=>s.trim().startsWith("Focus window")),i=o?Number(o.replace(/.*:\s*/,"").trim()):NaN;return r.map(s=>({...s,focused:s.id===i}))}function fy(n){if(!(!n||n==="HitTestMode.Default"))return n.startsWith("HitTestMode.")?n.slice(12):n}function wi(n){if(!(n==null||n==="")){if(typeof n=="boolean")return n;if(n==="true")return!0;if(n==="false")return!1}}function hy(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 gy(n){return n.originalText||void 0}function so(n,e){let t=[],r=[...n].reverse();for(;r.length>0;){let o=r.pop();o.id===e&&t.push(o);for(let i=o.children.length-1;i>=0;i--)r.push(o.children[i])}return t}function yy(n,e){let t=[],r=[{current:n,parent:null,depth:0}];for(;r.length>0;){let{current:o,parent:i,depth:s}=r.pop(),a=i===null,c=!o.id&&!o.text&&!o.clickable&&!o.longClickable&&!o.scrollable&&!o.checkable,l=a||!c,d=i;if(l){let w={...o,children:[]};if(a?t.push(w):i.children.push(w),d=w,e>0&&s+1>=e)continue}if(process.env.DEVECO_CLI_DEBUG){let w=o.type?o.id?`${o.type}#${o.id}`:o.type:"#";h(`collapse ${w} depth=${s} -> ${a?"root":c?"collapsed":"emitted"}`)}let g=l?s+1:s;for(let w=o.children.length-1;w>=0;w--)r.push({current:o.children[w],parent:d,depth:g})}return t}function Wk(n){let e=$k(n,"utf-8").trim();if(!e)throw new Error("Empty dumpLayout response from device");return JSON.parse(e)}function Vk(n){return n.attributes??{}}function _a(n,e,t){let r=Vk(n),o={id:r.id||void 0,type:r.type||void 0,text:gy(r),bounds:hy(r.bounds),clickable:wi(r.clickable)||void 0,longClickable:wi(r.longClickable)||void 0,scrollable:wi(r.scrollable)||void 0,checkable:wi(r.checkable)||void 0,hitTestBehavior:fy(r.hitTestBehavior),children:[]};return e>0&&t+1>=e||n.children&&(o.children=n.children.map(i=>_a(i,e,t+1))),o}function Gk(n,e){if(e){let r=n.find(o=>String(o.id)===e);if(!r){let o=n.map(i=>`${i.id} (${i.name})`).join(", ");throw new v(`Window '${e}' not found. Available windows: ${o||"none"}`,"Window not found.")}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 ir=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 o=this.buildRemoteDumpPath(),i=["-t",e,"shell","uitest","dumpLayout","-p",o];r!==void 0&&i.push("-d",String(r)),t&&i.push("-w",t),h(`Executing: ${this.hdcPath} ${i.join(" ")}`);let s=await oe(this.hdcPath,i);if(s.exitCode!==0)throw new Error(`Failed to dump layout: ${(s.stderr||s.stdout).trim()}`);return this.recvAndParseDump(e,o)}async recvAndParseDump(e,t){let r=Bk(Uk(),`deveco_cli_dump_${Date.now()}_${process.pid}.json`);try{return await this.recvDumpFile(e,t,r),Wk(r)}finally{await this.cleanupDumpArtifacts(e,r,t)}}async recvDumpFile(e,t,r){let o=["-t",e,"file","recv",t,r];h(`Executing: ${this.hdcPath} ${o.join(" ")}`);let i=await oe(this.hdcPath,o);if(i.exitCode!==0)throw new Error(`Failed to recv dump file: ${(i.stderr||i.stdout).trim()}`)}async cleanupDumpArtifacts(e,t,r){try{h(`Removing local dump file: ${t}`),Hk(t)}catch(i){h(`Failed to clean local dump file ${t}: ${i.message}`)}let o=["-t",e,"shell","rm","-f",r];h(`Executing: ${this.hdcPath} ${o.join(" ")}`),await oe(this.hdcPath,o).catch(i=>{h(`Failed to clean remote dump file ${r}: ${i.message}`)})}async dumpRawNodes(e,t,r){let i=await new zt(this.hdcPath,e).listWindows({all:!0});if(r){let a=[...new Set(i.map(l=>l.displayId))],c=[];for(let l of a)c.push(await this.fetchRawDump(e,void 0,l));return c}let s=Gk(i,t);return[await this.fetchRawDump(e,String(s.id),s.displayId)]}async dumpFullTree(e,t,r,o){return(await this.dumpRawNodes(e,r,o)).map(s=>_a(s,t,0))}async dumpFullTreeByDisplays(e,t,r){let o=[];for(let i of r){let s=await this.fetchRawDump(e,void 0,i);o.push({displayId:i,tree:_a(s,t,0)})}return o}async dumpCollapsedTree(e,t,r,o){return(await this.dumpRawNodes(e,r,o)).flatMap(s=>yy(_a(s,0,0),t))}};var Fa={left:"0",right:"1",up:"2",down:"3"};function Re(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&&Re(n,e)}function wy(n,e){if(n===void 0!=(e===void 0))throw new Error("x and y must be provided together")}function ja(n,e){if(n!==void 0&&n.length===0)throw new Error(`${e} must not be empty`)}function vi(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 vy(n){if(n!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(n))throw new Error("--window must consist of letters, digits, - or _")}function Sy(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 ao(n,e,t,r,o=!0){wy(n,e),ja(t,"--id"),Md(n,"x"),Md(e,"y"),vy(r),Sy(n!==void 0,!!t,!!r,o)}async function In(n,e){let r=await new Lr(n).selectDevice(e);if(!r)throw new Error("No device selected. Use `devecocli device list` to see targets.");return r}async function Tt(n){let e=await I.new(),t=await In(e,n);return{hdcPath:e.hdcPath,deviceId:t}}async function co(n,e,t,r,o,i){if(t!==void 0&&r!==void 0)return{x:t,y:r};if(o===void 0)throw new Error("Either provide x y coordinates or use --id");let a=await new zt(n,e).listWindows({all:!0}),c=new ir(n);return zk(c,e,a,o,i)}async function zk(n,e,t,r,o){if(o!==void 0){let i=t.find(a=>String(a.id)===o);if(i&&i.displayId!==0)throw new v(`Window "${o}" is on display ${i.displayId}. The current command only supports operations on the primary display.`,"The current command only supports operations on the primary display.");let s=await n.dumpFullTree(e,0,o,!1);return Jk(s,r)}return qk(n,e,t,r)}async function qk(n,e,t,r){let o=[...new Set(t.map(a=>a.displayId))],i=await n.dumpFullTreeByDisplays(e,0,o),s=[];for(let{displayId:a,tree:c}of i)for(let l of so([c],r))s.push({node:l,displayId:a});if(s.length===0)throw new v(`Node "${r}" not found.`,"Node not found.");if(s.length>1)throw new v(`Multiple nodes found with id "${r}".`,"Multiple nodes found");if(s[0].displayId!==0)throw new v(`Node "${r}" is on display ${s[0].displayId}. The current command only supports operations on the primary display.`,"The current command only supports operations on the primary display.");return by(s[0].node,r)}function Jk(n,e){let t=so(n,e);if(t.length===0)throw new v(`Node "${e}" not found.`,"Node not found.");if(t.length>1)throw new v(`Multiple nodes found with id "${e}".`,"Multiple nodes found");return by(t[0],e)}function by(n,e){let t=n.bounds;if(!t)throw new v(`Node "${e}" has no bounds.`,"Node has no bounds.");let[r,o,i,s]=t;return{x:Math.ceil((r+i)/2),y:Math.ceil((o+s)/2)}}async function ot(n,e,t){let r=["-t",e,"shell",...t];h(`Executing: ${n} ${r.join(" ")}`);let o=await oe(n,r);if(o.exitCode!==0)throw new Error(o.stderr||o.stdout||`uitest exited with code ${o.exitCode}`);let i=o.stdout.toLowerCase();if(["illegal","fail","error","incorrect","please confirm that the coordinate values are correct"].some(a=>i.includes(a))&&!i.includes("no error"))throw new Error(o.stdout.trim()||"uitest command failed")}import Xk from"ora";function Zk(n){let e=parseInt(n,10);if(!Number.isInteger(e)||e<0||String(e)!==n.trim())throw new Kk("depth must be a non-negative integer");return e}function Qk(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 Ey(n,e=0){let t=[],r=" ".repeat(e);for(let o of n)t.push(`${r}${Qk(o)}`),o.children.length>0&&t.push(...Ey(o.children,e+1).split(`
|
|
1352
1364
|
`));return t.join(`
|
|
1353
|
-
`)}function
|
|
1354
|
-
`).trim()}function
|
|
1365
|
+
`)}function eT(n){if(n.allWindows&&n.window)throw new Error("--all-windows and --window are mutually exclusive.")}function tT(n,e){let t=so(n,e);if(t.length===0)throw new Error(`Node '${e}' not found.`);let r=t.map(o=>({...o,children:[]}));return JSON.stringify(r,null,2)}function nT(n,e){return e.id?tT(n,e.id):e.format==="json"?JSON.stringify(n,null,2):Ey(n)}async function rT(n){eT(n);let e=Xk({text:"Dumping layout\u2026",color:"cyan"}).start(),t;try{let o=await I.new(),i=await In(o,n.device),s=new ir(o.hdcPath);t=n.mode==="full"?await s.dumpFullTree(i,n.depth,n.window,n.allWindows):await s.dumpCollapsedTree(i,n.depth,n.window,n.allWindows)}catch(o){throw e.stop(),new Error(`Failed to dump layout: ${o.message}`,{cause:o})}e.stop();let r=nT(t,n);return console.log(r),Buffer.byteLength(r,"utf8")}function oT(n){return{event:E.CommandExecuted,args:["ui","layout",...n.device?["--device"]:[]],mode:n.mode,outputSize:0}}async function iT(n){let e=oT(n),t=Date.now(),r=!0,o=null;try{e.outputSize=await rT(n)}catch(i){throw r=!1,o=ce(i),i}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await k.track(e,i)}}var Py=new Yk("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 _d("--depth <n>","Tree depth limit (0=unlimited, 1=root only, 2=root+children)").argParser(Zk).default(0)).addOption(new _d("--format <format>","Output format").choices(["default","json"]).default("default")).addOption(new _d("--mode <mode>","Output mode: full | simplified").choices(["full","simplified"]).default("simplified")).action(async n=>{await iT(n)});import{Command as sT,Option as aT}from"commander";import{yellow as cT}from"colorette";import lT from"ora";var dT=["Id","Name","Pid","DisplayId","Focused"];function uT(n,e){if(e==="json"){let r=n.map(o=>({id:o.id,name:o.name,pid:o.pid,displayId:o.displayId,focused:o.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(Mt(dT,t))}async function pT(n){let e=lT({text:"Listing windows\u2026",color:"cyan"}).start(),t;try{let r=await I.new(),o=await In(r,n.device);t=await new zt(r.hdcPath,o).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(cT(" No windows found."));return}uT(t,n.format)}var Fd=new sT("window").description("Manage device windows");Fd.command("list").description("List windows on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new aT("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show all windows including system windows").action(async n=>{await pT(n)});import{Command as mT}from"commander";import $e from"fs";import it from"path";import{randomUUID as fT}from"crypto";import{green as hT}from"colorette";function gT(n){return{event:E.CommandExecuted,args:["ui","screenshot",...n.device?["--device"]:[]]}}function yT(){return String(Date.now())}function Cy(n){let e;try{e=$e.statSync(n)}catch(t){let r=t.code;throw r==="ENOENT"?new Error(`Screenshot directory does not exist: ${n}`,{cause:t}):r==="EACCES"||r==="EPERM"?new Error(`Screenshot directory is not writable: ${n}`,{cause:t}):new Error(`Invalid screenshot path: ${t.message}${r?` (${r})`:""}`,{cause:t})}if(!e.isDirectory())throw new Error(`Screenshot parent path is not a directory: ${n}`);try{$e.accessSync(n,$e.constants.W_OK|$e.constants.X_OK)}catch(t){throw new Error(`Screenshot directory is not writable: ${n}`,{cause:t})}}function Iy(n,e){try{throw $e.lstatSync(n),new Error(`Screenshot file already exists: ${n}`)}catch(t){let r=t.code;if(r==="ENOENT")return;throw r==="EACCES"||r==="EPERM"?new Error(`Screenshot directory is not writable: ${e}`,{cause:t}):t instanceof Error&&!r?t:new Error(`Invalid screenshot path: ${t.message}${r?` (${r})`:""}`,{cause:t})}}function wT(n){if(!n?.trim())throw new Error("--path is required.");let e=n.trim(),t=it.resolve(e);try{if($e.statSync(t).isDirectory()){Cy(t);let o=it.join(t,`screenshot-${yT()}.png`);return Iy(o,t),o}}catch(o){if(o.code!=="ENOENT")throw o}if(it.extname(t).toLowerCase()!==".png")throw new Error(`Screenshot path must be an existing directory or a PNG file: ${t}`);let r=it.dirname(t);return Cy(r),Iy(t,r),t}function Ay(n){if(!$e.existsSync(n))throw new Error(`Screenshot file was not created: ${n}`);let e=$e.statSync(n);if(!e.isFile()||e.size===0)throw new Error(`Screenshot file is empty: ${n}`);let t=$e.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}`)}function vT(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 ST(n){let e=n.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}function bT(n,e){try{$e.copyFileSync(n,e,$e.constants.COPYFILE_EXCL)}catch(t){throw t.code==="EEXIST"?new Error(`Screenshot file already exists: ${e}`,{cause:t}):t}Ay(e)}function ET(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 PT(n){let e=["-t",n.serial,"shell","ls","-l",n.remotePath];h(`Executing: ${n.hdcPath} ${e.join(" ")}`);let t=await oe(n.hdcPath,e);return t.exitCode===0?ET(t.stdout):void 0}function CT(n){return[n.stdout,n.stderr].filter(Boolean).join(`
|
|
1366
|
+
`).trim()}function IT(n){return n.replace(/(Tips:\s*supported\s+displayIds)\s*:?[ \t]*(?:\r?\n[ \t]*)?(\d+(?:(?:[ \t]*,[ \t]*|[ \t]+|\r?\n[ \t]*)\d+)*)/gi,(e,t,r)=>`${t}: ${r.match(/\d+/g)?.join(", ")??r}`)}function AT(n){let e=String.raw`invalid|not found|not exist|does not exist|out of range|unsupported`;return new RegExp(String.raw`display(?:\s*id)?.*(?:${e})`,"is").test(n)||new RegExp(String.raw`(?:${e}).*display(?:\s*id)?`,"is").test(n)}async function DT(n,e){let t=vT(n,e);h(`Executing: ${n.hdcPath} ${t.join(" ")}`);let r=await oe(n.hdcPath,t),o=await PT(n);return{created:o!==void 0&&o>0,output:IT(CT(r))}}async function kT(n){let e="";for(let t of[void 0,"png"]){let r=await DT(n,t);if(r.created)return;if(n.display!==void 0&&AT(r.output))throw new Error(`Screenshot was not created on device: ${n.remotePath}.
|
|
1355
1367
|
snapshot_display output:
|
|
1356
1368
|
${r.output}`);r.output&&(e=r.output)}throw new Error(e?`Screenshot was not created on device: ${n.remotePath}.
|
|
1357
1369
|
snapshot_display output:
|
|
1358
|
-
${e}`:`Screenshot was not created on device: ${n.remotePath}.`)}function
|
|
1370
|
+
${e}`:`Screenshot was not created on device: ${n.remotePath}.`)}function Dy(n){try{return Ay(n),!0}catch{return!1}}function ky(n){let e=[];for(let t of $e.readdirSync(n,{withFileTypes:!0})){let r=it.join(n,t.name);if(t.isDirectory()){e.push(...ky(r));continue}t.isFile()&&Dy(r)&&e.push(r)}return e}function TT(n,e){let t=it.join(n,it.basename(e));if(Dy(t))return t;let r=ky(n);if(r.length===1)return r[0];if(r.length>1)throw new Error(`Multiple screenshot files were received in ${n}.`)}async function jd(n,e,t){let r=["-t",n.serial,"file","recv",n.remotePath,t];h(`Executing: ${n.hdcPath} ${r.join(" ")}`);let o=await oe(n.hdcPath,r);return o.exitCode!==0&&h(`hdc file recv failed: ${o.stderr||o.stdout||`exit code ${o.exitCode}`}`),TT(e,n.remotePath)}async function RT(n){let e=$e.mkdtempSync(it.join(it.dirname(n.localPath),".devecocli-screenshot-"));try{let t=await jd(n,e,it.join(e,it.basename(n.remotePath)))??await jd(n,e,e)??await jd(n,e,it.join(e,"screenshot.png"));if(!t)throw new Error(`Screenshot file was not created in ${e}.`);bT(t,n.localPath)}finally{$e.rmSync(e,{recursive:!0,force:!0})}}async function xT(n){let e=["-t",n.serial,"shell","rm","-f",n.remotePath];h(`Executing: ${n.hdcPath} ${e.join(" ")}`),await oe(n.hdcPath,e)}async function NT(n){try{await kT(n),await RT(n)}finally{await xT(n)}}async function LT(n){let e=gT(n),t=Date.now(),r=!0,o=null;try{let i=wT(n.path),s=n.display!==void 0?ST(n.display):void 0;if(n.device!==void 0&&!n.device.trim())throw new Error("--device must not be empty.");let a=await I.new(),c=await In(a,n.device),l=`/data/local/tmp/devecocli-${fT()}.png`;await NT({hdcPath:a.hdcPath,serial:c,localPath:i,remotePath:l,display:s}),console.log(hT(`Screenshot saved to ${i}`))}catch(i){throw r=!1,o=ce(i),i}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await k.track(e,i)}}var Ty=new mT("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>","Required directory or PNG file path; destination must be writable").action(LT);import{Command as An}from"commander";function Dn(n,e){let t=[];return"device"in e&&e.device&&t.push("--device"),"id"in e&&e.id&&t.push("--id"),"window"in e&&e.window&&t.push("--window"),"speed"in e&&e.speed&&t.push("--speed"),{event:E.CommandExecuted,args:["ui",n,...t]}}function OT(n){let t=`"$(printf '%s' '${Buffer.from(n,"utf8").toString("base64")}' | base64 -d)"`;return h(`escapeShellText: ${n} -> ${t}`),t}async function kn(n,e,t,r){let o=new pt;o.start(n);let i=Date.now(),s=!0,a=null;try{await r(o)}catch(c){throw o.stop(),s=!1,a=ce(c),new Error(`${e}: ${c.message}`,{cause:c})}finally{let c={duration_ms:Date.now()-i,success:s,error_code:a};await k.track(t,c)}}async function MT(n,e,t){let r=Dn("click",t);await kn("Executing click...","click failed",r,async o=>{ao(n,e,t.id,t.window);let{hdcPath:i,deviceId:s}=await Tt(t.device),{x:a,y:c}=await co(i,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await ot(i,s,["uitest","uiInput","click",String(a),String(c)]),o.succeed(`click at (${a}, ${c})`)})}async function _T(n,e,t){let r=Dn("doubleclick",t);await kn("Executing doubleclick...","doubleclick failed",r,async o=>{ao(n,e,t.id,t.window);let{hdcPath:i,deviceId:s}=await Tt(t.device),{x:a,y:c}=await co(i,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await ot(i,s,["uitest","uiInput","doubleClick",String(a),String(c)]),o.succeed(`doubleclick at (${a}, ${c})`)})}async function FT(n,e,t){let r=Dn("longclick",t);await kn("Executing longclick...","longclick failed",r,async o=>{ao(n,e,t.id,t.window);let{hdcPath:i,deviceId:s}=await Tt(t.device),{x:a,y:c}=await co(i,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await ot(i,s,["uitest","uiInput","longClick",String(a),String(c)]),o.succeed(`longclick at (${a}, ${c})`)})}async function jT(n,e,t,r,o){let i=Dn("swipe",o);await kn("Executing swipe...","swipe failed",i,async s=>{Re(n,"x1"),Re(e,"y1"),Re(t,"x2"),Re(r,"y2");let a=vi(o.speed),{hdcPath:c,deviceId:l}=await Tt(o.device),d=["uitest","uiInput","swipe",n,e,t,r];a&&d.push(a),await ot(c,l,d),s.succeed(`swipe from (${n}, ${e}) to (${t}, ${r})`)})}async function $T(n,e,t,r,o){let i=Dn("fling",o);await kn("Executing fling...","fling failed",i,async s=>{Re(n,"x1"),Re(e,"y1"),Re(t,"x2"),Re(r,"y2");let a=vi(o.speed),{hdcPath:c,deviceId:l}=await Tt(o.device),d=["uitest","uiInput","fling",n,e,t,r];a&&d.push(a),await ot(c,l,d),s.succeed(`fling from (${n}, ${e}) to (${t}, ${r})`)})}async function HT(n,e,t,r,o){let i=Dn("drag",o);await kn("Executing drag...","drag failed",i,async s=>{Re(n,"x1"),Re(e,"y1"),Re(t,"x2"),Re(r,"y2");let a=vi(o.speed),{hdcPath:c,deviceId:l}=await Tt(o.device),d=["uitest","uiInput","drag",n,e,t,r];a&&d.push(a),await ot(c,l,d),s.succeed(`drag from (${n}, ${e}) to (${t}, ${r})`)})}async function UT(n,e){let t=Dn("dircfling",e);await kn("Executing dircfling...","dircfling failed",t,async r=>{let o=Fa[n];if(o===void 0)throw new Error(`Invalid direction "${n}". Valid values: ${Object.keys(Fa).join(", ")}`);let{hdcPath:i,deviceId:s}=await Tt(e.device);await ot(i,s,["uitest","uiInput","dircFling",o]),r.succeed(`dircfling ${n}`)})}async function BT(n,e,t,r){let o=Dn("text",r);await kn("Executing text input...","input failed",o,async i=>{ao(e,t,r.id,r.window,!1),ja(n,"text");let{hdcPath:s,deviceId:a}=await Tt(r.device),c=OT(n);if(e!==void 0)await ot(s,a,["uitest","uiInput","inputText",`${e}`,`${t}`,c]),i.succeed(`input ${n} at (${e}, ${t})`);else if(r.id){let{x:l,y:d}=await co(s,a,void 0,void 0,r.id,r.window);await ot(s,a,["uitest","uiInput","inputText",`${l}`,`${d}`,c]),i.succeed(`input ${n} at (${l}, ${d})`)}else await ot(s,a,["uitest","uiInput","text",c]),i.succeed(`input ${n}`)})}var Ry=new An("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(MT),xy=new An("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(_T),Ny=new An("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(FT),Ly=new An("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(jT),Oy=new An("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($T),My=new An("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(HT),_y=new An("dircfling").argument("<direction>","Direction: up, down, left, right").description("Fling in a specified direction").option("--device <name|serial>","Target device (name or serial)").action(UT),Fy=new An("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(BT);var st=new WT("ui").description("Inspect and interact with UI on a connected device");st.addCommand(Py);st.addCommand(Fd);st.addCommand(Ty);st.addCommand(Ry);st.addCommand(xy);st.addCommand(Ny);st.addCommand(Ly);st.addCommand(Oy);st.addCommand(My);st.addCommand(_y);st.addCommand(Fy);var jy=st;import{Command as yw,InvalidArgumentError as xx}from"commander";import{execa as mR}from"execa";import Rt from"fs";import*as Wd from"os";import*as j from"path";var VT=new RegExp("\x1B\\[[0-?]*[ -/]*[@-~]","g"),GT=/\r/g,zT=/^(Working|Finished)\.\.\.\[[^\]]*\]\d+%$/,qT=/^<+\s*/,JT=/\s*>+$/,YT=[/^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\.$/],KT=new Set([1]);function Hd(n){if(!n)return"";let e=n.replace(VT,"").replace(GT,`
|
|
1359
1371
|
`).split(`
|
|
1360
|
-
`).map(
|
|
1372
|
+
`).map(XT).map(t=>t.trimEnd()).filter(t=>QT(t));return e.length>0?`${e.join(`
|
|
1361
1373
|
`)}
|
|
1362
|
-
`:""}function
|
|
1363
|
-
[output truncated: exceeded ${
|
|
1364
|
-
`};if(
|
|
1365
|
-
`);if(t.length>1&&t.every(
|
|
1374
|
+
`:""}function XT(n){let e=n.trim();if(!e.startsWith("{"))return n;try{let t=JSON.parse(e);return typeof t.content!="string"||typeof t.messageType!="number"?n:KT.has(t.messageType)?"":t.content}catch{return n}}var $y=50*1024*1024;function Wy(n){let e=Hd(n).trim();if(!e)return{jsonText:void 0,diagnostics:""};if(e.length>$y)return{jsonText:void 0,diagnostics:`${e.slice(0,1024)}
|
|
1375
|
+
[output truncated: exceeded ${$y} bytes]
|
|
1376
|
+
`};if($d(e))return{jsonText:e,diagnostics:""};let t=e.split(`
|
|
1377
|
+
`);if(t.length>1&&t.every($d))return{jsonText:JSON.stringify(t.map(i=>JSON.parse(i))),diagnostics:""};let r=eR(e);if(!r)return{jsonText:void 0,diagnostics:`${e}
|
|
1366
1378
|
`};let o=[e.slice(0,r.start).trim(),e.slice(r.end).trim()].filter(Boolean).join(`
|
|
1367
1379
|
`);return{jsonText:e.slice(r.start,r.end),diagnostics:o?`${o}
|
|
1368
|
-
`:""}}function
|
|
1369
|
-
${
|
|
1370
|
-
`;let t=e===void 0?n.issues:n.issues.slice(0,e),r=[
|
|
1380
|
+
`:""}}function ZT(n){return zT.test(n.trim())}function QT(n){let e=n.trim();return!!e&&!ZT(e)&&!YT.some(t=>t.test(e))}function $d(n){try{return JSON.parse(n),!0}catch{return!1}}function eR(n){for(let e=0;e<n.length;e++){let t=n[e];if(t!=="["&&t!=="{")continue;let o=tR(n,e,t,t==="["?"]":"}");if(o!==-1&&$d(n.slice(e,o+1)))return{start:e,end:o+1}}}function tR(n,e,t,r){let o=0,i=!1,s=!1;for(let a=e;a<n.length;a++){let c=n[a];if(s){s=!1;continue}if(c==="\\"&&i){s=!0;continue}if(c==='"'){i=!i;continue}if(!i){if(c===t)o++;else if(c===r&&(o--,o===0))return a}}return-1}var Hy=["Error","Warning","Suggestion","Info","Off","Unknown"];function Vy(n){let e=Ud(n);return{issues:iR(e),summary:nR(n,e)}}function nR(n,e){let t=aR(e);return{filesChecked:cR(n).size,issues:e.length,errors:t.get("Error")??0,warnings:t.get("Warning")??0,suggestions:t.get("Suggestion")??0}}function Ud(n,e=""){if(Array.isArray(n))return n.flatMap(i=>Ud(i,e));if(!Gy(n))return[];let t=Si(n,["filePath","file","path"])??e,r=rR(n,t);if(r.length>0)return r;let o=oR(n,t);return o?[o]:[]}function rR(n,e){let t=["messages","defects","issues","results","files"];for(let r of t){let o=n[r];if(Array.isArray(o)){let i=o.flatMap(s=>Ud(s,e));if(i.length>0)return i}}return[]}function oR(n,e){let t=Si(n,["message","description","desc","detail"])??"",r=pR(Si(n,["rule","ruleId","ruleName"])),o=dR(n,["severity","level"]),i=Si(n,["filePath","file","path"])??e;if(!(!t&&!r&&o==="Unknown"))return{file:i,line:By(n,["line","reportLine"]),column:By(n,["column","reportColumn"]),severity:o,rule:r,message:t}}function iR(n){return[...n].sort((e,t)=>{let r=Uy(e.severity)-Uy(t.severity);return r===0?sR(e,t):r})}function sR(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 aR(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 cR(n){let e=new Set;return Bd(e,n,""),e}function Bd(n,e,t){if(Array.isArray(e)){for(let o of e)Bd(n,o,t);return}if(!Gy(e))return;let r=Si(e,["filePath","file","path"])??t;r&&n.add(r),lR(n,e,r)}function lR(n,e,t){let r=["messages","defects","issues","results","files"];for(let o of r){let i=e[o];if(Array.isArray(i))for(let s of i)Bd(n,s,t)}}function dR(n,e){for(let t of e){let r=n[t];if(typeof r=="string"||typeof r=="number")return uR(r)}return"Unknown"}function uR(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 pR(n){let e=n?.normalize("NFKC").trim();if(e)return e.replace(qT,"").replace(JT,"").toLowerCase()}function Uy(n){let e=Hy.indexOf(n);return e===-1?Hy.length:e}function Si(n,e){for(let t of e){let r=n[t];if(typeof r=="string")return r}}function By(n,e){for(let t of e){let r=n[t];if(typeof r=="number")return r}}function Gy(n){return typeof n=="object"&&n!==null}var Tn=class extends Error{code;constructor(e,t,r){super(t,r),this.name="ValidationError",this.code=e}},zy="deveco-codelinter-",qy=[".ets",".ts",".js"],fR="6.1.0",bi=class n{resolution;cwd;toolProvider;constructor(e,t){this.toolProvider=e,this.resolution=n.resolveWithToolProvider(e),this.cwd=t}static resolveProjectRoot(e){try{return J.discover(e).rootDir}catch{return e}}async check(e){let t=Rt.mkdtempSync(j.join(Wd.tmpdir(),zy)),r=j.join(t,"report.json");try{let o=n.resolveProjectRoot(this.cwd),i=this.resolveLintTarget(e.lintPath,o),s=this.resolveConfigPath(e.configPath,i),a=this.buildNativeArgs(e,i.path,s,r,t,i.projectRoot??o),c=await this.run(a),l=Wy(c.stdout),d=l.diagnostics+Hd(c.stderr);try{let g=this.readJsonReport(r,l.jsonText);return{exitCode:c.exitCode,diagnostics:d,report:Vy(g)}}catch(g){return{exitCode:c.exitCode,diagnostics:d,reportError:g}}}finally{this.removeTempDir(t)}}resolveLintTarget(e,t){let r=e?j.resolve(this.cwd,e):t,o=this.resolveRealPath(r,"Lint path"),i=Rt.statSync(o);if(!i.isFile()&&!i.isDirectory())throw new Tn("errorCode",`Lint path must be a file or directory: ${r}`);if(i.isFile()){let a=j.extname(o).toLowerCase();if(!qy.some(l=>l===a))throw new Error(`Unsupported lint file extension "${a||"<none>"}": ${o}. Supported extensions: ${qy.join(", ")}.`)}let s=this.discoverProjectRoot(o,i.isDirectory());if(e!==void 0&&s===void 0)throw new Tn("errorCode",`Lint path is not in a valid project directory (project-level build-profile.json5 not found or invalid): ${o}`);return{path:o,projectRoot:s}}resolveConfigPath(e,t){let r=e?j.resolve(this.cwd,e):j.join(t.projectRoot??this.cwd,"code-linter.json5"),o=this.resolveRealPath(r,"`--config-path`");if(!Rt.statSync(o).isFile())throw new Tn("errorCode",`--config-path must point to a file: ${r}`);if(t.projectRoot){let i=this.discoverProjectRoot(o,!1);if(i===void 0||j.relative(t.projectRoot,i)!=="")throw new Tn("errorCode",`\`--config-path\` must belong to the same project as the lint path. Lint project: ${t.projectRoot}; Config project: ${i??"not found"}.`)}return o}discoverProjectRoot(e,t){let r=t?e:j.dirname(e);try{return Rt.realpathSync(J.discover(r).rootDir)}catch{return}}resolveRealPath(e,t){try{return Rt.realpathSync(e)}catch(r){throw new Tn("errorCode",`${t} does not exist or cannot be resolved: ${e}`,{cause:r})}}buildNativeArgs(e,t,r,o,i,s){if(this.resolution.isLegacyStudioArgs)return this.buildLegacyNativeArgs(e,t,r,i,s);let a=["--config",r];return e.fix&&a.push("--fix"),e.incremental&&a.push("--incremental"),a.push("--product",e.product,"--format","json","--output",o,t),a}buildLegacyNativeArgs(e,t,r,o,i){let s=String(this.toolProvider.getMaxApiLevel()),a=this.toolProvider.getSdkPlatformVersion(),c=j.join(o,"check-paths.json");Rt.writeFileSync(c,JSON.stringify([t]),"utf8");let l=["--dir",c,"--isTooManyFiles","true","--config",r,"--product",e.product,"--sdkPath",this.toolProvider.sdkPath,"--sdkNumberVersion",s,"--sdkStringVersion",a,"--project",i,"--logPath",j.join(o,"codelinter.log"),"--workdir",j.dirname(this.toolProvider.codelinterPath),"--inIde","true"];return e.fix&&l.push("--fix","true"),e.incremental&&l.push("--incremental","true"),l}async run(e){let t=this.resolution.isLegacyStudioArgs?[this.resolution.argsPrefix[0],...e]:[...this.resolution.argsPrefix,...e],r=this.resolution.workingDirectory??this.cwd;this.prepareRuntimeDirectories(),h(`Executing: ${this.resolution.command} ${t.join(" ")}`),h(`[CodelinterAdapter] Working directory: ${r}`);let o=await mR(this.resolution.command,t,{cwd:r,env:this.resolution.env,stdout:"pipe",stderr:"pipe",reject:!1});return{exitCode:o.exitCode??1,stdout:o.stdout,stderr:o.stderr}}prepareRuntimeDirectories(){for(let e of this.resolution.runtimeDirectories??[])Rt.mkdirSync(e,{recursive:!0})}readJsonReport(e,t){let o=(Rt.existsSync(e)?Rt.readFileSync(e,"utf-8").trim():void 0)||t?.trim();if(!o)throw new Tn("errorCode","Native JSON report was not generated.");return JSON.parse(o)}removeTempDir(e){let t=j.resolve(e),r=j.resolve(Wd.tmpdir());!(t.startsWith(`${r}${j.sep}`)||t===r)||!j.basename(t).startsWith(zy)||Rt.rmSync(t,{recursive:!0,force:!0})}static resolveWithToolProvider(e){let t=n.getSource(e),r=e.toolchainRoot,o=e.codelinterPath,i=e.sdkPath,s=n.getPathEntries(e,t),a=t==="ide"?"DevEco Studio":"DevEco Command Line Tools",c=t==="ide"&&I.compareVersion(St(e.toolchainRoot)??"0.0.0",fR)<0,l={command:e.nodePath,argsPrefix:[o,i],env:{...process.env,PATH:[...s,process.env.PATH||""].join(j.delimiter),DEVECO_SDK_HOME:i},isLegacyStudioArgs:c};return t==="command-line-tools"&&(l.workingDirectory=r,l.runtimeDirectories=[n.getResultDirectory(o)]),h(`[CodelinterAdapter] Selected ${a} entry: ${o}`),l}static getPathEntries(e,t){let r=[j.dirname(e.nodePath)];return t==="ide"&&e.javaPath&&r.unshift(j.dirname(e.javaPath)),r}static getResultDirectory(e){return j.resolve(e,"..","linter","result")}static getSource(e){return e.sourceType==="studio"?"ide":"command-line-tools"}};import{red as Ha,yellow as nw}from"colorette";import{Argument as IR,Command as AR,InvalidArgumentError as xn}from"commander";import Pi from"fs";import*as He from"path";import*as Ei from"path";var Jy="n/a",Yy=/\\/g,hR=/\|/g,gR=/\r?\n/g;function Ky(n,e){if(n.issues.length===0)return`No defects found.
|
|
1381
|
+
${Vd(n.summary)}
|
|
1382
|
+
`;let t=e===void 0?n.issues:n.issues.slice(0,e),r=[wR(t),Vd(n.summary)];return e!==void 0&&t.length<n.issues.length&&r.push(yR(n.issues.length,t.length)),`${r.join(`
|
|
1371
1383
|
`)}
|
|
1372
|
-
`}function
|
|
1373
|
-
`)}function
|
|
1374
|
-
`)}function
|
|
1375
|
-
`}function
|
|
1376
|
-
`)}function
|
|
1377
|
-
`))}}var
|
|
1378
|
-
`?(t.push(r),e.push(t),t=[],r="",i+=1):(s==="\r"||(r+=s),i+=1)}return(r.length>0||t.length>0)&&(t.push(r),e.push(t)),e}function
|
|
1384
|
+
`}function Xy(n,e){return[Vd(n.summary),`Full report: ${Gd(e)}`,""].join(`
|
|
1385
|
+
`)}function Zy(n){let e=["# CodeLinter report",""];return n.issues.length===0?e.push("No defects found.",""):e.push(...vR(n.issues),""),e.push("## Summary","",...bR(n.summary),""),e.join(`
|
|
1386
|
+
`)}function Qy(n){return`${JSON.stringify(n,null,2)}
|
|
1387
|
+
`}function Vd(n){return`Summary: Issues: ${at(n.issues)} | Errors: ${at(n.errors)} | Warnings: ${at(n.warnings)} | Suggestions: ${at(n.suggestions)} | Files checked: ${at(n.filesChecked)}`}function yR(n,e){return`Showing ${at(e)} of ${at(n)} issues. Use --output-path <path> to write all results.`}function wR(n){let e=["No","File","Line","Column","Severity","Rule","Message"],t=n.map((r,o)=>({cells:PR(r,o+1)}));return["CodeLinter report","",Mt(e,t)].join(`
|
|
1388
|
+
`)}function vR(n){let e=["| No | File | Line | Column | Severity | Rule | Message |","| ---: | --- | ---: | ---: | --- | --- | --- |"];for(let[t,r]of n.entries())e.push(SR(r,t+1));return e}function SR(n,e){return`| ${[String(e),Gd(Rn(n.file)),$a(n.line),$a(n.column),Rn(n.severity),Rn(n.rule),Rn(n.message)].map(ER).join(" | ")} |`}function bR(n){return[`- Issues: ${at(n.issues)}`,`- Errors: ${at(n.errors)}`,`- Warnings: ${at(n.warnings)}`,`- Suggestions: ${at(n.suggestions)}`,`- Files checked: ${at(n.filesChecked)}`]}function ER(n){return n.replace(Yy,"\\\\").replace(hR,"\\|").replace(gR,"<br>")}function PR(n,e){return[String(e),Gd(Rn(CR(n.file))),$a(n.line),$a(n.column),Rn(n.severity),Rn(n.rule),Rn(n.message)]}function CR(n){if(!Ei.isAbsolute(n))return n;let e=Ei.relative(process.cwd(),n);return!e||e.startsWith("..")||Ei.isAbsolute(e)?n:e}function Gd(n){return n.replace(Yy,"/")}function Rn(n){let e=n?.trim();return e||Jy}function $a(n){return n===void 0?Jy:String(n)}function at(n){return n.toLocaleString("en-US")}var zd=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function DR(n){let e=n;return n instanceof zd?n.code:e.code??e.name??"UnknownError"}async function ew(n,e,t,r){let o=await Pt(process.pid),i=o!==null?Ie(Number(o)*1024):"unknown",s={event:E.CheckCommand,args:r,mcpMemory:i,lspMemory:"unknown"},a={duration_ms:Date.now()-n,success:e,error_code:t};await k.track(s,a).catch(()=>{})}var kR=/^-?\d+$/,tw="6.1.0";function qd(){return new AR("lint").description("Run DevEco Code Linter checks for TS/ArkTS code").helpOption("-h, --help","display help for command").addArgument(new IR("[path]","File or directory to lint").argParser(LR)).option("--fix","Auto-fix fixable code issues").option("--incremental","Only check uncommitted files").option("--config-path <path>","Path to lint configuration file",RR).option("--product <product>","Product name defined in build-profile.json5",xR,"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",OR).action(MR)}function TR(n){if(n==="default"||n==="json")return n;throw new xn("Invalid --format. Expected one of: default, json.")}function RR(n){Jd(n,"--config-path");let e=He.extname(n).toLowerCase();if(e!==".json"&&e!==".json5")throw new xn("`--config-path` must point to a .json or .json5 file.");return n}function xR(n){return rw(n,"product"),n}function NR(n){return Jd(n,"--output-path"),n}function LR(n){return Jd(n,"path"),n}function OR(n){if(rw(n,"limit"),!kR.test(n))throw new xn("`--limit` must be a positive integer.");let e=Number.parseInt(n,10);if(e<=0||!Number.isSafeInteger(e))throw new xn("`--limit` must be an integer greater than 0.");return e}function rw(n,e){if(n.trim().length===0||sw(n))throw new xn(`Invalid --${e} value.`)}function Jd(n,e){let t=`\`${e}\``;if(n.length===0||sw(n))throw new xn(`${t} must be a non-empty path without control characters.`)}async function MR(n,e,t){let r=Date.now(),o=["check","lint"];try{let i=process.cwd(),s=await I.new(),a=jR(s,t,e),c=BR(a.outputPath,a.format,i);e.fix&&console.warn(nw("Running codelinter with --fix. Ensure your project source is trusted."));let l=await _R(s,n,e,i);qR(l.diagnostics),process.exitCode=HR(l,c,a.format,e.limit,i),await ew(r,!0,null,o)}catch(i){let s=DR(i);throw await ew(r,!1,s,o),i}}async function _R(n,e,t,r){let o=new bi(n,r);return $R(o,{lintPath:e,configPath:t.configPath,product:t.product,fix:t.fix,incremental:t.incremental})}function FR(n){return[["format","--format"],["outputPath","--output-path"]].filter(([e])=>n.getOptionValueSource(e)==="cli").map(([,e])=>e)}function jR(n,e,t){let r=FR(e);if(r.length===0||n.sourceType!=="studio")return t;let o=St(n.toolchainRoot);if(o&&I.compareVersion(o,tw)>=0)return t;let i=r.length===1?"option":"options";return console.warn(nw(`Warning: The detected DevEco Studio version is: ${o??"unknown"}. Unsupported ${i}: ${r.join(", ")}. Minimum supported version: ${tw}. Action: ignore the unsupported ${i} and continue the lint check with default terminal output.`)),{format:r.includes("--format")?"default":t.format,outputPath:r.includes("--output-path")?void 0:t.outputPath}}async function $R(n,e){let t=new pt;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,o){if(!n.report)return console.error(Ha("Failed to generate Code Linter report.")),console.error(Ha(n.reportError?.message??"Native JSON report was not generated.")),n.exitCode===0?1:n.exitCode;try{if(e){UR(e,t,n.report);let i=iw(e,o);process.stdout.write(Xy(n.report,i))}else process.stdout.write(Ky(n.report,r));return n.exitCode}catch(i){return console.error(Ha("Failed to generate Code Linter report.")),console.error(Ha(i.message)),n.exitCode===0?1:n.exitCode}}function UR(n,e,t){Pi.mkdirSync(He.dirname(n),{recursive:!0});let r=e==="json"?Qy(t):Zy(t);try{Pi.writeFileSync(n,r,{encoding:"utf-8",flag:"wx"})}catch(o){throw o.code==="EEXIST"?new Error(`Output file already exists: ${n}`,{cause:o}):o}}function BR(n,e,t){if(!n)return;let r=GR(n,t),o=VR(n,r),i=o?He.join(r,zR(e)):r;if(o||WR(n,e),Pi.existsSync(i))throw new xn(`Output file already exists: ${iw(i,t)}`);return i}function WR(n,e){let t=ow(e);if(He.extname(n).toLowerCase()!==t)throw new xn(`--output-path must use the ${t} extension for --format ${e}.`)}function VR(n,e){return Pi.existsSync(e)?Pi.statSync(e).isDirectory():n.endsWith("/")||n.endsWith("\\")||He.extname(n)===""}function GR(n,e){return He.resolve(e,n)}function zR(n){let e=new Date,t=[e.getFullYear(),e.getMonth()+1,e.getDate()].map((i,s)=>String(i).padStart(s===0?4:2,"0")).join(""),r=[e.getHours(),e.getMinutes(),e.getSeconds()].map(i=>String(i).padStart(2,"0")).join(""),o=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${r}-${o}${ow(n)}`}function ow(n){return n==="json"?".json":".md"}function iw(n,e){let t=He.relative(e,n);return t&&!t.startsWith("..")&&!He.isAbsolute(t)?t:n}function qR(n){n&&process.stderr.write(n)}function sw(n){for(let e of n){let t=e.charCodeAt(0);if(t<=31||t===127)return!0}return!1}import{InvalidArgumentError as JR}from"commander";import*as z from"path";import*as Yd from"os";import{readdirSync as YR,existsSync as Ua,readFileSync as KR,unlinkSync as XR,copyFileSync as dw,writeFileSync as uw}from"fs";import{execa as ZR}from"execa";import{cyan as ge,yellow as pw}from"colorette";import QR from"ora";var Q=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function Kd(n){let e=n;return n instanceof Q?n.code:e.code??e.name??"UnknownError"}async function lo(n,e,t,r){let o=await Pt(process.pid),i=o!==null?Ie(Number(o)*1024):"unknown",s={event:E.CheckCommand,args:r,mcpMemory:i,lspMemory:"unknown"},a={duration_ms:Date.now()-n,success:e,error_code:t};await k.track(s,a).catch(()=>{})}var ex=["default","csv","json"],aw=["default","json"];function tx(n){return[...n].sort((e,t)=>{let r=cw(e),o=cw(t);return r.apiVersion-o.apiVersion||r.suffix.localeCompare(o.suffix)})}function cw(n){let e=n.match(/\((\d+)\)/),t=e?Number(e[1]):0,r=n.lastIndexOf("_"),o=r>=0?n.slice(r+1):n;return{apiVersion:t,suffix:o}}function mw(n){let t=YR(n,{withFileTypes:!0}).filter(r=>r.isFile()&&r.name.toLowerCase().endsWith(".json")).map(r=>r.name.slice(0,-5));return tx(t)}async function fw(n){if(n=n===void 0?"default":n,!aw.includes(n))throw new Error(`--format must be ${aw.join(" or ")}. got "${n}"`);let e=Date.now(),t=["check","compat","versions"];try{let r=await I.new(),{apiChangeDir:o}=r.getApiscanPaths();h(ge(`[compat:versions] apiChangeDir: "${o}"`));let i=mw(o);if(n==="json")console.log(JSON.stringify({versions:i,count:i.length},null,2));else{if(i.length===0){console.log("No SDK versions available."),await lo(e,!0,null,t);return}console.log(i.join(`
|
|
1389
|
+
`))}await lo(e,!0,null,t)}catch(r){let o=Kd(r);throw await lo(e,!1,o,t),r}}var lw=new Set([".ets",".c",".cpp"]);function nx(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 o=n.profile.modules.map(s=>s.name).join(", "),i=r.length>1?"are":"is";throw new Q("errorCode",`Module ${r.map(s=>`"${s}"`).join(", ")} ${i} not defined in build-profile.json5. Available modules: ${o}.`)}function rx(n){for(let e of n){let t=z.resolve(e);if(!Ua(t))throw new Q("errorCode",`File "${e}" does not exist.`);let r=z.extname(t).toLowerCase();if(!lw.has(r)){let o=Array.from(lw).join(", ");throw new Q("errorCode",`Unsupported file extension "${r}" for "${e}". Supported: ${o}.`)}}}function ox(n){let e=[],t=[];for(let r of n)z.extname(r).toLowerCase()===".ets"?e.push(r):t.push(r);return{arkTs:e,cpp:t}}function ix(n){let e=[],t=[],r="",o=!1,i=0;for(;i<n.length;){let s=n[i];o?{field:r,inQuotes:o,i}=sx(n,i,s,r,o):s==='"'?(o=!0,i+=1):s===","?(t.push(r),r="",i+=1):s===`
|
|
1390
|
+
`?(t.push(r),e.push(t),t=[],r="",i+=1):(s==="\r"||(r+=s),i+=1)}return(r.length>0||t.length>0)&&(t.push(r),e.push(t)),e}function sx(n,e,t,r,o){return t!=='"'?{field:r+t,inQuotes:o,i:e+1}:n[e+1]==='"'?{field:r+'"',inQuotes:o,i:e+2}:{field:r,inQuotes:!1,i:e+1}}function ax(n,e){return e.map(t=>{let r=o=>{let i=n.indexOf(o);return i>=0&&i<t.length?t[i]:""};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 cx(n){let e=KR(n,"utf8"),t=e.startsWith("\uFEFF")?e.slice(1):e,r=ix(t);if(r.length<2)return[];let[o,...i]=r;return ax(o,i)}function lx(n,e){let t=n.match(/CSV saved to:\s*([^\r\n]+\.csv)/);if(!t)return null;let r=t[1].trim();if(z.isAbsolute(r))return r;let o=z.join(e,r);return C.ensurePathWithinRoot(e,o)}function dx(n,e){let t=new Map;for(let i of n){let s=i.changeType||"(unknown)";t.set(s,(t.get(s)??0)+1)}let r=Array.from(t.entries()).sort((i,s)=>s[1]-i[1]||i[0].localeCompare(s[0])),o=Math.max(5,...r.map(([i])=>i.length));console.log(ge("API change scan summary:")),console.log(` ${"Total".padEnd(o)} ${n.length}`);for(let[i,s]of r)console.log(` ${i.padEnd(o)} ${s}`);e&&console.log(` ${"Report".padEnd(o)} ${e}`)}function ux(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(ge(`Details (showing ${t.length}${r>0?` of ${n.length}`:""}):`));let o=[["Title","title"],["Language","language"],["ChangeId","changeId"],["Changed in","changedInSdk"],["Affected Versions","affectedVersions"],["Code Location","codeLocation"]],i=Math.max(...o.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 o)console.log(` ${c.padEnd(i)} ${s(a[l])}`)}r>0&&console.log(pw(` ... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function px(n,e){let t=n.slice(0,e),r=n.length-t.length;console.log(),console.log(JSON.stringify({records:t,count:n.length},null,2)),r>0&&console.log(pw(`... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function mx(n,e){let t=[];for(let r of e){let o=n.profile.modules.find(i=>i.name===r);if(!o)throw new Q("errorCode",`Module "${r}" not found in build-profile.json5.`);t.push(z.resolve(n.rootDir,o.srcPath))}return t}function fx(n,e,t,r){if(!r.sourceVersion||!r.targetVersion)throw new Q("errorCode","source-version and target-version are required.");let o=[n,"--startVersion",r.sourceVersion,"--endVersion",r.targetVersion];if(e.length>0){let{arkTs:i,cpp:s}=ox(e),a=d=>z.resolve(process.cwd(),d),c=i.map(a),l=s.map(a);c.length>0&&o.push("--arkTsFiles",c.join(",")),l.length>0&&o.push("--cppFiles",l.join(","))}else if(r.modules&&r.modules.length>0){let i=mx(t,r.modules);o.push("--modulePaths",i.join(","))}else o.push("--projectPath",t.rootDir);return o.push("--outputPath",Yd.tmpdir()),o}async function hx(n,e){let t=z.dirname(e[0]);try{let o=(await ZR(n.nodePath,e,{cwd:t,stdin:"ignore",stdout:"pipe",stderr:"inherit"})).stdout;return process.env.DEVECO_CLI_DEBUG&&(console.log(ge("[compat:check] === scan stdout ===")),process.stdout.write(o),o.endsWith(`
|
|
1379
1391
|
`)||process.stdout.write(`
|
|
1380
|
-
`),console.log(
|
|
1392
|
+
`),console.log(ge("[compat:check] === end stdout ==="))),o}catch(r){let o=r;process.env.DEVECO_CLI_DEBUG&&o.stdout&&(console.log(ge("[compat:check] === scan stdout (on error) ===")),process.stdout.write(o.stdout),o.stdout.endsWith(`
|
|
1381
1393
|
`)||process.stdout.write(`
|
|
1382
|
-
`),console.log(
|
|
1383
|
-
${o.stderr}`:""));throw o.stdout&&(i.stdout=o.stdout),i}}function
|
|
1384
|
-
Run \`devecocli compat versions\` to see all available versions.`)}if(n.sourceVersion&&n.targetVersion){let r=e.indexOf(n.sourceVersion),o=e.indexOf(n.targetVersion);if(r>=o)throw new
|
|
1385
|
-
`}function Ak(n,e,t,r){r===".csv"?iy(n,t):sy(t,dy(e),"utf8"),m(de(`[compat:check] saved report: "${t}"`))}function Dk(n,e,t,r){if(r==="json"){let i=V.basename(n,".csv"),s=V.join(t,`${i}.json`);return sy(s,dy(e),"utf8"),m(de(`[compat:check] saved report: "${s}"`)),s}let o=V.join(t,V.basename(n));return iy(n,o),m(de(`[compat:check] saved report: "${o}"`)),o}async function Rk(n,e){let t=new Ue(n,process.cwd(),!0),r=e.modules&&e.modules.length>0?e.modules[0]:void 0;try{await t.compileNative("default",r)}catch(o){throw new Error(`hvigorw compileNative failed (module=${r??"<project>"}): `+o.message,{cause:o})}}async function kk(n,e){yk(n,e);let t=G.discover(process.cwd());e.modules&&e.modules.length>0&&rk(t,e.modules),n.length>0&&ok(n);let r=await I.new(),{apiChangeDir:o,scriptPath:i}=r.getApiscanPaths();m(de(`[compat:check] script: "${i}"`));let s=cy(o);wk(e,s),e.outputPath&&m(de(`[compat:check] outputPath: "${e.outputPath}"`));let a=Ck(e.outputPath,e.format);return m(de(`[compat:check] outputTarget: ${a.kind}`)),Ik(a),{project:t,scriptPath:i,target:a,toolProvider:r}}async function uy(n,e){let{project:t,scriptPath:r,target:o,toolProvider:i}=await kk(n,e),s=ek({text:"Running compatibility check...",color:"cyan"}).start();try{await Rk(i,e);let a=hk(r,n,t,e);Sk(r,a);let c=await gk(i,a),l=dk(c,vd.tmpdir());if(!l)throw new Error("Scanner output format unexpected: missing report path.");m(de(`[compat:check] tmp csv: "${l}"`));let d=lk(l),g=null;if(o.kind==="file")Ak(l,d,o.filePath,o.ext),g=o.filePath;else if(o.kind==="dir")g=Dk(l,d,o.dirPath,e.format);else if(o.kind!=="none")throw new Error(`Unexpected output target kind: ${o.kind}`);Ek(l),s.stop(),vk(d,g,e.format,e.limit,o.kind)}catch(a){throw s.fail("Compatibility check failed"),a}}function xk(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new Tk(`--limit must be a positive integer (got "${n}")`);return e}function Nk(){let n=process.argv;for(let e=0;e<n.length;e++){if(n[e]==="--format"&&e+1<n.length)return n[e+1];if(n[e].startsWith("--format="))return n[e].slice(9)}}var Sd=new py("compat").description("Compatibility checking utilities.");Sd.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.',"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)",xk,100).action(async(n,e)=>{await uy(n,e)});Sd.command("versions").description("List all available target SDK versions for compatibility checking").option("--format <format>","Output format: default or json").action(async()=>{await ly(Nk())});var Lk=new py("check").description("Run DevEco project checks").addCommand(Sd).addCommand(yd()),fy=Lk;import{Command as Ex}from"commander";import{green as Wd,red as bx}from"colorette";import Vd from"fs";import Xy from"path";import Zy from"json5";import{readFileSync as cT}from"fs";import{join as Ok}from"path";var X={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"},Le={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:Ok(".ohos","config"),DOWNLOAD_CONNECT_TIMEOUT_MS:5e3},ue={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"},at={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."},ee={TOOLCHAIN_INIT_FAILED:"Auto-sign failed: unable to initialize toolchain",LOGIN_REQUIRED:"Failed to automatically generate signatures.Run devecocli auth login to sign in.",TEAM_INFO_FAILED:"Failed to obtain user team information.Check the network connection, HTTP proxy, and other configurations.",REALNAME_REQUIRED:"Users without real-name verification are not supported.Complete real-name verification in AppGallery Connect.",SESSION_EXPIRED:"User session expired or token invalid. Please login again.",REGION_CHINA_ONLY:"This feature is only available for accounts registered in Chinese mainland.",DEVICE_MISSING:"Unable to create the profile file due to missing devices.Connect a device through IP or USB, or manually add a device in AppGallery Connect first.If you are installing the HAP package on an emulator, you can skip the signing step.",DEVICE_DETECT_FAILED:"Unable to detect devices. Please check hdc status. If installing HAP on an emulator, signature step can be skipped.",PROJECT_DIR_MISSING:"Not in a valid project directory (project-level build-profile.json5 not found).",ATOMIC_SERVICE_UNSUPPORTED:"AtomicService projects are not yet supported. Please configure signing manually."};function Sa(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}function Ed(n){let e=n.replace(Le.TEAM_ID_INVALID_CHARS,"");return`${Le.CERT_NAME_PREFIX}${e}.cer`}function zr(n,e,t){if(n===at.FORBIDDEN)return e===ue.OPENPROXY_BLOCKED_URL?new Error(v.ERR_CERT_NETWORK_ERROR):new Error(v.ERR_FORBIDDEN);if(n===at.UNAUTHORIZED)return new Error(v.ERR_UNAUTHORIZED);if(t.includes(ue.USER_NOT_HARMONY_CODE))return new Error(v.ERR_USER_NOT_HARMONY);if(t.includes(ue.CERT_LIMIT_CODE))return new Error(v.ERR_CERT_LIMIT_REACHED);let r=Mk(t);return new Error(r??v.ERR_DOWNLOAD_CER)}function Mk(n){let e=my(n);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let r=typeof t=="string"?my(t):t;if(r&&typeof r=="object"){let o=r.msg;if(typeof o=="string"&&o.trim()!=="")return o}return null}function my(n){try{return JSON.parse(n)}catch{return null}}function bd(n){return JSON.parse(n)}async function hy(n){let e=`${X.BASE_URL}${X.CERT_LIST_PATH}`,t=await x.postAllowFailure(e,{headers:Sa(n)});if(t.statusCode!==200)throw zr(t.statusCode,t.statusText,t.data);return bd(t.data)?.certList??[]}async function Ea(n,e){return(await hy(n)).find(r=>r.certName===e)??null}async function Pd(n,e){let t=`${X.BASE_URL}${X.CERT_DELETE_PATH}`,r=await x.deleteAllowFailure(t,{headers:Sa(n),params:{certIds:[e]}});if(r.statusCode!==200)throw zr(r.statusCode,r.statusText,r.data);return bd(r.data)?.ret?.code===0}async function Cd(n,e,t){let r=`${X.BASE_URL}${X.CERT_ADD_PATH}`,o={csr:e,certName:t,certType:Le.CERT_TYPE_DEBUG},i=await x.postAllowFailure(r,{headers:Sa(n),params:o});if(i.statusCode!==200)throw zr(i.statusCode,i.statusText,i.data);if(!i.data.includes(ue.SUCCESS_MARKER))throw zr(void 0,i.statusText,i.data)}async function Id(n,e){let t=`${X.BASE_URL}${X.CERT_DOWNLOAD_URL_PATH}`,r=await x.postAllowFailure(t,{headers:Sa(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw zr(r.statusCode,r.statusText,r.data);return bd(r.data)?.urlsInfo?.[0]??null}import{mkdirSync as _k,writeFileSync as Fk,existsSync as jk}from"fs";import{dirname as $k}from"path";import{createHash as Hk}from"crypto";function Uk(n){let e;try{e=new URL(n)}catch{throw new Error(`Invalid download URL: ${JSON.stringify(n)}`)}if(e.protocol!=="https:")throw new Error(`Download URL must use HTTPS: ${e.protocol}`);let t=e.hostname.toLowerCase();if(t==="localhost"||t==="127.0.0.1"||t==="::1"||t.startsWith("169.254.")||t.startsWith("10.")||t.startsWith("192.168.")||/^172\.(1[6-9]|2\d|3[0-1])\./.test(t)||t.endsWith(".internal")||t.endsWith(".local"))throw new Error(`Download URL points to internal/private address: ${t}`)}async function si(n,e,t){Uk(n);let{statusCode:r,statusText:o,buffer:i}=await x.getBinaryAllowFailure(n,{timeout:Le.DOWNLOAD_CONNECT_TIMEOUT_MS});if(r!==200)throw r===at.FORBIDDEN&&o===ue.OPENPROXY_BLOCKED_URL?new Error(v.ERR_CERT_NETWORK_ERROR):new Error(v.ERR_DOWNLOAD_CER);if(t){let a=Hk("sha256").update(i).digest("hex");if(a!==t.toLowerCase())throw new Error(`SHA-256 mismatch for ${e}: expected ${t.toLowerCase()}, got ${a}`)}let s=$k(e);jk(s)||_k(s,{recursive:!0}),Fk(e,i)}import iT from"fs/promises";import{readFileSync as sT}from"fs";import ba from"path";import wy from"crypto";import Bk from"os";import ai from"fs/promises";var vy={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},gy=["ECC","RSA"],yy=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],Wk={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},Vk=8,Ad=64,Gk=/[\\/:*?"<>|=-]/g,ct={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function zk(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>Ad)throw new Error(`The length of keyAlias cannot exceed ${Ad}`);if(!gy.includes(n.keyAlg))throw new Error(`Invalid key algorithm ${n.keyAlg}, available: ${gy.join(" / ")}`);let e=Wk[n.keyAlg];if(!e.includes(n.keySize))throw new Error(`Key algorithm ${n.keyAlg} does not support size ${n.keySize}, available: ${e.join(", ")}`)}function qk(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(!yy.includes(n.signAlg))throw new Error(`Invalid sign algorithm ${n.signAlg}, available: ${yy.join(" / ")}`)}function Yk(n){return wy.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function Jk(n){let e=n?.trim()??"";return e&&e.replace(Gk,"_").replace(/\.+/g,"_").slice(0,Ad)||ct.productName}async function Sy(){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=ba.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");try{await ai.access(r)}catch(o){throw new Error(`Sign tool jar not found: ${r}`,{cause:o})}return{javaPath:e,jarPath:r}}async function Kk(n){let{javaPath:e,jarPath:t}=await Sy(),r=["-jar",t,vy.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 o=r.map((i,s)=>s>0&&["-keyPwd","-keystorePwd"].includes(r[s-1])?"******":i);return f.debug("generate-keypair \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),[e,...r]}async function Xk(n){let{javaPath:e,jarPath:t}=await Sy(),r=["-jar",t,vy.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 o=r.map((i,s)=>s>0&&["-keyPwd","-keystorePwd"].includes(r[s-1])?"******":i);return f.debug("generate-csr \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),[e,...r]}async function Zk(n){f.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),zk(n);let e=await Kk(n),t=await no(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 Qk(n){f.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),qk(n);let e=await Xk(n),t=await no(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 eT(n=Vk){return wy.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function tT(){let n=Bk.homedir();try{await ai.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=ba.join(n,".ohos","config");try{await ai.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 ye(n,e,t){let r=Jk(n),o=ba.basename(e),i=Yk(e),s=`${r}_${o}_${i}=.${t}`,a=await tT();return ba.join(a,s)}function nT(n){let e;try{e=G.discover(n).rootDir}catch(t){throw new Error(`Current directory ${n} is not a valid project root`,{cause:t})}return e}async function rT(n){try{await ai.access(n)}catch(e){throw new Error(`Project directory ${n} is not accessible, missing read/write permissions`,{cause:e})}}async function oT(n){try{await ai.access(n)}catch(e){throw new Error(`P12 file ${n} does not exist, terminating CSR generation.`,{cause:e})}}async function Dd(n,e,t){let r=process.cwd(),o=nT(r);await rT(o),f.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${o}`);let i=eT(),s=await ye(n??"",o,"p12"),a=await ye(n??"",o,"csr");return console.log("Start generating p12"),await Zk({keyAlias:e?.keyAlias??ct.keyAlias,keyPwd:i,keyAlg:e?.keyAlg??ct.keyAlg,keySize:e?.keySize??ct.keySize,keystoreFile:s,keystorePwd:i}),await oT(s),console.log("Start generating csr"),await Qk({subject:t?.subject??ct.csrSubject,outFile:a,keyAlias:t?.keyAlias??ct.keyAlias,keyPwd:i,signAlg:t?.signAlg??ct.signAlg,keystoreFile:s,keystorePwd:i}),{p12FilePath:s,csrFilePath:a,keyPwd:i,keyAlias:e?.keyAlias??ct.keyAlias}}var aT=["p12","cer","csr","p7b"];async function Rd(n,e){for(let t of aT){let r=await ye(n,e,t);await iT.rm(r,{force:!0})}}function kd(n){let e;try{e=sT(n,"utf-8")}catch{throw new Error(v.ERR_CERT_INVALIDATE)}if(!Le.CERT_PATTERN.test(e))throw new Error(v.ERR_CERT_INVALIDATE)}async function Ey(n,e){return{certPath:await ye(n,e,"cer"),csrPath:await ye(n,e,"csr"),p12Path:await ye(n,e,"p12"),profilePath:await ye(n,e,"p7b")}}async function Td(n,e){let t=e??"",r=G.discover(process.cwd()).rootDir;await Rd(t,r);let o=Ed(n.teamId),i=await Ea(n,o);if(i&&!await Pd(n,i.id))throw new Error(v.ERR_DOWNLOAD_CER);let s=await Dd(e),a;try{a=cT(s.csrFilePath,"utf-8")}catch{throw new Error(v.ERR_READ_CSR)}console.log("Start generating certificate"),await Cd(n,a,o);let c=await Ea(n,o);if(!c)throw new Error(v.ERR_DOWNLOAD_CER);let l=await Id(n,c.certObjectId);if(!l)throw new Error(v.ERR_DOWNLOAD_CER);let d=await ye(t,r,"cer");await si(l.newUrl,d,l.sha256),kd(d);let g=await ye(t,r,"p7b");return{p12FilePath:s.p12FilePath,csrFilePath:s.csrFilePath,cerFilePath:d,profileFilePath:g,certId:c.id,keyAlias:s.keyAlias,keyPwd:s.keyPwd,storePassword:s.keyPwd}}import Na from"crypto";import bn from"fs";import*as _y from"path";import TT from"json5";import{execa as Ly}from"execa";import Oy from"node-forge";import{createCipheriv as lT,createDecipheriv as dT,pbkdf2Sync as uT,randomBytes as Od}from"crypto";import{promises as qn}from"fs";import{dirname as pT,join as lt}from"path";var Pa=3,ci=16,fT=1e4,by="material",mT=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Ay="aes-128-gcm",zn=12,Ca=16,vn=4;function xd(n){return new Uint8Array(Od(n))}function hT(n){return Od(n).toString("hex")}function gT(...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 o=0;for(let i of n)o^=i[r];t[r]=o}return t}function Py(n,e,t=fT,r=ci){let o=[...n,mT],i=gT(...o),s=Buffer.from(i).toString("utf8"),a=Buffer.from(s,"utf8"),c=uT(a,e,t,r,"sha256");return new Uint8Array(c)}function Cy(n,e){let t=Od(zn),r=lT(Ay,n,t),o=Buffer.concat([r.update(e),r.final()]),i=r.getAuthTag(),s=Buffer.concat([o,i]),a=s.length,c=Buffer.alloc(vn+zn+s.length);return c.writeUInt32BE(a,0),t.copy(c,vn),s.copy(c,vn+zn),c}function Iy(n,e){if(e.length<vn+zn+Ca)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(vn,vn+zn),o=e.subarray(vn+zn,vn+zn+t);if(o.length<Ca)throw new Error("Ciphertext too short for auth tag");let i=o.subarray(0,o.length-Ca),s=o.subarray(o.length-Ca),a=dT(Ay,n,r);return a.setAuthTag(s),Buffer.concat([a.update(i),a.final()])}async function yT(n){try{await qn.rm(n,{recursive:!0,force:!0})}catch{}}async function Nd(n){let e=await qn.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 qn.readFile(lt(n,t[0]))}async function Ld(n,e){let t=hT(ci),r=lt(n,t);return await qn.writeFile(r,e,{mode:384}),t}var Sn=class{static keyChain=Promise.resolve();static async generateMaterial(e){let t=lt(e,by);await yT(t);let r=lt(t,"ac"),o=lt(t,"ce");await qn.mkdir(r,{recursive:!0,mode:448}),await qn.mkdir(o,{recursive:!0,mode:448});for(let d=0;d<Pa;d++)await qn.mkdir(lt(t,"fd",String(d)),{recursive:!0,mode:448});let i=xd(ci),s=[];for(let d=0;d<Pa;d++)s.push(xd(ci));let a=xd(ci),c=Py(s,i),l=Cy(c,a);await Ld(r,i),await Ld(o,l);for(let d=0;d<Pa;d++){let g=lt(t,"fd",String(d));await Ld(g,s[d])}return a}static async readMaterial(e){let t=lt(e,by),r=lt(t,"ac"),o=new Uint8Array(await Nd(r)),i=[];for(let d=0;d<Pa;d++){let g=lt(t,"fd",String(d)),w=await Nd(g);i.push(new Uint8Array(w))}let s=lt(t,"ce"),a=await Nd(s),c=Py(i,o),l=Iy(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t,r=this.keyChain;this.keyChain=new Promise(o=>{t=o}),await r;try{let o=pT(e);try{return await this.readMaterial(o)}catch{return await this.generateMaterial(o)}}finally{t()}}static async encryptedPassword(e,t){let r=await this.getStoreKey(t),o=Buffer.from(e,"utf8");return Cy(r,o).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let r=await this.getStoreKey(t),o=Buffer.from(e,"hex");return Iy(r,o).toString("utf8")}};import xy from"fs";import Ta from"path";import PT from"json5";import*as Ia from"fs";import*as Dy from"path";function Aa(n){let e=Dy.resolve(n);if(!Ia.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=Ia.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 o=r?.data?.apiVersion;if(o==null||o==="")throw new Error(`Missing data.apiVersion in SDK info file: ${e}`);let i=Number(o);if(!Number.isFinite(i))throw new Error(`Invalid data.apiVersion in SDK info file: ${String(o)}`);return i}import*as Yr from"fs";import*as Oe from"path";import{debuglog as qr}from"util";var Ry={"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 wT(n){return Object.prototype.hasOwnProperty.call(Ry,n)}function Da(n){if(wT(n))return Ry[n]}var ky={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as vT}from"url";var ka=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 Ra(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Ty(n){return n==null||n.length===0}function ST(n){return!Ty(n)}function Md(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function ET(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 bT(n,e){let t=n[e];if(typeof t=="number")return Math.trunc(t);if(typeof t=="string"){let r=Number.parseInt(t,10);return Number.isNaN(r)?0:r}return 0}var En=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=Oe.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=Oe.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,o=this.getOrCreateSet(this.aclPermissionNamesMap,r),i=this.getOrCreateSet(this.aclPermissionInfoMap,r);o.clear(),i.clear();let s=Oe.join(t.sdkPath,"default","sdk-pkg.json"),a=Aa(s);this.MIN_API_TO_FIND_ACL_IN_SDK-a>0?this.initAclPermissionFromBuiltInConfig(o,i):this.initAclPermissionFromSDK(t,o,i)}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=Oe.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(Yr.existsSync(e))return Yr.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=vT(e);if(t.includes("dist")){let s=Oe.dirname(t),a=Oe.dirname(s);return Oe.join(a,"src","resources")}let r=Oe.dirname(t),o=Oe.dirname(r),i=Oe.dirname(o);return Oe.join(i,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let r;try{r=this.readBuiltInConfigText()}catch{qr("read builtin acl permission failed.");return}if(r!==void 0)try{let o=JSON.parse(r),s=(Array.isArray(o)?o:Ra(o)?Object.values(o):[]).filter(Ra).map(a=>new ka(a));s.forEach(a=>{let c=a.permissionInsteadName;ST(c)&&(a.permissionInsteadName=Da(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(o){qr(`failed to parse aclPermissionsInfo.json: ${o}`)}}static initAclPermissionFromSDK(e,t,r){let o=this.parsePermissionDefinitionFile(e);o&&o.forEach(i=>{if(!Ra(i))return;let s=i,a=Md(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(Ty(a)||(this.generateAclInfos(r,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||Md(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||Md(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:ET(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let o=new ka;o.permissionName=t;let i=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;o.permissionDisplayName=i;let s=bT(r,this.ACL_SINCE_KEY);o.minSupportApiLevel=String(s),this.handleInsteadName(o,i),e.add(o)}static parsePermissionDefinitionFile(e){let t=Oe.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!Yr.existsSync(t))return;let r;try{r=Yr.readFileSync(t,"utf-8")}catch(s){qr(`failed to load permissionDefinitions.json: ${s}`);return}let o;try{let s=JSON.parse(r);if(!Ra(s)){qr("json object is null");return}o=s}catch(s){qr(`failed to parse permissionDefinitions.json: ${s}`);return}let i=o[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(i)){qr("definePermissions is not an array");return}return i}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=Da(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=Da(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function xa(n,e){let t=new Set,r=new Set;En.handleSpecificAclPermissions(),En.initAclPermission(n,e);for(let o of n.profile.modules){let i=Ny(o,n,e,r,Ta.join("src","main"));for(let a of i)t.add(a);let s=Ny(o,n,e,r,Ta.join("src","ohosTest"));for(let a of s)t.add(a)}return CT(r),t}function CT(n){if(n.size>0)throw new Error(ky.DUPLICATE_PERMISSION)}function Ny(n,e,t,r,o){let i=AT(e.rootDir,n,o);if(i==null)return new Set;let s=[];for(let w of i){if(typeof w!="object"||w===null)continue;let P=IT(w,"name");P&&s.push(P)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=Ta.join(t.sdkPath,"default","sdk-pkg.json"),l=Aa(c),d=En.getAclPermissionInfos(e),g=new Set(Array.from(d).filter(w=>{let P=Number(w.minSupportApiLevel);return Number.isFinite(P)&&P<=l}).map(w=>w.permissionName));for(let w of Array.from(a))g.has(w)||a.delete(w);return a}function IT(n,e){let t=n[e];return typeof t=="string"?t:""}function AT(n,e,t){let r=Ta.join(n,e.srcPath,t,"module.json5"),o=DT(r);if(o==null)return null;let i=RT(o,"module");return i==null?null:kT(i,"requestPermissions")}function DT(n){try{if(!xy.existsSync(n))return null;let e=xy.readFileSync(n,"utf-8");return PT.parse(e)}catch{return null}}function RT(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 kT(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}var Fd=class{verifyStorePassword(e,t){try{let r=bn.readFileSync(e),o=Oy.asn1.fromDer(r.toString("binary"));return Oy.pkcs12.pkcs12FromAsn1(o,t),!0}catch{return!1}}getLocalCerFingerprints(e){let r=bn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(r&&r.length>0)return r.map(o=>this.formatFp(new Na.X509Certificate(o).fingerprint256));try{return[this.formatFp(new Na.X509Certificate(bn.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let o=bn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let i of o)try{let s=new Na.X509Certificate(i);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 xT(n){let e=bn.readFileSync(n,"utf-8"),t=NT(e),r=null;if(t)try{r=JSON.parse(t)}catch{r=null}let o=r?.["bundle-info"]??{};return{rawContent:e,bundleNameInProfile:_d(o["bundle-name"]),expiryDate:LT(r?.validity?.["not-after"]),cerFingerprintInProfile:OT(_d(o["development-certificate"])),deviceUdidsInProfile:MT(r?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:_T(r?.acls?.["allowed-acls"]),teamIdInProfile:_d(o["developer-id"])}}function NT(n){let e=n.indexOf("{");if(e<0)return null;let t=0,r=-1,o=!1,i=!1;for(let s=e;s<n.length;s++){let a=n[s];if(o){i?i=!1:a==="\\"?i=!0:a==='"'&&(o=!1);continue}if(a==='"')o=!0;else if(a==="{")t++;else if(a==="}"&&(t--,t===0)){r=s;break}}return r<0?null:n.slice(e,r+1)}function LT(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function OT(n){if(!n)return null;try{let t=new Na.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function MT(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 _T(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 _d(n){return typeof n=="string"?n:null}var li=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.#o(r)??n.#i(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,o=e.teamId,i=e.productName??"default",s=G.discover(process.cwd()),a=s.rootDir,[c,l]=await Promise.all([FT(i,a),$T(t.hdcPath)]),d=null;if(My(c).allExist)try{d=xT(c.profileFile)}catch{}return{force:r,teamId:o,productName:i,projectPath:a,materialPaths:c,bundleName:s.getBundleName(),deviceUdids:l,storePassword:await jT(a,i,c.storeFile),localAclPermissions:[...xa(s,t)].sort(),hapSignTool:new Fd,profileInfo:d}}static#t(e){return e.force?(m("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:$e({force:!0})}):null}static#n(e){let t=My(e.materialPaths);return t.allExist?null:(m(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:$e({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:$e({allFilesExist:!0,profileContentNotEmpty:!1})})}static#o(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:$e({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!1})})}static#i(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:$e({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:$e({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=UT(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:$e({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return BT(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(m("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:$e({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:$e({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:$e({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:$e({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:$e({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:$e({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function FT(n,e){let[t,r,o,i]=await Promise.all([ye(n,e,"p12"),ye(n,e,"csr"),ye(n,e,"cer"),ye(n,e,"p7b")]);return{storeFile:t,csrFile:r,cerFile:o,profileFile:i}}async function jT(n,e,t){let r=_y.join(n,"build-profile.json5");if(!bn.existsSync(r))return;let o;try{o=TT.parse(bn.readFileSync(r,"utf-8"))}catch{return}let a=(o?.app?.signingConfigs??[]).find(c=>c.name===e)?.material?.storePassword;if(a)try{return await Sn.decryptPassword(a,t)}catch{return}}async function $T(n){m(`Executing: ${n} list targets`);let{stdout:e}=await Ly(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let o of e.split(`
|
|
1386
|
-
`)){let i=o.trim();if(!i||i.startsWith("[Empty]"))continue;let s=i.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 o of t)try{
|
|
1387
|
-
`);for(let o=0;o<t.length-1;o++)if(t[o].includes("udid of current device is")){let s=t[o+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
|
|
1388
|
-
`)){let i=o.trim();if(!i||i.startsWith("[Empty]"))continue;let s=i.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 o of t)try{let i=await
|
|
1389
|
-
`);for(let s=0;s<o.length-1;s++)if(o[s].includes("udid of current device is")){let c=o[s+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(c)return c[0].toUpperCase()}let i=r.match(/[A-Fa-f0-9]{64}/);return i?i[0].toUpperCase():""}async function qT(n,e){let{stdout:t}=await $d(e,["-c","-t",n,"shell","getprop","hw_sc.build.os.deviceType"],{stdio:["ignore","pipe","pipe"]});return YT(t)}function YT(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 Yn from"fs";import{createHash as JT}from"crypto";import{debuglog as jt}from"util";import{Buffer as Vy}from"buffer";import{createPublicKey as KT,X509Certificate as Hd}from"crypto";import{readFileSync as XT}from"fs";import Jn from"node-forge";async function Gy(n,e){console.log("Start generating profile");let{productName:t,bundleName:r,projectPath:o,aclPermissionList:i,allDeviceIds:s,certIds:a,keyAlias:c,keyPwd:l}=e;if(s==null||s.length===0)throw new Error(v.DEVICE_LIST_EMPTY);let d=`${X.BASE_URL}${X.PROVISION_ADD_TEST_PATH}`,g=ZT(t,r),w=await ex(n,d,a||[],r,s,g,i||[]);if(!w||!w.profileInfo||!w.profileInfo.provisionFileUrl)throw jt("add provision failed, the provision file url is null"),new Error(v.ADD_PROFILE_FAIL);let P=w.profileInfo,ne=(await ox(n,P.provisionFileUrl)).urlList,Ze=w.profileInfo.id;if(ne&&ne.length>0){let dt=await Ey(t,o),$t=dt.profilePath;if(!await ix(ne,$t))throw await Wy(n,Ze),new Error(v.ERROR_WHILE_DOWNLOAD_PROFILE);if(await Wy(n,Ze),Yn.existsSync(dt.certPath)&&Yn.existsSync($t)&&Yn.existsSync(dt.p12Path)){let nw=Yn.readFileSync(dt.certPath,"utf8"),rw=Yn.readFileSync($t,"utf8");return sx(rw,nw,dt.p12Path,c,l)||rx($t),$t}}throw new Error(v.ADD_PROFILE_FAIL)}function ZT(n,e){let t=n?`${n}_`:"";return`${QT(`${t}${e}_${e}`)}`}function QT(n){return JT("sha256").update(n).digest("hex").substring(0,16)}async function ex(n,e,t,r,o,i,s){tx(r);let a=Bd(n),c={certList:t,packageName:r,deviceList:o,provisionName:i};s.length&&(c.aclPermissionList=s);let l=await x.postAllowFailure(e,{headers:a,params:c});if(!l)throw jt("add provision failed: response is null"),new Error(v.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw Ud(l.statusCode,l.statusText,l.data);let d=JSON.parse(l.data);if(!d||!d.ret||d.ret.code!==0)throw jt(`add provision fail: ${l.data}`),nx(l.data,i),new Error(d.ret?.msg||v.ADD_PROFILE_FAIL);let g=d.provisionFileUrl;return{profileInfo:{id:d.id,name:i,provisionFileUrl:g}}}function Ud(n,e,t){return n===at.FORBIDDEN?e===ue.OPENPROXY_BLOCKED_URL?new Error(v.ERR_CERT_NETWORK_ERROR):new Error(v.ERR_FORBIDDEN):n===at.UNAUTHORIZED?new Error(v.ERR_UNAUTHORIZED):t.includes(ue.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(v.TEST_PROVISION_EXCEEDS_LIMIT):new Error(v.ADD_PROFILE_FAIL)}function tx(n){if(!n||n.trim().length===0)throw new Error(v.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!Le.BUNDLE_NAME_REGEX.test(n))throw new Error(v.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function nx(n,e){if(n.includes(ue.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(v.TEST_PROVISION_EXCEEDS_LIMIT);if(n.includes(ue.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(v.PROFILE_NAME_REPEAT)}async function Wy(n,e){if(!e||e.trim().length===0)return;let t=`${X.BASE_URL}${X.PROVISION_DELETE_PATH}?id=${e}`,r=await x.deleteAllowFailure(t,{headers:Bd(n)});if(r.statusCode!==200)throw Ud(r.statusCode,r.statusText,r.data);let o=JSON.parse(r.data);(!o||!o.ret||o.ret.code!==0)&&jt(`delete provision failed: ${r.data}`)}function rx(...n){for(let e of n)try{Yn.existsSync(e)&&Yn.unlinkSync(e)}catch(t){jt(`delete local sign file error: ${t.message}`)}}async function ox(n,e){let t=`${X.BASE_URL}${X.CERT_DOWNLOAD_URL_PATH}`,r=Bd(n),o={sourceUrls:e},i=await x.postAllowFailure(t,{headers:r,params:o});if(!i)throw jt("get download list failed: response is null"),new Error(v.ADD_PROFILE_FAIL);if(i.statusCode!==200)throw Ud(i.statusCode,i.statusText,i.data);let s=JSON.parse(i.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw jt("download: The application does not exist"),new Error(s.ret?.msg||v.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function ix(n,e){if(!n||n.length===0)return!1;let t=n[0];return await si(t.newUrl,e,t.sha256),!0}function sx(n,e,t,r,o){return ax(n,e),r=r||Le.TARGET_FRIENDLY_NAME,o=o||"",cx(e,t,r,o),!0}function ax(n,e){if(e.lastIndexOf(Le.CERT_BEGIN_HEADER)<0)throw new Error(v.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(Le.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!n.includes(t))throw new Error(v.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}function cx(n,e,t,r){let o=n.matchAll(Le.CERTIFICATE_PATTERN_GLOBAL),i=[],s=new Date;for(let c of o)try{let l=c[0],d=lx(l),g=new Date(d.validFrom),w=new Date(d.validTo);if(s<g||s>w){let P=`Certificate is not valid, Valid from ${g} to ${w}`;throw console.warn(`checkCertificateInValidityPeriod: ${P}`),new Error(v.CERTIFICATE_HAS_EXPIRED)}i.push(d)}catch(l){throw console.warn(`checkCertificateInValidityPeriod\uFF1A ${l.message}`),new Error(v.CERTIFICATE_HAS_EXPIRED,{cause:l})}if(!i||i.length===0)throw new Error(v.CERTIFICATE_HAS_EXPIRED);if(!ux(e,t,r,i))throw new Error(v.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function lx(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new Hd(t);let r=Vy.from(t,"base64");return new Hd(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}function dx(n){if(n.cert){let e=Jn.pki.publicKeyToPem(n.cert.publicKey);return KT(e).export({type:"spki",format:"der"})}if(n.asn1)try{let e=Jn.asn1.toDer(n.asn1).getBytes(),t=Vy.from(e,"binary");return new Hd(t).publicKey.export({type:"spki",format:"der"})}catch(e){return jt(`Failed to parse cert from asn1: ${e}`),null}return null}function ux(n,e,t,r){try{let o=XT(n),i=Jn.asn1.fromDer(Jn.util.createBuffer(o)),c=Jn.pkcs12.pkcs12FromAsn1(i,t).getBags({bagType:Jn.pki.oids.certBag})[Jn.pki.oids.certBag]||[];for(let l of c){let d=l.attributes?.friendlyName?.[0];if(!d||d.toLowerCase()!==e.toLowerCase())continue;let g=dx(l);if(!g)continue;if(r.some(P=>{let O=P.publicKey.export({type:"spki",format:"der"});return g.equals(O)}))return!0}return!1}catch(o){let i=o instanceof Error?o.message:String(o);return jt(`Failed to process P12 file: ${n}, error: ${i}`),!1}}function Bd(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var qy="https://developer.huawei.com",px={"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"},fx="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function mx(n){let e=px[n];return e?`${qy}${e}`:void 0}function hx(){return`${qy}${fx}`}var gx={"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 zy(n,e){return(gx[n]??n).replace(/\{(\d+)\}/g,(r,o)=>String(e[Number(o)]??""))}function yx(n){return Array.from(n).join(", ")}function Yy(n,e){if(n.size===0)return;let t=En.getAclPermissionInfos(e),r=new Set;for(let g of t)n.has(g.permissionName)&&r.add(g);for(let g of r){let w=mx(g.permissionName);w!=null&&(g.permissionHelpUrlKey=w)}let o=new Set;for(let g of r)o.add(g.permissionDisplayName);let i=new Set;for(let g of r)if(g.permissionHelpUrlKey!=null){let w=g.permissionInsteadName??g.permissionDisplayName;i.add(`${w} (${g.permissionHelpUrlKey})`)}let s=hx(),a=zy("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=i.size>0?Array.from(i).join(", ")+".":"",d=zy("acl.permissions.warn",[yx(o),l,c]);console.log(d)}var Oa=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=G.discover(process.cwd()),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Project.discover() failed: ${t.message}`),e(ee.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:ee.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import wx from"fs";import Jy from"path";var Ma=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=Jy.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");if(!wx.existsSync(r)){let o=Jy.join("sdk","default","openharmony","toolchains","lib","hap_sign_tools.jar");return e(`hap_sign_tools.jar not found.Check whether ${o} exists.`)}return{passed:!0,message:""}}};var _a=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await Ee.getUserInfo()}catch(e){return m(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await Ee.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(ee.LOGIN_REQUIRED)}catch(t){return m(`[EnvCheck] Login check failed: ${t.message}`),e(ee.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(ee.TEAM_INFO_FAILED);try{if((await Xt()).teamList.length>0)return{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Team API error: ${r.message}`),e(ee.TEAM_INFO_FAILED)}return m("[EnvCheck] No teams found for current user"),e(ee.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(ee.REALNAME_REQUIRED):t.isRealName!==!0?(m("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(ee.REALNAME_REQUIRED)):{passed:!0,message:""}:e(ee.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let r=e??"";try{let o=await Xt();if(r=e??(o.teamList.length>0?o.teamList[0].id:t.userId)??"",!o.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(o){return m(`[EnvCheck] Team ID check failed: ${o.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(ee.REGION_CHINA_ONLY):{passed:!0,message:""}:(m("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(ee.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function vx(n){try{let{teamList:e}=await Xt();if(e.length>0)return e[0].id}catch(e){m(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function Sx(n){let e=await Ee.getUserInfo(),t=await Ee.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await vx(e.userId);if(!r)throw new Error("No team found");let o={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await La(o)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var Fa=class{constructor(e){this.toolProvider=e}toolProvider;async checkDevice(e,t){try{let r=await Sx(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 i=await Q.from(this.toolProvider).listDevices();return i.length===0?(m("[EnvCheck] Scenario 4 Device check: no local devices found"),e(ee.DEVICE_MISSING)):i.some(a=>ft(a.serial))?{passed:!0,message:""}:(m("[EnvCheck] Scenario 4 Device check: local device found but not an emulator"),e(ee.DEVICE_MISSING))}catch(r){return m(`[EnvCheck] Scenario 4 Device check failed: ${r.message}`),e(ee.DEVICE_DETECT_FAILED)}}};var ja=class{projectChecker=new Oa;toolchainChecker=null;authChecker=new _a;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=i=>(i.passed||this.fail(i),!0),o=[()=>this.authChecker.checkLogin(t),()=>this.authChecker.checkRealname(t),()=>this.authChecker.checkTeamInfo(t)];for(let i of o)if(!r(await i()))return!1;return!(e.teamId&&!r(await this.authChecker.checkTeamId(e.teamId)))}async initToolchain(){try{let e=await I.new();return this.toolchainChecker=new Ma(e),this.deviceChecker=new Fa(e),!0}catch(e){throw m(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(ee.TOOLCHAIN_INIT_FAILED,{cause:e})}}async runDeviceCheck(e,t){return(o=>o.passed?!0:(this.fail(o),!1))(await this.deviceChecker.checkDevice(t,e.teamId))}async runProjectChecks(e,t){let r=i=>i.passed?!0:(this.fail(i),!1);if(!r(this.projectChecker.checkProjectDir(t))||!r(this.projectChecker.checkAtomicService()))return!1;let o=[()=>this.projectChecker.checkProduct(e.productName,t),()=>this.projectChecker.checkBundleName(e.productName,t),()=>this.toolchainChecker.checkJava(t),()=>this.toolchainChecker.checkHapSignTools(t)];for(let i of o)if(!r(i()))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)}};var Ky=5*1024*1024;function Px(n){try{let e=Vd.statSync(n);if(e.size>Ky)throw new Error(`Profile file too large: ${e.size} bytes (max ${Ky} bytes): ${n}`);let t=Vd.readFileSync(n,"utf-8");return Zy.parse(t)}catch(e){if(e.code==="ENOENT")return{app:{signingConfigs:[],products:[]}};throw new Error(`Failed to read profile: ${n}`,{cause:e})}}function Cx(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function Ix(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 Ax(n,e,t){let r=Xy.join(n,"build-profile.json5"),o=Px(r);Cx(o);let i=t??"default",{keyPassword:s,storePassword:a}=await Ix(e),c={name:i,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:s,profile:e.profileFilePath,signAlg:ct.signAlg,storeFile:e.p12FilePath,storePassword:a}},l=o.app?.signingConfigs?.findIndex(g=>g.name===i);l!==void 0&&l>=0?o.app.signingConfigs[l]=c:o.app.signingConfigs.push(c);let d=o.app?.products?.findIndex(g=>g.name===i);d!==void 0&&d>=0?o.app.products[d].signingConfig=i:o.app.products.push({name:i,signingConfig:i}),Vd.writeFileSync(r,Zy.stringify(o,null,2),"utf-8")}async function Dx(n){let e=await Ee.getUserInfo(),t=await Ee.refreshToken();if(!e||!t)throw new Error("Failed to obtain login credentials. Run `devecocli auth login` again.");return{uid:e.userId??"",teamId:n.teamId??e.userId??"",accessToken:t.accessToken??""}}async function Rx(n){let e=n.product||"default";await new ja().preflight({productName:e,teamId:n.teamId}),console.log("Executing signature generate command");let r=await Dx(n),o=await I.new(),{shouldRegenerate:i}=await li.shouldRegenerate({force:n.force??!1,teamId:r.teamId,productName:n.product},o);if(!i){console.log(Wd("Signature generation completed successfully."));return}await kx(n,r,o),console.log(Wd("Signature generation completed successfully."))}async function kx(n,e,t){let r=await Td(e,n.product),o=Tx(n,e,r,t);o.allDeviceIds=await jy(e,t.hdcPath),await Gy(e,o);let i=G.discover(process.cwd()).rootDir;await Ax(i,r,n.product??"default"),console.log(Wd(`Signing config written to ${Xy.join(i,"build-profile.json5")}`))}function Tx(n,e,t,r){let o=process.cwd(),i=G.discover(o),s=xa(i,r);return Yy(s,i),{productName:n.product||"default",bundleName:i.getBundleName(),projectPath:i.rootDir,teamId:e.teamId,force:n.force||!1,aclPermissionList:[...s],certIds:[t.certId],keyAlias:t.keyAlias,keyPwd:t.keyPwd}}var Qy=new Ex("signature").description("Generate application signature.");Qy.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 Rx(n)}catch(e){console.error(bx(e.message)),process.exit(1)}});var ew=Qy;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";xx();te.name("devecocli").description("HarmonyOS application development command line tool").version("1.3.0-Test.15");te.addCommand(xu);te.addCommand(rp);te.addCommand(up);te.addCommand(xp);te.addCommand(of);te.addCommand(Df);te.addCommand(Qf);te.addCommand(nm);te.addCommand(fm);te.addCommand(Em);te.addCommand(Hm);te.addCommand(lg);te.addCommand(Og);te.addCommand(fy);te.addCommand(ew);var Gd=process.argv.slice(2);Gd.length>=2&&Gd[Gd.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);function Lx(n){let e=n;for(;e.parent&&e.parent!==te;)e=e.parent;return e}var Ox=new Set(["update","auth","serve"]);te.hook("preAction",async(n,e)=>{let t=Lx(e),r=sr();if(t.name()==="update")return;let o=new Yt(tw.join(ht(),"update")),i=qt();if(r==="off"&&o.getBlockedVersions().includes(i))throw new Error(`devecocli ${i} has been disabled, run \`devecocli update\` to upgrade`);process.env.DEVECO_CLI_SKIP_VERSION_CHECK||Ox.has(t.name())||await I.checkVersion()});te.hook("postAction",async(n,e)=>{if(process.exitCode||sr()!=="off")return;await new lo(e).checkAndNotify()});te.parseAsync(process.argv).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(Nx(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
|
|
1394
|
+
`),console.log(ge("[compat:check] === end stdout ===")));let i=new Q("errorCode",`Compatibility scan failed: ${o.message}`+(o.stderr?`
|
|
1395
|
+
${o.stderr}`:""));throw o.stdout&&(i.stdout=o.stdout),i}}function gx(n,e){if(!ex.includes(e.format))throw new JR(`--format must be default, csv, or json (console: default|json, file: default|csv|json). got "${e.format}"`);if(n.length>0&&e.modules&&e.modules.length>0)throw new Q("errorCode","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 Q("errorCode","--source-version is required.");if(!e.targetVersion)throw new Q("errorCode","--target-version is required.");if(!e.outputPath&&e.format==="csv")throw new Q("errorCode","--format csv requires --output-path. For console output, use --format json or --format default (or omit the flag).")}function yx(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 Q("errorCode",`${t.join(" and ")} ${r} not in the available SDK version list.
|
|
1396
|
+
Run \`devecocli compat versions\` to see all available versions.`)}if(n.sourceVersion&&n.targetVersion){let r=e.indexOf(n.sourceVersion),o=e.indexOf(n.targetVersion);if(r>=o)throw new Q("errorCode",`--target-version "${n.targetVersion}" must be later than --source-version "${n.sourceVersion}". Run \`devecocli compat versions\` to see the available order.`)}}function wx(n,e,t,r,o){o==="none"&&(t==="json"?px(n,r):ux(n,r)),dx(n,e)}function vx(n,e){let t=z.dirname(n),r=z.basename(n),o=e.slice(1).map(i=>i.startsWith("--")?i:`"${i}"`).join(" ");h(ge(`[compat:check] command: cd "${t}" && node "${r}" ${o}`))}function Sx(n){try{XR(n),h(ge(`[compat:check] cleaned up tmp report: "${n}"`))}catch(e){h(ge(`[compat:check] failed to clean up tmp report: ${e.message}`))}}var bx=[".csv",".json"];function Ex(n){return bx.includes(n.toLowerCase())}function Px(n,e){if(!n)return{kind:"none"};let t=z.extname(n).toLowerCase();if(!Ex(t))return{kind:"dir",dirPath:z.resolve(n)};if(t===".csv"&&!(e==="default"||e==="csv")||t===".json"&&e!=="json")throw new Q("errorCode",`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:z.resolve(n),ext:t}}function Cx(n){if(n.kind==="file"){if(Ua(n.filePath))throw new Q("errorCode",`Target file "${n.filePath}" already exists. Remove it first, or choose a different --output-path.`);let e=z.dirname(n.filePath);if(!Ua(e))throw new Q("errorCode",`Target directory "${e}" does not exist. Create it first, or choose a different --output-path.`)}else if(n.kind==="dir"&&!Ua(n.dirPath))throw new Q("errorCode",`Target directory "${n.dirPath}" does not exist. Create it first, or choose a different --output-path.`)}function hw(n){return JSON.stringify({records:n,count:n.length},null,2)+`
|
|
1397
|
+
`}function Ix(n,e,t,r){r===".csv"?dw(n,t):uw(t,hw(e),"utf8"),h(ge(`[compat:check] saved report: "${t}"`))}function Ax(n,e,t,r){if(r==="json"){let i=z.basename(n,".csv"),s=z.join(t,`${i}.json`);return uw(s,hw(e),"utf8"),h(ge(`[compat:check] saved report: "${s}"`)),s}let o=z.join(t,z.basename(n));return dw(n,o),h(ge(`[compat:check] saved report: "${o}"`)),o}async function Dx(n,e){let t=new Ve(n,process.cwd(),!0),r=e.modules&&e.modules.length>0?e.modules[0]:void 0;try{await t.compileNative("default",r)}catch(o){throw new Q("errorCode",`hvigorw compileNative failed (module=${r??"<project>"}): `+o.message,{cause:o})}}async function kx(n,e){gx(n,e);let t=J.discover(process.cwd());e.modules&&e.modules.length>0&&nx(t,e.modules),n.length>0&&rx(n);let r=await I.new(),{apiChangeDir:o,scriptPath:i}=r.getApiscanPaths();h(ge(`[compat:check] script: "${i}"`));let s=mw(o);yx(e,s),e.outputPath&&h(ge(`[compat:check] outputPath: "${e.outputPath}"`));let a=Px(e.outputPath,e.format);return h(ge(`[compat:check] outputTarget: ${a.kind}`)),Cx(a),{project:t,scriptPath:i,target:a,toolProvider:r}}function Tx(n,e,t,r){if(t.kind==="file")return Ix(n,e,t.filePath,t.ext),t.filePath;if(t.kind==="dir")return Ax(n,e,t.dirPath,r);if(t.kind==="none")return null;throw new Q("errorCode",`Unexpected output target kind: ${t.kind}`)}async function Rx(n,e,t,r,o){let i=QR({text:"Running compatibility check...",color:"cyan"}).start();try{await Dx(n.toolProvider,t);let s=fx(n.scriptPath,e,n.project,t);vx(n.scriptPath,s);let a=await hx(n.toolProvider,s),c=lx(a,Yd.tmpdir());if(!c)throw new Q("errorCode","Scanner output format unexpected: missing report path.");h(ge(`[compat:check] tmp csv: "${c}"`));let l=cx(c),d=Tx(c,l,n.target,t.format);Sx(c),i.stop(),wx(l,d,t.format,t.limit,n.target.kind),await lo(r,!0,null,o)}catch(s){i.fail("Compatibility check failed");let a=Kd(s);throw await lo(r,!1,a,o),s}}async function gw(n,e){let t=Date.now(),r=["check","compat"];try{let o=await kx(n,e);await Rx(o,n,e,t,r)}catch(o){let i=Kd(o);throw await lo(t,!1,i,r),o}}function Nx(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new xx(`--limit must be a positive integer (got "${n}")`);return e}function Lx(){let n=process.argv;for(let e=0;e<n.length;e++){if(n[e]==="--format"&&e+1<n.length)return n[e+1];if(n[e].startsWith("--format="))return n[e].slice(9)}}var Xd=new yw("compat").description("Compatibility checking utilities.");Xd.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.',"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)",Nx,100).action(async(n,e)=>{await gw(n,e)});Xd.command("versions").description("List all available target SDK versions for compatibility checking").option("--format <format>","Output format: default or json").action(async()=>{await fw(Lx())});var Ox=new yw("check").description("Run DevEco project checks").addCommand(Xd).addCommand(qd()),ww=Ox;import{Command as EL}from"commander";import{green as Su,red as PL}from"colorette";import bu from"fs";import nv from"path";import rv from"json5";import{readFileSync as lN}from"fs";import{join as Mx}from"path";var te={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"},Ue={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:Mx(".ohos","config"),DOWNLOAD_CONNECT_TIMEOUT_MS:5e3},ye={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"},ht={FORBIDDEN:403,UNAUTHORIZED:401},P={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."},se={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 Ba(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}function Zd(n){let e=n.replace(Ue.TEAM_ID_INVALID_CHARS,"");return`${Ue.CERT_NAME_PREFIX}${e}.cer`}function uo(n,e,t){if(n===ht.FORBIDDEN)return e===ye.OPENPROXY_BLOCKED_URL?new Error(P.ERR_CERT_NETWORK_ERROR):new Error(P.ERR_FORBIDDEN);if(n===ht.UNAUTHORIZED)return new Error(P.ERR_UNAUTHORIZED);if(t.includes(ye.USER_NOT_HARMONY_CODE))return new Error(P.ERR_USER_NOT_HARMONY);if(t.includes(ye.CERT_LIMIT_CODE))return new Error(P.ERR_CERT_LIMIT_REACHED);let r=_x(t);return new Error(r??P.ERR_DOWNLOAD_CER)}function _x(n){let e=vw(n);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let r=typeof t=="string"?vw(t):t;if(r&&typeof r=="object"){let o=r.msg;if(typeof o=="string"&&o.trim()!=="")return o}return null}function vw(n){try{return JSON.parse(n)}catch{return null}}function Qd(n){return JSON.parse(n)}async function Sw(n){let e=`${te.BASE_URL}${te.CERT_LIST_PATH}`,t=await N.postAllowFailure(e,{headers:Ba(n)});if(t.statusCode!==200)throw uo(t.statusCode,t.statusText,t.data);return Qd(t.data)?.certList??[]}async function Wa(n,e){return(await Sw(n)).find(r=>r.certName===e)??null}async function eu(n,e){let t=`${te.BASE_URL}${te.CERT_DELETE_PATH}`,r=await N.deleteAllowFailure(t,{headers:Ba(n),params:{certIds:[e]}});if(r.statusCode!==200)throw uo(r.statusCode,r.statusText,r.data);return Qd(r.data)?.ret?.code===0}async function tu(n,e,t){let r=`${te.BASE_URL}${te.CERT_ADD_PATH}`,o={csr:e,certName:t,certType:Ue.CERT_TYPE_DEBUG},i=await N.postAllowFailure(r,{headers:Ba(n),params:o});if(i.statusCode!==200)throw uo(i.statusCode,i.statusText,i.data);if(!i.data.includes(ye.SUCCESS_MARKER))throw uo(void 0,i.statusText,i.data)}async function nu(n,e){let t=`${te.BASE_URL}${te.CERT_DOWNLOAD_URL_PATH}`,r=await N.postAllowFailure(t,{headers:Ba(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw uo(r.statusCode,r.statusText,r.data);return Qd(r.data)?.urlsInfo?.[0]??null}import{mkdirSync as Fx,writeFileSync as jx,existsSync as $x}from"fs";import{dirname as Hx}from"path";import{createHash as Ux}from"crypto";function Bx(n){let e;try{e=new URL(n)}catch{throw new Error(`Invalid download URL: ${JSON.stringify(n)}`)}if(e.protocol!=="https:")throw new Error(`Download URL must use HTTPS: ${e.protocol}`);let t=e.hostname.toLowerCase();if(t==="localhost"||t==="127.0.0.1"||t==="::1"||t.startsWith("169.254.")||t.startsWith("10.")||t.startsWith("192.168.")||/^172\.(1[6-9]|2\d|3[0-1])\./.test(t)||t.endsWith(".internal")||t.endsWith(".local"))throw new Error(`Download URL points to internal/private address: ${t}`)}async function Ci(n,e,t){Bx(n);let{statusCode:r,statusText:o,buffer:i}=await N.getBinaryAllowFailure(n,{timeout:Ue.DOWNLOAD_CONNECT_TIMEOUT_MS});if(r!==200)throw r===ht.FORBIDDEN&&o===ye.OPENPROXY_BLOCKED_URL?new Error(P.ERR_CERT_NETWORK_ERROR):new Error(P.ERR_DOWNLOAD_CER);if(t){let a=Ux("sha256").update(i).digest("hex");if(a!==t.toLowerCase())throw new Error(`SHA-256 mismatch for ${e}: expected ${t.toLowerCase()}, got ${a}`)}let s=Hx(e);$x(s)||Fx(s,{recursive:!0}),jx(e,i)}import sN from"fs/promises";import{readFileSync as aN}from"fs";import Va from"path";import Pw from"crypto";import Wx from"os";import Ii from"fs/promises";var Cw={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},bw=["ECC","RSA"],Ew=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],Vx={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},Gx=8,ru=64,zx=/[\\/:*?"<>|=-]/g,gt={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function qx(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>ru)throw new Error(`The length of keyAlias cannot exceed ${ru}`);if(!bw.includes(n.keyAlg))throw new Error(`Invalid key algorithm ${n.keyAlg}, available: ${bw.join(" / ")}`);let e=Vx[n.keyAlg];if(!e.includes(n.keySize))throw new Error(`Key algorithm ${n.keyAlg} does not support size ${n.keySize}, available: ${e.join(", ")}`)}function Jx(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(!Ew.includes(n.signAlg))throw new Error(`Invalid sign algorithm ${n.signAlg}, available: ${Ew.join(" / ")}`)}function Yx(n){return Pw.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function Kx(n){let e=n?.trim()??"";return e&&e.replace(zx,"_").replace(/\.+/g,"_").slice(0,ru)||gt.productName}async function Iw(){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;m.info(`\u8BFB\u53D6SDK\u6839\u76EE\u5F55\uFF1A${t}`);let r=Va.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");try{await Ii.access(r)}catch(o){throw new Error(`Sign tool jar not found: ${r}`,{cause:o})}return{javaPath:e,jarPath:r}}async function Xx(n){let{javaPath:e,jarPath:t}=await Iw(),r=["-jar",t,Cw.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 o=r.map((i,s)=>s>0&&["-keyPwd","-keystorePwd"].includes(r[s-1])?"******":i);return m.debug("generate-keypair \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),[e,...r]}async function Zx(n){let{javaPath:e,jarPath:t}=await Iw(),r=["-jar",t,Cw.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 o=r.map((i,s)=>s>0&&["-keyPwd","-keystorePwd"].includes(r[s-1])?"******":i);return m.debug("generate-csr \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),[e,...r]}async function Qx(n){m.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),qx(n);let e=await Xx(n),t=await Po(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 m.info("\u751F\u6210P12\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}async function eN(n){m.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),Jx(n);let e=await Zx(n),t=await Po(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 m.info("\u751F\u6210CSR\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}function tN(n=Gx){return Pw.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function nN(){let n=Wx.homedir();try{await Ii.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=Va.join(n,".ohos","config");try{await Ii.mkdir(e,{recursive:!0,mode:448})}catch(t){throw new Error(`Failed to create directory ${e}`,{cause:t})}return m.info(`\u7B7E\u540D\u914D\u7F6E\u76EE\u5F55\u5C31\u7EEA\uFF1A${e}`),e}async function Ce(n,e,t){let r=Kx(n),o=Va.basename(e),i=Yx(e),s=`${r}_${o}_${i}=.${t}`,a=await nN();return Va.join(a,s)}function rN(n){let e;try{e=J.discover(n).rootDir}catch(t){throw new Error(`Current directory ${n} is not a valid project root`,{cause:t})}return e}async function oN(n){try{await Ii.access(n)}catch(e){throw new Error(`Project directory ${n} is not accessible, missing read/write permissions`,{cause:e})}}async function iN(n){try{await Ii.access(n)}catch(e){throw new Error(`P12 file ${n} does not exist, terminating CSR generation.`,{cause:e})}}async function ou(n,e,t){let r=process.cwd(),o=rN(r);await oN(o),m.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${o}`);let i=tN(),s=await Ce(n??"",o,"p12"),a=await Ce(n??"",o,"csr");return console.log("Start generating p12"),await Qx({keyAlias:e?.keyAlias??gt.keyAlias,keyPwd:i,keyAlg:e?.keyAlg??gt.keyAlg,keySize:e?.keySize??gt.keySize,keystoreFile:s,keystorePwd:i}),await iN(s),console.log("Start generating csr"),await eN({subject:t?.subject??gt.csrSubject,outFile:a,keyAlias:t?.keyAlias??gt.keyAlias,keyPwd:i,signAlg:t?.signAlg??gt.signAlg,keystoreFile:s,keystorePwd:i}),{p12FilePath:s,csrFilePath:a,keyPwd:i,keyAlias:e?.keyAlias??gt.keyAlias}}var cN=["p12","cer","csr","p7b"];async function iu(n,e){for(let t of cN){let r=await Ce(n,e,t);await sN.rm(r,{force:!0})}}function su(n){let e;try{e=aN(n,"utf-8")}catch{throw new Error(P.ERR_CERT_INVALIDATE)}if(!Ue.CERT_PATTERN.test(e))throw new Error(P.ERR_CERT_INVALIDATE)}async function Aw(n,e){return{certPath:await Ce(n,e,"cer"),csrPath:await Ce(n,e,"csr"),p12Path:await Ce(n,e,"p12"),profilePath:await Ce(n,e,"p7b")}}async function au(n,e){let t=e??"",r=J.discover(process.cwd()).rootDir;await iu(t,r);let o=Zd(n.teamId),i=await Wa(n,o);if(i&&!await eu(n,i.id))throw new Error(P.ERR_DOWNLOAD_CER);let s=await ou(e),a;try{a=lN(s.csrFilePath,"utf-8")}catch{throw new Error(P.ERR_READ_CSR)}console.log("Start generating certificate"),await tu(n,a,o);let c=await Wa(n,o);if(!c)throw new Error(P.ERR_DOWNLOAD_CER);let l=await nu(n,c.certObjectId);if(!l)throw new Error(P.ERR_DOWNLOAD_CER);let d=await Ce(t,r,"cer");await Ci(l.newUrl,d,l.sha256),su(d);let g=await Ce(t,r,"p7b");return{p12FilePath:s.p12FilePath,csrFilePath:s.csrFilePath,cerFilePath:d,profileFilePath:g,certId:c.id,keyAlias:s.keyAlias,keyPwd:s.keyPwd,storePassword:s.keyPwd}}import ec from"crypto";import Mn from"fs";import*as Uw from"path";import xN from"json5";import{execa as jw}from"execa";import $w from"node-forge";import{createCipheriv as dN,createDecipheriv as uN,pbkdf2Sync as pN,randomBytes as uu}from"crypto";import{promises as ar}from"fs";import{dirname as mN,join as yt}from"path";var Ga=3,Ai=16,fN=1e4,Dw="material",hN=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),xw="aes-128-gcm",sr=12,za=16,Nn=4;function cu(n){return new Uint8Array(uu(n))}function gN(n){return uu(n).toString("hex")}function yN(...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 o=0;for(let i of n)o^=i[r];t[r]=o}return t}function kw(n,e,t=fN,r=Ai){let o=[...n,hN],i=yN(...o),s=Buffer.from(i).toString("utf8"),a=Buffer.from(s,"utf8"),c=pN(a,e,t,r,"sha256");return new Uint8Array(c)}function Tw(n,e){let t=uu(sr),r=dN(xw,n,t),o=Buffer.concat([r.update(e),r.final()]),i=r.getAuthTag(),s=Buffer.concat([o,i]),a=s.length,c=Buffer.alloc(Nn+sr+s.length);return c.writeUInt32BE(a,0),t.copy(c,Nn),s.copy(c,Nn+sr),c}function Rw(n,e){if(e.length<Nn+sr+za)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(Nn,Nn+sr),o=e.subarray(Nn+sr,Nn+sr+t);if(o.length<za)throw new Error("Ciphertext too short for auth tag");let i=o.subarray(0,o.length-za),s=o.subarray(o.length-za),a=uN(xw,n,r);return a.setAuthTag(s),Buffer.concat([a.update(i),a.final()])}async function wN(n){try{await ar.rm(n,{recursive:!0,force:!0})}catch{}}async function lu(n){let e=await ar.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 ar.readFile(yt(n,t[0]))}async function du(n,e){let t=gN(Ai),r=yt(n,t);return await ar.writeFile(r,e,{mode:384}),t}var Ln=class{static keyChain=Promise.resolve();static async generateMaterial(e){let t=yt(e,Dw);await wN(t);let r=yt(t,"ac"),o=yt(t,"ce");await ar.mkdir(r,{recursive:!0,mode:448}),await ar.mkdir(o,{recursive:!0,mode:448});for(let d=0;d<Ga;d++)await ar.mkdir(yt(t,"fd",String(d)),{recursive:!0,mode:448});let i=cu(Ai),s=[];for(let d=0;d<Ga;d++)s.push(cu(Ai));let a=cu(Ai),c=kw(s,i),l=Tw(c,a);await du(r,i),await du(o,l);for(let d=0;d<Ga;d++){let g=yt(t,"fd",String(d));await du(g,s[d])}return a}static async readMaterial(e){let t=yt(e,Dw),r=yt(t,"ac"),o=new Uint8Array(await lu(r)),i=[];for(let d=0;d<Ga;d++){let g=yt(t,"fd",String(d)),w=await lu(g);i.push(new Uint8Array(w))}let s=yt(t,"ce"),a=await lu(s),c=kw(i,o),l=Rw(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t,r=this.keyChain;this.keyChain=new Promise(o=>{t=o}),await r;try{let o=mN(e);try{return await this.readMaterial(o)}catch{return await this.generateMaterial(o)}}finally{t()}}static async encryptedPassword(e,t){let r=await this.getStoreKey(t),o=Buffer.from(e,"utf8");return Tw(r,o).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let r=await this.getStoreKey(t),o=Buffer.from(e,"hex");return Rw(r,o).toString("utf8")}};import _w from"fs";import Za from"path";import CN from"json5";import*as qa from"fs";import*as Nw from"path";function Ja(n){let e=Nw.resolve(n);if(!qa.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=qa.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 o=r?.data?.apiVersion;if(o==null||o==="")throw new Error(`Missing data.apiVersion in SDK info file: ${e}`);let i=Number(o);if(!Number.isFinite(i))throw new Error(`Invalid data.apiVersion in SDK info file: ${String(o)}`);return i}import*as mo from"fs";import*as Be from"path";import{debuglog as po}from"util";var Lw={"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 vN(n){return Object.prototype.hasOwnProperty.call(Lw,n)}function Ya(n){if(vN(n))return Lw[n]}var Ow={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as SN}from"url";var Xa=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 Ka(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Mw(n){return n==null||n.length===0}function bN(n){return!Mw(n)}function pu(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function EN(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 PN(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 On=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=Be.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=Be.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,o=this.getOrCreateSet(this.aclPermissionNamesMap,r),i=this.getOrCreateSet(this.aclPermissionInfoMap,r);o.clear(),i.clear();let s=Be.join(t.sdkPath,"default","sdk-pkg.json"),a=Ja(s);this.MIN_API_TO_FIND_ACL_IN_SDK-a>0?this.initAclPermissionFromBuiltInConfig(o,i):this.initAclPermissionFromSDK(t,o,i)}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=Be.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(mo.existsSync(e))return mo.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=SN(e);if(t.includes("dist")){let s=Be.dirname(t),a=Be.dirname(s);return Be.join(a,"src","resources")}let r=Be.dirname(t),o=Be.dirname(r),i=Be.dirname(o);return Be.join(i,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let r;try{r=this.readBuiltInConfigText()}catch{po("read builtin acl permission failed.");return}if(r!==void 0)try{let o=JSON.parse(r),s=(Array.isArray(o)?o:Ka(o)?Object.values(o):[]).filter(Ka).map(a=>new Xa(a));s.forEach(a=>{let c=a.permissionInsteadName;bN(c)&&(a.permissionInsteadName=Ya(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(o){po(`failed to parse aclPermissionsInfo.json: ${o}`)}}static initAclPermissionFromSDK(e,t,r){let o=this.parsePermissionDefinitionFile(e);o&&o.forEach(i=>{if(!Ka(i))return;let s=i,a=pu(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(Mw(a)||(this.generateAclInfos(r,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||pu(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||pu(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:EN(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let o=new Xa;o.permissionName=t;let i=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;o.permissionDisplayName=i;let s=PN(r,this.ACL_SINCE_KEY);o.minSupportApiLevel=String(s),this.handleInsteadName(o,i),e.add(o)}static parsePermissionDefinitionFile(e){let t=Be.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!mo.existsSync(t))return;let r;try{r=mo.readFileSync(t,"utf-8")}catch(s){po(`failed to load permissionDefinitions.json: ${s}`);return}let o;try{let s=JSON.parse(r);if(!Ka(s)){po("json object is null");return}o=s}catch(s){po(`failed to parse permissionDefinitions.json: ${s}`);return}let i=o[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(i)){po("definePermissions is not an array");return}return i}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=Ya(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=Ya(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function Qa(n,e){let t=new Set,r=new Set;On.handleSpecificAclPermissions(),On.initAclPermission(n,e);for(let o of n.profile.modules){let i=Fw(o,n,e,r,Za.join("src","main"));for(let a of i)t.add(a);let s=Fw(o,n,e,r,Za.join("src","ohosTest"));for(let a of s)t.add(a)}return IN(r),t}function IN(n){if(n.size>0)throw new Error(Ow.DUPLICATE_PERMISSION)}function Fw(n,e,t,r,o){let i=DN(e.rootDir,n,o);if(i==null)return new Set;let s=[];for(let w of i){if(typeof w!="object"||w===null)continue;let b=AN(w,"name");b&&s.push(b)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=Za.join(t.sdkPath,"default","sdk-pkg.json"),l=Ja(c),d=On.getAclPermissionInfos(e),g=new Set(Array.from(d).filter(w=>{let b=Number(w.minSupportApiLevel);return Number.isFinite(b)&&b<=l}).map(w=>w.permissionName));for(let w of Array.from(a))g.has(w)||a.delete(w);return a}function AN(n,e){let t=n[e];return typeof t=="string"?t:""}function DN(n,e,t){let r=Za.join(n,e.srcPath,t,"module.json5"),o=kN(r);if(o==null)return null;let i=TN(o,"module");return i==null?null:RN(i,"requestPermissions")}function kN(n){try{if(!_w.existsSync(n))return null;let e=_w.readFileSync(n,"utf-8");return CN.parse(e)}catch{return null}}function TN(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 RN(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}var fu=class{verifyStorePassword(e,t){try{let r=Mn.readFileSync(e),o=$w.asn1.fromDer(r.toString("binary"));return $w.pkcs12.pkcs12FromAsn1(o,t),!0}catch{return!1}}getLocalCerFingerprints(e){let r=Mn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(r&&r.length>0)return r.map(o=>this.formatFp(new ec.X509Certificate(o).fingerprint256));try{return[this.formatFp(new ec.X509Certificate(Mn.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let o=Mn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let i of o)try{let s=new ec.X509Certificate(i);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 NN(n){let e=Mn.readFileSync(n,"utf-8"),t=LN(e),r=null;if(t)try{r=JSON.parse(t)}catch{r=null}let o=r?.["bundle-info"]??{};return{rawContent:e,bundleNameInProfile:mu(o["bundle-name"]),expiryDate:ON(r?.validity?.["not-after"]),cerFingerprintInProfile:MN(mu(o["development-certificate"])),deviceUdidsInProfile:_N(r?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:FN(r?.acls?.["allowed-acls"]),teamIdInProfile:mu(o["developer-id"])}}function LN(n){let e=n.indexOf("{");if(e<0)return null;let t=0,r=-1,o=!1,i=!1;for(let s=e;s<n.length;s++){let a=n[s];if(o){i?i=!1:a==="\\"?i=!0:a==='"'&&(o=!1);continue}if(a==='"')o=!0;else if(a==="{")t++;else if(a==="}"&&(t--,t===0)){r=s;break}}return r<0?null:n.slice(e,r+1)}function ON(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function MN(n){if(!n)return null;try{let t=new ec.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function _N(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 FN(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 mu(n){return typeof n=="string"?n:null}var Di=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.#o(r)??n.#i(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,o=e.teamId,i=e.productName??"default",s=J.discover(process.cwd()),a=s.rootDir,[c,l]=await Promise.all([jN(i,a),HN(t.hdcPath)]),d=null;if(Hw(c).allExist)try{d=NN(c.profileFile)}catch{}return{force:r,teamId:o,productName:i,projectPath:a,materialPaths:c,bundleName:s.getBundleName(),deviceUdids:l,storePassword:await $N(a,i,c.storeFile),localAclPermissions:[...Qa(s,t)].sort(),hapSignTool:new fu,profileInfo:d}}static#t(e){return e.force?(h("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:Je({force:!0})}):null}static#n(e){let t=Hw(e.materialPaths);return t.allExist?null:(h(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:Je({allFilesExist:!1,missingFiles:t.missing})})}static#r(e){return(e.profileInfo?.rawContent??"").trim().length>0?null:(h("[reGenerateSign] profile content is empty"),{shouldRegenerate:!0,reason:"Profile file content is empty",checkDetails:Je({allFilesExist:!0,profileContentNotEmpty:!1})})}static#o(e){let t=e.profileInfo?.expiryDate;return!t||t>=new Date?null:(h(`[reGenerateSign] profile expired at ${t.toISOString()}`),{shouldRegenerate:!0,reason:`Profile expired at ${t.toISOString()}`,checkDetails:Je({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!1})})}static#i(e){let t=e.profileInfo?.bundleNameInProfile;return t&&t===e.bundleName?null:(h(`[reGenerateSign] bundleName mismatch \u2014 current=${e.bundleName}, profile=${t}`),{shouldRegenerate:!0,reason:`bundleName mismatch: current=${e.bundleName}, in profile=${t}`,checkDetails:Je({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!1})})}static#s(e){let t=e.profileInfo?.teamIdInProfile;return t&&t===e.teamId?null:(h(`[reGenerateSign] teamId mismatch \u2014 current=${e.teamId}, profile=${t}`),{shouldRegenerate:!0,reason:`teamId mismatch: current=${e.teamId}, in profile=${t}`,checkDetails:Je({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=BN(e.profileInfo?.deviceUdidsInProfile??[],e.deviceUdids);return t.allPresent?null:(h(`[reGenerateSign] missing device UDIDs: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Device UDID(s) not in profile: ${t.missing.join(", ")}`,checkDetails:Je({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return WN(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(h("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:Je({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:(h("[reGenerateSign] certificate mismatch"),{shouldRegenerate:!0,reason:"Certificate mismatch between profile and local .cer file",checkDetails:Je({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:(h(`[reGenerateSign] local certificate expired at ${r.toISOString()}`),{shouldRegenerate:!0,reason:`Local certificate expired at ${r.toISOString()}`,checkDetails:Je({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:(h("[reGenerateSign] keystore password verification failed"),{shouldRegenerate:!0,reason:"Keystore password verification failed (storeFile may be corrupted or password changed)",checkDetails:Je({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})}):(h("[reGenerateSign] no stored keystore password"),{shouldRegenerate:!0,reason:"No stored keystore password available for verification",checkDetails:Je({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})})}static#p(){return h("[reGenerateSign] all checks passed \u2014 skip regeneration"),{shouldRegenerate:!1,reason:"",checkDetails:Je({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function jN(n,e){let[t,r,o,i]=await Promise.all([Ce(n,e,"p12"),Ce(n,e,"csr"),Ce(n,e,"cer"),Ce(n,e,"p7b")]);return{storeFile:t,csrFile:r,cerFile:o,profileFile:i}}async function $N(n,e,t){let r=Uw.join(n,"build-profile.json5");if(!Mn.existsSync(r))return;let o;try{o=xN.parse(Mn.readFileSync(r,"utf-8"))}catch{return}let a=(o?.app?.signingConfigs??[]).find(c=>c.name===e)?.material?.storePassword;if(a)try{return await Ln.decryptPassword(a,t)}catch{return}}async function HN(n){h(`Executing: ${n} list targets`);let{stdout:e}=await jw(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let o of e.split(`
|
|
1398
|
+
`)){let i=o.trim();if(!i||i.startsWith("[Empty]"))continue;let s=i.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 o of t)try{h(`Executing: ${n} -t ${o} shell bm get -u`);let{stdout:i}=await jw(n,["-t",o,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),s=UN(i);s&&r.push(s)}catch{h(`[reGenerateSign] Failed to get UDID for ${o}, skipping`)}return r}function UN(n){let e=n.trim();if(!e)return null;let t=e.split(`
|
|
1399
|
+
`);for(let o=0;o<t.length-1;o++)if(t[o].includes("udid of current device is")){let s=t[o+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 Hw(n){let e=[n.storeFile,n.csrFile,n.cerFile,n.profileFile],t=[];for(let r of e)Mn.existsSync(r)||t.push(r);return{allExist:t.length===0,missing:t}}function BN(n,e){let t=[];for(let r of e)n.includes(r)||t.push(r);return{allPresent:t.length===0,missing:t}}function WN(n,e){let t=[...n].sort(),r=[...e].sort();return t.length!==r.length?!1:t.every((o,i)=>o===r[i])}function Je(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 hu}from"util";import{execa as gu}from"execa";async function Ww(n,e){let t=await tc(n);if(!t)throw new Error(P.DEVICE_LIST_EMPTY);let r=await zN(e);if(t.length===0)for(let s of r)await VN(n,s.udid,s.deviceName);else for(let s of r)await GN(n,t,s.udid,s.deviceName);let i=(await tc(n)).map(s=>s.id);if(i.length===0)throw new Error(P.DEVICE_LIST_EMPTY);return i}async function VN(n,e,t){await zw(n,e,Vw(t))}async function GN(n,e,t,r){for(let o=0;o<e.length;o++){if(t===e[o].udid)return;if(o===e.length-1){await zw(n,t,Vw(r));return}}}function Vw(n){switch(n){case"liteWearable":return"1";case"wearable":return"2";case"tv":return"3";default:return"4"}}async function Bw(n,e=1,t=100){let r=`${te.BASE_URL}${te.DEVICE_LIST_PATH}?encodeFlag=0&start=${e}&pageSize=${t}`,o=qw(n),i=await N.get(r,{headers:o});if(!i)throw hu("query devices failed: response is null"),new Error(P.ERROR_WHILE_ADD_DEVICE);if(i.statusCode!==200)throw Gw(i.statusCode,i.statusText,i.data);let s=JSON.parse(i.data);if(!s||!s.list)throw hu("query devices failed: response list is null"),new Error(s.ret?.msg||P.ERROR_WHILE_ADD_DEVICE);return{deviceList:s.list,total:s.totalCount||0}}function Gw(n,e,t){return n===ht.FORBIDDEN?e===ye.OPENPROXY_BLOCKED_URL?new Error(P.ERR_CERT_NETWORK_ERROR):new Error(P.ERR_FORBIDDEN):n===ht.UNAUTHORIZED?new Error(P.ERR_UNAUTHORIZED):t.includes(ye.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(P.DEVICE_LIMIT_REACHED):new Error(P.ERROR_WHILE_ADD_DEVICE)}async function tc(n){let t=await Bw(n,1,100);if(!t||!t.deviceList||t.deviceList.length===0)return[];let r=[...t.deviceList],o=t.total,i=Math.floor(o/100)+(o%100===0?0:1);for(let s=2;s<=i;s++){let a=await Bw(n,s,100);if(!a||!a.deviceList||a.deviceList.length===0)break;r.push(...a.deviceList)}return r}async function zw(n,e,t){let r=`${te.BASE_URL}${te.DEVICE_ADD_PATH}`,o=qw(n),s={deviceName:`auto_sign_device_No.${Math.floor(Math.random()*3e3)}${Date.now()}`,udid:e,deviceType:t},a=await N.postAllowFailure(r,{headers:o,params:s});if(!a)throw hu("add device failed: response is null"),new Error(P.ERROR_WHILE_ADD_DEVICE);if(a.statusCode!==200)throw Gw(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(ye.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(P.DEVICE_LIMIT_REACHED):c.includes(ye.DEVICE_NAME_REPEAT_CODE)?new Error(P.DEVICE_NAME_REPEAT):new Error(P.ERROR_WHILE_ADD_DEVICE)}function qw(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}async function zN(n){let{stdout:e}=await gu(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let o of e.split(`
|
|
1400
|
+
`)){let i=o.trim();if(!i||i.startsWith("[Empty]"))continue;let s=i.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 o of t)try{let i=await qN(o,n),s=await JN(o,n);i.length>0&&r.push({id:"",udid:i,deviceName:s})}catch{h(`Failed to get device info for ${o}, skipping`)}return r}async function qN(n,e){let{stdout:t}=await gu(e,["-t",n,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),r=t.trim();if(!r)return"";let o=r.split(`
|
|
1401
|
+
`);for(let s=0;s<o.length-1;s++)if(o[s].includes("udid of current device is")){let c=o[s+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(c)return c[0].toUpperCase()}let i=r.match(/[A-Fa-f0-9]{64}/);return i?i[0].toUpperCase():""}async function JN(n,e){let{stdout:t}=await gu(e,["-c","-t",n,"shell","getprop","hw_sc.build.os.deviceType"],{stdio:["ignore","pipe","pipe"]});return YN(t)}function YN(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 cr from"fs";import{createHash as KN}from"crypto";import{debuglog as qt}from"util";import{Buffer as Yw}from"buffer";import{createPublicKey as XN,X509Certificate as yu}from"crypto";import{readFileSync as ZN}from"fs";import lr from"node-forge";async function Kw(n,e){console.log("Start generating profile");let{productName:t,bundleName:r,projectPath:o,aclPermissionList:i,allDeviceIds:s,certIds:a,keyAlias:c,keyPwd:l}=e;if(s==null||s.length===0)throw new Error(P.DEVICE_LIST_EMPTY);let d=`${te.BASE_URL}${te.PROVISION_ADD_TEST_PATH}`,g=QN(t,r),w=await tL(n,d,a||[],r,s,g,i||[]);if(!w||!w.profileInfo||!w.profileInfo.provisionFileUrl)throw qt("add provision failed, the provision file url is null"),new Error(P.ADD_PROFILE_FAIL);let b=w.profileInfo,ne=(await iL(n,b.provisionFileUrl)).urlList,we=w.profileInfo.id;if(ne&&ne.length>0){let wt=await Aw(t,o),Jt=wt.profilePath;if(!await sL(ne,Jt))throw await Jw(n,we),new Error(P.ERROR_WHILE_DOWNLOAD_PROFILE);if(await Jw(n,we),cr.existsSync(wt.certPath)&&cr.existsSync(Jt)&&cr.existsSync(wt.p12Path)){let sv=cr.readFileSync(wt.certPath,"utf8"),av=cr.readFileSync(Jt,"utf8");return aL(av,sv,wt.p12Path,c,l)||oL(Jt),Jt}}throw new Error(P.ADD_PROFILE_FAIL)}function QN(n,e){let t=n?`${n}_`:"";return`${eL(`${t}${e}_${e}`)}`}function eL(n){return KN("sha256").update(n).digest("hex").substring(0,16)}async function tL(n,e,t,r,o,i,s){nL(r);let a=vu(n),c={certList:t,packageName:r,deviceList:o,provisionName:i};s.length&&(c.aclPermissionList=s);let l=await N.postAllowFailure(e,{headers:a,params:c});if(!l)throw qt("add provision failed: response is null"),new Error(P.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw wu(l.statusCode,l.statusText,l.data);let d=JSON.parse(l.data);if(!d||!d.ret||d.ret.code!==0)throw qt(`add provision fail: ${l.data}`),rL(l.data,i),new Error(d.ret?.msg||P.ADD_PROFILE_FAIL);let g=d.provisionFileUrl;return{profileInfo:{id:d.id,name:i,provisionFileUrl:g}}}function wu(n,e,t){return n===ht.FORBIDDEN?e===ye.OPENPROXY_BLOCKED_URL?new Error(P.ERR_CERT_NETWORK_ERROR):new Error(P.ERR_FORBIDDEN):n===ht.UNAUTHORIZED?new Error(P.ERR_UNAUTHORIZED):t.includes(ye.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(P.TEST_PROVISION_EXCEEDS_LIMIT):new Error(P.ADD_PROFILE_FAIL)}function nL(n){if(!n||n.trim().length===0)throw new Error(P.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!Ue.BUNDLE_NAME_REGEX.test(n))throw new Error(P.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function rL(n,e){if(n.includes(ye.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(P.TEST_PROVISION_EXCEEDS_LIMIT);if(n.includes(ye.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(P.PROFILE_NAME_REPEAT)}async function Jw(n,e){if(!e||e.trim().length===0)return;let t=`${te.BASE_URL}${te.PROVISION_DELETE_PATH}?id=${e}`,r=await N.deleteAllowFailure(t,{headers:vu(n)});if(r.statusCode!==200)throw wu(r.statusCode,r.statusText,r.data);let o=JSON.parse(r.data);(!o||!o.ret||o.ret.code!==0)&&qt(`delete provision failed: ${r.data}`)}function oL(...n){for(let e of n)try{cr.existsSync(e)&&cr.unlinkSync(e)}catch(t){qt(`delete local sign file error: ${t.message}`)}}async function iL(n,e){let t=`${te.BASE_URL}${te.CERT_DOWNLOAD_URL_PATH}`,r=vu(n),o={sourceUrls:e},i=await N.postAllowFailure(t,{headers:r,params:o});if(!i)throw qt("get download list failed: response is null"),new Error(P.ADD_PROFILE_FAIL);if(i.statusCode!==200)throw wu(i.statusCode,i.statusText,i.data);let s=JSON.parse(i.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw qt("download: The application does not exist"),new Error(s.ret?.msg||P.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function sL(n,e){if(!n||n.length===0)return!1;let t=n[0];return await Ci(t.newUrl,e,t.sha256),!0}function aL(n,e,t,r,o){return cL(n,e),r=r||Ue.TARGET_FRIENDLY_NAME,o=o||"",lL(e,t,r,o),!0}function cL(n,e){if(e.lastIndexOf(Ue.CERT_BEGIN_HEADER)<0)throw new Error(P.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(Ue.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!n.includes(t))throw new Error(P.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}function lL(n,e,t,r){let o=n.matchAll(Ue.CERTIFICATE_PATTERN_GLOBAL),i=[],s=new Date;for(let c of o)try{let l=c[0],d=dL(l),g=new Date(d.validFrom),w=new Date(d.validTo);if(s<g||s>w){let b=`Certificate is not valid, Valid from ${g} to ${w}`;throw console.warn(`checkCertificateInValidityPeriod: ${b}`),new Error(P.CERTIFICATE_HAS_EXPIRED)}i.push(d)}catch(l){throw console.warn(`checkCertificateInValidityPeriod\uFF1A ${l.message}`),new Error(P.CERTIFICATE_HAS_EXPIRED,{cause:l})}if(!i||i.length===0)throw new Error(P.CERTIFICATE_HAS_EXPIRED);if(!pL(e,t,r,i))throw new Error(P.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function dL(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new yu(t);let r=Yw.from(t,"base64");return new yu(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}function uL(n){if(n.cert){let e=lr.pki.publicKeyToPem(n.cert.publicKey);return XN(e).export({type:"spki",format:"der"})}if(n.asn1)try{let e=lr.asn1.toDer(n.asn1).getBytes(),t=Yw.from(e,"binary");return new yu(t).publicKey.export({type:"spki",format:"der"})}catch(e){return qt(`Failed to parse cert from asn1: ${e}`),null}return null}function pL(n,e,t,r){try{let o=ZN(n),i=lr.asn1.fromDer(lr.util.createBuffer(o)),c=lr.pkcs12.pkcs12FromAsn1(i,t).getBags({bagType:lr.pki.oids.certBag})[lr.pki.oids.certBag]||[];for(let l of c){let d=l.attributes?.friendlyName?.[0];if(!d||d.toLowerCase()!==e.toLowerCase())continue;let g=uL(l);if(!g)continue;if(r.some(b=>{let $=b.publicKey.export({type:"spki",format:"der"});return g.equals($)}))return!0}return!1}catch(o){let i=o instanceof Error?o.message:String(o);return qt(`Failed to process P12 file: ${n}, error: ${i}`),!1}}function vu(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var Zw="https://developer.huawei.com",mL={"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"},fL="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function hL(n){let e=mL[n];return e?`${Zw}${e}`:void 0}function gL(){return`${Zw}${fL}`}var yL={"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 Xw(n,e){return(yL[n]??n).replace(/\{(\d+)\}/g,(r,o)=>String(e[Number(o)]??""))}function wL(n){return Array.from(n).join(", ")}function Qw(n,e){if(n.size===0)return;let t=On.getAclPermissionInfos(e),r=new Set;for(let g of t)n.has(g.permissionName)&&r.add(g);for(let g of r){let w=hL(g.permissionName);w!=null&&(g.permissionHelpUrlKey=w)}let o=new Set;for(let g of r)o.add(g.permissionDisplayName);let i=new Set;for(let g of r)if(g.permissionHelpUrlKey!=null){let w=g.permissionInsteadName??g.permissionDisplayName;i.add(`${w} (${g.permissionHelpUrlKey})`)}let s=gL(),a=Xw("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=i.size>0?Array.from(i).join(", ")+".":"",d=Xw("acl.permissions.warn",[wL(o),l,c]);console.log(d)}var nc=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=J.discover(process.cwd()),{passed:!0,message:""}}catch(t){return h(`[EnvCheck] Project.discover() failed: ${t.message}`),e(se.PROJECT_DIR_MISSING)}}checkProduct(e,t){try{return this._project.validateProduct(e),{passed:!0,message:""}}catch(r){return h(`[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 h(`[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:se.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import vL from"fs";import ev from"path";var rc=class{constructor(e){this.toolProvider=e}toolProvider;checkJava(e){try{return this.toolProvider.assertJava(),{passed:!0,message:""}}catch(t){return h(`[EnvCheck] Java check failed: ${t.message}`),e(`${t.message}`)}}checkHapSignTools(e){let t=this.toolProvider.sdkPath,r=ev.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");if(!vL.existsSync(r)){let o=ev.join("sdk","default","openharmony","toolchains","lib","hap_sign_tools.jar");return e(`hap_sign_tools.jar not found.Check whether ${o} exists.`)}return{passed:!0,message:""}}};var oc=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await ke.getUserInfo()}catch(e){return h(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await ke.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(se.LOGIN_REQUIRED)}catch(t){return h(`[EnvCheck] Login check failed: ${t.message}`),e(se.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(se.TEAM_INFO_FAILED);try{if((await ln()).teamList.length>0)return{passed:!0,message:""}}catch(r){return h(`[EnvCheck] Team API error: ${r.message}`),e(se.TEAM_INFO_FAILED)}return h("[EnvCheck] No teams found for current user"),e(se.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(se.REALNAME_REQUIRED):t.isRealName!==!0?(h("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(se.REALNAME_REQUIRED)):{passed:!0,message:""}:e(se.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let r=e??"";try{let o=await ln();if(r=e??(o.teamList.length>0?o.teamList[0].id:t.userId)??"",!o.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 h(`[EnvCheck] ${s}`),{passed:!1,message:s}}return{passed:!0,message:""}}catch(o){return h(`[EnvCheck] Team ID check failed: ${o.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(se.REGION_CHINA_ONLY):{passed:!0,message:""}:(h("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(se.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function SL(n){try{let{teamList:e}=await ln();if(e.length>0)return e[0].id}catch(e){h(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function bL(n){let e=await ke.getUserInfo(),t=await ke.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await SL(e.userId);if(!r)throw new Error("No team found");let o={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await tc(o)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var ic=class{constructor(e){this.toolProvider=e}toolProvider;async checkDevice(e,t){try{let r=await bL(t);if(r.length>0)return h(`[EnvCheck] Scenario 4 Device check: ${r.length} device(s) found in AGC cloud, skipping local device check`),{passed:!0,message:""};h("[EnvCheck] Scenario 4 Device check: no cloud devices found, falling back to local hdc");let i=await ie.from(this.toolProvider).listDevices();return i.length===0?(h("[EnvCheck] Scenario 4 Device check: no local devices found"),e(se.DEVICE_MISSING)):i.some(a=>Ct(a.serial))?{passed:!0,message:""}:(h("[EnvCheck] Scenario 4 Device check: local device found but not an emulator"),e(se.DEVICE_MISSING))}catch(r){return h(`[EnvCheck] Scenario 4 Device check failed: ${r.message}`),e(se.DEVICE_DETECT_FAILED)}}};var sc=class{projectChecker=new nc;toolchainChecker=null;authChecker=new oc;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=i=>(i.passed||this.fail(i),!0),o=[()=>this.authChecker.checkLogin(t),()=>this.authChecker.checkRealname(t),()=>this.authChecker.checkTeamInfo(t)];for(let i of o)if(!r(await i()))return!1;return!(e.teamId&&!r(await this.authChecker.checkTeamId(e.teamId)))}async initToolchain(){try{let e=await I.new();return this.toolchainChecker=new rc(e),this.deviceChecker=new ic(e),!0}catch(e){throw h(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(se.TOOLCHAIN_INIT_FAILED,{cause:e})}}async runDeviceCheck(e,t){return(o=>o.passed?!0:(this.fail(o),!1))(await this.deviceChecker.checkDevice(t,e.teamId))}async runProjectChecks(e,t){let r=i=>i.passed?!0:(this.fail(i),!1);if(!r(this.projectChecker.checkProjectDir(t))||!r(this.projectChecker.checkAtomicService()))return!1;let o=[()=>this.projectChecker.checkProduct(e.productName,t),()=>this.projectChecker.checkBundleName(e.productName,t),()=>this.toolchainChecker.checkJava(t),()=>this.toolchainChecker.checkHapSignTools(t)];for(let i of o)if(!r(i()))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 h(`[EnvCheck] FAIL: ${e.message}`),new Error(e.message)}};var tv=5*1024*1024;function CL(n){try{let e=bu.statSync(n);if(e.size>tv)throw new Error(`Profile file too large: ${e.size} bytes (max ${tv} bytes): ${n}`);let t=bu.readFileSync(n,"utf-8");return rv.parse(t)}catch(e){if(e.code==="ENOENT")return{app:{signingConfigs:[],products:[]}};throw new Error(`Failed to read profile: ${n}`,{cause:e})}}function IL(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function AL(n){if(n.keyPwd===n.storePassword){let r=await Ln.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await Ln.encryptedPassword(n.keyPwd,n.p12FilePath),t=await Ln.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function DL(n,e,t){let r=nv.join(n,"build-profile.json5"),o=CL(r);IL(o);let i=t??"default",{keyPassword:s,storePassword:a}=await AL(e),c={name:i,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:s,profile:e.profileFilePath,signAlg:gt.signAlg,storeFile:e.p12FilePath,storePassword:a}},l=o.app?.signingConfigs?.findIndex(g=>g.name===i);l!==void 0&&l>=0?o.app.signingConfigs[l]=c:o.app.signingConfigs.push(c);let d=o.app?.products?.findIndex(g=>g.name===i);d!==void 0&&d>=0?o.app.products[d].signingConfig=i:o.app.products.push({name:i,signingConfig:i}),bu.writeFileSync(r,rv.stringify(o,null,2),"utf-8")}async function kL(n){let e=await ke.getUserInfo(),t=await ke.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 TL(n){let e=n.product||"default";await new sc().preflight({productName:e,teamId:n.teamId}),console.log("Executing signature generate command");let r=await kL(n),o=await I.new(),{shouldRegenerate:i}=await Di.shouldRegenerate({force:n.force??!1,teamId:r.teamId,productName:n.product},o);if(!i){console.log(Su("Signature generation completed successfully."));return}await RL(n,r,o),console.log(Su("Signature generation completed successfully."))}async function RL(n,e,t){let r=await au(e,n.product),o=xL(n,e,r,t);o.allDeviceIds=await Ww(e,t.hdcPath),await Kw(e,o);let i=J.discover(process.cwd()).rootDir;await DL(i,r,n.product??"default"),console.log(Su(`Signing config written to ${nv.join(i,"build-profile.json5")}`))}function xL(n,e,t,r){let o=process.cwd(),i=J.discover(o),s=Qa(i,r);return Qw(s,i),{productName:n.product||"default",bundleName:i.getBundleName(),projectPath:i.rootDir,teamId:e.teamId,force:n.force||!1,aclPermissionList:[...s],certIds:[t.certId],keyAlias:t.keyAlias,keyPwd:t.keyPwd}}var ov=new EL("signature").description("Generate application signature.");ov.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=>{let e={event:E.CommandExecuted,args:["signature","generate",...n.force?["--force"]:[],...n.teamId?["--team-id"]:[],...n.product?["--product"]:[]]},t=Date.now(),r=!0,o=null;try{await TL(n)}catch(i){r=!1,o=ce(i),console.error(PL(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await k.track(e,i)}});var iv=ov;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";NL();if(!Kt())try{k.init(ac.join(et(),"TraceLogData")),k.startScheduler()}catch(n){f.error(`[telemetry] init failed: ${n instanceof Error?n.message:String(n)}`)}(async()=>{if(!Kt())try{let n=await I.new();k.setSourceType(n.sourceType);let e=await I.getCltVersion();e&&k.setCltVersion(e);let t=await I.getStudioVersion();t&&k.setStudioVersion(t)}catch(n){f.error(`[telemetry] toolchain info failed: ${n instanceof Error?n.message:String(n)}`)}})();ae.name("devecocli").description("HarmonyOS application development command line tool").version("1.3.0-Test.16");ae.addCommand(kp);ae.addCommand(em);ae.addCommand(cm);ae.addCommand(Am);ae.addCommand(Qm);ae.addCommand(Ef);ae.addCommand(Yf);ae.addCommand(Zf);ae.addCommand(lh);ae.addCommand(wh);ae.addCommand(Wh);ae.addCommand(my);ae.addCommand(jy);ae.addCommand(ww);ae.addCommand(iv);var Eu=process.argv.slice(2);Eu.length>=2&&Eu[Eu.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);function OL(n){let e=n;for(;e.parent&&e.parent!==ae;)e=e.parent;return e}var ML=new Set(["update","auth","serve"]);ae.hook("preAction",async(n,e)=>{let t=OL(e),r=Er();if(t.name()==="update")return;let o=new on(ac.join(et(),"update")),i=rn();if(r==="off"&&o.getBlockedVersions().includes(i))throw new Error(`devecocli ${i} has been disabled, run \`devecocli update\` to upgrade`);process.env.DEVECO_CLI_SKIP_VERSION_CHECK||ML.has(t.name())||await I.checkVersion()});ae.hook("postAction",async(n,e)=>{if(process.exitCode||Er()!=="off")return;await new Ro(e).checkAndNotify()});ae.parseAsync(process.argv).finally(()=>{k.stopScheduler();try{wc(ac.join(et(),"TraceLogData"))}catch(n){f.error(`[telemetry] background upload spawn check failed: ${n instanceof Error?n.message:String(n)}`)}}).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(LL(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
|