@deveco-test/hmos-deveco-cli 0.4.0-TD.2.4 → 0.4.0-TD.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +112 -110
- package/index.zip +0 -0
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,79 +1,79 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var uv=Object.defineProperty;var pv=(n,e)=>{for(var t in e)uv(n,t,{get:e[t],enumerable:!0})};import{program as se}from"commander";import{red as sO}from"colorette";var so={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},Ri={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 ve={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"},q={LOGIN_URL:"https://devecostudio.huawei.com",CN_LOGIN_URL:"https://cn.devecostudio.huawei.com",AUTH_APPLY_PATH:"console/DevEcoIDE/apply",TEMP_TOKEN_CHECK_PATH:"authrouter/auth/api/temptoken/check",JWT_TOKEN_CHECK_PATH:"authrouter/auth/api/jwToken/check",LOGIN_SUCCESS_PATH:"console/DevEcoCLI/loginSuccess",LOGIN_FAILED_PATH:"console/DevEcoCLI/loginFailed",LOGOUT_PATH:"authrouter/auth/api/logout",AGC_TEAM_LIST_URL:"https://connect-api.cloud.huawei.com/api/ups/user-permission-service/v1/user-team-list"},Ln={ALGORITHM:"aes-256-gcm",KEY_LENGTH:32,IV_LENGTH:12,KEK_VERSIONS:["kek-v1","kek-v2","kek-v3"]},ao={TMS_URL:"https://terms-drcn.platform.dbankcloud.cn/agreementservice/user",PRIVACY_ID:"20000257",PRIVACY_URL:"https://legal.cloud.huawei.com/terms/scope/huawei/deveco-cli/privacy-statement.htm?code=CN&language=zh-CN&branchid=0&contenttag=default"},co={baseUrl:q.LOGIN_URL,authUrl:q.AUTH_APPLY_PATH,tempTokenCheckUrl:q.TEMP_TOKEN_CHECK_PATH,jwtTokenCheckUrl:q.JWT_TOKEN_CHECK_PATH,successRedirectUrl:q.LOGIN_SUCCESS_PATH,failedRedirectUrl:q.LOGIN_FAILED_PATH,logoutUrl:q.LOGOUT_PATH,agcTeamListUrl:q.AGC_TEAM_LIST_URL,appId:ve.APP_ID,timeout:so.LOGIN_TIMEOUT_MS,countryCode:"CN"};import{Command as aS}from"commander";import{green as Nc,red as Lc,yellow as Oc}from"colorette";import Q from"fs";import*as H from"path";import It from"json5";import*as gc from"fs";import*as Se from"path";function f(n){process.env.DEVECO_CLI_DEBUG&&process.stderr.write(`[DEBUG] ${n}
|
|
3
3
|
`)}var R=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(`
|
|
4
4
|
`)}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 assertRelativeTimeRange(e,t){if(e!==void 0&&t!==void 0&&e<t)throw new Error("--from must be greater than or equal to --to when both are provided (e.g. --from 30s --to 10s)")}static filterLogsByRelativeWindow(e,t,r,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 h=n.extractTimestampFromLogLine(d,o);h&&(l=n.isWithinBounds(h,i,s)),l&&c.push(d)}return c.join(`
|
|
5
|
-
`)}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",h=Number.parseInt(d.padEnd(3,"0").slice(0,3),10),w=new Date(o,i,s,a,c,l,h);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 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 f(`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=hc.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=hc.realpathSync(i)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${i}`}}return n.isPathContained(s,o)}};var q=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=H.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=H.join(e,"build-profile.json5");if(!Q.existsSync(t))return null;try{let r=Q.readFileSync(t,"utf-8"),o=It.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=R.resolvePathWithinRoot(this.rootDir,t.srcPath),o=H.join(r,"src","main","module.json5");if(!Q.existsSync(o))return"entry";try{let i=Q.readFileSync(o,"utf-8");return It.parse(i)?.module?.type||"entry"}catch(i){return console.warn(`Warning: Failed to parse ${o}:`,i),"entry"}}findOwningModule(e){let t=H.normalize(e);for(let r of this.profile.modules){let o=H.normalize(H.join(this.rootDir,r.srcPath)),i=o+H.sep;if(t.startsWith(i)||t===o)return r.name}return null}getModuleProfile(e){let t=this.profile.modules.find(a=>a.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let r=R.resolvePathWithinRoot(this.rootDir,t.srcPath),o=H.join(r,"build-profile.json5");if(!Q.existsSync(o))throw new Error(`Build profile for module '${e}' not found at ${o}.`);let i=Q.readFileSync(o,"utf-8");return It.parse(i)}getBundleName(){let e=H.join(this.rootDir,"AppScope","app.json5");if(Q.existsSync(e))try{let t=Q.readFileSync(e,"utf-8"),r=It.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=H.join(this.rootDir,"AppScope","app.json5");if(!Q.existsSync(e))return!1;try{let t=Q.readFileSync(e,"utf-8");return It.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=R.resolvePathWithinRoot(this.rootDir,r.srcPath),i=H.join(o,"src","main","module.json5");if(!Q.existsSync(i))return"EntryAbility";try{let s=Q.readFileSync(i,"utf-8"),c=It.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=R.resolvePathWithinRoot(this.rootDir,t.srcPath),o=H.join(r,"oh-package.json5");if(!Q.existsSync(o))return[];let i=[];try{let s=Q.readFileSync(o,"utf-8"),c=It.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=H.join(t.srcPath,d),v=R.resolvePathWithinRoot(this.rootDir,w),I=this.profile.modules.find(G=>H.resolve(this.rootDir,G.srcPath)===v);I&&i.push(I.name)}}catch{}return i}getModuleName(e){let t=this.profile.modules.find(i=>i.name===e);if(!t)return e;let r=R.resolvePathWithinRoot(this.rootDir,t.srcPath),o=H.join(r,"src","main","module.json5");if(!Q.existsSync(o))return e;try{let i=Q.readFileSync(o,"utf-8");return It.parse(i)?.module?.name||e}catch(i){return console.warn(`Warning: Failed to parse ${o}:`,i),e}}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(!Q.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 v=this.getSignedHapName(c,i.srcPath,o,t);v&&(d=v)}let h=s?"-signed.hsp":"-signed.hap";if(!r&&!d.endsWith(h))throw new Error(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`);let w=this.buildOutputPath(i.srcPath,o,["outputs",t,d]);if(!Q.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=H.isAbsolute(c)?c:this.buildOutputPath(o.srcPath,r,["outputs",t,c]);if(!Q.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 Q.existsSync(s)?i:null}buildOutputPath(e,t,r){let o=R.resolvePathWithinRoot(this.rootDir,e),i=H.resolve(o,"build",t,...r);return R.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=Q.readFileSync(e,"utf-8"),o=It.parse(r),i,s=!1,a=Array.isArray(o)?o:[o];for(let l of a)i||(i=l[t]),s||(s=l.isSigned===!0);if(!i)throw new Error(`Could not find ${t} in output_metadata.json at ${e}`);this.validatePackageName(i);let c=this.collectRemoteHsps(a);return{packageName:i,isSigned:s,dependRemoteHsps:c}}validatePackageName(e){let t=H.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 pe from"fs";import*as We from"os";import*as S from"path";import Cu from"fs";import*as Ti from"os";import*as Ri from"path";import pv from"regedit";import{execFileSync as dv}from"child_process";import Su from"fs";import*as bu from"os";import*as gc from"path";function Di(n,e){let t=gc.join(n,"Contents","Info.plist");if(!Su.existsSync(t)){f(`[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=dv(r,o,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(i&&!i.includes("Does Not Exist"))return i}catch{}}function uv(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}`),"");if(i&&/^\d+$/.test(i))return`${e}.${i}`}return e}function io(n){if(bu.platform()==="darwin")return uv(n);let e=gc.join(n,"product-info.json");try{let t=JSON.parse(Su.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}function so(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 fv(n){return n.filter(e=>{try{return Cu.statSync(e).isDirectory()}catch{return!1}})}function mv(){let n=[];for(let e of[Ri.join(Ti.homedir(),"Applications"),"/Applications"])try{n.push(...Cu.readdirSync(e).filter(t=>t.endsWith(".app")&&t.toLowerCase().includes("deveco")).map(t=>Ri.join(e,t)))}catch{}return n}function Eu(n){return new Promise((e,t)=>pv.list(n,(r,o)=>r?t(r):e(o)))}async function Pu(n,e,t){let o=((await Eu([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(o.length===0)return[];let i=await Eu(o);return o.flatMap(s=>{let a=i[s]?.values?.[t]?.value;return a?[a]:[]})}async function hv(){let n=[Ri.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 Pu(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 Pu(e,()=>!0,""))}catch{}return n}async function Iu(){let n=Ti.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"?mv():await hv(),t=fv(e).flatMap(r=>{let o=io(r);return o?(f(`[ToolProvider] ${r} => version ${o}`),[{root:r,version:o}]):(f(`[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)=>so(o.version,r.version)>0?o:r)}import*as Au from"fs";import*as ke from"path";function ao(n,e){let t=ke.relative(e,n);return t===""||!ke.isAbsolute(t)&&!t.startsWith(`..${ke.sep}`)&&t!==".."}function wt(n){let e=ke.resolve(n),t=[],r=e;for(;;)try{let o=Au.realpathSync(r);return t.length===0?o:ke.join(o,...t.reverse())}catch(o){if(o.code!=="ENOENT")throw o;let i=ke.dirname(r);if(i===r)return e;t.push(ke.basename(r)),r=i}}function ki(n,e){let t=wt(e),r=wt(n);return ao(r,t)?r:null}function xi(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function Ni(n){let e=xi(n);if(!e)throw new Error("Path must not be empty.");return wt(e)}var co={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},Li={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"},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"},Ln={ALGORITHM:"aes-256-gcm",KEY_LENGTH:32,IV_LENGTH:12,KEK_VERSIONS:["kek-v1","kek-v2","kek-v3"]},lo={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:Se.APP_ID,timeout:co.LOGIN_TIMEOUT_MS,countryCode:"CN"};import{homedir as Xt}from"os";import At from"path";import{xdgConfig as gv}from"xdg-basedir";var ue={"trae-cn":At.join(Xt(),".trae-cn"),opencode:At.join(gv,"opencode"),cursor:At.join(Xt(),".cursor"),codebuddy:At.join(Xt(),".codebuddy"),qoder:At.join(Xt(),".qoder"),"claude-code":At.join(Xt(),".claude"),codex:At.join(Xt(),".codex"),bitfun:At.join(Xt(),".bitfun"),opendesk:At.join(Xt(),".opendesk")};import Zt from"path";import*as Du from"os";function E(){return yc().toLowerCase().includes("openharmony")}function yc(){return Du.platform()}var wc="https://matrix.openharmony.cn",it={TAGS_API_URL:`${wc}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${wc}/api/registry/skill/skills`,SKILL_API_BASE:`${wc}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},Ru={"trae-cn":{path:Zt.join(ue["trae-cn"],"skills"),displayName:"trae-cn"},opencode:{path:Zt.join(ue.opencode,"skills"),displayName:"opencode"},cursor:{path:Zt.join(ue.cursor,"skills"),displayName:"cursor"},codebuddy:{path:Zt.join(ue.codebuddy,"skills"),displayName:"codebuddy"},qoder:{path:Zt.join(ue.qoder,"skills"),displayName:"qoder"},"claude-code":{path:Zt.join(ue["claude-code"],"skills"),projectPath:".claude/skills",displayName:"claude-code"},codex:{path:Zt.join(ue.codex,"skills"),displayName:"codex"}},Tu={opencode:{path:Zt.join(ue.opencode,"skills"),displayName:"opencode"}};function Dt(){return E()?Tu:Ru}import{homedir as uo}from"os";import Be from"path";var vt="deveco-mcp";var Qt={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:Be.join(ue.opencode,"opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:Be.join(process.platform==="win32"?Be.join(process.env.APPDATA??Be.join(uo(),"AppData","Roaming"),"Trae CN","User"):Be.join(uo(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:Be.join(ue.cursor,"mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:Be.join(ue.codebuddy,"mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:Be.join(process.platform==="win32"?Be.join(process.env.APPDATA??Be.join(uo(),"AppData","Roaming"),"Qoder","SharedClientCache"):Be.join(uo(),"Library","Application Support","Qoder","SharedClientCache"),"mcp.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"standard"},"claude-code":{name:"claude-code",displayName:"Claude Code",supportsGlobal:!0,globalConfigPath:Be.join(uo(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:Be.join(ue.codex,"config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function xu(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function ku(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 Oi(n,e){return n.format==="opencode"?xu(e):n.format==="claude-code"||n.format==="codex"?ku(e):Nu(e)}var st={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var vc="https://developer.huawei.com/consumer/cn/download/";var yv=/^#\s*Version:\s*(\S+)/,wv="26.0.0.810",vv=["sdk","default","openharmony","native","llvm","bin","clangd"];function Sv(n){try{let e=JSON.parse(pe.readFileSync(n,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch{return}}function bv(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 A=class n{constructor(e,t,r,o,i,s,a,c,l,d,h="",w=""){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;this._clangdPath=h;this._lspServerPath=w}_sourceType;_toolchainRoot;_devecoStudioPath;_nodePath;_ohpmJsPath;_hvigorJsPath;_javaPath;_sdkPath;_hdcPath;_emulatorPath;_clangdPath;_lspServerPath;static installSourcePromise;get sourceType(){return this._sourceType}get toolchainRoot(){return this._toolchainRoot}get devecoStudioPath(){return this._devecoStudioPath}get nodePath(){return 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??""}get sdkPath(){return this._sdkPath}get hdcPath(){return this._hdcPath}get emulatorPath(){return this._emulatorPath}get emulatorLauncherPath(){return this.emulatorPath}get clangdPath(){return this._clangdPath&&pe.existsSync(this._clangdPath)?this._clangdPath:""}get lspServerPath(){return this._lspServerPath&&pe.existsSync(this._lspServerPath)?this._lspServerPath:""}assertJava(){if(!E()&&(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.")}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 so(e,t)}static async checkVersion(){if(E())return;let e=await n.resolveInstallSource();(e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)).assertVersion()}static async new(){if(E())return n.fromOpenHarmony();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,n.resolveClangdPath(e),n.resolveLspServerPath(e))}static OPENHARMONY_STUDIO_ROOT="/data/service/hnp/hmos-clt.org/hmos-clt_1.0.0";static fromOpenHarmony(){let e=process.env.COMMAND_LINE_TOOL_PATH?.trim();if(!e&&!n.isDirectory(n.OPENHARMONY_STUDIO_ROOT))throw new Error("No toolchain found. Set COMMAND_LINE_TOOL_PATH.");return e?(f(`[ToolProvider] Using COMMAND_LINE_TOOL_PATH \u2192 ${e}`),n.buildOpenHarmonyProvider("clt",e)):(f("[ToolProvider] COMMAND_LINE_TOOL_PATH not set, using fallback DevEco Studio toolchain"),n.buildOpenHarmonyProvider("studio",n.OPENHARMONY_STUDIO_ROOT))}static buildOpenHarmonyToolPaths(e){let t=S.join(e,"sdk");return{nodePath:S.join(e,"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"),emulatorPath:"",clangdPath:S.join(e,"clangd","clangd"),lspServerPath:S.join(e,"ace-server","out","index.js")}}static buildOpenHarmonyProvider(e,t){let r=e==="clt"?"COMMAND_LINE_TOOL_PATH is invalid":"DevEco Studio toolchain is invalid";if(!n.isDirectory(t))throw new Error(`${r}: ${t} is not a valid directory.`);let o=n.buildOpenHarmonyToolPaths(t),i=Object.entries({node:o.nodePath,ohpm:o.ohpmJsPath,hvigor:o.hvigorJsPath,hdc:o.hdcPath}).filter(([,s])=>!s||!pe.existsSync(s)).map(([s])=>s);if(i.length>0)throw new Error(`${r}: ${t} \u2014 missing required: ${i.join(", ")}.`);return n.assertBuiltPathsInsideRoot(t,o,!1),new n(e,t,e==="studio"?t:void 0,o.nodePath,o.ohpmJsPath,o.hvigorJsPath,"",o.sdkPath,o.hdcPath,o.emulatorPath,o.clangdPath,o.lspServerPath)}static devecoContentRootForClangd(e){return We.platform()==="darwin"&&e.endsWith(".app")?S.join(e,"Contents"):e}static clangdCandidatesFromDevecoHome(e){let t=new Set,r=[e,n.devecoContentRootForClangd(e)];for(let o of r){let i=S.join(o,...vv);t.add(We.platform()==="win32"?i+".exe":i)}return[...t]}static resolveClangdPath(e){let t=n.clangdCandidatesFromDevecoHome(e);for(let r of t)if(pe.existsSync(r))return r;return""}static resolveLspServerPath(e){let t=We.platform(),r;if(t==="win32")r=S.join(e,"plugins","openharmony");else if(t==="darwin")r=S.join(e,"Contents","plugins","openharmony");else return"";let o=S.join(r,"ace-server","out","index.js");return pe.existsSync(o)?o:""}assertVersion(){if(this._sourceType==="clt"){this.assertCltVersion();return}this.assertIdeVersion()}assertCltVersion(e="26.0.0"){if(this._sourceType!=="clt")throw new Error("This operation requires Command Line Tools.");n.assertMinimumVersion(n.readCltVersion(this._toolchainRoot),"Command Line Tools","version.txt",e,this._toolchainRoot)}assertIdeVersion(e="6.1.0"){E()||(this.assertStudio(),n.assertMinimumVersion(io(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(so(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:
|
|
6
|
-
${
|
|
5
|
+
`)}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",h=Number.parseInt(d.padEnd(3,"0").slice(0,3),10),w=new Date(o,i,s,a,c,l,h);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 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 f(`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(Se.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=Se.resolve(Se.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=Se.normalize(e),o=Se.relative(r,t);if(o.split(Se.sep)[0]===".."||Se.isAbsolute(o))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||Se.isAbsolute(e)}static isPathContained(e,t){let r=Se.resolve(t,e),o=Se.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=gc.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let i=Se.resolve(o,e),s;try{s=gc.realpathSync(i)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${i}`}}return n.isPathContained(s,o)}};var z=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=H.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=H.join(e,"build-profile.json5");if(!Q.existsSync(t))return null;try{let r=Q.readFileSync(t,"utf-8"),o=It.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=R.resolvePathWithinRoot(this.rootDir,t.srcPath),o=H.join(r,"src","main","module.json5");if(!Q.existsSync(o))return"entry";try{let i=Q.readFileSync(o,"utf-8");return It.parse(i)?.module?.type||"entry"}catch(i){return console.warn(`Warning: Failed to parse ${o}:`,i),"entry"}}findOwningModule(e){let t=H.normalize(e);for(let r of this.profile.modules){let o=H.normalize(H.join(this.rootDir,r.srcPath)),i=o+H.sep;if(t.startsWith(i)||t===o)return r.name}return null}getModuleProfile(e){let t=this.profile.modules.find(a=>a.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let r=R.resolvePathWithinRoot(this.rootDir,t.srcPath),o=H.join(r,"build-profile.json5");if(!Q.existsSync(o))throw new Error(`Build profile for module '${e}' not found at ${o}.`);let i=Q.readFileSync(o,"utf-8");return It.parse(i)}getBundleName(){let e=H.join(this.rootDir,"AppScope","app.json5");if(Q.existsSync(e))try{let t=Q.readFileSync(e,"utf-8"),r=It.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=H.join(this.rootDir,"AppScope","app.json5");if(!Q.existsSync(e))return!1;try{let t=Q.readFileSync(e,"utf-8");return It.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=R.resolvePathWithinRoot(this.rootDir,r.srcPath),i=H.join(o,"src","main","module.json5");if(!Q.existsSync(i))return"EntryAbility";try{let s=Q.readFileSync(i,"utf-8"),c=It.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=R.resolvePathWithinRoot(this.rootDir,t.srcPath),o=H.join(r,"oh-package.json5");if(!Q.existsSync(o))return[];let i=[];try{let s=Q.readFileSync(o,"utf-8"),c=It.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=H.join(t.srcPath,d),v=R.resolvePathWithinRoot(this.rootDir,w),I=this.profile.modules.find(G=>H.resolve(this.rootDir,G.srcPath)===v);I&&i.push(I.name)}}catch{}return i}getModuleName(e){let t=this.profile.modules.find(i=>i.name===e);if(!t)return e;let r=R.resolvePathWithinRoot(this.rootDir,t.srcPath),o=H.join(r,"src","main","module.json5");if(!Q.existsSync(o))return e;try{let i=Q.readFileSync(o,"utf-8");return It.parse(i)?.module?.name||e}catch(i){return console.warn(`Warning: Failed to parse ${o}:`,i),e}}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(!Q.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 v=this.getSignedHapName(c,i.srcPath,o,t);v&&(d=v)}let h=s?"-signed.hsp":"-signed.hap";if(!r&&!d.endsWith(h))throw new Error(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`);let w=this.buildOutputPath(i.srcPath,o,["outputs",t,d]);if(!Q.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=H.isAbsolute(c)?c:this.buildOutputPath(o.srcPath,r,["outputs",t,c]);if(!Q.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 Q.existsSync(s)?i:null}buildOutputPath(e,t,r){let o=R.resolvePathWithinRoot(this.rootDir,e),i=H.resolve(o,"build",t,...r);return R.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=Q.readFileSync(e,"utf-8"),o=It.parse(r),i,s=!1,a=Array.isArray(o)?o:[o];for(let l of a)i||(i=l[t]),s||(s=l.isSigned===!0);if(!i)throw new Error(`Could not find ${t} in output_metadata.json at ${e}`);this.validatePackageName(i);let c=this.collectRemoteHsps(a);return{packageName:i,isSigned:s,dependRemoteHsps:c}}validatePackageName(e){let t=H.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 pe from"fs";import*as We from"os";import*as S from"path";import Du from"fs";import*as xi from"os";import*as ki from"path";import hv from"regedit";import{execFileSync as fv}from"child_process";import Pu from"fs";import*as Cu from"os";import*as yc from"path";function Ti(n,e){let t=yc.join(n,"Contents","Info.plist");if(!Pu.existsSync(t)){f(`[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=fv(r,o,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(i&&!i.includes("Does Not Exist"))return i}catch{}}function mv(n){let e=Ti(n,"CFBundleShortVersionString");if(!e)return Ti(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[Ti(n,"CFBundleVersion"),Ti(n,"CFBundleGetInfoString")?.match(/DS-[\d.]+/)?.[0]];for(let o of r){let i=o?.split(".").at(-1)?.replace(new RegExp(`^${t}`),"");if(i&&/^\d+$/.test(i))return`${e}.${i}`}return e}function lo(n){if(Cu.platform()==="darwin")return mv(n);let e=yc.join(n,"product-info.json");try{let t=JSON.parse(Pu.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}function uo(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 gv(n){return n.filter(e=>{try{return Du.statSync(e).isDirectory()}catch{return!1}})}function yv(){let n=[];for(let e of[ki.join(xi.homedir(),"Applications"),"/Applications"])try{n.push(...Du.readdirSync(e).filter(t=>t.endsWith(".app")&&t.toLowerCase().includes("deveco")).map(t=>ki.join(e,t)))}catch{}return n}function Iu(n){return new Promise((e,t)=>hv.list(n,(r,o)=>r?t(r):e(o)))}async function Au(n,e,t){let o=((await Iu([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(o.length===0)return[];let i=await Iu(o);return o.flatMap(s=>{let a=i[s]?.values?.[t]?.value;return a?[a]:[]})}async function wv(){let n=[ki.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 Au(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 Au(e,()=>!0,""))}catch{}return n}async function Ru(){let n=xi.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 wv(),t=gv(e).flatMap(r=>{let o=lo(r);return o?(f(`[ToolProvider] ${r} => version ${o}`),[{root:r,version:o}]):(f(`[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)=>uo(o.version,r.version)>0?o:r)}import*as Tu from"fs";import*as ke from"path";function po(n,e){let t=ke.relative(e,n);return t===""||!ke.isAbsolute(t)&&!t.startsWith(`..${ke.sep}`)&&t!==".."}function wt(n){let e=ke.resolve(n),t=[],r=e;for(;;)try{let o=Tu.realpathSync(r);return t.length===0?o:ke.join(o,...t.reverse())}catch(o){if(o.code!=="ENOENT")throw o;let i=ke.dirname(r);if(i===r)return e;t.push(ke.basename(r)),r=i}}function Ni(n,e){let t=wt(e),r=wt(n);return po(r,t)?r:null}function Li(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function Oi(n){let e=Li(n);if(!e)throw new Error("Path must not be empty.");return wt(e)}import{homedir as Xt}from"os";import At from"path";import{xdgConfig as vv}from"xdg-basedir";var ue={"trae-cn":At.join(Xt(),".trae-cn"),opencode:At.join(vv,"opencode"),cursor:At.join(Xt(),".cursor"),codebuddy:At.join(Xt(),".codebuddy"),qoder:At.join(Xt(),".qoder"),"claude-code":At.join(Xt(),".claude"),codex:At.join(Xt(),".codex"),bitfun:At.join(Xt(),".bitfun"),opendesk:At.join(Xt(),".opendesk")};import Zt from"path";import*as ku from"os";function b(){return wc().toLowerCase().includes("openharmony")}function wc(){return ku.platform()}var vc="https://matrix.openharmony.cn",it={TAGS_API_URL:`${vc}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${vc}/api/registry/skill/skills`,SKILL_API_BASE:`${vc}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},xu={"trae-cn":{path:Zt.join(ue["trae-cn"],"skills"),displayName:"trae-cn"},opencode:{path:Zt.join(ue.opencode,"skills"),displayName:"opencode"},cursor:{path:Zt.join(ue.cursor,"skills"),displayName:"cursor"},codebuddy:{path:Zt.join(ue.codebuddy,"skills"),displayName:"codebuddy"},qoder:{path:Zt.join(ue.qoder,"skills"),displayName:"qoder"},"claude-code":{path:Zt.join(ue["claude-code"],"skills"),projectPath:".claude/skills",displayName:"claude-code"},codex:{path:Zt.join(ue.codex,"skills"),displayName:"codex"}},Nu={opencode:{path:Zt.join(ue.opencode,"skills"),displayName:"opencode"}};function Dt(){return b()?Nu:xu}import{homedir as fo}from"os";import Be from"path";var vt="deveco-mcp";var Qt={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:Be.join(ue.opencode,"opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:Be.join(process.platform==="win32"?Be.join(process.env.APPDATA??Be.join(fo(),"AppData","Roaming"),"Trae CN","User"):Be.join(fo(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:Be.join(ue.cursor,"mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:Be.join(ue.codebuddy,"mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:Be.join(process.platform==="win32"?Be.join(process.env.APPDATA??Be.join(fo(),"AppData","Roaming"),"Qoder","SharedClientCache"):Be.join(fo(),"Library","Application Support","Qoder","SharedClientCache"),"mcp.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"standard"},"claude-code":{name:"claude-code",displayName:"Claude Code",supportsGlobal:!0,globalConfigPath:Be.join(fo(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:Be.join(ue.codex,"config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function Ou(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function Lu(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function Mu(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function Mi(n,e){return n.format==="opencode"?Ou(e):n.format==="claude-code"||n.format==="codex"?Lu(e):Mu(e)}var st={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var Sc="https://developer.huawei.com/consumer/cn/download/";var Sv=/^#\s*Version:\s*(\S+)/,bv="26.0.0.810",Ev=["sdk","default","openharmony","native","llvm","bin","clangd"];function Pv(n){try{let e=JSON.parse(pe.readFileSync(n,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch{return}}function Cv(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 A=class n{constructor(e,t,r,o,i,s,a,c,l,d,h="",w=""){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;this._clangdPath=h;this._lspServerPath=w}_sourceType;_toolchainRoot;_devecoStudioPath;_nodePath;_ohpmJsPath;_hvigorJsPath;_javaPath;_sdkPath;_hdcPath;_emulatorPath;_clangdPath;_lspServerPath;static installSourcePromise;get sourceType(){return this._sourceType}get toolchainRoot(){return this._toolchainRoot}get devecoStudioPath(){return this._devecoStudioPath}get nodePath(){return 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??""}get sdkPath(){return this._sdkPath}get hdcPath(){return this._hdcPath}get emulatorPath(){return this._emulatorPath}get emulatorLauncherPath(){return this.emulatorPath}get clangdPath(){return this._clangdPath&&pe.existsSync(this._clangdPath)?this._clangdPath:""}get lspServerPath(){return this._lspServerPath&&pe.existsSync(this._lspServerPath)?this._lspServerPath:""}assertJava(){if(!b()&&(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.")}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 uo(e,t)}static async checkVersion(){if(b())return;let e=await n.resolveInstallSource();(e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)).assertVersion()}static async new(){if(b())return n.fromOpenHarmony();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,n.resolveClangdPath(e),n.resolveLspServerPath(e))}static OPENHARMONY_STUDIO_ROOT="/data/service/hnp/hmos-clt.org/hmos-clt_1.0.0";static fromOpenHarmony(){let e=process.env.COMMAND_LINE_TOOL_PATH?.trim();if(!e&&!n.isDirectory(n.OPENHARMONY_STUDIO_ROOT))throw new Error("No toolchain found. Set COMMAND_LINE_TOOL_PATH.");return e?(f(`[ToolProvider] Using COMMAND_LINE_TOOL_PATH \u2192 ${e}`),n.buildOpenHarmonyProvider("clt",e)):(f("[ToolProvider] COMMAND_LINE_TOOL_PATH not set, using fallback DevEco Studio toolchain"),n.buildOpenHarmonyProvider("studio",n.OPENHARMONY_STUDIO_ROOT))}static buildOpenHarmonyToolPaths(e){let t=S.join(e,"sdk");return{nodePath:S.join(e,"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"),emulatorPath:"",clangdPath:S.join(e,"clangd","clangd"),lspServerPath:S.join(e,"ace-server","out","index.js")}}static buildOpenHarmonyProvider(e,t){let r=e==="clt"?"COMMAND_LINE_TOOL_PATH is invalid":"DevEco Studio toolchain is invalid";if(!n.isDirectory(t))throw new Error(`${r}: ${t} is not a valid directory.`);let o=n.buildOpenHarmonyToolPaths(t),i=Object.entries({node:o.nodePath,ohpm:o.ohpmJsPath,hvigor:o.hvigorJsPath,hdc:o.hdcPath}).filter(([,s])=>!s||!pe.existsSync(s)).map(([s])=>s);if(i.length>0)throw new Error(`${r}: ${t} \u2014 missing required: ${i.join(", ")}.`);return n.assertBuiltPathsInsideRoot(t,o,!1),new n(e,t,e==="studio"?t:void 0,o.nodePath,o.ohpmJsPath,o.hvigorJsPath,"",o.sdkPath,o.hdcPath,o.emulatorPath,o.clangdPath,o.lspServerPath)}static devecoContentRootForClangd(e){return We.platform()==="darwin"&&e.endsWith(".app")?S.join(e,"Contents"):e}static clangdCandidatesFromDevecoHome(e){let t=new Set,r=[e,n.devecoContentRootForClangd(e)];for(let o of r){let i=S.join(o,...Ev);t.add(We.platform()==="win32"?i+".exe":i)}return[...t]}static resolveClangdPath(e){let t=n.clangdCandidatesFromDevecoHome(e);for(let r of t)if(pe.existsSync(r))return r;return""}static resolveLspServerPath(e){let t=We.platform(),r;if(t==="win32")r=S.join(e,"plugins","openharmony");else if(t==="darwin")r=S.join(e,"Contents","plugins","openharmony");else return"";let o=S.join(r,"ace-server","out","index.js");return pe.existsSync(o)?o:""}assertVersion(){if(this._sourceType==="clt"){this.assertCltVersion();return}this.assertIdeVersion()}assertCltVersion(e="26.0.0"){if(this._sourceType!=="clt")throw new Error("This operation requires Command Line Tools.");n.assertMinimumVersion(n.readCltVersion(this._toolchainRoot),"Command Line Tools","version.txt",e,this._toolchainRoot)}assertIdeVersion(e="6.1.0"){b()||(this.assertStudio(),n.assertMinimumVersion(lo(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(uo(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:
|
|
6
|
+
${Sc}`)}static resolveCodelinterPath(e,t){let r=n.getCodelinterCandidates(e,t),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 Error(`${a}
|
|
7
7
|
Searched paths:
|
|
8
8
|
${r.join(`
|
|
9
|
-
`)}`)}let i=wt(e),s=wt(o);return n.assertInsideRoot(s,i,"codelinter"),s}static getCodelinterCandidates(e,t){if(t==="studio"){if(E())return[S.join(e,"codelinter","index.js")];let r=We.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 pe.existsSync(S.join(e,"version.txt"));let r=We.platform()==="darwin"?S.join(e,"Contents"):e,o=We.platform()==="darwin"?S.join(r,"Info.plist"):S.join(r,"product-info.json");if(!pe.existsSync(o))return!1;let i=n.buildToolPaths(e,"studio");return[i.nodePath,i.ohpmJsPath,i.hvigorJsPath].every(pe.existsSync)}static buildToolPaths(e,t){return t==="clt"?n.buildCltToolPaths(e):n.buildStudioToolPaths(e)}static buildCltToolPaths(e){let t=S.join(e,"sdk"),r=We.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=We.platform()==="darwin",r=We.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 pe.statSync(e).isFile()}catch{return!1}}static isDirectory(e){try{return pe.existsSync(e)&&pe.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 f(`[ToolProvider] Using ${r} \u2192 ${a}`),{sourceType:i,toolchainRoot:a}}}let t=await Iu();return f(`[ToolProvider] Using auto \u2192 ${t.root} (${t.version})`),{sourceType:"studio",toolchainRoot:t.root}}static resolveExplicitRoot(e,t,r){let o;try{o=Ni(e)}catch(i){throw new Error(`Invalid ${r}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return t==="studio"&&We.platform()==="darwin"&&(o=n.normalizeMacStudioRoot(o)),n.isValidRoot(o,t)?o:n.throwInvalidSource(o,t,r,e)}static assertBuiltPathsInsideRoot(e,t,r){let o=wt(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)a&&n.assertInsideRoot(a,o,s)}static assertInsideRoot(e,t,r){if(ki(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 pe.readFileSync(S.join(e,"version.txt"),"utf-8").split(/\r?\n/).map(t=>t.match(yv)?.[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 pe.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(We.platform()==="win32"?["java.exe","java.cmd"]:["java"]).map(r=>S.join(e,r)).find(pe.existsSync)}getMaxApiLevel(){for(let e of bv(this.sdkPath)){let t=Sv(e);if(t!==void 0)return t}return 23}detectApiLevel(){return this.getMaxApiLevel()}_apiscanPaths;getApiscanPaths(){if(this._apiscanPaths)return this._apiscanPaths;let e=We.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(!pe.existsSync(o)||!pe.existsSync(i)){let s=io(this._toolchainRoot)??"unknown";throw new Error(`A required component is missing. The detected DevEco Studio version is ${s}. The minimum required version is ${wv}. Upgrade before using 'check compat' at ${vc}`)}return this._apiscanPaths={apiChangeDir:o,scriptPath:i},this._apiscanPaths}};import{execa as Ev}from"execa";import*as Rt from"path";import*as Mi from"fs";import*as Sc from"os";var xe=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let o={...process.env,DEVECO_SDK_HOME:e.sdkPath};if(e.javaPath){let i=Rt.dirname(e.javaPath);o.PATH=`${i}${Rt.delimiter}${process.env.PATH||""}`,e.sourceType==="clt"&&(o.JAVA_HOME=Rt.dirname(i))}E()&&(o.HVIGOR_USER_HOME=Rt.join(Sc.homedir(),".hvigor")),this.env=o}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(){E()||await this.runHvigor(["--stop-daemon"])}async ensureDaemonRunning(){if(this.findProjectDaemon()){f("[HvigorAdapter] Daemon already running.");return}f("[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(!Mi.existsSync(t))return null;try{let r=Mi.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||Rt.join(Sc.homedir(),".hvigor");return Rt.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){E()&&(e=e.includes("--no-daemon")?e:["--no-daemon",...e]);let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];f(`Executing: ${t} ${r.join(" ")}`);let o=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit";await Ev(t,r,{cwd:this.projectRoot,env:this.env,stdout:o,stderr:o})}};import{execa as Pv}from"execa";var en=class{toolProvider;projectRoot;constructor(e,t){this.toolProvider=e,this.projectRoot=t}async installAll(){let e=this.toolProvider.nodePath,t=["--no-deprecation",this.toolProvider.ohpmJsPath,"install","--all"];f(`Executing: ${e} ${t.join(" ")}`),await Pv(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"})}};import{mkdir as Cv}from"fs/promises";import{dirname as Iv,resolve as Av}from"path";import{execa as Dv}from"execa";import{lock as bc,check as _M}from"proper-lockfile";function Ec(n){return Av(n,".hvigor",".build-lock")}function Rv(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function Lu(n){let e=Iv(Ec(n));if(await Cv(e,{recursive:!0}),process.platform==="win32")try{await Dv("attrib",["+h",e])}catch{}}async function Tv(n,e){let t=new AbortController,r=Rv(e);await Lu(n);let o={lockfilePath:Ec(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await bc(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 bc(n,{...o,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function Tt(n,e,t){let{release:r,signal:o}=await Tv(n,t);try{return await e(o)}finally{await r()}}async function _i(n,e){let t=new AbortController;await Lu(n);let r={lockfilePath:Ec(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},o;try{o=await bc(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 tn from"fs";import*as On from"path";import kv from"json5";var xv=1e3;function ji(n){f(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=On.join(n,st.SYNC_OUTPUT_PATH);if(!tn.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return f(`[ProjectCheck] ${l.reason}`),l}let t=tn.statSync(e).mtimeMs;f(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=Nv(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return f(`[ProjectCheck] ${l.reason}`),l}let o=On.join(n,st.OH_PACKAGE_JSON5),i=Fi(o,t,"root");if(i.required)return f(`[ProjectCheck] Root check: ${i.reason}`),i;let s=On.join(n,st.BUILD_PROFILE_JSON5),a=Fi(s,t,"build-profile");if(a.required)return f(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let d=On.join(n,l.srcPath,st.OH_PACKAGE_JSON5),h=Fi(d,t,l.name);if(h.required)return f(`[ProjectCheck] Module '${l.name}' check: ${h.reason}`),h;let w=On.join(n,l.srcPath,st.BUILD_PROFILE_JSON5),v=Fi(w,t,l.name);if(v.required)return f(`[ProjectCheck] Module '${l.name}' build-profile check: ${v.reason}`),v}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return f(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function Fi(n,e,t){if(!tn.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=tn.statSync(n).mtimeMs;return r-e>xv?{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 Nv(n){let e=On.join(n,st.BUILD_PROFILE_JSON5);try{let t=tn.readFileSync(e,"utf-8");if(!t.trim())return null;let r=kv.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 Ve from"fs";import*as ct from"path";import*as Bu from"util";import*as M from"fs";import*as Gi from"path";import ne from"fs";import*as Hi from"os";import*as Y from"path";import Lv from"json5";var Ou=3;function $i(n){if(!ne.existsSync(n)||!ne.statSync(n).isDirectory())return!1;let e=ne.existsSync(Y.join(n,"build-profile.json5")),t=ne.existsSync(Y.join(n,"hvigorfile.js"))||ne.existsSync(Y.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=ne.readFileSync(Y.join(n,"build-profile.json5"),"utf-8");return Lv.parse(r).app!==void 0}catch{return!1}}function Pc(n,e,t){if(e>=t)return null;let r=Ov(n),o=Mv(r);if(o)return o;for(let i of r){let s=Pc(i,e+1,t);if(s)return s}return null}function Ov(n){try{let e=ne.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(Y.join(n,r.name));return t}catch{return[]}}function Mv(n){for(let e of n)if($i(e))return e;return null}function kt(n){if(!n||n.trim()==="")return null;let e=Y.resolve(n),t;try{t=ne.realpathSync(e)}catch{t=e}if(!ne.existsSync(t))return null;if($i(t))return t;let r=t;for(let o=1;o<=3;o++){let i=Y.dirname(r);if(i===r)break;if($i(i))return i;r=i}if(ne.statSync(t).isDirectory()){let o=Pc(t,0,Ou);if(o)return o}return null}function Ui(n){if(!n||n.trim()==="")return null;let e=Y.resolve(n),t;try{t=ne.realpathSync(e)}catch{t=e}return!ne.existsSync(t)||!ne.statSync(t).isDirectory()?null:$i(t)?t:Pc(t,0,Ou)}var Cc=[E()?".bitfun":".idea",".deveco",E()?".cxx":"cxx","compile_commands.json"];function ir(n){return Y.join(n,...Cc)}function Mu(n){return new Promise(e=>setTimeout(e,n))}var _v=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function Mn(n){let e=Y.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&_v.has(e)}function Bi(n){return Y.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 Fv(n){return fe(n)}function _n(n){let e=Fv(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function nn(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??Y.join(Hi.homedir(),"AppData","Local");return Y.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?Y.join(Hi.homedir(),"Library","Logs","devecocli-mcp-server"):Y.join(Hi.homedir(),".local","share","devecocli-mcp-server","logs")}function _u(n,e){let t=jv(e),r=Hv(t,n);if(r!==null)return r;let o=Date.now(),s=`${n.replace(/:/g,"\\:")}=${o}`,a=$v(t,n,s);return Uv(e,a),o}function jv(n){let e;try{e=ne.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function Hv(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 $v(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 Uv(n,e){try{ne.mkdirSync(Y.dirname(n),{recursive:!0})}catch{}try{ne.writeFileSync(n,e.join(`
|
|
9
|
+
`)}`)}let i=wt(e),s=wt(o);return n.assertInsideRoot(s,i,"codelinter"),s}static getCodelinterCandidates(e,t){if(t==="studio"){if(b())return[S.join(e,"codelinter","index.js")];let r=We.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 pe.existsSync(S.join(e,"version.txt"));let r=We.platform()==="darwin"?S.join(e,"Contents"):e,o=We.platform()==="darwin"?S.join(r,"Info.plist"):S.join(r,"product-info.json");if(!pe.existsSync(o))return!1;let i=n.buildToolPaths(e,"studio");return[i.nodePath,i.ohpmJsPath,i.hvigorJsPath].every(pe.existsSync)}static buildToolPaths(e,t){return t==="clt"?n.buildCltToolPaths(e):n.buildStudioToolPaths(e)}static buildCltToolPaths(e){let t=S.join(e,"sdk"),r=We.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=We.platform()==="darwin",r=We.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 pe.statSync(e).isFile()}catch{return!1}}static isDirectory(e){try{return pe.existsSync(e)&&pe.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 f(`[ToolProvider] Using ${r} \u2192 ${a}`),{sourceType:i,toolchainRoot:a}}}let t=await Ru();return f(`[ToolProvider] Using auto \u2192 ${t.root} (${t.version})`),{sourceType:"studio",toolchainRoot:t.root}}static resolveExplicitRoot(e,t,r){let o;try{o=Oi(e)}catch(i){throw new Error(`Invalid ${r}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return t==="studio"&&We.platform()==="darwin"&&(o=n.normalizeMacStudioRoot(o)),n.isValidRoot(o,t)?o:n.throwInvalidSource(o,t,r,e)}static assertBuiltPathsInsideRoot(e,t,r){let o=wt(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)a&&n.assertInsideRoot(a,o,s)}static assertInsideRoot(e,t,r){if(Ni(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 pe.readFileSync(S.join(e,"version.txt"),"utf-8").split(/\r?\n/).map(t=>t.match(Sv)?.[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 pe.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(We.platform()==="win32"?["java.exe","java.cmd"]:["java"]).map(r=>S.join(e,r)).find(pe.existsSync)}getMaxApiLevel(){for(let e of Cv(this.sdkPath)){let t=Pv(e);if(t!==void 0)return t}return 23}detectApiLevel(){return this.getMaxApiLevel()}_apiscanPaths;getApiscanPaths(){if(this._apiscanPaths)return this._apiscanPaths;let e=We.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(!pe.existsSync(o)||!pe.existsSync(i)){let s=lo(this._toolchainRoot)??"unknown";throw new Error(`A required component is missing. The detected DevEco Studio version is ${s}. The minimum required version is ${bv}. Upgrade before using 'check compat' at ${Sc}`)}return this._apiscanPaths={apiChangeDir:o,scriptPath:i},this._apiscanPaths}};import{execa as Iv}from"execa";import*as Rt from"path";import*as _i from"fs";import*as bc from"os";var xe=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let o={...process.env,DEVECO_SDK_HOME:e.sdkPath};if(e.javaPath){let i=Rt.dirname(e.javaPath);o.PATH=`${i}${Rt.delimiter}${process.env.PATH||""}`,e.sourceType==="clt"&&(o.JAVA_HOME=Rt.dirname(i))}b()&&(o.HVIGOR_USER_HOME=Rt.join(bc.homedir(),".hvigor")),this.env=o}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(){b()||await this.runHvigor(["--stop-daemon"])}async ensureDaemonRunning(){if(this.findProjectDaemon()){f("[HvigorAdapter] Daemon already running.");return}f("[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(!_i.existsSync(t))return null;try{let r=_i.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||Rt.join(bc.homedir(),".hvigor");return Rt.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){b()&&(e=e.includes("--no-daemon")?e:["--no-daemon",...e]);let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];f(`Executing: ${t} ${r.join(" ")}`);let o=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit";await Iv(t,r,{cwd:this.projectRoot,env:this.env,stdout:o,stderr:o})}};import{execa as Av}from"execa";var en=class{toolProvider;projectRoot;constructor(e,t){this.toolProvider=e,this.projectRoot=t}async installAll(){let e=this.toolProvider.nodePath,t=["--no-deprecation",this.toolProvider.ohpmJsPath,"install","--all"];f(`Executing: ${e} ${t.join(" ")}`),await Av(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"})}};import{mkdir as Dv}from"fs/promises";import{dirname as Rv,resolve as Tv}from"path";import{execa as kv}from"execa";import{lock as Ec,check as UM}from"proper-lockfile";function Pc(n){return Tv(n,".hvigor",".build-lock")}function xv(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function _u(n){let e=Rv(Pc(n));if(await Dv(e,{recursive:!0}),process.platform==="win32")try{await kv("attrib",["+h",e])}catch{}}async function Nv(n,e){let t=new AbortController,r=xv(e);await _u(n);let o={lockfilePath:Pc(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await Ec(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 Ec(n,{...o,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function Tt(n,e,t){let{release:r,signal:o}=await Nv(n,t);try{return await e(o)}finally{await r()}}async function Fi(n,e){let t=new AbortController;await _u(n);let r={lockfilePath:Pc(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},o;try{o=await Ec(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 tn from"fs";import*as On from"path";import Lv from"json5";var Ov=1e3;function Hi(n){f(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=On.join(n,st.SYNC_OUTPUT_PATH);if(!tn.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return f(`[ProjectCheck] ${l.reason}`),l}let t=tn.statSync(e).mtimeMs;f(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=Mv(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return f(`[ProjectCheck] ${l.reason}`),l}let o=On.join(n,st.OH_PACKAGE_JSON5),i=ji(o,t,"root");if(i.required)return f(`[ProjectCheck] Root check: ${i.reason}`),i;let s=On.join(n,st.BUILD_PROFILE_JSON5),a=ji(s,t,"build-profile");if(a.required)return f(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let d=On.join(n,l.srcPath,st.OH_PACKAGE_JSON5),h=ji(d,t,l.name);if(h.required)return f(`[ProjectCheck] Module '${l.name}' check: ${h.reason}`),h;let w=On.join(n,l.srcPath,st.BUILD_PROFILE_JSON5),v=ji(w,t,l.name);if(v.required)return f(`[ProjectCheck] Module '${l.name}' build-profile check: ${v.reason}`),v}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return f(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function ji(n,e,t){if(!tn.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=tn.statSync(n).mtimeMs;return r-e>Ov?{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 Mv(n){let e=On.join(n,st.BUILD_PROFILE_JSON5);try{let t=tn.readFileSync(e,"utf-8");if(!t.trim())return null;let r=Lv.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 Ve from"fs";import*as ct from"path";import*as Vu from"util";import*as M from"fs";import*as Vi from"path";import ne from"fs";import*as $i from"os";import*as Y from"path";import _v from"json5";var Fu=3;function Ui(n){if(!ne.existsSync(n)||!ne.statSync(n).isDirectory())return!1;let e=ne.existsSync(Y.join(n,"build-profile.json5")),t=ne.existsSync(Y.join(n,"hvigorfile.js"))||ne.existsSync(Y.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=ne.readFileSync(Y.join(n,"build-profile.json5"),"utf-8");return _v.parse(r).app!==void 0}catch{return!1}}function Cc(n,e,t){if(e>=t)return null;let r=Fv(n),o=jv(r);if(o)return o;for(let i of r){let s=Cc(i,e+1,t);if(s)return s}return null}function Fv(n){try{let e=ne.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(Y.join(n,r.name));return t}catch{return[]}}function jv(n){for(let e of n)if(Ui(e))return e;return null}function kt(n){if(!n||n.trim()==="")return null;let e=Y.resolve(n),t;try{t=ne.realpathSync(e)}catch{t=e}if(!ne.existsSync(t))return null;if(Ui(t))return t;let r=t;for(let o=1;o<=3;o++){let i=Y.dirname(r);if(i===r)break;if(Ui(i))return i;r=i}if(ne.statSync(t).isDirectory()){let o=Cc(t,0,Fu);if(o)return o}return null}function Bi(n){if(!n||n.trim()==="")return null;let e=Y.resolve(n),t;try{t=ne.realpathSync(e)}catch{t=e}return!ne.existsSync(t)||!ne.statSync(t).isDirectory()?null:Ui(t)?t:Cc(t,0,Fu)}var Ic=[b()?".bitfun":".idea",".deveco",b()?".cxx":"cxx","compile_commands.json"];function sr(n){return Y.join(n,...Ic)}function ju(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 Mn(n){let e=Y.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&Hv.has(e)}function Wi(n){return Y.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 $v(n){return fe(n)}function _n(n){let e=$v(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function nn(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??Y.join($i.homedir(),"AppData","Local");return Y.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?Y.join($i.homedir(),"Library","Logs","devecocli-mcp-server"):Y.join($i.homedir(),".local","share","devecocli-mcp-server","logs")}function Hu(n,e){let t=Uv(e),r=Bv(t,n);if(r!==null)return r;let o=Date.now(),s=`${n.replace(/:/g,"\\:")}=${o}`,a=Wv(t,n,s);return Gv(e,a),o}function Uv(n){let e;try{e=ne.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function Bv(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 Wv(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 Gv(n,e){try{ne.mkdirSync(Y.dirname(n),{recursive:!0})}catch{}try{ne.writeFileSync(n,e.join(`
|
|
10
10
|
`)+`
|
|
11
|
-
`,"utf8")}catch{}}function
|
|
12
|
-
`;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}},ze=null;function Fn(n=!1){ze&&ze.dispose(),ze=new
|
|
11
|
+
`,"utf8")}catch{}}function Ac(n,e,t="[Cleanup]"){try{let r=Y.dirname(n);if(!ne.existsSync(r))return;let o=Date.now();for(let i of ne.readdirSync(r,{withFileTypes:!0}))i.isDirectory()&&Vv(Y.join(r,i.name),o,e,t)}catch{}}function Vv(n,e,t,r){try{let{mtimeMs:o}=ne.statSync(n);if(e-o<=t)return;ne.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 $u="mcp-server.log",qv="mcp-server",zv={maxSize:10*1024*1024,maxFiles:4},Dc=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={...zv,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=nn(),this.currentLogFile=Vi.join(this.logDir,$u),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 Vi.join(this.logDir,`${qv}-${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===$u||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(o)){let i=Vi.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}
|
|
12
|
+
`;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}},ze=null;function Fn(n=!1){ze&&ze.dispose(),ze=new Dc(n)}function Uu(){ze&&(ze.dispose(),ze=null)}function Bu(){ze&&ze.flush()}function Wu(){return ze?.getLogFilePath()??null}function Gu(){return ze?.getLogDirectory()??null}function Gi(){return ze||Fn(!1),ze}var g={debug:(n,...e)=>Gi().debug(n,...e),info:(n,...e)=>Gi().info(n,...e),warn:(n,...e)=>Gi().warn(n,...e),error:(n,...e)=>Gi().error(n,...e)};var Rc="";function zi(n){if(!n||n==="auto"||n==="stdout"||n==="none"){Rc="";return}Rc=n}function qu(){return Rc||(Gu()??"")}function qi(n,...e){if(e.length===0)return n;try{return Vu.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var m={info(n,...e){g.info(`[lsp] ${qi(n,...e)}`)},warn(n,...e){g.warn(`[lsp] ${qi(n,...e)}`)},error(n,...e){g.error(`[lsp] ${qi(n,...e)}`)},debug(n,...e){g.debug(`[lsp] ${qi(n,...e)}`)}};import*as mo from"fs";import*as ho from"os";import*as ar from"path";import Yv 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"},T="2.0";var zu=8192,Tc=100,Yu=.03,Ju=.7,Ye=900*1e3,Yi="/data/app/sdk.org/sdk_1.0.0";function Ge(n){if(!mo.existsSync(n))return null;try{let e=mo.readFileSync(n,"utf-8");return e.trim()?Yv.parse(e):null}catch{return null}}function Ji(n,e){let t=Math.floor(ho.totalmem()/1048576),r=Math.floor(t*Ju),o,i;e!==void 0&&Number.isFinite(e)&&e>0?(o=e,i=`override(${e})`):(o=zu,n>Tc&&(o+=(n-Tc)*Yu*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 at(n){if(n.startsWith("file:"))return n;try{let e=ar.resolve(n),t=new URL(`file://${e}`).toString();if(ho.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 cr(n){return n&&n.replace(/\\/g,"/")}function U(n){let e=ar.normalize(n).replace(/\\/g,"/");if(ho.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function Ku(n){return ar.join(n,"build-profile.json5")}var xt=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=Ku(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*as Xu from"os";import*as Zu from"path";import{spawn as Jv}from"child_process";var Kv=600*1e3;function Xv(n){let e=[],t=[];return n.stdout?.on("data",r=>{e.push(r.toString())}),n.stderr?.on("data",r=>{t.push(r.toString())}),{stdout:e,stderr:t}}function Ki(n){return n.join("")}function Zv(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
|
|
13
13
|
Output so far:
|
|
14
|
-
`+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function
|
|
14
|
+
`+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function Qv(n,e,t){return new Promise(r=>{let o=Jv(n[0],n[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:i,stderr:s}=Xv(o),a=setTimeout(()=>{o.kill();let c=[Ki(i),Ki(s)].filter(Boolean).join(`
|
|
15
15
|
`).trim();r({success:!1,output:`Build process timeout after 10 minutes.
|
|
16
16
|
Output so far:
|
|
17
|
-
`+c,exitCode:-1})},
|
|
18
|
-
`).trim()||"";r(
|
|
19
|
-
[ohpm install] Running...`);try{await n.installAll()}catch(a){
|
|
20
|
-
[hvigor sync] Running...`);try{await e.sync(t,r)}catch(a){
|
|
17
|
+
`+c,exitCode:-1})},Kv);o.on("close",(c,l)=>{clearTimeout(a);let d=[Ki(i),Ki(s)].filter(Boolean).join(`
|
|
18
|
+
`).trim()||"";r(Zv(c,l,d))}),o.on("error",c=>{clearTimeout(a),r({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function kc(n,e,t,r,o){let i={...process.env,DEVECO_SDK_HOME:r};return b()&&(i.HVIGOR_USER_HOME=Zu.join(Xu.homedir(),".hvigor")),await Qv([e,[t,...o]],n,i)}var eS=["--sync","-p","product=default","--analyze=normal","--parallel","--incremental","--no-daemon"];async function Qu(n,e){try{return(await kc(n,e.nodePath,e.hvigorJsPath,e.sdkPath,eS)).success}catch(t){return m.info(`syncProject failed: ${JSON.stringify(t)}`),!1}}function tS(n){let e=ct.extname(n).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh","c++","h++"].includes(e)}function nS(n,e){let t=ct.join(n,e.name);return e.isDirectory()?e.name===".cxx"||ep(t):tS(t)}function ep(n){if(!Ve.existsSync(n))return!1;try{return Ve.readdirSync(n,{withFileTypes:!0}).some(t=>nS(n,t))}catch{}return!1}function jn(n){try{let t=new xt(n).getAllModuleInfo(),r=[];for(let o of t){let i=ct.resolve(n,o.srcPath);ep(i)&&r.push(o)}return r}catch(e){throw g.error(`[CppCompile] findCppModules threw: ${e instanceof Error?e.message:String(e)}`),e}}function rS(n){let e=[],r=new xt(n).getAllModuleInfo();for(let o of r){let i=ct.resolve(n,o.srcPath),s=ct.join(i,".cxx");Ve.existsSync(s)&&tp(s,e)}return e}function tp(n,e){try{let t=Ve.readdirSync(n,{withFileTypes:!0});for(let r of t){let o=ct.join(n,r.name);r.isDirectory()?tp(o,e):r.name==="compile_commands.json"&&e.push(o)}}catch{}}function oS(n){let e=[];for(let t of n)try{let r=Ve.readFileSync(t,"utf8"),o=JSON.parse(r);e.push(...o)}catch{}return e}function iS(n,e){let t=ct.join(n,...Ic.slice(0,-1));Ve.mkdirSync(t,{recursive:!0});let r=ct.join(t,"compile_commands.json");Ve.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function xc(n){let e=rS(n);if(e.length>0){let t=oS(e);iS(n,t),g.info(`[CppCompile] compile_commands.json generated, ${t.length} compile commands`)}else g.warn("[CppCompile] No compile_commands.json files found")}async function sS(n,e,t){g.info(`[CppCompile] devecoPath: ${e.devecoStudioPath}, sdkPath: ${e.sdkPath}, nodePath: ${e.nodePath},hvigorJsPath:${e.hvigorJsPath}`);for(let r of t){let o=["--mode","module","-p",`module=${r.name}`,"-p","product=default","compileNative","--analyze=normal","--parallel","--incremental","--no-daemon"];g.info(`[CppCompile] Running compileNative for module: ${r.name}`);let i=await kc(n,e.nodePath,e.hvigorJsPath,e.sdkPath,o);i.success?g.info(`[CppCompile] compileNative ${r.name} succeeded`):g.warn(`[CppCompile] compileNative ${r.name} failed: ${i.output}`)}}async function np(n,e){let t=jn(n);if(t.length===0){g.info("[CppCompile] No C++ modules found, skipping initialization");return}g.info(`[CppCompile] Found ${t.length} C++ module(s): ${t.map(r=>r.name).join(", ")}`),await sS(n,e,t),xc(n)}function cS(n,e){if(e.product&&n.validateProduct(e.product),e.buildMode&&!n.profile.app.buildModeSet.some(r=>r.name===e.buildMode))throw new Error(`Build mode '${e.buildMode}' not found in project build-profile.json5.`)}function lS(n,e){let t;if(e.modules&&e.modules.length>0)t=e.modules;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 Error(`Multiple entry modules found (${i.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`):new Error(`No entry module found and multiple modules available (${o.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`)}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 yo(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 go(n,e){let t=e,r=`${n} failed`;console.error(Lc(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 wo(n,e,t,r,o,i){let s=Hi(i);console.log(`
|
|
19
|
+
[ohpm install] Running...`);try{await n.installAll()}catch(a){go("ohpm install",a)}if(s.required){console.log(`
|
|
20
|
+
[hvigor sync] Running...`);try{await e.sync(t,r)}catch(a){go("hvigor sync",a)}}else console.log(`
|
|
21
21
|
[hvigor sync] Skipped (configurations unchanged)`);console.log(`
|
|
22
|
-
[hvigor build] Running...`);try{o.type==="product"?await e.buildProduct(t,r):await e.buildModules(t,r,o.modulesToBuild,o.moduleTasks)}catch(a){
|
|
23
|
-
Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(
|
|
24
|
-
Failed to merge compile_commands.json: ${e.message}`))}}var
|
|
25
|
-
`+
|
|
26
|
-
[1/2] Running hvigor clean...`);try{await r.clean()}catch(o){
|
|
27
|
-
[2/2] Running hvigor --stop-daemon...`);try{await r.stopDaemon()}catch(o){
|
|
28
|
-
`+
|
|
22
|
+
[hvigor build] Running...`);try{o.type==="product"?await e.buildProduct(t,r):await e.buildModules(t,r,o.modulesToBuild,o.moduleTasks)}catch(a){go("hvigor build",a)}dS(i)}function dS(n){try{if(jn(n).length===0)return;xc(n),console.log(Nc(`
|
|
23
|
+
Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(Oc(`
|
|
24
|
+
Failed to merge compile_commands.json: ${e.message}`))}}var rp=new aS("build").description("Build HarmonyOS project").option("--product <product>","Product name defined in build-profile.json5 (default: default)").option("--modules <modules...>","Modules to build (format: module or module@target)").option("--build-mode <mode>","Build mode (buildModeSet in build-profile.json5; e.g. debug, release; default: debug)").action(async n=>{try{let e=process.cwd(),t=z.discover(e);console.warn(Oc("Ensure the project source is trustworthy before proceeding."));let r=await A.new();r.assertJava(),cS(t,n);let o=n.product||"default",i=n.buildMode||"debug",s;if(n.product&&!n.modules)s={type:"product"};else{let l=lS(t,n),d=yo(t,l);s={type:"modules",modulesToBuild:l,moduleTasks:d}}let a=new en(r,t.rootDir),c=new xe(r,t.rootDir);await Tt(t.rootDir,async()=>wo(a,c,o,i,s,t.rootDir),()=>{console.log("Another build is already running for this project. Waiting for completion...")}),console.log(`
|
|
25
|
+
`+Nc("Build completed successfully"))}catch(e){console.error(Lc(e.message)),process.exit(1)}});rp.command("clean").description("Clean HarmonyOS project build outputs").action(async()=>{try{let n=process.cwd(),e=z.discover(n);console.warn(Oc("Ensure the project source is trusted before proceeding."));let t=await A.new();t.assertJava();let r=new xe(t,e.rootDir);await Tt(e.rootDir,async()=>{console.log(`
|
|
26
|
+
[1/2] Running hvigor clean...`);try{await r.clean()}catch(o){go("hvigor clean",o)}console.log(`
|
|
27
|
+
[2/2] Running hvigor --stop-daemon...`);try{await r.stopDaemon()}catch(o){go("hvigor --stop-daemon",o)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
|
|
28
|
+
`+Nc("Clean completed successfully."))}catch(n){console.error(Lc(n.message)),process.exit(1)}});var op=rp;import{Command as yb}from"commander";import{green as Eo,red as wb,yellow as cs}from"colorette";import*as ls from"path";import{randomUUID as PS}from"crypto";import{execa as CS}from"execa";import{execa as ES}from"execa";import{execFile as uS,spawn as pS}from"child_process";import{promisify as fS}from"util";var mS=fS(uS);function ip(n,e,t){let o=n.replace(/\r\n/g,`
|
|
29
29
|
`).split(`
|
|
30
|
-
`),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
|
|
31
|
-
`)){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"){f(`[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
|
|
30
|
+
`),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 sp(n,e,t){let r=n.endsWith("\r")?n.slice(0,-1):n;r.length>0&&t.onData([r],e)}function hS(n,e){return{stdout:n.stdoutChunks.join(""),stderr:n.stderrChunks.join(""),exitCode:e??-1}}function gS(){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=ip(e.stdoutLineBuffer+s,"stdout",t)}),n.stderr?.on("data",i=>{let s=i.toString();e.stderrChunks.push(s),e.stderrLineBuffer=ip(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,sp(e.stdoutLineBuffer,"stdout",t),sp(e.stderrLineBuffer,"stderr",t),t.onClose(i);let s=hS(e,i);r(s)})}async function Hn(n,e=[],t={}){try{let{stdout:r,stderr:o}=await mS(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 ap(n,e,t){return await new Promise((r,o)=>{let i=pS(n,e,{stdio:["inherit","pipe","pipe"]}),s=gS();yS(i,s,t,r,o)})}function cp(n){let e=n.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var wS=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],vS=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function lr(n){return n?wS.some(e=>e.test(n))?"transient":vS.some(e=>e.test(n))?"fatal":"ok":"ok"}var Mc=[800,1500,2500];function SS(n){return new Promise(e=>setTimeout(e,n))}async function ae(n,e){let t=1+Mc.length,r={stdout:"",stderr:"",exitCode:-1};for(let o=0;o<t;o++){if(r=await Hn(n,e),r.exitCode===0||lr(r.stderr)!=="transient"||o>=t-1)return r;f(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${Mc[o]}ms`),await SS(Mc[o])}return r}var lp=/^[\w.-]+$/;async function Xi(n,e,t){if(!lp.test(t)){f(`Skipping invalid param key: ${JSON.stringify(t)}`);return}let r=["-t",e,"shell","param","get",t];f(`Executing: ${n} ${r.join(" ")}`);let o=await ae(n,r);if(o.exitCode!==0)return;let i=o.stdout.trim();if(!(!i||lr(i)!=="ok"))return cp(i)}var _c="__DEVECO_PARAM_DELIM__";function bS(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||lr(i)!=="ok")continue;let s=cp(i);s&&t.set(e[o],s)}return t}async function dr(n,e,t){let r=t.filter(a=>lp.test(a)?!0:(f(`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 Xi(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 ae(n,["-t",e,"shell",o]);if(i.exitCode===0){let a=bS(i.stdout,r);if(a.size>0)return a}f(`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 Xi(n,e,a);c&&s.set(a,c)}return s}function $n(n){return n.startsWith("127.0.0.1:")}var dp=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],re=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 f(`Executing: ${this.hdcPath} ${e.join(" ")}`),ES(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let r of e.split(`
|
|
31
|
+
`)){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"){f(`[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 dr(this.hdcPath,e,[...dp]);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 Error(`Multiple devices match "${t}". Use a serial instead:
|
|
32
32
|
`+i.map(s=>` - ${s.name} (${s.device.serial})`).join(`
|
|
33
|
-
`)):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
|
|
34
|
-
`).map(t=>t.trim()).filter(t=>t.length>0&&t!=="[Empty]")}async isDevEcoStudioRunningViaHdc(e){return(await this.runHdc(["-t",e,"shell","ps -ef | grep com.huawei.devecostudio | grep -v grep"],!1)).trim().length>0}async launchPreview(e,t,r,o,i,s,a,c,l){let h=JSON.stringify({bundleName:t,abilityName:r,moduleName:s,productName:o,productType:i,subProductType:a,instanceId:c,launchDeviceIndex:l,launchFlag:"{}",isCustom:!1,nativeDebuggable:!1,appDebuggable:!1}).replace(/'/g,"'\\''"),w=`aa start -a DevEcoViewerAbility -b com.huawei.devecostudio -m DevEcoViewer --pi instanceId ${c} --ps paramJson '${h}'`;return await this.runHdc(["-t",e,"shell",w])}async forceStopApp(e,t){let r=["-t",e,"shell","aa","force-stop",t];return await this.runHdc(r,!1)}};import _c from"fs";import*as $n from"path";function wo(n,e){if(!_c.existsSync(n))throw new Error(`Apply file list not found: ${n}`);let r=_c.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=$n.resolve(e),i=new Set,s=[];for(let a of r){let c=$n.resolve(o,a),l=$n.isAbsolute(a)?$n.relative(o,a):a;if(l.startsWith(".."))throw new Error(`File path is outside the project directory: ${a}`);let d=R.isPathContainedWithSymlink(l,o);if(!d.contained){if(!_c.existsSync(c))throw new Error(`File not found: ${a}`);let h=d.reason?`; ${d.reason}`:"";throw new Error(`File path is outside the project directory: ${a}${h}`)}i.has(c)||(i.add(c),s.push(c))}return s}import Fc from"fs";import dr from"path";import{execa as CS}from"execa";import cp from"fs";import*as lp from"path";import ES from"json5";function PS(n,e){try{let r=ES.parse(cp.readFileSync(n,"utf-8")).modules?.find(o=>o.name===e);return r?.srcPath?r.srcPath.replace(/^\.\//,""):null}catch(t){return f(`[apply] resolveModuleSrcPath fallback (module=${e}): ${t.message}`),null}}function St(n,e){let t=lp.join(n,"build-profile.json5");return cp.existsSync(t)?PS(t,e)??e:e}import*as dp from"os";async function up(n,e,t,r){let o={...process.env,DEVECO_SDK_HOME:n.sdkPath};if(n.javaPath){let c=dr.dirname(n.javaPath);o.PATH=`${c}${dr.delimiter}${process.env.PATH||""}`}E()&&(o.HVIGOR_USER_HOME=dr.join(dp.homedir(),".hvigor"));let i=[n.hvigorJsPath,"--mode","module","-p",`module=${t.join(",")}@${r}`,"-p",`product=${r}`,"-p","debuggable=true","assembleDevHqf","--analyze=normal","--parallel","--incremental","--no-daemon"];f(`[buildSignedHqf] ${n.nodePath} ${i.join(" ")}`);let s=await CS(n.nodePath,i,{cwd:e,env:o,stdout:"inherit",stderr:"inherit",reject:!1}),a=(s.exitCode??0)|0;if(a===-1)throw new Error("hvigor hot compile produced invalid abc (exit code -1)");if(a!==0)throw new Error(`hvigor assembleDevHqf failed with exit code ${s.exitCode}`);return t.map(c=>AS(e,c,r))}function pp(n,e,t){let r=St(n,e);return dr.join(n,r,"build",t,"outputs")}function IS(n,e,t){return dr.join(pp(n,e,t),`${e}-${t}-signed.hqf`)}function AS(n,e,t){let r=pp(n,e,t),o=IS(n,e,t);if(Fc.existsSync(o))return o;let i=jc(r,"-signed.hqf")??jc(r,".hqf");if(!i)throw new Error(`Signed hqf not found at ${o} (and no *.hqf under ${r})`);return f(`[buildSignedHqf] signed hqf not at exact path, using fallback: ${i}`),i}function jc(n,e){if(!Fc.existsSync(n))return null;for(let t of Fc.readdirSync(n,{withFileTypes:!0})){let r=dr.join(n,t.name);if(t.isDirectory()){let o=jc(r,e);if(o)return o}else if(t.isFile()&&t.name.endsWith(e))return r}return null}import J from"fs";import*as N from"path";import Hc from"json5";var fp="default",ur=class n{static writeChangedFileLists(e,t,r,o){let i=t||fp,s=n.loadBuildProfile(e);if(!s)return{writtenModules:[],skippedFiles:r};let a=s.modules,c=n.filterRunnableModules(e,a);if(c.length===0)return{writtenModules:[],skippedFiles:r};let l=n.buildReverseDependencyMap(e,a),d=n.createCollectors(c),h=n.collectChanges(r,e,a,l,d);return{writtenModules:n.flushCollectors(e,i,c,d,o),skippedFiles:h}}static initEmptyChangedFileLists(e,t,r){let o=t||fp,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 h=n.resolveTargetModules(d,t,r,o);if(h.length===0){s.push(c);continue}n.dispatchToCollectors(h,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(J.existsSync(s)||(J.mkdirSync(i,{recursive:!0}),J.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");J.existsSync(c)||(J.mkdirSync(a,{recursive:!0}),J.writeFileSync(c,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=N.join(e,"build-profile.json5");if(!J.existsSync(t))return null;try{let r=J.readFileSync(t,"utf-8");return Hc.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(!J.existsSync(r))return"entry";try{let o=J.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=N.join(e,t,"oh-package.json5");if(!J.existsSync(r))return[];try{let o=J.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=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(h=>h.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);J.existsSync(l)||J.mkdirSync(l,{recursive:!0}),J.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),f(`[ChangedFileListWriter] Written hotReload: ${s} (${c.length} entries)`)}static readExistingApply(e){if(!J.existsSync(e))return[];try{let t=J.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"),h=o.map(V=>n.resolveRelativePathForPatch(V,d)),w=n.mergeStrings(l.modifiedFiles,h),v=n.mergePatchResources(l.rawFile,i),I=n.mergePatchResources(l.resFile,s),G=N.dirname(c);J.existsSync(G)||J.mkdirSync(G,{recursive:!0}),J.writeFileSync(c,JSON.stringify({resources:{resFile:I,rawFile:v},modifiedFiles:w}),"utf-8"),f(`[ChangedFileListWriter] Written patch: ${c}`)}static readExistingPatch(e){if(!J.existsSync(e))return{modifiedFiles:[],rawFile:[],resFile:[]};try{let t=J.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 DS from"fs";import{randomUUID as RS}from"crypto";import{execa as TS}from"execa";var pr=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,r){for(let a of t)if(!DS.existsSync(a)){let c=`Signed hqf file not found: ${a}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}let i=`/data/local/tmp/${RS()}`,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(f(`[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;f(`[InstallHqf] Executing: ${r} ${e.join(" ")}`);try{let{stdout:o}=await TS(r,e,{env:{...process.env}});return o}catch(o){if(t)throw o;return o.stdout||""}}};var kS="6.1.1",Xi=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}toolProvider;projectRoot;async execute(e){await Tt(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion(kS);let t=wo(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=ur.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 f(`[Apply] hvigor assembleDevHqf --no-daemon (modules=${t.join(",")})`),await up(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 pr(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 Nt(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 Nt(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 mp from"fs";import*as F from"path";var Zi=class n{static generate(e,t,r,o){let i=St(e,t),s=F.join(e,i),a=F.join(s,"build","config"),c=n.buildConfig(e,s,r,o);mp.mkdirSync(a,{recursive:!0}),mp.writeFileSync(F.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),f(`[BuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,o){let i=F.dirname(o.nodePath)+F.sep,s=F.join(t,"build",r),a=F.join(s,"intermediates"),c=F.join(a,"loader_out",r),l=F.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:i,projectProfilePath:F.join(e,"build-profile.json5"),localPropertiesPath:F.join(e,"local.properties"),appResource:F.join(l,"ResourceTable.txt"),cachePath:F.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:F.join(a,"loader",r,"loader.json"),aceModuleJsonPath:F.join(l,"module.json"),aceSoPath:F.join(c,"nativeDependencies.txt"),aceModuleRoot:F.join(t,"src","main","ets"),aceModuleBuild:F.join(c,"ets"),aceProfilePath:F.join(l,"resources","base","profile"),aceSuperVisualPath:F.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:F.join(c,"ets"),changedFileList:F.join(a,"patch","default","changedFileList.json"),patchAbcPath:F.join(a,"patch","default","ets"),removeChangedFileListInSdk:"true"}}}};import hp from"fs";import*as j from"path";var Qi=class n{static generate(e,t,r,o){let i=St(e,t),s=j.join(e,i),a=j.join(s,"build","config"),c=n.buildConfig(e,s,r,o);hp.mkdirSync(a,{recursive:!0}),hp.writeFileSync(j.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),f(`[HotReloadBuildConfigManager] 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,"hotReload","changedFileList.json"),patchAbcPath:j.join(a,"hotReload","patchAbcPath","ets"),removeChangedFileListInSdk:"true"}}}};import gp from"crypto";import Je from"fs";import Ke from"path";import yp from"os";import{io as xS}from"socket.io-client";var NS=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),fr=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;Je.mkdirSync(Ke.dirname(o),{recursive:!0}),Je.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
|
+
`)):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 dr(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=b()?!1:$n(e),r,o;try{let i=await dr(this.hdcPath,e,[...dp]);r=this.extractDisplayName(i),o=i.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:o}}async ensureWirelessSelfConnection(){if(!b())return{mode:"tcp"};let e=await this.getLocalParam("persist.hdc.mode");if(!e)return{mode:""};if(e!=="tcp")return{mode:e};let t=await this.getLocalParam("persist.hdc.port");if(!t)return{mode:"tcp"};let r=await this.listDevices();if(this.hasDeviceWithPort(r,t))return{mode:"tcp",port:t,autoConnected:!1};let o=`127.0.0.1:${t}`;f(`Executing: ${this.hdcPath} tconn ${o}`);let i=!1;try{await this.executeHdc(["tconn",o]),i=!0}catch(s){f(`hdc tconn ${o} failed: ${s.message}`)}return{mode:"tcp",port:t,autoConnected:i}}async getLocalParam(e){f(`Executing: param get ${e}`);let t=await Hn("param",["get",e]);return t.exitCode!==0||!t.stdout||/^Get parameter\b.*fail!/i.test(t.stdout)?"":this.parseLocalParamValue(t.stdout)}parseLocalParamValue(e){let t=e.trim(),r=t.indexOf("=");if(r!==-1)return t.slice(r+1).trim();let o=t.match(/^[\w.]+\s*:\s*(.+)$/);return o?o[1].trim():t}hasDeviceWithPort(e,t){let r=`127.0.0.1:${t}`;return e.some(o=>o.serial===r)}};var Nt=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=re.from(e)}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;f(`Executing: ${r} ${e.join(" ")}`);try{let{stdout:o}=await CS(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){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/${PS()}`;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){let o=["-t",e,"shell","aa","start","-a",r,"-b",t];return await this.runHdc(o)}async connectTarget(e){await this.runHdc(["tconn",e])}async disconnectTarget(e){await this.runHdc(["tconn",e,"-remove"],!1)}async listRawTargets(){return(await this.runHdc(["list","targets"],!1)).split(`
|
|
34
|
+
`).map(t=>t.trim()).filter(t=>t.length>0&&t!=="[Empty]")}async isDevEcoStudioRunningViaHdc(e){return(await this.runHdc(["-t",e,"shell","ps -ef | grep com.huawei.devecostudio | grep -v grep"],!1)).trim().length>0}async launchPreview(e,t,r,o,i,s,a,c,l){let h=JSON.stringify({bundleName:t,abilityName:r,moduleName:s,productName:o,productType:i,subProductType:a,instanceId:c,launchDeviceIndex:l,launchFlag:"{}",isCustom:!1,nativeDebuggable:!1,appDebuggable:!1}).replace(/'/g,"'\\''"),w=`aa start -a DevEcoViewerAbility -b com.huawei.devecostudio -m DevEcoViewer --pi instanceId ${c} --ps paramJson '${h}'`;return await this.runHdc(["-t",e,"shell",w])}async forceStopApp(e,t){let r=["-t",e,"shell","aa","force-stop",t];return await this.runHdc(r,!1)}};import Fc from"fs";import*as Un from"path";function vo(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=Un.resolve(e),i=new Set,s=[];for(let a of r){let c=Un.resolve(o,a),l=Un.isAbsolute(a)?Un.relative(o,a):a;if(l.startsWith(".."))throw new Error(`File path is outside the project directory: ${a}`);let d=R.isPathContainedWithSymlink(l,o);if(!d.contained){if(!Fc.existsSync(c))throw new Error(`File not found: ${a}`);let h=d.reason?`; ${d.reason}`:"";throw new Error(`File path is outside the project directory: ${a}${h}`)}i.has(c)||(i.add(c),s.push(c))}return s}import jc from"fs";import ur from"path";import{execa as DS}from"execa";import up from"fs";import*as pp from"path";import IS from"json5";function AS(n,e){try{let r=IS.parse(up.readFileSync(n,"utf-8")).modules?.find(o=>o.name===e);return r?.srcPath?r.srcPath.replace(/^\.\//,""):null}catch(t){return f(`[apply] resolveModuleSrcPath fallback (module=${e}): ${t.message}`),null}}function St(n,e){let t=pp.join(n,"build-profile.json5");return up.existsSync(t)?AS(t,e)??e:e}import*as fp from"os";async function mp(n,e,t,r){let o={...process.env,DEVECO_SDK_HOME:n.sdkPath};if(n.javaPath){let c=ur.dirname(n.javaPath);o.PATH=`${c}${ur.delimiter}${process.env.PATH||""}`}b()&&(o.HVIGOR_USER_HOME=ur.join(fp.homedir(),".hvigor"));let i=[n.hvigorJsPath,"--mode","module","-p",`module=${t.join(",")}@${r}`,"-p",`product=${r}`,"-p","debuggable=true","assembleDevHqf","--analyze=normal","--parallel","--incremental","--no-daemon"];f(`[buildSignedHqf] ${n.nodePath} ${i.join(" ")}`);let s=await DS(n.nodePath,i,{cwd:e,env:o,stdout:"inherit",stderr:"inherit",reject:!1}),a=(s.exitCode??0)|0;if(a===-1)throw new Error("hvigor hot compile produced invalid abc (exit code -1)");if(a!==0)throw new Error(`hvigor assembleDevHqf failed with exit code ${s.exitCode}`);return t.map(c=>TS(e,c,r))}function hp(n,e,t){let r=St(n,e);return ur.join(n,r,"build",t,"outputs")}function RS(n,e,t){return ur.join(hp(n,e,t),`${e}-${t}-signed.hqf`)}function TS(n,e,t){let r=hp(n,e,t),o=RS(n,e,t);if(jc.existsSync(o))return o;let i=Hc(r,"-signed.hqf")??Hc(r,".hqf");if(!i)throw new Error(`Signed hqf not found at ${o} (and no *.hqf under ${r})`);return f(`[buildSignedHqf] signed hqf not at exact path, using fallback: ${i}`),i}function Hc(n,e){if(!jc.existsSync(n))return null;for(let t of jc.readdirSync(n,{withFileTypes:!0})){let r=ur.join(n,t.name);if(t.isDirectory()){let o=Hc(r,e);if(o)return o}else if(t.isFile()&&t.name.endsWith(e))return r}return null}import J from"fs";import*as N from"path";import $c from"json5";var gp="default",pr=class n{static writeChangedFileLists(e,t,r,o){let i=t||gp,s=n.loadBuildProfile(e);if(!s)return{writtenModules:[],skippedFiles:r};let a=s.modules,c=n.filterRunnableModules(e,a);if(c.length===0)return{writtenModules:[],skippedFiles:r};let l=n.buildReverseDependencyMap(e,a),d=n.createCollectors(c),h=n.collectChanges(r,e,a,l,d);return{writtenModules:n.flushCollectors(e,i,c,d,o),skippedFiles:h}}static initEmptyChangedFileLists(e,t,r){let o=t||gp,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 h=n.resolveTargetModules(d,t,r,o);if(h.length===0){s.push(c);continue}n.dispatchToCollectors(h,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(J.existsSync(s)||(J.mkdirSync(i,{recursive:!0}),J.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");J.existsSync(c)||(J.mkdirSync(a,{recursive:!0}),J.writeFileSync(c,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=N.join(e,"build-profile.json5");if(!J.existsSync(t))return null;try{let r=J.readFileSync(t,"utf-8");return $c.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(!J.existsSync(r))return"entry";try{let o=J.readFileSync(r,"utf-8");return $c.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(!J.existsSync(r))return[];try{let o=J.readFileSync(r,"utf-8"),i=$c.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(h=>h.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);J.existsSync(l)||J.mkdirSync(l,{recursive:!0}),J.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),f(`[ChangedFileListWriter] Written hotReload: ${s} (${c.length} entries)`)}static readExistingApply(e){if(!J.existsSync(e))return[];try{let t=J.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"),h=o.map(V=>n.resolveRelativePathForPatch(V,d)),w=n.mergeStrings(l.modifiedFiles,h),v=n.mergePatchResources(l.rawFile,i),I=n.mergePatchResources(l.resFile,s),G=N.dirname(c);J.existsSync(G)||J.mkdirSync(G,{recursive:!0}),J.writeFileSync(c,JSON.stringify({resources:{resFile:I,rawFile:v},modifiedFiles:w}),"utf-8"),f(`[ChangedFileListWriter] Written patch: ${c}`)}static readExistingPatch(e){if(!J.existsSync(e))return{modifiedFiles:[],rawFile:[],resFile:[]};try{let t=J.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 kS from"fs";import{randomUUID as xS}from"crypto";import{execa as NS}from"execa";var fr=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,r){for(let a of t)if(!kS.existsSync(a)){let c=`Signed hqf file not found: ${a}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}let i=`/data/local/tmp/${xS()}`,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(f(`[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;f(`[InstallHqf] Executing: ${r} ${e.join(" ")}`);try{let{stdout:o}=await NS(r,e,{env:{...process.env}});return o}catch(o){if(t)throw o;return o.stdout||""}}};var LS="6.1.1",Zi=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}toolProvider;projectRoot;async execute(e){await Tt(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion(LS);let t=vo(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=pr.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 f(`[Apply] hvigor assembleDevHqf --no-daemon (modules=${t.join(",")})`),await mp(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 fr(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 Nt(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 Nt(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 yp from"fs";import*as F from"path";var Qi=class n{static generate(e,t,r,o){let i=St(e,t),s=F.join(e,i),a=F.join(s,"build","config"),c=n.buildConfig(e,s,r,o);yp.mkdirSync(a,{recursive:!0}),yp.writeFileSync(F.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),f(`[BuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,o){let i=F.dirname(o.nodePath)+F.sep,s=F.join(t,"build",r),a=F.join(s,"intermediates"),c=F.join(a,"loader_out",r),l=F.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:i,projectProfilePath:F.join(e,"build-profile.json5"),localPropertiesPath:F.join(e,"local.properties"),appResource:F.join(l,"ResourceTable.txt"),cachePath:F.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:F.join(a,"loader",r,"loader.json"),aceModuleJsonPath:F.join(l,"module.json"),aceSoPath:F.join(c,"nativeDependencies.txt"),aceModuleRoot:F.join(t,"src","main","ets"),aceModuleBuild:F.join(c,"ets"),aceProfilePath:F.join(l,"resources","base","profile"),aceSuperVisualPath:F.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:F.join(c,"ets"),changedFileList:F.join(a,"patch","default","changedFileList.json"),patchAbcPath:F.join(a,"patch","default","ets"),removeChangedFileListInSdk:"true"}}}};import wp from"fs";import*as j from"path";var es=class n{static generate(e,t,r,o){let i=St(e,t),s=j.join(e,i),a=j.join(s,"build","config"),c=n.buildConfig(e,s,r,o);wp.mkdirSync(a,{recursive:!0}),wp.writeFileSync(j.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),f(`[HotReloadBuildConfigManager] 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,"hotReload","changedFileList.json"),patchAbcPath:j.join(a,"hotReload","patchAbcPath","ets"),removeChangedFileListInSdk:"true"}}}};import vp from"crypto";import Je from"fs";import Ke from"path";import Sp from"os";import{io as OS}from"socket.io-client";var MS=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),mr=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;Je.mkdirSync(Ke.dirname(o),{recursive:!0}),Je.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(`
|
|
35
35
|
`)?a:a+`
|
|
36
36
|
`),r.length>100&&r.shift())},onWatchResult:s=>{let a=n.extractText(s);if(!a.trim())return;let c=`[WatchResult] ${a}`;console.log(c),Je.writeFileSync(e,[...r,c+`
|
|
37
|
-
`].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 Ke.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=
|
|
37
|
+
`].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 Ke.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=OS(`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),h(),this.invalidateSocket(),o(new Error(`Socket disconnected: ${w}`)))},s=this.createOutputHandler(),{onWatchLog:a,onWatchResult:c,onWatchCompileResult:l,onWatchCompileData:d}=this.getDataHandler(),h=()=>{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:h}}getDataHandler(){let e=n.extractText;return{onWatchLog:s=>{let a=e(s);a.trim()&&process.stdout.write(a+(a.endsWith(`
|
|
38
38
|
`)?"":`
|
|
39
|
-
`))},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(!Je.existsSync(e))return null;try{let t=Je.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=Ke.join(t,"fd"),o=Ke.join(t,"ac"),i=Ke.join(t,"ce"),s=this.readComponents(r),a=this.xorBuffers([s[0],s[1],s[2],Buffer.from(NS)]),c=this.readSingleFile(o),l=gp.pbkdf2Sync(Buffer.from(a).toString(),c,1e4,16,"sha256"),d=this.readSingleFile(i),h=this.aesGcmDecrypt(l,d),w=Buffer.from(e,"hex");return this.aesGcmDecrypt(h,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=gp.createDecipheriv("aes-128-gcm",e,i);return l.setAuthTag(c),Buffer.concat([l.update(a),l.final()])}readComponents(e){let t=Je.readdirSync(e).map(r=>Ke.join(e,r)).filter(r=>Je.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=Je.readdirSync(r);if(o.length===0)throw new Error(`No file in ${r}`);return Je.readFileSync(Ke.join(r,o[0]))})}readSingleFile(e){let t=Je.readdirSync(e).map(r=>Ke.join(e,r)).filter(r=>Je.statSync(r).isFile());if(t.length===0)throw new Error(`No file in ${e}`);return Je.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||Ke.join(yp.homedir(),".hvigor");return Ke.join(e,"daemon","cache","daemon-sec.json")}getMetaDir(){let e=process.env.HVIGOR_USER_HOME||Ke.join(yp.homedir(),".hvigor");return Ke.join(e,"meta")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}};import Sp from"fs";import*as Lt from"path";import{green as rs,yellow as $c}from"colorette";import Un from"fs";import*as Bn from"path";import LS from"json5";var OS=2e6,MS=1e6,_S="hotreload",es=class n{static generateOrUpdate(e,t,r){let o=n.readAppConfig(e),i=Bn.resolve(e,t),s=Bn.join(i,"patch.json"),a;return Un.existsSync(s)?(f(`[PatchManager] patch.json found at ${s}, incrementing patchVersionCode`),a=n.readExistingPatch(s),a.app.patchVersionCode+=1):(f(`[PatchManager] patch.json not found, generating new one at ${s}`),a={app:{bundleName:o.bundleName,patchVersionCode:OS,versionCode:o.versionCode},module:{name:r,type:_S}}),n.writePatchJson(s,a),a}static readAppConfig(e){let t=Bn.join(e,"AppScope","app.json5");if(!Un.existsSync(t))throw new Error(`AppScope/app.json5 not found at ${t}. Unable to read bundleName and versionCode.`);let r=Un.readFileSync(t,"utf-8"),o=LS.parse(r),i=o?.app?.bundleName;if(!i)throw new Error("bundleName is missing in AppScope/app.json5");let s=o?.app?.versionCode??MS;return{bundleName:i,versionCode:s}}static readExistingPatch(e){let t=Un.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=Bn.dirname(e);Un.existsSync(r)||Un.mkdirSync(r,{recursive:!0});let o=JSON.stringify(t,null,2);Un.writeFileSync(e,o,"utf-8"),f(`[PatchManager] patch.json written to ${e}`),f(`[PatchManager] Content: ${o}`)}};import me from"fs";import*as $ from"path";import wp from"crypto";import FS from"json5";import{execa as vp}from"execa";var ts=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}`);f(`[DecipherUtil] Decrypting ${r}, encrypted length: ${t.length}`);let o=$.resolve(e,"material"),i=n.getKey(o,r),s=new Int8Array(Buffer.from(t,"hex"));return f(`[DecipherUtil] Data length: ${s.length}, key length: ${i.length}`),n.decrypt(i,s).toString("utf-8")}static getKey(e,t){let r=$.resolve(e,n.DIRS[0]),o=n.readFd(r,t),i=n.readDirBytes($.resolve(e,n.DIRS[1]),t),s=n.getRootKey(o,i,t),a=n.readDirBytes($.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=wp.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=wp.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=me.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=$.join(e,i);o.push(n.readDirBytes(s,t))}return o}static readDirBytes(e,t){if(me.statSync(e).isDirectory()){let o=me.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(me.readFileSync($.join(e,o[0])))}return new Int8Array(me.readFileSync(e))}},ns=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let o=`${$.dirname(e.javaPath)}${$.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=$.join(e,"ets","modules.abc");if(me.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(!me.existsSync(e))return null;let t=me.readdirSync(e,{withFileTypes:!0});for(let r of t){let o=$.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=St(this.projectRoot,e),o=$.join(this.projectRoot,r,"build",t,"outputs","default");return me.existsSync(o)||me.mkdirSync(o,{recursive:!0}),{unsignedHqfPath:$.join(o,`${e}-default-unsigned.hqf`),signedHqfPath:$.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=$.dirname(t),s=this.toolProvider.javaPath,a=["-jar",o,"--mode","hqf","--json-path",e,"--ets-path",i,"--out-path",r,"--force","true"];f(`[GenSignHqf] Packing: ${s} ${a.join(" ")}`);try{let c=Date.now(),l=await vp(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):me.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;f(`[GenSignHqf] Signing: ${i} ${o.join(" ")}`);try{let s=Date.now(),a=await vp(i,o,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] sign (JVM#2): ${Date.now()-s}ms`),a.stdout&&console.log(a.stdout),a.stderr&&console.error(a.stderr),a.exitCode!==0?this.signFailResult(e,`hqf signing failed with exit code ${a.exitCode}`):me.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(s){return this.signFailResult(e,`hqf signing failed: ${s.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=ts.decryptPwd(r,t.storePassword,"storePassword"),i=ts.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=$.resolve(e.storeFile,".."),r=$.join(t,"material");return me.existsSync(r)?t:null}readSigningConfig(e){let t=$.join(this.projectRoot,"build-profile.json5");if(!me.existsSync(t))return null;try{let r=me.readFileSync(t,"utf-8"),o=FS.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=[$.join(e,"default","openharmony","toolchains","lib","hap-sign-tool.jar"),$.join(e,"toolchains","lib","hap-sign-tool.jar")];for(let r of t)if(me.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=[$.join(e,"default","openharmony","toolchains","lib","app_packing_tool.jar"),$.join(e,"toolchains","lib","app_packing_tool.jar")];for(let r of t)if(me.existsSync(r))return r;return null}};async function bp(n){let e=Date.now(),t=St(n.projectPath,n.moduleName),r=jS(n);console.log($c("[HotReload] Ensure the project source is trusted before proceeding."));let o=HS(n),i=wo(r,n.projectPath);console.log(`[HotReload] Parsed ${i.length} changed file(s) from ${n.applyFileName}`),$S(n,i),US(n,t),await BS(n,o);let s=Lt.join(n.projectPath,t,"patch.json"),a=await GS(n,t,s);return await VS(n,a),console.log(rs("[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 jS(n){if(Lt.basename(n.applyFileName)!==n.applyFileName)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${n.applyFileName}`);return Lt.join(n.projectPath,".hvigor",n.applyFileName)}function HS(n){let{projectPath:e,toolProvider:t}=n,r=new fr(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 $S(n,e){let t=ur.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(rs(`[HotReload] changedFileList written for: ${t.writtenModules.join(", ")}`)),t.skippedFiles.length>0&&console.warn($c(`[HotReload] skipped ${t.skippedFiles.length} file(s)`))}function US(n,e){let t=es.generateOrUpdate(n.projectPath,e,n.moduleName);console.log(rs(`[HotReload] patch.json ready (patchVersionCode=${t.app.patchVersionCode})`))}async function BS(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=WS(r);throw new Error(`Daemon hot compile exited with code ${o}`+(i?`
|
|
39
|
+
`))},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(!Je.existsSync(e))return null;try{let t=Je.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=Ke.join(t,"fd"),o=Ke.join(t,"ac"),i=Ke.join(t,"ce"),s=this.readComponents(r),a=this.xorBuffers([s[0],s[1],s[2],Buffer.from(MS)]),c=this.readSingleFile(o),l=vp.pbkdf2Sync(Buffer.from(a).toString(),c,1e4,16,"sha256"),d=this.readSingleFile(i),h=this.aesGcmDecrypt(l,d),w=Buffer.from(e,"hex");return this.aesGcmDecrypt(h,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=vp.createDecipheriv("aes-128-gcm",e,i);return l.setAuthTag(c),Buffer.concat([l.update(a),l.final()])}readComponents(e){let t=Je.readdirSync(e).map(r=>Ke.join(e,r)).filter(r=>Je.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=Je.readdirSync(r);if(o.length===0)throw new Error(`No file in ${r}`);return Je.readFileSync(Ke.join(r,o[0]))})}readSingleFile(e){let t=Je.readdirSync(e).map(r=>Ke.join(e,r)).filter(r=>Je.statSync(r).isFile());if(t.length===0)throw new Error(`No file in ${e}`);return Je.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||Ke.join(Sp.homedir(),".hvigor");return Ke.join(e,"daemon","cache","daemon-sec.json")}getMetaDir(){let e=process.env.HVIGOR_USER_HOME||Ke.join(Sp.homedir(),".hvigor");return Ke.join(e,"meta")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}};import Pp from"fs";import*as Lt from"path";import{green as os,yellow as Uc}from"colorette";import Bn from"fs";import*as Wn from"path";import _S from"json5";var FS=2e6,jS=1e6,HS="hotreload",ts=class n{static generateOrUpdate(e,t,r){let o=n.readAppConfig(e),i=Wn.resolve(e,t),s=Wn.join(i,"patch.json"),a;return Bn.existsSync(s)?(f(`[PatchManager] patch.json found at ${s}, incrementing patchVersionCode`),a=n.readExistingPatch(s),a.app.patchVersionCode+=1):(f(`[PatchManager] patch.json not found, generating new one at ${s}`),a={app:{bundleName:o.bundleName,patchVersionCode:FS,versionCode:o.versionCode},module:{name:r,type:HS}}),n.writePatchJson(s,a),a}static readAppConfig(e){let t=Wn.join(e,"AppScope","app.json5");if(!Bn.existsSync(t))throw new Error(`AppScope/app.json5 not found at ${t}. Unable to read bundleName and versionCode.`);let r=Bn.readFileSync(t,"utf-8"),o=_S.parse(r),i=o?.app?.bundleName;if(!i)throw new Error("bundleName is missing in AppScope/app.json5");let s=o?.app?.versionCode??jS;return{bundleName:i,versionCode:s}}static readExistingPatch(e){let t=Bn.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=Wn.dirname(e);Bn.existsSync(r)||Bn.mkdirSync(r,{recursive:!0});let o=JSON.stringify(t,null,2);Bn.writeFileSync(e,o,"utf-8"),f(`[PatchManager] patch.json written to ${e}`),f(`[PatchManager] Content: ${o}`)}};import me from"fs";import*as $ from"path";import bp from"crypto";import $S from"json5";import{execa as Ep}from"execa";var ns=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}`);f(`[DecipherUtil] Decrypting ${r}, encrypted length: ${t.length}`);let o=$.resolve(e,"material"),i=n.getKey(o,r),s=new Int8Array(Buffer.from(t,"hex"));return f(`[DecipherUtil] Data length: ${s.length}, key length: ${i.length}`),n.decrypt(i,s).toString("utf-8")}static getKey(e,t){let r=$.resolve(e,n.DIRS[0]),o=n.readFd(r,t),i=n.readDirBytes($.resolve(e,n.DIRS[1]),t),s=n.getRootKey(o,i,t),a=n.readDirBytes($.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=bp.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=bp.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=me.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=$.join(e,i);o.push(n.readDirBytes(s,t))}return o}static readDirBytes(e,t){if(me.statSync(e).isDirectory()){let o=me.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(me.readFileSync($.join(e,o[0])))}return new Int8Array(me.readFileSync(e))}},rs=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let o=`${$.dirname(e.javaPath)}${$.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=$.join(e,"ets","modules.abc");if(me.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(!me.existsSync(e))return null;let t=me.readdirSync(e,{withFileTypes:!0});for(let r of t){let o=$.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=St(this.projectRoot,e),o=$.join(this.projectRoot,r,"build",t,"outputs","default");return me.existsSync(o)||me.mkdirSync(o,{recursive:!0}),{unsignedHqfPath:$.join(o,`${e}-default-unsigned.hqf`),signedHqfPath:$.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=$.dirname(t),s=this.toolProvider.javaPath,a=["-jar",o,"--mode","hqf","--json-path",e,"--ets-path",i,"--out-path",r,"--force","true"];f(`[GenSignHqf] Packing: ${s} ${a.join(" ")}`);try{let c=Date.now(),l=await Ep(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):me.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;f(`[GenSignHqf] Signing: ${i} ${o.join(" ")}`);try{let s=Date.now(),a=await Ep(i,o,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] sign (JVM#2): ${Date.now()-s}ms`),a.stdout&&console.log(a.stdout),a.stderr&&console.error(a.stderr),a.exitCode!==0?this.signFailResult(e,`hqf signing failed with exit code ${a.exitCode}`):me.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(s){return this.signFailResult(e,`hqf signing failed: ${s.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=ns.decryptPwd(r,t.storePassword,"storePassword"),i=ns.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=$.resolve(e.storeFile,".."),r=$.join(t,"material");return me.existsSync(r)?t:null}readSigningConfig(e){let t=$.join(this.projectRoot,"build-profile.json5");if(!me.existsSync(t))return null;try{let r=me.readFileSync(t,"utf-8"),o=$S.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=[$.join(e,"default","openharmony","toolchains","lib","hap-sign-tool.jar"),$.join(e,"toolchains","lib","hap-sign-tool.jar")];for(let r of t)if(me.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=[$.join(e,"default","openharmony","toolchains","lib","app_packing_tool.jar"),$.join(e,"toolchains","lib","app_packing_tool.jar")];for(let r of t)if(me.existsSync(r))return r;return null}};async function Cp(n){let e=Date.now(),t=St(n.projectPath,n.moduleName),r=US(n);console.log(Uc("[HotReload] Ensure the project source is trusted before proceeding."));let o=BS(n),i=vo(r,n.projectPath);console.log(`[HotReload] Parsed ${i.length} changed file(s) from ${n.applyFileName}`),WS(n,i),GS(n,t),await VS(n,o);let s=Lt.join(n.projectPath,t,"patch.json"),a=await zS(n,t,s);return await YS(n,a),console.log(os("[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 US(n){if(Lt.basename(n.applyFileName)!==n.applyFileName)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${n.applyFileName}`);return Lt.join(n.projectPath,".hvigor",n.applyFileName)}function BS(n){let{projectPath:e,toolProvider:t}=n,r=new mr(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 WS(n,e){let t=pr.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(os(`[HotReload] changedFileList written for: ${t.writtenModules.join(", ")}`)),t.skippedFiles.length>0&&console.warn(Uc(`[HotReload] skipped ${t.skippedFiles.length} file(s)`))}function GS(n,e){let t=ts.generateOrUpdate(n.projectPath,e,n.moduleName);console.log(os(`[HotReload] patch.json ready (patchVersionCode=${t.app.patchVersionCode})`))}async function VS(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=qS(r);throw new Error(`Daemon hot compile exited with code ${o}`+(i?`
|
|
40
40
|
--- compile output (from watch session) ---
|
|
41
|
-
${i}`:""))}}finally{e.disconnect()}console.log(`[Timing] daemon hot compile: ${Date.now()-t}ms`)}function
|
|
42
|
-
`):""}catch{return""}}async function
|
|
41
|
+
${i}`:""))}}finally{e.disconnect()}console.log(`[Timing] daemon hot compile: ${Date.now()-t}ms`)}function qS(n){try{return Pp.existsSync(n)?Pp.readFileSync(n,"utf8").split(/\r?\n/).filter(t=>t.trim()).slice(-40).join(`
|
|
42
|
+
`):""}catch{return""}}async function zS(n,e,t){let r=Lt.join(n.projectPath,e,"build",n.productName,"intermediates"),o=[Lt.join(r,"hotReload","patchAbcPath"),Lt.join(r,"patch","default")],i=Date.now(),s=new rs(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 YS(n,e){let t=Date.now(),o=await new fr(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 Ip(n,e,t){let r=Lt.join(n.rootDir,".hvigor",t),o;try{o=vo(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 Ap(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 Dp(n,e){await new xe(n,e.rootDir).stopDaemon(),console.log(os("Hvigor daemon stopped."))}import{execa as Vc}from"execa";import*as Rp from"readline/promises";import{stdin as eb,stdout as tb}from"process";import{green as hr,red as as,yellow as qc}from"colorette";import ss from"fs";import*as bo from"path";import nb from"json5";var JS=[{productIndex:0,productName:"Pura 90 Pro",productType:"phone",subProductType:"phone"},{productIndex:1,productName:"MatePad 11.5'S",productType:"tablet",subProductType:"tablet"},{productIndex:2,productName:"Mate X7",productType:"phone",subProductType:"foldable"},{productIndex:3,productName:"Pura X",productType:"phone",subProductType:"widefold"},{productIndex:4,productName:"Mate XT",productType:"phone",subProductType:"triplefold"}],So={productIndex:0,productName:"phone",productType:"phone",subProductType:"phone"};async function KS(){return[]}async function Wc(){let n=await KS();return n.length>0?n:JS}function is(n){return n.toLowerCase().replace(/[\s\W]+/g,"")}var XS={phone:"Pura 90 Pro",tablet:"MatePad 11.5'S",pad:"MatePad 11.5'S",fold:"Mate X7",foldable:"Mate X7",widefold:"Pura X",wide:"Pura X",triplefold:"Mate XT",triple:"Mate XT",pura90:"Pura 90 Pro",pura90pro:"Pura 90 Pro",matepad:"MatePad 11.5'S",matex7:"Mate X7",purax:"Pura X",matext:"Mate XT"};function ZS(n,e){let t=n.length,r=e.length;if(t===0)return r;if(r===0)return t;let o=new Array(r+1),i=new Array(r+1);for(let s=0;s<=r;s++)o[s]=s;for(let s=1;s<=t;s++){i[0]=s;for(let a=1;a<=r;a++){let c=n[s-1]===e[a-1]?0:1;i[a]=Math.min(o[a]+1,i[a-1]+1,o[a-1]+c)}for(let a=0;a<=r;a++)o[a]=i[a]}return o[r]}function QS(n,e){let t=n.map(i=>({spec:i,dist:ZS(e,is(i.productName))})),r=t.reduce((i,s)=>Math.min(i,s.dist),1/0);if(r>2)return;let o=t.filter(i=>i.dist===r);return o.length===1?{spec:o[0].spec,matchedName:o[0].spec.productName,fuzzy:!0,matchType:"fuzzy"}:{matchType:"none",ambiguous:o.map(i=>i.spec.productName)}}function Gc(n,e){if(/[\u4e00-\u9fff\u3400-\u4dbf\u3040-\u30ff\uac00-\ud7af]/.test(e))return{matchType:"none"};let t=is(e);if(t.length===0)return{matchType:"none"};let r=n.find(a=>is(a.productName)===t);if(r)return{spec:r,matchedName:r.productName,matchType:"exact"};let o=XS[t];if(o){let a=n.find(c=>c.productName===o);if(a)return{spec:a,matchedName:a.productName,matchType:"alias"}}let i=n.filter(a=>{let c=is(a.productName);return c.includes(t)||t.includes(c)});if(i.length===1)return{spec:i[0],matchedName:i[0].productName,matchType:"substring"};if(i.length>1)return{matchType:"none",ambiguous:i.map(a=>a.productName)};let s=QS(n,t);return s||{matchType:"none"}}async function rb(n){for(let e of n){let{stdout:t}=await Vc("tasklist",["/FI",`IMAGENAME eq ${e}`,"/FO","CSV","/NH"],{reject:!1});if(t.toLowerCase().includes(e.toLowerCase()))return!0}return!1}async function ob(){try{let n=wc();if(n==="win32")return rb(["devecostudio64.exe","devecostudio.exe"]);if(n==="darwin"){let{stdout:e}=await Vc("pgrep",["-x","DevEco Studio"],{reject:!1});return e.trim().length>0}if(n==="openharmony"||n==="linux"){let{stdout:e}=await Vc("pgrep",["-f","com.huawei.devecostudio"],{reject:!1});return e.trim().length>0}}catch{}return!1}async function ib(n,e){if(!b()){if(await ob()){console.log("DevEco Studio is already running.");return}throw new Error(`DevEco Studio is not running. The previewer requires DevEco Studio to be running.
|
|
43
43
|
Please start DevEco Studio manually, then retry.`)}if(!n||!e)throw new Error("Internal error: hdcAdapter and targetDeviceId are required for IDE detection on HarmonyOS.");if(await n.isDevEcoStudioRunningViaHdc(e)){console.log("DevEco Studio is already running.");return}throw new Error(`DevEco Studio is not running. The previewer requires DevEco Studio to be running.
|
|
44
|
-
Please start DevEco Studio manually, then retry.`)}async function
|
|
44
|
+
Please start DevEco Studio manually, then retry.`)}async function sb(n,e){let t=await e.listDevices();if(t.length===0)return!1;let r=await e.listDevicesWithName();for(let o of n){if(t.some(s=>s.serial===o))return!0;let i=o.toLowerCase();if(r.some(s=>s.name.toLowerCase()===i))return!0}return!1}async function Tp(n,e){if(!n)return!1;let t=n.split(",").map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0||e&&await sb(t,e))return!1;let r=await Wc(),o=r.length>0?r:[So];return t.every(i=>Gc(o,i).spec!==void 0)}function ab(n,e){if(!n)return[e[0]||So];let t=n.split(",").map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0)return[e[0]||So];let r=[],o=[];for(let i of t){let s=Gc(e,i);if(s.spec)r.push(s.spec),s.matchType==="fuzzy"?console.warn(qc(` [fuzzy] "${i}" \u2192 ${s.matchedName}`)):(s.matchType==="alias"||s.matchType==="substring")&&console.log(` [${s.matchType}] "${i}" \u2192 ${s.matchedName}`);else{if(s.ambiguous&&s.ambiguous.length>0)throw new Error(`Ambiguous device name "${i}". Candidates:
|
|
45
45
|
`+s.ambiguous.map(a=>` - ${a}`).join(`
|
|
46
46
|
`)+`
|
|
47
47
|
Please specify a more precise name.`);o.push(i)}}if(o.length>0){let i=e.map(s=>s.productName).join(", ");throw new Error(`Device type(s) not found: ${o.join(", ")}
|
|
48
|
-
Available: ${i}`)}return
|
|
48
|
+
Available: ${i}`)}return cb(r)}function cb(n){let e=new Set,t=[];for(let r of n)e.has(r.productName)||(e.add(r.productName),t.push(r));return t}async function lb(n){if(!process.stdin.isTTY)return;console.log(""),console.log("No device connected. To connect to this HarmonyOS device:"),console.log(' 1. Open "Settings \u2192 System \u2192 Developer options \u2192 Wireless debugging"'),console.log(" 2. Enable it and note the port number shown"),console.log(" 3. Enter the port below (or set DEVECO_HDC_PORT env var)"),console.log("");let e=Rp.createInterface({input:eb,output:tb});try{let t=await e.question("Wireless debugging port: ");if(t.trim()){let r=`127.0.0.1:${t.trim()}`;return await n.connectTarget(r),console.log(hr(`Connected to local device: ${r}`)),r}}catch{}finally{e.close()}}async function db(n,e){if(e){let i=e.includes(":")?e:`127.0.0.1:${e}`;return await n.connectTarget(i),console.log(`Connected to local device: ${i}`),i}let t=process.env.DEVECO_HDC_PORT;if(t){let i=`127.0.0.1:${t}`;try{return await n.connectTarget(i),console.log(`Connected to local device via DEVECO_HDC_PORT: ${i}`),i}catch{console.warn(qc(`DEVECO_HDC_PORT=${t} but connect failed, trying other methods...`))}}let r=await n.listRawTargets();if(r.length>0){let i=r[0];return f(`[preview] Found existing target: ${i}`),i}let o=await lb(n);if(o)return o;throw new Error(`Cannot connect to local HarmonyOS device.
|
|
49
49
|
Please either:
|
|
50
50
|
1. Run with --device 127.0.0.1:<port>, or
|
|
51
51
|
2. Set DEVECO_HDC_PORT env var, or
|
|
52
|
-
3. Open wireless debugging in system settings first.`)}async function
|
|
53
|
-
`))}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
|
|
52
|
+
3. Open wireless debugging in system settings first.`)}async function ub(n,e){let t=await n.listDevices();if(t.length===0)throw new Error(b()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device.");if(!e&&t.length>1){let o=await n.listDevicesWithName();throw new Error("Multiple devices found. Please specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+o.map(i=>` - ${i.name} (${i.serial})`).join(`
|
|
53
|
+
`))}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 pb(n){if(!ss.existsSync(n))throw new Error(`app.json5 not found at ${n}`);let e=ss.readFileSync(n,"utf8"),t=nb.parse(e);return t.app?.multiAppMode?(console.log("[multi-preview] app.json5 already has multiAppMode, skipping injection."),()=>{}):(t.app||(t.app={}),t.app.multiAppMode={multiAppModeType:"appClone",maxCount:5},ss.writeFileSync(n,JSON.stringify(t,null,2),"utf8"),console.log(`[multi-preview] Injected multiAppMode into ${bo.basename(n)}`),()=>{ss.writeFileSync(n,e,"utf8"),console.log(`[multi-preview] Restored original ${bo.basename(n)}`)})}async function fb(n){let{options:e,project:t,toolProvider:r,hdcAdapter:o,moduleName:i,isMulti:s,targetDeviceId:a}=n,c=bo.join(t.rootDir,"AppScope","app.json5"),l=s?pb(c):()=>{},d=s?"[multi-preview]":"[preview]";try{let h=e.product||"default",w=e.buildMode||"debug",v="default";if(s||!e.skipBuild){console.log(s?`
|
|
54
54
|
${d} Building with multiAppMode (appClone) for multi-instance preview...`:`
|
|
55
|
-
${d} Building and installing hap for preview...`);let G=new en(r,t.rootDir),V=new xe(r,t.rootDir),ot=t.collectNonHarDependentModuleList(i).map(
|
|
56
|
-
Launching DevEco Studio previewer on ${n.targetDeviceId}...`),console.log(` bundleName : ${n.bundleName}`),console.log(` abilityName : ${n.mainAbility}`),console.log(` moduleName : ${n.moduleJsonName}`),console.log(` instanceId : ${n.instanceId}`),console.log(` mode : ${n.isMulti?"multi":"single"}`),console.log(` previewers : ${n.targets.map(e=>e.productName).join(", ")}`)}async function
|
|
57
|
-
[${d+1}/${t.length}] Launching ${h.productName} (${h.productType}/${h.subProductType})...`);try{let v=await e.launchPreview(o,i,s,h.productName,h.productType,a,h.subProductType,c,w),I=/start ability successfully/i.test(v);l.push({name:h.productName,success:I,output:v}),I?console.log(
|
|
58
|
-
`+"\u2500".repeat(50));let e=n.filter(r=>r.success).length,t=n.length-e;console.log(`Previewer launch summary: ${
|
|
59
|
-
`))}let
|
|
55
|
+
${d} Building and installing hap for preview...`);let G=new en(r,t.rootDir),V=new xe(r,t.rootDir),ot=t.collectNonHarDependentModuleList(i).map(hc=>`${hc}@${v}`),Eu=yo(t,ot),mc={type:"modules",modulesToBuild:ot,moduleTasks:Eu};await Tt(t.rootDir,async()=>{await wo(G,V,h,w,mc,t.rootDir)},()=>console.log("Another build is already running. Waiting...")),console.log(hr(`${d} Build completed.`))}else console.log(`${d} Skipping build (--skip-build), installing existing hap...`);let I=t.findArtifactPath(i,v,!1,h);console.log(`${d} Installing hap to ${a}...`),await o.installApp(a,[I]),console.log(hr(`${d} Installed hap.`))}finally{l()}}function mb(n){console.log(`
|
|
56
|
+
Launching DevEco Studio previewer on ${n.targetDeviceId}...`),console.log(` bundleName : ${n.bundleName}`),console.log(` abilityName : ${n.mainAbility}`),console.log(` moduleName : ${n.moduleJsonName}`),console.log(` instanceId : ${n.instanceId}`),console.log(` mode : ${n.isMulti?"multi":"single"}`),console.log(` previewers : ${n.targets.map(e=>e.productName).join(", ")}`)}async function hb(n){let{hdcAdapter:e,targets:t,isMulti:r,targetDeviceId:o,bundleName:i,mainAbility:s,moduleJsonName:a,instanceId:c}=n,l=[];for(let d=0;d<t.length;d++){let h=t[d],w=r?d:-1;console.log(`
|
|
57
|
+
[${d+1}/${t.length}] Launching ${h.productName} (${h.productType}/${h.subProductType})...`);try{let v=await e.launchPreview(o,i,s,h.productName,h.productType,a,h.subProductType,c,w),I=/start ability successfully/i.test(v);l.push({name:h.productName,success:I,output:v}),I?console.log(hr(` \u2713 ${h.productName}: ${v.trim()}`)):console.error(as(` \u2717 ${h.productName}: ${v.trim()}`))}catch(v){let I=v.message;l.push({name:h.productName,success:!1,output:I}),console.error(as(` \u2717 ${h.productName}: ${I}`))}}return l}function gb(n){console.log(`
|
|
58
|
+
`+"\u2500".repeat(50));let e=n.filter(r=>r.success).length,t=n.length-e;console.log(`Previewer launch summary: ${hr(String(e))} succeeded, ${t>0?as(String(t)):"0"} failed.`);for(let r of n){let o=r.success?hr("\u2713"):as("\u2717");console.log(` ${o} ${r.name}`)}return t===0}async function kp(n,e,t,r,o,i){let s=await Wc(),a=s.length>0?s:[So],c=ab(n.device,a),l=c.length>1,d;if(b()){let I=(await r.listRawTargets()).find(G=>G.includes("127.0.0.1:"));I?(d=I,console.log(`Using self-connected device: ${d}`)):(console.warn(qc("hdc \u672A\u81EA\u8054\u5230\u672C\u673A\u8BBE\u5907(\u9700\u8981 127.0.0.1:<port>)\u3002\u6B63\u5728\u5C1D\u8BD5\u81EA\u52A8\u8FDE\u63A5...")),d=await db(r,void 0))}else d=await ub(o,void 0);let h={options:n,project:e,toolProvider:t,hdcAdapter:r,moduleName:i,targetDeviceId:d,isMulti:l,targets:c,bundleName:e.getBundleName(),mainAbility:e.getMainAbility(i,n.ability),moduleJsonName:e.getModuleName(i),instanceId:process.pid};await fb(h),await ib(r,d),mb(h);let w=await hb(h);return gb(w)}function zc(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 ds(n,e){let t=await n.ensureWirelessSelfConnection(),r=await n.listDevices();if(r.length===0)throw t.mode?new Error(b()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device."):new Error("No active devices found. To run on the local device, enable wireless debugging: Settings \u2192 System \u2192 Developer options \u2192 Wireless debugging");if(!e&&r.length>1){let i=await n.listDevicesWithName();throw new Error("Multiple devices found. Specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+i.map(s=>` - ${s.name} (${s.serial})`).join(`
|
|
59
|
+
`))}let o=await n.getDeviceInfo(r,e);if(!o)throw new Error("No active devices found.");if(!e){let i=await n.getDeviceName(o.serial);console.log(`Auto-selected device: ${i} (${o.serial})`)}return o.serial}function Yc(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 Error(`Specify module(s) using --module <name> [<name>...].
|
|
60
60
|
Available runnable modules:
|
|
61
61
|
`+t.map(r=>` - ${r.name}`).join(`
|
|
62
|
-
`))}function
|
|
63
|
-
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(
|
|
62
|
+
`))}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 Np(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(`
|
|
63
|
+
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(Eo(`
|
|
64
64
|
Application '${t}': ${s}`))}else console.log(`
|
|
65
|
-
Application '${t}' installed successfully (no ability to launch).`)}var
|
|
66
|
-
`+
|
|
67
|
-
${n} is already up to date (v${e}, tag: ${t})`));return}console.log(
|
|
68
|
-
New version found: ${o} (current: ${e})`)),console.log(
|
|
69
|
-
`+
|
|
70
|
-
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:
|
|
71
|
-
`).trim(),a=
|
|
72
|
-
`:"";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=
|
|
65
|
+
Application '${t}' installed successfully (no ability to launch).`)}var Jc=new yb("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/");b()||Jc.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.");Jc.action(async n=>{try{await Eb(n)}catch(e){console.error(wb(e.message)),process.exit(1)}});async function vb(n,e,t,r,o){let i=new en(e,n.rootDir),s=new xe(e,n.rootDir),a=new Set,c=new Set;for(let{moduleName:w,targetName:v}of t)for(let I of n.collectNonHarDependentModuleList(w))a.add(`${I}@${v}`),c.add(I);let l=[...a],d=yo(n,l),h={type:"modules",modulesToBuild:l,moduleTasks:d};for(let w of c)Qi.generate(n.rootDir,w,r,e);await Tt(n.rootDir,()=>wo(i,s,r,o,h,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion...")),console.log(`
|
|
66
|
+
`+Eo("Build completed successfully."))}async function Sb(n,e,t,r,o){let i=new Nt(t),s=re.from(t),a=r[0]?.moduleName||o[0];await kp(n,e,t,i,s,a)}function bb(n,e){for(let{moduleName:t}of e){let r=n.getModuleType(t);if(r!=="entry"&&r!=="feature"&&r!=="shared")throw new Error(`Module '${t}' '${r}' is not runnable. Specify an entry or feature module.`)}}async function Eb(n){let e=z.discover(process.cwd());console.warn(cs("Ensure the project source is trusted before proceeding."));let t=await A.new();if(n.skipBuild||t.assertJava(),n.hotreloadApply){await Cb(n,e,t);return}if(n.hotreload){await Pb(n,e,t);return}if(n.apply){await Ab(n,e,t);return}await Lp(n,e,t)}async function Pb(n,e,t){if(n.hotreload==="stop"){await Dp(t,e);return}let o=Yc(e,n.module).map(zc),{moduleName:i,targetName:s}=o[0];Bc(n.module,i);let a=new Nt(t),c=re.from(t),l=await ds(c,n.device),d=l.includes("127.0.0.1")||l.includes("localhost"),h=n.product||"default";e.validateProduct(h);let w=e.getBundleName(),v=xp(e,o,n.ability);es.generate(e.rootDir,i,h,t);let I=new xe(t,e.rootDir);console.log(Eo("Ensuring hvigor daemon is running (via --sync --daemon, no hap build)...")),await I.ensureDaemonRunning();let G=[`${i}@${h}`];for(let ot of e.collectNonHarDependentModuleList(i))G.includes(`${ot}@${h}`)||G.push(`${ot}@${h}`);console.log(Eo("Building hap + starting watch session (socket -> CommonBuild assembleHap --hot-reload-build --watch, kept open)..."));let V=new mr(e.rootDir,t);await V.startWatchSession({moduleSpecs:G,productName:h});let rt=Ap(e,i,s,d,h);await Np(a,l,w,rt,v,!!n.uninstall),console.log(Eo("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.")),V.onSocketDisconnect(()=>{console.log("Daemon disconnected (likely via --hotreload stop). Exiting watch session."),process.exit(0)}),await new Promise(()=>{})}async function Cb(n,e,t){let r=n.hotreloadApply;if(!r)throw new Error("hotreload-apply requires --hotreload-apply <fileName> (under .hvigor/)");let o=Yc(e,n.module),{moduleName:i}=zc(o[0]);Bc(n.module,i);let s=re.from(t),a=await ds(s,n.device),c=n.product||"default";e.validateProduct(c);let l=e.getBundleName();Ip(e,i,r);let d=[`${i}@${c}`],h=await Cp({applyFileName:r,projectPath:e.rootDir,moduleName:i,productName:c,bundleName:l,toolProvider:t,targetDeviceId:a,moduleSpecs:d});if(!h.success)throw new Error(h.message)}function Ib(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 Lp(n,e,t){let r=Yc(e,n.module),o=r.map(zc),i=re.from(t);if(await Tp(n.device,i)){await Sb(n,e,t,o,r);return}bb(e,o);let s=new Nt(t),a=await ds(i,n.device),c=a.includes("127.0.0.1")||a.includes("localhost"),l=n.product||"default";e.validateProduct(l);let d=n.buildMode||"debug";n.skipBuild||await vb(e,t,o,l,d);let h=Ib(e,o,c,l),w=e.getBundleName(),v=xp(e,o,n.ability);await Np(s,a,w,h,v,!!n.uninstall)}async function Ab(n,e,t){let r=n.apply;if(!r)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(ls.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let o=ls.join(e.rootDir,".hvigor",r),i=re.from(t),s=await ds(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",h=new Zi(t,e.rootDir);try{await h.execute({applyFile:o,productName:a,targetDeviceId:s,bundleName:c,abilityName:d}),console.log(cs("[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(cs(`[Apply] \u5931\u8D25\uFF1A${w.message}`)),console.warn(cs("[Apply] \u81EA\u52A8\u56DE\u9000\u5230\u5168\u91CF devecocli run..."))}await Lp(n,e,t)}var Op=Jc;import{Command as Db}from"commander";import{green as Mp,red as _p,cyan as Kc}from"colorette";import{execa as Fp}from"execa";function Rb(){return"beta"}function Tb(){return"@deveco-test/hmos-deveco-cli"}function kb(){return"0.4.0-TD.3"}var xb=new Db("update").description("Update deveco-cli to latest").action(async()=>{let n=Tb(),e=kb(),t=Rb();console.log(Kc("Checking for updates..."));try{let{stdout:r}=await Fp("npm",["view",n,`dist-tags.${t}`]),o=r.trim();if(!o||o===e){console.log(Mp(`
|
|
67
|
+
${n} is already up to date (v${e}, tag: ${t})`));return}console.log(Kc(`
|
|
68
|
+
New version found: ${o} (current: ${e})`)),console.log(Kc(`Updating ${n}...`)),await Fp("npm",["install","-g",`${n}@${t}`],{stdio:"inherit"}),console.log(`
|
|
69
|
+
`+Mp(`${n} updated successfully to version ${o}.`))}catch(r){let o=r;console.error(_p(`Failed to update ${n}`)),o.message&&console.error(_p(o.message)),process.exit(1)}}),jp=xb;import{Command as aE}from"commander";import{execa as ps}from"execa";function be(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as Nb}from"child_process";var Lb=2500;function Ob(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 Mb(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,Lb);n.once("error",d=>c(d.message)),Ob(n,l,s,a,c,i)}function Hp(n,e,t){return f(`Spawning emulator: ${n} ${t.join(" ")}`),new Promise((r,o)=>{let i=[],s=Nb(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)),Mb(s,i,r,o)})}import*as gr from"path";function _b(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 Fb(n){let e=n.instancePath?.trim();if(e)return gr.dirname(gr.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?gr.dirname(gr.normalize(t)).replace(/\\/g,"/"):""}function jb(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function $p(n,e){return e?[...n,"-bootmode",e]:n}function Hb(n,e,t){let r=[$p(["-start",n],t)],o=Fb(e);if(o)for(let i of jb(e.imageRoot))r.push($p(["-hvd",n,"-path",o,...i],t));return _b(r)}async function Up(n,e,t,r){let o=new Error("No start strategy ran"),i=Hb(n,e,r);for(let s of i)try{return await t(s),{ok:!0}}catch(a){o=a}return{ok:!1,lastError:o}}async function Xc(n){return(await re.withHdcPath(n).listDevices()).map(t=>t.serial).filter($n)}async function Zc(n){let e=await Xc(n);return e.length===0?[]:(await Promise.all(e.map(r=>Xi(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function Bp(n,e){return(await Zc(n)).includes(e)}import*as wr from"path";import{existsSync as $b,statSync as Ub}from"fs";function yr(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function Bb(n){let e=yr(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 Wb(n){return yr(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function Gb(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=wr.dirname(wr.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let o=wr.join(t,r.name);$b(o)&&Ub(o).isDirectory()&&(r.instancePath=o.replace(/\\/g,"/"))}}function Vb(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=Wb(t),o=yr(t,["deviceType","DeviceType","devicetype"]),i=yr(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:Bb(t),path:yr(t,["path","Path","hvdPath","hvd_path"]),imageRoot:yr(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 qb(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 Wp(n){let t=Vb(n)??qb(n);return Gb(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 zb(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function Yb(n){if(!zb(n))return null;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 us(n){let e=n.trim();if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let r=[];for(let o of t){if(!o||typeof o!="object")continue;let i=Yb(o);i&&r.push(i)}return r}catch{return[]}}function Gp(n){let t=us(n).map(r=>r.osVersion).filter(Boolean);return[...new Set(t)]}var Vp=/no images are available/i,Jb="7.0.0",Kb={foldable:["open","half-open","close"],"2in1_foldable":["open","vertical-open","half-open","close"],triplefold:["single","double","triple","left-folded-right-half-folded","left-half-folded-right-expanded","left-expanded-right-folded","left-half-folded-right-folded","left-expanded-right-half-folded","left-half-folded-right-half-folded"]};function lt(n){return n.normalize("NFKC").trim().toLowerCase()}function Xb(n,e){let t=n.deviceType?.trim(),r=t?Kb[lt(t)]:void 0;if(!r)throw new Error(`Fold-state control is not supported for emulator "${n.name}" (device type: ${t||"unknown"}).`);if(!r.includes(e))throw new Error(`Fold state "${e}" is not supported by emulator "${n.name}" (device type: ${t}). Available states: ${r.join(", ")}.`)}function Zb(n){let e=n.message||"";return Vp.test(e)}function Qb(n){return n.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function Po(n,e){return`${n} ${e.join(" ")}`.trim()}function eE(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 vr=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 f(`Executing: ${Po(this.emulatorPath,e)}`),ps(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return Hp(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return Wp(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 Error(`Emulator "${e}" not found.`);let i=o.name;if(await this.isAlreadyRunning(i,o))return"already-running";await this.assertSystemImageAvailable(o);let s=await Up(i,o,a=>this.executeEmulatorDetached(a),"snapshot");if(s.ok)return"started";if(await this.isAlreadyRunning(i))return"already-running";throw new Error(`Unable to start emulator "${e}". All methods failed.
|
|
70
|
+
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:Bp(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 Error(`Emulator "${e}" 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 Error(`Emulator "${e}" not found.`);if(!await this.isAlreadyRunning(o.name,o))throw new Error(`Emulator "${e}" is not running.`);t.type==="folded-state"&&Xb(o,t.state);let i=this.buildControlArgs(o.name,t);f(`[EmulatorManager] control ${eE(t)} -> ${Po(this.emulatorPath,i)}`),await this.runEmulatorChecked(i,{printOutputOnSuccess:!1})}async assertControlCommandSupported(){let e=this.emulatorPath;if(n.supportedControlPaths.has(e))return;let t=["-version"];f(`Executing: ${Po(this.emulatorPath,t)}`);let{stdout:r,stderr:o,exitCode:i}=await ps(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(`
|
|
71
|
+
`).trim(),a=Qb(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(A.compareVersion(a,Jb)<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],{type:o}=t;switch(o){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(`Unsupported emulator control action type: ${o}`)}}async executeEmulatorInherit(e){f(`Executing: ${Po(this.emulatorPath,e)}`);let{exitCode:t}=await ps(this.emulatorPath,e,{stdio:"inherit",env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1});if(t!==0)throw new Error(`Emulator exited with code ${t===null?"null":t}.`)}async installEmulatorImage(e){let t=["-install","-deviceType",e.deviceType,"-osVersion",e.osVersion];e.force&&t.push("-force"),await this.executeEmulatorInherit(t)}async uninstallEmulatorImage(e){let t=await this.resolveSoftwareVersionsForUninstall(e);if(t.length===0)throw new Error(`No downloaded image matches --os-version "${e.osVersion}" for --device-type "${e.deviceType}".`);let r;try{await this.runUninstallImageChecked(e.deviceType,e.osVersion)}catch(i){if(!Zb(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 Gp(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}
|
|
72
|
+
`:"";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=us(t),o=lt(e.deviceType),i=lt(e.osVersion);return r.filter(s=>lt(s.deviceType)===o&&(lt(s.osVersion)===i||lt(s.softwareVersion)===i))}async hasDownloadedSystemImage(e,t){let r=await this.listEmulatorImages({downloaded:!0}),o=us(r),i=lt(t),s=e?.trim()?lt(e):void 0;return o.some(a=>lt(a.osVersion)===i||lt(a.softwareVersion)===i?s===void 0?!0:lt(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:[Vp]})}async runEmulatorChecked(e,t){f(`Executing: ${Po(this.emulatorPath,e)}`);let{stdout:r,stderr:o,exitCode:i}=await ps(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(`
|
|
73
73
|
`).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 Error(`Emulator "${e}" already exists. Use \`--force\` to overwrite.`);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(`
|
|
74
74
|
`)}),!await this.waitForEmulatorPresenceByList(t))throw new Error(`Emulator "${e.name}" was reported as created, but it did not appear in the emulator list within the waiting period. Open the device manager list in DevEco Studio, then run this command again.`)}async waitForEmulatorPresenceByList(e,t=1e4,r=500){let 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 Error(`Emulator "${e}" not found.`);let i=o.name;if(o.isRunning===!0||await this.isAlreadyRunning(i,o))throw new Error(`Failed to delete device: ${i}
|
|
75
|
-
The device may be running.`);return await this.runEmulatorChecked(["-delete",i,"-force"],{printOutputOnSuccess:!1}),i}};import{red as
|
|
76
|
-
`)}function
|
|
75
|
+
The device may be running.`);return await this.runEmulatorChecked(["-delete",i,"-force"],{printOutputOnSuccess:!1}),i}};import{red as nl,yellow as Yp,gray as rl}from"colorette";import cE from"ora";import{red as tE}from"colorette";function fs(n,e){n?n.fail(e):console.error(tE(e)),process.exit(1)}import{green as nE}from"colorette";var rE=[[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]],oE=[[0,31],[127,159],[768,879],[6832,6911],[7616,7679],[8203,8207],[8400,8447],[65024,65039],[65056,65071],[8205,8205]],iE=new RegExp("\x1B\\[([0-9;]*)[a-zA-Z]","g");function qp(n,e){for(let[t,r]of e)if(n>=t&&n<=r)return!0;return!1}function el(n){let e=n.replace(iE,""),t=0,r=0;for(;r<e.length;){let o=e.codePointAt(r);if(o===void 0)break;qp(o,oE)||(qp(o,rE)?t+=2:t+=1),r+=o>65535?2:1}return t}function zp(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 Ot(n,e){let t=sE(n,e),r=[];r.push(n.map((o,i)=>zp(o,t[i])).join(" ")),r.push(t.map(o=>"-".repeat(o)).join(" "));for(let o of e){let i=o.cells.map((s,a)=>zp(s??"",t[a])).join(" ").trimEnd();r.push(o.highlight?nE(i):i)}return r.join(`
|
|
76
|
+
`)}function lE(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 uE(n){return{cells:[n.name??n.serial,n.serial,n.isEmulator?"emulator":"device",n.deviceType??"-"],highlight:!0}}function pE(n,e){return n.isEmulator!==e.isEmulator?n.isEmulator?1:-1:(n.name??n.serial).localeCompare(e.name??e.serial)}function fE(){console.log(Yp(" No active devices.")),console.log(rl(b()?" Connect a USB device with debugging enabled.":" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function tl(n,e){n||console.log(rl(` To ${e==="list"?"list local devices":"view local device details"}, enable wireless debugging: Settings \u2192 System \u2192 Developer options \u2192 Wireless debugging`))}function mE(n){let t=[...n].sort(pE).map(uE);console.log(Ot(dE,t))}async function hE(n,e){if(b()||!n.some(o=>o.isEmulator)||!e.emulatorPath)return;let r=await vr.from(e).getDeviceTypeByName();lE(n,r)}async function gE(n,e,t){try{let r=await n.ensureWirelessSelfConnection(),o=await n.getConnectedEntries();await hE(o,e),t?.stop(),o.length===0?fE():mE(o),tl(r.mode,"list")}catch(r){fs(t,`Failed to list devices: ${r.message}`)}}async function yE(n,e){let t=await n.listDevices();if(!(t.length<2)){console.error(nl("Multiple devices connected. Specify a device with:"));for(let r of t){let o=await n.getDeviceName(r.serial);console.error(rl(` ${e} -t ${r.serial} # ${o}`))}process.exit(1)}}async function wE(n,e){try{let t=await n.ensureWirelessSelfConnection();e||await yE(n,"devecocli device view");let r=await n.listDevices(),o=await n.getDeviceInfo(r,e);o||(console.log(Yp("No connected device found.")),tl(t.mode,"view"),process.exit(1));let i=await n.getDeviceDetail(o.serial),s=await n.getDeviceName(o.serial);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}`),tl(t.mode,"view")}catch(t){console.error(nl(`Failed to show device details: ${t.message}`)),process.exit(1)}}async function Jp(){try{let n=await A.new();return{manager:re.from(n),toolProvider:n}}catch(n){console.error(nl(`Failed to initialize device manager: ${n.message}`)),process.exit(1);return}}var ol=new aE("device").description("Manage connected devices");ol.command("list").description("List all connected devices").action(async()=>{let{manager:n,toolProvider:e}=await Jp(),t=cE({text:"Querying connected devices\u2026",color:"cyan"}).start();await gE(n,e,t)});ol.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").action(async n=>{let{manager:e}=await Jp();await wE(e,n.target)});var Kp=ol;import{Argument as ul,Command as pl,Option as Do}from"commander";import{green as Ro,cyan as br,red as Ce,yellow as bt,gray as Ao}from"colorette";import OE from"ora";import vE from"readline/promises";import{execa as Zp}from"execa";import*as rn from"fs/promises";import*as sl from"os";import*as Gn from"path";var il=`1/4:\r
|
|
77
77
|
---------------------------------------\r
|
|
78
78
|
Statement About HarmonyOS and Privacy\r
|
|
79
79
|
\r
|
|
@@ -1243,13 +1243,13 @@ Part I: Chinese mainland.\r
|
|
|
1243
1243
|
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
|
|
1244
1244
|
\r
|
|
1245
1245
|
Part III: Other countries and regions.\r
|
|
1246
|
-
---------------------------------------\r`;var
|
|
1247
|
-
`),
|
|
1248
|
-
`)}function
|
|
1249
|
-
${t}.`);return
|
|
1250
|
-
`,"utf8"),!0}catch{}return!1}async function
|
|
1246
|
+
---------------------------------------\r`;var SE=new Set,ms=new Map,al="HarmonyOS_Software_Service_Agreement",Qp=["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(`
|
|
1247
|
+
`),ef=Qp,cl="HarmonyOS_SDK_Agreement";function tf(n,e){return`${n}\0${e}`}function nf(){SE.clear(),ms.clear()}var bE=Qp,Xe=class extends Error{constructor(e=bE){super(e),this.name="EmulatorLicenseBlockedError"}};function rf(n,e){return[n??"",e??""].join(`
|
|
1248
|
+
`)}function of(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 EE(n){return`Emulator${n.trim()}`}function sf(n){let e=EE(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 Gn.join(r,"Huawei",e,".emu_config")}if(process.platform==="darwin")return Gn.join(sl.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||Gn.join(sl.homedir(),".cache");return Gn.join(t,"Huawei",e,".emu_config")}async function PE(n,e,t){let r=tf(n,e),o=ms.get(r);if(o!==void 0)return o;let i=await Zp(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=rf(i.stdout,i.stderr).trim();if(i.exitCode!==0||!s)throw new Xe(t);return ms.set(r,s),s}function CE(n){let e=n[0],t=n[n.length-1];return(e==='"'||e==="'")&&e===t?n.slice(1,-1):n}function IE(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 AE(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=CE(e.slice(r+1).trim());return{key:o,entry:{value:i,delimiter:t}}}}function DE(n){let e={};for(let t of n.split(/\r?\n/)){let r=AE(t);r&&(e[r.key]=r.entry)}return e}function RE(n){let e=n.trim();if(!e)return{};let t=IE(e);return t||DE(n)}function TE(n){return typeof n!="string"?!1:n.normalize("NFKC").trim().toLowerCase()==="agree"}async function af(n,e,t,r){let o=await PE(n,e,r),i=of(o);if(!i)throw new Xe(r);let s=sf(i),a;try{a=await rn.readFile(s,"utf8")}catch(d){throw d.code==="ENOENT"?new Xe(r):d}let l=RE(a)[t];if(!l)throw new Xe(r);if(l.delimiter==="=")throw new Xe(r);if(!TE(l.value))throw new Xe(r)}async function ll(n,e){await af(n,e,al,ef)}async function dl(n,e){await af(n,e,cl,ef)}async function kE(n,e){let t=await Zp(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),r=rf(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=tf(n,e);return ms.set(o,r),r}async function cf(n,e){let t=await kE(n,e),r=of(t);if(!r)throw new Error(`Cannot parse Emulator major.minor from:
|
|
1249
|
+
${t}.`);return sf(r)}function Xp(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function xE(n,e,t){if(!t.startsWith("{"))return!1;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return r[al]="agree",r[cl]="agree",await rn.writeFile(n,`${JSON.stringify(r,null,2)}
|
|
1250
|
+
`,"utf8"),!0}catch{}return!1}async function NE(n,e){let t=al,r=cl,o=[{k:t,re:new RegExp(`^\\s*${Xp(t)}\\s*[:=]`)},{k:r,re:new RegExp(`^\\s*${Xp(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:h}of o)if(h.test(c)){s.push(`${d}:agree`),a.add(d),l=!0;break}l||s.push(c)}a.has(t)||s.push(`${t}:agree`),a.has(r)||s.push(`${r}:agree`),await rn.writeFile(n,s.join(`
|
|
1251
1251
|
`)+(s.length>0?`
|
|
1252
|
-
`:""),"utf8")}async function
|
|
1252
|
+
`:""),"utf8")}async function lf(n){await rn.mkdir(Gn.dirname(n),{recursive:!0});let e="";try{e=await rn.readFile(n,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}let t=e.trim();await xE(n,e,t)||await NE(n,e)}async function df(n,e){return console.log(il),0}var LE="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function uf(n,e){try{return await ll(n,e),await dl(n,e),!0}catch(t){if(t instanceof Xe)return!1;throw t}}async function pf(n,e){if(await uf(n,e))return console.log("Emulator license agreements are already accepted."),0;if(console.log(il),!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=vE.createInterface({input:process.stdin,output:process.stdout}),o;try{o=await r.question(LE)}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 cf(n,e);await lf(s),nf()}catch(s){return console.error(s.message),1}return console.log("Emulator license agreements accepted."),0}async function ff(n,e){if(await uf(n,e))return console.log("Emulator license agreements are already accepted."),0;try{let t=await cf(n,e);await lf(t),nf()}catch(t){return console.error(t.message),1}return console.log("Emulator license agreements accepted."),0}var ME=["ohos.qemu.hvd.name","const.product.name","const.product.model"],mf=["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"],_E=`
|
|
1253
1253
|
Folded state scene mappings:
|
|
1254
1254
|
foldableFold (3):
|
|
1255
1255
|
open Fully expanded state
|
|
@@ -1272,43 +1272,43 @@ Folded state scene mappings:
|
|
|
1272
1272
|
left-half-folded-right-folded
|
|
1273
1273
|
left-expanded-right-half-folded
|
|
1274
1274
|
left-half-folded-right-half-folded
|
|
1275
|
-
`;function OE(n){let e=n.trim();if(!e)throw new Error("--target must not be empty.");return e}function ME(n){let e=n.trim();if(!pf.includes(e))throw new Error(`Invalid fold state "${n}". Available values: ${pf.join(", ")}`);return e}function mf(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 hf(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&&!_E(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 _E(n,e){let t=n.split(".")[1];return t===void 0||t.length<=e}function FE(n,e,t,r,o){return Number(hf(n,e,t,r,o))}function jE(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 HE(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 $E(n,e){let t=o=>o.normalize("NFKC").trim(),r=t(n);if(e.length===0)throw console.error(bt("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(bt("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(Ce("--os-version does not match any downloaded image (exact string required).")),console.log(bt("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 UE=["Name","Status","Serial","Device Type","OS Version"];function BE(n,e,t){return{cells:[n.name,t?"running":"stopped",e??"-",n.deviceType??"-",n.osVersion??"-"],highlight:t}}async function WE(n,e){let t=await Promise.all(e.map(async r=>{let o=await lr(n,r,NE);return[r,o]}));return new Map(t)}async function GE(n){let e=await Kc(n),t=await WE(n,e);return{serials:e,params:t}}function VE(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 qE(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&&VE(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 zE(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(o=>BE(o.emu,o.serial,o.effectiveRunning))}async function YE(n,e,t){try{let[r,o]=await Promise.all([n.listEmulators(),GE(e)]);if(r.length===0){t?.stop(),console.log(bt(" No emulator instances found."));return}let i=r.filter(l=>l.isRunning).map(l=>l.name),{productSerialMap:s,hvdSerialMap:a}=qE(o.serials,o.params,i);t?.stop();let c=zE(r,s,a);console.log(Ot(UE,c))}catch(r){ps(t,`Failed to list emulators: ${r.message}`)}}function gf(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(Ce(`Failed to ${t} emulator "${e[o]}": ${s.message}`)),s.stdout&&console.error(Io(s.stdout)),s.stderr&&console.error(Io(s.stderr))}return r}var JE=2e3,KE=6e4;async function XE(n,e){let t=be(e);return(await Xc(n)).some(o=>be(o)===t)}async function yf(n,e,t,r=KE,o=JE){let i=Date.now()+r;for(;Date.now()<i;){if(await XE(n,e)===t)return!0;await new Promise(a=>setTimeout(a,o))}return!1}async function ZE(n,e,t){if(await n.startEmulator(t)==="already-running"){console.log(bt(`Emulator "${t}" is already running.`));return}console.log(Sr(`Starting emulator "${t}"...`));let o=await yf(e,t,!0);console.log(o?Do(`Emulator "${t}" started successfully.`):bt(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function QE(n,e,t){let r=await Promise.allSettled(t.map(i=>ZE(n,e,i)));gf(r,t,"start")&&process.exit(1)}async function wf(n,e){let t=e.trim();if(!Hn(t))return t;let r=await re.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 eP(n,e,t){let r=await wf(e,t);if(console.log(Sr(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(bt(`Emulator "${r}" is already stopped.`));return}let i=await yf(e,r,!1);console.log(i?Do(`Emulator "${r}" stopped successfully.`):bt(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function tP(n,e,t){let r=await Promise.allSettled(t.map(i=>eP(n,e,i)));gf(r,t,"stop")&&process.exit(1)}async function Ze(){try{let n=await A.new();return{manager:wr.from(n),toolProvider:n}}catch(n){console.error(Ce(`Failed to initialize emulator: ${n.message}`)),process.exit(1);return}}async function Mt(n,e){try{let t=OE(n.target),r=e(),{manager:o,toolProvider:i}=await Ze(),s=await wf(i.hdcPath,t);await o.controlEmulator(s,r),console.log(Do(`Emulator "${t}" operation completed.`))}catch(t){let r=n.target?.trim()||"<unknown>";console.error(Ce(`Failed to operate emulator "${r}": ${t.message}`)),process.exit(1)}}function nP(n){let e=[];return ms(e,"longitude",n.longitude,-180,180,8),ms(e,"latitude",n.latitude,-90,90,8),ms(e,"altitude",n.altitude,-1e4,1e4,2),ms(e,"bearing",n.direction,0,359.99,2,"--direction"),dl(e,"Specify one geolocation option.")}function rP(n){let e=[];return Po(e,"light",n.lightIntensity,0,1e5,!1,"--light-intensity"),Po(e,"humidity",n.humidity,0,100,!1),Po(e,"temperature",n.temperature,-273.1,100,!1),Po(e,"steps",n.steps,0,1e4,!0),Po(e,"heartrate",n.heartrate,0,255,!0),dl(e,"Specify one sensor option.")}function dl(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 ms(n,e,t,r,o,i,s=`--${e}`){t!==void 0&&n.push({type:"gps",key:e,value:hf(s,t,r,o,i)})}function Po(n,e,t,r,o,i,s=`--${e}`){if(t===void 0)return;let a=i?mf(s,t,r,o):FE(s,t,r,o,1);n.push({type:"sensor",key:e,value:a})}function oP(n){let e=[];return n.level!==void 0&&e.push({type:"battery",level:mf("--level",n.level,1,100)}),n.status!==void 0&&e.push({type:"battery-status",status:n.status==="charging"?1:0}),dl(e,"Specify --level or --status.")}var he=new ll("emulator").description("Manage emulator instances"),iP=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function hs(n){let e=new Ao("--device-type <type>","Emulator device type").choices([...iP]);return n?e.makeOptionMandatory():e}function vr(n,e){for(let t of e)if(t in n)return n[t]}function Co(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function ff(n){let e=Co(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var sP=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],aP="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function vf(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function Sf(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let o=r,i=Co(vr(o,["osVersion","OsVersion","OSVersion","os_version"])),s=Co(vr(o,["deviceType","DeviceType","device_type"])),a=ff(vr(o,["downloaded","Downloaded","isDownloaded"])),c=Co(vr(o,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=Co(vr(o,["releaseType","ReleaseType","release_type"])),d=ff(vr(o,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[i,s,c,l,d,a],highlight:e&&a==="true"})}return t}function cP(n){let e=n.trim();if(!e)return!0;let t=vf(e);return t===null?!1:t.length===0?!0:Sf(t,!0).length===0}function lP(n,e){let t=n.trim();if(!t)return"";let r=vf(t);if(!r)return n.trimEnd();let o=Sf(r,e);return Ot(sP,o)}var gs=new ll("image").description("HarmonyOS emulator system images (download, list, remove)");gs.command("download").description("Download system image").addOption(hs(!1)).option("--os-version <version>","Example: HarmonyOS 5.1.1(19) or HarmonyOS 6.0.1(21) (required)").option("--force","Overwrite an existing image").action(async n=>{let{manager:e,toolProvider:t}=await Ze();try{await al(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof Xe&&(console.error(Ce(r.message)),process.exit(1)),r}n.deviceType?.trim()||(console.error(Ce("Error: missing required option '--device-type <type>'")),process.exit(1)),n.osVersion?.trim()||(console.error(Ce("Error: misssing required option '--os-version <version>'")),process.exit(1));try{await e.installEmulatorImage({deviceType:n.deviceType.trim(),osVersion:n.osVersion.trim(),force:n.force===!0})}catch(r){console.error(Ce(`Failed to download system image: ${r.message}`)),process.exit(1)}});gs.command("remove").description("Remove a downloaded system image").addOption(hs(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let{manager:e}=await Ze();try{await e.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})}catch(t){console.error(Ce(`Failed to remove system image: ${t.message}`)),process.exit(1)}});gs.command("list").description("List system images").addOption(hs(!1)).option("--all","List all images (local and remote)").addOption(new Ao("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let{manager:e}=await Ze();try{let t;n.all?t=void 0:t=!0;let r=await e.listEmulatorImages({deviceType:n.deviceType,downloaded:t});if(cP(r)){console.log(bt(aP));return}if(n.format==="json"){console.log(r.trimEnd());return}let o=lP(r,n.all===!0);console.log(o)}catch(t){console.error(Ce(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});he.addCommand(gs);var ys=new ll("license").description("Review and accept emulator license agreements interactively (prints full text + y/N prompt)");ys.command("view").description("Review agreement text (read-only, no changes)").action(async()=>{let{toolProvider:n}=await Ze(),e=await cf(n.emulatorPath,n.sdkPath);process.exit(e)});ys.command("accept").description("Accept all emulator license agreements non-interactively (skips review and prompt)").action(async()=>{let{toolProvider:n}=await Ze(),e=await uf(n.emulatorPath,n.sdkPath);process.exit(e)});ys.action(async()=>{let{toolProvider:n}=await Ze(),e=await df(n.emulatorPath,n.sdkPath);process.exit(e)});he.addCommand(ys);he.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Mt(n,()=>({type:"shake"})));he.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Mt(n,()=>({type:"power"})));he.command("rotate").description("Rotate emulator").addOption(new Ao("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new cl("<direction>").choices(["left","right"])).action((n,e)=>Mt(e,()=>({type:"rotation",direction:n})));he.command("volume").description("Change volume").addOption(new Ao("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new cl("<direction>").choices(["up","down"])).action((n,e)=>Mt(e,()=>({type:"volume",direction:n})));he.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",LE).action((n,e)=>Mt(e,()=>({type:"folded-state",state:ME(n)})));he.command("battery").description("Set battery level or charging status").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--level <1-100>","Battery level, SOC (integer 1-100)").addOption(new Ao("--status <status>","Charging status").choices(["charging","discharging"])).action(n=>Mt(n,()=>oP(n)));he.command("geolocation").description("Inject geographic coordinates and direction").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--longitude <value>","Longitude (-180.0 to 180.0)").option("--latitude <value>","Latitude (-90.0 to 90.0)").option("--altitude <value>","Altitude (-10000.0 to 10000.0)").option("--direction <value>","Heading direction in degrees (0.00 to 359.99)").action(n=>Mt(n,()=>nP(n)));he.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new cl("<type>","Motion simulation scene").choices(["outdoorRunning","outdoorCycling","drivingNavigation"])).action((n,e)=>{let t={outdoorRunning:{type:"outdoor-running"},outdoorCycling:{type:"outdoor-cycling"},drivingNavigation:{type:"driving-navigation"}};return Mt(e,()=>t[n])});he.command("sensor").description("Inject sensor data").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--light-intensity <value>","Light sensor (0 to 100000)").option("--humidity <value>","Humidity sensor (0 to 100)").option("--temperature <value>","Temperature sensor (-273.1 to 100)").option("--steps <value>","Steps sensor (integer 0 to 10000)").option("--heartrate <value>","Heart rate sensor (integer 0 to 255)").action(n=>Mt(n,()=>rP(n)));he.command("list").description("List all emulator instances").action(async()=>{let{manager:n,toolProvider:e}=await Ze(),t=xE({text:"Listing emulators\u2026",color:"cyan"}).start();await YE(n,e.hdcPath,t)});he.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let{manager:e,toolProvider:t}=await Ze();try{await sl(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof Xe&&(console.error(Ce(r.message)),process.exit(1)),r}n?.length||(console.error(Ce("Error: missing required argument 'names'")),process.exit(1)),await QE(e,t.hdcPath,n)});he.command("stop <names...>").description("Stop one or more emulator instances (by name or serial,e.g.,127.0.0.1:<port>)").action(async n=>{let{manager:e,toolProvider:t}=await Ze();n?.length||(console.error(Ce("Error: missing required argument 'names'")),process.exit(1)),await tP(e,t.hdcPath,n)});var bf=he.command("create <name>").description("Create a local emulator by running emulator -create <name> \u2026. --os-version must match a downloaded image from `emulator image list`.").addOption(hs(!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");bf.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
|
|
1276
|
-
${bt("Tip: ")}${
|
|
1277
|
-
${
|
|
1278
|
-
${
|
|
1279
|
-
`)}});bf.action(async(n,e)=>{try{jE(n),HE(e.osVersion);let{manager:t}=await Ze(),r=await t.listDownloadedImageOsVersions();$E(e.osVersion,r),console.log(Sr(`Creating emulator "${n}"...`)),await t.createVirtualDevice({name:n,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(Do(`Emulator "${n}" created successfully.`))}catch(t){console.error(Ce(`${t.message}`)),process.exit(1)}});he.command("delete <name>").description("Delete a local emulator instance").action(async n=>{let{manager:e}=await Ze();console.log(Sr(`Deleting emulator "${n}"...`));try{let t=await e.deleteVirtualDevice(n);console.log(Do(`Emulator "${t}" deleted successfully.`))}catch(t){let r=t;console.error(Ce(r.message)),r.stdout&&console.error(Io(r.stdout)),r.stderr&&console.error(Io(r.stderr)),process.exit(1)}});var Ef=he;import{Command as TP}from"commander";import{red as gl,cyan as Ht}from"colorette";import*as Wf from"readline";import*as Uf from"crypto";import*as Pf from"http";import*as Cf from"crypto";import{URL as dP}from"url";var ws=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=Pf.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 dP(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&&Cf.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 Le from"fs";import*as on from"path";import{homedir as yP}from"os";var _t={};lv(_t,{LocalCrypto:()=>_t,decryptForLocalStorage:()=>mP,decryptForLocalStorageFromDirectory:()=>hP,encryptForLocalStorage:()=>fP,isEncryptedBlob:()=>gP});import*as K from"fs";import*as Ae from"path";import*as Ne from"crypto";import*as Af from"os";import{homedir as Df}from"os";var Ie=class extends Error{constructor(e){super(e),this.name="DefinedError"}};var Ro=Ln.ALGORITHM,Rf=Ln.IV_LENGTH,To=Ln.KEY_LENGTH,ko=Ln.KEY_LENGTH,Gn=Ln.KEK_VERSIONS,vs=process.env.DEVECO_CLI_DATA_DIR||Ae.join(Df(),Se.CONFIG_DIR_NAME,Se.APP_NAME),Ss=Ae.join(Df(),".local","share",Se.APP_NAME,"keys"),br=Ae.join(vs,Se.KEY_FILE_NAME);function If(n){return Af.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 ul(n){return Ae.join(Ss,`${n}.bin`)}function Tf(){if(!K.existsSync(vs))try{K.mkdirSync(vs,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new Ie(If(vs)):n}if(!K.existsSync(Ss))try{K.mkdirSync(Ss,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new Ie(If(Ae.dirname(Ss))):n}}function kf(){Tf();for(let n of Gn){let e=ul(n);K.existsSync(e)||K.writeFileSync(e,Ne.randomBytes(To),{mode:384})}}function xf(n){if(!Gn.includes(n))throw new Error(`Invalid kekId: ${n}`);kf();let e=ul(n),t=K.readFileSync(e);if(t.length===To)return t;let r=Ne.randomBytes(To);return K.writeFileSync(e,r,{mode:384}),r}function pl(n,e){let t=Ne.randomBytes(Rf),r=xf(e),o=Ne.createCipheriv(Ro,r,t),i=Buffer.concat([o.update(n),o.final()]),s=o.getAuthTag();return{version:1,algorithm:Ro,kekId:e,encryptedDek:i.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function Nf(n,e){return Lf(Buffer.from(n.encryptedDek,"base64"),e,n.iv,n.authTag)}function Lf(n,e,t,r){let o=Ne.createDecipheriv(Ro,e,Buffer.from(t,"base64"));return o.setAuthTag(Buffer.from(r,"base64")),Buffer.concat([o.update(n),o.final()])}function Of(n,e){return Lf(Buffer.from(n.ciphertext,"base64"),e,n.iv,n.authTag).toString("utf8")}function uP(){if(kf(),K.existsSync(br))return;let n=Ne.randomBytes(ko),e=pl(n,Gn[0]);K.writeFileSync(br,JSON.stringify(e,null,2),{mode:384})}function Mf(){uP();let n=JSON.parse(K.readFileSync(br,"utf8")),e=Nf(n,xf(n.kekId));if(e.length===ko)return e;let t=Ne.randomBytes(ko),r=pl(t,Gn[0]);return K.writeFileSync(br,JSON.stringify(r,null,2),{mode:384}),t}function pP(){Tf();for(let t of Gn){let r=ul(t);K.existsSync(r)||K.writeFileSync(r,Ne.randomBytes(To),{mode:384})}if(K.existsSync(br))return;let n=Ne.randomBytes(ko),e=pl(n,Gn[0]);K.writeFileSync(br,JSON.stringify(e,null,2),{mode:384})}function fP(n){let e=Mf(),t=Ne.randomBytes(Rf),r=Ne.createCipheriv(Ro,e,t),o=Buffer.concat([r.update(n,"utf8"),r.final()]),i=r.getAuthTag();return{version:1,algorithm:Ro,ciphertext:o.toString("base64"),iv:t.toString("base64"),authTag:i.toString("base64"),timeStamp:Date.now()}}function mP(n){try{return Of(n,Mf())}catch{throw pP(),new Error("Failed to decrypt local ciphertext")}}function hP(n,e){let t=Ae.join(e,Se.KEY_FILE_NAME),r=JSON.parse(K.readFileSync(t,"utf8"));if(!Gn.includes(r.kekId))throw new Error(`Invalid kekId: ${r.kekId}`);let o=Ae.join(e,"keys",`${r.kekId}.bin`),i=Ae.resolve(o),s=Ae.resolve(Ae.join(e,"keys"));if(!i.startsWith(s+Ae.sep)&&i!==s)throw new Error("kekId resolves outside the keys directory");let a=K.readFileSync(i);if(a.length!==To)throw new Error("Invalid external root key");let c=Nf(r,a);if(c.length!==ko)throw new Error("Invalid external data encryption key");return Of(n,c)}function gP(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 dt(){return process.env.DEVECO_CLI_AUTH_SOURCE===Se.AUTH_SOURCE_DEVECO_CODE}var bs=class{getLocalTokenFilePath(){let e=process.env.DEVECO_CLI_DATA_DIR||on.join(yP(),Se.CONFIG_DIR_NAME,Se.APP_NAME);return on.join(e,Se.TOKEN_FILE_NAME)}ensureConfigDir(){let e=on.dirname(this.getLocalTokenFilePath());Le.existsSync(e)||Le.mkdirSync(e,{recursive:!0,mode:448})}async saveJwtToken(e){if(!e)throw new Error("Token is empty");let t=_t.encryptForLocalStorage(e);this.ensureConfigDir();let r=this.getLocalTokenFilePath();Le.writeFileSync(r,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){return dt()?this.loadDevecoCodeToken():this.loadLocalJwtToken()}loadDevecoCodeToken(){if(!dt())return null;let e=process.env.DEVECO_CODE_AUTH_DIR?.trim();if(!e)return null;let t=on.resolve(e);try{let r=on.join(t,Se.TOKEN_FILE_NAME);if(!Le.existsSync(r))return null;let o=JSON.parse(Le.readFileSync(r,"utf8"));return _t.isEncryptedBlob(o)?_t.decryptForLocalStorageFromDirectory(o,e):null}catch{return null}}async loadLocalJwtToken(){let e=this.getLocalTokenFilePath();try{if(!Le.existsSync(e))return null;let t=JSON.parse(Le.readFileSync(e,"utf8"));return _t.isEncryptedBlob(t)?_t.decryptForLocalStorage(t):null}catch(t){let r=t.code;return r==="EACCES"||r==="EPERM"||r==="ENOENT"||await this.clearToken(),null}}async clearToken(){if(dt()){f("clearToken: skipped, session managed by DevEco Code");return}let e=this.getLocalTokenFilePath();try{Le.existsSync(e)&&Le.unlinkSync(e)}catch(t){throw new Error("Failed to clear token",{cause:t})}}},Ft=new bs;import{exec as wP}from"child_process";import{promisify as vP}from"util";var SP=vP(wP);async function _f(n){let e=process.platform,t;switch(e){case"win32":t=`start "" "${n}"`;break;case"darwin":t=`open "${n}"`;break;case"openharmony":console.log("\u65E0\u6CD5\u81EA\u52A8\u6253\u5F00\u6D4F\u89C8\u5668\uFF0C\u8BF7\u624B\u52A8\u590D\u5236\u4EE5\u4E0B\u767B\u5F55\u94FE\u63A5\u5230\u6D4F\u89C8\u5668\u6253\u5F00\uFF1A"),console.log(n);return;default:t=`xdg-open "${n}"`;break}try{await SP(t)}catch(r){throw new Error("Failed to open browser",{cause:r})}}import bP from"axios";import{getProxyForUrl as EP}from"proxy-from-env";function PP(n){let e=new URL(n);return{protocol:e.protocol,host:e.hostname,port:e.port?Number.parseInt(e.port,10):e.protocol==="https:"?443:80,auth:{username:decodeURIComponent(e.username),password:decodeURIComponent(e.password)}}}var fl=class{client;constructor(){let e={timeout:co.HTTP_TIMEOUT_MS,headers:{"User-Agent":Li.USER_AGENT,"accept-language":Li.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=bP.create(e),this.client.interceptors.request.use(t=>{let r=EP(t.url??"");return t.proxy=r?PP(r):!1,t}),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}
|
|
1280
|
-
${r}`)})}async get(e,t){let r=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}async post(e,t){let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}convertResponse(e){return{data:typeof e.data=="string"?e.data:JSON.stringify(e.data),statusCode:e.status,statusText:e.statusText??"",headers:e.headers}}parseJson(e){return JSON.parse(e.data)}async getBinary(e,t){let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout});if(r.status!==200)throw new Error(`HTTP ${r.status}`);return Buffer.from(r.data)}async postAllowFailure(e,t){let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});return this.convertResponse(r)}async deleteAllowFailure(e,t){let r=await this.client.request({method:"DELETE",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});return this.convertResponse(r)}async getBinaryAllowFailure(e,t){let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0}),o=Buffer.from(r.data),i=o.toString("utf8");return{statusCode:r.status,statusText:r.statusText??"",buffer:o,body:i}}},x=new
|
|
1281
|
-
`)}function xP(){return new Promise(n=>{let e=Wf.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),n()})})}var xo=new TP("auth").description("Authentication commands (login, logout, status, team)");xo.command("login").description("Log in to your Huawei Developer account").action(async()=>{if(dt()){console.log(gl("Login is managed by DevEco Code. Login from DevEco Code instead."));return}try{let n=await De.getUserInfo();if(n){console.log(Ht(`Already logged in, User Name:${n.userName}`));return}console.log(Ht("Starting login process...")),console.log(Ht("Press Enter to open browser for login...")),await xP();let e=await De.login();console.log(Ht(`Login successful. Logged in as ${e.userName}.`))}catch(n){throw n instanceof Ie||(n instanceof Error?n.message:String(n)).includes("Network connection failed")?n:new Error("Login failed",{cause:n})}});xo.command("logout").description("Log out of your Huawei Developer account").action(async()=>{if(dt()){console.log(gl("Login is managed by DevEco Code. Log out from DevEco Code instead."));return}try{let n=await De.logout();console.log(n?Ht("Logout successful"):Ht("Already logged out."))}catch(n){throw new Error("Logout failed",{cause:n})}});xo.command("status").description("Show the currently logged-in user").action(async()=>{let n=await De.getUserInfo();if(!n){console.log(Ht("Not logged in"));return}console.log(Ht(`Current user: ${n.userName}`))});var NP=xo.command("team").description("Team-related commands");NP.command("list").description("List team accounts the current user has joined").action(async()=>{try{let n=await sn();console.log(kP(n.teamList))}catch(n){if(n instanceof Ie){console.log(gl(n.message));return}throw n}});var Gf=xo;import{Command as VP}from"commander";import{green as qP,red as _o,cyan as pm,yellow as fm,dim as mm}from"colorette";import zP from"p-limit";import LP from"ora";var ut=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=LP(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 Vf from"fs";import*as qf from"path";var zf=["DevEco"];async function Is(){let n=await x.get(it.TAGS_API_URL),t=As(n,"Tags API").data.skill.filter(r=>r.name==="HMOS");if(t.length===0)throw new Error("No HMOS tag found.");return t.map(r=>r.id)}async function OP(n){let e=[],t=it.DEFAULT_PAGE_SIZE,r=1;for(;;){let o=await x.post(it.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:r,pageSize:t,tagIds:[n]}}),i=As(o,"Skills API");if(e.push(...i.data.list),i.data.list.length<t)break;r++}return e}async function yl(n){let e=new Map,t=n.map(o=>OP(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=>!zf.includes(i.name)))}async function MP(n,e){let t=await x.post(it.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:it.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return As(t,"Skills API").data.list}async function wl(n,e){let t=new Map,r=e.map(i=>MP(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=>!zf.includes(s.name)))}function Yf(n){let e=[],t=Dt();for(let[,r]of Object.entries(t)){let o=qf.join(r.path,n);Vf.existsSync(o)&&e.push(r.displayName)}return e.sort()}function As(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=x.parseJson(n);if(t.code!==it.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Jf(n){let e=`${it.SKILL_API_BASE}/${n}/checksum`,t=await x.get(e);return As(t,"Checksum API").data}import _P from"adm-zip";import FP from"crypto";import Xf from"fs";import ie from"path";import{fileURLToPath as jP}from"url";import{red as HP}from"colorette";var $t=Xf.promises;function vl(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}function Kf(n,e){let t=ie.resolve(e),r=ie.resolve(n),o=ie.relative(r,t);if(o.startsWith("..")||ie.isAbsolute(o))throw new Error(`Path traversal detected: ${e}.`)}function Sl(n){return ie.isAbsolute(n)?n:ie.resolve(process.cwd(),n)}function $P(n){return FP.createHash("sha256").update(n).digest("hex")}async function UP(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=$P(n),o=e.sha256.toLowerCase();if(r!==o)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function Zf(n){let e=`${it.SKILL_API_BASE}/${n}/install?format=zip`,t=await x.getBinary(e),r=await Jf(n);return await UP(t,r),t}async function BP(n,e,t){vl(t);let r=new _P(n),o=r.getEntries();try{await $t.stat(e)}catch{await $t.mkdir(e,{recursive:!0})}let i=ie.join(e,t);Kf(e,i);for(let s of o){let a=ie.join(i,s.entryName);Kf(i,a)}r.extractAllTo(i,!0)}async function bl(n){let e=Dt();if(!e[n])throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(e).join(", ")}`);let r=ue[n];try{return await $t.access(r),!0}catch{return!1}}function El(n){return Dt()[n].path}function Pl(n,e){let r=Dt()[e],o="projectPath"in r?r.projectPath:ie.join("."+e,"skills");return ie.join(n,o)}async function WP(n,e,t){vl(e);let r=ie.join(n,e);try{if(await $t.access(r),t)await $t.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 Cl(n,e,t){await BP(n,e,t),console.log(`Skill ${t} installed to ${ie.join(e,t)}.`)}async function Il(n,e,t){let r=ie.join(e,t);await $t.mkdir(r,{recursive:!0});let o=ie.join(r,ie.basename(n));await $t.copyFile(n,o),console.log(`Skill ${t} installed to ${r}.`)}function Qf(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(HP(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function Pr(n,e,t,r){try{let o=await e(),{shouldSkip:i}=await WP(o,n,r);return i?{success:!0,skipped:!0}:(await t(o),{success:!0})}catch(o){return Qf(n,o,"Installation failed")}}async function Al(n,e){try{vl(n);let t=await e(),r=ie.join(t,n);try{await $t.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await $t.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return Qf(n,t,"Removal failed")}}async function em(n,e,t,r=!1){return Pr(n,()=>El(e),o=>Cl(t,o,n),r)}async function tm(n,e,t,r=!1){return Pr(n,()=>t,o=>Cl(e,o,n),r)}async function nm(n,e,t,r,o=!1){return Pr(n,()=>Pl(t,r),i=>Cl(e,i,n),o)}async function rm(n,e,t,r=!1){return Pr(n,()=>El(t),o=>Il(e,o,n),r)}async function om(n,e,t,r,o=!1){return Pr(n,()=>Pl(t,r),i=>Il(e,i,n),o)}async function im(n,e,t,r=!1){return Pr(n,()=>t,o=>Il(e,o,n),r)}async function sm(n,e){return Al(n,()=>El(e))}async function am(n,e){return Al(n,()=>e)}async function cm(n,e,t){return Al(n,()=>Pl(e,t))}function lm(){let e=ie.dirname(jP(import.meta.url));for(;;){let t=ie.join(e,"SKILL.md");if(Xf.existsSync(t))return t;let r=ie.dirname(e);if(r===e)break;e=r}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import dm from"fs";import{cyan as GP}from"colorette";async function No(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await bl(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function Lo(){let n=[],e=Dt();for(let t of Object.keys(e))await bl(t)&&n.push(t);return n}function Oo(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(GP("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function an(n,e,t){if(!dm.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!dm.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function Mo(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?Sl(n):void 0,resolvedProject:e?Sl(e):void 0}}async function Ds(n,e,t){let r=[],o=[],i;if(e?i=e:t&&n.agent?o=(await No(n.agent)).map(a=>({project:t,agent:a})):t?o=(await Lo()).map(a=>({project:t,agent:a})):n.agent?r=await No(n.agent):r=await Lo(),!i&&r.length===0&&o.length===0)throw new Error("No agents found. Install an AI agent (opencode, etc.) or use `--path` for a custom location.");return{agents:r,projectAgents:o,customPath:i}}async function YP(n){let e=await Is();if(n.all)return(await yl(e)).map(r=>r.enName);{let r=(await wl(n.skill,e)).find(o=>o.enName===n.skill);if(!r)throw new Error(`Skill "${n.skill}" not found`);return[r.enName]}}async function JP(n,e,t,r){let o=[];if(t.customPath){let i=await tm(n,e,t.customPath,r);return o.push(i),o}for(let i of t.agents){let s=await em(n,i,e,r);o.push(s)}for(let{project:i,agent:s}of t.projectAgents){let a=await nm(n,e,i,s,r);o.push(a)}return o}function KP(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}=Mo(n.path,n.project,n.agent);return t&&an(t,"Project directory",n.force),e&&an(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}async function XP(n,e,t){let r=await Ds(n,e,t);return{skillNames:await YP(n),targets:r}}async function ZP(n,e,t,r){let o=[],i=n.length,s=zP(5),a=n.map(c=>s(()=>QP(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 h=await a[c];if(!h.success){r.fail(),console.log(_o(`${l}: Download failed - ${h.error}`)),o.push({success:!1});continue}r.stop();let w=await JP(l,h.buffer,e,t);o.push(...w)}return o}async function QP(n){try{let e=await Zf(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 eC(n){let e=new ut;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=KP(n),{skillNames:o,targets:i}=await XP(n,t,r),s=await ZP(o,i,n.force||!1,e);e.stop(),Oo(s)}catch(t){throw e.stop(),t}}function tC(n){let{resolvedPath:e,resolvedProject:t}=Mo(n.path,n.project,n.agent);return t&&an(t,"Project directory"),e&&an(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function nC(n,e){let t=new ut;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:o}=tC(e);t.stop();let i=await rC(e,n,r,o);t.stop(),Oo(i)}catch(r){throw t.stop(),r}}function um(n,e=""){if(n.length===0)throw new Error(`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function Rs(n,e){let t=[];for(let r of e){let o=r.type==="agent"?await sm(n,r.agent):await cm(n,r.project,r.agent);t.push(o)}return t}async function rC(n,e,t,r){if(t)return[await am(e,t)];if(r&&n.agent){let a=(await No(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return Rs(e,a)}if(r){let s=await Lo();um(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return Rs(e,a)}if(n.agent){let a=(await No(n.agent)).map(c=>({type:"agent",agent:c}));return Rs(e,a)}let o=await Lo();um(o,"or use --path for a custom location.");let i=o.map(s=>({type:"agent",agent:s}));return Rs(e,i)}var Fo=new VP("skills").description("Manage HarmonyOS skills");Fo.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 ut;try{e.start("Fetching skills...");let t=await Is(),r=await yl(t);if(r.length===0){e.stop(),console.log(fm("No skills available."));return}e.succeed(`Fetched ${r.length} skills`);for(let o of r)if(n.long){console.log(pm(o.enName)),console.log(mm(o.description));let i=Yf(o.enName);i.length>0&&console.log(qP(`Installed for: ${i.join(", ")}`)),console.log()}else console.log(o.enName)}catch(t){e.stop(),console.error(_o(t.message)),process.exit(1)}});Fo.command("find <keyword>").description("Search skills by keyword").action(async n=>{let e=new ut;try{e.start("Searching skills...");let t=await Is(),r=await wl(n,t);if(r.length===0){console.log(fm(`No skills found matching '${n}'.`)),e.stop();return}e.succeed(`Found ${r.length} skills.`);for(let o of r)console.log(pm(o.enName)),console.log(mm(o.description)),console.log()}catch(t){e.stop(),console.error(_o(t.message)),process.exit(1)}});Fo.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 eC(n)}catch(e){console.error(_o(e.message)),process.exit(1)}});Fo.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 nC(n.skill,n)}catch(e){console.error(_o(e.message)),process.exit(1)}});var hm=Fo;import{Command as iC,InvalidArgumentError as ks}from"commander";import{cyan as Ts}from"colorette";function qn(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=cr(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 Dl=[800,1500,2500];function oC(n){return new Promise(e=>setTimeout(e,n))}function gm(){return E()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device."}var Cr=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=re.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(`
|
|
1282
|
-
`)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let o=t[0];return f(
|
|
1275
|
+
`;function FE(n){let e=n.trim();if(!e)throw new Error("--target must not be empty.");return e}function jE(n){let e=n.trim();if(!mf.includes(e))throw new Error(`Invalid fold state "${n}". Available values: ${mf.join(", ")}`);return e}function gf(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 yf(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&&!HE(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 HE(n,e){let t=n.split(".")[1];return t===void 0||t.length<=e}function $E(n,e,t,r,o){return Number(yf(n,e,t,r,o))}function UE(n){let e=n.trim();if(!e||!/^[A-Za-z0-9_ ]+$/.test(e))throw new Error("The virtual device name can only contain letters, spaces, numbers, and underscores (_).")}function BE(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 WE(n,e){let t=o=>o.normalize("NFKC").trim(),r=t(n);if(e.length===0)throw console.error(bt("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(bt("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(Ce("--os-version does not match any downloaded image (exact string required).")),console.log(bt("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 GE=["Name","Status","Serial","Device Type","OS Version"];function VE(n,e,t){return{cells:[n.name,t?"running":"stopped",e??"-",n.deviceType??"-",n.osVersion??"-"],highlight:t}}async function qE(n,e){let t=await Promise.all(e.map(async r=>{let o=await dr(n,r,ME);return[r,o]}));return new Map(t)}async function zE(n){let e=await Xc(n),t=await qE(n,e);return{serials:e,params:t}}function YE(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 JE(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&&YE(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 KE(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(o=>VE(o.emu,o.serial,o.effectiveRunning))}async function XE(n,e,t){try{let[r,o]=await Promise.all([n.listEmulators(),zE(e)]);if(r.length===0){t?.stop(),console.log(bt(" No emulator instances found."));return}let i=r.filter(l=>l.isRunning).map(l=>l.name),{productSerialMap:s,hvdSerialMap:a}=JE(o.serials,o.params,i);t?.stop();let c=KE(r,s,a);console.log(Ot(GE,c))}catch(r){fs(t,`Failed to list emulators: ${r.message}`)}}function wf(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(Ce(`Failed to ${t} emulator "${e[o]}": ${s.message}`)),s.stdout&&console.error(Ao(s.stdout)),s.stderr&&console.error(Ao(s.stderr))}return r}var ZE=2e3,QE=6e4;async function eP(n,e){let t=be(e);return(await Zc(n)).some(o=>be(o)===t)}async function vf(n,e,t,r=QE,o=ZE){let i=Date.now()+r;for(;Date.now()<i;){if(await eP(n,e)===t)return!0;await new Promise(a=>setTimeout(a,o))}return!1}async function tP(n,e,t){if(await n.startEmulator(t)==="already-running"){console.log(bt(`Emulator "${t}" is already running.`));return}console.log(br(`Starting emulator "${t}"...`));let o=await vf(e,t,!0);console.log(o?Ro(`Emulator "${t}" started successfully.`):bt(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function nP(n,e,t){let r=await Promise.allSettled(t.map(i=>tP(n,e,i)));wf(r,t,"start")&&process.exit(1)}async function Sf(n,e){let t=e.trim();if(!$n(t))return t;let r=await re.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 rP(n,e,t){let r=await Sf(e,t);if(console.log(br(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(bt(`Emulator "${r}" is already stopped.`));return}let i=await vf(e,r,!1);console.log(i?Ro(`Emulator "${r}" stopped successfully.`):bt(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function oP(n,e,t){let r=await Promise.allSettled(t.map(i=>rP(n,e,i)));wf(r,t,"stop")&&process.exit(1)}async function Ze(){try{let n=await A.new();return{manager:vr.from(n),toolProvider:n}}catch(n){console.error(Ce(`Failed to initialize emulator: ${n.message}`)),process.exit(1);return}}async function Mt(n,e){try{let t=FE(n.target),r=e(),{manager:o,toolProvider:i}=await Ze(),s=await Sf(i.hdcPath,t);await o.controlEmulator(s,r),console.log(Ro(`Emulator "${t}" operation completed.`))}catch(t){let r=n.target?.trim()||"<unknown>";console.error(Ce(`Failed to operate emulator "${r}": ${t.message}`)),process.exit(1)}}function iP(n){let e=[];return hs(e,"longitude",n.longitude,-180,180,8),hs(e,"latitude",n.latitude,-90,90,8),hs(e,"altitude",n.altitude,-1e4,1e4,2),hs(e,"bearing",n.direction,0,359.99,2,"--direction"),fl(e,"Specify one geolocation option.")}function sP(n){let e=[];return Co(e,"light",n.lightIntensity,0,1e5,!1,"--light-intensity"),Co(e,"humidity",n.humidity,0,100,!1),Co(e,"temperature",n.temperature,-273.1,100,!1),Co(e,"steps",n.steps,0,1e4,!0),Co(e,"heartrate",n.heartrate,0,255,!0),fl(e,"Specify one sensor option.")}function fl(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 hs(n,e,t,r,o,i,s=`--${e}`){t!==void 0&&n.push({type:"gps",key:e,value:yf(s,t,r,o,i)})}function Co(n,e,t,r,o,i,s=`--${e}`){if(t===void 0)return;let a=i?gf(s,t,r,o):$E(s,t,r,o,1);n.push({type:"sensor",key:e,value:a})}function aP(n){let e=[];return n.level!==void 0&&e.push({type:"battery",level:gf("--level",n.level,1,100)}),n.status!==void 0&&e.push({type:"battery-status",status:n.status==="charging"?1:0}),fl(e,"Specify --level or --status.")}var he=new pl("emulator").description("Manage emulator instances"),cP=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function gs(n){let e=new Do("--device-type <type>","Emulator device type").choices([...cP]);return n?e.makeOptionMandatory():e}function Sr(n,e){for(let t of e)if(t in n)return n[t]}function Io(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function hf(n){let e=Io(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var lP=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],dP="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function bf(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function Ef(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let o=r,i=Io(Sr(o,["osVersion","OsVersion","OSVersion","os_version"])),s=Io(Sr(o,["deviceType","DeviceType","device_type"])),a=hf(Sr(o,["downloaded","Downloaded","isDownloaded"])),c=Io(Sr(o,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=Io(Sr(o,["releaseType","ReleaseType","release_type"])),d=hf(Sr(o,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[i,s,c,l,d,a],highlight:e&&a==="true"})}return t}function uP(n){let e=n.trim();if(!e)return!0;let t=bf(e);return t===null?!1:t.length===0?!0:Ef(t,!0).length===0}function pP(n,e){let t=n.trim();if(!t)return"";let r=bf(t);if(!r)return n.trimEnd();let o=Ef(r,e);return Ot(lP,o)}var ys=new pl("image").description("HarmonyOS emulator system images (download, list, remove)");ys.command("download").description("Download system image").addOption(gs(!1)).option("--os-version <version>","Example: HarmonyOS 5.1.1(19) or HarmonyOS 6.0.1(21) (required)").option("--force","Overwrite an existing image").action(async n=>{let{manager:e,toolProvider:t}=await Ze();try{await dl(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof Xe&&(console.error(Ce(r.message)),process.exit(1)),r}n.deviceType?.trim()||(console.error(Ce("Error: missing required option '--device-type <type>'")),process.exit(1)),n.osVersion?.trim()||(console.error(Ce("Error: misssing required option '--os-version <version>'")),process.exit(1));try{await e.installEmulatorImage({deviceType:n.deviceType.trim(),osVersion:n.osVersion.trim(),force:n.force===!0})}catch(r){console.error(Ce(`Failed to download system image: ${r.message}`)),process.exit(1)}});ys.command("remove").description("Remove a downloaded system image").addOption(gs(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let{manager:e}=await Ze();try{await e.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})}catch(t){console.error(Ce(`Failed to remove system image: ${t.message}`)),process.exit(1)}});ys.command("list").description("List system images").addOption(gs(!1)).option("--all","List all images (local and remote)").addOption(new Do("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let{manager:e}=await Ze();try{let t;n.all?t=void 0:t=!0;let r=await e.listEmulatorImages({deviceType:n.deviceType,downloaded:t});if(uP(r)){console.log(bt(dP));return}if(n.format==="json"){console.log(r.trimEnd());return}let o=pP(r,n.all===!0);console.log(o)}catch(t){console.error(Ce(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});he.addCommand(ys);var ws=new pl("license").description("Review and accept emulator license agreements interactively (prints full text + y/N prompt)");ws.command("view").description("Review agreement text (read-only, no changes)").action(async()=>{let{toolProvider:n}=await Ze(),e=await df(n.emulatorPath,n.sdkPath);process.exit(e)});ws.command("accept").description("Accept all emulator license agreements non-interactively (skips review and prompt)").action(async()=>{let{toolProvider:n}=await Ze(),e=await ff(n.emulatorPath,n.sdkPath);process.exit(e)});ws.action(async()=>{let{toolProvider:n}=await Ze(),e=await pf(n.emulatorPath,n.sdkPath);process.exit(e)});he.addCommand(ws);he.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Mt(n,()=>({type:"shake"})));he.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Mt(n,()=>({type:"power"})));he.command("rotate").description("Rotate emulator").addOption(new Do("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new ul("<direction>").choices(["left","right"])).action((n,e)=>Mt(e,()=>({type:"rotation",direction:n})));he.command("volume").description("Change volume").addOption(new Do("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new ul("<direction>").choices(["up","down"])).action((n,e)=>Mt(e,()=>({type:"volume",direction:n})));he.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",_E).action((n,e)=>Mt(e,()=>({type:"folded-state",state:jE(n)})));he.command("battery").description("Set battery level or charging status").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--level <1-100>","Battery level, SOC (integer 1-100)").addOption(new Do("--status <status>","Charging status").choices(["charging","discharging"])).action(n=>Mt(n,()=>aP(n)));he.command("geolocation").description("Inject geographic coordinates and direction").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--longitude <value>","Longitude (-180.0 to 180.0)").option("--latitude <value>","Latitude (-90.0 to 90.0)").option("--altitude <value>","Altitude (-10000.0 to 10000.0)").option("--direction <value>","Heading direction in degrees (0.00 to 359.99)").action(n=>Mt(n,()=>iP(n)));he.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new ul("<type>","Motion simulation scene").choices(["outdoorRunning","outdoorCycling","drivingNavigation"])).action((n,e)=>{let t={outdoorRunning:{type:"outdoor-running"},outdoorCycling:{type:"outdoor-cycling"},drivingNavigation:{type:"driving-navigation"}};return Mt(e,()=>t[n])});he.command("sensor").description("Inject sensor data").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--light-intensity <value>","Light sensor (0 to 100000)").option("--humidity <value>","Humidity sensor (0 to 100)").option("--temperature <value>","Temperature sensor (-273.1 to 100)").option("--steps <value>","Steps sensor (integer 0 to 10000)").option("--heartrate <value>","Heart rate sensor (integer 0 to 255)").action(n=>Mt(n,()=>sP(n)));he.command("list").description("List all emulator instances").action(async()=>{let{manager:n,toolProvider:e}=await Ze(),t=OE({text:"Listing emulators\u2026",color:"cyan"}).start();await XE(n,e.hdcPath,t)});he.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let{manager:e,toolProvider:t}=await Ze();try{await ll(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof Xe&&(console.error(Ce(r.message)),process.exit(1)),r}n?.length||(console.error(Ce("Error: missing required argument 'names'")),process.exit(1)),await nP(e,t.hdcPath,n)});he.command("stop <names...>").description("Stop one or more emulator instances (by name or serial,e.g.,127.0.0.1:<port>)").action(async n=>{let{manager:e,toolProvider:t}=await Ze();n?.length||(console.error(Ce("Error: missing required argument 'names'")),process.exit(1)),await oP(e,t.hdcPath,n)});var Pf=he.command("create <name>").description("Create a local emulator by running emulator -create <name> \u2026. --os-version must match a downloaded image from `emulator image list`.").addOption(gs(!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");Pf.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
|
|
1276
|
+
${bt("Tip: ")}${Ao("Unquoted --os-version values with spaces/parentheses are split into multiple arguments. Use:")}
|
|
1277
|
+
${br('devecocli emulator create 123 --device-type phone --os-version "HarmonyOS 6.0.1(21)"')}
|
|
1278
|
+
${br('devecocli emulator create 123 --device-type phone --os-version="HarmonyOS 6.0.1(21)"')}
|
|
1279
|
+
`)}});Pf.action(async(n,e)=>{try{UE(n),BE(e.osVersion);let{manager:t}=await Ze(),r=await t.listDownloadedImageOsVersions();WE(e.osVersion,r),console.log(br(`Creating emulator "${n}"...`)),await t.createVirtualDevice({name:n,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(Ro(`Emulator "${n}" created successfully.`))}catch(t){console.error(Ce(`${t.message}`)),process.exit(1)}});he.command("delete <name>").description("Delete a local emulator instance").action(async n=>{let{manager:e}=await Ze();console.log(br(`Deleting emulator "${n}"...`));try{let t=await e.deleteVirtualDevice(n);console.log(Ro(`Emulator "${t}" deleted successfully.`))}catch(t){let r=t;console.error(Ce(r.message)),r.stdout&&console.error(Ao(r.stdout)),r.stderr&&console.error(Ao(r.stderr)),process.exit(1)}});var Cf=he;import{Command as OP}from"commander";import{red as vl,cyan as Ht}from"colorette";import*as qf from"readline";import*as Gf from"crypto";import*as If from"http";import*as Af from"crypto";import{URL as fP}from"url";var vs=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=If.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 fP(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 Le from"fs";import*as on from"path";import{homedir as SP}from"os";var _t={};pv(_t,{LocalCrypto:()=>_t,decryptForLocalStorage:()=>yP,decryptForLocalStorageFromDirectory:()=>wP,encryptForLocalStorage:()=>gP,isEncryptedBlob:()=>vP});import*as K from"fs";import*as Ae from"path";import*as Ne from"crypto";import*as Rf from"os";import{homedir as Tf}from"os";var Ie=class extends Error{constructor(e){super(e),this.name="DefinedError"}};var To=Ln.ALGORITHM,kf=Ln.IV_LENGTH,ko=Ln.KEY_LENGTH,xo=Ln.KEY_LENGTH,Vn=Ln.KEK_VERSIONS,Ss=process.env.DEVECO_CLI_DATA_DIR||Ae.join(Tf(),ve.CONFIG_DIR_NAME,ve.APP_NAME),bs=Ae.join(Tf(),".local","share",ve.APP_NAME,"keys"),Er=Ae.join(Ss,ve.KEY_FILE_NAME);function Df(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 ml(n){return Ae.join(bs,`${n}.bin`)}function xf(){if(!K.existsSync(Ss))try{K.mkdirSync(Ss,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new Ie(Df(Ss)):n}if(!K.existsSync(bs))try{K.mkdirSync(bs,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new Ie(Df(Ae.dirname(bs))):n}}function Nf(){xf();for(let n of Vn){let e=ml(n);K.existsSync(e)||K.writeFileSync(e,Ne.randomBytes(ko),{mode:384})}}function Lf(n){if(!Vn.includes(n))throw new Error(`Invalid kekId: ${n}`);Nf();let e=ml(n),t=K.readFileSync(e);if(t.length===ko)return t;let r=Ne.randomBytes(ko);return K.writeFileSync(e,r,{mode:384}),r}function hl(n,e){let t=Ne.randomBytes(kf),r=Lf(e),o=Ne.createCipheriv(To,r,t),i=Buffer.concat([o.update(n),o.final()]),s=o.getAuthTag();return{version:1,algorithm:To,kekId:e,encryptedDek:i.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function Of(n,e){return Mf(Buffer.from(n.encryptedDek,"base64"),e,n.iv,n.authTag)}function Mf(n,e,t,r){let o=Ne.createDecipheriv(To,e,Buffer.from(t,"base64"));return o.setAuthTag(Buffer.from(r,"base64")),Buffer.concat([o.update(n),o.final()])}function _f(n,e){return Mf(Buffer.from(n.ciphertext,"base64"),e,n.iv,n.authTag).toString("utf8")}function mP(){if(Nf(),K.existsSync(Er))return;let n=Ne.randomBytes(xo),e=hl(n,Vn[0]);K.writeFileSync(Er,JSON.stringify(e,null,2),{mode:384})}function Ff(){mP();let n=JSON.parse(K.readFileSync(Er,"utf8")),e=Of(n,Lf(n.kekId));if(e.length===xo)return e;let t=Ne.randomBytes(xo),r=hl(t,Vn[0]);return K.writeFileSync(Er,JSON.stringify(r,null,2),{mode:384}),t}function hP(){xf();for(let t of Vn){let r=ml(t);K.existsSync(r)||K.writeFileSync(r,Ne.randomBytes(ko),{mode:384})}if(K.existsSync(Er))return;let n=Ne.randomBytes(xo),e=hl(n,Vn[0]);K.writeFileSync(Er,JSON.stringify(e,null,2),{mode:384})}function gP(n){let e=Ff(),t=Ne.randomBytes(kf),r=Ne.createCipheriv(To,e,t),o=Buffer.concat([r.update(n,"utf8"),r.final()]),i=r.getAuthTag();return{version:1,algorithm:To,ciphertext:o.toString("base64"),iv:t.toString("base64"),authTag:i.toString("base64"),timeStamp:Date.now()}}function yP(n){try{return _f(n,Ff())}catch{throw hP(),new Error("Failed to decrypt local ciphertext")}}function wP(n,e){let t=Ae.join(e,ve.KEY_FILE_NAME),r=JSON.parse(K.readFileSync(t,"utf8"));if(!Vn.includes(r.kekId))throw new Error(`Invalid kekId: ${r.kekId}`);let o=Ae.join(e,"keys",`${r.kekId}.bin`),i=Ae.resolve(o),s=Ae.resolve(Ae.join(e,"keys"));if(!i.startsWith(s+Ae.sep)&&i!==s)throw new Error("kekId resolves outside the keys directory");let a=K.readFileSync(i);if(a.length!==ko)throw new Error("Invalid external root key");let c=Of(r,a);if(c.length!==xo)throw new Error("Invalid external data encryption key");return _f(n,c)}function vP(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 dt(){return process.env.DEVECO_CLI_AUTH_SOURCE===ve.AUTH_SOURCE_DEVECO_CODE}var Es=class{getLocalTokenFilePath(){let e=process.env.DEVECO_CLI_DATA_DIR||on.join(SP(),ve.CONFIG_DIR_NAME,ve.APP_NAME);return on.join(e,ve.TOKEN_FILE_NAME)}ensureConfigDir(){let e=on.dirname(this.getLocalTokenFilePath());Le.existsSync(e)||Le.mkdirSync(e,{recursive:!0,mode:448})}async saveJwtToken(e){if(!e)throw new Error("Token is empty");let t=_t.encryptForLocalStorage(e);this.ensureConfigDir();let r=this.getLocalTokenFilePath();Le.writeFileSync(r,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){return dt()?this.loadDevecoCodeToken():this.loadLocalJwtToken()}loadDevecoCodeToken(){if(!dt())return null;let e=process.env.DEVECO_CODE_AUTH_DIR?.trim();if(!e)return null;let t=on.resolve(e);try{let r=on.join(t,ve.TOKEN_FILE_NAME);if(!Le.existsSync(r))return null;let o=JSON.parse(Le.readFileSync(r,"utf8"));return _t.isEncryptedBlob(o)?_t.decryptForLocalStorageFromDirectory(o,e):null}catch{return null}}async loadLocalJwtToken(){let e=this.getLocalTokenFilePath();try{if(!Le.existsSync(e))return null;let t=JSON.parse(Le.readFileSync(e,"utf8"));return _t.isEncryptedBlob(t)?_t.decryptForLocalStorage(t):null}catch(t){let r=t.code;return r==="EACCES"||r==="EPERM"||r==="ENOENT"||await this.clearToken(),null}}async clearToken(){if(dt()){f("clearToken: skipped, session managed by DevEco Code");return}let e=this.getLocalTokenFilePath();try{Le.existsSync(e)&&Le.unlinkSync(e)}catch(t){throw new Error("Failed to clear token",{cause:t})}}},Ft=new Es;import{exec as bP}from"child_process";import{promisify as EP}from"util";var PP=EP(bP);async function jf(n){let e=process.platform,t;switch(e){case"win32":t=`start "" "${n}"`;break;case"darwin":t=`open "${n}"`;break;case"openharmony":console.log("\u65E0\u6CD5\u81EA\u52A8\u6253\u5F00\u6D4F\u89C8\u5668\uFF0C\u8BF7\u624B\u52A8\u590D\u5236\u4EE5\u4E0B\u767B\u5F55\u94FE\u63A5\u5230\u6D4F\u89C8\u5668\u6253\u5F00\uFF1A"),console.log(n);return;default:t=`xdg-open "${n}"`;break}try{await PP(t)}catch(r){throw new Error("Failed to open browser",{cause:r})}}import CP from"axios";import{getProxyForUrl as IP}from"proxy-from-env";function AP(n){let e=new URL(n);return{protocol:e.protocol,host:e.hostname,port:e.port?Number.parseInt(e.port,10):e.protocol==="https:"?443:80,auth:{username:decodeURIComponent(e.username),password:decodeURIComponent(e.password)}}}var gl=class{client;constructor(){let e={timeout:so.HTTP_TIMEOUT_MS,headers:{"User-Agent":Ri.USER_AGENT,"accept-language":Ri.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=CP.create(e),this.client.interceptors.request.use(t=>{let r=IP(t.url??"");return t.proxy=r?AP(r):!1,t}),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}
|
|
1280
|
+
${r}`)})}async get(e,t){let r=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}async post(e,t){let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}convertResponse(e){return{data:typeof e.data=="string"?e.data:JSON.stringify(e.data),statusCode:e.status,statusText:e.statusText??"",headers:e.headers}}parseJson(e){return JSON.parse(e.data)}async getBinary(e,t){let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout});if(r.status!==200)throw new Error(`HTTP ${r.status}`);return Buffer.from(r.data)}async postAllowFailure(e,t){let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});return this.convertResponse(r)}async deleteAllowFailure(e,t){let r=await this.client.request({method:"DELETE",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});return this.convertResponse(r)}async getBinaryAllowFailure(e,t){let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0}),o=Buffer.from(r.data),i=o.toString("utf8");return{statusCode:r.status,statusText:r.statusText??"",buffer:o,body:i}}},x=new gl;function Hf(n){let e=n.split(".");return e.length===3&&e.every(t=>t.length>0)}var jt={CHINA:"CN",RUSSIA:"RU",SINGAPORE:"SG",EUROPE:"EU"},qn={CHINA:"zh_CN",RUSSIA:"ru_RU",EUROPE:"de_DE"},Ps={CHINA:"1",SINGAPORE:"5",EUROPE:"7",RUSSIA:"8"},DP={[jt.CHINA]:qn.CHINA,[jt.RUSSIA]:qn.RUSSIA,[jt.EUROPE]:qn.EUROPE,[jt.SINGAPORE]:qn.CHINA},RP={[Ps.CHINA]:jt.CHINA,[Ps.SINGAPORE]:jt.SINGAPORE,[Ps.EUROPE]:jt.EUROPE,[Ps.RUSSIA]:jt.RUSSIA};function $f(n){return DP[n]??qn.CHINA}function Uf(n){return RP[n]??jt.CHINA}var yl=class{async getJwtToken(e,t,r,o,i){let s=e.split("&")[0],a=Uf(t),c={tempToken:s,site:a,version:ve.API_VERSION,appid:i},l=`${r}/${o}`,d=await x.get(l,{params:c});if(d.statusCode!==200)throw new Error(`Failed to get jwtToken: status=${d.statusCode}`);let h=d.data.trim();if(!Hf(h))throw new Error("Invalid jwtToken format");return h}},Bf=new yl;var wl=class{async checkJwtToken(e,t,r=!1){let o={refresh:String(r),jwtToken:e},i=`${t}/${q.JWT_TOKEN_CHECK_PATH}`,s=await x.get(i,{headers:o});if(s.statusCode!==200)throw new Error(`Failed to check jwtToken: ${s.statusCode}`);return x.parseJson(s)}async refreshToken(e){let t=await Ft.loadJwtToken();return t?this.refreshTokenWithToken(t,e):null}async refreshTokenWithToken(e,t){try{let r={refresh:"true",jwtToken:e},o=`${t}/${q.JWT_TOKEN_CHECK_PATH}`,i=await x.get(o,{headers:r});if(i.statusCode!==200)return null;let s=x.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?(f("jwtToken invalid."),await Ft.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:$f(o.userInfo.nationalCode),isRealName:String(o.userInfo.realName)==="true"}}async fetchUserInfo(e,t){let r=await Ft.loadJwtToken();return r?this.getUserInfoFromJwt(r,e,t):null}},Pr=new wl;import TP from"querystring";import{spawn as kP}from"child_process";function Wf(n){try{let e=JSON.stringify({signInfo:[{agrType:ao.PRIVACY_ID,country:"CN",language:"zh_CN",isAgree:!0}]}),t=TP.stringify({nsp_svc:"as.user.sign",access_token:n,request:e}),r=kP("curl",["-s","-X","POST",ao.TMS_URL,"-H","Content-Type: application/x-www-form-urlencoded","-d",t,"--max-time","5","-o","/dev/null","-w","%{http_code}"],{detached:!0,stdio:["ignore","pipe","ignore"]});r.unref(),r.stdout?.on("data",o=>{let i=o.toString().trim();i==="200"?f("Agreement sign reported successfully"):f(`Agreement sign failed: HTTP ${i}`)}).on("error",()=>{})}catch(e){f(`Agreement sign error: ${e.message}`)}}var Cs=class{config;server=null;constructor(e){this.config={...co,...e}}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}async login(){try{f(`Login started, isDevecoCodeAuth: ${dt()}`);let e=this.generateClientSecret();this.server=new vs(e,q.CN_LOGIN_URL,this.config.successRedirectUrl,this.config.failedRedirectUrl),await this.server.start(),f(`Local auth server started on port ${this.server.getPort()}`),await this.openLoginPage(this.server.getPort(),e),f("Browser opened for authentication");let t=await this.server.waitForCallback(this.config.timeout);if(f(`Callback received: siteId=${t.siteId}`),t.siteId!=="1")throw new Ie("Non-China accounts are not supported.");let r=await Bf.getJwtToken(t.tempToken,t.siteId,q.CN_LOGIN_URL,this.config.tempTokenCheckUrl,this.config.appId);f("JWT token received");let o=await Pr.getUserInfoFromJwt(r,q.CN_LOGIN_URL);if(!o)throw new Ie("Login failed: failed to get user info");return f(`User info received: ${o.userName}`),await Ft.saveJwtToken(r),f("JWT token saved"),Wf(o.accessToken),o}finally{this.server&&(await this.server.stop(),this.server=null)}}async isLoggedIn(){return await this.getUserInfo(!0)!==null}async logout(){let e=await Ft.loadJwtToken();if(!e)return!1;let r=`${q.CN_LOGIN_URL}/${this.config.logoutUrl}?jwtToken=${e}`;try{await x.post(r,{timeout:5e3})}catch{f("Logout: server notification failed, local token cleared")}finally{await Ft.clearToken()}return!0}async getUserInfo(e=!0){return Pr.fetchUserInfo(q.CN_LOGIN_URL,e)}generateClientSecret(){return Gf.randomUUID().replace(/-/g,"")}async openLoginPage(e,t){let o=`${q.CN_LOGIN_URL}/${this.config.authUrl}?port=${e}&appid=${this.config.appId}&code=${t}`;await jf(o)}async refreshToken(){return Pr.refreshToken(q.CN_LOGIN_URL)}},De=new Cs;function NP(){return dt()?"Not logged in. Please login via DevEco Code first.":"Please run `devecocli auth login` first."}function LP(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 Is=class{config;constructor(e){this.config={...co,...e}}updateConfig(e){this.config={...this.config,...e}}async listTeams(){let e=await Pr.fetchUserInfo(q.CN_LOGIN_URL,!0);if(!e)throw new Ie(NP());let t=await this.fetchTeamList(e.accessToken,e.userId),r=LP(t);return{userId:e.userId,teamList:r}}async fetchTeamList(e,t){let r=this.config.agcTeamListUrl,o;try{o=await x.get(r,{headers:{oauth2Token:e,uid:t,source:"cli",lang:qn.CHINA},timeout:15e3})}catch(i){let s=i.message;throw s.includes("401")?new Ie("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}},Vf=new Is;async function sn(){return Vf.listTeams()}function MP(n){if(n.length===0)return Ht("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(`
|
|
1281
|
+
`)}function _P(){return new Promise(n=>{let e=qf.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),n()})})}var No=new OP("auth").description("Authentication commands (login, logout, status, team)");No.command("login").description("Log in to your Huawei Developer account").action(async()=>{if(dt()){console.log(vl("Login is managed by DevEco Code. Login from DevEco Code instead."));return}try{let n=await De.getUserInfo();if(n){console.log(Ht(`Already logged in, User Name:${n.userName}`));return}console.log(Ht("Starting login process...")),console.log(Ht("Press Enter to open browser for login...")),await _P();let e=await De.login();console.log(Ht(`Login successful. Logged in as ${e.userName}.`))}catch(n){throw n instanceof Ie||(n instanceof Error?n.message:String(n)).includes("Network connection failed")?n:new Error("Login failed",{cause:n})}});No.command("logout").description("Log out of your Huawei Developer account").action(async()=>{if(dt()){console.log(vl("Login is managed by DevEco Code. Log out from DevEco Code instead."));return}try{let n=await De.logout();console.log(n?Ht("Logout successful"):Ht("Already logged out."))}catch(n){throw new Error("Logout failed",{cause:n})}});No.command("status").description("Show the currently logged-in user").action(async()=>{let n=await De.getUserInfo();if(!n){console.log(Ht("Not logged in"));return}console.log(Ht(`Current user: ${n.userName}`))});var FP=No.command("team").description("Team-related commands");FP.command("list").description("List team accounts the current user has joined").action(async()=>{try{let n=await sn();console.log(MP(n.teamList))}catch(n){if(n instanceof Ie){console.log(vl(n.message));return}throw n}});var zf=No;import{Command as KP}from"commander";import{green as XP,red as Fo,cyan as hm,yellow as gm,dim as ym}from"colorette";import ZP from"p-limit";import jP from"ora";var ut=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=jP(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 Yf from"fs";import*as Jf from"path";var Kf=["DevEco"];async function As(){let n=await x.get(it.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 HP(n){let e=[],t=it.DEFAULT_PAGE_SIZE,r=1;for(;;){let o=await x.post(it.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:r,pageSize:t,tagIds:[n]}}),i=Ds(o,"Skills API");if(e.push(...i.data.list),i.data.list.length<t)break;r++}return e}async function Sl(n){let e=new Map,t=n.map(o=>HP(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=>!Kf.includes(i.name)))}async function $P(n,e){let t=await x.post(it.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:it.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return Ds(t,"Skills API").data.list}async function bl(n,e){let t=new Map,r=e.map(i=>$P(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=>!Kf.includes(s.name)))}function Xf(n){let e=[],t=Dt();for(let[,r]of Object.entries(t)){let o=Jf.join(r.path,n);Yf.existsSync(o)&&e.push(r.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!==it.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Zf(n){let e=`${it.SKILL_API_BASE}/${n}/checksum`,t=await x.get(e);return Ds(t,"Checksum API").data}import UP from"adm-zip";import BP from"crypto";import em from"fs";import ie from"path";import{fileURLToPath as WP}from"url";import{red as GP}from"colorette";var $t=em.promises;function El(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}function Qf(n,e){let t=ie.resolve(e),r=ie.resolve(n),o=ie.relative(r,t);if(o.startsWith("..")||ie.isAbsolute(o))throw new Error(`Path traversal detected: ${e}.`)}function Pl(n){return ie.isAbsolute(n)?n:ie.resolve(process.cwd(),n)}function VP(n){return BP.createHash("sha256").update(n).digest("hex")}async function qP(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=VP(n),o=e.sha256.toLowerCase();if(r!==o)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function tm(n){let e=`${it.SKILL_API_BASE}/${n}/install?format=zip`,t=await x.getBinary(e),r=await Zf(n);return await qP(t,r),t}async function zP(n,e,t){El(t);let r=new UP(n),o=r.getEntries();try{await $t.stat(e)}catch{await $t.mkdir(e,{recursive:!0})}let i=ie.join(e,t);Qf(e,i);for(let s of o){let a=ie.join(i,s.entryName);Qf(i,a)}r.extractAllTo(i,!0)}async function Cl(n){let e=Dt();if(!e[n])throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(e).join(", ")}`);let r=ue[n];try{return await $t.access(r),!0}catch{return!1}}function Il(n){return Dt()[n].path}function Al(n,e){let r=Dt()[e],o="projectPath"in r?r.projectPath:ie.join("."+e,"skills");return ie.join(n,o)}async function YP(n,e,t){El(e);let r=ie.join(n,e);try{if(await $t.access(r),t)await $t.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 Dl(n,e,t){await zP(n,e,t),console.log(`Skill ${t} installed to ${ie.join(e,t)}.`)}async function Rl(n,e,t){let r=ie.join(e,t);await $t.mkdir(r,{recursive:!0});let o=ie.join(r,ie.basename(n));await $t.copyFile(n,o),console.log(`Skill ${t} installed to ${r}.`)}function nm(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(GP(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function Cr(n,e,t,r){try{let o=await e(),{shouldSkip:i}=await YP(o,n,r);return i?{success:!0,skipped:!0}:(await t(o),{success:!0})}catch(o){return nm(n,o,"Installation failed")}}async function Tl(n,e){try{El(n);let t=await e(),r=ie.join(t,n);try{await $t.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await $t.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return nm(n,t,"Removal failed")}}async function rm(n,e,t,r=!1){return Cr(n,()=>Il(e),o=>Dl(t,o,n),r)}async function om(n,e,t,r=!1){return Cr(n,()=>t,o=>Dl(e,o,n),r)}async function im(n,e,t,r,o=!1){return Cr(n,()=>Al(t,r),i=>Dl(e,i,n),o)}async function sm(n,e,t,r=!1){return Cr(n,()=>Il(t),o=>Rl(e,o,n),r)}async function am(n,e,t,r,o=!1){return Cr(n,()=>Al(t,r),i=>Rl(e,i,n),o)}async function cm(n,e,t,r=!1){return Cr(n,()=>t,o=>Rl(e,o,n),r)}async function lm(n,e){return Tl(n,()=>Il(e))}async function dm(n,e){return Tl(n,()=>e)}async function um(n,e,t){return Tl(n,()=>Al(e,t))}function pm(){let e=ie.dirname(WP(import.meta.url));for(;;){let t=ie.join(e,"SKILL.md");if(em.existsSync(t))return t;let r=ie.dirname(e);if(r===e)break;e=r}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import fm from"fs";import{cyan as JP}from"colorette";async function Lo(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await Cl(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function Oo(){let n=[],e=Dt();for(let t of Object.keys(e))await Cl(t)&&n.push(t);return n}function Mo(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(JP("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function an(n,e,t){if(!fm.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!fm.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function _o(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?Pl(n):void 0,resolvedProject:e?Pl(e):void 0}}async function Rs(n,e,t){let r=[],o=[],i;if(e?i=e:t&&n.agent?o=(await Lo(n.agent)).map(a=>({project:t,agent:a})):t?o=(await Oo()).map(a=>({project:t,agent:a})):n.agent?r=await Lo(n.agent):r=await Oo(),!i&&r.length===0&&o.length===0)throw new Error("No agents found. Install an AI agent (opencode, etc.) or use `--path` for a custom location.");return{agents:r,projectAgents:o,customPath:i}}async function QP(n){let e=await As();if(n.all)return(await Sl(e)).map(r=>r.enName);{let r=(await bl(n.skill,e)).find(o=>o.enName===n.skill);if(!r)throw new Error(`Skill "${n.skill}" not found`);return[r.enName]}}async function eC(n,e,t,r){let o=[];if(t.customPath){let i=await om(n,e,t.customPath,r);return o.push(i),o}for(let i of t.agents){let s=await rm(n,i,e,r);o.push(s)}for(let{project:i,agent:s}of t.projectAgents){let a=await im(n,e,i,s,r);o.push(a)}return o}function tC(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}=_o(n.path,n.project,n.agent);return t&&an(t,"Project directory",n.force),e&&an(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}async function nC(n,e,t){let r=await Rs(n,e,t);return{skillNames:await QP(n),targets:r}}async function rC(n,e,t,r){let o=[],i=n.length,s=ZP(5),a=n.map(c=>s(()=>oC(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 h=await a[c];if(!h.success){r.fail(),console.log(Fo(`${l}: Download failed - ${h.error}`)),o.push({success:!1});continue}r.stop();let w=await eC(l,h.buffer,e,t);o.push(...w)}return o}async function oC(n){try{let e=await tm(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 iC(n){let e=new ut;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=tC(n),{skillNames:o,targets:i}=await nC(n,t,r),s=await rC(o,i,n.force||!1,e);e.stop(),Mo(s)}catch(t){throw e.stop(),t}}function sC(n){let{resolvedPath:e,resolvedProject:t}=_o(n.path,n.project,n.agent);return t&&an(t,"Project directory"),e&&an(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function aC(n,e){let t=new ut;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:o}=sC(e);t.stop();let i=await cC(e,n,r,o);t.stop(),Mo(i)}catch(r){throw t.stop(),r}}function mm(n,e=""){if(n.length===0)throw new Error(`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function Ts(n,e){let t=[];for(let r of e){let o=r.type==="agent"?await lm(n,r.agent):await um(n,r.project,r.agent);t.push(o)}return t}async function cC(n,e,t,r){if(t)return[await dm(e,t)];if(r&&n.agent){let a=(await Lo(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return Ts(e,a)}if(r){let s=await Oo();mm(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return Ts(e,a)}if(n.agent){let a=(await Lo(n.agent)).map(c=>({type:"agent",agent:c}));return Ts(e,a)}let o=await Oo();mm(o,"or use --path for a custom location.");let i=o.map(s=>({type:"agent",agent:s}));return Ts(e,i)}var jo=new KP("skills").description("Manage HarmonyOS skills");jo.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 ut;try{e.start("Fetching skills...");let t=await As(),r=await Sl(t);if(r.length===0){e.stop(),console.log(gm("No skills available."));return}e.succeed(`Fetched ${r.length} skills`);for(let o of r)if(n.long){console.log(hm(o.enName)),console.log(ym(o.description));let i=Xf(o.enName);i.length>0&&console.log(XP(`Installed for: ${i.join(", ")}`)),console.log()}else console.log(o.enName)}catch(t){e.stop(),console.error(Fo(t.message)),process.exit(1)}});jo.command("find <keyword>").description("Search skills by keyword").action(async n=>{let e=new ut;try{e.start("Searching skills...");let t=await As(),r=await bl(n,t);if(r.length===0){console.log(gm(`No skills found matching '${n}'.`)),e.stop();return}e.succeed(`Found ${r.length} skills.`);for(let o of r)console.log(hm(o.enName)),console.log(ym(o.description)),console.log()}catch(t){e.stop(),console.error(Fo(t.message)),process.exit(1)}});jo.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 iC(n)}catch(e){console.error(Fo(e.message)),process.exit(1)}});jo.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 aC(n.skill,n)}catch(e){console.error(Fo(e.message)),process.exit(1)}});var wm=jo;import{Command as dC,InvalidArgumentError as xs}from"commander";import{cyan as ks}from"colorette";function zn(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=lr(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 kl=[800,1500,2500];function lC(n){return new Promise(e=>setTimeout(e,n))}function vm(){return b()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device."}var Ir=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=re.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(`
|
|
1282
|
+
`)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let o=t[0];return f(ks(`Using device serial: ${o}`)),o}if(e&&t.includes(e))return f(ks(`Using device serial: ${e}`)),e;let r=await this.loadConnectedDevicesByName();if(e){let o=this.findDeviceByArg(r,e);if(o)return f(ks(`Using device: ${o.name} (${o.serial})`)),o.serial;let i=this.formatConnectedDeviceList(r);throw new Error(`Device '${e}' not found.
|
|
1283
1283
|
Available devices:
|
|
1284
|
-
${i}`)}if(r.length===1){let o=r[0];return f(
|
|
1284
|
+
${i}`)}if(r.length===1){let o=r[0];return f(ks(`Using device: ${o.name} (${o.serial})`)),o.serial}throw new Error("Multiple devices found. Specify a target device using `--device <name>` or `--device <serial>`.\nAvailable devices:\n"+this.formatConnectedDeviceList(r))}async getConnectedDeviceSerials(){let e=await this.deviceManager.listDevices();if(e.length===0)throw new Error(vm());return e.map(t=>t.serial)}async getConnectedDevices(){let e=await this.deviceManager.listDevicesWithName();if(e.length===0)throw new Error(vm());return e}async getPidForBundle(e,t,r){f(`Retrieving PID for bundle ${r}`),R.assertBundleNameStrict(r);let o=await ae(e,["-t",t,"shell","pidof",r]),i=zn(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 f(`Found PID for ${r}: ${a}`),a}return f(`No PID found for bundle: ${r}`),null}async resizeHilogBuffer(e,t,r){f(`Setting hilog buffer size to: ${r}`);let o=await ae(e,["-t",t,"shell","hilog","-G",r]),i=zn(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&&(R.assertHilogToken(e.tag,"tag"),r.push("-T",e.tag)),e.level&&(R.assertHilogLevel(e.level),r.push("-L",e.level)),e.domain&&(R.assertHilogToken(e.domain,"domain"),r.push("-D",e.domain)),t&&r.push("-P",t),e.keyword&&(R.assertHilogKeyword(e.keyword),r.push("-e",R.quotePosixShellArg(e.keyword))),r.join(" ")}async followHilog(e,t,r,o,i){let a=await ap(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+kl.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||lr(a.stderr)!=="transient"||c>=s-1)return a;f(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${kl[c]}ms`),await lC(kl[c])}return a}async runHilogStreamingCollect(e,t,r){return this.runHilogWithSpawnRetry(e,t,()=>{},o=>{f(`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);f(`Ready to run hilog snapshot command: ${s} ${a.join(" ")}`);let c=await this.runHilogStreamingCollect(s,a,"a hilog snapshot streaming read"),l=zn(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=R.filterLogsByRelativeWindow(c.stdout||c.stderr,r.fromSeconds,r.toSeconds);d=R.getLastLines(d,r.tail),d.trim()&&console.log(d)}async getHilogOnce(e,t,r,o){let[i,s]=this.buildHilogCommand(e,t,r,o);f(`Ready to run hilog command: ${i} ${s.join(" ")}`);let a=await this.runHilogStreamingCollect(i,s,"a single hilog streaming read"),c=zn(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=R.filterLogsByRelativeWindow(l,r.fromSeconds,r.toSeconds);return d=R.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);f(`Ready to run hilog command which contain \`follow\` and \`tail\`: ${i} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(i,s,this.createFollowLineHandler(),l=>{f(`Spawn error during hilog follow: ${l.message}`)},()=>{}),c=zn(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 Error(`No running process found for bundle '${t.bundleName}'. Ensure the app is launched on the device before fetching logs.`);return t.logSize&&await this.resizeHilogBuffer(r,e,t.logSize),t.isFollow?await this.runHilogFollow(r,e,t,o||""):await this.getHilogOnce(r,e,t,o||"")}async getCrashLog(e,t){f(`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"];f(`Running command: ${e} ${o.join(" ")}`);let i=await this.runHilogStreamingCollect(e,o,"a crash log list streaming read"),s=zn(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 f(`Crash logs list output:
|
|
1285
1285
|
${i.stdout}`),this.parseCrashLogFilenames(i.stdout,r)}parseCrashLogFilenames(e,t){return e.split(`
|
|
1286
|
-
`).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>{try{return R.assertCrashFilename(r),!0}catch{return!1}}).filter(r=>t?r.toLowerCase().includes(t.toLowerCase()):!0)}async fetchCrashLogContent(e,t,r){f(`Fetching latest crash log file: ${r}`);let o=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];f(`Executing command: ${e} ${o.join(" ")}`);let i=await this.runHilogStreamingCollect(e,o,"a crash log streaming read"),s=qn(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 wm}from"colorette";import sC from"ora";function aC(n){try{return R.parsePositiveInteger(n,"tail")}catch{throw new ks("`tail` must be a positive integer.")}}function ym(n,e){try{return R.parseDurationToSeconds(n,e)}catch{throw new ks(`${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 cC(n){try{return R.assertHilogLevel(n),n}catch{throw new ks("`level` must be one of: D, I, W, E, F.")}}function lC(n){try{return R.assertBundleNameStrict(n),n}catch(e){throw new ks(e.message)}}function dC(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.");R.assertRelativeTimeRange(n.from,n.to)}async function uC(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 pC(n,e,t,r){let o=R.filterLogsByRelativeWindow(n,t,r);return e.tail?R.getLastLines(o,e.tail):o}var fC=new iC("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(wm(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",cC).option("--bundle-name <bundle-name>","Filter by application bundle name",lC).option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",aC).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>ym(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>ym(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await mC(n)});async function mC(n){let e=sC({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),dC(n);let r=n.from,o=n.to,i=await A.new(),s=new Cr(i),a=await s.selectDevice(n.device);a||(t(),process.exit(1)),f(Rl(`deviceId: ${a}`)),f(Rl(`type: ${n.crash?"Crash logs":"Common logs"}`)),f(Rl("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await uC(s,a,n,r,o);t(),n.crash&&c&&(c=pC(c,n,r,o)),c&&console.log(c)}catch(r){t(),console.error(wm(r.message)),process.exit(1)}}var vm=fC;import Ho from"path";import Ut from"fs";import kl from"process";import Rm from"os";import{Command as DC}from"commander";import{green as Cm,red as Tl,cyan as RC,yellow as Im}from"colorette";import ce from"fs-extra";import _ from"path";import*as bm from"os";import{fileURLToPath as hC}from"url";var Sm={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"}},gC=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function yC(){let n=import.meta.url,e=hC(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 Em(n,e){ce.mkdirSync(e,{recursive:!0});for(let t of ce.readdirSync(n,{withFileTypes:!0})){let r=_.join(n,t.name),o=_.join(e,t.name);if(t.isDirectory()){Em(r,o);continue}ce.existsSync(o)||(ce.mkdirSync(_.dirname(o),{recursive:!0}),ce.copyFileSync(r,o))}}function jo(n,e){let t=ce.readFileSync(n,"utf-8"),r=t;for(let[o,i]of e)r=r.replaceAll(o,i);r!==t&&ce.writeFileSync(n,r,"utf-8")}function wC(n){if(Sm[n])return Sm[n];if(n>=26){let e=`${n}.0.0`;return{sdkVersion:e,modelVersion:e}}}function vC(n,e){if(e===22)return;let t=wC(e);t&&(jo(_.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),jo(_.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),jo(_.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function SC(n){return gC.filter(t=>!ce.existsSync(_.join(n,t))).length===0}function bC(){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 EC(n){return bm.platform()==="darwin"?_.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):_.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function PC(n,e){let t=EC(e);if(!ce.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);ce.existsSync(s)&&(ce.mkdirSync(_.dirname(a),{recursive:!0}),ce.copyFileSync(s,a))}return!0}function CC(n){let e=bC(),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);ce.mkdirSync(_.dirname(o),{recursive:!0}),ce.writeFileSync(o,e)}}function IC(n,e){e&&PC(n,e)||CC(n)}function AC(n){let e=[_.join(n,"gitignore.txt"),_.join(n,"entry","gitignore.txt")];for(let t of e)if(ce.existsSync(t)){let r=_.dirname(t);ce.renameSync(t,_.join(r,".gitignore"))}}function Pm(n,e,t,r,o){let i=yC();if(!ce.existsSync(i))throw new Error(`Template directory not found: ${i}`);ce.mkdirSync(n,{recursive:!0}),Em(i,n),AC(n),IC(n,o),jo(_.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),jo(_.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),vC(n,r);let s=SC(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function TC(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 Tm(n){if(Rm.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function Am(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=Rm.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=Tm(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 kC(n){let e=n,t=Ho.parse(n).root;for(;e!==t;){if(Ut.existsSync(e))return e;e=Ho.dirname(e)}return Ut.existsSync(t)?t:null}function Dm(n){let e=kC(n);if(!e)throw new Error(`No existing parent directory found for '${n}'. Cannot create project directory.`);try{Ut.accessSync(e,Ut.constants.W_OK)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}let t=Ho.join(e,`.deveco_write_test_${Date.now()}`);try{Ut.writeFileSync(t,"test"),Ut.unlinkSync(t)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}}function xC(n){return`com.example.${n.toLowerCase()}`}function NC(n,e){if(e){let o=Tm(e),i=Ho.resolve(o);if(Ut.existsSync(i)){if(Ut.readdirSync(i).length>0)throw new Error(`Directory '${i}' is not empty. Cannot create project here.`)}else Dm(i);return i}let t=kl.cwd(),r=Ho.join(t,n);if(Ut.existsSync(r))throw new Error(`Directory '${r}' already exists. Cannot create project here.`);return Dm(r),r}function LC(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}. No SDK detected; default supported range is API 17-${r}.`);return o}return t!==void 0?t:23}async function OC(){try{return await A.new()}catch(n){console.error(Im(`Toolchain not found: ${n.message}`)),console.log(Im("Use placeholder API level instead."));return}}var MC=new DC("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(Tl("Error: --app-name is required")),kl.exit(1));let e=n.appName;TC(e);let t=n.bundleName||xC(e);R.assertBundleNameStrict(t),n.projectPath&&Am(n.projectPath);let r=NC(e,n.projectPath);Am(r),console.log(RC("Initializing project...")),console.log(`Project path: ${r}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let o=await OC(),i=LC(n,o);console.log(`API level: ${i}`);let s=o?.devecoStudioPath,a=Pm(r,e,t,i,s);console.log(`
|
|
1287
|
-
`+
|
|
1288
|
-
Failed to create project.`)),console.error(
|
|
1286
|
+
`).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>{try{return R.assertCrashFilename(r),!0}catch{return!1}}).filter(r=>t?r.toLowerCase().includes(t.toLowerCase()):!0)}async fetchCrashLogContent(e,t,r){f(`Fetching latest crash log file: ${r}`);let o=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];f(`Executing command: ${e} ${o.join(" ")}`);let i=await this.runHilogStreamingCollect(e,o,"a crash log streaming read"),s=zn(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 xl,red as bm}from"colorette";import uC from"ora";function pC(n){try{return R.parsePositiveInteger(n,"tail")}catch{throw new xs("`tail` must be a positive integer.")}}function Sm(n,e){try{return R.parseDurationToSeconds(n,e)}catch{throw new xs(`${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 fC(n){try{return R.assertHilogLevel(n),n}catch{throw new xs("`level` must be one of: D, I, W, E, F.")}}function mC(n){try{return R.assertBundleNameStrict(n),n}catch(e){throw new xs(e.message)}}function hC(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.");R.assertRelativeTimeRange(n.from,n.to)}async function gC(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 yC(n,e,t,r){let o=R.filterLogsByRelativeWindow(n,t,r);return e.tail?R.getLastLines(o,e.tail):o}var wC=new dC("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(bm(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",fC).option("--bundle-name <bundle-name>","Filter by application bundle name",mC).option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",pC).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>Sm(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>Sm(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await vC(n)});async function vC(n){let e=uC({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),hC(n);let r=n.from,o=n.to,i=await A.new(),s=new Ir(i),a=await s.selectDevice(n.device);a||(t(),process.exit(1)),f(xl(`deviceId: ${a}`)),f(xl(`type: ${n.crash?"Crash logs":"Common logs"}`)),f(xl("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await gC(s,a,n,r,o);t(),n.crash&&c&&(c=yC(c,n,r,o)),c&&console.log(c)}catch(r){t(),console.error(bm(r.message)),process.exit(1)}}var Em=wC;import $o from"path";import Ut from"fs";import Ll from"process";import xm from"os";import{Command as NC}from"commander";import{green as Dm,red as Nl,cyan as LC,yellow as Rm}from"colorette";import ce from"fs-extra";import _ from"path";import*as Cm from"os";import{fileURLToPath as SC}from"url";var Pm={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"}},bC=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function EC(){let n=import.meta.url,e=SC(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){ce.mkdirSync(e,{recursive:!0});for(let t of ce.readdirSync(n,{withFileTypes:!0})){let r=_.join(n,t.name),o=_.join(e,t.name);if(t.isDirectory()){Im(r,o);continue}ce.existsSync(o)||(ce.mkdirSync(_.dirname(o),{recursive:!0}),ce.copyFileSync(r,o))}}function Ho(n,e){let t=ce.readFileSync(n,"utf-8"),r=t;for(let[o,i]of e)r=r.replaceAll(o,i);r!==t&&ce.writeFileSync(n,r,"utf-8")}function PC(n){if(Pm[n])return Pm[n];if(n>=26){let e=`${n}.0.0`;return{sdkVersion:e,modelVersion:e}}}function CC(n,e){if(e===22)return;let t=PC(e);t&&(Ho(_.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),Ho(_.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),Ho(_.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function IC(n){return bC.filter(t=>!ce.existsSync(_.join(n,t))).length===0}function AC(){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 DC(n){return Cm.platform()==="darwin"?_.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):_.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function RC(n,e){let t=DC(e);if(!ce.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);ce.existsSync(s)&&(ce.mkdirSync(_.dirname(a),{recursive:!0}),ce.copyFileSync(s,a))}return!0}function TC(n){let e=AC(),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);ce.mkdirSync(_.dirname(o),{recursive:!0}),ce.writeFileSync(o,e)}}function kC(n,e){e&&RC(n,e)||TC(n)}function xC(n){let e=[_.join(n,"gitignore.txt"),_.join(n,"entry","gitignore.txt")];for(let t of e)if(ce.existsSync(t)){let r=_.dirname(t);ce.renameSync(t,_.join(r,".gitignore"))}}function Am(n,e,t,r,o){let i=EC();if(!ce.existsSync(i))throw new Error(`Template directory not found: ${i}`);ce.mkdirSync(n,{recursive:!0}),Im(i,n),xC(n),kC(n,o),Ho(_.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),Ho(_.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),CC(n,r);let s=IC(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function OC(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 Nm(n){if(xm.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function Tm(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=xm.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=Nm(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 MC(n){let e=n,t=$o.parse(n).root;for(;e!==t;){if(Ut.existsSync(e))return e;e=$o.dirname(e)}return Ut.existsSync(t)?t:null}function km(n){let e=MC(n);if(!e)throw new Error(`No existing parent directory found for '${n}'. Cannot create project directory.`);try{Ut.accessSync(e,Ut.constants.W_OK)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}let t=$o.join(e,`.deveco_write_test_${Date.now()}`);try{Ut.writeFileSync(t,"test"),Ut.unlinkSync(t)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}}function _C(n){return`com.example.${n.toLowerCase()}`}function FC(n,e){if(e){let o=Nm(e),i=$o.resolve(o);if(Ut.existsSync(i)){if(Ut.readdirSync(i).length>0)throw new Error(`Directory '${i}' is not empty. Cannot create project here.`)}else km(i);return i}let t=Ll.cwd(),r=$o.join(t,n);if(Ut.existsSync(r))throw new Error(`Directory '${r}' already exists. Cannot create project here.`);return km(r),r}function jC(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}. No SDK detected; default supported range is API 17-${r}.`);return o}return t!==void 0?t:23}async function HC(){try{return await A.new()}catch(n){console.error(Rm(`Toolchain not found: ${n.message}`)),console.log(Rm("Use placeholder API level instead."));return}}var $C=new NC("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(Nl("Error: --app-name is required")),Ll.exit(1));let e=n.appName;OC(e);let t=n.bundleName||_C(e);R.assertBundleNameStrict(t),n.projectPath&&Tm(n.projectPath);let r=FC(e,n.projectPath);Tm(r),console.log(LC("Initializing project...")),console.log(`Project path: ${r}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let o=await HC(),i=jC(n,o);console.log(`API level: ${i}`);let s=o?.devecoStudioPath,a=Am(r,e,t,i,s);console.log(`
|
|
1287
|
+
`+Dm("Project created successfully.")),console.log(`Project root: ${a.projectRoot}`),console.log(`App name: ${a.appName}`),console.log(`Bundle name: ${a.bundleName}`),console.log(`API level: ${a.apiLevel}`),console.log(Dm("Template integrity check passed."))}catch(e){let t=e;console.error(Nl(`
|
|
1288
|
+
Failed to create project.`)),console.error(Nl(t.message)),Ll.exit(1)}}),Lm=$C;import{Command as zC}from"commander";import{red as YC,cyan as $m}from"colorette";import UC from"fs";import Ns from"path";import{cyan as BC}from"colorette";import*as Ls from"smol-toml";var Ar=UC.promises;async function WC(n){try{let e=await Ar.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 GC(n){try{let e=await Ar.readFile(n,"utf8");return e.trim()===""?{}:Ls.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 VC(n,e){let t=Ns.dirname(n);await Ar.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await Ar.writeFile(n,r,"utf8")}async function qC(n,e){let t=Ns.dirname(n);await Ar.mkdir(t,{recursive:!0});let r=Ls.stringify(e);await Ar.writeFile(n,r,"utf8")}function Om(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function Mm(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 _m(n,e){return n.format==="codex"?GC(e):WC(e)}async function Fm(n,e,t){return n.format==="codex"?qC(e,t):VC(e,t)}async function jm(n,e,t=!1){let r=Qt[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Qt).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 _m(r,r.globalConfigPath);if(Om(o,r.mcpServersKey,vt)&&!t)return console.log(`MCP server ${vt} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let i=Mi(r,void 0);return Mm(o,r.mcpServersKey,vt,i,t),await Fm(r,r.globalConfigPath,o),console.log(`MCP server ${vt} 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=Qt[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Qt).join(", ")}`};let o=Ns.isAbsolute(r.projectConfigPath)?r.projectConfigPath:Ns.join(e,r.projectConfigPath);try{let i=await _m(r,o);if(Om(i,r.mcpServersKey,vt)&&!t)return console.log(`MCP server ${vt} already configured in ${o}.`),{success:!0,skipped:!0,configPath:o,agentName:n,installType:"project"};let s=Mi(r,e);return Mm(i,r.mcpServersKey,vt,s,t),await Fm(r,o,i),console.log(`MCP server ${vt} 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 Hm(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(BC("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 JC(n,e,t){if(n.customPath)return[await cm(Ml,e,n.customPath,t.force)];let r=[...n.projectAgents.map(({project:s,agent:a})=>()=>am(Ml,e,s,a,t.force)),...n.agents.map(s=>()=>sm(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}async function KC(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 XC(n,e){let t=[];for(let r of n){if(!Qt[r])continue;let i=await jm(r,process.cwd(),e);t.push(i)}return t}async function ZC(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 KC(s,e,r):await XC(s.agents,r);a.length>0&&(console.log($m("MCP Configuration:")),Hm(a))}async function QC(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}=_o(n.path,n.project,n.agent);t&&an(t,"Project directory",n.force),e&&an(e,"Directory",n.force);let r=await Rs(n,e,t);if(n.mcp){await ZC(r,t,n);return}let o=pm(),i=await JC(r,o,n);console.log(),i.length>0&&(console.log($m("Skill Installation:")),Mo(i))}var eI=new zC("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 QC(n)}catch(e){console.error(YC(e.message)),process.exit(1)}}),Um=eI;import{Command as qI}from"commander";import{McpServer as xI}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as NI}from"@modelcontextprotocol/sdk/server/stdio.js";import*as mn from"path";import*as nh from"fs";import{z as de}from"zod";var Os=class{tools=new Map;add(e,t){return this.tools.set(e.name,{definition:e,handler:t}),this}getAll(){return Array.from(this.tools.values())}registerToServer(e){for(let{definition:t,handler:r}of this.getAll())e.registerTool(t.name,{description:t.description,inputSchema:t.inputSchema},(async o=>r(o)))}};function _l(){return new Os}import*as Me from"fs";import*as le from"path";import{z as jl}from"zod";function Bm(n){return"method"in n&&!("id"in n)}import{spawn as tI}from"child_process";import{EventEmitter as nI}from"events";import*as Dr from"fs";import*as Wm from"path";var cn=class extends nI{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;ensureDirectories(){let t=Wm.join(this.config.logPath,"lspLog");return Dr.existsSync(t)||Dr.mkdirSync(t,{recursive:!0}),Dr.existsSync(this.config.indexingDataLocation)||Dr.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){let r=this.ensureDirectories();m.info(`[LspClient] serverMaxSize=${t}MB`);let o=U(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=this.config.nodePath;m.info(`[LspClient] nodePath: ${s}`),this.process=tI(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
|
|
1289
1289
|
\r
|
|
1290
1290
|
${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this.buffer.indexOf(`\r
|
|
1291
1291
|
\r
|
|
1292
|
-
`);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),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 ln=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)o(t,r),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}`),o(),this.timeouts.delete(e)},r);this.timeouts.set(e,s)}clearTimeout(e){let t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e))}deleteCallback(e){this.callbacks.delete(e)}hasCallback(e){return this.callbacks.has(e)||this.pending.has(e)}clear(e){this.clearTimeout(e);let t=this.pending.get(e);t&&(t.reject(new Error(`Request '${t.method}' (id=${e}) cancelled`)),this.pending.delete(e)),this.callbacks.delete(e)}rejectAll(e){for(let[,t]of this.pending)t.reject(e);this.pending.clear();for(let[,t]of this.timeouts)clearTimeout(t);this.timeouts.clear(),this.callbacks.clear()}};var Os=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var Dr=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 Um=20*1e3,ZC=30*1e3,Ms=class{client;nextRequestId=1;stopOnce=null;callbacks=new Dr;requestCallbacks=new ln;diagnosticMap=new Map;initProgressReset=null;constructor(e){this.client=new cn(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,Ye);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 Os(t)),this.registerDiagnosticTimeout(t)),this.client.sendNotification(y.DID_OPEN,e)}sendDidChange(e){let t=e.textDocument.uri,r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t)),this.client.sendNotification(y.DID_CHANGE,e)}closeFile(e){this.cleanupDiagnosticState(e.textDocument.uri),this.client.sendNotification(y.DID_CLOSE,e)}sendLspRequest(e,t,r=ZC){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){D(e)&&this.broadcastToClients({jsonrpc:T,method:y.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,y.PUBLISH_DIAGNOSTICS,Um,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${Um}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:T,method:y.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var _s=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 Ol(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)}},Ol=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var QC={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"},eI={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate",ON_FORCE_OPEN_FILE:"aceProject/onForceOpenFile",ON_PACKAGE_CHANGE_FINISH:"aceProject/onPackageChangeFinish",TEXT_DOCUMENT_ON_ASYNC_DEFINITION:"textDocument/onAsyncDefinition",ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:"textDocument/onDidChangePackageDependencies",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",REFERENCES:"textDocument/references",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",BROADCAST:"lsp/broadcast",ARKTS_ERROR:"arkts/error",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing"},k={...QC,...eI},dn={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"},Bm=new Set([1e3,2e3,3e3,3001]);function tI(n){if(!D(n))return!1;let e=n.textDocument;return D(e)&&typeof e.uri=="string"}function nI(n){return D(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function rI(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 Fs=class n{client;isInitialized=!1;stopOnce=null;callbacks=new Dr;requestCallbacks=new ln;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;constructor(e){this.client=new cn(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:T,method:k.EXIT,params:{}}),dn.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(k.BROADCAST),this.callbacks.register(k.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(k.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(k.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(k.INDEXING_PROGRESS_UPDATE,e)}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}sendInitialize(e,t){this.client.send("initialize",e,t)}sendInitialized(e){this.client.sendRaw(JSON.stringify({jsonrpc:T,method:k.INITIALIZED,params:{editors:e}}),dn.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:T,id:0,result:{}}),dn.EMPTY)}sendAsyncRequest(e,t,r,o){if(!D(t)){m.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!tI(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=at(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:T,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(!nI(r)){m.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:T,method:k.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),k.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!D(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){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:T,method:k.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),dn.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let o=at(t);e.textDocument.uri=o,m.info(`[LSP] onAsyncOpenFile, uri: ${o}`);let i=this.diagnosticMap.get(o);i||(i=new _s(o),this.diagnosticMap.set(o,i),this.registerDiagnosticTimeout(o,k.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(i.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:T,method:k.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),dn.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=at(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,k.PUBLISH_DIAGNOSTICS)),m.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:T,method:k.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),dn.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=at(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:T,method:k.DID_CLOSE,params:{textDocument:{uri:r}}}),dn.DID_CLOSE)}getDiagnosticMessage(e){let t=at(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,k.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:T,method:k.ARKTS_ERROR,params:{message:e.message}})}handleLspMessage(e){let t=e.method;t!==void 0&&(!this.isInitialized&&this.handlePreInitMessage(t,e)||this.handlePostInitMessage(t,e))}handlePreInitMessage(e,t){switch(e){case k.MODULE_INIT_FINISH:return m.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(k.MODULE_INIT_FINISH),this.callbacks.unregister(k.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case k.INDEXING_PROGRESS_UPDATE:return m.info(`[LSP] onIndexingProgressUpdate: ${rI(t.params)}`),this.callbacks.invoke(k.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case k.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case k.ON_PACKAGE_CHANGE_FINISH:m.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case k.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case k.ON_ASYNC_HOVER:this.handleAsyncResponse(t,k.HOVER);return;case k.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,k.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case k.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,k.REFERENCES);return;default: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;D(t)&&D(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:T,method:k.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(!D(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,k.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(Bm)&&this.finalizeDiagnostic(t,k.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 Go from"path";import*as Gs from"path";var js=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var Hs=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var $s=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var Us=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var Bs=class{typeSetting=new $s;parameterNames=new Us};var Ws=class{constructor(e,t,r,o){this.rootUri=e;this.lspServerWorkspacePath=U(Gs.dirname(t)),this.indexingDataLocation=U(o),this.loggerPath=U(Gs.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new js;gutterIconsSetting=new Hs;inlayHintsSetting=new Bs;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as Wm from"path";var $o=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(U(Wm.join(e,"src","main","resources")))}};var oI="OS",Rr=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${oI}`;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 $o(e)):this.buildProfileParam=new $o}toString(){return JSON.stringify(this)}};var Tr=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as Re from"path";import*as Nr from"fs";var Vs=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 kr=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 xr=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:st.OH_PACKAGE_JSON5},Uo=`${L.HVIGOR_CACHE}/${L.DEPENDENCY}`,Yn=`${L.DEPENDENCY}${L.JSON5}`,nW=st.SYNC_OUTPUT_PATH;var Bo=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,L.OH_PACKAGE_JSON5),r=Ge(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"){m.error(`${i} package dependency value is not String ${t}`);continue}let a=new xr;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,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)),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 Wo from"fs";import*as un from"path";import iI from"json5";var zs=class n{projectPath;static FILE_DEPENDENCY_PREFIX="file:";fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[];storePathMap=new Map;lockFileCache=null;lockFileParsed=!1;constructor(e=""){this.projectPath=e}parseDependencies(e){if(!this.ensureLockFileParsed())return!1;let t=this.lockFileCache;return this.extractDependencies(t.modules,t.storePathMap,e),!0}ensureLockFileParsed(){if(this.lockFileParsed)return this.lockFileCache!==null;this.lockFileParsed=!0;let e=this.getLockFilePath(),t=this.readLockFile(e);if(!t)return!1;let r=this.validateLockFile(t);return r.valid?(this.lockFileCache={modules:r.modules,storePathMap:this.parseStorePathMap(r.packages)},!0):!1}getLockFilePath(){return un.join(this.projectPath,L.OH_MODULES_PATH,L.OHPM_PATH,L.LOCK_JSON5_FILE)}readLockFile(e){if(!Wo.existsSync(e))return m.error("lock file does not exist"),this.clearDependencies(),null;try{let t=Wo.readFileSync(e,"utf8"),r=iI.parse(t);return r||(m.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return m.error("Error parsing lock.json5:",t),this.clearDependencies(),null}}validateLockFile(e){if(!D(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,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;for(let[r,o]of Object.entries(e)){if(!D(o)){m.error(`${r} value is not json object`);continue}typeof o.storePath=="string"&&t.set(r,o.storePath)}return t}getDependencyList(e,t,r){if(!D(e))return[];for(let[o,i]of Object.entries(e))if(D(i)){let s=typeof i.name=="string"?i.name:"";if(r==="."&&s===""||s===r)return this.getFinalDependencyList(e,t,o)}return[]}getFinalDependencyList(e,t,r){let o=e[r];if(!D(o))return m.error("moduleJsonObject is null"),[];let i=[],s=o[t];if(!D(s))return[];for(let[a,c]of Object.entries(s)){if(!D(c))continue;let l=typeof c.specifier=="string"?c.specifier:"",d=typeof c.version=="string"?c.version:"",h=new xr;h.name=a,h.version=d.startsWith(n.FILE_DEPENDENCY_PREFIX)?d.substring(n.FILE_DEPENDENCY_PREFIX.length):d,this.parseDependencyPath(h,r,a,l,d);let w=`${a}@${d}`;this.storePathMap.has(w)&&(h.storePath=this.storePathMap.get(w)||""),i.push(h)}return i}parseDependencyPath(e,t,r,o,i){let s=un.resolve(this.projectPath,un.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=un.isAbsolute(a)?a:un.resolve(this.projectPath,a);Wo.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",a)}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};function Gm(n){return D(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var Jn=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new xt(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=Re.join(t,Uo),o=Re.join(r,Yn);if(!Nr.existsSync(r)||!Nr.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 kr(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];Gm(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=Re.join(r,Uo),i=Re.join(o,Yn);if(!Nr.existsSync(o)||!Nr.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 kr(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(!Gm(l))continue;let d=l.name;if(s&&!s.has(d))continue;let h=Re.resolve(this.projectPath,l.srcPath),w=Re.join(o,d),v=U(h),I=this.buildModuleDependencies(d,v,w,a);I.moduleName=d,t.push(I)}return t}parseSingleModule(e,t,r,o){let i=e.name,s=Re.resolve(this.projectPath,e.srcPath),a=Re.join(t,i),c=U(s),l=new Rr(c),d=this.buildModuleDependencies(i,c,a,r);this.parseModuleJson5(c,l);let h=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=i,l.moduleType=i,l.packageName=i,l.moduleDependencies=d,l.moduleJsonParam=new Tr(h),o.push(l)}buildModuleDependencies(e,t,r,o){let i=new kr(this.projectPath,e,t);Bo.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 Vs;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=Re.join(e,L.OH_PACKAGE_JSON5);if(!Nr.existsSync(r))return;Bo.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 zs(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=Re.join(e,"src","main","module.json5"),o=Ge(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=Re.join(e,"src","main","resources","base","profile","main_pages.json"),r=Ge(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=Re.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=Ge(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=Re.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!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 Ys=class{constructor(e=[]){this.valueSet=e}valueSet};var Lr=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var Vm=(P=>(P[P.File=1]="File",P[P.Module=2]="Module",P[P.Namespace=3]="Namespace",P[P.Package=4]="Package",P[P.Class=5]="Class",P[P.Method=6]="Method",P[P.Property=7]="Property",P[P.Field=8]="Field",P[P.Constructor=9]="Constructor",P[P.Enum=10]="Enum",P[P.Interface=11]="Interface",P[P.Function=12]="Function",P[P.Variable=13]="Variable",P[P.Constant=14]="Constant",P[P.String=15]="String",P[P.Number=16]="Number",P[P.Boolean=17]="Boolean",P[P.Array=18]="Array",P[P.Object=19]="Object",P[P.Key=20]="Key",P[P.Null=21]="Null",P[P.EnumMember=22]="EnumMember",P[P.Struct=23]="Struct",P[P.Event=24]="Event",P[P.Operator=25]="Operator",P[P.TypeParameter=26]="TypeParameter",P))(Vm||{}),qm=()=>Object.values(Vm).filter(n=>typeof n=="number");var Js=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Ks=class{applyEdit=!0;workspaceEdit=new Js;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new Ys(qm());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Lr;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Xs=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Zs=class{constructor(e=[]){this.valueSet=e}valueSet};var Qs=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var zm=(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))(zm||{}),Ym=()=>Object.values(zm).filter(n=>typeof n=="number");var ea=class{completionItemKind=new Zs(Ym());completionItem=new Qs;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var ta=class{synchronization=new Xs;completion=new ea;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 Lr;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var na=class{workspace=new Ks;textDocument=new ta;notebookDocument=null;window=null;general=null;experimental=null};var ra=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};var oa=class{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=[];sdkPath;rootUri;nodeMaxOldSpaceSize;nodePath;useStandardProtocol;get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}constructor(e){this.sdkPath=e.sdkPath,this.rootUri=e.workspaceRoot,this.nodeMaxOldSpaceSize=e.nodeMaxOldSpaceSize,this.nodePath=e.nodePath,this.useStandardProtocol=e.useStandardProtocol,this.serverPath=e.useStandardProtocol?Go.resolve(Go.dirname(e.arktsLangServerPath),"standardIndex","index.js"):e.arktsLangServerPath,this.logPath=Wu(),this.indexLogPath=e.indexLogPath||this.logPath;let t={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath,nodePath:this.nodePath};this.messageHandle=e.useStandardProtocol?new Ms(t):new Fs(t),this.messageHandle.setBroadcastToClients(r=>this.onLspMessage(r))}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=at(this.rootUri),i=new Ws(o,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new Jn(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),i.modules=s;let l=Yi(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(l),this.currentParams=new ra(o,i,new na),this.useStandardProtocol){let d=this.messageHandle;await d.sendInitializeResettable(this.currentParams,Ye),m.info("[LSP] initialize response received"),d.broadcastToClients({jsonrpc:T,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:T,method:y.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((o,i)=>{r.onIndexingProgressUpdate(i),r.onInitializationCompleted(o)},"LSP initialization",Ye),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=D(r)?r:{};m.info(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let i={jsonrpc:T,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 Jn(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,h)=>{(o.dependencies??={})[d]=this.makeDeleteEntry(d,h)}),this.markAddAndDeleteInDeps(a,l,(d,h)=>{(o.dynamicDependencies??={})[d]=this.makeDeleteEntry(d,h)})}}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 Rr(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new Tr([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let r=[];for(let 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=ar(Go.join(t,"default/openharmony/ets/build-tools/ets-loader")),o=ar(Go.join(t,"default/openharmony/ets/api")),i=ar(Go.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:T,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:T,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:T,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:T,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:T,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:T,id:e.id,error:{code:-32603,message:t.message}}));break;default:m.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!Hm(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 Oe from"path";import{createHash as aI}from"crypto";import{EventEmitter as cI}from"events";var ia=class extends cI{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=Oe.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=Oe.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=Oe.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=Oe.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=Oe.join(this.projectRoot,L.OH_PACKAGE_JSON5);Wt.existsSync(r)&&t.push(r);let o=this.parseModulesFromBuildProfile();for(let i of o){let s=Oe.resolve(this.projectRoot,i.srcPath),a=Oe.join(s,L.OH_PACKAGE_JSON5);Wt.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return Oe.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Wt.readFileSync(t,"utf-8");return aI("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:Oe.basename(t),relativePath:Oe.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 pn from"fs";import*as pt from"path";import{createHash as lI}from"crypto";import{EventEmitter as dI}from"events";var sa=class extends dI{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=pt.join(t,Uo)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!pn.existsSync(this.depMapDir)){m.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=pn.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 U(pt.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===Yn)i="dep-map-json";else{let a=o.match(/^([^/]+)\/oh-package\.json5$/);i=a?`module:${a[1]}`:""}if(!i)return;let s=pt.join(this.depMapDir,r);pn.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=pt.join(this.depMapDir,L.OH_PACKAGE_JSON5),r=pt.join(this.depMapDir,Yn),o=this.parseModulesFromDepMap(),i=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...o.map(s=>({path:pt.join(this.depMapDir,s.name,L.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of i){if(!pn.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=pt.join(this.depMapDir,Yn);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 U(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=pt.join(this.depMapDir,a.name,L.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=pt.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})`);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=pn.readFileSync(t,"utf-8");return lI("sha256").update(r).digest("hex")}catch{return null}}};import{spawn as uI}from"child_process";var pI=["install","--all"];async function fI(n,e,t,r){return new Promise(o=>{let i=uI(n,e,{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(`
|
|
1292
|
+
`);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),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 ln=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)o(t,r),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}`),o(),this.timeouts.delete(e)},r);this.timeouts.set(e,s)}clearTimeout(e){let t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e))}deleteCallback(e){this.callbacks.delete(e)}hasCallback(e){return this.callbacks.has(e)||this.pending.has(e)}clear(e){this.clearTimeout(e);let t=this.pending.get(e);t&&(t.reject(new Error(`Request '${t.method}' (id=${e}) cancelled`)),this.pending.delete(e)),this.callbacks.delete(e)}rejectAll(e){for(let[,t]of this.pending)t.reject(e);this.pending.clear();for(let[,t]of this.timeouts)clearTimeout(t);this.timeouts.clear(),this.callbacks.clear()}};var Ms=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var Rr=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 Gm=20*1e3,rI=30*1e3,_s=class{client;nextRequestId=1;stopOnce=null;callbacks=new Rr;requestCallbacks=new ln;diagnosticMap=new Map;initProgressReset=null;constructor(e){this.client=new cn(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,Ye);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 Ms(t)),this.registerDiagnosticTimeout(t)),this.client.sendNotification(y.DID_OPEN,e)}sendDidChange(e){let t=e.textDocument.uri,r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t)),this.client.sendNotification(y.DID_CHANGE,e)}closeFile(e){this.cleanupDiagnosticState(e.textDocument.uri),this.client.sendNotification(y.DID_CLOSE,e)}sendLspRequest(e,t,r=rI){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){D(e)&&this.broadcastToClients({jsonrpc:T,method:y.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,y.PUBLISH_DIAGNOSTICS,Gm,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${Gm}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:T,method:y.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var Fs=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 Fl(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)}},Fl=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var oI={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"},iI={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate",ON_FORCE_OPEN_FILE:"aceProject/onForceOpenFile",ON_PACKAGE_CHANGE_FINISH:"aceProject/onPackageChangeFinish",TEXT_DOCUMENT_ON_ASYNC_DEFINITION:"textDocument/onAsyncDefinition",ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:"textDocument/onDidChangePackageDependencies",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",REFERENCES:"textDocument/references",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",BROADCAST:"lsp/broadcast",ARKTS_ERROR:"arkts/error",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing"},k={...oI,...iI},dn={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"},Vm=new Set([1e3,2e3,3e3,3001]);function sI(n){if(!D(n))return!1;let e=n.textDocument;return D(e)&&typeof e.uri=="string"}function aI(n){return D(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function cI(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 js=class n{client;isInitialized=!1;stopOnce=null;callbacks=new Rr;requestCallbacks=new ln;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;constructor(e){this.client=new cn(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:T,method:k.EXIT,params:{}}),dn.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(k.BROADCAST),this.callbacks.register(k.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(k.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(k.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(k.INDEXING_PROGRESS_UPDATE,e)}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}sendInitialize(e,t){this.client.send("initialize",e,t)}sendInitialized(e){this.client.sendRaw(JSON.stringify({jsonrpc:T,method:k.INITIALIZED,params:{editors:e}}),dn.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:T,id:0,result:{}}),dn.EMPTY)}sendAsyncRequest(e,t,r,o){if(!D(t)){m.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!sI(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=at(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:T,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(!aI(r)){m.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:T,method:k.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),k.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!D(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){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:T,method:k.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),dn.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let o=at(t);e.textDocument.uri=o,m.info(`[LSP] onAsyncOpenFile, uri: ${o}`);let i=this.diagnosticMap.get(o);i||(i=new Fs(o),this.diagnosticMap.set(o,i),this.registerDiagnosticTimeout(o,k.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(i.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:T,method:k.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),dn.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=at(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,k.PUBLISH_DIAGNOSTICS)),m.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:T,method:k.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),dn.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=at(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:T,method:k.DID_CLOSE,params:{textDocument:{uri:r}}}),dn.DID_CLOSE)}getDiagnosticMessage(e){let t=at(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,k.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:T,method:k.ARKTS_ERROR,params:{message:e.message}})}handleLspMessage(e){let t=e.method;t!==void 0&&(!this.isInitialized&&this.handlePreInitMessage(t,e)||this.handlePostInitMessage(t,e))}handlePreInitMessage(e,t){switch(e){case k.MODULE_INIT_FINISH:return m.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(k.MODULE_INIT_FINISH),this.callbacks.unregister(k.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case k.INDEXING_PROGRESS_UPDATE:return m.info(`[LSP] onIndexingProgressUpdate: ${cI(t.params)}`),this.callbacks.invoke(k.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case k.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case k.ON_PACKAGE_CHANGE_FINISH:m.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case k.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case k.ON_ASYNC_HOVER:this.handleAsyncResponse(t,k.HOVER);return;case k.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,k.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case k.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,k.REFERENCES);return;default: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;D(t)&&D(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:T,method:k.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(!D(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,k.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(Vm)&&this.finalizeDiagnostic(t,k.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 Vo from"path";import*as Vs from"path";var Hs=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var $s=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var Us=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var Bs=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var Ws=class{typeSetting=new Us;parameterNames=new Bs};var Gs=class{constructor(e,t,r,o){this.rootUri=e;this.lspServerWorkspacePath=U(Vs.dirname(t)),this.indexingDataLocation=U(o),this.loggerPath=U(Vs.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new Hs;gutterIconsSetting=new $s;inlayHintsSetting=new Ws;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as qm from"path";var Uo=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(U(qm.join(e,"src","main","resources")))}};var lI="OS",Tr=class{deviceType=[5];aceLoaderPath;modulePath;jsComponentType="declarative";sdkJsPath;compatibleSdkVersion;compatibleSdkLevel;compileSdkLevel;compileSdkVersion="6.0.1.112";compileSdkType="Release";syscap={NDeviceSysCaps:[],addedSysCaps:[]};apiType="stageMode";hosSdkPath;runtimeOs=`Harmony${lI}`;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 Uo(e)):this.buildProfileParam=new Uo}toString(){return JSON.stringify(this)}};var kr=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as Re from"path";import*as Lr from"fs";var qs=class{modulePath;dependencies={};dynamicDependencies={}};var Yn=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 xr=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 zs from"fs";var Nr=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:st.OH_PACKAGE_JSON5},Bo=`${L.HVIGOR_CACHE}/${L.DEPENDENCY}`,Jn=`${L.DEPENDENCY}${L.JSON5}`,gW=st.SYNC_OUTPUT_PATH;var Wo=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,L.OH_PACKAGE_JSON5),r=Ge(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"){m.error(`${i} package dependency value is not String ${t}`);continue}let a=new Nr;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,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)),Bt.isAbsolute(s)){r.dependencyPath=i;return}o||(i=Bt.resolve(this.modulePath,s)),zs.existsSync(i)&&zs.statSync(i).isDirectory()&&(r.dependencyPath=i)}catch(i){m.error("parser dependency path is invalid",i)}}};import*as Go from"fs";import*as un from"path";import dI from"json5";var Ys=class n{projectPath;static FILE_DEPENDENCY_PREFIX="file:";fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[];storePathMap=new Map;lockFileCache=null;lockFileParsed=!1;constructor(e=""){this.projectPath=e}parseDependencies(e){if(!this.ensureLockFileParsed())return!1;let t=this.lockFileCache;return this.extractDependencies(t.modules,t.storePathMap,e),!0}ensureLockFileParsed(){if(this.lockFileParsed)return this.lockFileCache!==null;this.lockFileParsed=!0;let e=this.getLockFilePath(),t=this.readLockFile(e);if(!t)return!1;let r=this.validateLockFile(t);return r.valid?(this.lockFileCache={modules:r.modules,storePathMap:this.parseStorePathMap(r.packages)},!0):!1}getLockFilePath(){return un.join(this.projectPath,L.OH_MODULES_PATH,L.OHPM_PATH,L.LOCK_JSON5_FILE)}readLockFile(e){if(!Go.existsSync(e))return m.error("lock file does not exist"),this.clearDependencies(),null;try{let t=Go.readFileSync(e,"utf8"),r=dI.parse(t);return r||(m.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return m.error("Error parsing lock.json5:",t),this.clearDependencies(),null}}validateLockFile(e){if(!D(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,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;for(let[r,o]of Object.entries(e)){if(!D(o)){m.error(`${r} value is not json object`);continue}typeof o.storePath=="string"&&t.set(r,o.storePath)}return t}getDependencyList(e,t,r){if(!D(e))return[];for(let[o,i]of Object.entries(e))if(D(i)){let s=typeof i.name=="string"?i.name:"";if(r==="."&&s===""||s===r)return this.getFinalDependencyList(e,t,o)}return[]}getFinalDependencyList(e,t,r){let o=e[r];if(!D(o))return m.error("moduleJsonObject is null"),[];let i=[],s=o[t];if(!D(s))return[];for(let[a,c]of Object.entries(s)){if(!D(c))continue;let l=typeof c.specifier=="string"?c.specifier:"",d=typeof c.version=="string"?c.version:"",h=new Nr;h.name=a,h.version=d.startsWith(n.FILE_DEPENDENCY_PREFIX)?d.substring(n.FILE_DEPENDENCY_PREFIX.length):d,this.parseDependencyPath(h,r,a,l,d);let w=`${a}@${d}`;this.storePathMap.has(w)&&(h.storePath=this.storePathMap.get(w)||""),i.push(h)}return i}parseDependencyPath(e,t,r,o,i){let s=un.resolve(this.projectPath,un.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=un.isAbsolute(a)?a:un.resolve(this.projectPath,a);Go.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",a)}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};function zm(n){return D(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var Kn=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new xt(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=Re.join(t,Bo),o=Re.join(r,Jn);if(!Lr.existsSync(r)||!Lr.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 xr(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];zm(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=Re.join(r,Bo),i=Re.join(o,Jn);if(!Lr.existsSync(o)||!Lr.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 xr(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(!zm(l))continue;let d=l.name;if(s&&!s.has(d))continue;let h=Re.resolve(this.projectPath,l.srcPath),w=Re.join(o,d),v=U(h),I=this.buildModuleDependencies(d,v,w,a);I.moduleName=d,t.push(I)}return t}parseSingleModule(e,t,r,o){let i=e.name,s=Re.resolve(this.projectPath,e.srcPath),a=Re.join(t,i),c=U(s),l=new Tr(c),d=this.buildModuleDependencies(i,c,a,r);this.parseModuleJson5(c,l);let h=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=i,l.moduleType=i,l.packageName=i,l.moduleDependencies=d,l.moduleJsonParam=new kr(h),o.push(l)}buildModuleDependencies(e,t,r,o){let i=new xr(this.projectPath,e,t);Wo.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 qs;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 Yn(i);for(let i of e.finalDynamicDependencies)o[i.name]=new Yn(i);t.dependencies=r,t.dynamicDependencies=o}parseProjectDependencies(e,t){let r=Re.join(e,L.OH_PACKAGE_JSON5);if(!Lr.existsSync(r))return;Wo.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 Ys(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=Re.join(e,"src","main","module.json5"),o=Ge(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=Re.join(e,"src","main","resources","base","profile","main_pages.json"),r=Ge(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=Re.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=Ge(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=Re.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!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 Js=class{constructor(e=[]){this.valueSet=e}valueSet};var Or=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var Ym=(P=>(P[P.File=1]="File",P[P.Module=2]="Module",P[P.Namespace=3]="Namespace",P[P.Package=4]="Package",P[P.Class=5]="Class",P[P.Method=6]="Method",P[P.Property=7]="Property",P[P.Field=8]="Field",P[P.Constructor=9]="Constructor",P[P.Enum=10]="Enum",P[P.Interface=11]="Interface",P[P.Function=12]="Function",P[P.Variable=13]="Variable",P[P.Constant=14]="Constant",P[P.String=15]="String",P[P.Number=16]="Number",P[P.Boolean=17]="Boolean",P[P.Array=18]="Array",P[P.Object=19]="Object",P[P.Key=20]="Key",P[P.Null=21]="Null",P[P.EnumMember=22]="EnumMember",P[P.Struct=23]="Struct",P[P.Event=24]="Event",P[P.Operator=25]="Operator",P[P.TypeParameter=26]="TypeParameter",P))(Ym||{}),Jm=()=>Object.values(Ym).filter(n=>typeof n=="number");var Ks=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Xs=class{applyEdit=!0;workspaceEdit=new Ks;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new Js(Jm());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Or;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Zs=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Qs=class{constructor(e=[]){this.valueSet=e}valueSet};var ea=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var Km=(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))(Km||{}),Xm=()=>Object.values(Km).filter(n=>typeof n=="number");var ta=class{completionItemKind=new Qs(Xm());completionItem=new ea;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var na=class{synchronization=new Zs;completion=new ta;hover={contentFormat:{},dynamicRegistration:{}};signatureHelp={signatureInformation:{},contextSupport:{},dynamicRegistration:{}};references={dynamicRegistration:{}};documentHighlight={dynamicRegistration:!0};documentSymbol=null;formatting={dynamicRegistration:{}};rangeFormatting={dynamicRegistration:{}};onTypeFormatting={dynamicRegistration:{}};declaration={};definition={linkSupport:{},dynamicRegistration:{}};codeLens=null;documentLink={tooltipSupport:{},dynamicRegistration:{}};colorProvider=null;rename={prepareSupport:!0,prepareSupportDefaultBehavior:null,honorsChangeAnnotations:null,dynamicRegistrationSupport:null};publishDiagnostics=null;foldingRage=null;typeHierarchy=null;callHierarchy={dynamicRegistration:{}};selectionRange=null;semanticTokens=new Or;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var ra=class{workspace=new Xs;textDocument=new na;notebookDocument=null;window=null;general=null;experimental=null};var oa=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};var ia=class{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=[];sdkPath;rootUri;nodeMaxOldSpaceSize;nodePath;useStandardProtocol;get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}constructor(e){this.sdkPath=e.sdkPath,this.rootUri=e.workspaceRoot,this.nodeMaxOldSpaceSize=e.nodeMaxOldSpaceSize,this.nodePath=e.nodePath,this.useStandardProtocol=e.useStandardProtocol,this.serverPath=e.useStandardProtocol?Vo.resolve(Vo.dirname(e.arktsLangServerPath),"standardIndex","index.js"):e.arktsLangServerPath,this.logPath=qu(),this.indexLogPath=e.indexLogPath||this.logPath;let t={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath,nodePath:this.nodePath};this.messageHandle=e.useStandardProtocol?new _s(t):new js(t),this.messageHandle.setBroadcastToClients(r=>this.onLspMessage(r))}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=at(this.rootUri),i=new Gs(o,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new Kn(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),i.modules=s;let l=Ji(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(l),this.currentParams=new oa(o,i,new ra),this.useStandardProtocol){let d=this.messageHandle;await d.sendInitializeResettable(this.currentParams,Ye),m.info("[LSP] initialize response received"),d.broadcastToClients({jsonrpc:T,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:T,method:y.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((o,i)=>{r.onIndexingProgressUpdate(i),r.onInitializationCompleted(o)},"LSP initialization",Ye),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=D(r)?r:{};m.info(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let i={jsonrpc:T,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 Kn(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,h)=>{(o.dependencies??={})[d]=this.makeDeleteEntry(d,h)}),this.markAddAndDeleteInDeps(a,l,(d,h)=>{(o.dynamicDependencies??={})[d]=this.makeDeleteEntry(d,h)})}}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 Yn({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Tr(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new kr([]),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=cr(Vo.join(t,"default/openharmony/ets/build-tools/ets-loader")),o=cr(Vo.join(t,"default/openharmony/ets/api")),i=cr(Vo.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:T,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:T,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:T,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:T,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:T,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:T,id:e.id,error:{code:-32603,message:t.message}}));break;default:m.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!Bm(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 Oe from"path";import{createHash as pI}from"crypto";import{EventEmitter as fI}from"events";var sa=class extends fI{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=Oe.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=Oe.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=Oe.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=Oe.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=Oe.join(this.projectRoot,L.OH_PACKAGE_JSON5);Wt.existsSync(r)&&t.push(r);let o=this.parseModulesFromBuildProfile();for(let i of o){let s=Oe.resolve(this.projectRoot,i.srcPath),a=Oe.join(s,L.OH_PACKAGE_JSON5);Wt.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return Oe.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Wt.readFileSync(t,"utf-8");return pI("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:Oe.basename(t),relativePath:Oe.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 pn from"fs";import*as pt from"path";import{createHash as mI}from"crypto";import{EventEmitter as hI}from"events";var aa=class extends hI{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=pt.join(t,Bo)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!pn.existsSync(this.depMapDir)){m.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=pn.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 U(pt.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===Jn)i="dep-map-json";else{let a=o.match(/^([^/]+)\/oh-package\.json5$/);i=a?`module:${a[1]}`:""}if(!i)return;let s=pt.join(this.depMapDir,r);pn.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=pt.join(this.depMapDir,L.OH_PACKAGE_JSON5),r=pt.join(this.depMapDir,Jn),o=this.parseModulesFromDepMap(),i=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...o.map(s=>({path:pt.join(this.depMapDir,s.name,L.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of i){if(!pn.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=pt.join(this.depMapDir,Jn);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 U(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=pt.join(this.depMapDir,a.name,L.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=pt.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})`);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=pn.readFileSync(t,"utf-8");return mI("sha256").update(r).digest("hex")}catch{return null}}};import{spawn as gI}from"child_process";var yI=["install","--all"];async function wI(n,e,t,r){return new Promise(o=>{let i=gI(n,e,{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(`
|
|
1293
1293
|
`);o({exitCode:c??-1,output:l})}),i.on("error",c=>{let l=[s,a].filter(Boolean).join(`
|
|
1294
1294
|
`);o({exitCode:-1,output:l+`
|
|
1295
|
-
`+c.message})})})}function mI(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>m.info("[ohpm] %s",e))}async function Jm(n,e){try{let{exitCode:t,output:r}=await fI(e.nodePath,[e.ohpmJsPath,...pI],n,e.sdkPath);return mI(r),t===0?(m.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(m.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",t),m.error("ohpm \u8F93\u51FA: %s",r),!1)}catch(t){return m.error("ohpm \u5B89\u88C5\u5F02\u5E38",t),!1}}var Km={UNINITIALIZED:-32099,UNKNOWN:-32e3},Vo=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,Km.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,Km.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var Or=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 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){if(m.info("[ArktsLspManager] Received arkts/syncProject"),!e)return m.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let o=r?.skipHvigorSync===!0,i=await _i(e,async()=>await Jm(e,t)?o?(m.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await Ku(e,t)?(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 i.acquired?i.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 oa(this.config);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:T,method:y.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();m.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?Vo.uninitialized(t):Vo.unknown();this.onMessage({jsonrpc:T,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:T,method:y.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new ia(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new sa(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:T,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 hI=10080*60*1e3,gI=7200*60*1e3,yI=120*1e3,Mr=class n{manager=null;initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;toolProvider;nodeMaxOldSpaceSize;onConfigChangedCallback=null;useStandardProtocol=!0;diagnosticWaiters=new Map;static FEATURE_METHOD_MAP={hover:y.HOVER,definition:y.DEFINITION,declaration:y.DECLARATION,references:y.REFERENCES,implementation:y.IMPLEMENTATION,completion:y.COMPLETION,signatureHelp:y.SIGNATURE_HELP,documentHighlight:y.DOCUMENT_HIGHLIGHT};constructor(e,t,r){this.projectPath=e,this.toolProvider=t,this.nodeMaxOldSpaceSize=r}setOnConfigChanged(e){this.onConfigChangedCallback=e}static getToolDefinition(){return{name:"check_ets_files",description:"\u5BF9\u4F20\u5165\u7684ets\u6587\u4EF6\u8FDB\u884C\u9759\u6001\u8BED\u6CD5\u68C0\u67E5(ArkTS-Check)\u5E76\u5B9E\u65F6\u8FD4\u56DE\u8BCA\u65AD\u4FE1\u606F\u3002",inputSchema:Ml.object({files:Ml.array(Ml.string()).describe('\u5F85\u68C0\u67E5\u7684 ETS \u6587\u4EF6\u8DEF\u5F84\u5217\u8868\uFF0C\u683C\u5F0F\u4E3A ["file1.ets","file2.ets",...]')})}}isInitializing(){return this.initializing}isInitialized(){return this.initialized}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initializing=!0,this.initPromise=this.doInitialize().then(()=>{this.initialized=!0}).finally(()=>{this.initializing=!1}),await this.initPromise}}async doInitialize(){let{harmonyRoot:e,devecoPath:t,arktsLangServerPath:r,useStandardProtocol:o}=this.resolveProjectAndDeveco();this.useStandardProtocol=o;let i=fe(e),{logPath:s,indexPath:a}=this.getLogAndIndexPath(i);setImmediate(()=>{Ic(a,hI,"[ArkTS-Check]"),Ic(s,gI,"[ArkTS-Check]")}),qi(s);let c=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,l=Number.isNaN(c)?void 0:c;g.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${l??"undefined \u2192 dynamic formula applies"}`);let d=this.toolProvider.sdkPath;g.info(`ArktsCheck devecoStudioPath: ${t}, sdkPath: ${d}`),this.manager=new Or({sdkPath:d,arktsLangServerPath:r,workspaceRoot:U(i),indexLogPath:a,nodeMaxOldSpaceSize:l,nodePath:this.toolProvider.nodePath,useStandardProtocol:o}),this.manager.setOnMessage(h=>this.handleLspMessage(h)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((h,w)=>{this.initResolve=h,this.initReject=w,this.armInitTimer(Ye),this.manager.start([]).catch(v=>{let I=v instanceof Error?v:new Error(String(v));this.failInit(I)})})}resolveProjectAndDeveco(){let e=kt(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.toolProvider.devecoStudioPath??"";g.debug(`DevEco Studio installation path: ${t}`);let r=this.toolProvider.lspServerPath;if(!r)throw new Error("arkts-lang-server path not found");let o=le.resolve(le.dirname(r),"standardIndex","index.js"),i=Me.existsSync(o);return g.info(`ArktsCheck protocol: ${i?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${i})`),{harmonyRoot:e,devecoPath:t,arktsLangServerPath:r,useStandardProtocol:i}}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=_n(e),o=await Me.promises.readFile(e,"utf8"),s=`deveco.apptool.${le.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){g.debug(`textDocument/didOpen uri=${t} content_len=${r.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:r,languageId:o,version:1}});try{g.debug(`textDocument/diagnostic uri=${t}`);let i=await e.diagnostic({textDocument:{uri:t}});return wI(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"))},yI);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:d})});g.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(`
|
|
1295
|
+
`+c.message})})})}function vI(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>m.info("[ohpm] %s",e))}async function Zm(n,e){try{let{exitCode:t,output:r}=await wI(e.nodePath,[e.ohpmJsPath,...yI],n,e.sdkPath);return vI(r),t===0?(m.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(m.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",t),m.error("ohpm \u8F93\u51FA: %s",r),!1)}catch(t){return m.error("ohpm \u5B89\u88C5\u5F02\u5E38",t),!1}}var Qm={UNINITIALIZED:-32099,UNKNOWN:-32e3},qo=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,Qm.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,Qm.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var Mr=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 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){if(m.info("[ArktsLspManager] Received arkts/syncProject"),!e)return m.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let o=r?.skipHvigorSync===!0,i=await Fi(e,async()=>await Zm(e,t)?o?(m.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await Qu(e,t)?(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 i.acquired?i.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 ia(this.config);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:T,method:y.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();m.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?qo.uninitialized(t):qo.unknown();this.onMessage({jsonrpc:T,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:T,method:y.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new sa(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new aa(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:T,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 SI=10080*60*1e3,bI=7200*60*1e3,EI=120*1e3,_r=class n{manager=null;initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;toolProvider;nodeMaxOldSpaceSize;onConfigChangedCallback=null;useStandardProtocol=!0;diagnosticWaiters=new Map;static FEATURE_METHOD_MAP={hover:y.HOVER,definition:y.DEFINITION,declaration:y.DECLARATION,references:y.REFERENCES,implementation:y.IMPLEMENTATION,completion:y.COMPLETION,signatureHelp:y.SIGNATURE_HELP,documentHighlight:y.DOCUMENT_HIGHLIGHT};constructor(e,t,r){this.projectPath=e,this.toolProvider=t,this.nodeMaxOldSpaceSize=r}setOnConfigChanged(e){this.onConfigChangedCallback=e}static getToolDefinition(){return{name:"check_ets_files",description:"\u5BF9\u4F20\u5165\u7684ets\u6587\u4EF6\u8FDB\u884C\u9759\u6001\u8BED\u6CD5\u68C0\u67E5(ArkTS-Check)\u5E76\u5B9E\u65F6\u8FD4\u56DE\u8BCA\u65AD\u4FE1\u606F\u3002",inputSchema:jl.object({files:jl.array(jl.string()).describe('\u5F85\u68C0\u67E5\u7684 ETS \u6587\u4EF6\u8DEF\u5F84\u5217\u8868\uFF0C\u683C\u5F0F\u4E3A ["file1.ets","file2.ets",...]')})}}isInitializing(){return this.initializing}isInitialized(){return this.initialized}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initializing=!0,this.initPromise=this.doInitialize().then(()=>{this.initialized=!0}).finally(()=>{this.initializing=!1}),await this.initPromise}}async doInitialize(){let{harmonyRoot:e,devecoPath:t,arktsLangServerPath:r,useStandardProtocol:o}=this.resolveProjectAndDeveco();this.useStandardProtocol=o;let i=fe(e),{logPath:s,indexPath:a}=this.getLogAndIndexPath(i);setImmediate(()=>{Ac(a,SI,"[ArkTS-Check]"),Ac(s,bI,"[ArkTS-Check]")}),zi(s);let c=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,l=Number.isNaN(c)?void 0:c;g.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${l??"undefined \u2192 dynamic formula applies"}`);let d=this.toolProvider.sdkPath;g.info(`ArktsCheck devecoStudioPath: ${t}, sdkPath: ${d}`),this.manager=new Mr({sdkPath:d,arktsLangServerPath:r,workspaceRoot:U(i),indexLogPath:a,nodeMaxOldSpaceSize:l,nodePath:this.toolProvider.nodePath,useStandardProtocol:o}),this.manager.setOnMessage(h=>this.handleLspMessage(h)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((h,w)=>{this.initResolve=h,this.initReject=w,this.armInitTimer(Ye),this.manager.start([]).catch(v=>{let I=v instanceof Error?v:new Error(String(v));this.failInit(I)})})}resolveProjectAndDeveco(){let e=kt(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.toolProvider.devecoStudioPath??"";g.debug(`DevEco Studio installation path: ${t}`);let r=this.toolProvider.lspServerPath;if(!r)throw new Error("arkts-lang-server path not found");let o=le.resolve(le.dirname(r),"standardIndex","index.js"),i=Me.existsSync(o);return g.info(`ArktsCheck protocol: ${i?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${i})`),{harmonyRoot:e,devecoPath:t,arktsLangServerPath:r,useStandardProtocol:i}}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=_n(e),o=await Me.promises.readFile(e,"utf8"),s=`deveco.apptool.${le.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){g.debug(`textDocument/didOpen uri=${t} content_len=${r.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:r,languageId:o,version:1}});try{g.debug(`textDocument/diagnostic uri=${t}`);let i=await e.diagnostic({textDocument:{uri:t}});return PI(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"))},EI);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:d})});g.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(`
|
|
1296
1296
|
`):"\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};g.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 g.error(`handleLspFeature ${e} failed: ${s}`),{content:[{type:"text",text:`${e} failed: ${s}`}],isError:!0}}}async handleWorkspaceSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();g.info(`handleWorkspaceSymbol: query="${e}"`);try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return{content:[{type:"text",text:t==null?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(t,null,2)}`}]}}catch(t){let r=t instanceof Error?t.message:String(t);return g.error(`handleWorkspaceSymbol failed: ${r}`),{content:[{type:"text",text:`workspaceSymbol failed: ${r}`}],isError:!0}}}async handleWorkspaceSymbolRaw(e){if(!this.initialized)return null;try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return g.error(`handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};g.info(`handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async 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 g.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};g.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 h=await this.manager.sendFeatureRequest(c,{item:d});Array.isArray(h)?l.push(...h):h&&l.push(h)}return{items:a,calls:l}});return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){let o=r instanceof Error?r.message:String(r);return g.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};g.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};g.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};g.info(`handleTypeHierarchy: 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_TYPE_HIERARCHY,{textDocument:{uri:i},position:{line:e.line,character:e.character}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],results:[]};let c=e.direction==="supertypes"?y.SUPERTYPES:y.SUBTYPES,l=[];for(let d of a){let h=await this.manager.sendFeatureRequest(c,{item:d});Array.isArray(h)?l.push(...h):h&&l.push(h)}return{items:a,results:l}});return{content:[{type:"text",text:`typeHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("typeHierarchy",r)}}async handleCompletionItemResolve(e){if(!this.initialized)return this.buildNotReadyResponse();g.info("handleCompletionItemResolve");try{let t=await this.manager.sendFeatureRequest(y.COMPLETION_ITEM_RESOLVE,{item:e});return{content:[{type:"text",text:t==null?"completionItemResolve: no result":`completionItemResolve: ${JSON.stringify(t,null,2)}`}]}}catch(t){return this.buildErrorResponse("completionItemResolve",t)}}async handleInlayHint(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};try{let o=(await Me.promises.readFile(t,"utf8")).split(`
|
|
1297
|
-
`).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 g.error(`${e} failed: ${r}`),{content:[{type:"text",text:`${e} failed: ${r}`}],isError:!0}}async withOpenFile(e,t){let r=_n(e),o=await Me.promises.readFile(e,"utf8"),s=`deveco.apptool.${le.extname(e).replace(/^\./,"")||"plaintext"}`;g.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=le.isAbsolute(e)?e:le.join(this.projectPath,e);return!Me.existsSync(t)||!Me.statSync(t).isFile()||!t.endsWith(".ets")?null:t}buildNotReadyResponse(){return{content:[{type:"text",text:this.initializing?"LSP \u6B63\u5728\u521D\u59CB\u5316\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5":this.projectPath?"LSP\u672A\u521D\u59CB\u5316":"\u6CA1\u6709\u914D\u7F6E\u5DE5\u7A0B\u8DEF\u5F84\uFF0C\u8BF7\u914D\u7F6EPROJECT_PATH\u53C2\u6570"}],isError:!0}}collectValidFiles(e,t){let r=this.projectPath,o=[];for(let i of e){let s=le.resolve(le.isAbsolute(i)?i:le.join(r,i));if(!Me.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${i}`);continue}if(!Me.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
|
|
1297
|
+
`).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 g.error(`${e} failed: ${r}`),{content:[{type:"text",text:`${e} failed: ${r}`}],isError:!0}}async withOpenFile(e,t){let r=_n(e),o=await Me.promises.readFile(e,"utf8"),s=`deveco.apptool.${le.extname(e).replace(/^\./,"")||"plaintext"}`;g.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=le.isAbsolute(e)?e:le.join(this.projectPath,e);return!Me.existsSync(t)||!Me.statSync(t).isFile()||!t.endsWith(".ets")?null:t}buildNotReadyResponse(){return{content:[{type:"text",text:this.initializing?"LSP \u6B63\u5728\u521D\u59CB\u5316\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5":this.projectPath?"LSP\u672A\u521D\u59CB\u5316":"\u6CA1\u6709\u914D\u7F6E\u5DE5\u7A0B\u8DEF\u5F84\uFF0C\u8BF7\u914D\u7F6EPROJECT_PATH\u53C2\u6570"}],isError:!0}}collectValidFiles(e,t){let r=this.projectPath,o=[];for(let i of e){let s=le.resolve(le.isAbsolute(i)?i:le.join(r,i));if(!Me.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${i}`);continue}if(!Me.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 ju(500);try{let i=await this.checkFile(o);r.push(CI(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(`
|
|
1298
1298
|
`)),t.length>0&&r.push(t.join(`
|
|
1299
1299
|
`));let o=r.join(`
|
|
1300
|
-
`).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){g.warn(`Failed to dispose ArktsLspManager: ${t}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,r=t.method;if(r)switch(r){case"textDocument/publishDiagnostics":{this.handleDiagnosticsNotification(t.params);break}case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(Ye),g.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{g.info("Received arkts/initialized");let o=this.initResolve;this.clearInitHandlers(),o?.();break}case"arkts/initializationFailed":{let i=t.params?.message??"unknown";g.error(`LSP initialization failed: ${i}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${i}`));break}case"workspace/didChangeConfiguration":g.info("Received workspace/didChangeConfiguration, sync deferred to next check");break;default:break}}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let r=this.popDiagnosticWaiter(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.popDiagnosticWaiter(s)}if(!r)return;if(typeof e.errorMessage=="string"){g.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),r.resolve({errorMessage:e.errorMessage});return}let o=e.diagnostics,i=Array.isArray(o)?o.length:0;g.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=le.join(nn(),"ArkTSCheck"),r=le.join(t,"mapping-config.properties"),o=
|
|
1301
|
-
`):"No valid C/C++ files"}],isError:!0};this.manager.patchSdkPathInCompileCommands();for(let c of o){await
|
|
1300
|
+
`).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){g.warn(`Failed to dispose ArktsLspManager: ${t}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,r=t.method;if(r)switch(r){case"textDocument/publishDiagnostics":{this.handleDiagnosticsNotification(t.params);break}case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(Ye),g.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{g.info("Received arkts/initialized");let o=this.initResolve;this.clearInitHandlers(),o?.();break}case"arkts/initializationFailed":{let i=t.params?.message??"unknown";g.error(`LSP initialization failed: ${i}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${i}`));break}case"workspace/didChangeConfiguration":g.info("Received workspace/didChangeConfiguration, sync deferred to next check");break;default:break}}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let r=this.popDiagnosticWaiter(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.popDiagnosticWaiter(s)}if(!r)return;if(typeof e.errorMessage=="string"){g.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),r.resolve({errorMessage:e.errorMessage});return}let o=e.diagnostics,i=Array.isArray(o)?o.length:0;g.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=le.join(nn(),"ArkTSCheck"),r=le.join(t,"mapping-config.properties"),o=Hu(e,r),i=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=le.join(t,"lsp-log",String(o),i),a=le.join(t,"lsp-index",String(o));return Me.mkdirSync(s,{recursive:!0}),Me.mkdirSync(a,{recursive:!0}),{logPath:fe(s),indexPath:fe(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function PI(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 CI(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 fn from"fs";import*as Hr from"path";import{z as Hl}from"zod";function Fr(){return{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}}function ca(n,e){let t=e instanceof Error?e.message:String(e);return g.error(`[CppLsp] ${n} failed: ${t}`),{content:[{type:"text",text:`${n} failed: ${t}`}],isError:!0}}var II=500,jr=class{manager;toolProvider;constructor(e,t){this.manager=e,this.toolProvider=t}static getToolDefinition(){return{name:"check_cpp_files",description:"Perform static syntax checks on the provided C/C++ files and return clangd diagnostics.",inputSchema:Hl.object({files:Hl.array(Hl.string()).describe('List of C/C++ file paths to check, format: ["file1.cpp","file2.hpp",...]')})}}async handleCall(e){if(!this.manager.ready)return Fr();let t=[],r=[],o=this.collectValidFiles(e.files,t);if(o.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
|
|
1301
|
+
`):"No valid C/C++ files"}],isError:!0};this.manager.patchSdkPathInCompileCommands();for(let c of o){await DI(II);try{let l=await this.checkFile(c);r.push(AI(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(`
|
|
1302
1302
|
`)),r.length>0&&s.push(r.join(`
|
|
1303
1303
|
`));let a=s.join(`
|
|
1304
|
-
`).trim();return!i&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:i}}async checkFile(e){let t=_n(e),r=await fn.promises.readFile(e,"utf8"),o=Bi(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=this.manager.projectRoot,o=[];for(let i of e){let s=jr.resolve(jr.isAbsolute(i)?i:jr.join(r,i));if(!fn.existsSync(s)){t.push(`File does not exist: ${i}`);continue}if(!fn.statSync(s).isFile()){t.push(`Not a regular file: ${i}`);continue}if(!Mn(s)){t.push(`Not a supported C/C++ file: ${i}`);continue}try{o.push(fn.realpathSync(s))}catch{o.push(s)}}return o}};function bI(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 EI(n){return new Promise(e=>setTimeout(e,n))}import*as $r from"fs";import*as ca from"path";var Hr=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 _r();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};g.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 aa(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 g.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return _r();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e}`}],isError:!0};g.info(`[ClangdLspTool] handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async 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 aa("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return _r();if(e.direction==="outgoing")return{content:[{type:"text",text:"callHierarchy outgoing is not supported by clangd (incoming only)"}],isError:!0};let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e.file}`}],isError:!0};g.info(`[ClangdLspTool] handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,i=>this.fetchCallHierarchyResult(i,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return aa("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=_n(e),o=await $r.promises.readFile(e,"utf8"),i=Bi(e);g.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=ca.isAbsolute(e)?e:ca.join(this.manager.projectRoot,e);return!$r.existsSync(t)||!$r.statSync(t).isFile()||!Mn(t)?null:t}};import{spawn as PI}from"child_process";import*as da from"fs";import*as Xm from"path";var CI=30*1e3,II=30*1e3,la=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new ln;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,nodePath:this.config.nodePath};this.client=new cn(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,Ye),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}`))},II);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=${U(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];m.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=PI(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=ar(this.config.workspaceRoot),t=at(e),r=Xm.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"0.4.0-TD.2.4"},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=CI){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){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:T,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:T,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:T,method:y.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{da.existsSync(this.config.logPath)||da.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)),at(r)}}catch{}return e}};import*as qo from"path";import*as Gt 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.patchSdkPathInCompileCommands(),this.proxy.sendFeatureRequest(e,t)}registerDiagnosticCallback(e){return this.proxy?this.proxy.registerDiagnosticCallback(e):Promise.reject(new Error("[ClangdLspManager] LSP not ready"))}patchSdkPathInCompileCommands(){if(!E()||this.config.toolProvider.sourceType==="studio"||process.env.COMMAND_LINE_TOOL_PATH?.trim()===A.OPENHARMONY_STUDIO_ROOT)return;let e=ir(this.projectRoot);if(!Gt.existsSync(e))return;let t=Gt.readFileSync(e,"utf8");if(!t.includes(zi))return;let r=t.replaceAll(zi,this.config.toolProvider.sdkPath);Gt.writeFileSync(e,r,"utf8"),m.info(`[CppCheck] Patched SDK path in compile_commands.json: ${zi} -> ${this.config.toolProvider.sdkPath}`)}static async handleSyncCppProject(e,t){if(m.info("[ClangdLspManager] Received cpp/syncProject"),!e)return m.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or devecoPath is empty"),{status:"failed",reason:"workspaceRoot or devecoPath is empty"};if(jn(e).length===0)return m.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let o=await _i(e,async()=>{try{return await Qu(e,t),m.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(i){let s=i instanceof Error?i.message:String(i);return m.error(`[ClangdLspManager] compileNative failed: ${s}`),{status:"failed",reason:s}}});return o.acquired?o.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(Ye);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=kt(this.config.workspaceRoot);this.resolvedRoot=e?fe(e):fe(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();qi(t);let r=this.config.toolProvider.clangdPath;if(!r){let s="clangd executable not found inside DevEco Studio SDK";m.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let o=qo.dirname(ir(this.resolvedRoot));try{Gt.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 la({clangdPath:r,workspaceRoot:this.resolvedRoot,compileCommandsDir:o,logPath:t,nodePath:this.config.toolProvider.nodePath});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=qo.join(nn(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=qo.join(e,"lsp-log",t);return Gt.mkdirSync(r,{recursive:!0}),fe(r)}catch{return"auto"}}};function Zm(n){let e=ji(n);return m.info(`[SyncGuard] ${e.reason}`),e}var Hl=(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))(Hl||{}),eh=(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))(eh||{}),Et=3,Fl=600*1e3,jl=100,ua=class{server;toolRouter;config;arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";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,Fn(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),g.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",g.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,g.info(`Constructor: using configured path as startPath: '${t}'`));let o=kt(t);g.info(`Constructor: findHarmonyProject('${t}') => ${o??"null"}`),this.config.projectPath=o??void 0,this.server=new AI({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=Ll(),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:de.object({target:de.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:de.object({files:de.array(de.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){g.info("Skip registering LSP feature tools (hover/definition/declaration/references/implementation, workspaceSymbol, documentSymbol, callHierarchy): standard LSP protocol unavailable (standardIndex/index.js not found). These tools require a DevEco Studio version that ships the standard LSP server entry.");return}let e=de.object({file:de.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:de.number().describe("Line number (0-based)"),character:de.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:de.object({query:de.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:de.object({file:de.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:de.object({file:de.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:de.number().describe("Line number (0-based)"),character:de.number().describe("Character offset in the line (0-based)"),direction:de.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.config.toolProvider.lspServerPath;if(!e)return g.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=mn.join(mn.dirname(e),"standardIndex","index.js"),r=Qm.existsSync(t);return g.info(`ArktsCheck protocol: ${r?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${r})`),r}catch(e){return g.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=R.isPathContainedWithSymlink(i,t);s.contained||(g.warn(`Containment check failed: ${s.reason}`),o.push(s.reason))}return o.length>0?{content:[{type:"text",text:o.join(`
|
|
1304
|
+
`).trim();return!i&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:i}}async checkFile(e){let t=_n(e),r=await fn.promises.readFile(e,"utf8"),o=Wi(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=this.manager.projectRoot,o=[];for(let i of e){let s=Hr.resolve(Hr.isAbsolute(i)?i:Hr.join(r,i));if(!fn.existsSync(s)){t.push(`File does not exist: ${i}`);continue}if(!fn.statSync(s).isFile()){t.push(`Not a regular file: ${i}`);continue}if(!Mn(s)){t.push(`Not a supported C/C++ file: ${i}`);continue}try{o.push(fn.realpathSync(s))}catch{o.push(s)}}return o}};function AI(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 DI(n){return new Promise(e=>setTimeout(e,n))}import*as Ur from"fs";import*as la from"path";var $r=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 Fr();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};g.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 ca(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 g.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return Fr();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e}`}],isError:!0};g.info(`[ClangdLspTool] handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async 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 ca("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return Fr();if(e.direction==="outgoing")return{content:[{type:"text",text:"callHierarchy outgoing is not supported by clangd (incoming only)"}],isError:!0};let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e.file}`}],isError:!0};g.info(`[ClangdLspTool] handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,i=>this.fetchCallHierarchyResult(i,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return ca("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=_n(e),o=await Ur.promises.readFile(e,"utf8"),i=Wi(e);g.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=la.isAbsolute(e)?e:la.join(this.manager.projectRoot,e);return!Ur.existsSync(t)||!Ur.statSync(t).isFile()||!Mn(t)?null:t}};import{spawn as RI}from"child_process";import*as ua from"fs";import*as eh from"path";var TI=30*1e3,kI=30*1e3,da=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new ln;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,nodePath:this.config.nodePath};this.client=new cn(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,Ye),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}`))},kI);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=${U(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];m.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=RI(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=cr(this.config.workspaceRoot),t=at(e),r=eh.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"0.4.0-TD.3"},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=TI){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){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:T,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:T,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:T,method:y.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{ua.existsSync(this.config.logPath)||ua.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)),at(r)}}catch{}return e}};import*as zo from"path";import*as Gt from"fs";var Yo=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.patchSdkPathInCompileCommands(),this.proxy.sendFeatureRequest(e,t)}registerDiagnosticCallback(e){return this.proxy?this.proxy.registerDiagnosticCallback(e):Promise.reject(new Error("[ClangdLspManager] LSP not ready"))}patchSdkPathInCompileCommands(){if(!b()||this.config.toolProvider.sourceType==="studio"||process.env.COMMAND_LINE_TOOL_PATH?.trim()===A.OPENHARMONY_STUDIO_ROOT)return;let e=sr(this.projectRoot);if(!Gt.existsSync(e))return;let t=Gt.readFileSync(e,"utf8");if(!t.includes(Yi))return;let r=t.replaceAll(Yi,this.config.toolProvider.sdkPath);Gt.writeFileSync(e,r,"utf8"),m.info(`[CppCheck] Patched SDK path in compile_commands.json: ${Yi} -> ${this.config.toolProvider.sdkPath}`)}static async handleSyncCppProject(e,t){if(m.info("[ClangdLspManager] Received cpp/syncProject"),!e)return m.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or devecoPath is empty"),{status:"failed",reason:"workspaceRoot or devecoPath is empty"};if(jn(e).length===0)return m.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let o=await Fi(e,async()=>{try{return await np(e,t),m.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(i){let s=i instanceof Error?i.message:String(i);return m.error(`[ClangdLspManager] compileNative failed: ${s}`),{status:"failed",reason:s}}});return o.acquired?o.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(Ye);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=kt(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.toolProvider.clangdPath;if(!r){let s="clangd executable not found inside DevEco Studio SDK";m.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let o=zo.dirname(sr(this.resolvedRoot));try{Gt.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 da({clangdPath:r,workspaceRoot:this.resolvedRoot,compileCommandsDir:o,logPath:t,nodePath:this.config.toolProvider.nodePath});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=zo.join(nn(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=zo.join(e,"lsp-log",t);return Gt.mkdirSync(r,{recursive:!0}),fe(r)}catch{return"auto"}}};function th(n){let e=Hi(n);return m.info(`[SyncGuard] ${e.reason}`),e}var Bl=(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))(Bl||{}),rh=(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))(rh||{}),Et=3,$l=600*1e3,Ul=100,pa=class{server;toolRouter;config;arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";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,Fn(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),g.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",g.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,g.info(`Constructor: using configured path as startPath: '${t}'`));let o=kt(t);g.info(`Constructor: findHarmonyProject('${t}') => ${o??"null"}`),this.config.projectPath=o??void 0,this.server=new xI({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=_l(),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:de.object({target:de.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:de.object({files:de.array(de.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){g.info("Skip registering LSP feature tools (hover/definition/declaration/references/implementation, workspaceSymbol, documentSymbol, callHierarchy): standard LSP protocol unavailable (standardIndex/index.js not found). These tools require a DevEco Studio version that ships the standard LSP server entry.");return}let e=de.object({file:de.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:de.number().describe("Line number (0-based)"),character:de.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:de.object({query:de.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:de.object({file:de.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:de.object({file:de.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:de.number().describe("Line number (0-based)"),character:de.number().describe("Character offset in the line (0-based)"),direction:de.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.config.toolProvider.lspServerPath;if(!e)return g.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=mn.join(mn.dirname(e),"standardIndex","index.js"),r=nh.existsSync(t);return g.info(`ArktsCheck protocol: ${r?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${r})`),r}catch(e){return g.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=R.isPathContainedWithSymlink(i,t);s.contained||(g.warn(`Containment check failed: ${s.reason}`),o.push(s.reason))}return o.length>0?{content:[{type:"text",text:o.join(`
|
|
1305
1305
|
`)}],isError:!0}:null}let r=e.filter(o=>mn.isAbsolute(o));return r.length>0?(g.warn(`Absolute paths rejected (no project root): ${r.join(", ")}`),{content:[{type:"text",text:r.map(o=>`Absolute path is not allowed: ${o}`).join(`
|
|
1306
|
-
`)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(d=>typeof d=="string"):[];if(t.length===0)return g.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};if(t.length>
|
|
1306
|
+
`)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(d=>typeof d=="string"):[];if(t.length===0)return g.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};if(t.length>Ul)return g.warn(`check tool called with ${t.length} files (max: ${Ul})`),{content:[{type:"text",text:`Too many files: ${t.length}. Maximum allowed is ${Ul}.`}],isError:!0};let{etsFiles:r,cppFiles:o,unsupported:i}=LI(t);i.length>0&&g.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(`
|
|
1307
1307
|
`),s.join(`
|
|
1308
1308
|
`)].filter(d=>d.trim().length>0).join(`
|
|
1309
|
-
`).trim()||"No diagnostics collected"}],isError:c}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return g.warn(`ArkTS check rejected: project is ${Hl[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return g.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return this.arktsCheckTool.handleCall({files:e});default:return g.error(`ArkTS check: unknown project state ${this.projectState}, files: ${e.join(", ")}`),{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],isError:!0}}}async handleLspFeatureCall(e,t){let r=t.file,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 g.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){g.warn(`workspaceSymbol ArkTS query failed: ${a.message}`)}if(r)try{this.mergeSymbolItems(await this.cppLspTool.handleWorkspaceSymbolRaw(e),i,o)}catch(a){g.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}/${Et})`;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}/${Et})`;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 g.warn(`ArkTS ${e} rejected: project is ${Hl[this.projectState]}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return g.warn(`ArkTS ${e} rejected: LSP is initializing`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return t();default:return g.error(`ArkTS ${e}: unknown project state ${this.projectState}`),{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],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"),g.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(g.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:"Initializing, please retry in 10 seconds"}],isError:!0}):(g.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"No HarmonyOS project detected. Please verify the project directory or create a project first."}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=Et?(g.error(`Init retry limit reached (${this.initRetryCount}/${Et}), will not auto-retry`),{content:[{type:"text",text:`Project initialization failed repeatedly (auto-retry exhausted: ${this.initRetryCount}/${Et}). 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}):(g.info(`Error check: auto-retrying (${this.initRetryCount}/${Et})`),this.ensureProjectReady(),{content:[{type:"text",text:"Project initialization failed, auto-retrying, please retry in 10 seconds"}],isError:!0})}async routeCppRequest(e,t){switch(this.cppProjectState){case 0:return this.handleCppIdleCheck();case 1:case 2:return g.warn(`C++ ${e} rejected: C++ project is ${eh[this.cppProjectState]}`),{content:[{type:"text",text:"C++ project is syncing (compileNative), please retry in 25 seconds"}],isError:!0};case 3:return g.warn(`C++ ${e} rejected: clangd is initializing`),{content:[{type:"text",text:"C++ LSP (clangd) is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleCppErrorCheck();case 4:return this.cppHasNoCppCode?{content:[{type:"text",text:"No C++ code in this project"}],isError:!0}:this.cppLspManager?.ready?t():{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0};default:return g.error(`C++ ${e}: unknown C++ project state ${this.cppProjectState}`),{content:[{type:"text",text:`Unknown C++ project state: ${this.cppProjectState}`}],isError:!0}}}async routeLspRequest(e,t,r){return e.endsWith(".ets")?this.routeArktsRequest(t,r):Mn(e)?this.routeCppRequest(t,r):{content:[{type:"text",text:`Unsupported file type: ${e} (only .ets and C/C++ source/header files are supported)`}],isError:!0}}async handleCppIdleCheck(){if(this.ensureCppProjectReady(),this.config.projectPath){let e;return this.cppSyncSkippedDueToLock?(e=`Another build process is running, C++ sync deferred (waiting ${this.cppSyncSkipStartedAt>0?Math.round((Date.now()-this.cppSyncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,this.cppSyncSkippedDueToLock=!1):e="C++ project detected, syncing (compileNative), please retry in 25 seconds",g.info(`C++ idle check: project '${this.config.projectPath}', triggering C++ init`),{content:[{type:"text",text:e}],isError:!0}}return{content:[{type:"text",text:"No HarmonyOS project detected for C++ tools."}],isError:!0}}async handleCppErrorCheck(){return this.cppInitRetryCount>=Et?(g.error(`C++ init retry limit reached (${this.cppInitRetryCount}/${Et}), will not auto-retry`),{content:[{type:"text",text:`C++ project initialization failed repeatedly (auto-retry exhausted: ${this.cppInitRetryCount}/${Et}). 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}):(g.info(`C++ error check: auto-retrying (${this.cppInitRetryCount}/${Et})`),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(`
|
|
1310
|
-
`);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){g.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=>g.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,g.info("[restart] ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(e=>g.warn("Failed to re-init ArkTS project during restart:",e)))}restartCpp(){this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(e=>g.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,g.info("[restart] C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>g.warn("Failed to re-init C++ project during restart:",e)))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{g.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(t=>{g.warn("Failed to dispose ClangdLspManager during setProjectPath:",t)}),this.cppLspManager=null),this.initPromise?(this.needsReinit=!0,g.info("Project path changed while ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{g.warn("Failed to re-init project after setProjectPath:",t)})),this.cppInitPromise?(this.cppNeedsReinit=!0,g.info("Project path changed while C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.cppHasNoCppCode=!1,this.cppInitRetryCount=0,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.ensureCppProjectReady().catch(t=>{g.warn("Failed to re-init C++ project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new DI;if(await this.server.connect(e),g.info("devecocli-mcp-server started"),!this.config.debug){let t=$u();t&&g.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=kt(t);r?(g.info(`Detected project path from client root: ${r}`),this.config.projectPath=r):g.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?g.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):g.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{g.warn("Background project init failed:",t)})}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return g.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return g.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){g.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,g.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{g.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{g.error("shutdown failed:",r),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{g.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?kt(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=kt(this.originalProjectPath),t&&g.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=>{g.warn("Background C++ project init failed:",e)}),this.projectState=3,this.arktsCheckTool=new Mr(this.config.projectPath,this.config.toolProvider,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{g.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,g.info("Project fully initialized, check tool is available")}catch(e){g.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=Zm(e),r=!t.required;return g.info(`Sync check: skipHvigor=${r}, reason=${t.reason}`),this.runSync(e,{skipHvigorSync:r})}async runSync(e,t){this.projectState=2,g.info("Starting project sync...");let r=await Or.handleSyncProject(e,this.config.toolProvider,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>=Fl?(g.error(`Sync skipped for ${i}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(g.warn(`Sync skipped: ${r.reason}, resetting to IDLE for retry (elapsed ${i}s / ${Fl/1e3}s)`),this.projectState=0,!1)}case"failed":return g.error(`Project sync failed: ${r.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:return g.error(`Project sync: unknown status ${r.status}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}async ensureCppProjectReady(){if(!this.cppInitPromise){this.cppInitPromise=this.doEnsureCppProjectReady();try{await this.cppInitPromise}finally{this.cppInitPromise=null}this.cppNeedsReinit&&(this.cppNeedsReinit=!1,this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>{g.warn("Failed to re-init C++ project after cppNeedsReinit:",e)}))}}async doEnsureCppProjectReady(){let e=this.config.projectPath;if(!e){g.info("[Cpp] No project path, skipping C++ init");return}this.cppProjectState=1;let t=jn(e);if(t.length===0){g.info('[Cpp] No C++ modules found, C++ tools will return "no C++ code"'),this.cppHasNoCppCode=!0,this.cppProjectState=4,this.cppInitRetryCount=0;return}if(this.cppHasNoCppCode=!1,g.info(`[Cpp] Found ${t.length} C++ module(s): ${t.map(r=>r.name).join(", ")}`),!!await this.runSyncCpp(e)){this.cppProjectState=3,this.cppLspManager=new zo({workspaceRoot:e,toolProvider:this.config.toolProvider});try{await this.cppLspManager.start(),this.cppCheckTool=new Fr(this.cppLspManager,this.config.toolProvider),this.cppLspTool=new Hr(this.cppLspManager),this.cppProjectState=4,this.cppInitRetryCount=0,g.info("[Cpp] C++ project fully initialized, C++ tools are available")}catch(r){g.error("[Cpp] C++ LSP initialization failed:",r),this.cppLspManager&&this.cppLspManager.dispose().catch(()=>{}),this.cppLspManager=null,this.cppCheckTool=null,this.cppLspTool=null,this.cppInitRetryCount++,this.cppProjectState=5}}}async runSyncCpp(e){this.cppProjectState=2,g.info("[Cpp] Starting C++ project sync (compileNative)...");let t=await zo.handleSyncCppProject(e,this.config.toolProvider);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>=Fl?(g.error(`[Cpp] C++ sync skipped for ${o}s due to lock contention, giving up`),this.cppInitRetryCount++,this.cppSyncSkipStartedAt=0,this.cppProjectState=5,!1):(g.warn(`[Cpp] C++ sync skipped: ${t.reason}, resetting to IDLE_CPP for retry (elapsed ${o}s)`),this.cppProjectState=0,!1)}case"failed":return g.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){g.warn("Failed to close MCP server connection:",e)}g.info("devecocli-mcp-server stopped"),Hu(),ju()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function RI(n){let e=[],t=[],r=[];for(let o of n)mn.extname(o).toLowerCase()===".ets"?e.push(o):Mn(o)?t.push(o):r.push(o);return{etsFiles:e,cppFiles:t,unsupported:r}}function $l(n){return new ua(n)}import*as Ul from"fs";import*as hn from"path";import{spawn as TI}from"child_process";async function th(n){Fn(!1);let{serverPath:e,logPath:t,projectPath:r,serverMaxSize:o}=await kI(n),i=LI(e,t,r,n.toolProvider,o);g.info("ace-server started, bridging stdio (initialize is left to the client)"),MI(i)}async function kI(n){E()||n.toolProvider.require({clt:!1});let e;if(n.projectPath)e=fe(hn.resolve(n.projectPath)),g.info(`projectPath=specified ('${e}'), no search`);else if(n.autoDetect){let a=Ui(process.cwd());e=fe(a??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${a??"null, fallback to cwd"}`)}else e=fe(process.cwd()),g.info(`projectPath=cwd ('${e}'), no search (pass --auto-detect to search subdirs)`);let t=n.toolProvider.sdkPath,r=n.toolProvider.lspServerPath;r||(g.error("ace-server not found in DevEco Studio installation."),process.exit(1));let o=hn.resolve(hn.dirname(r),"standardIndex","index.js"),i=hn.join(nn(),"lsp-server",String(Date.now()));Ul.mkdirSync(i,{recursive:!0});let s=xI(e,t);return g.info(`projectPath=${e}, sdkPath=${t}, serverPath=${o}, logPath=${i}, serverMaxSize=${s}MB`),{projectPath:e,serverPath:o,logPath:i,serverMaxSize:s}}function xI(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=NI(n,e),s=Yi(i,o);return g.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${i}, override=${o??"none"})`),s}function NI(n,e){try{let t=[];return new Jn(n,e).getAllDependencyMap(t).status==="OK"?t.length:new xt(n).getAllModuleInfo().length}catch{return 0}}function LI(n,e,t,r,o){let i=hn.join(e,"lspLog");Ul.mkdirSync(i,{recursive:!0});let s=OI(n,i,t,r.sdkPath,o),a=r.nodePath;return g.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),TI(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function OI(n,e,t,r,o){let i=U(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=${U(t)}`,`--sdkPath=${U(r)}`]}function MI(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{g.error(`[ace-server] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{g.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{g.info(`ace-server exited with code ${e}`),process.exit(e??0)})}import*as nh from"fs";import*as Kn from"path";import{spawn as _I}from"child_process";async function rh(n){Fn(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await FI(n),o=Kn.join(t,"compile_commands.json");nh.existsSync(o)||g.warn(`compile_commands.json not found at ${o}. Cross-file navigation/completion will be limited. Run \`devecocli build\` first to generate it.`);let i=jI(e,t,r);g.info("clangd started, bridging stdio (initialize is left to the client)"),$I(i)}async function FI(n){let e;if(n.projectPath)e=fe(Kn.resolve(n.projectPath)),g.info(`projectPath=specified ('${e}'), no search`);else if(n.autoDetect){let i=Ui(process.cwd());e=fe(i??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${i??"null, fallback to cwd"}`)}else e=fe(Kn.resolve(process.cwd())),g.info(`projectPath=cwd ('${e}'), no search (pass --auto-detect to search subdirs)`);let t=n.toolProvider.clangdPath;t||(g.error("clangd not found in DevEco Studio SDK. Expected at <deveco>/sdk/default/openharmony/native/llvm/bin/clangd"),process.exit(1));let r=ir(e),o=Kn.dirname(r);return g.info(`projectPath=${e}, clangdPath=${t}, compileCommandsDir=${o}`),{projectPath:e,clangdPath:t,compileCommandsDir:o}}function jI(n,e,t){let r=HI(e);return g.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),_I(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function HI(n){return[`--compile-commands-dir=${U(n)}`,"--log=info","--pch-storage=memory"]}function $I(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{g.error(`[clangd] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{g.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{g.info(`clangd exited with code ${e}`),process.exit(e??0)})}async function BI(){let n=process.env.PROJECT_PATH||"",e=process.env.NODE_MAX_OLD_SPACE_SIZE,t=process.env.DEBUG==="true"||process.env.DEBUG==="1",r=await A.new();E()||r.require({clt:!1});let i=$l({toolProvider:r,projectPath:n,nodeMaxOldSpaceSize:e,debug:t}),s=async()=>{await i.shutdown(),process.exit(0)};process.once("SIGINT",s),process.once("SIGTERM",s),process.platform==="win32"&&process.once("SIGBREAK",s);try{await i.start()}catch(a){console.error("Failed to start MCP server:",a),process.exit(1)}}var Bl=new UI("serve").description("Host bundled auxiliary protocol servers");Bl.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await BI()});Bl.command("lsp").description("Start a bundled LSP language server").option("--arkts","Start the ArkTS language server (ace-server)").option("--cpp","Start the C/C++ language server (clangd)").option("--project-path <path>","project root path (used as-is, no search)").option("--auto-detect","When --project-path is not specified, search the current directory and its subdirectories for the project root (no upward search)").action(async n=>{n.arkts&&n.cpp&&(console.error("--arkts and --cpp are mutually exclusive. Specify only one."),process.exit(1));let e=await A.new();n.arkts?await th({toolProvider:e,projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await rh({toolProvider:e,projectPath:n.projectPath,autoDetect:n.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var oh=Bl;import{Command as GR,InvalidArgumentError as Nd}from"commander";import{red as Ha,dim as VR}from"colorette";import*as oe from"fs";import*as Pt from"path";import RR from"adm-zip";import TR from"proper-lockfile";import py from"ora";import*as ft from"fs";import*as ri from"path";var gn=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],Xn={"harmonyos-guides":"\u5F00\u53D1\u6307\u5357","harmonyos-references":"API\u53C2\u8003","best-practices":"\u6700\u4F73\u5B9E\u8DF5","harmonyos-faqs":"FAQ","harmonyos-releases":"\u7248\u672C\u8BF4\u660E","harmonyos-roadmap":"\u53D8\u66F4\u9884\u544A"};var Ur="1.9.1",g2=48*1024*1024,ih=280,sh=6,ah=100,ch=3,lh=28,Wl=10,dh=/API参考|APIReference/i,Yo=200,uh=12,ph=4,Gl=8,fh=6,pa=700,Vl=250,ql=400,mh=1320,hh=120,gh=450,yh=250,wh=500,vh=480,Sh=80,bh=200,Eh=60,Ph=200,Ch=40,Ih=200,Ah=200,Dh=40,Br=500,Rh=Object.fromEntries(gn.map((n,e)=>[Xn[n],e])),yn=Object.fromEntries(gn.map((n,e)=>[n,e]));import*as Jo from"fs";import*as O from"path";import{fileURLToPath as Nh}from"url";import*as wn from"fs";import*as Th from"path";import{homedir as WI}from"os";var GI="deveco-cli",zl,Zn=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function VI(){let n=process.env.DEVECO_CLI_DATA_DIR;return n!==void 0&&xi(n)!==""}function kh(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":xi(n))||Th.join(WI(),".local","share",GI);try{return Ni(t)}catch(r){throw new Zn(r instanceof Error?r.message:String(r))}}async function xh(){let n=kh();await wn.promises.mkdir(n,{recursive:!0});let e;try{e=await wn.promises.realpath(n)}catch(r){throw new Zn(`DEVECO_CLI_DATA_DIR is not usable: ${r instanceof Error?r.message:String(r)}`)}if(!(await wn.promises.stat(e)).isDirectory())throw new Zn("DEVECO_CLI_DATA_DIR must be a writable directory.");return zl=e,e}function fa(n){let e=Wr();return VI()?[`Data directory (DEVECO_CLI_DATA_DIR): ${e}`,"If you changed this in System Environment Variables, open a new terminal and retry.",`Log file: ${n}`]:[`Data directory (default): ${e}`,"To use a custom location, set DEVECO_CLI_DATA_DIR and open a new terminal.",`Log file: ${n}`]}function Wr(){if(zl!==void 0)return zl;let n=kh();try{if(wn.existsSync(n))return wn.realpathSync(n)}catch{}return n}var qI="docs";function Gr(){return O.join(Wr(),qI)}function ee(){return O.join(Gr(),".index")}function ma(){return O.join(ee(),"build.lock")}function Ko(){return O.join(ee(),"build-status.json")}function Vr(){return O.join(ee(),"build-meta.json")}function Qn(){return O.join(ee(),"search.db")}function Xo(){return O.join(ee(),"sqlite-backend.json")}function Zo(){return O.join(ee(),"jieba-backend.json")}function Vt(){return O.join(ee(),".tmp")}function zI(){return O.join(Wr(),"logs")}function qr(){return O.join(zI(),"doc-init.log")}function YI(n,e){let t=e;for(;!t.endsWith(`${O.sep}dist`)&&t!==O.dirname(t);)t=O.dirname(t);return t}function Lh(n,e){return O.dirname(YI(n,e))}function Oh(){let n=Nh(import.meta.url),e=O.dirname(n);return n.includes(`${O.sep}dist${O.sep}`)?Lh(n,e):O.join(e,"..","..","..")}function JI(...n){let e=Nh(import.meta.url),t=O.dirname(e);return e.includes(`${O.sep}dist${O.sep}`)?[O.join(Lh(e,t),...n)]:[O.join(t,"..","..","..",...n)]}function Mh(...n){let e=Oh(),t=Jo.realpathSync(e);for(let r of JI(...n))try{let o=Jo.lstatSync(r);if(o.isSymbolicLink()||!o.isFile())throw new Error(`Unsafe documentation package asset: ${n.join("/")} must be a regular file.`);let i=Jo.realpathSync(r);if(!ao(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 vn(){return Mh("docs.zip")}function Yl(){return Mh("index.zip")}function _h(){return O.join(Oh(),"index","data")}import*as qt from"fs";import*as er from"path";var zt=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],ha=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};function Fh(n){return n instanceof ha}var Jl=null;function Kl(n){Jl=n}function Xl(){if(Jl)return Jl;let n=ee();if(zt.every(o=>qt.existsSync(er.join(n,o))))return n;let t=_h();if(zt.every(o=>qt.existsSync(er.join(t,o))))return t;throw new ha("Lexicon files not found. Install the documentation index first (index.zip).")}function jh(){Xl()}function tr(n){let e=er.join(Xl(),n);return qt.readFileSync(e,"utf-8")}function Hh(n,e){return qt.readFileSync(er.join(e,n),"utf-8")}async function $h(n,e=Xl()){await qt.promises.mkdir(n,{recursive:!0});for(let t of zt){let r=er.join(e,t),o=er.join(n,t);await qt.promises.copyFile(r,o)}}import*as ga from"fs";import*as Uh from"path";import*as Bh from"yauzl";var Qo=null;function KI(n){return new Promise((e,t)=>{Bh.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 XI(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function ZI(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",o=>{let i=XI(o);i.endsWith("/")||e.set(i,o),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function QI(){Qo?.zipfile.close(),Qo=null}async function eA(n){let e=Uh.resolve(n),t=await ga.promises.stat(e),r=Qo;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;QI();let o=await KI(e),i=await ZI(o);return Qo={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:o,entries:i,readChain:Promise.resolve()},Qo}function tA(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 nA(n,e){let t=n.readChain,r;n.readChain=new Promise(o=>{r=o}),await t;try{return await tA(n.zipfile,e)}finally{r()}}function rA(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 oA(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function Wh(n){let e=vn();if(!e)throw new Error("docs.zip not found");let t=await eA(e),r=oA(t.entries,rA(n));if(!r)throw new Error(`Document not found: ${n}`);return(await nA(t,r)).toString("utf-8")}function Zl(){let n=vn();return n!==null&&ga.existsSync(n)}import*as ge from"fs";import*as Yt from"path";import Gh from"adm-zip";import*as ei from"fs";import*as wa from"path";var ya=class extends Error{constructor(e){super(`Unsafe documentation path: ${e}`),this.name="DocPathSafetyError"}};function ti(n){return n instanceof Zn||n instanceof ya||n instanceof Error&&(n.name==="CliDataDirError"||n.name==="DocPathSafetyError")}function td(n){return new ya(n)}function iA(){return wt(Wr())}function ed(n,e,t){let r=ki(n,e);if(r===null)throw td(`${t} resolves outside the data directory.`);return r}async function Ql(n,e){await ei.promises.mkdir(n,{recursive:!0});let t=ed(n,e,"directory");if(!(await ei.promises.stat(t)).isDirectory())throw td("path must be a directory.")}function ni(n){let e=iA();try{let t=ed(n,e,"file");if(!ei.statSync(t).isFile())throw td("path must be a regular file.")}catch(t){if(t.code==="ENOENT"){ed(wa.dirname(n),e,"file parent");return}throw t}}async function zr(n={}){let e=n.mode??"write",t=await xh();await Ql(Gr(),t),await Ql(ee(),t),e==="write"&&await Ql(Vt(),t);for(let r of[Qn(),Vr(),Ko(),ma(),Zo(),Xo(),...zt.map(o=>wa.join(ee(),o))])ni(r)}var nd=["search.db","build-meta.json",...zt],sA=["corpus.json","corpus-offsets.json","orama.dpack"];async function aA(n){for(let e of sA)await ge.promises.rm(Yt.join(n,e),{force:!0})}async function cA(n){let e=await ge.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await ge.promises.rm(Yt.join(n,t.name),{recursive:!0,force:!0})}function Vh(n){let t=new Gh(n).getEntry("build-meta.json");if(!t)throw new Error("index.zip is missing build-meta.json");return JSON.parse(t.getData().toString("utf-8"))}async function lA(n){let e=ee();await ge.promises.mkdir(e,{recursive:!0});for(let t of nd){let r=Yt.join(e,t);await ge.promises.rm(r,{force:!0}),await ge.promises.rename(Yt.join(n,t),r)}await aA(e),await ge.promises.rm(Vt(),{recursive:!0,force:!0})}function qh(n){let e=Yl();if(!e)return!1;try{let t=Vh(e);return t.indexVersion===Ur&&t.docsZipSha256===n&&t.segmentCount>0}catch{return!1}}async function zh(n){await zr({mode:"write"});let e=Yl();if(!e)throw new Error("index.zip not found");let t=Vh(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=Vt();await ge.promises.rm(r,{recursive:!0,force:!0}),await ge.promises.mkdir(r,{recursive:!0});let o=new Gh(e);for(let s of nd){let a=o.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await ge.promises.writeFile(Yt.join(r,s),a.getData())}let i=JSON.parse(await ge.promises.readFile(Yt.join(r,"build-meta.json"),"utf-8"));if(!ge.existsSync(Yt.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await lA(r),await ge.promises.mkdir(Gr(),{recursive:!0}),await cA(Gr()),i}async function Yh(){await ge.promises.rm(Vt(),{recursive:!0,force:!0});let n=ee();for(let e of nd)await ge.promises.rm(Yt.join(n,e),{force:!0})}import{createHash as Jh}from"crypto";import*as Kh from"fs";async function va(n){return new Promise((e,t)=>{let r=Jh("sha256"),o=Kh.createReadStream(n);o.on("data",i=>r.update(i)),o.on("error",t),o.on("end",()=>e(r.digest("hex")))})}function Xh(n){return Jh("sha256").update(n,"utf8").digest("hex")}var rd=null;function dA(){let n=tr("harmonyos-synonyms.json");return JSON.parse(n)}function uA(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 pA(){let n=uA(dA()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function fA(){return rd||(rd=pA()),rd}function od(n,e){let t=fA(),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 Zh(n,e){let t=e?Hh(n,e):tr(n);return Xh(t)}function Sa(n){return Zh("harmonyos-synonyms.json",n)}function ba(n){return Zh("harmonyos-terms.txt",n)}var mA={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function Ea(){try{let n=await ft.promises.readFile(Ko(),"utf-8");return JSON.parse(n)}catch{return{...mA}}}async function id(n){let e=Ko();await ft.promises.mkdir(ri.dirname(e),{recursive:!0}),await ft.promises.writeFile(e,JSON.stringify(n,null,2))}function Qh(n){let e=Date.now();return{state:"extracting",phase:1,phaseLabel:"Extracting documentation",current:0,total:0,message:n,startedAt:e,updatedAt:e,error:null}}async function Sn(n){let t={...await Ea(),...n,updatedAt:Date.now()};return await id(t),t}async function sd(){let n=vn();return n?va(n):null}async function ad(){try{let n=await ft.promises.readFile(Vr(),"utf-8");return JSON.parse(n)}catch{return null}}async function Pa(n=!1){if(n)return"no-index";let e=await ad();if(!e||e.segmentCount===0)return"no-index";let t=await sd();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==Ur?"engine-upgraded":e.termsHash!==ba()?"terms-changed":e.synonymsHash!==Sa()?"synonyms-changed":null}function oi(){if(!Zl()||!ft.existsSync(Qn())||!ft.existsSync(Vr()))return!1;let n=ri.dirname(Qn());if(!zt.every(e=>ft.existsSync(ri.join(n,e))))return!1;try{let e=ft.readFileSync(Vr(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function cd(n=!1){return n?!0:Zl()?oi()?await Pa()!==null:!0:!1}async function eg(){let n=await Ea();return["installing","indexing","persisting"].includes(n.state)}import*as Ee from"fs";import*as iy from"os";import*as _e from"path";var tg=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),ld=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),ng=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"]),rg=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 hA=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,gA=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,yA=/[A-Z][a-zA-Z0-9]{2,}/g,wA=/@[A-Z][a-zA-Z0-9]*/g,vA=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,og=6,SA=/^[a-z][a-z0-9]{2,}$/,bA=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,EA=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,PA=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,CA=/^[A-Z][a-zA-Z0-9]+$/;function IA(n){return`"${n.replace(/"/g,'""')}"`}function si(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(IA).join(` ${e} `)}function ii(n){return si(n,"OR")}function ig(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?ii([...t,...r]):`(${ii(t)}) AND (${ii(r)})`}function ai(n){return EA.test(n)}function sg(n){return PA.test(n)&&n.length>=og}function AA(n){return CA.test(n)}function ci(n){return ai(n)||sg(n)||AA(n)}function DA(n){let e=n.trim().toLowerCase();return rg.has(e)?!1:tg.has(e)}function RA(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function Ca(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function dd(n){return[...n.matchAll(hA)].map(e=>e[0])}function ud(n,e=og){let t=[];for(let r of n.matchAll(gA))r[0].length>=e&&t.push(r[0]);return t}function Yr(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 mt(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function TA(n){let e=new Set;mt(e,n);let t=Ca(n);return t&&mt(e,t),Yr([...e])}function Ia(n){if(ai(n))return TA(n);let e=new Set;return mt(e,n),Yr([...e])}function Aa(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(bA);if(!t)return null;let r=t[1].toLowerCase(),o=t[2].toLowerCase();if(!SA.test(r)||ng.has(r)||!DA(o))return null;let i=RA(r,o);return{first:r,second:o,camelCase:i,lower:i.toLowerCase()}}function pd(n){let e=Aa(n.trim());return!e||e.second!=="manager"?null:e}function kA(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function ag(n){let e=n.trim(),t=pd(e);if(t&&ld.has(t.first))return!0;if(sg(e)){let r=kA(e);return r!==null&&ld.has(r)}return!1}function fd(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 md(n){let e=n.trim();if(ci(e))return Ia(e);let t=new Set;for(let r of dd(n)){mt(t,r);let o=Ca(r);o&&mt(t,o)}for(let r of ud(n))mt(t,r);for(let r of n.matchAll(wA))t.add(r[0]);for(let r of n.matchAll(vA))t.add(r[0]);for(let r of n.matchAll(yA))r[0].length>=4&&t.add(r[0]);return Yr([...t])}function cg(n){let e=n.trim();if(ci(e))return Ia(e);let t=new Set,r=Aa(e);r&&mt(t,r.camelCase);for(let o of md(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 Yr([...t])}function lg(n){return ci(n)}var X={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 dg(n){return X.pureApiSymbol.test(n.trim())}function li(n){let e=n.trim();return X.stageModelExact.test(e)||X.stageModelEnglishExact.test(e)}function ug(n){let e=[];return li(n.trim())&&e.push("Stage\u6A21\u578B","Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0"),X.declarePermissionTokens.test(n)&&e.push("\u58F0\u660E\u6743\u9650"),X.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 pg(n){return li(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var xA=[{matches:n=>X.uiAbilityLifecycleBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:n=>li(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!li(n)&&X.stageModel.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:n=>X.entryAbilityPage.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:n=>X.declarePermissionBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:n=>X.stateDecoratorBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:n=>X.stateManagement.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:n=>X.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=>X.dialogPopupBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function NA(n,e){for(let{catalog:t,multiplier:r}of e){let o=yn[t];n.set(o,(n.get(o)??1)*r)}}function fg(n,e){for(let t of xA)t.matches(n)&&NA(e,t.weights)}function mg(n,e){if(e!==void 0)return!1;let t=n.trim();return ai(t)||X.pureApiSymbol.test(t)||ag(t)}function hg(n){let e=n.trim();if(ai(e)||X.pureApiSymbol.test(e))return"harmonyos-references";if(li(e)||X.uiAbilityLifecycleCatalog.test(e)||X.stateDecoratorCatalog.test(e)||X.stateManagement.test(e)||X.declarePermissionCatalog.test(e)||X.stageModelEntryPage.test(e)||X.routerRoute.test(e)||X.dialogPopupExact.test(e))return"harmonyos-guides"}import*as Jr from"fs";import*as yg from"path";var Da=null,hd=null,gd=null;function LA(){return Jr.existsSync(Zo())}function OA(n){let e=Zo(),t={backend:"jieba-wasm",reason:"native-jieba-load-failed",message:n,createdAt:new Date().toISOString()};Jr.mkdirSync(yg.dirname(e),{recursive:!0}),ni(e),Jr.writeFileSync(e,JSON.stringify(t,null,2))}function MA(){if(Da)return Da;let n=tr("harmonyos-stopwords.txt");return Da=new Set(n.split(`
|
|
1311
|
-
`).map(e=>e.trim()).filter(Boolean)),
|
|
1309
|
+
`).trim()||"No diagnostics collected"}],isError:c}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return g.warn(`ArkTS check rejected: project is ${Bl[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return g.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return this.arktsCheckTool.handleCall({files:e});default:return g.error(`ArkTS check: unknown project state ${this.projectState}, files: ${e.join(", ")}`),{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],isError:!0}}}async handleLspFeatureCall(e,t){let r=t.file,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 g.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){g.warn(`workspaceSymbol ArkTS query failed: ${a.message}`)}if(r)try{this.mergeSymbolItems(await this.cppLspTool.handleWorkspaceSymbolRaw(e),i,o)}catch(a){g.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}/${Et})`;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}/${Et})`;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 g.warn(`ArkTS ${e} rejected: project is ${Bl[this.projectState]}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return g.warn(`ArkTS ${e} rejected: LSP is initializing`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return t();default:return g.error(`ArkTS ${e}: unknown project state ${this.projectState}`),{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],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"),g.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(g.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:"Initializing, please retry in 10 seconds"}],isError:!0}):(g.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"No HarmonyOS project detected. Please verify the project directory or create a project first."}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=Et?(g.error(`Init retry limit reached (${this.initRetryCount}/${Et}), will not auto-retry`),{content:[{type:"text",text:`Project initialization failed repeatedly (auto-retry exhausted: ${this.initRetryCount}/${Et}). 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}):(g.info(`Error check: auto-retrying (${this.initRetryCount}/${Et})`),this.ensureProjectReady(),{content:[{type:"text",text:"Project initialization failed, auto-retrying, please retry in 10 seconds"}],isError:!0})}async routeCppRequest(e,t){switch(this.cppProjectState){case 0:return this.handleCppIdleCheck();case 1:case 2:return g.warn(`C++ ${e} rejected: C++ project is ${rh[this.cppProjectState]}`),{content:[{type:"text",text:"C++ project is syncing (compileNative), please retry in 25 seconds"}],isError:!0};case 3:return g.warn(`C++ ${e} rejected: clangd is initializing`),{content:[{type:"text",text:"C++ LSP (clangd) is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleCppErrorCheck();case 4:return this.cppHasNoCppCode?{content:[{type:"text",text:"No C++ code in this project"}],isError:!0}:this.cppLspManager?.ready?t():{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0};default:return g.error(`C++ ${e}: unknown C++ project state ${this.cppProjectState}`),{content:[{type:"text",text:`Unknown C++ project state: ${this.cppProjectState}`}],isError:!0}}}async routeLspRequest(e,t,r){return e.endsWith(".ets")?this.routeArktsRequest(t,r):Mn(e)?this.routeCppRequest(t,r):{content:[{type:"text",text:`Unsupported file type: ${e} (only .ets and C/C++ source/header files are supported)`}],isError:!0}}async handleCppIdleCheck(){if(this.ensureCppProjectReady(),this.config.projectPath){let e;return this.cppSyncSkippedDueToLock?(e=`Another build process is running, C++ sync deferred (waiting ${this.cppSyncSkipStartedAt>0?Math.round((Date.now()-this.cppSyncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,this.cppSyncSkippedDueToLock=!1):e="C++ project detected, syncing (compileNative), please retry in 25 seconds",g.info(`C++ idle check: project '${this.config.projectPath}', triggering C++ init`),{content:[{type:"text",text:e}],isError:!0}}return{content:[{type:"text",text:"No HarmonyOS project detected for C++ tools."}],isError:!0}}async handleCppErrorCheck(){return this.cppInitRetryCount>=Et?(g.error(`C++ init retry limit reached (${this.cppInitRetryCount}/${Et}), will not auto-retry`),{content:[{type:"text",text:`C++ project initialization failed repeatedly (auto-retry exhausted: ${this.cppInitRetryCount}/${Et}). 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}):(g.info(`C++ error check: auto-retrying (${this.cppInitRetryCount}/${Et})`),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(`
|
|
1310
|
+
`);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){g.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=>g.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,g.info("[restart] ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(e=>g.warn("Failed to re-init ArkTS project during restart:",e)))}restartCpp(){this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(e=>g.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,g.info("[restart] C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>g.warn("Failed to re-init C++ project during restart:",e)))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{g.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(t=>{g.warn("Failed to dispose ClangdLspManager during setProjectPath:",t)}),this.cppLspManager=null),this.initPromise?(this.needsReinit=!0,g.info("Project path changed while ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{g.warn("Failed to re-init project after setProjectPath:",t)})),this.cppInitPromise?(this.cppNeedsReinit=!0,g.info("Project path changed while C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.cppHasNoCppCode=!1,this.cppInitRetryCount=0,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.ensureCppProjectReady().catch(t=>{g.warn("Failed to re-init C++ project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new NI;if(await this.server.connect(e),g.info("devecocli-mcp-server started"),!this.config.debug){let t=Wu();t&&g.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=kt(t);r?(g.info(`Detected project path from client root: ${r}`),this.config.projectPath=r):g.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?g.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):g.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{g.warn("Background project init failed:",t)})}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return g.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return g.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){g.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,g.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{g.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{g.error("shutdown failed:",r),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{g.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?kt(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=kt(this.originalProjectPath),t&&g.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=>{g.warn("Background C++ project init failed:",e)}),this.projectState=3,this.arktsCheckTool=new _r(this.config.projectPath,this.config.toolProvider,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{g.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,g.info("Project fully initialized, check tool is available")}catch(e){g.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=th(e),r=!t.required;return g.info(`Sync check: skipHvigor=${r}, reason=${t.reason}`),this.runSync(e,{skipHvigorSync:r})}async runSync(e,t){this.projectState=2,g.info("Starting project sync...");let r=await Mr.handleSyncProject(e,this.config.toolProvider,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>=$l?(g.error(`Sync skipped for ${i}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(g.warn(`Sync skipped: ${r.reason}, resetting to IDLE for retry (elapsed ${i}s / ${$l/1e3}s)`),this.projectState=0,!1)}case"failed":return g.error(`Project sync failed: ${r.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:return g.error(`Project sync: unknown status ${r.status}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}async ensureCppProjectReady(){if(!this.cppInitPromise){this.cppInitPromise=this.doEnsureCppProjectReady();try{await this.cppInitPromise}finally{this.cppInitPromise=null}this.cppNeedsReinit&&(this.cppNeedsReinit=!1,this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>{g.warn("Failed to re-init C++ project after cppNeedsReinit:",e)}))}}async doEnsureCppProjectReady(){let e=this.config.projectPath;if(!e){g.info("[Cpp] No project path, skipping C++ init");return}this.cppProjectState=1;let t=jn(e);if(t.length===0){g.info('[Cpp] No C++ modules found, C++ tools will return "no C++ code"'),this.cppHasNoCppCode=!0,this.cppProjectState=4,this.cppInitRetryCount=0;return}if(this.cppHasNoCppCode=!1,g.info(`[Cpp] Found ${t.length} C++ module(s): ${t.map(r=>r.name).join(", ")}`),!!await this.runSyncCpp(e)){this.cppProjectState=3,this.cppLspManager=new Yo({workspaceRoot:e,toolProvider:this.config.toolProvider});try{await this.cppLspManager.start(),this.cppCheckTool=new jr(this.cppLspManager,this.config.toolProvider),this.cppLspTool=new $r(this.cppLspManager),this.cppProjectState=4,this.cppInitRetryCount=0,g.info("[Cpp] C++ project fully initialized, C++ tools are available")}catch(r){g.error("[Cpp] C++ LSP initialization failed:",r),this.cppLspManager&&this.cppLspManager.dispose().catch(()=>{}),this.cppLspManager=null,this.cppCheckTool=null,this.cppLspTool=null,this.cppInitRetryCount++,this.cppProjectState=5}}}async runSyncCpp(e){this.cppProjectState=2,g.info("[Cpp] Starting C++ project sync (compileNative)...");let t=await Yo.handleSyncCppProject(e,this.config.toolProvider);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>=$l?(g.error(`[Cpp] C++ sync skipped for ${o}s due to lock contention, giving up`),this.cppInitRetryCount++,this.cppSyncSkipStartedAt=0,this.cppProjectState=5,!1):(g.warn(`[Cpp] C++ sync skipped: ${t.reason}, resetting to IDLE_CPP for retry (elapsed ${o}s)`),this.cppProjectState=0,!1)}case"failed":return g.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){g.warn("Failed to close MCP server connection:",e)}g.info("devecocli-mcp-server stopped"),Bu(),Uu()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function LI(n){let e=[],t=[],r=[];for(let o of n)mn.extname(o).toLowerCase()===".ets"?e.push(o):Mn(o)?t.push(o):r.push(o);return{etsFiles:e,cppFiles:t,unsupported:r}}function Wl(n){return new pa(n)}import*as Gl from"fs";import*as hn from"path";import{spawn as OI}from"child_process";async function oh(n){Fn(!1);let{serverPath:e,logPath:t,projectPath:r,serverMaxSize:o}=await MI(n),i=jI(e,t,r,n.toolProvider,o);g.info("ace-server started, bridging stdio (initialize is left to the client)"),$I(i)}async function MI(n){b()||n.toolProvider.require({clt:!1});let e;if(n.projectPath)e=fe(hn.resolve(n.projectPath)),g.info(`projectPath=specified ('${e}'), no search`);else if(n.autoDetect){let a=Bi(process.cwd());e=fe(a??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${a??"null, fallback to cwd"}`)}else e=fe(process.cwd()),g.info(`projectPath=cwd ('${e}'), no search (pass --auto-detect to search subdirs)`);let t=n.toolProvider.sdkPath,r=n.toolProvider.lspServerPath;r||(g.error("ace-server not found in DevEco Studio installation."),process.exit(1));let o=hn.resolve(hn.dirname(r),"standardIndex","index.js"),i=hn.join(nn(),"lsp-server",String(Date.now()));Gl.mkdirSync(i,{recursive:!0});let s=_I(e,t);return g.info(`projectPath=${e}, sdkPath=${t}, serverPath=${o}, logPath=${i}, serverMaxSize=${s}MB`),{projectPath:e,serverPath:o,logPath:i,serverMaxSize:s}}function _I(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=FI(n,e),s=Ji(i,o);return g.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${i}, override=${o??"none"})`),s}function FI(n,e){try{let t=[];return new Kn(n,e).getAllDependencyMap(t).status==="OK"?t.length:new xt(n).getAllModuleInfo().length}catch{return 0}}function jI(n,e,t,r,o){let i=hn.join(e,"lspLog");Gl.mkdirSync(i,{recursive:!0});let s=HI(n,i,t,r.sdkPath,o),a=r.nodePath;return g.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),OI(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function HI(n,e,t,r,o){let i=U(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=${U(t)}`,`--sdkPath=${U(r)}`]}function $I(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{g.error(`[ace-server] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{g.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{g.info(`ace-server exited with code ${e}`),process.exit(e??0)})}import*as ih from"fs";import*as Xn from"path";import{spawn as UI}from"child_process";async function sh(n){Fn(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await BI(n),o=Xn.join(t,"compile_commands.json");ih.existsSync(o)||g.warn(`compile_commands.json not found at ${o}. Cross-file navigation/completion will be limited. Run \`devecocli build\` first to generate it.`);let i=WI(e,t,r);g.info("clangd started, bridging stdio (initialize is left to the client)"),VI(i)}async function BI(n){let e;if(n.projectPath)e=fe(Xn.resolve(n.projectPath)),g.info(`projectPath=specified ('${e}'), no search`);else if(n.autoDetect){let i=Bi(process.cwd());e=fe(i??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${i??"null, fallback to cwd"}`)}else e=fe(Xn.resolve(process.cwd())),g.info(`projectPath=cwd ('${e}'), no search (pass --auto-detect to search subdirs)`);let t=n.toolProvider.clangdPath;t||(g.error("clangd not found in DevEco Studio SDK. Expected at <deveco>/sdk/default/openharmony/native/llvm/bin/clangd"),process.exit(1));let r=sr(e),o=Xn.dirname(r);return g.info(`projectPath=${e}, clangdPath=${t}, compileCommandsDir=${o}`),{projectPath:e,clangdPath:t,compileCommandsDir:o}}function WI(n,e,t){let r=GI(e);return g.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),UI(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function GI(n){return[`--compile-commands-dir=${U(n)}`,"--log=info","--pch-storage=memory"]}function VI(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{g.error(`[clangd] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{g.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{g.info(`clangd exited with code ${e}`),process.exit(e??0)})}async function zI(){let n=process.env.PROJECT_PATH||"",e=process.env.NODE_MAX_OLD_SPACE_SIZE,t=process.env.DEBUG==="true"||process.env.DEBUG==="1",r=await A.new();b()||r.require({clt:!1});let i=Wl({toolProvider:r,projectPath:n,nodeMaxOldSpaceSize:e,debug:t}),s=async()=>{await i.shutdown(),process.exit(0)};process.once("SIGINT",s),process.once("SIGTERM",s),process.platform==="win32"&&process.once("SIGBREAK",s);try{await i.start()}catch(a){console.error("Failed to start MCP server:",a),process.exit(1)}}var Vl=new qI("serve").description("Host bundled auxiliary protocol servers");Vl.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await zI()});Vl.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));let e=await A.new();n.arkts?await oh({toolProvider:e,projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await sh({toolProvider:e,projectPath:n.projectPath,autoDetect:n.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var ah=Vl;import{Command as JR,InvalidArgumentError as Md}from"commander";import{red as $a,dim as KR}from"colorette";import*as oe from"fs";import*as Pt from"path";import LR from"adm-zip";import OR from"proper-lockfile";import hy from"ora";import*as ft from"fs";import*as oi from"path";var gn=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],Zn={"harmonyos-guides":"\u5F00\u53D1\u6307\u5357","harmonyos-references":"API\u53C2\u8003","best-practices":"\u6700\u4F73\u5B9E\u8DF5","harmonyos-faqs":"FAQ","harmonyos-releases":"\u7248\u672C\u8BF4\u660E","harmonyos-roadmap":"\u53D8\u66F4\u9884\u544A"};var Br="1.9.1",k2=48*1024*1024,ch=280,lh=6,dh=100,uh=3,ph=28,ql=10,fh=/API参考|APIReference/i,Jo=200,mh=12,hh=4,zl=8,gh=6,fa=700,Yl=250,Jl=400,yh=1320,wh=120,vh=450,Sh=250,bh=500,Eh=480,Ph=80,Ch=200,Ih=60,Ah=200,Dh=40,Rh=200,Th=200,kh=40,Wr=500,xh=Object.fromEntries(gn.map((n,e)=>[Zn[n],e])),yn=Object.fromEntries(gn.map((n,e)=>[n,e]));import*as Ko from"fs";import*as O from"path";import{fileURLToPath as Mh}from"url";import*as wn from"fs";import*as Nh from"path";import{homedir as YI}from"os";var JI="deveco-cli",Kl,Qn=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function KI(){let n=process.env.DEVECO_CLI_DATA_DIR;return n!==void 0&&Li(n)!==""}function Lh(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":Li(n))||Nh.join(YI(),".local","share",JI);try{return Oi(t)}catch(r){throw new Qn(r instanceof Error?r.message:String(r))}}async function Oh(){let n=Lh();await wn.promises.mkdir(n,{recursive:!0});let e;try{e=await wn.promises.realpath(n)}catch(r){throw new Qn(`DEVECO_CLI_DATA_DIR is not usable: ${r instanceof Error?r.message:String(r)}`)}if(!(await wn.promises.stat(e)).isDirectory())throw new Qn("DEVECO_CLI_DATA_DIR must be a writable directory.");return Kl=e,e}function ma(n){let e=Gr();return KI()?[`Data directory (DEVECO_CLI_DATA_DIR): ${e}`,"If you changed this in System Environment Variables, open a new terminal and retry.",`Log file: ${n}`]:[`Data directory (default): ${e}`,"To use a custom location, set DEVECO_CLI_DATA_DIR and open a new terminal.",`Log file: ${n}`]}function Gr(){if(Kl!==void 0)return Kl;let n=Lh();try{if(wn.existsSync(n))return wn.realpathSync(n)}catch{}return n}var XI="docs";function Vr(){return O.join(Gr(),XI)}function ee(){return O.join(Vr(),".index")}function ha(){return O.join(ee(),"build.lock")}function Xo(){return O.join(ee(),"build-status.json")}function qr(){return O.join(ee(),"build-meta.json")}function er(){return O.join(ee(),"search.db")}function Zo(){return O.join(ee(),"sqlite-backend.json")}function Qo(){return O.join(ee(),"jieba-backend.json")}function Vt(){return O.join(ee(),".tmp")}function ZI(){return O.join(Gr(),"logs")}function zr(){return O.join(ZI(),"doc-init.log")}function QI(n,e){let t=e;for(;!t.endsWith(`${O.sep}dist`)&&t!==O.dirname(t);)t=O.dirname(t);return t}function _h(n,e){return O.dirname(QI(n,e))}function Fh(){let n=Mh(import.meta.url),e=O.dirname(n);return n.includes(`${O.sep}dist${O.sep}`)?_h(n,e):O.join(e,"..","..","..")}function eA(...n){let e=Mh(import.meta.url),t=O.dirname(e);return e.includes(`${O.sep}dist${O.sep}`)?[O.join(_h(e,t),...n)]:[O.join(t,"..","..","..",...n)]}function jh(...n){let e=Fh(),t=Ko.realpathSync(e);for(let r of eA(...n))try{let o=Ko.lstatSync(r);if(o.isSymbolicLink()||!o.isFile())throw new Error(`Unsafe documentation package asset: ${n.join("/")} must be a regular file.`);let i=Ko.realpathSync(r);if(!po(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 vn(){return jh("docs.zip")}function Xl(){return jh("index.zip")}function Hh(){return O.join(Fh(),"index","data")}import*as qt from"fs";import*as tr from"path";var zt=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],ga=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};function $h(n){return n instanceof ga}var Zl=null;function Ql(n){Zl=n}function ed(){if(Zl)return Zl;let n=ee();if(zt.every(o=>qt.existsSync(tr.join(n,o))))return n;let t=Hh();if(zt.every(o=>qt.existsSync(tr.join(t,o))))return t;throw new ga("Lexicon files not found. Install the documentation index first (index.zip).")}function Uh(){ed()}function nr(n){let e=tr.join(ed(),n);return qt.readFileSync(e,"utf-8")}function Bh(n,e){return qt.readFileSync(tr.join(e,n),"utf-8")}async function Wh(n,e=ed()){await qt.promises.mkdir(n,{recursive:!0});for(let t of zt){let r=tr.join(e,t),o=tr.join(n,t);await qt.promises.copyFile(r,o)}}import*as ya from"fs";import*as Gh from"path";import*as Vh from"yauzl";var ei=null;function tA(n){return new Promise((e,t)=>{Vh.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 nA(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function rA(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",o=>{let i=nA(o);i.endsWith("/")||e.set(i,o),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function oA(){ei?.zipfile.close(),ei=null}async function iA(n){let e=Gh.resolve(n),t=await ya.promises.stat(e),r=ei;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;oA();let o=await tA(e),i=await rA(o);return ei={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:o,entries:i,readChain:Promise.resolve()},ei}function sA(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 aA(n,e){let t=n.readChain,r;n.readChain=new Promise(o=>{r=o}),await t;try{return await sA(n.zipfile,e)}finally{r()}}function cA(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 lA(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function qh(n){let e=vn();if(!e)throw new Error("docs.zip not found");let t=await iA(e),r=lA(t.entries,cA(n));if(!r)throw new Error(`Document not found: ${n}`);return(await aA(t,r)).toString("utf-8")}function td(){let n=vn();return n!==null&&ya.existsSync(n)}import*as ge from"fs";import*as Yt from"path";import zh from"adm-zip";import*as ti from"fs";import*as va from"path";var wa=class extends Error{constructor(e){super(`Unsafe documentation path: ${e}`),this.name="DocPathSafetyError"}};function ni(n){return n instanceof Qn||n instanceof wa||n instanceof Error&&(n.name==="CliDataDirError"||n.name==="DocPathSafetyError")}function od(n){return new wa(n)}function dA(){return wt(Gr())}function rd(n,e,t){let r=Ni(n,e);if(r===null)throw od(`${t} resolves outside the data directory.`);return r}async function nd(n,e){await ti.promises.mkdir(n,{recursive:!0});let t=rd(n,e,"directory");if(!(await ti.promises.stat(t)).isDirectory())throw od("path must be a directory.")}function ri(n){let e=dA();try{let t=rd(n,e,"file");if(!ti.statSync(t).isFile())throw od("path must be a regular file.")}catch(t){if(t.code==="ENOENT"){rd(va.dirname(n),e,"file parent");return}throw t}}async function Yr(n={}){let e=n.mode??"write",t=await Oh();await nd(Vr(),t),await nd(ee(),t),e==="write"&&await nd(Vt(),t);for(let r of[er(),qr(),Xo(),ha(),Qo(),Zo(),...zt.map(o=>va.join(ee(),o))])ri(r)}var id=["search.db","build-meta.json",...zt],uA=["corpus.json","corpus-offsets.json","orama.dpack"];async function pA(n){for(let e of uA)await ge.promises.rm(Yt.join(n,e),{force:!0})}async function fA(n){let e=await ge.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await ge.promises.rm(Yt.join(n,t.name),{recursive:!0,force:!0})}function Yh(n){let t=new zh(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 mA(n){let e=ee();await ge.promises.mkdir(e,{recursive:!0});for(let t of id){let r=Yt.join(e,t);await ge.promises.rm(r,{force:!0}),await ge.promises.rename(Yt.join(n,t),r)}await pA(e),await ge.promises.rm(Vt(),{recursive:!0,force:!0})}function Jh(n){let e=Xl();if(!e)return!1;try{let t=Yh(e);return t.indexVersion===Br&&t.docsZipSha256===n&&t.segmentCount>0}catch{return!1}}async function Kh(n){await Yr({mode:"write"});let e=Xl();if(!e)throw new Error("index.zip not found");let t=Yh(e);if(t.docsZipSha256!==n)throw new Error("Bundled index.zip does not match docs.zip. Rebuild index.zip with npm run build:index.");if(t.segmentCount<=0)throw new Error("Bundled index.zip is empty");let r=Vt();await ge.promises.rm(r,{recursive:!0,force:!0}),await ge.promises.mkdir(r,{recursive:!0});let o=new zh(e);for(let s of id){let a=o.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await ge.promises.writeFile(Yt.join(r,s),a.getData())}let i=JSON.parse(await ge.promises.readFile(Yt.join(r,"build-meta.json"),"utf-8"));if(!ge.existsSync(Yt.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await mA(r),await ge.promises.mkdir(Vr(),{recursive:!0}),await fA(Vr()),i}async function Xh(){await ge.promises.rm(Vt(),{recursive:!0,force:!0});let n=ee();for(let e of id)await ge.promises.rm(Yt.join(n,e),{force:!0})}import{createHash as Zh}from"crypto";import*as Qh from"fs";async function Sa(n){return new Promise((e,t)=>{let r=Zh("sha256"),o=Qh.createReadStream(n);o.on("data",i=>r.update(i)),o.on("error",t),o.on("end",()=>e(r.digest("hex")))})}function eg(n){return Zh("sha256").update(n,"utf8").digest("hex")}var sd=null;function hA(){let n=nr("harmonyos-synonyms.json");return JSON.parse(n)}function gA(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 yA(){let n=gA(hA()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function wA(){return sd||(sd=yA()),sd}function ad(n,e){let t=wA(),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 tg(n,e){let t=e?Bh(n,e):nr(n);return eg(t)}function ba(n){return tg("harmonyos-synonyms.json",n)}function Ea(n){return tg("harmonyos-terms.txt",n)}var vA={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function Pa(){try{let n=await ft.promises.readFile(Xo(),"utf-8");return JSON.parse(n)}catch{return{...vA}}}async function cd(n){let e=Xo();await ft.promises.mkdir(oi.dirname(e),{recursive:!0}),await ft.promises.writeFile(e,JSON.stringify(n,null,2))}function ng(n){let e=Date.now();return{state:"extracting",phase:1,phaseLabel:"Extracting documentation",current:0,total:0,message:n,startedAt:e,updatedAt:e,error:null}}async function Sn(n){let t={...await Pa(),...n,updatedAt:Date.now()};return await cd(t),t}async function ld(){let n=vn();return n?Sa(n):null}async function dd(){try{let n=await ft.promises.readFile(qr(),"utf-8");return JSON.parse(n)}catch{return null}}async function Ca(n=!1){if(n)return"no-index";let e=await dd();if(!e||e.segmentCount===0)return"no-index";let t=await ld();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==Br?"engine-upgraded":e.termsHash!==Ea()?"terms-changed":e.synonymsHash!==ba()?"synonyms-changed":null}function ii(){if(!td()||!ft.existsSync(er())||!ft.existsSync(qr()))return!1;let n=oi.dirname(er());if(!zt.every(e=>ft.existsSync(oi.join(n,e))))return!1;try{let e=ft.readFileSync(qr(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function ud(n=!1){return n?!0:td()?ii()?await Ca()!==null:!0:!1}async function rg(){let n=await Pa();return["installing","indexing","persisting"].includes(n.state)}import*as Ee from"fs";import*as cy from"os";import*as _e from"path";var og=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),pd=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),ig=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"]),sg=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 SA=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,bA=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,EA=/[A-Z][a-zA-Z0-9]{2,}/g,PA=/@[A-Z][a-zA-Z0-9]*/g,CA=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,ag=6,IA=/^[a-z][a-z0-9]{2,}$/,AA=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,DA=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,RA=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,TA=/^[A-Z][a-zA-Z0-9]+$/;function kA(n){return`"${n.replace(/"/g,'""')}"`}function ai(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(kA).join(` ${e} `)}function si(n){return ai(n,"OR")}function cg(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?si([...t,...r]):`(${si(t)}) AND (${si(r)})`}function ci(n){return DA.test(n)}function lg(n){return RA.test(n)&&n.length>=ag}function xA(n){return TA.test(n)}function li(n){return ci(n)||lg(n)||xA(n)}function NA(n){let e=n.trim().toLowerCase();return sg.has(e)?!1:og.has(e)}function LA(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function Ia(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function fd(n){return[...n.matchAll(SA)].map(e=>e[0])}function md(n,e=ag){let t=[];for(let r of n.matchAll(bA))r[0].length>=e&&t.push(r[0]);return t}function Jr(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 mt(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function OA(n){let e=new Set;mt(e,n);let t=Ia(n);return t&&mt(e,t),Jr([...e])}function Aa(n){if(ci(n))return OA(n);let e=new Set;return mt(e,n),Jr([...e])}function Da(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(AA);if(!t)return null;let r=t[1].toLowerCase(),o=t[2].toLowerCase();if(!IA.test(r)||ig.has(r)||!NA(o))return null;let i=LA(r,o);return{first:r,second:o,camelCase:i,lower:i.toLowerCase()}}function hd(n){let e=Da(n.trim());return!e||e.second!=="manager"?null:e}function MA(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function dg(n){let e=n.trim(),t=hd(e);if(t&&pd.has(t.first))return!0;if(lg(e)){let r=MA(e);return r!==null&&pd.has(r)}return!1}function gd(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 yd(n){let e=n.trim();if(li(e))return Aa(e);let t=new Set;for(let r of fd(n)){mt(t,r);let o=Ia(r);o&&mt(t,o)}for(let r of md(n))mt(t,r);for(let r of n.matchAll(PA))t.add(r[0]);for(let r of n.matchAll(CA))t.add(r[0]);for(let r of n.matchAll(EA))r[0].length>=4&&t.add(r[0]);return Jr([...t])}function ug(n){let e=n.trim();if(li(e))return Aa(e);let t=new Set,r=Da(e);r&&mt(t,r.camelCase);for(let o of yd(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 Jr([...t])}function pg(n){return li(n)}var X={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 fg(n){return X.pureApiSymbol.test(n.trim())}function di(n){let e=n.trim();return X.stageModelExact.test(e)||X.stageModelEnglishExact.test(e)}function mg(n){let e=[];return di(n.trim())&&e.push("Stage\u6A21\u578B","Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0"),X.declarePermissionTokens.test(n)&&e.push("\u58F0\u660E\u6743\u9650"),X.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 hg(n){return di(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var _A=[{matches:n=>X.uiAbilityLifecycleBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:n=>di(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!di(n)&&X.stageModel.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:n=>X.entryAbilityPage.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:n=>X.declarePermissionBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:n=>X.stateDecoratorBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:n=>X.stateManagement.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:n=>X.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=>X.dialogPopupBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function FA(n,e){for(let{catalog:t,multiplier:r}of e){let o=yn[t];n.set(o,(n.get(o)??1)*r)}}function gg(n,e){for(let t of _A)t.matches(n)&&FA(e,t.weights)}function yg(n,e){if(e!==void 0)return!1;let t=n.trim();return ci(t)||X.pureApiSymbol.test(t)||dg(t)}function wg(n){let e=n.trim();if(ci(e)||X.pureApiSymbol.test(e))return"harmonyos-references";if(di(e)||X.uiAbilityLifecycleCatalog.test(e)||X.stateDecoratorCatalog.test(e)||X.stateManagement.test(e)||X.declarePermissionCatalog.test(e)||X.stageModelEntryPage.test(e)||X.routerRoute.test(e)||X.dialogPopupExact.test(e))return"harmonyos-guides"}import*as Kr from"fs";import*as Sg from"path";var Ra=null,wd=null,vd=null;function jA(){return Kr.existsSync(Qo())}function HA(n){let e=Qo(),t={backend:"jieba-wasm",reason:"native-jieba-load-failed",message:n,createdAt:new Date().toISOString()};Kr.mkdirSync(Sg.dirname(e),{recursive:!0}),ri(e),Kr.writeFileSync(e,JSON.stringify(t,null,2))}function $A(){if(Ra)return Ra;let n=nr("harmonyos-stopwords.txt");return Ra=new Set(n.split(`
|
|
1311
|
+
`).map(e=>e.trim()).filter(Boolean)),Ra}function UA(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=$A(),t=[];for(let r of UA(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 Eg(n){let{dict:e}=await import("@node-rs/jieba/dict.js"),t=n.withDict(e),r=nr("harmonyos-terms.txt");return t.loadDict(Buffer.from(r,"utf-8")),t}async function BA(){let{Jieba:n}=await import("@node-rs/jieba");return Eg(n)}async function vg(){let{Jieba:n}=await import("@node-rs/jieba-wasm32-wasi");return Eg(n)}async function WA(){let n=await import("jieba-wasm"),e=nr("harmonyos-terms.txt");return n.with_dict(e),{cut:n.cut,cutForSearch:n.cut_for_search}}async function GA(){if(b())return WA();if(jA())return vg();try{let e=await BA();return f("doc-index: using @node-rs/jieba backend"),e}catch(e){let t=e instanceof Error?e.message:String(e);HA(t),f(`doc-index: @node-rs/jieba unavailable (${t}); falling back to wasm32-wasi`)}let n=await vg();return f("doc-index: using @node-rs/jieba-wasm32-wasi backend"),n}async function bn(){return wd||(vd||(vd=GA().then(n=>(wd=n,n))),vd)}async function VA(n){let e=await bn();return bg(e.cutForSearch(n,!0))}async function Pg(n){let e=await bn();return bg(e.cut(n,!0))}async function Ta(n,e){let t=n.trim();if(!t||e<=0)return"";let r=(await VA(t)).join(" ");return r.length<=e?r:r.slice(0,e)}async function qA(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 ka(n){let e=!!n.sectionTitle.trim(),t=n.titleTokens.trim(),r=e?Eh:yh,o=e?Ch:vh,i=e?await qA(n.apiSymbols,o):await Ta(n.apiSymbols.join(" "),o),a=(await Promise.all([Ta(t,e?Ph:wh),Promise.resolve(i),Ta(n.headingsText,e?Ih:Sh),Ta(n.bodySample,e?Ah:bh)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}function zA(n){return n.join(" ").replace(/\s+/g," ").trim().slice(0,Jo)}function Sd(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>=mh))break}return r}function YA(n){return n.length>=2&&n.length<=hh}function JA(n,e){let t=ad(n,zl),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=Sd(o,i);return{rawQuery:n,expandedQuery:t,tokens:s,preferAnd:!1,ftsMatch:cg(o,i)}}function KA(n,e){let t=Sd(Aa(e),[]);return{rawQuery:n,expandedQuery:n,tokens:t,preferAnd:!1,ftsMatch:si(t)}}async function Cg(n){let e=zA(n),t=e.trim(),r=hg(t);if(r)return{rawQuery:e,expandedQuery:r.expandedQuery,tokens:r.tokens,preferAnd:!1};let o=Da(t);if(o)return JA(e,o);if(li(t))return KA(e,t);let i=mg(e),s=[...yd(e),...i],c=pg(t)?e:ad(e,zl),l=await Pg(c),d=Sd(s,l);return{rawQuery:e,expandedQuery:c,tokens:d,preferAnd:i.length===0&&YA(d)}}var Ig=["harmonyos-releases","harmonyos-roadmap"],XA=new Set(Ig.map(n=>yn[n])),ZA=Ig.map(n=>`${Zn[n]}/`);function QA(n){return XA.has(n)}function eD(n){return ZA.some(e=>n.startsWith(e))}function Ag(n){let e=[],t=[];for(let r of n)QA(r.catalog_id)?t.push(r):e.push(r);return[...e,...t]}function Dg(n){let e=[],t=[];for(let r of n)eD(r.documentId)?t.push(r):e.push(r);return[...e,...t]}var tD=[{pattern:/@ohos\./i,catalog:"harmonyos-references",multiplier:1.5},{pattern:/@[A-Z][a-zA-Z]+/,catalog:"harmonyos-guides",multiplier:1.35},{pattern:/(如何|怎么|怎样|步骤)/,catalog:"harmonyos-guides",multiplier:1.45},{pattern:/(生命周期|原理|概述|什么是|模型|介绍)/,catalog:"harmonyos-guides",multiplier:1.35},{pattern:/(报错|失败|错误|异常|排查)/,catalog:"harmonyos-guides",multiplier:1.25},{pattern:/(报错|失败|FAQ)/i,catalog:"harmonyos-faqs",multiplier:1.2},{pattern:/(构建|签名|打包|发布|上架|应用市场|hvigor|ohpm)/i,catalog:"harmonyos-guides",multiplier:1.3},{pattern:/(行为变更|changelog|升级|适配|版本说明)/i,catalog:"harmonyos-releases",multiplier:1.3},{pattern:/(路由|弹窗|手势|页面|权限|装饰器)/,catalog:"harmonyos-guides",multiplier:1.25,skipForPureApiSymbol:!0}];function ui(n,e,t){let r=yn[e];n.set(r,(n.get(r)??1)*t)}function nD(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)){ui(e,"harmonyos-guides",1.45),ui(e,"harmonyos-references",1.35);return}(o||i)&&ui(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(t)&&ui(e,"harmonyos-references",1.75)}function Rg(n){let e=new Map,t=n.trim();if(!t)return e;let r=fg(t);nD(t,e),gg(t,e);for(let o of tD)o.pattern.test(t)&&(o.skipForPureApiSymbol&&r||ui(e,o.catalog,o.multiplier));return e}function Tg(n){return wg(n)}import*as Zr from"fs";import*as Fg from"path";var rD=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function kg(n,e){let t=-1;for(let r of rD){let o=n.lastIndexOf(r);o>t&&(t=o)}return t>=e?t:-1}function xg(n,e){let t=n.trim();if(t.length<=e)return{text:t,excerptTruncated:!1};let r=t.slice(0,e),o=kg(r,e-20),i=o>=0?o:e;return{text:t.slice(0,i).trimEnd(),excerptTruncated:!0}}function Ng(n,e,t={}){let{maxLen:r=Th,contextChars:o=kh,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(V=>V.trim()).filter(Boolean),c=0;for(let V of a){let rt=s.toLowerCase().indexOf(V.toLowerCase());if(rt>=0){c=rt;break}}let l=Math.max(0,c-o),d=Math.min(s.length,l+r),h=s.slice(l,d),w=kg(h,r-25);w>=0&&(d=l+w);let v=s.slice(l,d).trim(),I=l>0?"...":"",G=d<s.length||i?"...":"";return`${I}${v}${G}`}var oD=`
|
|
1312
1312
|
SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
|
|
1313
1313
|
d.catalog_id, bm25(segments_fts) AS bm25
|
|
1314
1314
|
FROM segments_fts
|
|
@@ -1317,7 +1317,7 @@ ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this
|
|
|
1317
1317
|
WHERE segments_fts MATCH ?
|
|
1318
1318
|
ORDER BY bm25(segments_fts)
|
|
1319
1319
|
LIMIT ?
|
|
1320
|
-
`,
|
|
1320
|
+
`,iD=`
|
|
1321
1321
|
SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
|
|
1322
1322
|
d.catalog_id, bm25(segments_fts) AS bm25
|
|
1323
1323
|
FROM segments_fts
|
|
@@ -1326,7 +1326,7 @@ ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this
|
|
|
1326
1326
|
WHERE segments_fts MATCH ? AND d.catalog_id = ?
|
|
1327
1327
|
ORDER BY bm25(segments_fts)
|
|
1328
1328
|
LIMIT ?
|
|
1329
|
-
`,
|
|
1329
|
+
`,sD=3.5,aD=1.4,cD=4,lD=1.8,dD=1.35,uD=3.5,pD=1.8,fD=120,Lg=6;function Ed(n){return n.toLowerCase().replace(/[^\p{L}\p{N}@.]+/gu,"")}function mD(n){return n.split(/[^\p{L}\p{N}@.]+/u).map(Ed).filter(e=>e.length>=2)}function hD(n,e){return e.length>1&&e.every(t=>n.includes(t))}function gD(n){return/^[a-z0-9]{1,4}$/.test(n.trim().toLowerCase())}function yD(n,e){return n===e?uD:n.startsWith(e)||n.includes(`@ohos.${e}`)?pD:1}function wD(n,e){let t=Ed(e);if(t.length<2)return 1;let r=Ed(n.doc_title);if(gD(e))return yD(r,t);if(r.includes(t))return cD;if(t.length>=Lg&&r.includes(t.slice(0,Lg)))return lD;let o=mD(e);return hD(r,o)?dD:1}function vD(n,e){return e<=1?n:n<0?n*e:n/e}function xa(n,e,t,r){let o=n.bm25/(e.get(n.catalog_id)??1);return o=vD(o,wD(n,t)),r&&gd(n.doc_title,n.section_title,r)&&(o/=sD,n.catalog_id===yn["harmonyos-references"]&&(o/=aD)),o}function bd(n,e,t,r){return n.reduce((o,i)=>xa(i,e,t,r)<xa(o,e,t,r)?i:o)}function SD(n,e){return e.some(t=>n.section_title.includes(t)||n.doc_title.includes(t))}function bD(n,e,t,r,o){if(o){let i=n.filter(s=>gd(s.doc_title,s.section_title,o));if(i.length>0)return bd(i,t,r,o)}if(e.length>0){let i=n.filter(s=>SD(s,e));if(i.length>0)return bd(i,t,r,o)}return bd(n,t,r,o)}function Og(n,e,t,r,o){let i=Rg(e),s=ug(e),c=hd(e)?.camelCase,l=new Map;for(let v of n){let I=l.get(v.document_id)??[];I.push(v),l.set(v.document_id,I)}let d=[];for(let v of l.values())d.push(bD(v,s,i,t,c));let h=d.sort((v,I)=>xa(v,i,t,c)-xa(I,i,t,c));return(o?Ag(h):h).slice(0,r)}function Na(n,e,t,r,o,i){let s=e?yn[e]:void 0,a=Math.max(t,t*gh,fD),c=s===void 0?n.all(oD,r,a):n.all(iD,r,s,a);return(s===void 0?Og(c,i,o,t,!0):Og(c,i,o,t,!1)).map(d=>({title:d.doc_title,documentId:d.document_id,sectionTitle:d.section_title||void 0,snippet:Ng(d.lead_text,o,{excerptTruncated:!!d.excerpt_truncated})}))}var La=`
|
|
1330
1330
|
CREATE TABLE documents (
|
|
1331
1331
|
id INTEGER PRIMARY KEY,
|
|
1332
1332
|
document_id TEXT NOT NULL UNIQUE,
|
|
@@ -1364,57 +1364,59 @@ CREATE TRIGGER segments_au AFTER UPDATE ON segments BEGIN
|
|
|
1364
1364
|
END;
|
|
1365
1365
|
|
|
1366
1366
|
CREATE INDEX segments_doc_id_idx ON segments(doc_id);
|
|
1367
|
-
`;var
|
|
1367
|
+
`;var Xr=null,Pd=null;function ED(){Xr?.close(),Xr=null,Pd=null}function PD(n,e){if(Xr&&Pd===e)return Xr;Xr?.close();let t=new n(e,{readonly:!0,fileMustExist:!0});return Xr=t,Pd=e,t.pragma("mmap_size = 268435456"),t.pragma("cache_size = -8000"),t.pragma("query_only = ON"),t}function CD(n,e){let t=new n(e);return t.pragma("journal_mode = OFF"),t.pragma("synchronous = OFF"),t.pragma("temp_store = MEMORY"),t.exec(La),t}function ID(n,e,t){let r=e.get(t.documentId);if(r!==void 0)return r;let i=n.prepare("SELECT id FROM documents WHERE document_id = ?").get(t.documentId);if(i)return e.set(t.documentId,i.id),i.id;let a=n.prepare(`
|
|
1368
1368
|
INSERT INTO documents(document_id, catalog_id, doc_title)
|
|
1369
1369
|
VALUES (?, ?, ?)
|
|
1370
|
-
`).run(t.documentId,t.catalogId,t.docTitle),c=Number(a.lastInsertRowid);return e.set(t.documentId,c),c}async function
|
|
1370
|
+
`).run(t.documentId,t.catalogId,t.docTitle),c=Number(a.lastInsertRowid);return e.set(t.documentId,c),c}async function AD(n,e,t,r){await bn();let o=CD(n,e),i=new Map,s=o.prepare(`
|
|
1371
1371
|
INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated)
|
|
1372
1372
|
VALUES (?, ?, ?, ?, ?)
|
|
1373
|
-
`),a=t.length;for(let c=0;c<a;c+=Br){let l=t.slice(c,c+Br),d=await Promise.all(l.map(async w=>({source:w,searchText:await Ta(w)})));o.transaction(w=>{for(let v of w){let I=SD(o,i,v.source);s.run(I,v.source.sectionTitle,v.source.leadText,v.searchText,v.source.excerptTruncated?1:0)}})(d),await r?.(Math.min(c+l.length,a),a)}o.exec("ANALYZE"),o.exec("VACUUM"),o.close()}function ED(n,e,t,r,o,i,s){let a=wD(n,e);return xa({all(c,...l){return a.prepare(c).all(...l)}},t,r,o,i,s)}async function Ng(){let e=(await import("better-sqlite3")).default;return{kind:"better-sqlite3",resetCache:yD,buildSearchIndex:(t,r,o)=>bD(e,t,r,o),searchIndex:(t,r,o,i,s,a,c)=>Promise.resolve(ED(e,i,r,o,s,a,c))}}import{readFile as PD,stat as CD,writeFile as ID}from"fs/promises";var bd=null,En=null;async function Ed(){return bd||(bd=(async()=>{let n=(await import("@sqlite.org/sqlite-wasm")).default;return n()})()),bd}function AD(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 DD(n){let e=await CD(n);if(En&&En.dbPath===n&&En.mtimeMs===e.mtimeMs)return En.db;En?.db.close();let t=await Ed(),r=t.capi,o=t.wasm,i=new Uint8Array(await PD(n)),s=o.allocFromTypedArray(i),a=new t.oo1.DB(":memory:"),c=a.pointer;if(c===void 0)throw new Error("sqlite3_deserialize: database pointer is undefined");let l=r.SQLITE_DESERIALIZE_READONLY|r.SQLITE_DESERIALIZE_RESIZEABLE|r.SQLITE_DESERIALIZE_FREEONCLOSE;return r.sqlite3_deserialize(c,"main",s,i.byteLength,i.byteLength,l),En={dbPath:n,mtimeMs:e.mtimeMs,db:a},a}function Lg(){En?.db.close(),En=null}async function RD(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 TD(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 kD(n,e,t){await bn();let r=await Ed(),o=new r.oo1.DB(":memory:","c");o.exec(Na);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=TD(o,i,s),l=e.length;for(let h=0;h<l;h+=Br){let w=e.slice(h,h+Br),v=await Promise.all(w.map(async I=>({source:I,searchText:await Ta(I)})));await RD(o,a,c,v),await t?.(Math.min(h+w.length,l),l)}o.exec("ANALYZE");let d=r.capi.sqlite3_js_db_export(o);await ID(n,d),o.close(),Lg()}async function xD(n,e,t,r,o,i){let s=await DD(n);return xa(AD(s),e,t,r,o,i)}async function Pd(){return await Ed(),{kind:"sqlite-wasm",resetCache:Lg,buildSearchIndex:kD,searchIndex:(n,e,t,r,o,i,s)=>xD(r,e,t,o,i,s)}}var La=null,Cd=null;function ND(){return Xr.existsSync(Xo())}function LD(n){let e=Xo(),t={backend:"sqlite-wasm",reason:"better-sqlite3-load-failed",message:n,createdAt:new Date().toISOString()};Xr.mkdirSync(Og.dirname(e),{recursive:!0}),ni(e),Xr.writeFileSync(e,JSON.stringify(t,null,2))}async function OD(){if(ND())return Pd();try{let n=await Ng();return f("doc-index: using better-sqlite3 SQLite backend"),n}catch(n){let e=n instanceof Error?n.message:String(n);LD(e),f(`doc-index: better-sqlite3 unavailable (${e}); falling back to sqlite-wasm`)}return Pd()}async function ui(){return La||(La=OD().then(n=>(Cd=n,n))),La}function Mg(){Cd?.resetCache(),La=null,Cd=null}async function MD(n,e,t,r,o,i,s){let a=await ui(),c=s??Qn();return a.searchIndex(n,e,t,c,r,o,i)}function Zr(){Mg()}async function Fg(n,e,t){await(await ui()).buildSearchIndex(n,e,t)}function jg(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 Oa(n,e,t,r,o,i){return MD(n,e,t,o,r.expandedQuery,r.rawQuery,i)}async function _D(n,e,t,r,o){let i=await Oa(n,e,t,r,si(r.tokens,"AND"),o);if(i.length>=t)return i;let s=await Oa(n,e,t,r,si(r.tokens,"OR"),o);return jg(i,s,t)}async function Id(n,e,t,r,o){return r.ftsMatch?Oa(n,e,t,r,r.ftsMatch,o):r.preferAnd?_D(n,e,t,r,o):Oa(n,e,t,r,si(r.tokens,"OR"),o)}async function FD(n,e,t,r){let o=await Id(n,"harmonyos-references",e,t,r);if(o.length>=e)return o;let i=await Id(n,void 0,e,t,r);return jg(o,i,e)}function _g(n,e){return e!==void 0?n:Cg(n)}async function Ad(n,e,t=20,r){let o=await bg(n);if(mg(o.rawQuery,e)){let a=await FD(n,t,o,r);return _g(a,e)}let i=e??Ag(o.rawQuery),s=await Id(n,i,t,o,r);return _g(s,e)}import{unified as qg}from"unified";import zg from"remark-parse";import Yg from"remark-gfm";import{toString as _a}from"mdast-util-to-string";var jD=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,HD=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,$D=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,UD=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,BD=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function Ma(n){let e=n.trim(),t=e.match(UD);return t?t[1]:e}function WD(n){let e=n.match(jD);if(!e)return;let t=Ma(e[1].trim());return{displayTitle:n,symbolName:t,searchExtras:[t,e[3]]}}function GD(n){let e=Ma(n.replace(/\([^)]*\)$/,""));if(/^[A-Z][A-Za-z0-9]*$/.test(e))return{displayTitle:n,symbolName:e,searchExtras:[e]};if(/^[A-Z][A-Za-z0-9]*(\([^)]*\))?$/.test(n))return{displayTitle:n,symbolName:e,searchExtras:[e]}}function pi(n){let e=n.trim();return e?WD(e)??(()=>{let t=e.match(HD);if(t){let r=t[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let t=e.match($D);if(!t)return;let r=t[1].trim(),o=t[2].trim();return{displayTitle:e,symbolName:o,searchExtras:[r,o]}})()??GD(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function VD(n){if(n.length<2||n.length>36||BD.test(n))return!1;let e=[...n.replace(/\s/g,"")];return e.length===0?!1:e.filter(r=>new RegExp("\\p{Script=Han}","u").test(r)).length/e.length>=.4}function Hg(n){for(let e of n){let t=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(VD(t))return t}return""}function $g(n,e,t){let r=[n,...t.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var qD=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,fi=/@[A-Z][a-zA-Z]+/g,zD=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,YD=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,JD=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,KD=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),XD=new Set(["HAP","HSP","HAR","NAPI","CAPI","NDK","ArkTS","ArkUI","OHPM"]),ZD=new Set(["JSON","Object","Array","Promise","console","Math","Date","String","Number","Boolean","Error","Function","Map","Set","RegExp"]);function Jg(n,e){let t=new Set,r=[n,...e];for(let o of r){for(let i of dd(o)){mt(t,i);let s=Ca(i);s&&mt(t,s)}for(let i of ud(o))mt(t,i);for(let i of o.matchAll(qD)){let s=i[0];QD(s)&&t.add(s)}for(let i of o.matchAll(fi))t.add(i[0])}return Yr([...t])}function QD(n){let e=n.trim();if(!e||fi.test(e))return!!e;if(e.includes(".")){let t=e.split(".")[0]??"";return ZD.has(t)?!1:/^[A-Z]/.test(t)}return KD.has(e)?!1:XD.has(e)?!0:e.length<=3?!1:/^[A-Z][a-z]+[A-Z]/.test(e)?!0:e.length>=6&&/^[A-Z][A-Za-z0-9]+$/.test(e)}function Ug(n){let e=n.trim();return!!(!e||JD.test(e)||e.length>28&&!/[A-Z\u4e00-\u9fff]/.test(e)&&/^[a-z0-9_-]+$/.test(e))}function Kg(n,e){let t=e.jsonTitle?.trim(),r=rR(n,"").trim(),o=e.fileName.trim();return t&&!Ug(t)?t:r&&!Ug(r)?r:t||r||o}function Xg(n){return zD.test(n.trim())}function Dd(n){let e=n.trim().replace(/\([^)]*\)$/,""),t=Ma(e);return YD.test(t)}function Fa(n){let e=n.trim();return e?fi.test(e)||Xg(e)||Dd(e)?!0:!!pi(e).symbolName:!1}function eR(n){let e=n.trim();return!(!e||Xg(e)||Dd(e))}function tR(n){let e=new Set,t=[];for(let r of n){let o=r.trim();!eR(o)||e.has(o)||(e.add(o),t.push(o))}return t}function Bg(n){if(!n.includes("."))return 0;let e=n.split(".").pop()??"";return/^[a-z]/.test(e)?1:2}function nR(n,e){let t=Bg(n)-Bg(e);return t!==0?t:n.localeCompare(e)}function Zg(n,e=[]){let t=[...new Set(e.map(i=>i.trim()).filter(Boolean))],r=new Set(t),o=[...new Set(n.map(i=>i.trim()).filter(Boolean))].filter(i=>!r.has(i));return o.sort(nR),[...t,...o].slice(0,Ch)}function ja(n){return n.replace(/\s+/g," ").trim()}function Wg(n){return n.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function rR(n,e=""){let t=n.split(/\r?\n/),r=0;for(;r<t.length&&!t[r].trim();)r+=1;if(r>=t.length)return e;let o=Wg(t[r].trim()),i=o.match(/^#+\s+(.+)$/);if(i)return Wg(i[1].trim());if(r+1<t.length){let s=t[r+1].trim();if(/^=+$/.test(s)||/^-+$/.test(s))return o}return o||e}function Qg(n){let e=ja(n.join(" "));if(e.length<=pa)return e;let t=e.slice(0,pa);return e.length<=pa+Vl?t:`${t} ${e.slice(-Vl)}`}function oR(n){let e=tR(n).join(" ");return e.length<=ql?e:e.slice(0,ql)}function ey(n){let e=ja(n),{text:t,excerptTruncated:r}=Rg(e,Ih);return{leadText:t,excerptTruncated:r}}function iR(n,e){let{leadText:t,excerptTruncated:r}=ey(n);return{leadText:t,excerptTruncated:r||!!e.trim()}}function ty(n,e){if(n.type==="code"){e.codeBlocks.push(n.value??"");return}if("children"in n&&Array.isArray(n.children)){for(let r of n.children)ty(r,e);return}let t=ja(_a(n));t&&e.bodyParts.push(t)}function sR(n){let e=qg().use(zg).use(Yg).parse(n),t=[],r=null,o=()=>{r&&((r.sectionTitle||r.bodyParts.length||r.codeBlocks.length)&&t.push(r),r=null)},i=()=>{r||(r={sectionTitle:"",bodyParts:[],codeBlocks:[]})};for(let s of e.children){if(s.type==="heading"){let a=s,c=_a(a).trim();if(a.depth>=4&&c&&Fa(c)){o(),r={sectionTitle:c,bodyParts:[],codeBlocks:[]};continue}i(),c&&r.bodyParts.push(c);continue}i(),ty(s,r)}return o(),t.length===0?[{sectionTitle:"",bodyParts:[],codeBlocks:[]}]:t}function aR(n){return dh.test(n)}function cR(n){return n.filter(e=>e.sectionTitle&&Fa(e.sectionTitle)).length}function lR(n){return{sectionTitle:n.map(e=>e.sectionTitle.trim()).join(" | "),bodyParts:n.flatMap(e=>e.bodyParts).slice(0,40),codeBlocks:n.flatMap(e=>e.codeBlocks).slice(0,8)}}function Gg(n){let e=n.trim();return!e||fi.test(e)?fi.test(e):/对象说明$|枚举说明$/.test(e)?!0:Dd(e)}function dR(n){let e=n.filter(h=>!h.sectionTitle||!Fa(h.sectionTitle)),t=n.filter(h=>h.sectionTitle&&Fa(h.sectionTitle)),r=t.filter(h=>Gg(h.sectionTitle)),o=t.filter(h=>!Gg(h.sectionTitle)),i=Math.max(0,lh-r.length),s=o.slice(0,i),a=o.slice(i),c=a.filter(h=>Vg(h.sectionTitle)),l=a.filter(h=>!Vg(h.sectionTitle)),d=[];for(let h=0;h<l.length;h+=Wl)d.push(lR(l.slice(h,h+Wl)));return[...e,...r,...s,...c,...d]}function uR(n,e,t){let r=n.split(/\r?\n/).length,o=cR(e);return o===0?!1:aR(t)?r>=ah&&o>=ch:r>=ih&&o>=sh}var pR=/^\[h2\][A-Za-z]/;function Vg(n){return pR.test(n.trim())}function ny(n){if(!n.includes(" | ")){let t=pi(n);return t.symbolName?[t.symbolName]:[]}let e=[];for(let t of n.split(" | ")){let r=pi(t.trim()).symbolName;r&&e.push(r)}return e}function fR(n,e,t,r){let o=ny(n),i=Jg(t,r);return e.symbolName&&i.push(e.symbolName),Zg([...o,...i],o)}function mR(n,e){let t=Qg(n.bodyParts),r=n.sectionTitle.trim(),o=pi(r),i=Hg(n.bodyParts),s=$g(r,i,o),a=ny(r),c=r?a.length>0?`${e.docTitle} ${a.join(" ")}`:`${e.docTitle} ${o.symbolName??r}`:e.docTitle,l=[e.docTitle,s,...n.bodyParts].join(" "),{leadText:d,excerptTruncated:h}=iR(t,r);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:e.docTitle,sectionTitle:r,titleTokens:c,headingsText:s,apiSymbols:fR(r,o,l,n.codeBlocks),bodySample:t,leadText:d,excerptTruncated:h}}function ry(n,e){for(let t of n){if(t.type==="heading"){let o=_a(t).trim();o&&e.headings.push(o);continue}if(t.type==="code"){e.codeBlocks.push(t.value??"");continue}if("children"in t&&Array.isArray(t.children)){ry(t.children,e);continue}let r=ja(_a(t));r&&e.bodyParts.push(r)}}function hR(n){let e=qg().use(zg).use(Yg).parse(n),t={headings:[],bodyParts:[],codeBlocks:[]};return ry(e.children,t),t}function gR(n,e){let t=hR(n),r=e.docTitle?.trim()||e.documentId,o=Qg(t.bodyParts),i=[r,...t.headings,o].join(" "),{leadText:s,excerptTruncated:a}=ey(o);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:r,sectionTitle:"",titleTokens:r,headingsText:oR(t.headings),apiSymbols:Zg(Jg(i,t.codeBlocks)),bodySample:o,leadText:s,excerptTruncated:a}}function oy(n,e){let t=e.docTitle?.trim()||e.documentId,r=sR(n);return uR(n,r,e.documentId)?dR(r).filter(o=>o.sectionTitle||o.bodyParts.length>0||o.codeBlocks.length>0).map(o=>mR(o,{...e,docTitle:t})):[gR(n,{...e,docTitle:t})]}async function yR(n){let e=[];async function t(r){let o=await Ee.promises.readdir(r,{withFileTypes:!0});for(let i of o){if(i.name.startsWith("."))continue;let s=_e.join(r,i.name);i.isDirectory()?await t(s):i.isFile()&&i.name.endsWith(".md")&&e.push(s)}}return await t(n),e}function wR(n,e){let t=_e.relative(e,n).split(_e.sep).join("/").split("/");if(t[0]==="docs"&&(t=t.slice(1)),t.length<2)return null;let r=t[0],o=Rh[r];if(o===void 0)return null;let i=t[t.length-1].replace(/\.md$/,"");return t[t.length-1]=i,{documentId:t.join("/"),catalogId:o,docTitle:i}}async function vR(n){let e=n.replace(/\.md$/,".json");try{let t=await Ee.promises.readFile(e,"utf-8");return JSON.parse(t).title?.trim()||void 0}catch{return}}async function SR(n,e){let t=wR(n,e);if(!t)return[];let r=await Ee.promises.readFile(n,"utf-8"),o=Kg(r,{jsonTitle:await vR(n),fileName:t.docTitle});return oy(r,{...t,docTitle:o})}async function bR(n,e,t){let r=_e.join(e,"search.db");return await Fg(r,n,async(o,i)=>{await t?.({current:o,total:i,message:`Building search index\u2026 ${o.toLocaleString()} / ${i.toLocaleString()} segments`})}),n.length}async function ER(n){let e=await yR(n),t=[];for(let r of e){let o=await SR(r,n);t.push(...o)}return t}function PR(n,e){return{indexVersion:Ur,docsZipSha256:n.docsZipSha256,termsHash:n.termsHash,synonymsHash:n.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:n.builtBy}}async function sy(n){n.lexiconDir&&Kl(n.lexiconDir);try{let e=await ER(n.docsDir);await n.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await Ee.promises.mkdir(n.tmpDir,{recursive:!0});let t=await bR(e,n.tmpDir,n.onProgress),r=PR(n,t);return await Ee.promises.writeFile(_e.join(n.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await $h(n.tmpDir),r}finally{n.lexiconDir&&Kl(null)}}async function ay(){return Ee.promises.mkdtemp(_e.join(iy.tmpdir(),"deveco-docs-"))}async function CR(n,e){try{await Ee.promises.rename(n,e)}catch(t){let r=t.code;if(r!=="EPERM"&&r!=="EXDEV")throw t;await Ee.promises.cp(n,e,{recursive:!0}),await Ee.promises.rm(n,{recursive:!0,force:!0})}}async function cy(n){let e=_e.join(n,"docs");try{await Ee.promises.access(e)}catch{return}let t=new Set(["docs","docs.zip"]);for(let r of await Ee.promises.readdir(e,{withFileTypes:!0})){if(t.has(r.name))continue;let o=_e.join(e,r.name),i=_e.join(n,r.name);await Ee.promises.rm(i,{recursive:!0,force:!0}),await CR(o,i)}await Ee.promises.rm(_e.join(e,"docs"),{recursive:!0,force:!0}),await Ee.promises.rm(_e.join(e,"docs.zip"),{force:!0}),await Ee.promises.rm(e,{recursive:!0,force:!0})}var mi=class extends Error{constructor(e){super(e),this.name="NativeDepsError"}};function IR(){let n=qr(),e=ee();return["Documentation search index is not installed yet.","",...fa(n),`Index directory: ${e}`,"","Try:"," 1. Wait a moment and run the docs command again (postinstall may still be running)"," 2. Reinstall: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>"," 3. Check the log file above for setup errors"].join(`
|
|
1374
|
-
`)}function
|
|
1375
|
-
`)}function
|
|
1376
|
-
`)}async function
|
|
1373
|
+
`),a=t.length;for(let c=0;c<a;c+=Wr){let l=t.slice(c,c+Wr),d=await Promise.all(l.map(async w=>({source:w,searchText:await ka(w)})));o.transaction(w=>{for(let v of w){let I=ID(o,i,v.source);s.run(I,v.source.sectionTitle,v.source.leadText,v.searchText,v.source.excerptTruncated?1:0)}})(d),await r?.(Math.min(c+l.length,a),a)}o.exec("ANALYZE"),o.exec("VACUUM"),o.close()}function DD(n,e,t,r,o,i,s){let a=PD(n,e);return Na({all(c,...l){return a.prepare(c).all(...l)}},t,r,o,i,s)}async function Mg(){let e=(await import("better-sqlite3")).default;return{kind:"better-sqlite3",resetCache:ED,buildSearchIndex:(t,r,o)=>AD(e,t,r,o),searchIndex:(t,r,o,i,s,a,c)=>Promise.resolve(DD(e,i,r,o,s,a,c))}}import{readFile as RD,stat as TD,writeFile as kD}from"fs/promises";var Cd=null,En=null;async function Id(){return Cd||(Cd=(async()=>{let n=(await import("@sqlite.org/sqlite-wasm")).default;return n()})()),Cd}function xD(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 ND(n){let e=await TD(n);if(En&&En.dbPath===n&&En.mtimeMs===e.mtimeMs)return En.db;En?.db.close();let t=await Id(),r=t.capi,o=t.wasm,i=new Uint8Array(await RD(n)),s=o.allocFromTypedArray(i),a=new t.oo1.DB(":memory:"),c=a.pointer;if(c===void 0)throw new Error("sqlite3_deserialize: database pointer is undefined");let l=r.SQLITE_DESERIALIZE_READONLY|r.SQLITE_DESERIALIZE_RESIZEABLE|r.SQLITE_DESERIALIZE_FREEONCLOSE;return r.sqlite3_deserialize(c,"main",s,i.byteLength,i.byteLength,l),En={dbPath:n,mtimeMs:e.mtimeMs,db:a},a}function _g(){En?.db.close(),En=null}async function LD(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 OD(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 MD(n,e,t){await bn();let r=await Id(),o=new r.oo1.DB(":memory:","c");o.exec(La);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=OD(o,i,s),l=e.length;for(let h=0;h<l;h+=Wr){let w=e.slice(h,h+Wr),v=await Promise.all(w.map(async I=>({source:I,searchText:await ka(I)})));await LD(o,a,c,v),await t?.(Math.min(h+w.length,l),l)}o.exec("ANALYZE");let d=r.capi.sqlite3_js_db_export(o);await kD(n,d),o.close(),_g()}async function _D(n,e,t,r,o,i){let s=await ND(n);return Na(xD(s),e,t,r,o,i)}async function Ad(){return await Id(),{kind:"sqlite-wasm",resetCache:_g,buildSearchIndex:MD,searchIndex:(n,e,t,r,o,i,s)=>_D(r,e,t,o,i,s)}}var Oa=null,Dd=null;function FD(){return Zr.existsSync(Zo())}function jD(n){let e=Zo(),t={backend:"sqlite-wasm",reason:"better-sqlite3-load-failed",message:n,createdAt:new Date().toISOString()};Zr.mkdirSync(Fg.dirname(e),{recursive:!0}),ri(e),Zr.writeFileSync(e,JSON.stringify(t,null,2))}async function HD(){if(FD())return Ad();try{let n=await Mg();return f("doc-index: using better-sqlite3 SQLite backend"),n}catch(n){let e=n instanceof Error?n.message:String(n);jD(e),f(`doc-index: better-sqlite3 unavailable (${e}); falling back to sqlite-wasm`)}return Ad()}async function pi(){return Oa||(Oa=HD().then(n=>(Dd=n,n))),Oa}function jg(){Dd?.resetCache(),Oa=null,Dd=null}async function $D(n,e,t,r,o,i,s){let a=await pi(),c=s??er();return a.searchIndex(n,e,t,c,r,o,i)}function Qr(){jg()}async function $g(n,e,t){await(await pi()).buildSearchIndex(n,e,t)}function Ug(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 Ma(n,e,t,r,o,i){return $D(n,e,t,o,r.expandedQuery,r.rawQuery,i)}async function UD(n,e,t,r,o){let i=await Ma(n,e,t,r,ai(r.tokens,"AND"),o);if(i.length>=t)return i;let s=await Ma(n,e,t,r,ai(r.tokens,"OR"),o);return Ug(i,s,t)}async function Rd(n,e,t,r,o){return r.ftsMatch?Ma(n,e,t,r,r.ftsMatch,o):r.preferAnd?UD(n,e,t,r,o):Ma(n,e,t,r,ai(r.tokens,"OR"),o)}async function BD(n,e,t,r){let o=await Rd(n,"harmonyos-references",e,t,r);if(o.length>=e)return o;let i=await Rd(n,void 0,e,t,r);return Ug(o,i,e)}function Hg(n,e){return e!==void 0?n:Dg(n)}async function Td(n,e,t=20,r){let o=await Cg(n);if(yg(o.rawQuery,e)){let a=await BD(n,t,o,r);return Hg(a,e)}let i=e??Tg(o.rawQuery),s=await Rd(n,i,t,o,r);return Hg(s,e)}import{unified as Jg}from"unified";import Kg from"remark-parse";import Xg from"remark-gfm";import{toString as Fa}from"mdast-util-to-string";var WD=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,GD=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,VD=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,qD=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,zD=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function _a(n){let e=n.trim(),t=e.match(qD);return t?t[1]:e}function YD(n){let e=n.match(WD);if(!e)return;let t=_a(e[1].trim());return{displayTitle:n,symbolName:t,searchExtras:[t,e[3]]}}function JD(n){let e=_a(n.replace(/\([^)]*\)$/,""));if(/^[A-Z][A-Za-z0-9]*$/.test(e))return{displayTitle:n,symbolName:e,searchExtras:[e]};if(/^[A-Z][A-Za-z0-9]*(\([^)]*\))?$/.test(n))return{displayTitle:n,symbolName:e,searchExtras:[e]}}function fi(n){let e=n.trim();return e?YD(e)??(()=>{let t=e.match(GD);if(t){let r=t[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let t=e.match(VD);if(!t)return;let r=t[1].trim(),o=t[2].trim();return{displayTitle:e,symbolName:o,searchExtras:[r,o]}})()??JD(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function KD(n){if(n.length<2||n.length>36||zD.test(n))return!1;let e=[...n.replace(/\s/g,"")];return e.length===0?!1:e.filter(r=>new RegExp("\\p{Script=Han}","u").test(r)).length/e.length>=.4}function Bg(n){for(let e of n){let t=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(KD(t))return t}return""}function Wg(n,e,t){let r=[n,...t.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var XD=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,mi=/@[A-Z][a-zA-Z]+/g,ZD=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,QD=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,eR=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,tR=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),nR=new Set(["HAP","HSP","HAR","NAPI","CAPI","NDK","ArkTS","ArkUI","OHPM"]),rR=new Set(["JSON","Object","Array","Promise","console","Math","Date","String","Number","Boolean","Error","Function","Map","Set","RegExp"]);function Zg(n,e){let t=new Set,r=[n,...e];for(let o of r){for(let i of fd(o)){mt(t,i);let s=Ia(i);s&&mt(t,s)}for(let i of md(o))mt(t,i);for(let i of o.matchAll(XD)){let s=i[0];oR(s)&&t.add(s)}for(let i of o.matchAll(mi))t.add(i[0])}return Jr([...t])}function oR(n){let e=n.trim();if(!e||mi.test(e))return!!e;if(e.includes(".")){let t=e.split(".")[0]??"";return rR.has(t)?!1:/^[A-Z]/.test(t)}return tR.has(e)?!1:nR.has(e)?!0:e.length<=3?!1:/^[A-Z][a-z]+[A-Z]/.test(e)?!0:e.length>=6&&/^[A-Z][A-Za-z0-9]+$/.test(e)}function Gg(n){let e=n.trim();return!!(!e||eR.test(e)||e.length>28&&!/[A-Z\u4e00-\u9fff]/.test(e)&&/^[a-z0-9_-]+$/.test(e))}function Qg(n,e){let t=e.jsonTitle?.trim(),r=cR(n,"").trim(),o=e.fileName.trim();return t&&!Gg(t)?t:r&&!Gg(r)?r:t||r||o}function ey(n){return ZD.test(n.trim())}function kd(n){let e=n.trim().replace(/\([^)]*\)$/,""),t=_a(e);return QD.test(t)}function ja(n){let e=n.trim();return e?mi.test(e)||ey(e)||kd(e)?!0:!!fi(e).symbolName:!1}function iR(n){let e=n.trim();return!(!e||ey(e)||kd(e))}function sR(n){let e=new Set,t=[];for(let r of n){let o=r.trim();!iR(o)||e.has(o)||(e.add(o),t.push(o))}return t}function Vg(n){if(!n.includes("."))return 0;let e=n.split(".").pop()??"";return/^[a-z]/.test(e)?1:2}function aR(n,e){let t=Vg(n)-Vg(e);return t!==0?t:n.localeCompare(e)}function ty(n,e=[]){let t=[...new Set(e.map(i=>i.trim()).filter(Boolean))],r=new Set(t),o=[...new Set(n.map(i=>i.trim()).filter(Boolean))].filter(i=>!r.has(i));return o.sort(aR),[...t,...o].slice(0,Dh)}function Ha(n){return n.replace(/\s+/g," ").trim()}function qg(n){return n.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function cR(n,e=""){let t=n.split(/\r?\n/),r=0;for(;r<t.length&&!t[r].trim();)r+=1;if(r>=t.length)return e;let o=qg(t[r].trim()),i=o.match(/^#+\s+(.+)$/);if(i)return qg(i[1].trim());if(r+1<t.length){let s=t[r+1].trim();if(/^=+$/.test(s)||/^-+$/.test(s))return o}return o||e}function ny(n){let e=Ha(n.join(" "));if(e.length<=fa)return e;let t=e.slice(0,fa);return e.length<=fa+Yl?t:`${t} ${e.slice(-Yl)}`}function lR(n){let e=sR(n).join(" ");return e.length<=Jl?e:e.slice(0,Jl)}function ry(n){let e=Ha(n),{text:t,excerptTruncated:r}=xg(e,Rh);return{leadText:t,excerptTruncated:r}}function dR(n,e){let{leadText:t,excerptTruncated:r}=ry(n);return{leadText:t,excerptTruncated:r||!!e.trim()}}function oy(n,e){if(n.type==="code"){e.codeBlocks.push(n.value??"");return}if("children"in n&&Array.isArray(n.children)){for(let r of n.children)oy(r,e);return}let t=Ha(Fa(n));t&&e.bodyParts.push(t)}function uR(n){let e=Jg().use(Kg).use(Xg).parse(n),t=[],r=null,o=()=>{r&&((r.sectionTitle||r.bodyParts.length||r.codeBlocks.length)&&t.push(r),r=null)},i=()=>{r||(r={sectionTitle:"",bodyParts:[],codeBlocks:[]})};for(let s of e.children){if(s.type==="heading"){let a=s,c=Fa(a).trim();if(a.depth>=4&&c&&ja(c)){o(),r={sectionTitle:c,bodyParts:[],codeBlocks:[]};continue}i(),c&&r.bodyParts.push(c);continue}i(),oy(s,r)}return o(),t.length===0?[{sectionTitle:"",bodyParts:[],codeBlocks:[]}]:t}function pR(n){return fh.test(n)}function fR(n){return n.filter(e=>e.sectionTitle&&ja(e.sectionTitle)).length}function mR(n){return{sectionTitle:n.map(e=>e.sectionTitle.trim()).join(" | "),bodyParts:n.flatMap(e=>e.bodyParts).slice(0,40),codeBlocks:n.flatMap(e=>e.codeBlocks).slice(0,8)}}function zg(n){let e=n.trim();return!e||mi.test(e)?mi.test(e):/对象说明$|枚举说明$/.test(e)?!0:kd(e)}function hR(n){let e=n.filter(h=>!h.sectionTitle||!ja(h.sectionTitle)),t=n.filter(h=>h.sectionTitle&&ja(h.sectionTitle)),r=t.filter(h=>zg(h.sectionTitle)),o=t.filter(h=>!zg(h.sectionTitle)),i=Math.max(0,ph-r.length),s=o.slice(0,i),a=o.slice(i),c=a.filter(h=>Yg(h.sectionTitle)),l=a.filter(h=>!Yg(h.sectionTitle)),d=[];for(let h=0;h<l.length;h+=ql)d.push(mR(l.slice(h,h+ql)));return[...e,...r,...s,...c,...d]}function gR(n,e,t){let r=n.split(/\r?\n/).length,o=fR(e);return o===0?!1:pR(t)?r>=dh&&o>=uh:r>=ch&&o>=lh}var yR=/^\[h2\][A-Za-z]/;function Yg(n){return yR.test(n.trim())}function iy(n){if(!n.includes(" | ")){let t=fi(n);return t.symbolName?[t.symbolName]:[]}let e=[];for(let t of n.split(" | ")){let r=fi(t.trim()).symbolName;r&&e.push(r)}return e}function wR(n,e,t,r){let o=iy(n),i=Zg(t,r);return e.symbolName&&i.push(e.symbolName),ty([...o,...i],o)}function vR(n,e){let t=ny(n.bodyParts),r=n.sectionTitle.trim(),o=fi(r),i=Bg(n.bodyParts),s=Wg(r,i,o),a=iy(r),c=r?a.length>0?`${e.docTitle} ${a.join(" ")}`:`${e.docTitle} ${o.symbolName??r}`:e.docTitle,l=[e.docTitle,s,...n.bodyParts].join(" "),{leadText:d,excerptTruncated:h}=dR(t,r);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:e.docTitle,sectionTitle:r,titleTokens:c,headingsText:s,apiSymbols:wR(r,o,l,n.codeBlocks),bodySample:t,leadText:d,excerptTruncated:h}}function sy(n,e){for(let t of n){if(t.type==="heading"){let o=Fa(t).trim();o&&e.headings.push(o);continue}if(t.type==="code"){e.codeBlocks.push(t.value??"");continue}if("children"in t&&Array.isArray(t.children)){sy(t.children,e);continue}let r=Ha(Fa(t));r&&e.bodyParts.push(r)}}function SR(n){let e=Jg().use(Kg).use(Xg).parse(n),t={headings:[],bodyParts:[],codeBlocks:[]};return sy(e.children,t),t}function bR(n,e){let t=SR(n),r=e.docTitle?.trim()||e.documentId,o=ny(t.bodyParts),i=[r,...t.headings,o].join(" "),{leadText:s,excerptTruncated:a}=ry(o);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:r,sectionTitle:"",titleTokens:r,headingsText:lR(t.headings),apiSymbols:ty(Zg(i,t.codeBlocks)),bodySample:o,leadText:s,excerptTruncated:a}}function ay(n,e){let t=e.docTitle?.trim()||e.documentId,r=uR(n);return gR(n,r,e.documentId)?hR(r).filter(o=>o.sectionTitle||o.bodyParts.length>0||o.codeBlocks.length>0).map(o=>vR(o,{...e,docTitle:t})):[bR(n,{...e,docTitle:t})]}async function ER(n){let e=[];async function t(r){let o=await Ee.promises.readdir(r,{withFileTypes:!0});for(let i of o){if(i.name.startsWith("."))continue;let s=_e.join(r,i.name);i.isDirectory()?await t(s):i.isFile()&&i.name.endsWith(".md")&&e.push(s)}}return await t(n),e}function PR(n,e){let t=_e.relative(e,n).split(_e.sep).join("/").split("/");if(t[0]==="docs"&&(t=t.slice(1)),t.length<2)return null;let r=t[0],o=xh[r];if(o===void 0)return null;let i=t[t.length-1].replace(/\.md$/,"");return t[t.length-1]=i,{documentId:t.join("/"),catalogId:o,docTitle:i}}async function CR(n){let e=n.replace(/\.md$/,".json");try{let t=await Ee.promises.readFile(e,"utf-8");return JSON.parse(t).title?.trim()||void 0}catch{return}}async function IR(n,e){let t=PR(n,e);if(!t)return[];let r=await Ee.promises.readFile(n,"utf-8"),o=Qg(r,{jsonTitle:await CR(n),fileName:t.docTitle});return ay(r,{...t,docTitle:o})}async function AR(n,e,t){let r=_e.join(e,"search.db");return await $g(r,n,async(o,i)=>{await t?.({current:o,total:i,message:`Building search index\u2026 ${o.toLocaleString()} / ${i.toLocaleString()} segments`})}),n.length}async function DR(n){let e=await ER(n),t=[];for(let r of e){let o=await IR(r,n);t.push(...o)}return t}function RR(n,e){return{indexVersion:Br,docsZipSha256:n.docsZipSha256,termsHash:n.termsHash,synonymsHash:n.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:n.builtBy}}async function ly(n){n.lexiconDir&&Ql(n.lexiconDir);try{let e=await DR(n.docsDir);await n.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await Ee.promises.mkdir(n.tmpDir,{recursive:!0});let t=await AR(e,n.tmpDir,n.onProgress),r=RR(n,t);return await Ee.promises.writeFile(_e.join(n.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await Wh(n.tmpDir),r}finally{n.lexiconDir&&Ql(null)}}async function dy(){return Ee.promises.mkdtemp(_e.join(cy.tmpdir(),"deveco-docs-"))}async function TR(n,e){try{await Ee.promises.rename(n,e)}catch(t){let r=t.code;if(r!=="EPERM"&&r!=="EXDEV")throw t;await Ee.promises.cp(n,e,{recursive:!0}),await Ee.promises.rm(n,{recursive:!0,force:!0})}}async function uy(n){let e=_e.join(n,"docs");try{await Ee.promises.access(e)}catch{return}let t=new Set(["docs","docs.zip"]);for(let r of await Ee.promises.readdir(e,{withFileTypes:!0})){if(t.has(r.name))continue;let o=_e.join(e,r.name),i=_e.join(n,r.name);await Ee.promises.rm(i,{recursive:!0,force:!0}),await TR(o,i)}await Ee.promises.rm(_e.join(e,"docs"),{recursive:!0,force:!0}),await Ee.promises.rm(_e.join(e,"docs.zip"),{force:!0}),await Ee.promises.rm(e,{recursive:!0,force:!0})}var hi=class extends Error{constructor(e){super(e),this.name="NativeDepsError"}};function kR(){let n=zr(),e=ee();return["Documentation search index is not installed yet.","",...ma(n),`Index directory: ${e}`,"","Try:"," 1. Wait a moment and run the docs command again (postinstall may still be running)"," 2. Reinstall: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>"," 3. Check the log file above for setup errors"].join(`
|
|
1374
|
+
`)}function xR(){let n=zr();return[`Chinese tokenizer (${b()?"jieba-wasm":"@node-rs/jieba"}) failed to load.`,"",`Node.js: ${process.version} (required: >=18)`,"",...ma(n),"","Try:"," 1. Reinstall: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>"," 2. Use Node.js 18 or newer",b()?" 3. Verify jieba-wasm package is installed (WASM backend for OpenHarmony)":" 3. Configure npm registry/proxy if your network blocks optional platform packages"].join(`
|
|
1375
|
+
`)}function NR(n){let e=zr();return[n,"",...ma(e)].join(`
|
|
1376
|
+
`)}async function py(){try{Uh()}catch(n){throw $h(n)?new hi(`${kR()}
|
|
1377
1377
|
|
|
1378
|
-
Detail: ${n.message}`):n}try{await bn()}catch(n){let e=n instanceof Error?n.message:String(n);throw new
|
|
1378
|
+
Detail: ${n.message}`):n}try{await bn()}catch(n){let e=n instanceof Error?n.message:String(n);throw new hi(`${xR()}
|
|
1379
1379
|
|
|
1380
|
-
Detail: ${e}`)}try{await
|
|
1381
|
-
`)}async function
|
|
1382
|
-
`),t=e.findIndex(s=>s.trimStart().startsWith("WindowName"));if(t===-1)return[];let r=[];for(let s=t+1;s<e.length;s++){let a=e[s].trim();if(!a||/^-+$/.test(a)||a.startsWith("Focus window")||a.startsWith("total window"))break;let c=a.split(/\s+/);if(c.length<5)continue;let l=c[0],d=Number(c[1]),h=Number(c[2]),w=Number(c[3]),v=Number(c[4]);Number.isFinite(w)&&Number.isFinite(d)&&Number.isFinite(h)&&r.push({id:w,name:l,pid:h,displayId:d,type:v})}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
|
|
1380
|
+
Detail: ${e}`)}try{await pi()}catch(n){let e=n instanceof Error?n.message:String(n);throw new hi(NR(e))}}var xd=class extends Error{constructor(t,r){super(r);this.code=t;this.name="DocNotReadyError"}code};function MR(n){return new Promise(e=>setTimeout(e,n))}async function gy(n){let e=zr();await oe.promises.mkdir(Pt.dirname(e),{recursive:!0}),await oe.promises.appendFile(e,`${new Date().toISOString()} ${n}
|
|
1381
|
+
`)}async function _R(n){let e=vn();if(!e)throw new Error("docs.zip not found");await oe.promises.rm(n,{recursive:!0,force:!0}),await oe.promises.mkdir(n,{recursive:!0});let t=Pt.resolve(n),r=new LR(e);for(let o of r.getEntries()){let i=Pt.resolve(t,o.entryName);if(!po(i,t))throw new Error(`Unsafe docs.zip entry path: ${o.entryName}`);if(o.isDirectory){await oe.promises.mkdir(i,{recursive:!0});continue}await oe.promises.mkdir(Pt.dirname(i),{recursive:!0}),await oe.promises.writeFile(i,o.getData())}await uy(n)}async function FR(){await Yr({mode:"write"});let n=ee(),e=Vt(),t=await oe.promises.readdir(e);for(let r of t){let o=Pt.join(n,r);await oe.promises.rm(o,{force:!0}),await oe.promises.rename(Pt.join(e,r),o)}await oe.promises.rm(e,{recursive:!0,force:!0}),await oe.promises.rm(Pt.join(n,"orama.dpack"),{force:!0})}async function fy(n,e,t){e?.start(t),await Sn({state:"installing",phase:1,phaseLabel:"Installing index",message:t}),await Kh(n),Qr(),e&&(e.text="Documentation index installed.")}async function jR(n,e){try{return await fy(n,e,"Installing documentation index\u2026"),await Nd(e),!0}catch(t){if(ni(t))throw t}try{return await Xh(),Qr(),await fy(n,e,"Retrying documentation index install\u2026"),await Nd(e),!0}catch(t){if(ni(t))throw t;let r=t instanceof Error?t.message:String(t);return await gy(`Bundled index install failed; falling back to local rebuild: ${r}`),!1}}async function HR(n,e,t){let r=Vt(),o=await dy();await oe.promises.mkdir(ee(),{recursive:!0}),await oe.promises.rm(r,{recursive:!0,force:!0}),t?.start("Building search index\u2026"),await Sn({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"});try{await _R(o),await ly({docsDir:o,tmpDir:r,docsZipSha256:e,termsHash:Ea(),synonymsHash:ba(),builtBy:n.builtBy??"doc-init",onProgress:async i=>{t&&(t.text=i.message),await Sn({state:"indexing",current:i.current,total:i.total,message:i.message})}})}finally{await oe.promises.rm(o,{recursive:!0,force:!0})}await Sn({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await FR(),Qr()}async function Nd(n){await Sn({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function $R(n){let e=await dd(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";n?.succeed(t),await Sn({state:"done",message:t,error:null})}async function UR(n,e){let t=n instanceof Error?n.message:String(n);throw await Sn({state:"error",error:t}),await gy(`ERROR: ${t}`),e?.fail(t),n}async function BR(){let n=ee();await oe.promises.mkdir(n,{recursive:!0});let e=ha();return oe.existsSync(e)||await oe.promises.writeFile(e,"","utf-8"),e}async function WR(){let n=await BR();return OR.lock(n,{stale:1800*1e3})}async function GR(){let n=vn(),e=(n?await Sa(n):null)??await ld();if(!e)throw new Error("docs.zip not found");return e}async function VR(n,e){let t=await GR(),r=n.force||await ud(n.force),o=await Ca(n.force);if(!r&&!o&&ii()){await $R(e);return}!n.force&&Jh(t)&&await jR(t,e)||(await HR(n,t,e),await Nd(e))}var gi=class{static async run(e={}){let t=e.background??!1,o=e.quiet??t?void 0:hy({text:"Checking documentation\u2026",color:"cyan"}),i;try{e.assumeStorageSafe||await Yr({mode:"write"}),i=await WR(),await cd(ng("Starting documentation setup\u2026")),await VR(e,o)}catch(s){throw i&&await UR(s,o),s}finally{i&&await i()}}};async function qR(n){for(;;){let e=await Pa();if(e.state==="done"&&ii())return;if(e.state==="error")throw new xd("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 MR(500)}}async function my(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await gi.run({builtBy:"doc-init",force:e,quiet:!0})}async function zR(){let n=await Ca()!==null;if(ii()&&!n)return;let e=hy({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await rg()){await qR(e),e.succeed("Documentation ready.");return}if(await ud()){await my(e),e.succeed("Documentation ready.");return}await my(e,!0),e.succeed("Documentation ready.")}catch(t){throw e.fail(t.message),t}}async function yi(){await Yr({mode:"read"}),await zR(),await py()}function YR(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 Ld=class{async search(e,t,r=20){await yi();try{return await Td(e,t,r)}catch(o){if(!YR(o))throw o;return Qr(),await gi.run({builtBy:"doc-init",force:!0,quiet:!0,assumeStorageSafe:!0}),Td(e,t,r)}}async readDocument(e){return await yi(),qh(e)}},Od=new Ld;function yy(...n){return e=>{if(!n.includes(e))throw new Md(`Allowed values: ${n.join(", ")}`);return e}}function XR(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new Md("Must be a positive integer.");return e}var ZR=yy("json","default"),QR=yy("json","default");function _d(n){let e=n instanceof Error?n.message:String(n);return ni(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 Ua=new JR("docs").description("Search and read HarmonyOS documentation from local docs directory");Ua.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",tT,"all").option("--format <fmt>","Output format (default, json)",ZR,"default").option("--limit <n>","Max number of results",XR,20).action(async(n,e)=>{try{let t=eT(n),r=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=await Od.search(t,r,e.limit);e.format==="json"?console.log(JSON.stringify(o,null,2)):nT(o)}catch(t){console.error($a(_d(t))),process.exit(1)}});Ua.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{try{let e=n.trim();e||(console.error($a("Document ID cannot be empty.")),process.exit(1));let t=await Od.readDocument(e);console.log(t)}catch(e){console.error($a(_d(e))),process.exit(1)}});Ua.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",QR,"default").action(async n=>{try{if(await yi(),n.format==="json"){let e=gn.map(t=>({name:t,title:Zn[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of gn)console.log(` ${e.padEnd(20)} ${KR(Zn[e])}`)}catch(e){console.error($a(_d(e))),process.exit(1)}});function eT(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>Jo)throw new Error(`Query exceeds ${Jo} characters.`);return e}function tT(n){if(n==="all")return"all";if(!gn.includes(n))throw new Md(`Invalid catalog "${n}". Allowed: all, ${gn.join(", ")}`);return n}function nT(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 wy=Ua;import{Command as ok}from"commander";import{Command as mT,InvalidArgumentError as hT,Option as jd}from"commander";import{readFileSync as oT,unlinkSync as iT}from"fs";import{tmpdir as sT}from"os";import{join as aT}from"path";var Jt=class{constructor(e,t){this.hdcPath=e;this.serial=t}hdcPath;serial;async listWindows(e){let t=await this.fetchDump(),r=rT(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"];f(`Executing: ${this.hdcPath} ${e.join(" ")}`);let t=await ae(this.hdcPath,e);if(t.exitCode!==0)throw new Error(`Failed to query windows: ${(t.stderr||t.stdout).trim()}`);return t.stdout}};function rT(n){let e=n.split(`
|
|
1382
|
+
`),t=e.findIndex(s=>s.trimStart().startsWith("WindowName"));if(t===-1)return[];let r=[];for(let s=t+1;s<e.length;s++){let a=e[s].trim();if(!a||/^-+$/.test(a)||a.startsWith("Focus window")||a.startsWith("total window"))break;let c=a.split(/\s+/);if(c.length<5)continue;let l=c[0],d=Number(c[1]),h=Number(c[2]),w=Number(c[3]),v=Number(c[4]);Number.isFinite(w)&&Number.isFinite(d)&&Number.isFinite(h)&&r.push({id:w,name:l,pid:h,displayId:d,type:v})}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 vy(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 Sy(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 by(n){return n.originalText||void 0}function eo(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 Ey(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:"#";f(`collapse ${w} depth=${s} -> ${a?"root":c?"collapsed":"emitted"}`)}let h=l?s+1:s;for(let w=o.children.length-1;w>=0;w--)r.push({current:o.children[w],parent:d,depth:h})}return t}function cT(n){let e=oT(n,"utf-8").trim();if(!e)throw new Error("Empty dumpLayout response from device");return JSON.parse(e)}function lT(n){return n.attributes??{}}function Ba(n,e,t){let r=lT(n),o={id:r.id||void 0,type:r.type||void 0,text:by(r),bounds:Sy(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:vy(r.hitTestBehavior),children:[]};return e>0&&t+1>=e||n.children&&(o.children=n.children.map(i=>Ba(i,e,t+1))),o}function dT(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 Error(`Window '${e}' not found. Available windows: ${o||"none"}`)}return r}let t=n.find(r=>r.focused);if(t)return t;throw new Error("No window id specified and could not detect focused window")}var rr=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),f(`Executing: ${this.hdcPath} ${i.join(" ")}`);let s=await ae(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=aT(sT(),`deveco_cli_dump_${Date.now()}_${process.pid}.json`);try{return await this.recvDumpFile(e,t,r),cT(r)}finally{await this.cleanupDumpArtifacts(e,r,t)}}async recvDumpFile(e,t,r){let o=["-t",e,"file","recv",t,r];f(`Executing: ${this.hdcPath} ${o.join(" ")}`);let i=await ae(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{f(`Removing local dump file: ${t}`),iT(t)}catch(i){f(`Failed to clean local dump file ${t}: ${i.message}`)}let o=["-t",e,"shell","rm","-f",r];f(`Executing: ${this.hdcPath} ${o.join(" ")}`),await ae(this.hdcPath,o).catch(i=>{f(`Failed to clean remote dump file ${r}: ${i.message}`)})}async dumpRawNodes(e,t,r){let i=await new Jt(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=dT(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=>Ba(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:Ba(s,t,0)})}return o}async dumpCollapsedTree(e,t,r,o){return(await this.dumpRawNodes(e,r,o)).flatMap(s=>Ey(Ba(s,0,0),t))}};var Wa={left:"0",right:"1",up:"2",down:"3"};function Te(n,e){let t=Number(n);if(!Number.isInteger(t)||t<=0)throw new Error(`${e} must be a positive integer`)}function Fd(n,e){n!==void 0&&Te(n,e)}function Py(n,e){if(n===void 0!=(e===void 0))throw new Error("x and y must be provided together")}function Ga(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 Cy(n){if(n!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(n))throw new Error("--window must consist of letters, digits, - or _")}function Iy(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 to(n,e,t,r,o=!0){Py(n,e),Ga(t,"--id"),Fd(n,"x"),Fd(e,"y"),Cy(r),Iy(n!==void 0,!!t,!!r,o)}async function Pn(n,e){let r=await new Ir(n).selectDevice(e);if(!r)throw new Error("No device selected. Use `devecocli device list` to see targets.");return r}async function Ct(n){let e=await A.new(),t=await Pn(e,n);return{hdcPath:e.hdcPath,deviceId:t}}async function no(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 Jt(n,e).listWindows({all:!0}),c=new rr(n);return uT(c,e,a,o,i)}async function uT(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 Error(`Window "${o}" is on display ${i.displayId}. The current command only supports operations on the primary display.`);let s=await n.dumpFullTree(e,0,o,!1);return fT(s,r)}return pT(n,e,t,r)}async function pT(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 eo([c],r))s.push({node:l,displayId:a});if(s.length===0)throw new Error(`Node "${r}" not found.`);if(s.length>1)throw new Error(`Multiple nodes found with id "${r}".`);if(s[0].displayId!==0)throw new Error(`Node "${r}" is on display ${s[0].displayId}. The current command only supports operations on the primary display.`);return Ay(s[0].node,r)}function fT(n,e){let t=eo(n,e);if(t.length===0)throw new Error(`Node "${e}" not found.`);if(t.length>1)throw new Error(`Multiple nodes found with id "${e}".`);return Ay(t[0],e)}function Ay(n,e){let t=n.bounds;if(!t)throw new Error(`Node "${e}" has no bounds.`);let[r,o,i,s]=t;return{x:Math.ceil((r+i)/2),y:Math.ceil((o+s)/2)}}async function Qe(n,e,t){let r=["-t",e,"shell",t.join(" ")];f(`Executing: ${n} ${r.join(" ")}`);let o=await ae(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 gT from"ora";function yT(n){let e=parseInt(n,10);if(!Number.isInteger(e)||e<0||String(e)!==n.trim())throw new hT("depth must be a non-negative integer");return e}function wT(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 Dy(n,e=0){let t=[],r=" ".repeat(e);for(let o of n)t.push(`${r}${wT(o)}`),o.children.length>0&&t.push(...Dy(o.children,e+1).split(`
|
|
1383
1383
|
`));return t.join(`
|
|
1384
|
-
`)}function
|
|
1385
|
-
`).trim()}function
|
|
1384
|
+
`)}function vT(n){if(n.allWindows&&n.window)throw new Error("--all-windows and --window are mutually exclusive.")}function ST(n,e){let t=eo(n,e);if(t.length===0)throw new Error(`Node '${e}' not found.`);let r=t.map(o=>({...o,children:[]}));console.log(JSON.stringify(r,null,2))}function bT(n,e){console.log(e==="json"?JSON.stringify(n,null,2):Dy(n))}async function ET(n){vT(n);let e=gT({text:"Dumping layout\u2026",color:"cyan"}).start(),t;try{let r=await A.new(),o=await Pn(r,n.device),i=new rr(r.hdcPath);t=n.mode==="full"?await i.dumpFullTree(o,n.depth,n.window,n.allWindows):await i.dumpCollapsedTree(o,n.depth,n.window,n.allWindows)}catch(r){throw e.stop(),new Error(`Failed to dump layout: ${r.message}`,{cause:r})}if(e.stop(),n.id){ST(t,n.id);return}bT(t,n.format)}var Ry=new mT("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 jd("--depth <n>","Tree depth limit (0=unlimited, 1=root only, 2=root+children)").argParser(yT).default(0)).addOption(new jd("--format <format>","Output format").choices(["default","json"]).default("default")).addOption(new jd("--mode <mode>","Output mode: full | simplified").choices(["full","simplified"]).default("simplified")).action(async n=>{await ET(n)});import{Command as PT,Option as CT}from"commander";import{yellow as IT}from"colorette";import AT from"ora";var DT=["Id","Name","Pid","DisplayId","Focused"];function RT(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(Ot(DT,t))}async function TT(n){let e=AT({text:"Listing windows\u2026",color:"cyan"}).start(),t;try{let r=await A.new(),o=await Pn(r,n.device);t=await new Jt(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(IT(" No windows found."));return}RT(t,n.format)}var Hd=new PT("window").description("Manage device windows");Hd.command("list").description("List windows on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new CT("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show all windows including system windows").action(async n=>{await TT(n)});import{Command as kT}from"commander";import Fe from"fs";import et from"path";import{randomUUID as xT}from"crypto";import{green as NT}from"colorette";function LT(){return String(Date.now())}function Ty(n){let e;try{e=Fe.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{Fe.accessSync(n,Fe.constants.W_OK|Fe.constants.X_OK)}catch(t){throw new Error(`Screenshot directory is not writable: ${n}`,{cause:t})}}function ky(n,e){try{throw Fe.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 OT(n){if(!n?.trim())throw new Error("--path is required.");let e=n.trim(),t=et.resolve(e);try{if(Fe.statSync(t).isDirectory()){Ty(t);let o=et.join(t,`screenshot-${LT()}.png`);return ky(o,t),o}}catch(o){if(o.code!=="ENOENT")throw o}if(et.extname(t).toLowerCase()!==".png")throw new Error(`Screenshot path must be an existing directory or a PNG file: ${t}`);let r=et.dirname(t);return Ty(r),ky(t,r),t}function xy(n){if(!Fe.existsSync(n))throw new Error(`Screenshot file was not created: ${n}`);let e=Fe.statSync(n);if(!e.isFile()||e.size===0)throw new Error(`Screenshot file is empty: ${n}`);let t=Fe.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 MT(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 _T(n){let e=n.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}function FT(n,e){try{Fe.copyFileSync(n,e,Fe.constants.COPYFILE_EXCL)}catch(t){throw t.code==="EEXIST"?new Error(`Screenshot file already exists: ${e}`,{cause:t}):t}xy(e)}function jT(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 HT(n){let e=["-t",n.serial,"shell","ls","-l",n.remotePath];f(`Executing: ${n.hdcPath} ${e.join(" ")}`);let t=await ae(n.hdcPath,e);return t.exitCode===0?jT(t.stdout):void 0}function $T(n){return[n.stdout,n.stderr].filter(Boolean).join(`
|
|
1385
|
+
`).trim()}function UT(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 BT(n,e){let t=MT(n,e);f(`Executing: ${n.hdcPath} ${t.join(" ")}`);let r=await ae(n.hdcPath,t),o=await HT(n);return{created:o!==void 0&&o>0,output:$T(r)}}async function WT(n){let e="";for(let t of[void 0,"png"]){let r=await BT(n,t);if(r.created)return;if(n.display!==void 0&&UT(r.output))throw new Error(`Screenshot was not created on device: ${n.remotePath}.
|
|
1386
1386
|
snapshot_display output:
|
|
1387
1387
|
${r.output}`);r.output&&(e=r.output)}throw new Error(e?`Screenshot was not created on device: ${n.remotePath}.
|
|
1388
1388
|
snapshot_display output:
|
|
1389
|
-
${e}`:`Screenshot was not created on device: ${n.remotePath}.`)}function
|
|
1389
|
+
${e}`:`Screenshot was not created on device: ${n.remotePath}.`)}function Ny(n){try{return xy(n),!0}catch{return!1}}function Ly(n){let e=[];for(let t of Fe.readdirSync(n,{withFileTypes:!0})){let r=et.join(n,t.name);if(t.isDirectory()){e.push(...Ly(r));continue}t.isFile()&&Ny(r)&&e.push(r)}return e}function GT(n,e){let t=et.join(n,et.basename(e));if(Ny(t))return t;let r=Ly(n);if(r.length===1)return r[0];if(r.length>1)throw new Error(`Multiple screenshot files were received in ${n}.`)}async function $d(n,e,t){let r=["-t",n.serial,"file","recv",n.remotePath,t];f(`Executing: ${n.hdcPath} ${r.join(" ")}`);let o=await ae(n.hdcPath,r);return o.exitCode!==0&&f(`hdc file recv failed: ${o.stderr||o.stdout||`exit code ${o.exitCode}`}`),GT(e,n.remotePath)}async function VT(n){let e=Fe.mkdtempSync(et.join(et.dirname(n.localPath),".devecocli-screenshot-"));try{let t=await $d(n,e,et.join(e,et.basename(n.remotePath)))??await $d(n,e,e)??await $d(n,e,et.join(e,"screenshot.png"));if(!t)throw new Error(`Screenshot file was not created in ${e}.`);FT(t,n.localPath)}finally{Fe.rmSync(e,{recursive:!0,force:!0})}}async function qT(n){let e=["-t",n.serial,"shell","rm","-f",n.remotePath];f(`Executing: ${n.hdcPath} ${e.join(" ")}`),await ae(n.hdcPath,e)}async function zT(n){try{await WT(n),await VT(n)}finally{await qT(n)}}async function YT(n){let e=OT(n.path),t=n.display!==void 0?_T(n.display):void 0;if(n.device!==void 0&&!n.device.trim())throw new Error("--device must not be empty.");let r=await A.new(),o=await Pn(r,n.device),i=`/data/local/tmp/devecocli-${xT()}.png`;await zT({hdcPath:r.hdcPath,serial:o,localPath:e,remotePath:i,display:t}),console.log(NT(`Screenshot saved to ${e}`))}var Oy=new kT("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(YT);import{Command as Cn}from"commander";function JT(n){let t=`"$(printf '%s' '${Buffer.from(n,"utf8").toString("base64")}' | base64 -d)"`;return f(`escapeShellText: ${n} -> ${t}`),t}async function In(n,e,t){let r=new ut;r.start(n);try{await t(r)}catch(o){throw r.stop(),new Error(`${e}: ${o.message}`,{cause:o})}}async function KT(n,e,t){await In("Executing click...","click failed",async r=>{to(n,e,t.id,t.window);let{hdcPath:o,deviceId:i}=await Ct(t.device),{x:s,y:a}=await no(o,i,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await Qe(o,i,["uitest","uiInput","click",String(s),String(a)]),r.succeed(`click at (${s}, ${a})`)})}async function XT(n,e,t){await In("Executing doubleclick...","doubleclick failed",async r=>{to(n,e,t.id,t.window);let{hdcPath:o,deviceId:i}=await Ct(t.device),{x:s,y:a}=await no(o,i,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await Qe(o,i,["uitest","uiInput","doubleClick",String(s),String(a)]),r.succeed(`doubleclick at (${s}, ${a})`)})}async function ZT(n,e,t){await In("Executing longclick...","longclick failed",async r=>{to(n,e,t.id,t.window);let{hdcPath:o,deviceId:i}=await Ct(t.device),{x:s,y:a}=await no(o,i,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await Qe(o,i,["uitest","uiInput","longClick",String(s),String(a)]),r.succeed(`longclick at (${s}, ${a})`)})}async function QT(n,e,t,r,o){await In("Executing swipe...","swipe failed",async i=>{Te(n,"x1"),Te(e,"y1"),Te(t,"x2"),Te(r,"y2");let s=vi(o.speed),{hdcPath:a,deviceId:c}=await Ct(o.device),l=["uitest","uiInput","swipe",n,e,t,r];s&&l.push(s),await Qe(a,c,l),i.succeed(`swipe from (${n}, ${e}) to (${t}, ${r})`)})}async function ek(n,e,t,r,o){await In("Executing fling...","fling failed",async i=>{Te(n,"x1"),Te(e,"y1"),Te(t,"x2"),Te(r,"y2");let s=vi(o.speed),{hdcPath:a,deviceId:c}=await Ct(o.device),l=["uitest","uiInput","fling",n,e,t,r];s&&l.push(s),await Qe(a,c,l),i.succeed(`fling from (${n}, ${e}) to (${t}, ${r})`)})}async function tk(n,e,t,r,o){await In("Executing drag...","drag failed",async i=>{Te(n,"x1"),Te(e,"y1"),Te(t,"x2"),Te(r,"y2");let s=vi(o.speed),{hdcPath:a,deviceId:c}=await Ct(o.device),l=["uitest","uiInput","drag",n,e,t,r];s&&l.push(s),await Qe(a,c,l),i.succeed(`drag from (${n}, ${e}) to (${t}, ${r})`)})}async function nk(n,e){await In("Executing dircfling...","dircfling failed",async t=>{let r=Wa[n];if(r===void 0)throw new Error(`Invalid direction "${n}". Valid values: ${Object.keys(Wa).join(", ")}`);let{hdcPath:o,deviceId:i}=await Ct(e.device);await Qe(o,i,["uitest","uiInput","dircFling",r]),t.succeed(`dircfling ${n}`)})}async function rk(n,e,t,r){await In("Executing text input...","input failed",async o=>{to(e,t,r.id,r.window,!1),Ga(n,"text");let{hdcPath:i,deviceId:s}=await Ct(r.device),a=JT(n);if(e!==void 0)await Qe(i,s,["uitest","uiInput","inputText",`${e}`,`${t}`,a]),o.succeed(`input ${n} at (${e}, ${t})`);else if(r.id){let{x:c,y:l}=await no(i,s,void 0,void 0,r.id,r.window);await Qe(i,s,["uitest","uiInput","inputText",`${c}`,`${l}`,a]),o.succeed(`input ${n} at (${c}, ${l})`)}else await Qe(i,s,["uitest","uiInput","text",a]),o.succeed(`input ${n}`)})}var My=new Cn("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(KT),_y=new Cn("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(XT),Fy=new Cn("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(ZT),jy=new Cn("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(QT),Hy=new Cn("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(ek),$y=new Cn("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(tk),Uy=new Cn("dircfling").argument("<direction>","Direction: up, down, left, right").description("Fling in a specified direction").option("--device <name|serial>","Target device (name or serial)").action(nk),By=new Cn("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(rk);var tt=new ok("ui").description("Inspect and interact with UI on a connected device");tt.addCommand(Ry);tt.addCommand(Hd);tt.addCommand(Oy);tt.addCommand(My);tt.addCommand(_y);tt.addCommand(Fy);tt.addCommand(jy);tt.addCommand(Hy);tt.addCommand($y);tt.addCommand(Uy);tt.addCommand(By);var Wy=tt;import{Command as Bx}from"commander";import{execa as Ak}from"execa";import Kt from"fs";import*as Gd from"os";import*as B from"path";var ik=new RegExp("\x1B\\[[0-?]*[ -/]*[@-~]","g"),sk=/\r/g,ak=/^(Working|Finished)\.\.\.\[[^\]]*\]\d+%$/,ck=/^<+\s*/,lk=/\s*>+$/,dk=[/^The configuration file .+ is in use\.$/,/^The configuration file .+ in the project is in use\.$/,/^Currently active product: ?.+$/,/^Writing the result to .+\.$/,/^Write finished\.$/,/^CodeLinter found some defects in your code\.$/];function Ud(n){if(!n)return"";let e=n.replace(ik,"").replace(sk,`
|
|
1390
1390
|
`).split(`
|
|
1391
|
-
`).map(t=>t.trimEnd()).filter(t=>
|
|
1391
|
+
`).map(t=>t.trimEnd()).filter(t=>pk(t));return e.length>0?`${e.join(`
|
|
1392
1392
|
`)}
|
|
1393
|
-
`:""}function
|
|
1393
|
+
`:""}function zy(n){let e=Ud(n).trim();if(!e)return{jsonText:void 0,diagnostics:""};if(Yy(e))return{jsonText:e,diagnostics:""};let t=fk(e);if(!t)return{jsonText:void 0,diagnostics:`${e}
|
|
1394
1394
|
`};let r=[e.slice(0,t.start).trim(),e.slice(t.end).trim()].filter(Boolean).join(`
|
|
1395
1395
|
`);return{jsonText:e.slice(t.start,t.end),diagnostics:r?`${r}
|
|
1396
|
-
`:""}}function
|
|
1397
|
-
${
|
|
1398
|
-
`;let t=e===void 0?n.issues:n.issues.slice(0,e),r=[
|
|
1396
|
+
`:""}}function uk(n){return ak.test(n.trim())}function pk(n){let e=n.trim();return!!e&&!uk(e)&&!dk.some(t=>t.test(e))}function Yy(n){try{return JSON.parse(n),!0}catch{return!1}}function fk(n){for(let e=0;e<n.length;e++){if(n[e]!=="["&&n[e]!=="{")continue;let t=mk(n,e);if(t)return t}}function mk(n,e){for(let t=n.length;t>e;t--){let r=n[t-1];if(r!=="]"&&r!=="}")continue;let o=n.slice(e,t);if(Yy(o))return{start:e,end:t}}}var Gy=["Error","Warning","Suggestion","Info","Off","Unknown"];function Jy(n){let e=Bd(n);return{issues:wk(e),summary:hk(n,e)}}function hk(n,e){let t=Sk(e);return{filesChecked:bk(n).size,issues:e.length,errors:t.get("Error")??0,warnings:t.get("Warning")??0,suggestions:t.get("Suggestion")??0}}function Bd(n,e=""){if(Array.isArray(n))return n.flatMap(i=>Bd(i,e));if(!Ky(n))return[];let t=Si(n,["filePath","file","path"])??e,r=gk(n,t);if(r.length>0)return r;let o=yk(n,t);return o?[o]:[]}function gk(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=>Bd(s,e));if(i.length>0)return i}}return[]}function yk(n,e){let t=Si(n,["message","description","desc","detail"])??"",r=Ik(Si(n,["rule","ruleId","ruleName"])),o=Pk(n,["severity","level"]),i=Si(n,["filePath","file","path"])??e;if(!(!t&&!r&&o==="Unknown"))return{file:i,line:qy(n,["line","reportLine"]),column:qy(n,["column","reportColumn"]),severity:o,rule:r,message:t}}function wk(n){return[...n].sort((e,t)=>{let r=Vy(e.severity)-Vy(t.severity);return r===0?vk(e,t):r})}function vk(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 Sk(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 bk(n){let e=new Set;return Wd(e,n,""),e}function Wd(n,e,t){if(Array.isArray(e)){for(let o of e)Wd(n,o,t);return}if(!Ky(e))return;let r=Si(e,["filePath","file","path"])??t;r&&n.add(r),Ek(n,e,r)}function Ek(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)Wd(n,s,t)}}function Pk(n,e){for(let t of e){let r=n[t];if(typeof r=="string"||typeof r=="number")return Ck(r)}return"Unknown"}function Ck(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 Ik(n){let e=n?.normalize("NFKC").trim();if(e)return e.replace(ck,"").replace(lk,"").toLowerCase()}function Vy(n){let e=Gy.indexOf(n);return e===-1?Gy.length:e}function Si(n,e){for(let t of e){let r=n[t];if(typeof r=="string")return r}}function qy(n,e){for(let t of e){let r=n[t];if(typeof r=="number")return r}}function Ky(n){return typeof n=="object"&&n!==null}var Xy="deveco-codelinter-",Zy=[".ets",".ts",".js"],bi=class n{resolution;cwd;constructor(e,t){this.resolution=n.resolveWithToolProvider(e),this.cwd=t}static resolveProjectRoot(e){try{return z.discover(e).rootDir}catch{return e}}async check(e){let t=Kt.mkdtempSync(B.join(Gd.tmpdir(),Xy)),r=B.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),c=await this.run(a),l=zy(c.stdout),d=l.diagnostics+Ud(c.stderr);try{let h=this.readJsonReport(r,l.jsonText);return{exitCode:c.exitCode,diagnostics:d,report:Jy(h)}}catch(h){return{exitCode:c.exitCode,diagnostics:d,reportError:h}}}finally{this.removeTempDir(t)}}resolveLintTarget(e,t){let r=e?B.resolve(this.cwd,e):t,o=this.resolveRealPath(r,"Lint path"),i=Kt.statSync(o);if(!i.isFile()&&!i.isDirectory())throw new Error(`Lint path must be a file or directory: ${r}`);if(i.isFile()){let a=B.extname(o).toLowerCase();if(!Zy.some(l=>l===a))throw new Error(`Unsupported lint file extension "${a||"<none>"}": ${o}. Supported extensions: ${Zy.join(", ")}.`)}let s=this.discoverProjectRoot(o,i.isDirectory());if(e!==void 0&&s===void 0)throw new Error(`Lint path is not in a valid project directory (project-level build-profile.json5 not found or invalid): ${o}`);return{path:o,projectRoot:s}}resolveConfigPath(e,t){let r=e?B.resolve(this.cwd,e):B.join(t.projectRoot??this.cwd,"code-linter.json5"),o=this.resolveRealPath(r,"`--config-path`");if(!Kt.statSync(o).isFile())throw new Error(`--config-path must point to a file: ${r}`);if(t.projectRoot){let i=this.discoverProjectRoot(o,!1);if(i===void 0||B.relative(t.projectRoot,i)!=="")throw new Error(`\`--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:B.dirname(e);try{return Kt.realpathSync(z.discover(r).rootDir)}catch{return}}resolveRealPath(e,t){try{return Kt.realpathSync(e)}catch(r){throw new Error(`${t} does not exist or cannot be resolved: ${e}`,{cause:r})}}buildNativeArgs(e,t,r,o){let i=["--config",r];return e.fix&&i.push("--fix"),e.incremental&&i.push("--incremental"),i.push("--product",e.product,"--format","json","--output",o,t),i}async run(e){let t=[...this.resolution.argsPrefix,...e],r=this.resolution.workingDirectory??this.cwd;this.prepareRuntimeDirectories(),f(`Executing: ${this.resolution.command} ${t.join(" ")}`),f(`[CodelinterAdapter] Working directory: ${r}`);let o=await Ak(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??[])try{Kt.mkdirSync(e,{recursive:!0})}catch(t){f(`[CodelinterAdapter] Skipping runtime directory ${e}: ${t.message}`)}}readJsonReport(e,t){let o=(Kt.existsSync(e)?Kt.readFileSync(e,"utf-8").trim():void 0)||t?.trim();if(!o)throw new Error("Native JSON report was not generated.");return JSON.parse(o)}removeTempDir(e){let t=B.resolve(e),r=B.resolve(Gd.tmpdir());!(t.startsWith(`${r}${B.sep}`)||t===r)||!B.basename(t).startsWith(Xy)||Kt.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={command:e.nodePath,argsPrefix:[o,i],env:{...process.env,PATH:[...s,process.env.PATH||""].join(B.delimiter),DEVECO_SDK_HOME:i}};return t==="command-line-tools"&&(c.workingDirectory=r,c.runtimeDirectories=[n.getResultDirectory(o)]),f(`[CodelinterAdapter] Selected ${a} entry: ${o}`),c}static getPathEntries(e,t){let r=[B.dirname(e.nodePath)];return t==="ide"&&e.javaPath&&r.unshift(B.dirname(e.javaPath)),r}static getResultDirectory(e){return B.resolve(e,"..","linter","result")}static getSource(e){return e.sourceType==="studio"?"ide":"command-line-tools"}};import{red as qa,yellow as Fk}from"colorette";import{Argument as jk,Command as Hk,InvalidArgumentError as Dn}from"commander";import Pi from"fs";import*as je from"path";import*as Ei from"path";var Qy="n/a",ew=/\\/g,Dk=/\|/g,Rk=/\r?\n/g;function tw(n,e){if(n.issues.length===0)return`No defects found.
|
|
1397
|
+
${Vd(n.summary)}
|
|
1398
|
+
`;let t=e===void 0?n.issues:n.issues.slice(0,e),r=[kk(t),Vd(n.summary)];return e!==void 0&&t.length<n.issues.length&&r.push(Tk(n.issues.length,t.length)),`${r.join(`
|
|
1399
1399
|
`)}
|
|
1400
|
-
`}function
|
|
1401
|
-
`)}function
|
|
1402
|
-
`)}function
|
|
1403
|
-
`}function
|
|
1404
|
-
`)}function
|
|
1405
|
-
`))}}var
|
|
1406
|
-
`?(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
|
|
1400
|
+
`}function nw(n,e){return[Vd(n.summary),`Full report: ${qd(e)}`,""].join(`
|
|
1401
|
+
`)}function rw(n){let e=["# CodeLinter report",""];return n.issues.length===0?e.push("No defects found.",""):e.push(...xk(n.issues),""),e.push("## Summary","",...Lk(n.summary),""),e.join(`
|
|
1402
|
+
`)}function ow(n){return`${JSON.stringify(n,null,2)}
|
|
1403
|
+
`}function Vd(n){return`Summary: Issues: ${nt(n.issues)} | Errors: ${nt(n.errors)} | Warnings: ${nt(n.warnings)} | Suggestions: ${nt(n.suggestions)} | Files checked: ${nt(n.filesChecked)}`}function Tk(n,e){return`Showing ${nt(e)} of ${nt(n)} issues. Use --output-path <path> to write all results.`}function kk(n){let e=["No","File","Line","Column","Severity","Rule","Message"],t=n.map((r,o)=>({cells:Mk(r,o+1)}));return["CodeLinter report","",Ot(e,t)].join(`
|
|
1404
|
+
`)}function xk(n){let e=["| No | File | Line | Column | Severity | Rule | Message |","| ---: | --- | ---: | ---: | --- | --- | --- |"];for(let[t,r]of n.entries())e.push(Nk(r,t+1));return e}function Nk(n,e){return`| ${[String(e),qd(An(n.file)),Va(n.line),Va(n.column),An(n.severity),An(n.rule),An(n.message)].map(Ok).join(" | ")} |`}function Lk(n){return[`- Issues: ${nt(n.issues)}`,`- Errors: ${nt(n.errors)}`,`- Warnings: ${nt(n.warnings)}`,`- Suggestions: ${nt(n.suggestions)}`,`- Files checked: ${nt(n.filesChecked)}`]}function Ok(n){return n.replace(ew,"\\\\").replace(Dk,"\\|").replace(Rk,"<br>")}function Mk(n,e){return[String(e),qd(An(_k(n.file))),Va(n.line),Va(n.column),An(n.severity),An(n.rule),An(n.message)]}function _k(n){if(!Ei.isAbsolute(n))return n;let e=Ei.relative(process.cwd(),n);return!e||e.startsWith("..")||Ei.isAbsolute(e)?n:e}function qd(n){return n.replace(ew,"/")}function An(n){let e=n?.trim();return e||Qy}function Va(n){return n===void 0?Qy:String(n)}function nt(n){return n.toLocaleString("en-US")}var $k=/^-?\d+$/;function zd(){return new Hk("lint").description("Run DevEco Code Linter checks for TS/ArkTS code").addArgument(new jk("[path]","File or directory to lint").argParser(Vk)).option("--fix","Auto-fix fixable code issues").option("--incremental","Only check uncommitted files").option("--config-path <path>","Path to lint configuration file",Bk).option("--product <product>","Product name defined in build-profile.json5",Wk,"default").option("--format <format>","Report format (choices: default, json)",Uk,"default").option("--output-path <path>","Complete report file or directory",Gk).option("--limit <number>","Maximum terminal issues to display when --output-path is omitted",qk).action(async(n,e)=>{await zk(n,e)})}function Uk(n){if(n==="default"||n==="json")return n;throw new Dn("Invalid --format. Expected one of: default, json.")}function Bk(n){Yd(n,"--config-path");let e=je.extname(n).toLowerCase();if(e!==".json"&&e!==".json5")throw new Dn("`--config-path` must point to a .json or .json5 file.");return n}function Wk(n){return iw(n,"product"),n}function Gk(n){return Yd(n,"--output-path"),n}function Vk(n){return Yd(n,"path"),n}function qk(n){if(iw(n,"limit"),!$k.test(n))throw new Dn("`--limit` must be a positive integer.");let e=Number.parseInt(n,10);if(e<=0||!Number.isSafeInteger(e))throw new Dn("`--limit` must be an integer greater than 0.");return e}function iw(n,e){if(n.trim().length===0||cw(n))throw new Dn(`Invalid --${e} value.`)}function Yd(n,e){let t=`\`${e}\``;if(n.length===0||cw(n))throw new Dn(`${t} must be a non-empty path without control characters.`)}async function zk(n,e){let t=process.cwd(),r=Zk(e.outputPath,e.format,t);e.fix&&console.warn(Fk("Running codelinter with --fix. Ensure your project source is trusted."));let o=await Yk(n,e,t);rx(o.diagnostics),process.exitCode=Kk(o,r,e.format,e.limit,t)}async function Yk(n,e,t){let r=await A.new(),o=new bi(r,t);return Jk(o,{lintPath:n,configPath:e.configPath,product:e.product,fix:e.fix,incremental:e.incremental})}async function Jk(n,e){let t=new ut;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 Kk(n,e,t,r,o){if(!n.report)return console.error(qa("Failed to generate Code Linter report.")),console.error(qa(n.reportError?.message??"Native JSON report was not generated.")),n.exitCode===0?1:n.exitCode;try{if(e){Xk(e,t,n.report);let i=aw(e,o);process.stdout.write(nw(n.report,i))}else process.stdout.write(tw(n.report,r));return n.exitCode}catch(i){return console.error(qa("Failed to generate Code Linter report.")),console.error(qa(i.message)),n.exitCode===0?1:n.exitCode}}function Xk(n,e,t){Pi.mkdirSync(je.dirname(n),{recursive:!0});let r=e==="json"?ow(t):rw(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 Zk(n,e,t){if(!n)return;let r=tx(n,t),o=ex(n,r),i=o?je.join(r,nx(e)):r;if(o||Qk(n,e),Pi.existsSync(i))throw new Dn(`Output file already exists: ${aw(i,t)}`);return i}function Qk(n,e){let t=sw(e);if(je.extname(n).toLowerCase()!==t)throw new Dn(`--output-path must use the ${t} extension for --format ${e}.`)}function ex(n,e){return Pi.existsSync(e)?Pi.statSync(e).isDirectory():n.endsWith("/")||n.endsWith("\\")||je.extname(n)===""}function tx(n,e){return je.resolve(e,n)}function nx(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}${sw(n)}`}function sw(n){return n==="json"?".json":".md"}function aw(n,e){let t=je.relative(e,n);return t&&!t.startsWith("..")&&!je.isAbsolute(t)?t:n}function rx(n){n&&process.stderr.write(n)}function cw(n){for(let e of n){let t=e.charCodeAt(0);if(t<=31||t===127)return!0}return!1}import{Command as ox,InvalidArgumentError as pw}from"commander";import*as W from"path";import*as Jd from"os";import{readdirSync as ix,existsSync as za,readFileSync as sx,unlinkSync as ax,copyFileSync as fw,writeFileSync as mw}from"fs";import{execa as cx}from"execa";import{cyan as ye,yellow as hw}from"colorette";import lx from"ora";var lw=["default","csv","json"];function gw(n){if(lw.includes(n))return n;throw new pw(`--format must be one of: ${lw.join(", ")} (got "${n}")`)}function dx(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new pw(`--limit must be a positive integer (got "${n}")`);return e}function ux(n){return[...n].sort((e,t)=>{let r=dw(e),o=dw(t);return r.apiVersion-o.apiVersion||r.suffix.localeCompare(o.suffix)})}function dw(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 yw(n){let t=ix(n,{withFileTypes:!0}).filter(r=>r.isFile()&&r.name.toLowerCase().endsWith(".json")).map(r=>r.name.slice(0,-5));return ux(t)}function px(n){let e=process.argv;for(let t=0;t<e.length;t+=1){let r=e[t],o;if(r==="--format"&&t+1<e.length?o=e[t+1]:r.startsWith("--format=")&&(o=r.slice(9)),o!==void 0){let i=gw(o);return i==="default"?"csv":i}}return n}async function fx(n){let e=await A.new(),{apiChangeDir:t}=e.getApiscanPaths();f(ye(`[compat:versions] apiChangeDir: "${t}"`));let r=yw(t);if(n==="json")console.log(JSON.stringify({versions:r,count:r.length},null,2));else{if(r.length===0){console.log("No SDK versions available.");return}console.log(r.join(`
|
|
1405
|
+
`))}}var uw=new Set([".ets",".c",".cpp"]);function mx(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 Error(`Module ${r.map(s=>`"${s}"`).join(", ")} ${i} not defined in build-profile.json5. Available modules: ${o}.`)}function hx(n){for(let e of n){let t=W.resolve(e);if(!za(t))throw new Error(`File "${e}" does not exist.`);let r=W.extname(t).toLowerCase();if(!uw.has(r)){let o=Array.from(uw).join(", ");throw new Error(`Unsupported file extension "${r}" for "${e}". Supported: ${o}.`)}}}function gx(n){let e=[],t=[];for(let r of n)W.extname(r).toLowerCase()===".ets"?e.push(r):t.push(r);return{arkTs:e,cpp:t}}function yx(n){let e=[],t=[],r="",o=!1,i=0;for(;i<n.length;){let s=n[i];o?{field:r,inQuotes:o,i}=wx(n,i,s,r,o):s==='"'?(o=!0,i+=1):s===","?(t.push(r),r="",i+=1):s===`
|
|
1406
|
+
`?(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 wx(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 vx(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 Sx(n){let e=sx(n,"utf8"),t=e.startsWith("\uFEFF")?e.slice(1):e,r=yx(t);if(r.length<2)return[];let[o,...i]=r;return vx(o,i)}function bx(n,e){let t=n.match(/CSV saved to:\s*([^\r\n]+\.csv)/);if(!t)return null;let r=t[1].trim();return W.isAbsolute(r)?r:W.join(e,r)}function Ex(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(ye("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 Px(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(ye(`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(hw(` ... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function Cx(n,e){let t=n.slice(0,e),r=n.length-t.length;console.log(),console.log(JSON.stringify({count:n.length,records:t},null,2)),r>0&&console.log(hw(`... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function Ix(n,e){let t=[];for(let r of e){let o=n.profile.modules.find(i=>i.name===r);if(!o)throw new Error(`Module "${r}" not found in build-profile.json5.`);t.push(W.resolve(n.rootDir,o.srcPath))}return t}function Ax(n,e,t,r){if(!r.sourceVersion||!r.targetVersion)throw new Error("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}=gx(e),a=d=>W.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=Ix(t,r.modules);o.push("--modulePaths",i.join(","))}else o.push("--projectPath",t.rootDir);return o.push("--outputPath",Jd.tmpdir()),o}async function Dx(n,e){let t=W.dirname(e[0]);try{let o=(await cx(n.nodePath,e,{cwd:t,stdin:"ignore",stdout:"pipe",stderr:"inherit"})).stdout;return process.env.DEVECO_CLI_DEBUG&&(console.log(ye("[compat:check] === scan stdout ===")),process.stdout.write(o),o.endsWith(`
|
|
1407
1407
|
`)||process.stdout.write(`
|
|
1408
1408
|
`),console.log(ye("[compat:check] === end stdout ==="))),o}catch(r){let o=r;process.env.DEVECO_CLI_DEBUG&&o.stdout&&(console.log(ye("[compat:check] === scan stdout (on error) ===")),process.stdout.write(o.stdout),o.stdout.endsWith(`
|
|
1409
1409
|
`)||process.stdout.write(`
|
|
1410
1410
|
`),console.log(ye("[compat:check] === end stdout ===")));let i=new Error(`Compatibility scan failed: ${o.message}`+(o.stderr?`
|
|
1411
|
-
${o.stderr}`:""));throw o.stdout&&(i.stdout=o.stdout),i}}function
|
|
1412
|
-
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 Error(`--target-version "${n.targetVersion}" must be later than --source-version "${n.sourceVersion}". Run \`devecocli compat versions\` to see the available order.`)}}function
|
|
1413
|
-
`}function Nx(n,e,t,r){r===".csv"?dw(n,t):uw(t,hw(e),"utf8"),f(ye(`[compat:check] saved report: "${t}"`))}function Lx(n,e,t,r){if(r==="json"){let i=W.basename(n,".csv"),s=W.join(t,`${i}.json`);return uw(s,hw(e),"utf8"),f(ye(`[compat:check] saved report: "${s}"`)),s}let o=W.join(t,W.basename(n));return dw(n,o),f(ye(`[compat:check] saved report: "${o}"`)),o}async function Ox(n,e){let t=new xe(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 Mx(n,e){Px(n,e);let t=q.discover(process.cwd());e.modules&&e.modules.length>0&&lx(t,e.modules),n.length>0&&dx(n);let r=await A.new(),{apiChangeDir:o,scriptPath:i}=r.getApiscanPaths();f(ye(`[compat:check] script: "${i}"`));let s=mw(o);Cx(e,s),e.outputPath&&f(ye(`[compat:check] outputPath: "${e.outputPath}"`));let a=kx(e.outputPath,e.format);return f(ye(`[compat:check] outputTarget: ${a.kind}`)),xx(a),{project:t,scriptPath:i,target:a,toolProvider:r}}async function _x(n,e){let{project:t,scriptPath:r,target:o,toolProvider:i}=await Mx(n,e),s=ox({text:"Running compatibility check...",color:"cyan"}).start();try{await Ox(i,e);let a=bx(r,n,t,e);Ax(r,a);let c=await Ex(i,a),l=gx(c,qd.tmpdir());if(!l)throw new Error("Scanner output format unexpected: missing report path.");f(ye(`[compat:check] tmp csv: "${l}"`));let d=hx(l),h=null;if(o.kind==="file")Nx(l,d,o.filePath,o.ext),h=o.filePath;else if(o.kind==="dir")h=Lx(l,d,o.dirPath,e.format);else if(o.kind!=="none")throw new Error(`Unexpected output target kind: ${o.kind}`);Dx(l),s.stop(),Ix(d,h,e.format,e.limit,o.kind)}catch(a){throw s.fail("Compatibility check failed"),a}}var zd=new Qk("compat").description("Compatibility checking utilities.");zd.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.',fw,"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)",ix,100).action(async(n,e)=>{await _x(n,e)});zd.command("versions").description("List all available target SDK versions for compatibility checking").action(async()=>{let n=ax("csv");await cx(n)});var gw=zd;var yw=new Fx("check").description("Run DevEco project checks").addCommand(Gd());E()||yw.addCommand(gw);var ww=yw;import{Command as GL}from"commander";import{green as gu,red as VL}from"colorette";import yu from"fs";import iv from"path";import qL from"json5";import{readFileSync as dN}from"fs";import{join as jx}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"},He={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:jx(".ohos","config"),DOWNLOAD_CONNECT_TIMEOUT_MS:5e3},we={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},b={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."},Z={TOOLCHAIN_INIT_FAILED:"Auto-sign failed: unable to initialize toolchain",LOGIN_REQUIRED:"Failed to automatically generate signatures.Run devecocli auth login to sign in.",TEAM_INFO_FAILED:"Failed to obtain user team information.Check the network connection, HTTP proxy, and other configurations.",REALNAME_REQUIRED:"Users without real-name verification are not supported.Complete real-name verification in AppGallery Connect.",SESSION_EXPIRED:"User session expired or token invalid. Please login again.",REGION_CHINA_ONLY:"This feature is only available for accounts registered in Chinese mainland.",DEVICE_MISSING:"Unable to create the profile file due to missing devices.Connect a device through IP or USB, or manually add a device in AppGallery Connect first.If you are installing the HAP package on an emulator, you can skip the signing step.",DEVICE_DETECT_FAILED:"Unable to detect devices. Please check hdc status. If installing HAP on an emulator, signature step can be skipped.",JAVA_PLATFORM_UNSUPPORTED:"Java environment not found (Windows/macOS/Linux only).",JAVA_REQUIRED:"Java runtime is required to run hvigor.Set JAVA_HOME or add Java to PATH.",PROJECT_DIR_MISSING:"Not in a valid project directory (project-level build-profile.json5 not found).",ATOMIC_SERVICE_UNSUPPORTED:"AtomicService projects are not yet supported. Please configure signing manually."};function za(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}function Yd(n){let e=n.replace(He.TEAM_ID_INVALID_CHARS,"");return`${He.CERT_NAME_PREFIX}${e}.cer`}function no(n,e,t){if(n===ht.FORBIDDEN)return e===we.OPENPROXY_BLOCKED_URL?new Error(b.ERR_CERT_NETWORK_ERROR):new Error(b.ERR_FORBIDDEN);if(n===ht.UNAUTHORIZED)return new Error(b.ERR_UNAUTHORIZED);if(t.includes(we.USER_NOT_HARMONY_CODE))return new Error(b.ERR_USER_NOT_HARMONY);if(t.includes(we.CERT_LIMIT_CODE))return new Error(b.ERR_CERT_LIMIT_REACHED);let r=Hx(t);return new Error(r??b.ERR_DOWNLOAD_CER)}function Hx(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 Jd(n){return JSON.parse(n)}async function Sw(n){let e=`${te.BASE_URL}${te.CERT_LIST_PATH}`,t=await x.postAllowFailure(e,{headers:za(n)});if(t.statusCode!==200)throw no(t.statusCode,t.statusText,t.data);return Jd(t.data)?.certList??[]}async function Ya(n,e){return(await Sw(n)).find(r=>r.certName===e)??null}async function Kd(n,e){let t=`${te.BASE_URL}${te.CERT_DELETE_PATH}`,r=await x.deleteAllowFailure(t,{headers:za(n),params:{certIds:[e]}});if(r.statusCode!==200)throw no(r.statusCode,r.statusText,r.data);return Jd(r.data)?.ret?.code===0}async function Xd(n,e,t){let r=`${te.BASE_URL}${te.CERT_ADD_PATH}`,o={csr:e,certName:t,certType:He.CERT_TYPE_DEBUG},i=await x.postAllowFailure(r,{headers:za(n),params:o});if(i.statusCode!==200)throw no(i.statusCode,i.statusText,i.data);if(!i.data.includes(we.SUCCESS_MARKER))throw no(void 0,i.statusText,i.data)}async function Zd(n,e){let t=`${te.BASE_URL}${te.CERT_DOWNLOAD_URL_PATH}`,r=await x.postAllowFailure(t,{headers:za(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw no(r.statusCode,r.statusText,r.data);return Jd(r.data)?.urlsInfo?.[0]?.newUrl??null}import{mkdirSync as $x,writeFileSync as Ux,existsSync as Bx}from"fs";import{dirname as Wx}from"path";async function Pi(n,e){let{statusCode:t,statusText:r,buffer:o}=await x.getBinaryAllowFailure(n,{timeout:He.DOWNLOAD_CONNECT_TIMEOUT_MS});if(t!==200)throw t===ht.FORBIDDEN&&r===we.OPENPROXY_BLOCKED_URL?new Error(b.ERR_CERT_NETWORK_ERROR):new Error(b.ERR_DOWNLOAD_CER);let i=Wx(e);Bx(i)||$x(i,{recursive:!0}),Ux(e,o)}import aN from"fs/promises";import{readFileSync as cN}from"fs";import Ja from"path";import Pw from"crypto";import Gx from"os";import Ci 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"]},qx=8,Qd=64,zx=/[\\:*?"<>|=-]/g,gt={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function Yx(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>Qd)throw new Error(`The length of keyAlias cannot exceed ${Qd}`);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 Kx(n){return Pw.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function Xx(n){let e=n?.trim()??"";return e&&e.replace(zx,"_").slice(0,Qd)||gt.productName}async function Iw(){let n=await A.new(),e=n.javaPath;if(!e&&!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=E()?"hap-sign-tool":"hap-sign-tool.jar",o=Ja.join(t,"default","openharmony","toolchains","lib",r);try{await Ci.access(o)}catch(i){throw new Error(`${r} not found: ${o}`,{cause:i})}return{javaPath:e,toolPath:o}}async function Zx(n){let{javaPath:e,toolPath:t}=await Iw(),r=[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=>["-keyPwd","-keystorePwd"].includes(i)?`${i} ******`:i);return m.debug("generate-keypair \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),E()?[t,...r]:[e,"-jar",t,...r]}async function Qx(n){let{javaPath:e,toolPath:t}=await Iw(),r=[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=>["-keyPwd","-keystorePwd"].includes(i)?`${i} ******`:i);return m.debug("generate-csr \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),E()?[t,...r]:[e,"-jar",t,...r]}async function eN(n){m.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),Yx(n);let e=await Zx(n),t=await yo(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 tN(n){m.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),Jx(n);let e=await Qx(n),t=await yo(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 nN(n=qx){return Pw.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function rN(){let n=Gx.homedir();try{await Ci.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=Ja.join(n,".ohos","config");try{await Ci.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 Pe(n,e,t){let r=Xx(n),o=Ja.basename(e),i=Kx(e),s=`${r}_${o}_${i}=.${t}`,a=await rN();return Ja.join(a,s)}function oN(n){let e;try{e=q.discover(n).rootDir}catch(t){throw new Error(`Current directory ${n} is not a valid project root`,{cause:t})}return e}async function iN(n){try{await Ci.access(n)}catch(e){throw new Error(`Project directory ${n} is not accessible, missing read/write permissions`,{cause:e})}}async function sN(n){try{await Ci.access(n)}catch(e){throw new Error(`P12 file ${n} does not exist, terminating CSR generation.`,{cause:e})}}async function eu(n,e,t){let r=process.cwd(),o=oN(r);await iN(o),m.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${o}`);let i=nN(),s=await Pe(n??"",o,"p12"),a=await Pe(n??"",o,"csr");return console.log("Start generating p12"),await eN({keyAlias:e?.keyAlias??gt.keyAlias,keyPwd:i,keyAlg:e?.keyAlg??gt.keyAlg,keySize:e?.keySize??gt.keySize,keystoreFile:s,keystorePwd:i}),await sN(s),console.log("Start generating csr"),await tN({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 lN=["p12","cer","csr","p7b"];async function tu(n,e){for(let t of lN){let r=await Pe(n,e,t);await aN.rm(r,{force:!0})}}function nu(n){let e;try{e=cN(n,"utf-8")}catch{throw new Error(b.ERR_CERT_INVALIDATE)}if(!He.CERT_PATTERN.test(e))throw new Error(b.ERR_CERT_INVALIDATE)}async function Aw(n,e){return{certPath:await Pe(n,e,"cer"),csrPath:await Pe(n,e,"csr"),p12Path:await Pe(n,e,"p12"),profilePath:await Pe(n,e,"p7b")}}async function ru(n,e){let t=e??"",r=q.discover(process.cwd()).rootDir;await tu(t,r);let o=Yd(n.teamId),i=await Ya(n,o);if(i&&!await Kd(n,i.id))throw new Error(b.ERR_DOWNLOAD_CER);let s=await eu(e),a;try{a=dN(s.csrFilePath,"utf-8")}catch{throw new Error(b.ERR_READ_CSR)}console.log("Start generating certificate"),await Xd(n,a,o);let c=await Ya(n,o);if(!c)throw new Error(b.ERR_DOWNLOAD_CER);let l=await Zd(n,c.certObjectId);if(!l)throw new Error(b.ERR_DOWNLOAD_CER);let d=await Pe(t,r,"cer");await Pi(l,d),nu(d);let h=await Pe(t,r,"p7b");return{p12FilePath:s.p12FilePath,csrFilePath:s.csrFilePath,cerFilePath:d,profileFilePath:h,certId:c.id,keyAlias:s.keyAlias,keyPwd:s.keyPwd,storePassword:s.keyPwd}}import ic from"crypto";import xn from"fs";import*as $w from"path";import NN from"json5";import{execa as jw}from"execa";import*as Uw from"pkijs";import{createCipheriv as uN,createDecipheriv as pN,pbkdf2Sync as fN,randomBytes as au}from"crypto";import{promises as or}from"fs";import{dirname as mN,join as yt}from"path";var Ka=3,Ii=16,hN=1e4,Dw="material",gN=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),xw="aes-128-gcm",rr=12,Xa=16,Rn=4;function ou(n){return new Uint8Array(au(n))}function yN(n){return au(n).toString("hex")}function wN(...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 Rw(n,e,t=hN,r=Ii){let o=[...n,gN],i=wN(...o),s=Buffer.from(i).toString("utf8"),a=Buffer.from(s,"utf8"),c=fN(a,e,t,r,"sha256");return new Uint8Array(c)}function Tw(n,e){let t=au(rr),r=uN(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(Rn+rr+s.length);return c.writeUInt32BE(a,0),t.copy(c,Rn),s.copy(c,Rn+rr),c}function kw(n,e){if(e.length<Rn+rr+Xa)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(Rn,Rn+rr),o=e.subarray(Rn+rr,Rn+rr+t);if(o.length<Xa)throw new Error("Ciphertext too short for auth tag");let i=o.subarray(0,o.length-Xa),s=o.subarray(o.length-Xa),a=pN(xw,n,r);return a.setAuthTag(s),Buffer.concat([a.update(i),a.final()])}async function vN(n){try{await or.rm(n,{recursive:!0,force:!0})}catch{}}async function iu(n){let e=await or.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 or.readFile(yt(n,t[0]))}async function su(n,e){let t=yN(Ii),r=yt(n,t);return await or.writeFile(r,e),t}var Tn=class{static async generateMaterial(e){let t=yt(e,Dw);await vN(t);let r=yt(t,"ac"),o=yt(t,"ce");await or.mkdir(r,{recursive:!0}),await or.mkdir(o,{recursive:!0});for(let d=0;d<Ka;d++)await or.mkdir(yt(t,"fd",String(d)),{recursive:!0});let i=ou(Ii),s=[];for(let d=0;d<Ka;d++)s.push(ou(Ii));let a=ou(Ii),c=Rw(s,i),l=Tw(c,a);await su(r,i),await su(o,l);for(let d=0;d<Ka;d++){let h=yt(t,"fd",String(d));await su(h,s[d])}return a}static async readMaterial(e){let t=yt(e,Dw),r=yt(t,"ac"),o=new Uint8Array(await iu(r)),i=[];for(let d=0;d<Ka;d++){let h=yt(t,"fd",String(d)),w=await iu(h);i.push(new Uint8Array(w))}let s=yt(t,"ce"),a=await iu(s),c=Rw(i,o),l=kw(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t=mN(e);try{return await this.readMaterial(t)}catch{return await this.generateMaterial(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 kw(r,o).toString("utf8")}};import _w from"fs";import rc from"path";import IN from"json5";import*as Za from"fs";import*as Nw from"path";function Qa(n){let e=Nw.resolve(n);if(!Za.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=Za.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 oo from"fs";import*as $e from"path";import{debuglog as ro}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 SN(n){return Object.prototype.hasOwnProperty.call(Lw,n)}function ec(n){if(SN(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 bN}from"url";var nc=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 tc(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Mw(n){return n==null||n.length===0}function EN(n){return!Mw(n)}function cu(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function PN(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 CN(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 kn=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=$e.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=$e.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=$e.join(t.sdkPath,"default","sdk-pkg.json"),a=Qa(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=$e.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(oo.existsSync(e))return oo.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=bN(e);if(t.includes("dist")){let s=$e.dirname(t),a=$e.dirname(s);return $e.join(a,"src","resources")}let r=$e.dirname(t),o=$e.dirname(r),i=$e.dirname(o);return $e.join(i,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let r;try{r=this.readBuiltInConfigText()}catch{ro("read builtin acl permission failed.");return}if(r!==void 0)try{let o=JSON.parse(r),s=(Array.isArray(o)?o:tc(o)?Object.values(o):[]).filter(tc).map(a=>new nc(a));s.forEach(a=>{let c=a.permissionInsteadName;EN(c)&&(a.permissionInsteadName=ec(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(o){ro(`failed to parse aclPermissionsInfo.json: ${o}`)}}static initAclPermissionFromSDK(e,t,r){let o=this.parsePermissionDefinitionFile(e);o&&o.forEach(i=>{if(!tc(i))return;let s=i,a=cu(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)||cu(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||cu(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:PN(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let o=new nc;o.permissionName=t;let i=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;o.permissionDisplayName=i;let s=CN(r,this.ACL_SINCE_KEY);o.minSupportApiLevel=String(s),this.handleInsteadName(o,i),e.add(o)}static parsePermissionDefinitionFile(e){let t=$e.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!oo.existsSync(t))return;let r;try{r=oo.readFileSync(t,"utf-8")}catch(s){ro(`failed to load permissionDefinitions.json: ${s}`);return}let o;try{let s=JSON.parse(r);if(!tc(s)){ro("json object is null");return}o=s}catch(s){ro(`failed to parse permissionDefinitions.json: ${s}`);return}let i=o[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(i)){ro("definePermissions is not an array");return}return i}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=ec(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=ec(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function oc(n,e){let t=new Set,r=new Set;kn.handleSpecificAclPermissions(),kn.initAclPermission(n,e);for(let o of n.profile.modules){let i=Fw(o,n,e,r,rc.join("src","main"));for(let a of i)t.add(a);let s=Fw(o,n,e,r,rc.join("src","ohosTest"));for(let a of s)t.add(a)}return AN(r),t}function AN(n){if(n.size>0)throw new Error(Ow.DUPLICATE_PERMISSION)}function Fw(n,e,t,r,o){let i=RN(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 v=DN(w,"name");v&&s.push(v)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=rc.join(t.sdkPath,"default","sdk-pkg.json"),l=Qa(c),d=kn.getAclPermissionInfos(e),h=new Set(Array.from(d).filter(w=>{let v=Number(w.minSupportApiLevel);return Number.isFinite(v)&&v<=l}).map(w=>w.permissionName));for(let w of Array.from(a))h.has(w)||a.delete(w);return a}function DN(n,e){let t=n[e];return typeof t=="string"?t:""}function RN(n,e,t){let r=rc.join(n,e.srcPath,t,"module.json5"),o=TN(r);if(o==null)return null;let i=kN(o,"module");return i==null?null:xN(i,"requestPermissions")}function TN(n){try{if(!_w.existsSync(n))return null;let e=_w.readFileSync(n,"utf-8");return IN.parse(e)}catch{return null}}function kN(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 xN(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}function LN(n){let e=Buffer.from(n,"utf8"),t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var du=class{async verifyStorePassword(e,t){try{let r=xn.readFileSync(e);return await Uw.PFX.fromBER(r).parseInternalValues({password:LN(t),checkIntegrity:!0}),!0}catch{return!1}}getLocalCerFingerprints(e){let r=xn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(r&&r.length>0)return r.map(o=>this.formatFp(new ic.X509Certificate(o).fingerprint256));try{return[this.formatFp(new ic.X509Certificate(xn.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let o=xn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let i of o)try{let s=new ic.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 ON(n){let e=xn.readFileSync(n,"utf-8"),t=MN(e),r=null;if(t)try{r=JSON.parse(t)}catch{r=null}let o=r?.["bundle-info"]??{};return{rawContent:e,bundleNameInProfile:lu(o["bundle-name"]),expiryDate:_N(r?.validity?.["not-after"]),cerFingerprintInProfile:FN(lu(o["development-certificate"])),deviceUdidsInProfile:jN(r?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:HN(r?.acls?.["allowed-acls"]),teamIdInProfile:lu(o["developer-id"])}}function MN(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 _N(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function FN(n){if(!n)return null;try{let t=new ic.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function jN(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 HN(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 lu(n){return typeof n=="string"?n:null}var Ai=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=q.discover(process.cwd()),a=s.rootDir,[c,l]=await Promise.all([$N(i,a),BN(t.hdcPath)]),d=null;if(Hw(c).allExist)try{d=ON(c.profileFile)}catch{}return{force:r,teamId:o,productName:i,projectPath:a,materialPaths:c,bundleName:s.getBundleName(),deviceUdids:l,storePassword:await UN(a,i,c.storeFile),localAclPermissions:[...oc(s,t)].sort(),hapSignTool:new du,profileInfo:d}}static#t(e){return e.force?(f("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:qe({force:!0})}):null}static#n(e){let t=Hw(e.materialPaths);return t.allExist?null:(f(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:qe({allFilesExist:!1,missingFiles:t.missing})})}static#r(e){return(e.profileInfo?.rawContent??"").trim().length>0?null:(f("[reGenerateSign] profile content is empty"),{shouldRegenerate:!0,reason:"Profile file content is empty",checkDetails:qe({allFilesExist:!0,profileContentNotEmpty:!1})})}static#o(e){let t=e.profileInfo?.expiryDate;return!t||t>=new Date?null:(f(`[reGenerateSign] profile expired at ${t.toISOString()}`),{shouldRegenerate:!0,reason:`Profile expired at ${t.toISOString()}`,checkDetails:qe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!1})})}static#i(e){let t=e.profileInfo?.bundleNameInProfile;return t&&t===e.bundleName?null:(f(`[reGenerateSign] bundleName mismatch \u2014 current=${e.bundleName}, profile=${t}`),{shouldRegenerate:!0,reason:`bundleName mismatch: current=${e.bundleName}, in profile=${t}`,checkDetails:qe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!1})})}static#s(e){let t=e.profileInfo?.teamIdInProfile;return t&&t===e.teamId?null:(f(`[reGenerateSign] teamId mismatch \u2014 current=${e.teamId}, profile=${t}`),{shouldRegenerate:!0,reason:`teamId mismatch: current=${e.teamId}, in profile=${t}`,checkDetails:qe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=GN(e.profileInfo?.deviceUdidsInProfile??[],e.deviceUdids);return t.allPresent?null:(f(`[reGenerateSign] missing device UDIDs: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Device UDID(s) not in profile: ${t.missing.join(", ")}`,checkDetails:qe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return VN(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(f("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:qe({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:(f("[reGenerateSign] certificate mismatch"),{shouldRegenerate:!0,reason:"Certificate mismatch between profile and local .cer file",checkDetails:qe({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:(f(`[reGenerateSign] local certificate expired at ${r.toISOString()}`),{shouldRegenerate:!0,reason:`Local certificate expired at ${r.toISOString()}`,checkDetails:qe({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?await e.hapSignTool.verifyStorePassword(e.materialPaths.storeFile,e.storePassword)?null:(f("[reGenerateSign] keystore password verification failed"),{shouldRegenerate:!0,reason:"Keystore password verification failed (storeFile may be corrupted or password changed)",checkDetails:qe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})}):(f("[reGenerateSign] no stored keystore password"),{shouldRegenerate:!0,reason:"No stored keystore password available for verification",checkDetails:qe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})})}static#p(){return f("[reGenerateSign] all checks passed \u2014 skip regeneration"),{shouldRegenerate:!1,reason:"",checkDetails:qe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function $N(n,e){let[t,r,o,i]=await Promise.all([Pe(n,e,"p12"),Pe(n,e,"csr"),Pe(n,e,"cer"),Pe(n,e,"p7b")]);return{storeFile:t,csrFile:r,cerFile:o,profileFile:i}}async function UN(n,e,t){let r=$w.join(n,"build-profile.json5");if(!xn.existsSync(r))return;let o;try{o=NN.parse(xn.readFileSync(r,"utf-8"))}catch{return}let a=(o?.app?.signingConfigs??[]).find(c=>c.name===e)?.material?.storePassword;if(a)try{return await Tn.decryptPassword(a,t)}catch{return}}async function BN(n){f(`Executing: ${n} list targets`);let{stdout:e}=await jw(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let o of e.split(`
|
|
1414
|
-
`)){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{f(`Executing: ${n} -t ${o} shell bm get -u`);let{stdout:i}=await
|
|
1415
|
-
`);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
|
|
1416
|
-
`)){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
|
|
1417
|
-
`);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
|
|
1411
|
+
${o.stderr}`:""));throw o.stdout&&(i.stdout=o.stdout),i}}function Rx(n,e){if(n.length>0&&e.modules&&e.modules.length>0)throw new Error("Cannot use `--modules` together with file arguments. Use either file-level scanning (with files) or module-level scanning (with --modules).");if(!e.sourceVersion)throw new Error("--source-version is required.");if(!e.targetVersion)throw new Error("--target-version is required.");if(!e.outputPath&&e.format==="csv")throw new Error("--format csv requires --output-path. For console output, use --format json or --format default (or omit the flag).")}function Tx(n,e){let t=[];if(n.sourceVersion&&!e.includes(n.sourceVersion)&&t.push(`--source-version "${n.sourceVersion}"`),n.targetVersion&&!e.includes(n.targetVersion)&&t.push(`--target-version "${n.targetVersion}"`),t.length>0){let r=t.length>1?"are":"is";throw new Error(`${t.join(" and ")} ${r} not in the available SDK version list.
|
|
1412
|
+
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 Error(`--target-version "${n.targetVersion}" must be later than --source-version "${n.sourceVersion}". Run \`devecocli compat versions\` to see the available order.`)}}function kx(n,e,t,r,o){o==="none"&&(t==="json"?Cx(n,r):Px(n,r)),Ex(n,e)}function xx(n,e){let t=W.dirname(n),r=W.basename(n),o=e.slice(1).map(i=>i.startsWith("--")?i:`"${i}"`).join(" ");f(ye(`[compat:check] command: cd "${t}" && node "${r}" ${o}`))}function Nx(n){try{ax(n),f(ye(`[compat:check] cleaned up tmp report: "${n}"`))}catch(e){f(ye(`[compat:check] failed to clean up tmp report: ${e.message}`))}}var Lx=[".csv",".json"];function Ox(n){return Lx.includes(n.toLowerCase())}function Mx(n,e){if(!n)return{kind:"none"};let t=W.extname(n).toLowerCase();if(!Ox(t))return{kind:"dir",dirPath:W.resolve(n)};if(t===".csv"&&!(e==="default"||e==="csv")||t===".json"&&e!=="json")throw new Error(`The --output-path file extension '${t}' does not match --format ${e}. Use --format ${t===".json"?"json":"default"}, or rename the file.`);return{kind:"file",filePath:W.resolve(n),ext:t}}function _x(n){if(n.kind==="file"){if(za(n.filePath))throw new Error(`Target file "${n.filePath}" already exists. Remove it first, or choose a different --output-path.`);let e=W.dirname(n.filePath);if(!za(e))throw new Error(`Target directory "${e}" does not exist. Create it first, or choose a different --output-path.`)}else if(n.kind==="dir"&&!za(n.dirPath))throw new Error(`Target directory "${n.dirPath}" does not exist. Create it first, or choose a different --output-path.`)}function ww(n){return JSON.stringify({count:n.length,records:n},null,2)+`
|
|
1413
|
+
`}function Fx(n,e,t,r){r===".csv"?fw(n,t):mw(t,ww(e),"utf8"),f(ye(`[compat:check] saved report: "${t}"`))}function jx(n,e,t,r){if(r==="json"){let i=W.basename(n,".csv"),s=W.join(t,`${i}.json`);return mw(s,ww(e),"utf8"),f(ye(`[compat:check] saved report: "${s}"`)),s}let o=W.join(t,W.basename(n));return fw(n,o),f(ye(`[compat:check] saved report: "${o}"`)),o}async function Hx(n,e){let t=new xe(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 $x(n,e){Rx(n,e);let t=z.discover(process.cwd());e.modules&&e.modules.length>0&&mx(t,e.modules),n.length>0&&hx(n);let r=await A.new(),{apiChangeDir:o,scriptPath:i}=r.getApiscanPaths();f(ye(`[compat:check] script: "${i}"`));let s=yw(o);Tx(e,s),e.outputPath&&f(ye(`[compat:check] outputPath: "${e.outputPath}"`));let a=Mx(e.outputPath,e.format);return f(ye(`[compat:check] outputTarget: ${a.kind}`)),_x(a),{project:t,scriptPath:i,target:a,toolProvider:r}}async function Ux(n,e){let{project:t,scriptPath:r,target:o,toolProvider:i}=await $x(n,e),s=lx({text:"Running compatibility check...",color:"cyan"}).start();try{await Hx(i,e);let a=Ax(r,n,t,e);xx(r,a);let c=await Dx(i,a),l=bx(c,Jd.tmpdir());if(!l)throw new Error("Scanner output format unexpected: missing report path.");f(ye(`[compat:check] tmp csv: "${l}"`));let d=Sx(l),h=null;if(o.kind==="file")Fx(l,d,o.filePath,o.ext),h=o.filePath;else if(o.kind==="dir")h=jx(l,d,o.dirPath,e.format);else if(o.kind!=="none")throw new Error(`Unexpected output target kind: ${o.kind}`);Nx(l),s.stop(),kx(d,h,e.format,e.limit,o.kind)}catch(a){throw s.fail("Compatibility check failed"),a}}var Kd=new ox("compat").description("Compatibility checking utilities.");Kd.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.',gw,"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)",dx,100).action(async(n,e)=>{await Ux(n,e)});Kd.command("versions").description("List all available target SDK versions for compatibility checking").action(async()=>{let n=px("csv");await fx(n)});var vw=Kd;var Sw=new Bx("check").description("Run DevEco project checks").addCommand(zd());b()||Sw.addCommand(vw);var bw=Sw;import{Command as JL}from"commander";import{green as vu,red as KL}from"colorette";import Su from"fs";import cv from"path";import XL from"json5";import{readFileSync as hN}from"fs";import{join as Wx}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"},He={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:Wx(".ohos","config"),DOWNLOAD_CONNECT_TIMEOUT_MS:5e3},we={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},E={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."},Z={TOOLCHAIN_INIT_FAILED:"Auto-sign failed: unable to initialize toolchain",LOGIN_REQUIRED:"Failed to automatically generate signatures.Run devecocli auth login to sign in.",TEAM_INFO_FAILED:"Failed to obtain user team information.Check the network connection, HTTP proxy, and other configurations.",REALNAME_REQUIRED:"Users without real-name verification are not supported.Complete real-name verification in AppGallery Connect.",SESSION_EXPIRED:"User session expired or token invalid. Please login again.",REGION_CHINA_ONLY:"This feature is only available for accounts registered in Chinese mainland.",DEVICE_MISSING:"Unable to create the profile file due to missing devices.Connect a device through IP or USB, or manually add a device in AppGallery Connect first.If you are installing the HAP package on an emulator, you can skip the signing step.",DEVICE_DETECT_FAILED:"Unable to detect devices. Please check hdc status. If installing HAP on an emulator, signature step can be skipped.",JAVA_PLATFORM_UNSUPPORTED:"Java environment not found (Windows/macOS/Linux only).",JAVA_REQUIRED:"Java runtime is required to run hvigor.Set JAVA_HOME or add Java to PATH.",PROJECT_DIR_MISSING:"Not in a valid project directory (project-level build-profile.json5 not found).",ATOMIC_SERVICE_UNSUPPORTED:"AtomicService projects are not yet supported. Please configure signing manually."};function Ya(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}function Xd(n){let e=n.replace(He.TEAM_ID_INVALID_CHARS,"");return`${He.CERT_NAME_PREFIX}${e}.cer`}function ro(n,e,t){if(n===ht.FORBIDDEN)return e===we.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN);if(n===ht.UNAUTHORIZED)return new Error(E.ERR_UNAUTHORIZED);if(t.includes(we.USER_NOT_HARMONY_CODE))return new Error(E.ERR_USER_NOT_HARMONY);if(t.includes(we.CERT_LIMIT_CODE))return new Error(E.ERR_CERT_LIMIT_REACHED);let r=Gx(t);return new Error(r??E.ERR_DOWNLOAD_CER)}function Gx(n){let e=Ew(n);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let r=typeof t=="string"?Ew(t):t;if(r&&typeof r=="object"){let o=r.msg;if(typeof o=="string"&&o.trim()!=="")return o}return null}function Ew(n){try{return JSON.parse(n)}catch{return null}}function Zd(n){return JSON.parse(n)}async function Pw(n){let e=`${te.BASE_URL}${te.CERT_LIST_PATH}`,t=await x.postAllowFailure(e,{headers:Ya(n)});if(t.statusCode!==200)throw ro(t.statusCode,t.statusText,t.data);return Zd(t.data)?.certList??[]}async function Ja(n,e){return(await Pw(n)).find(r=>r.certName===e)??null}async function Qd(n,e){let t=`${te.BASE_URL}${te.CERT_DELETE_PATH}`,r=await x.deleteAllowFailure(t,{headers:Ya(n),params:{certIds:[e]}});if(r.statusCode!==200)throw ro(r.statusCode,r.statusText,r.data);return Zd(r.data)?.ret?.code===0}async function eu(n,e,t){let r=`${te.BASE_URL}${te.CERT_ADD_PATH}`,o={csr:e,certName:t,certType:He.CERT_TYPE_DEBUG},i=await x.postAllowFailure(r,{headers:Ya(n),params:o});if(i.statusCode!==200)throw ro(i.statusCode,i.statusText,i.data);if(!i.data.includes(we.SUCCESS_MARKER))throw ro(void 0,i.statusText,i.data)}async function tu(n,e){let t=`${te.BASE_URL}${te.CERT_DOWNLOAD_URL_PATH}`,r=await x.postAllowFailure(t,{headers:Ya(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw ro(r.statusCode,r.statusText,r.data);return Zd(r.data)?.urlsInfo?.[0]?.newUrl??null}import{mkdirSync as Vx,writeFileSync as qx,existsSync as zx}from"fs";import{dirname as Yx}from"path";async function Ci(n,e){let{statusCode:t,statusText:r,buffer:o}=await x.getBinaryAllowFailure(n,{timeout:He.DOWNLOAD_CONNECT_TIMEOUT_MS});if(t!==200)throw t===ht.FORBIDDEN&&r===we.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_DOWNLOAD_CER);let i=Yx(e);zx(i)||Vx(i,{recursive:!0}),qx(e,o)}import pN from"fs/promises";import{readFileSync as fN}from"fs";import Ka from"path";import Aw from"crypto";import Jx from"os";import Ii from"fs/promises";var Dw={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},Cw=["ECC","RSA"],Iw=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],Kx={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},Xx=8,nu=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>nu)throw new Error(`The length of keyAlias cannot exceed ${nu}`);if(!Cw.includes(n.keyAlg))throw new Error(`Invalid key algorithm ${n.keyAlg}, available: ${Cw.join(" / ")}`);let e=Kx[n.keyAlg];if(!e.includes(n.keySize))throw new Error(`Key algorithm ${n.keyAlg} does not support size ${n.keySize}, available: ${e.join(", ")}`)}function eN(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(!Iw.includes(n.signAlg))throw new Error(`Invalid sign algorithm ${n.signAlg}, available: ${Iw.join(" / ")}`)}function tN(n){return Aw.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function nN(n){let e=n?.trim()??"";return e&&e.replace(Zx,"_").slice(0,nu)||gt.productName}async function Rw(){let n=await A.new(),e=n.javaPath;if(!e&&!b())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=b()?"hap-sign-tool":"hap-sign-tool.jar",o=Ka.join(t,"default","openharmony","toolchains","lib",r);try{await Ii.access(o)}catch(i){throw new Error(`${r} not found: ${o}`,{cause:i})}return{javaPath:e,toolPath:o}}async function rN(n){let{javaPath:e,toolPath:t}=await Rw(),r=[Dw.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=>["-keyPwd","-keystorePwd"].includes(i)?`${i} ******`:i);return m.debug("generate-keypair \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),b()?[t,...r]:[e,"-jar",t,...r]}async function oN(n){let{javaPath:e,toolPath:t}=await Rw(),r=[Dw.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=>["-keyPwd","-keystorePwd"].includes(i)?`${i} ******`:i);return m.debug("generate-csr \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),b()?[t,...r]:[e,"-jar",t,...r]}async function iN(n){m.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),Qx(n);let e=await rN(n),t=await Hn(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 sN(n){m.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),eN(n);let e=await oN(n),t=await Hn(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 aN(n=Xx){return Aw.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function cN(){let n=Jx.homedir();try{await Ii.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=Ka.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 Pe(n,e,t){let r=nN(n),o=Ka.basename(e),i=tN(e),s=`${r}_${o}_${i}=.${t}`,a=await cN();return Ka.join(a,s)}function lN(n){let e;try{e=z.discover(n).rootDir}catch(t){throw new Error(`Current directory ${n} is not a valid project root`,{cause:t})}return e}async function dN(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 uN(n){try{await Ii.access(n)}catch(e){throw new Error(`P12 file ${n} does not exist, terminating CSR generation.`,{cause:e})}}async function ru(n,e,t){let r=process.cwd(),o=lN(r);await dN(o),m.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${o}`);let i=aN(),s=await Pe(n??"",o,"p12"),a=await Pe(n??"",o,"csr");return console.log("Start generating p12"),await iN({keyAlias:e?.keyAlias??gt.keyAlias,keyPwd:i,keyAlg:e?.keyAlg??gt.keyAlg,keySize:e?.keySize??gt.keySize,keystoreFile:s,keystorePwd:i}),await uN(s),console.log("Start generating csr"),await sN({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 mN=["p12","cer","csr","p7b"];async function ou(n,e){for(let t of mN){let r=await Pe(n,e,t);await pN.rm(r,{force:!0})}}function iu(n){let e;try{e=fN(n,"utf-8")}catch{throw new Error(E.ERR_CERT_INVALIDATE)}if(!He.CERT_PATTERN.test(e))throw new Error(E.ERR_CERT_INVALIDATE)}async function Tw(n,e){return{certPath:await Pe(n,e,"cer"),csrPath:await Pe(n,e,"csr"),p12Path:await Pe(n,e,"p12"),profilePath:await Pe(n,e,"p7b")}}async function su(n,e){let t=e??"",r=z.discover(process.cwd()).rootDir;await ou(t,r);let o=Xd(n.teamId),i=await Ja(n,o);if(i&&!await Qd(n,i.id))throw new Error(E.ERR_DOWNLOAD_CER);let s=await ru(e),a;try{a=hN(s.csrFilePath,"utf-8")}catch{throw new Error(E.ERR_READ_CSR)}console.log("Start generating certificate"),await eu(n,a,o);let c=await Ja(n,o);if(!c)throw new Error(E.ERR_DOWNLOAD_CER);let l=await tu(n,c.certObjectId);if(!l)throw new Error(E.ERR_DOWNLOAD_CER);let d=await Pe(t,r,"cer");await Ci(l,d),iu(d);let h=await Pe(t,r,"p7b");return{p12FilePath:s.p12FilePath,csrFilePath:s.csrFilePath,cerFilePath:d,profileFilePath:h,certId:c.id,keyAlias:s.keyAlias,keyPwd:s.keyPwd,storePassword:s.keyPwd}}import sc from"crypto";import xn from"fs";import*as Ww from"path";import FN from"json5";import{execa as Uw}from"execa";import*as Gw from"pkijs";import{createCipheriv as gN,createDecipheriv as yN,pbkdf2Sync as wN,randomBytes as du}from"crypto";import{promises as ir}from"fs";import{dirname as vN,join as yt}from"path";var Xa=3,Ai=16,SN=1e4,kw="material",bN=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Ow="aes-128-gcm",or=12,Za=16,Rn=4;function au(n){return new Uint8Array(du(n))}function EN(n){return du(n).toString("hex")}function PN(...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 xw(n,e,t=SN,r=Ai){let o=[...n,bN],i=PN(...o),s=Buffer.from(i).toString("utf8"),a=Buffer.from(s,"utf8"),c=wN(a,e,t,r,"sha256");return new Uint8Array(c)}function Nw(n,e){let t=du(or),r=gN(Ow,n,t),o=Buffer.concat([r.update(e),r.final()]),i=r.getAuthTag(),s=Buffer.concat([o,i]),a=s.length,c=Buffer.alloc(Rn+or+s.length);return c.writeUInt32BE(a,0),t.copy(c,Rn),s.copy(c,Rn+or),c}function Lw(n,e){if(e.length<Rn+or+Za)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(Rn,Rn+or),o=e.subarray(Rn+or,Rn+or+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=yN(Ow,n,r);return a.setAuthTag(s),Buffer.concat([a.update(i),a.final()])}async function CN(n){try{await ir.rm(n,{recursive:!0,force:!0})}catch{}}async function cu(n){let e=await ir.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 ir.readFile(yt(n,t[0]))}async function lu(n,e){let t=EN(Ai),r=yt(n,t);return await ir.writeFile(r,e),t}var Tn=class{static async generateMaterial(e){let t=yt(e,kw);await CN(t);let r=yt(t,"ac"),o=yt(t,"ce");await ir.mkdir(r,{recursive:!0}),await ir.mkdir(o,{recursive:!0});for(let d=0;d<Xa;d++)await ir.mkdir(yt(t,"fd",String(d)),{recursive:!0});let i=au(Ai),s=[];for(let d=0;d<Xa;d++)s.push(au(Ai));let a=au(Ai),c=xw(s,i),l=Nw(c,a);await lu(r,i),await lu(o,l);for(let d=0;d<Xa;d++){let h=yt(t,"fd",String(d));await lu(h,s[d])}return a}static async readMaterial(e){let t=yt(e,kw),r=yt(t,"ac"),o=new Uint8Array(await cu(r)),i=[];for(let d=0;d<Xa;d++){let h=yt(t,"fd",String(d)),w=await cu(h);i.push(new Uint8Array(w))}let s=yt(t,"ce"),a=await cu(s),c=xw(i,o),l=Lw(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t=vN(e);try{return await this.readMaterial(t)}catch{return await this.generateMaterial(t)}}static async encryptedPassword(e,t){let r=await this.getStoreKey(t),o=Buffer.from(e,"utf8");return Nw(r,o).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let r=await this.getStoreKey(t),o=Buffer.from(e,"hex");return Lw(r,o).toString("utf8")}};import Hw from"fs";import oc from"path";import kN from"json5";import*as Qa from"fs";import*as Mw from"path";function ec(n){let e=Mw.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 io from"fs";import*as $e from"path";import{debuglog as oo}from"util";var _w={"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 IN(n){return Object.prototype.hasOwnProperty.call(_w,n)}function tc(n){if(IN(n))return _w[n]}var Fw={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as AN}from"url";var rc=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 nc(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function jw(n){return n==null||n.length===0}function DN(n){return!jw(n)}function uu(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function RN(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 TN(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 kn=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=$e.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=$e.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=$e.join(t.sdkPath,"default","sdk-pkg.json"),a=ec(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=$e.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(io.existsSync(e))return io.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=AN(e);if(t.includes("dist")){let s=$e.dirname(t),a=$e.dirname(s);return $e.join(a,"src","resources")}let r=$e.dirname(t),o=$e.dirname(r),i=$e.dirname(o);return $e.join(i,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let r;try{r=this.readBuiltInConfigText()}catch{oo("read builtin acl permission failed.");return}if(r!==void 0)try{let o=JSON.parse(r),s=(Array.isArray(o)?o:nc(o)?Object.values(o):[]).filter(nc).map(a=>new rc(a));s.forEach(a=>{let c=a.permissionInsteadName;DN(c)&&(a.permissionInsteadName=tc(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(o){oo(`failed to parse aclPermissionsInfo.json: ${o}`)}}static initAclPermissionFromSDK(e,t,r){let o=this.parsePermissionDefinitionFile(e);o&&o.forEach(i=>{if(!nc(i))return;let s=i,a=uu(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(jw(a)||(this.generateAclInfos(r,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||uu(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||uu(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:RN(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let o=new rc;o.permissionName=t;let i=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;o.permissionDisplayName=i;let s=TN(r,this.ACL_SINCE_KEY);o.minSupportApiLevel=String(s),this.handleInsteadName(o,i),e.add(o)}static parsePermissionDefinitionFile(e){let t=$e.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!io.existsSync(t))return;let r;try{r=io.readFileSync(t,"utf-8")}catch(s){oo(`failed to load permissionDefinitions.json: ${s}`);return}let o;try{let s=JSON.parse(r);if(!nc(s)){oo("json object is null");return}o=s}catch(s){oo(`failed to parse permissionDefinitions.json: ${s}`);return}let i=o[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(i)){oo("definePermissions is not an array");return}return i}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=tc(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=tc(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function ic(n,e){let t=new Set,r=new Set;kn.handleSpecificAclPermissions(),kn.initAclPermission(n,e);for(let o of n.profile.modules){let i=$w(o,n,e,r,oc.join("src","main"));for(let a of i)t.add(a);let s=$w(o,n,e,r,oc.join("src","ohosTest"));for(let a of s)t.add(a)}return xN(r),t}function xN(n){if(n.size>0)throw new Error(Fw.DUPLICATE_PERMISSION)}function $w(n,e,t,r,o){let i=LN(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 v=NN(w,"name");v&&s.push(v)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=oc.join(t.sdkPath,"default","sdk-pkg.json"),l=ec(c),d=kn.getAclPermissionInfos(e),h=new Set(Array.from(d).filter(w=>{let v=Number(w.minSupportApiLevel);return Number.isFinite(v)&&v<=l}).map(w=>w.permissionName));for(let w of Array.from(a))h.has(w)||a.delete(w);return a}function NN(n,e){let t=n[e];return typeof t=="string"?t:""}function LN(n,e,t){let r=oc.join(n,e.srcPath,t,"module.json5"),o=ON(r);if(o==null)return null;let i=MN(o,"module");return i==null?null:_N(i,"requestPermissions")}function ON(n){try{if(!Hw.existsSync(n))return null;let e=Hw.readFileSync(n,"utf-8");return kN.parse(e)}catch{return null}}function MN(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 _N(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}function jN(n){let e=Buffer.from(n,"utf8"),t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var fu=class{async verifyStorePassword(e,t){try{let r=xn.readFileSync(e);return await Gw.PFX.fromBER(r).parseInternalValues({password:jN(t),checkIntegrity:!0}),!0}catch{return!1}}getLocalCerFingerprints(e){let r=xn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(r&&r.length>0)return r.map(o=>this.formatFp(new sc.X509Certificate(o).fingerprint256));try{return[this.formatFp(new sc.X509Certificate(xn.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let o=xn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let i of o)try{let s=new sc.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 HN(n){let e=xn.readFileSync(n,"utf-8"),t=$N(e),r=null;if(t)try{r=JSON.parse(t)}catch{r=null}let o=r?.["bundle-info"]??{};return{rawContent:e,bundleNameInProfile:pu(o["bundle-name"]),expiryDate:UN(r?.validity?.["not-after"]),cerFingerprintInProfile:BN(pu(o["development-certificate"])),deviceUdidsInProfile:WN(r?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:GN(r?.acls?.["allowed-acls"]),teamIdInProfile:pu(o["developer-id"])}}function $N(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 UN(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function BN(n){if(!n)return null;try{let t=new sc.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function WN(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 GN(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 pu(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=z.discover(process.cwd()),a=s.rootDir,[c,l]=await Promise.all([VN(i,a),zN(t.hdcPath)]),d=null;if(Bw(c).allExist)try{d=HN(c.profileFile)}catch{}return{force:r,teamId:o,productName:i,projectPath:a,materialPaths:c,bundleName:s.getBundleName(),deviceUdids:l,storePassword:await qN(a,i,c.storeFile),localAclPermissions:[...ic(s,t)].sort(),hapSignTool:new fu,profileInfo:d}}static#t(e){return e.force?(f("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:qe({force:!0})}):null}static#n(e){let t=Bw(e.materialPaths);return t.allExist?null:(f(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:qe({allFilesExist:!1,missingFiles:t.missing})})}static#r(e){return(e.profileInfo?.rawContent??"").trim().length>0?null:(f("[reGenerateSign] profile content is empty"),{shouldRegenerate:!0,reason:"Profile file content is empty",checkDetails:qe({allFilesExist:!0,profileContentNotEmpty:!1})})}static#o(e){let t=e.profileInfo?.expiryDate;return!t||t>=new Date?null:(f(`[reGenerateSign] profile expired at ${t.toISOString()}`),{shouldRegenerate:!0,reason:`Profile expired at ${t.toISOString()}`,checkDetails:qe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!1})})}static#i(e){let t=e.profileInfo?.bundleNameInProfile;return t&&t===e.bundleName?null:(f(`[reGenerateSign] bundleName mismatch \u2014 current=${e.bundleName}, profile=${t}`),{shouldRegenerate:!0,reason:`bundleName mismatch: current=${e.bundleName}, in profile=${t}`,checkDetails:qe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!1})})}static#s(e){let t=e.profileInfo?.teamIdInProfile;return t&&t===e.teamId?null:(f(`[reGenerateSign] teamId mismatch \u2014 current=${e.teamId}, profile=${t}`),{shouldRegenerate:!0,reason:`teamId mismatch: current=${e.teamId}, in profile=${t}`,checkDetails:qe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=JN(e.profileInfo?.deviceUdidsInProfile??[],e.deviceUdids);return t.allPresent?null:(f(`[reGenerateSign] missing device UDIDs: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Device UDID(s) not in profile: ${t.missing.join(", ")}`,checkDetails:qe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return KN(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(f("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:qe({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:(f("[reGenerateSign] certificate mismatch"),{shouldRegenerate:!0,reason:"Certificate mismatch between profile and local .cer file",checkDetails:qe({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:(f(`[reGenerateSign] local certificate expired at ${r.toISOString()}`),{shouldRegenerate:!0,reason:`Local certificate expired at ${r.toISOString()}`,checkDetails:qe({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?await e.hapSignTool.verifyStorePassword(e.materialPaths.storeFile,e.storePassword)?null:(f("[reGenerateSign] keystore password verification failed"),{shouldRegenerate:!0,reason:"Keystore password verification failed (storeFile may be corrupted or password changed)",checkDetails:qe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})}):(f("[reGenerateSign] no stored keystore password"),{shouldRegenerate:!0,reason:"No stored keystore password available for verification",checkDetails:qe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})})}static#p(){return f("[reGenerateSign] all checks passed \u2014 skip regeneration"),{shouldRegenerate:!1,reason:"",checkDetails:qe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function VN(n,e){let[t,r,o,i]=await Promise.all([Pe(n,e,"p12"),Pe(n,e,"csr"),Pe(n,e,"cer"),Pe(n,e,"p7b")]);return{storeFile:t,csrFile:r,cerFile:o,profileFile:i}}async function qN(n,e,t){let r=Ww.join(n,"build-profile.json5");if(!xn.existsSync(r))return;let o;try{o=FN.parse(xn.readFileSync(r,"utf-8"))}catch{return}let a=(o?.app?.signingConfigs??[]).find(c=>c.name===e)?.material?.storePassword;if(a)try{return await Tn.decryptPassword(a,t)}catch{return}}async function zN(n){f(`Executing: ${n} list targets`);let{stdout:e}=await Uw(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let o of e.split(`
|
|
1414
|
+
`)){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{f(`Executing: ${n} -t ${o} shell bm get -u`);let{stdout:i}=await Uw(n,["-t",o,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),s=YN(i);s&&r.push(s)}catch{f(`[reGenerateSign] Failed to get UDID for ${o}, skipping`)}return r}function YN(n){let e=n.trim();if(!e)return null;let t=e.split(`
|
|
1415
|
+
`);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 Bw(n){let e=[n.storeFile,n.csrFile,n.cerFile,n.profileFile],t=[];for(let r of e)xn.existsSync(r)||t.push(r);return{allExist:t.length===0,missing:t}}function JN(n,e){let t=[];for(let r of e)n.includes(r)||t.push(r);return{allPresent:t.length===0,missing:t}}function KN(n,e){let t=[...n].sort(),r=[...e].sort();return t.length!==r.length?!1:t.every((o,i)=>o===r[i])}function qe(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 mu}from"util";import{execa as hu}from"execa";async function qw(n,e){let t=await ac(n);if(!t)throw new Error(E.DEVICE_LIST_EMPTY);let r=await QN(e);if(t.length===0)for(let s of r)await XN(n,s.udid,s.deviceName);else for(let s of r)await ZN(n,t,s.udid,s.deviceName);let i=(await ac(n)).map(s=>s.id);if(i.length===0)throw new Error(E.DEVICE_LIST_EMPTY);return i}async function XN(n,e,t){await Jw(n,e,zw(t))}async function ZN(n,e,t,r){for(let o=0;o<e.length;o++){if(t===e[o].udid)return;if(o===e.length-1){await Jw(n,t,zw(r));return}}}function zw(n){switch(n){case"liteWearable":return"1";case"wearable":return"2";case"tv":return"3";default:return"4"}}async function Vw(n,e=1,t=100){let r=`${te.BASE_URL}${te.DEVICE_LIST_PATH}?encodeFlag=0&start=${e}&pageSize=${t}`,o=Kw(n),i=await x.get(r,{headers:o});if(!i)throw mu("query devices failed: response is null"),new Error(E.ERROR_WHILE_ADD_DEVICE);if(i.statusCode!==200)throw Yw(i.statusCode,i.statusText,i.data);let s=JSON.parse(i.data);if(!s||!s.list)throw mu("query devices failed: response list is null"),new Error(s.ret?.msg||E.ERROR_WHILE_ADD_DEVICE);return{deviceList:s.list,total:s.totalCount||0}}function Yw(n,e,t){return n===ht.FORBIDDEN?e===we.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN):n===ht.UNAUTHORIZED?new Error(E.ERR_UNAUTHORIZED):t.includes(we.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(E.DEVICE_LIMIT_REACHED):new Error(E.ERROR_WHILE_ADD_DEVICE)}async function ac(n){let t=await Vw(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 Vw(n,s,100);if(!a||!a.deviceList||a.deviceList.length===0)break;r.push(...a.deviceList)}return r}async function Jw(n,e,t){let r=`${te.BASE_URL}${te.DEVICE_ADD_PATH}`,o=Kw(n),s={deviceName:`auto_sign_device_No.${Math.floor(Math.random()*3e3)}${Date.now()}`,udid:e,deviceType:t},a=await x.postAllowFailure(r,{headers:o,params:s});if(!a)throw mu("add device failed: response is null"),new Error(E.ERROR_WHILE_ADD_DEVICE);if(a.statusCode!==200)throw Yw(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(we.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(E.DEVICE_LIMIT_REACHED):c.includes(we.DEVICE_NAME_REPEAT_CODE)?new Error(E.DEVICE_NAME_REPEAT):new Error(E.ERROR_WHILE_ADD_DEVICE)}function Kw(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}async function QN(n){let{stdout:e}=await hu(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let o of e.split(`
|
|
1416
|
+
`)){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 eL(o,n),s=await tL(o,n);i.length>0&&r.push({id:"",udid:i,deviceName:s})}catch{f(`Failed to get device info for ${o}, skipping`)}return r}async function eL(n,e){let{stdout:t}=await hu(e,["-t",n,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),r=t.trim();if(!r)return"";let o=r.split(`
|
|
1417
|
+
`);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 tL(n,e){let{stdout:t}=await hu(e,["-c","-t",n,"shell","getprop","hw_sc.build.os.deviceType"],{stdio:["ignore","pipe","pipe"]});return nL(t)}function nL(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 Nn from"fs";import{Buffer as cc}from"buffer";import{createHash as fL,createPrivateKey as mL,createPublicKey as hL,X509Certificate as gu}from"crypto";import*as Ue from"pkijs";import{createDecipheriv as rL,createHash as oL}from"crypto";var iL="1.2.840.113549.1.12.1.3",sL="1.2.840.113549.1.12.1.4";function aL(n){let e=new Uint8Array(n.length*2+2),t=new DataView(e.buffer);for(let r=0;r<n.length;r++)t.setUint16(r*2,n.charCodeAt(r),!1);return t.setUint16(n.length*2,0,!1),e}function Xw(n,e){let t=new Uint8Array(e*Math.ceil(n.length/e));for(let r=0;r<t.length;r++)t[r]=n[r%n.length];return t}function cL(n,e,t,r,o){let i=Math.ceil(r/t)+Math.ceil(o/t),s=new Uint8Array(i*t);for(let a=0;a<i;a++){let c=Array.from(n.slice(a*t,(a+1)*t)),l=511;for(let d=t-1;d>=0;d--)l>>=8,l+=e[d]+(c[d]||0),c[d]=l&255;s.set(c,a*t)}return s}function Zw(n,e,t,r,o){let a=new Uint8Array(64).fill(n),c=Xw(t,64),l=Xw(e,64),d=new Uint8Array(c.length+l.length);d.set(c),d.set(l,c.length);let h=Math.ceil(o/20),w=new Uint8Array(h*20);for(let v=0;v<h;v++){let I=Buffer.alloc(a.length+d.length);I.set(a),I.set(d,a.length);for(let V=0;V<r;V++)I=oL("sha1").update(I).digest();w.set(I.subarray(0,20),v*20);let G=new Uint8Array(64);for(let V=0;V<64;V++)G[V]=I[V%I.length];d=cL(d,G,64,t.length,e.length)}return w.subarray(0,o)}function lL(n){try{let t=n?.valueBlock?.value;if(!t||t.length<2)return null;let r=t[0]?.valueBlock?.valueHex,o=t[1]?.valueBlock?.valueDec;return!r||typeof o!="number"?null:{salt:new Uint8Array(r),iterations:o}}catch{return null}}function dL(n){switch(n){case iL:return{cipherName:"des-ede3-cbc",keyLen:24,ivLen:8};case sL:return{cipherName:"des-ede-cbc",keyLen:16,ivLen:8};default:return null}}function uL(n){let e=n.encryptedContent;if(!e)return null;let t=e.getValue?.()??e.valueBlock?.valueHex;return t?new Uint8Array(t):null}function pL(n){let e=n.encryptedContentInfo;if(!e)return null;let t=dL(e.contentEncryptionAlgorithm.algorithmId);if(!t)return null;let r=lL(e.contentEncryptionAlgorithm.algorithmParams);if(!r)return null;let o=uL(e);return o?{config:t,salt:r.salt,iterations:r.iterations,ciphertext:o}:null}function Qw(n,e){let t=pL(n);if(!t)return null;let r=aL(e),o=Zw(1,r,t.salt,t.iterations,t.config.keyLen),i=Zw(2,r,t.salt,t.iterations,t.config.ivLen);try{let s=rL(t.config.cipherName,Buffer.from(o),Buffer.from(i)),a=Buffer.concat([s.update(Buffer.from(t.ciphertext)),s.final()]);return new Uint8Array(a)}catch(s){throw new Error(`${t.config.cipherName} decryption failed: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}async function nv(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(E.DEVICE_LIST_EMPTY);let d=`${te.BASE_URL}${te.PROVISION_ADD_TEST_PATH}`,h=gL(t,r),w=await wL(n,d,a||[],r,s,h,i||[]);if(!w||!w.profileInfo||!w.profileInfo.provisionFileUrl)throw f("add provision failed, the provision file url is null"),new Error(E.ADD_PROFILE_FAIL);let v=w.profileInfo,G=(await EL(n,v.provisionFileUrl)).urlList,V=w.profileInfo.id;if(G&&G.length>0){let rt=await Tw(t,o),ot=rt.profilePath;if(!await PL(G,ot))throw await ev(n,V),new Error(E.ERROR_WHILE_DOWNLOAD_PROFILE);if(await ev(n,V),Nn.existsSync(rt.certPath)&&Nn.existsSync(ot)&&Nn.existsSync(rt.p12Path)){let mc=Nn.readFileSync(rt.certPath,"utf8"),hc=Nn.readFileSync(ot,"utf8");return await CL(hc,mc,rt.p12Path,c,l)||bL(ot),ot}}throw new Error(E.ADD_PROFILE_FAIL)}function gL(n,e){let t=n?`${n}_`:"";return`${yL(`${t}${e}_${e}`)}`}function yL(n){return fL("sha256").update(n).digest("hex").substring(0,16)}async function wL(n,e,t,r,o,i,s){vL(r);let a=wu(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 f("add provision failed: response is null"),new Error(E.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw yu(l.statusCode,l.statusText,l.data);let d=JSON.parse(l.data);if(!d||!d.ret||d.ret.code!==0)throw f(`add provision fail: ${l.data}`),SL(l.data,i),new Error(d.ret?.msg||E.ADD_PROFILE_FAIL);let h=d.provisionFileUrl;return{profileInfo:{id:d.id,name:i,provisionFileUrl:h}}}function yu(n,e,t){return n===ht.FORBIDDEN?e===we.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN):n===ht.UNAUTHORIZED?new Error(E.ERR_UNAUTHORIZED):t.includes(we.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(E.TEST_PROVISION_EXCEEDS_LIMIT):new Error(E.ADD_PROFILE_FAIL)}function vL(n){if(!n||n.trim().length===0)throw new Error(E.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!He.BUNDLE_NAME_REGEX.test(n))throw new Error(E.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function SL(n,e){if(n.includes(we.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(E.TEST_PROVISION_EXCEEDS_LIMIT);if(n.includes(we.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(E.PROFILE_NAME_REPEAT)}async function ev(n,e){if(!e||e.trim().length===0)return;let t=`${te.BASE_URL}${te.PROVISION_DELETE_PATH}?id=${e}`,r=await x.deleteAllowFailure(t,{headers:wu(n)});if(r.statusCode!==200)throw yu(r.statusCode,r.statusText,r.data);let o=JSON.parse(r.data);(!o||!o.ret||o.ret.code!==0)&&f(`delete provision failed: ${r.data}`)}function bL(...n){for(let e of n)try{Nn.existsSync(e)&&Nn.unlinkSync(e)}catch(t){f(`delete local sign file error: ${t.message}`)}}async function EL(n,e){let t=`${te.BASE_URL}${te.CERT_DOWNLOAD_URL_PATH}`,r=wu(n),o={sourceUrls:e},i=await x.postAllowFailure(t,{headers:r,params:o});if(!i)throw f("get download list failed: response is null"),new Error(E.ADD_PROFILE_FAIL);if(i.statusCode!==200)throw yu(i.statusCode,i.statusText,i.data);let s=JSON.parse(i.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw f("download: The application does not exist"),new Error(s.ret?.msg||E.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function PL(n,e){if(!n||n.length===0)return!1;let t=n[0].newUrl;return await Ci(t,e),!0}async function CL(n,e,t,r,o){return IL(n,e),r=r||He.TARGET_FRIENDLY_NAME,o=o||"",await AL(e,t,r,o),!0}function IL(n,e){if(e.lastIndexOf(He.CERT_BEGIN_HEADER)<0)throw new Error(E.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(He.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!n.includes(t))throw new Error(E.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}async function AL(n,e,t,r){let o=n.matchAll(He.CERTIFICATE_PATTERN_GLOBAL),i=[],s=new Date;for(let c of o)try{let l=c[0],d=DL(l),h=new Date(d.validFrom),w=new Date(d.validTo);if(s<h||s>w){let v=`Certificate is not valid, Valid from ${h} to ${w}`;throw console.warn(`checkCertificateInValidityPeriod: ${v}`),new Error(E.CERTIFICATE_HAS_EXPIRED)}i.push(d)}catch(l){throw console.warn(`checkCertificateInValidityPeriod\uFF1A ${l.message}`),new Error(E.CERTIFICATE_HAS_EXPIRED,{cause:l})}if(!i||i.length===0)throw new Error(E.CERTIFICATE_HAS_EXPIRED);if(!await HL(e,t,r,i))throw new Error(E.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function DL(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new gu(t);let r=cc.from(t,"base64");return new gu(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}var RL="1.2.840.113549.1.9.20",TL="1.2.840.113549.1.12.10.1.3",kL="1.2.840.113549.1.12.10.1.2",xL="1.2.840.113549.1.7.1",NL="1.2.840.113549.1.7.6";function LL(n){let e=cc.from(n,"utf8"),t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}function tv(n){let e=new DataView(n),t="";for(let o=0;o+1<n.byteLength;o+=2)t+=String.fromCharCode(e.getUint16(o,!1));let r=t.length;for(;r>0&&t.charCodeAt(r-1)===0;)r--;return t.substring(0,r)}function rv(n){if(n){for(let e of n)if(e.type===RL&&e.values.length>0){let t=e.values[0];if(t&&typeof t.value=="string")return t.value;if(t?.valueBlock&&typeof t.valueBlock.value=="string")return t.valueBlock.value;let r=t?.valueBlock?.valueHex;if(r instanceof ArrayBuffer)return tv(r);let o=t?.valueBlock?.valueHexView;if(o instanceof Uint8Array){let i=new ArrayBuffer(o.byteLength);return new Uint8Array(i).set(o),tv(i)}}}}function OL(n){if(!(n instanceof Ue.CertBag))return null;let e=n.parsedValue;if(!(e instanceof Ue.Certificate))return null;try{let t=e.toSchema().toBER(!1),r=new gu(cc.from(t));return r.publicKey?r.publicKey.export({type:"spki",format:"der"}):null}catch(t){return f(`Failed to parse cert from CertBag: ${t}`),null}}function ML(n,e,t){for(let r of n){if(r.bagId!==TL)continue;let o=rv(r.bagAttributes);if(!o||o.toLowerCase()!==e.toLowerCase())continue;let i=OL(r.bagValue);if(!i)continue;if(t.some(a=>{let c=a.publicKey.export({type:"spki",format:"der"});return i.equals(c)}))return!0}return!1}function _L(n,e,t,r){for(let o of n){if(o.bagId!==kL)continue;let i=rv(o.bagAttributes);if(!(!i||i.toLowerCase()!==e.toLowerCase()))try{let s=o.bagValue;if(!(s instanceof Ue.PKCS8ShroudedKeyBag))continue;let a=s.toSchema().toBER(!1),c=cc.from(a).toString("base64"),d=`-----BEGIN ENCRYPTED PRIVATE KEY-----
|
|
1418
1418
|
${(c.match(/.{1,64}/g)??[c]).join(`
|
|
1419
1419
|
`)}
|
|
1420
|
-
-----END ENCRYPTED PRIVATE KEY-----`,h=lL({key:d,format:"pem",passphrase:r}),v=dL(h).export({type:"spki",format:"der"});if(t.some(G=>{let V=G.publicKey.export({type:"spki",format:"der"});return v.equals(V)}))return!0}catch{}}return!1}async function NL(n,e,t){let r=new Ue.EncryptedData({schema:n.content});try{let o=await r.decrypt({password:e});return Ue.SafeContents.fromBER(o).safeBags}catch(o){try{let i=Kw(r,t);if(i){let s=new ArrayBuffer(i.byteLength);return new Uint8Array(s).set(i),Ue.SafeContents.fromBER(s).safeBags}}catch{}f(`SafeContent decrypt failed: pkijs=${o instanceof Error?o.message:String(o)}`)}return[]}async function LL(n,e,t){if(n.contentType===AL)try{let r=n.content;if(typeof r.getValue=="function"){let o=r.getValue();return Ue.SafeContents.fromBER(o).safeBags}}catch(r){f(`data SafeContent parse error: ${r instanceof Error?r.message:String(r)}`)}else if(n.contentType===DL)return NL(n,e,t);return[]}async function OL(n,e,t,r){try{let o=Nn.readFileSync(n),i=RL(t),s=Ue.PFX.fromBER(o);await s.parseInternalValues({password:i,checkIntegrity:!0});let a=s.parsedValue?.authenticatedSafe;if(!a)return!1;let c=[];for(let l of a.safeContents){let d=await LL(l,i,t);c.push(...d)}return c.length===0?!1:kL(c,e,r)?!0:xL(c,e,r,t)}catch(o){let i=o instanceof Error?o.message:String(o);return f(`Failed to process P12 file: ${n}, error: ${i}`),!1}}function hu(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var nv="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"},_L="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function FL(n){let e=ML[n];return e?`${nv}${e}`:void 0}function jL(){return`${nv}${_L}`}var HL={"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 tv(n,e){return(HL[n]??n).replace(/\{(\d+)\}/g,(r,o)=>String(e[Number(o)]??""))}function $L(n){return Array.from(n).join(", ")}function rv(n,e){if(n.size===0)return;let t=kn.getAclPermissionInfos(e),r=new Set;for(let h of t)n.has(h.permissionName)&&r.add(h);for(let h of r){let w=FL(h.permissionName);w!=null&&(h.permissionHelpUrlKey=w)}let o=new Set;for(let h of r)o.add(h.permissionDisplayName);let i=new Set;for(let h of r)if(h.permissionHelpUrlKey!=null){let w=h.permissionInsteadName??h.permissionDisplayName;i.add(`${w} (${h.permissionHelpUrlKey})`)}let s=jL(),a=tv("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=i.size>0?Array.from(i).join(", ")+".":"",d=tv("acl.permissions.warn",[$L(o),l,c]);console.log(d)}var cc=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=q.discover(process.cwd()),{passed:!0,message:""}}catch(t){return f(`[EnvCheck] Project.discover() failed: ${t.message}`),e(Z.PROJECT_DIR_MISSING)}}checkProduct(e,t){try{return this._project.validateProduct(e),{passed:!0,message:""}}catch(r){return f(`[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 f(`[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:Z.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import UL from"fs";import ov from"path";var lc=class{constructor(e){this.toolProvider=e}toolProvider;checkJava(e){try{return this.toolProvider.assertJava(),{passed:!0,message:""}}catch(t){return f(`[EnvCheck] Java check failed: ${t.message}`),e(Z.JAVA_PLATFORM_UNSUPPORTED)}}checkHapSignTools(e){let t=this.toolProvider.sdkPath,r=E()?"hap-sign-tool":"hap-sign-tool.jar",o=ov.join(t,"default","openharmony","toolchains","lib",r);if(!UL.existsSync(o)){let i=ov.join("sdk","default","openharmony","toolchains","lib",r);return e(`${r} not found.Check whether ${i} exists.`)}return{passed:!0,message:""}}};var dc=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await De.getUserInfo()}catch(e){return f(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await De.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(Z.LOGIN_REQUIRED)}catch(t){return f(`[EnvCheck] Login check failed: ${t.message}`),e(Z.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(Z.TEAM_INFO_FAILED);try{if((await sn()).teamList.length>0)return{passed:!0,message:""}}catch(r){return f(`[EnvCheck] Team API error: ${r.message}`),e(Z.TEAM_INFO_FAILED)}return f("[EnvCheck] No teams found for current user"),e(Z.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(Z.REALNAME_REQUIRED):t.isRealName!==!0?(f("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(Z.REALNAME_REQUIRED)):{passed:!0,message:""}:e(Z.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let r=e??"";try{let o=await sn();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 f(`[EnvCheck] ${s}`),{passed:!1,message:s}}return{passed:!0,message:""}}catch(o){return f(`[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(Z.REGION_CHINA_ONLY):{passed:!0,message:""}:(f("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(Z.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function BL(n){try{let{teamList:e}=await sn();if(e.length>0)return e[0].id}catch(e){f(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function WL(n){let e=await De.getUserInfo(),t=await De.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await BL(e.userId);if(!r)throw new Error("No team found");let o={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await sc(o)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var uc=class{constructor(e){this.toolProvider=e}toolProvider;async checkDevice(e,t){try{let r=await WL(t);if(r.length>0)return f(`[EnvCheck] Scenario 4 Device check: ${r.length} device(s) found in AGC cloud, skipping local device check`),{passed:!0,message:""};f("[EnvCheck] Scenario 4 Device check: no cloud devices found, falling back to local hdc");let i=await re.from(this.toolProvider).listDevices();return i.length===0?(f("[EnvCheck] Scenario 4 Device check: no local devices found"),e(Z.DEVICE_MISSING)):i.some(a=>Hn(a.serial))?{passed:!0,message:""}:(f("[EnvCheck] Scenario 4 Device check: local device found but not an emulator"),e(Z.DEVICE_MISSING))}catch(r){return f(`[EnvCheck] Scenario 4 Device check failed: ${r.message}`),e(Z.DEVICE_DETECT_FAILED)}}};var pc=class{projectChecker=new cc;toolchainChecker=null;authChecker=new dc;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 A.new();return this.toolchainChecker=new lc(e),this.deviceChecker=new uc(e),!0}catch(e){throw f(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(Z.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 f(`[EnvCheck] FAIL: ${e.message}`),new Error(e.message)}};function zL(n){if(yu.existsSync(n)){let e=yu.readFileSync(n,"utf-8");return qL.parse(e)}return{app:{signingConfigs:[],products:[]}}}function YL(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function JL(n){if(n.keyPwd===n.storePassword){let r=await Tn.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await Tn.encryptedPassword(n.keyPwd,n.p12FilePath),t=await Tn.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function KL(n,e,t){let r=iv.join(n,"build-profile.json5"),o=zL(r);YL(o);let i=t??"default",{keyPassword:s,storePassword:a}=await JL(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(h=>h.name===i);l!==void 0&&l>=0?o.app.signingConfigs[l]=c:o.app.signingConfigs.push(c);let d=o.app?.products?.findIndex(h=>h.name===i);d!==void 0&&d>=0?o.app.products[d].signingConfig=i:o.app.products.push({name:i,signingConfig:i}),yu.writeFileSync(r,JSON.stringify(o,null,2),"utf-8")}async function XL(n){let e=await De.getUserInfo(),t=await De.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 ZL(n){let e=n.product||"default";await new pc().preflight({productName:e,teamId:n.teamId}),console.log("Executing signature generate command");let r=await XL(n),o=await A.new(),{shouldRegenerate:i}=await Ai.shouldRegenerate({force:n.force??!1,teamId:r.teamId,productName:n.product},o);if(!i){console.log(gu("Signature generation completed successfully."));return}await QL(n,r,o),console.log(gu("Signature generation completed successfully."))}async function QL(n,e,t){let r=await ru(e,n.product),o=eO(n,e,r,t);o.allDeviceIds=await Ww(e,t.hdcPath),await Qw(e,o);let i=q.discover(process.cwd()).rootDir;await KL(i,r,n.product??"default"),console.log(gu(`Signing config written to ${iv.join(i,"build-profile.json5")}`))}function eO(n,e,t,r){let o=process.cwd(),i=q.discover(o),s=oc(i,r);return rv(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 sv=new GL("signature").description("Generate application signature.");sv.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 ZL(n)}catch(e){console.error(VL(e.message)),process.exit(1)}});var av=sv;se.name("devecocli").description("HarmonyOS application development command line tool").version("0.4.0-TD.2.4");se.addCommand(tp);se.addCommand(xp);se.addCommand(Mp);se.addCommand(Yp);se.addCommand(Gf);se.addCommand(hm);se.addCommand(vm);se.addCommand(km);se.addCommand(jm);se.addCommand(oh);se.addCommand(hy);se.addCommand(av);se.addCommand(ww);se.addCommand($y);E()||se.addCommand(Ef);var wu=process.argv.slice(2);wu.length>=2&&wu[wu.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var nO=new Set(["update","auth"]);se.hook("preAction",async(n,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==se;)t=t.parent;nO.has(t.name())||await A.checkVersion()});se.parseAsync(process.argv).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(tO(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
|
|
1420
|
+
-----END ENCRYPTED PRIVATE KEY-----`,h=mL({key:d,format:"pem",passphrase:r}),v=hL(h).export({type:"spki",format:"der"});if(t.some(G=>{let V=G.publicKey.export({type:"spki",format:"der"});return v.equals(V)}))return!0}catch{}}return!1}async function FL(n,e,t){let r=new Ue.EncryptedData({schema:n.content});try{let o=await r.decrypt({password:e});return Ue.SafeContents.fromBER(o).safeBags}catch(o){try{let i=Qw(r,t);if(i){let s=new ArrayBuffer(i.byteLength);return new Uint8Array(s).set(i),Ue.SafeContents.fromBER(s).safeBags}}catch{}f(`SafeContent decrypt failed: pkijs=${o instanceof Error?o.message:String(o)}`)}return[]}async function jL(n,e,t){if(n.contentType===xL)try{let r=n.content;if(typeof r.getValue=="function"){let o=r.getValue();return Ue.SafeContents.fromBER(o).safeBags}}catch(r){f(`data SafeContent parse error: ${r instanceof Error?r.message:String(r)}`)}else if(n.contentType===NL)return FL(n,e,t);return[]}async function HL(n,e,t,r){try{let o=Nn.readFileSync(n),i=LL(t),s=Ue.PFX.fromBER(o);await s.parseInternalValues({password:i,checkIntegrity:!0});let a=s.parsedValue?.authenticatedSafe;if(!a)return!1;let c=[];for(let l of a.safeContents){let d=await jL(l,i,t);c.push(...d)}return c.length===0?!1:ML(c,e,r)?!0:_L(c,e,r,t)}catch(o){let i=o instanceof Error?o.message:String(o);return f(`Failed to process P12 file: ${n}, error: ${i}`),!1}}function wu(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var iv="https://developer.huawei.com",$L={"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"},UL="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function BL(n){let e=$L[n];return e?`${iv}${e}`:void 0}function WL(){return`${iv}${UL}`}var GL={"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 ov(n,e){return(GL[n]??n).replace(/\{(\d+)\}/g,(r,o)=>String(e[Number(o)]??""))}function VL(n){return Array.from(n).join(", ")}function sv(n,e){if(n.size===0)return;let t=kn.getAclPermissionInfos(e),r=new Set;for(let h of t)n.has(h.permissionName)&&r.add(h);for(let h of r){let w=BL(h.permissionName);w!=null&&(h.permissionHelpUrlKey=w)}let o=new Set;for(let h of r)o.add(h.permissionDisplayName);let i=new Set;for(let h of r)if(h.permissionHelpUrlKey!=null){let w=h.permissionInsteadName??h.permissionDisplayName;i.add(`${w} (${h.permissionHelpUrlKey})`)}let s=WL(),a=ov("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=i.size>0?Array.from(i).join(", ")+".":"",d=ov("acl.permissions.warn",[VL(o),l,c]);console.log(d)}var lc=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=z.discover(process.cwd()),{passed:!0,message:""}}catch(t){return f(`[EnvCheck] Project.discover() failed: ${t.message}`),e(Z.PROJECT_DIR_MISSING)}}checkProduct(e,t){try{return this._project.validateProduct(e),{passed:!0,message:""}}catch(r){return f(`[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 f(`[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:Z.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import qL from"fs";import av from"path";var dc=class{constructor(e){this.toolProvider=e}toolProvider;checkJava(e){try{return this.toolProvider.assertJava(),{passed:!0,message:""}}catch(t){return f(`[EnvCheck] Java check failed: ${t.message}`),e(Z.JAVA_PLATFORM_UNSUPPORTED)}}checkHapSignTools(e){let t=this.toolProvider.sdkPath,r=b()?"hap-sign-tool":"hap-sign-tool.jar",o=av.join(t,"default","openharmony","toolchains","lib",r);if(!qL.existsSync(o)){let i=av.join("sdk","default","openharmony","toolchains","lib",r);return e(`${r} not found.Check whether ${i} exists.`)}return{passed:!0,message:""}}};var uc=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await De.getUserInfo()}catch(e){return f(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await De.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(Z.LOGIN_REQUIRED)}catch(t){return f(`[EnvCheck] Login check failed: ${t.message}`),e(Z.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(Z.TEAM_INFO_FAILED);try{if((await sn()).teamList.length>0)return{passed:!0,message:""}}catch(r){return f(`[EnvCheck] Team API error: ${r.message}`),e(Z.TEAM_INFO_FAILED)}return f("[EnvCheck] No teams found for current user"),e(Z.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(Z.REALNAME_REQUIRED):t.isRealName!==!0?(f("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(Z.REALNAME_REQUIRED)):{passed:!0,message:""}:e(Z.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let r=e??"";try{let o=await sn();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 f(`[EnvCheck] ${s}`),{passed:!1,message:s}}return{passed:!0,message:""}}catch(o){return f(`[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(Z.REGION_CHINA_ONLY):{passed:!0,message:""}:(f("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(Z.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function zL(n){try{let{teamList:e}=await sn();if(e.length>0)return e[0].id}catch(e){f(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function YL(n){let e=await De.getUserInfo(),t=await De.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await zL(e.userId);if(!r)throw new Error("No team found");let o={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await ac(o)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var pc=class{constructor(e){this.toolProvider=e}toolProvider;async checkDevice(e,t){try{let r=await YL(t);if(r.length>0)return f(`[EnvCheck] Scenario 4 Device check: ${r.length} device(s) found in AGC cloud, skipping local device check`),{passed:!0,message:""};f("[EnvCheck] Scenario 4 Device check: no cloud devices found, falling back to local hdc");let i=await re.from(this.toolProvider).listDevices();return i.length===0?(f("[EnvCheck] Scenario 4 Device check: no local devices found"),e(Z.DEVICE_MISSING)):i.some(a=>$n(a.serial))?{passed:!0,message:""}:(f("[EnvCheck] Scenario 4 Device check: local device found but not an emulator"),e(Z.DEVICE_MISSING))}catch(r){return f(`[EnvCheck] Scenario 4 Device check failed: ${r.message}`),e(Z.DEVICE_DETECT_FAILED)}}};var fc=class{projectChecker=new lc;toolchainChecker=null;authChecker=new uc;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 A.new();return this.toolchainChecker=new dc(e),this.deviceChecker=new pc(e),!0}catch(e){throw f(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(Z.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 f(`[EnvCheck] FAIL: ${e.message}`),new Error(e.message)}};function ZL(n){if(Su.existsSync(n)){let e=Su.readFileSync(n,"utf-8");return XL.parse(e)}return{app:{signingConfigs:[],products:[]}}}function QL(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function eO(n){if(n.keyPwd===n.storePassword){let r=await Tn.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await Tn.encryptedPassword(n.keyPwd,n.p12FilePath),t=await Tn.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function tO(n,e,t){let r=cv.join(n,"build-profile.json5"),o=ZL(r);QL(o);let i=t??"default",{keyPassword:s,storePassword:a}=await eO(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(h=>h.name===i);l!==void 0&&l>=0?o.app.signingConfigs[l]=c:o.app.signingConfigs.push(c);let d=o.app?.products?.findIndex(h=>h.name===i);d!==void 0&&d>=0?o.app.products[d].signingConfig=i:o.app.products.push({name:i,signingConfig:i}),Su.writeFileSync(r,JSON.stringify(o,null,2),"utf-8")}async function nO(n){let e=await De.getUserInfo(),t=await De.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 rO(n){let e=n.product||"default";await new fc().preflight({productName:e,teamId:n.teamId}),console.log("Executing signature generate command");let r=await nO(n),o=await A.new(),{shouldRegenerate:i}=await Di.shouldRegenerate({force:n.force??!1,teamId:r.teamId,productName:n.product},o);if(!i){console.log(vu("Signature generation completed successfully."));return}await oO(n,r,o),console.log(vu("Signature generation completed successfully."))}async function oO(n,e,t){let r=await su(e,n.product),o=iO(n,e,r,t);o.allDeviceIds=await qw(e,t.hdcPath),await nv(e,o);let i=z.discover(process.cwd()).rootDir;await tO(i,r,n.product??"default"),console.log(vu(`Signing config written to ${cv.join(i,"build-profile.json5")}`))}function iO(n,e,t,r){let o=process.cwd(),i=z.discover(o),s=ic(i,r);return sv(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 lv=new JL("signature").description("Generate application signature.");lv.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 rO(n)}catch(e){console.error(KL(e.message)),process.exit(1)}});var dv=lv;se.name("devecocli").description(`HarmonyOS application development command line tool
|
|
1421
|
+
|
|
1422
|
+
Privacy: ${ao.PRIVACY_URL}`).version("0.4.0-TD.3");se.addCommand(op);se.addCommand(Op);se.addCommand(jp);se.addCommand(Kp);se.addCommand(zf);se.addCommand(wm);se.addCommand(Em);se.addCommand(Lm);se.addCommand(Um);se.addCommand(ah);se.addCommand(wy);se.addCommand(dv);se.addCommand(bw);se.addCommand(Wy);b()||se.addCommand(Cf);var bu=process.argv.slice(2);bu.length>=2&&bu[bu.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var aO=new Set(["update","auth"]);se.hook("preAction",async(n,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==se;)t=t.parent;aO.has(t.name())||await A.checkVersion()});se.parseAsync(process.argv).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(sO(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
|