@deveco-test/hmos-deveco-cli 0.3.0-TD.1.3 → 0.3.0-TD.2-alpha2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +785 -654
  3. package/SKILL.md +172 -167
  4. package/dist/cli.js +116 -116
  5. package/dist/internal/doc-init-background.js +1 -1
  6. package/docs.zip +0 -0
  7. package/index.zip +0 -0
  8. package/package.json +102 -102
  9. package/scripts/install-better-sqlite3.mjs +51 -51
  10. package/scripts/install-jieba-wasm.mjs +47 -47
  11. package/scripts/lib/better-sqlite3-vendor.mjs +128 -128
  12. package/scripts/lib/cli-data-dir.mjs +44 -44
  13. package/scripts/lib/doc-init-log-path.mjs +15 -15
  14. package/scripts/lib/jieba-wasm-vendor.mjs +102 -102
  15. package/scripts/postinstall.mjs +54 -54
  16. package/src/resources/aclPermission/aclPermissionsInfo.json +310 -310
  17. package/templates/application/AppScope/app.json5 +10 -10
  18. package/templates/application/AppScope/resources/base/element/string.json +8 -8
  19. package/templates/application/AppScope/resources/base/media/layered_image.json +6 -6
  20. package/templates/application/build-profile.json5 +41 -41
  21. package/templates/application/code-linter.json5 +31 -31
  22. package/templates/application/entry/build-profile.json5 +32 -32
  23. package/templates/application/entry/gitignore.txt +5 -5
  24. package/templates/application/entry/hvigorfile.ts +7 -7
  25. package/templates/application/entry/obfuscation-rules.txt +19 -19
  26. package/templates/application/entry/oh-package.json5 +10 -10
  27. package/templates/application/entry/src/main/ets/entryability/EntryAbility.ets +62 -62
  28. package/templates/application/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets +30 -30
  29. package/templates/application/entry/src/main/ets/pages/Index.ets +37 -37
  30. package/templates/application/entry/src/main/module.json5 +49 -49
  31. package/templates/application/entry/src/main/resources/base/element/color.json +7 -7
  32. package/templates/application/entry/src/main/resources/base/element/float.json +8 -8
  33. package/templates/application/entry/src/main/resources/base/element/string.json +15 -15
  34. package/templates/application/entry/src/main/resources/base/media/layered_image.json +6 -6
  35. package/templates/application/entry/src/main/resources/base/profile/backup_config.json +2 -2
  36. package/templates/application/entry/src/main/resources/base/profile/main_pages.json +5 -5
  37. package/templates/application/entry/src/main/resources/dark/element/color.json +7 -7
  38. package/templates/application/gitignore.txt +11 -11
  39. package/templates/application/hvigor/hvigor-config.json5 +23 -23
  40. package/templates/application/hvigorfile.ts +7 -7
  41. package/templates/application/oh-package.json5 +10 -10
package/dist/cli.js CHANGED
@@ -1,77 +1,77 @@
1
1
  #!/usr/bin/env node
2
- var nv=Object.defineProperty;var rv=(n,e)=>{for(var t in e)nv(n,t,{get:e[t],enumerable:!0})};import{bootstrap as IL}from"global-agent";import{program as ie}from"commander";import{red as AL}from"colorette";import{Command as Zv}from"commander";import{green as Ac,red as Dc,yellow as Rc}from"colorette";import X from"fs";import*as H from"path";import Et from"json5";import*as dc from"fs";import*as le from"path";function m(n){process.env.DEVECO_CLI_DEBUG&&console.log(`[DEBUG] ${n}`)}var P=class n{static ASCII_CONTROL_MAX=31;static ASCII_DELETE=127;static parsePositiveInteger(e,t="value"){let r=e.trim();if(!/^\d+$/.test(r))throw new Error(`${t} must be a positive integer`);let 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(`
2
+ var rv=Object.defineProperty;var ov=(n,e)=>{for(var t in e)rv(n,t,{get:e[t],enumerable:!0})};import{bootstrap as AL}from"global-agent";import{program as ie}from"commander";import{red as DL}from"colorette";import{Command as Qv}from"commander";import{green as Dc,red as Rc,yellow as Tc}from"colorette";import X from"fs";import*as H from"path";import Ct from"json5";import*as uc from"fs";import*as we from"path";function m(n){process.env.DEVECO_CLI_DEBUG&&console.log(`[DEBUG] ${n}`)}var D=class n{static ASCII_CONTROL_MAX=31;static ASCII_DELETE=127;static parsePositiveInteger(e,t="value"){let r=e.trim();if(!/^\d+$/.test(r))throw new Error(`${t} must be a positive integer`);let o=Number.parseInt(r,10);if(!Number.isInteger(o)||o<=0)throw new Error(`${t} must be a positive integer`);return o}static getLastLines(e,t){return!t||t<=0?e:e.split(/\r?\n/).slice(-t).join(`
3
3
  `)}static parseDurationToSeconds(e,t="value"){let o=e.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)([sm])?$/);if(!o)throw new Error(`${t} must be like 30s, 5m or 2.5m (only s/m supported).`);let i=o[1];if((o[2]??"s")==="s")return n.parsePositiveInteger(i,t);if(!/^\d+(?:\.\d)?$/.test(i))throw new Error(`${t} supports a maximum of 1 decimal place for minutes (e.g. 2.5m).`);let a=Number.parseFloat(i);if(!Number.isFinite(a)||a<=0)throw new Error(`${t} must be a positive duration.`);return Math.round(a*60)}static 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(`
4
- `)}static resolveTimeBounds(e,t,r){let o=e?new Date(r.getTime()-e*1e3):null,i=t?new Date(r.getTime()-t*1e3):null;return o&&i?o<i?[o,i]:[i,o]:o?[o,r]:i?[null,i]:[null,null]}static isWithinBounds(e,t,r){let o=e.getTime(),i=t?Math.floor(t.getTime()/1e3)*1e3:null,s=r?Math.floor(r.getTime()/1e3)*1e3+999:null;return!(i!==null&&o<i||s!==null&&o>s)}static extractTimestampFromLogLine(e,t){let r=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!r)return null;let o=t.getFullYear(),i=Number.parseInt(r[1],10)-1,s=Number.parseInt(r[2],10),a=Number.parseInt(r[3],10),c=Number.parseInt(r[4],10),l=Number.parseInt(r[5],10),d=r[6]??"0",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 m(`quotePosixShellArg: ${e} -> ${r}`),r}static assertCrashFilename(e){if(!/^\w+-[\w.]+-\d+-\d+$/.test(e))throw new Error(`Invalid crash log filename: ${JSON.stringify(e)}`)}static assertHilogLevel(e){if(!/^[DIWEF]$/.test(e))throw new Error(`Invalid log level: ${e}`)}static resolvePathWithinRoot(e,t){if(le.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=le.resolve(le.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=le.normalize(e),o=le.relative(r,t);if(o.split(le.sep)[0]===".."||le.isAbsolute(o))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||le.isAbsolute(e)}static isPathContained(e,t){let r=le.resolve(t,e),o=le.relative(t,r);return n.isPathEscaping(o)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){if(le.isAbsolute(e))return{contained:!1,reason:`Absolute path is not allowed: ${e}`};let r=n.isPathContained(e,t);if(!r.contained)return r;let o;try{o=dc.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let i=le.resolve(o,e),s;try{s=dc.realpathSync(i)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${i}`}}return n.isPathContained(s,o)}};var G=class n{rootDir;profile;constructor(e,t){this.rootDir=e,this.profile=t}static discover(e){let t=e;for(;;){let r=n.tryLoadProjectProfile(t);if(r)return new n(t,r);let o=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(!X.existsSync(t))return null;try{let r=X.readFileSync(t,"utf-8"),o=Et.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=P.resolvePathWithinRoot(this.rootDir,t.srcPath),o=H.join(r,"src","main","module.json5");if(!X.existsSync(o))return"entry";try{let i=X.readFileSync(o,"utf-8");return Et.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=P.resolvePathWithinRoot(this.rootDir,t.srcPath),o=H.join(r,"build-profile.json5");if(!X.existsSync(o))throw new Error(`Build profile for module '${e}' not found at ${o}.`);let i=X.readFileSync(o,"utf-8");return Et.parse(i)}getBundleName(){let e=H.join(this.rootDir,"AppScope","app.json5");if(X.existsSync(e))try{let t=X.readFileSync(e,"utf-8"),r=Et.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(!X.existsSync(e))return!1;try{let t=X.readFileSync(e,"utf-8");return Et.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=P.resolvePathWithinRoot(this.rootDir,r.srcPath),i=H.join(o,"src","main","module.json5");if(!X.existsSync(i))return"EntryAbility";try{let s=X.readFileSync(i,"utf-8"),c=Et.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=P.resolvePathWithinRoot(this.rootDir,t.srcPath),o=H.join(r,"oh-package.json5");if(!X.existsSync(o))return[];let i=[];try{let s=X.readFileSync(o,"utf-8"),c=Et.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),S=P.resolvePathWithinRoot(this.rootDir,w),k=this.profile.modules.find(re=>H.resolve(this.rootDir,re.srcPath)===S);k&&i.push(k.name)}}catch{}return i}getModuleName(e){let t=this.profile.modules.find(i=>i.name===e);if(!t)return e;let r=P.resolvePathWithinRoot(this.rootDir,t.srcPath),o=H.join(r,"src","main","module.json5");if(!X.existsSync(o))return e;try{let i=X.readFileSync(o,"utf-8");return Et.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(!X.existsSync(a))throw new Error(`Build metadata not found for module '${e}' at ${a}. Build the project first.`);let c=this.parseOutputMetadata(a,s);return{moduleNode: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 S=this.getSignedHapName(c,i.srcPath,o,t);S&&(d=S)}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(!X.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(!X.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 X.existsSync(s)?i:null}buildOutputPath(e,t,r){let o=P.resolvePathWithinRoot(this.rootDir,e),i=H.resolve(o,"build",t,...r);return P.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=X.readFileSync(e,"utf-8"),o=Et.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{execFileSync as ku}from"child_process";import z from"fs";import*as we from"os";import*as v from"path";import bu from"fs";import*as Ai from"os";import*as Ii from"path";import sv from"regedit";import{execFileSync as ov}from"child_process";import yu from"fs";import*as wu from"os";import*as uc from"path";function Ci(n,e){let t=uc.join(n,"Contents","Info.plist");if(!yu.existsSync(t)){m(`[ToolProvider] Info.plist not found at: ${t}`);return}for(let[r,o]of[["/usr/libexec/PlistBuddy",["-c",`Print :${e}`,t]],["plutil",["-extract",e,"raw","-o","-",t]]])try{let i=ov(r,o,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(i&&!i.includes("Does Not Exist"))return i}catch{}}function iv(n){let e=Ci(n,"CFBundleShortVersionString");if(!e)return Ci(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[Ci(n,"CFBundleVersion"),Ci(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 Zr(n){if(wu.platform()==="darwin")return iv(n);let e=uc.join(n,"product-info.json");try{let t=JSON.parse(yu.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}function Qr(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 av(n){return n.filter(e=>{try{return bu.statSync(e).isDirectory()}catch{return!1}})}function cv(){let n=[];for(let e of[Ii.join(Ai.homedir(),"Applications"),"/Applications"])try{n.push(...bu.readdirSync(e).filter(t=>t.endsWith(".app")&&t.toLowerCase().includes("deveco")).map(t=>Ii.join(e,t)))}catch{}return n}function vu(n){return new Promise((e,t)=>sv.list(n,(r,o)=>r?t(r):e(o)))}async function Su(n,e,t){let o=((await vu([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(o.length===0)return[];let i=await vu(o);return o.flatMap(s=>{let a=i[s]?.values?.[t]?.value;return a?[a]:[]})}async function lv(){let n=[Ii.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 Su(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 Su(e,()=>!0,""))}catch{}return n}async function Eu(){let n=Ai.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"?cv():await lv(),t=av(e).flatMap(r=>{let o=Zr(r);return o?(m(`[ToolProvider] ${r} => version ${o}`),[{root:r,version:o}]):(m(`[ToolProvider] Skipping ${r}: could not read version`),[])});if(!t.length)throw new Error("DevEco Studio installation not found in default locations.");return t.reduce((r,o)=>Qr(o.version,r.version)>0?o:r)}import*as Pu from"fs";import*as Re from"path";function eo(n,e){let t=Re.relative(e,n);return t===""||!Re.isAbsolute(t)&&!t.startsWith(`..${Re.sep}`)&&t!==".."}function ht(n){let e=Re.resolve(n),t=[],r=e;for(;;)try{let o=Pu.realpathSync(r);return t.length===0?o:Re.join(o,...t.reverse())}catch(o){if(o.code!=="ENOENT")throw o;let i=Re.dirname(r);if(i===r)return e;t.push(Re.basename(r)),r=i}}function Di(n,e){let t=ht(e),r=ht(n);return eo(r,t)?r:null}function Ri(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function Ti(n){let e=Ri(n);if(!e)throw new Error("Path must not be empty.");return ht(e)}var to={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},ki={USER_AGENT:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",ACCEPT_LANGUAGE:"zh-CN"};var Ce={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"},rt={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"},An={ALGORITHM:"aes-256-gcm",KEY_LENGTH:32,IV_LENGTH:12,KEK_VERSIONS:["kek-v1","kek-v2","kek-v3"]},no={baseUrl:rt.LOGIN_URL,authUrl:rt.AUTH_APPLY_PATH,tempTokenCheckUrl:rt.TEMP_TOKEN_CHECK_PATH,jwtTokenCheckUrl:rt.JWT_TOKEN_CHECK_PATH,successRedirectUrl:rt.LOGIN_SUCCESS_PATH,failedRedirectUrl:rt.LOGIN_FAILED_PATH,logoutUrl:rt.LOGOUT_PATH,agcTeamListUrl:rt.AGC_TEAM_LIST_URL,appId:Ce.APP_ID,timeout:to.LOGIN_TIMEOUT_MS,countryCode:"CN"};import{homedir as zt}from"os";import Pt from"path";import{xdgConfig as dv}from"xdg-basedir";var de={"trae-cn":Pt.join(zt(),".trae-cn"),opencode:Pt.join(dv,"opencode"),cursor:Pt.join(zt(),".cursor"),codebuddy:Pt.join(zt(),".codebuddy"),qoder:Pt.join(zt(),".qoder"),"claude-code":Pt.join(zt(),".claude"),codex:Pt.join(zt(),".codex"),bitfun:Pt.join(zt(),".bitfun"),opendesk:Pt.join(zt(),".opendesk")};import qt from"path";import*as Cu from"os";function b(){return pc()==="openharmony"}function pc(){return Cu.platform()}var fc="https://matrix.openharmony.cn",ot={TAGS_API_URL:`${fc}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${fc}/api/registry/skill/skills`,SKILL_API_BASE:`${fc}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},Iu={"trae-cn":{path:qt.join(de["trae-cn"],"skills"),displayName:"trae-cn"},opencode:{path:qt.join(de.opencode,"skills"),displayName:"opencode"},cursor:{path:qt.join(de.cursor,"skills"),displayName:"cursor"},codebuddy:{path:qt.join(de.codebuddy,"skills"),displayName:"codebuddy"},qoder:{path:qt.join(de.qoder,"skills"),displayName:"qoder"},"claude-code":{path:qt.join(de["claude-code"],"skills"),projectPath:".claude/skills",displayName:"claude-code"},codex:{path:qt.join(de.codex,"skills"),displayName:"codex"}},Au={opencode:{path:qt.join(de.opencode,"skills"),displayName:"opencode"}};function Ct(){return b()?Au:Iu}import{homedir as ro}from"os";import je from"path";var gt="deveco-mcp";var Vt={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:je.join(de.opencode,"opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:je.join(process.platform==="win32"?je.join(process.env.APPDATA??je.join(ro(),"AppData","Roaming"),"Trae CN","User"):je.join(ro(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:je.join(de.cursor,"mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:je.join(de.codebuddy,"mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:je.join(process.platform==="win32"?je.join(process.env.APPDATA??je.join(ro(),"AppData","Roaming"),"Qoder","SharedClientCache"):je.join(ro(),"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:je.join(ro(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:je.join(de.codex,"config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function Ru(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function Du(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function Tu(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function xi(n,e){return n.format==="opencode"?Ru(e):n.format==="claude-code"||n.format==="codex"?Du(e):Tu(e)}var it={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var mc="https://developer.huawei.com/consumer/cn/download/";var uv=/^#\s*Version:\s*(\S+)/,pv="26.0.0.810",fv=["sdk","default","openharmony","native","llvm","bin","clangd"];function mv(n){try{let e=JSON.parse(z.readFileSync(n,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch{return}}function hv(n){let e=v.join(n,"default","openharmony");return[v.join(n,"default","sdk-pkg.json"),...["toolchains","native","previewer"].map(t=>v.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 verifiedPaths=new Set;static powerShellPath;static powerShellModulesPath;static installSourcePromise;get sourceType(){return this._sourceType}get toolchainRoot(){return this._toolchainRoot}get devecoStudioPath(){return this._devecoStudioPath}get nodePath(){return this.verify(this._nodePath)}get ohpmJsPath(){return this._ohpmJsPath}get hvigorJsPath(){return this._hvigorJsPath}get codelinterPath(){return n.resolveCodelinterPath(this._toolchainRoot,this._sourceType)}get javaPath(){return this._javaPath?this.verify(this._javaPath):""}get sdkPath(){return this._sdkPath}get hdcPath(){return this.verify(this._hdcPath)}get emulatorPath(){return this.verify(this._emulatorPath)}get emulatorLauncherPath(){return this.emulatorPath}get clangdPath(){return this.verify(this._clangdPath)}get lspServerPath(){return this.verify(this._lspServerPath)}verify(e){return e&&(n.verifiedPaths.has(e)||(n.verifySignature(e),n.verifiedPaths.add(e)),e)}assertJava(){if(!b()){if(this._sourceType==="clt"&&!this._javaPath&&(this._javaPath=n.resolveCltJava(!0)),!this._javaPath)throw new Error("Java runtime is required to run hvigor. Set JAVA_HOME or add Java to PATH.");this.verify(this._javaPath)}}assertEmulator(){this.verify(this._emulatorPath)}assertStudio(){if(this._sourceType==="clt")throw new Error("This operation requires DevEco Studio. Set DEVECO_CLI_STUDIO_PATH to a DevEco Studio installation.")}assertLsp(){this.assertStudio()}static compareVersion(e,t){return Qr(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 fromOpenHarmony(){let e=process.env.COMMAND_LINE_TOOL_PATH;if(!e)throw new Error("COMMAND_LINE_TOOL_PATH environment variable is not set.");let t=n.buildOpenHarmonyToolPaths(e);n.assertBuiltPathsInsideRoot(e,t,!1);let r=v.join(e,"clangd","clangd"),o=v.join(e,"ace-server","out","index.js");return new n("clt",e,void 0,t.nodePath,t.ohpmJsPath,t.hvigorJsPath,"",t.sdkPath,t.hdcPath,t.emulatorPath,r,o)}static buildOpenHarmonyToolPaths(e){let t=v.join(e,"sdk");return{nodePath:v.join(e,"node","bin","node"),ohpmJsPath:v.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:v.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:t,hdcPath:v.join(t,"default","openharmony","toolchains","hdc"),emulatorPath:""}}static devecoContentRootForClangd(e){return we.platform()==="darwin"&&e.endsWith(".app")?v.join(e,"Contents"):e}static clangdCandidatesFromDevecoHome(e){let t=new Set,r=[e,n.devecoContentRootForClangd(e)];for(let o of r){let i=v.join(o,...fv);t.add(we.platform()==="win32"?i+".exe":i)}return[...t]}static resolveClangdPath(e){let t=n.clangdCandidatesFromDevecoHome(e);for(let r of t)if(z.existsSync(r))return r;return""}static resolveLspServerPath(e){let t=we.platform(),r;if(t==="win32")r=v.join(e,"plugins","openharmony");else if(t==="darwin")r=v.join(e,"Contents","plugins","openharmony");else return"";let o=v.join(r,"ace-server","out","index.js");return z.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(Zr(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(Qr(e,o)<0)throw new Error(`The detected ${t} version is ${e}, which is below the minimum required version ${o}. Upgrade before using deveco-cli:
5
- ${mc}`)}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}
4
+ `)}static resolveTimeBounds(e,t,r){let o=e?new Date(r.getTime()-e*1e3):null,i=t?new Date(r.getTime()-t*1e3):null;return o&&i?o<i?[o,i]:[i,o]:o?[o,r]:i?[null,i]:[null,null]}static isWithinBounds(e,t,r){let o=e.getTime(),i=t?Math.floor(t.getTime()/1e3)*1e3:null,s=r?Math.floor(r.getTime()/1e3)*1e3+999:null;return!(i!==null&&o<i||s!==null&&o>s)}static extractTimestampFromLogLine(e,t){let r=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!r)return null;let o=t.getFullYear(),i=Number.parseInt(r[1],10)-1,s=Number.parseInt(r[2],10),a=Number.parseInt(r[3],10),c=Number.parseInt(r[4],10),l=Number.parseInt(r[5],10),d=r[6]??"0",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 m(`quotePosixShellArg: ${e} -> ${r}`),r}static assertCrashFilename(e){if(!/^\w+-[\w.]+-\d+-\d+$/.test(e))throw new Error(`Invalid crash log filename: ${JSON.stringify(e)}`)}static assertHilogLevel(e){if(!/^[DIWEF]$/.test(e))throw new Error(`Invalid log level: ${e}`)}static resolvePathWithinRoot(e,t){if(we.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=we.resolve(we.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=we.normalize(e),o=we.relative(r,t);if(o.split(we.sep)[0]===".."||we.isAbsolute(o))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||we.isAbsolute(e)}static isPathContained(e,t){let r=we.resolve(t,e),o=we.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=uc.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let i=we.resolve(o,e),s;try{s=uc.realpathSync(i)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${i}`}}return n.isPathContained(s,o)}};var G=class n{rootDir;profile;constructor(e,t){this.rootDir=e,this.profile=t}static discover(e){let t=e;for(;;){let r=n.tryLoadProjectProfile(t);if(r)return new n(t,r);let o=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(!X.existsSync(t))return null;try{let r=X.readFileSync(t,"utf-8"),o=Ct.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=D.resolvePathWithinRoot(this.rootDir,t.srcPath),o=H.join(r,"src","main","module.json5");if(!X.existsSync(o))return"entry";try{let i=X.readFileSync(o,"utf-8");return Ct.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=D.resolvePathWithinRoot(this.rootDir,t.srcPath),o=H.join(r,"build-profile.json5");if(!X.existsSync(o))throw new Error(`Build profile for module '${e}' not found at ${o}.`);let i=X.readFileSync(o,"utf-8");return Ct.parse(i)}getBundleName(){let e=H.join(this.rootDir,"AppScope","app.json5");if(X.existsSync(e))try{let t=X.readFileSync(e,"utf-8"),r=Ct.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(!X.existsSync(e))return!1;try{let t=X.readFileSync(e,"utf-8");return Ct.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=D.resolvePathWithinRoot(this.rootDir,r.srcPath),i=H.join(o,"src","main","module.json5");if(!X.existsSync(i))return"EntryAbility";try{let s=X.readFileSync(i,"utf-8"),c=Ct.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=D.resolvePathWithinRoot(this.rootDir,t.srcPath),o=H.join(r,"oh-package.json5");if(!X.existsSync(o))return[];let i=[];try{let s=X.readFileSync(o,"utf-8"),c=Ct.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),S=D.resolvePathWithinRoot(this.rootDir,w),k=this.profile.modules.find(re=>H.resolve(this.rootDir,re.srcPath)===S);k&&i.push(k.name)}}catch{}return i}getModuleName(e){let t=this.profile.modules.find(i=>i.name===e);if(!t)return e;let r=D.resolvePathWithinRoot(this.rootDir,t.srcPath),o=H.join(r,"src","main","module.json5");if(!X.existsSync(o))return e;try{let i=X.readFileSync(o,"utf-8");return Ct.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(!X.existsSync(a))throw new Error(`Build metadata not found for module '${e}' at ${a}. Build the project first.`);let c=this.parseOutputMetadata(a,s);return{moduleNode: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 S=this.getSignedHapName(c,i.srcPath,o,t);S&&(d=S)}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(!X.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(!X.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 X.existsSync(s)?i:null}buildOutputPath(e,t,r){let o=D.resolvePathWithinRoot(this.rootDir,e),i=H.resolve(o,"build",t,...r);return D.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=X.readFileSync(e,"utf-8"),o=Ct.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{execFileSync as xu}from"child_process";import z from"fs";import*as ve from"os";import*as v from"path";import Eu from"fs";import*as Ri from"os";import*as Di from"path";import av from"regedit";import{execFileSync as iv}from"child_process";import wu from"fs";import*as vu from"os";import*as pc from"path";function Ai(n,e){let t=pc.join(n,"Contents","Info.plist");if(!wu.existsSync(t)){m(`[ToolProvider] Info.plist not found at: ${t}`);return}for(let[r,o]of[["/usr/libexec/PlistBuddy",["-c",`Print :${e}`,t]],["plutil",["-extract",e,"raw","-o","-",t]]])try{let i=iv(r,o,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(i&&!i.includes("Does Not Exist"))return i}catch{}}function sv(n){let e=Ai(n,"CFBundleShortVersionString");if(!e)return Ai(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[Ai(n,"CFBundleVersion"),Ai(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 to(n){if(vu.platform()==="darwin")return sv(n);let e=pc.join(n,"product-info.json");try{let t=JSON.parse(wu.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}function no(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 cv(n){return n.filter(e=>{try{return Eu.statSync(e).isDirectory()}catch{return!1}})}function lv(){let n=[];for(let e of[Di.join(Ri.homedir(),"Applications"),"/Applications"])try{n.push(...Eu.readdirSync(e).filter(t=>t.endsWith(".app")&&t.toLowerCase().includes("deveco")).map(t=>Di.join(e,t)))}catch{}return n}function Su(n){return new Promise((e,t)=>av.list(n,(r,o)=>r?t(r):e(o)))}async function bu(n,e,t){let o=((await Su([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(o.length===0)return[];let i=await Su(o);return o.flatMap(s=>{let a=i[s]?.values?.[t]?.value;return a?[a]:[]})}async function dv(){let n=[Di.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 bu(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 bu(e,()=>!0,""))}catch{}return n}async function Pu(){let n=Ri.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"?lv():await dv(),t=cv(e).flatMap(r=>{let o=to(r);return o?(m(`[ToolProvider] ${r} => version ${o}`),[{root:r,version:o}]):(m(`[ToolProvider] Skipping ${r}: could not read version`),[])});if(!t.length)throw new Error("DevEco Studio installation not found in default locations.");return t.reduce((r,o)=>no(o.version,r.version)>0?o:r)}import*as Cu from"fs";import*as Te from"path";function ro(n,e){let t=Te.relative(e,n);return t===""||!Te.isAbsolute(t)&&!t.startsWith(`..${Te.sep}`)&&t!==".."}function gt(n){let e=Te.resolve(n),t=[],r=e;for(;;)try{let o=Cu.realpathSync(r);return t.length===0?o:Te.join(o,...t.reverse())}catch(o){if(o.code!=="ENOENT")throw o;let i=Te.dirname(r);if(i===r)return e;t.push(Te.basename(r)),r=i}}function Ti(n,e){let t=gt(e),r=gt(n);return ro(r,t)?r:null}function ki(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function xi(n){let e=ki(n);if(!e)throw new Error("Path must not be empty.");return gt(e)}var oo={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},Ni={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 Ce={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"},rt={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"},Rn={ALGORITHM:"aes-256-gcm",KEY_LENGTH:32,IV_LENGTH:12,KEK_VERSIONS:["kek-v1","kek-v2","kek-v3"]},io={baseUrl:rt.LOGIN_URL,authUrl:rt.AUTH_APPLY_PATH,tempTokenCheckUrl:rt.TEMP_TOKEN_CHECK_PATH,jwtTokenCheckUrl:rt.JWT_TOKEN_CHECK_PATH,successRedirectUrl:rt.LOGIN_SUCCESS_PATH,failedRedirectUrl:rt.LOGIN_FAILED_PATH,logoutUrl:rt.LOGOUT_PATH,agcTeamListUrl:rt.AGC_TEAM_LIST_URL,appId:Ce.APP_ID,timeout:oo.LOGIN_TIMEOUT_MS,countryCode:"CN"};import{homedir as Jt}from"os";import It from"path";import{xdgConfig as uv}from"xdg-basedir";var ue={"trae-cn":It.join(Jt(),".trae-cn"),opencode:It.join(uv,"opencode"),cursor:It.join(Jt(),".cursor"),codebuddy:It.join(Jt(),".codebuddy"),qoder:It.join(Jt(),".qoder"),"claude-code":It.join(Jt(),".claude"),codex:It.join(Jt(),".codex"),bitfun:It.join(Jt(),".bitfun"),opendesk:It.join(Jt(),".opendesk")};import Yt from"path";import*as Iu from"os";function b(){return fc().toLowerCase().includes("openharmony")}function fc(){return Iu.platform()}var mc="https://matrix.openharmony.cn",ot={TAGS_API_URL:`${mc}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${mc}/api/registry/skill/skills`,SKILL_API_BASE:`${mc}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},Au={"trae-cn":{path:Yt.join(ue["trae-cn"],"skills"),displayName:"trae-cn"},opencode:{path:Yt.join(ue.opencode,"skills"),displayName:"opencode"},cursor:{path:Yt.join(ue.cursor,"skills"),displayName:"cursor"},codebuddy:{path:Yt.join(ue.codebuddy,"skills"),displayName:"codebuddy"},qoder:{path:Yt.join(ue.qoder,"skills"),displayName:"qoder"},"claude-code":{path:Yt.join(ue["claude-code"],"skills"),projectPath:".claude/skills",displayName:"claude-code"},codex:{path:Yt.join(ue.codex,"skills"),displayName:"codex"}},Du={opencode:{path:Yt.join(ue.opencode,"skills"),displayName:"opencode"}};function At(){return b()?Du:Au}import{homedir as so}from"os";import $e from"path";var yt="deveco-mcp";var Kt={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:$e.join(ue.opencode,"opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:$e.join(process.platform==="win32"?$e.join(process.env.APPDATA??$e.join(so(),"AppData","Roaming"),"Trae CN","User"):$e.join(so(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:$e.join(ue.cursor,"mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:$e.join(ue.codebuddy,"mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:$e.join(process.platform==="win32"?$e.join(process.env.APPDATA??$e.join(so(),"AppData","Roaming"),"Qoder","SharedClientCache"):$e.join(so(),"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:$e.join(so(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:$e.join(ue.codex,"config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function Tu(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function Ru(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function ku(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function Li(n,e){return n.format==="opencode"?Tu(e):n.format==="claude-code"||n.format==="codex"?Ru(e):ku(e)}var it={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var hc="https://developer.huawei.com/consumer/cn/download/";var pv=/^#\s*Version:\s*(\S+)/,fv="26.0.0.810",mv=["sdk","default","openharmony","native","llvm","bin","clangd"];function hv(n){try{let e=JSON.parse(z.readFileSync(n,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch{return}}function gv(n){let e=v.join(n,"default","openharmony");return[v.join(n,"default","sdk-pkg.json"),...["toolchains","native","previewer"].map(t=>v.join(e,t,"oh-uni-package.json"))]}var I=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 verifiedPaths=new Set;static powerShellPath;static powerShellModulesPath;static installSourcePromise;get sourceType(){return this._sourceType}get toolchainRoot(){return this._toolchainRoot}get devecoStudioPath(){return this._devecoStudioPath}get nodePath(){return this.verify(this._nodePath)}get ohpmJsPath(){return this._ohpmJsPath}get hvigorJsPath(){return this._hvigorJsPath}get codelinterPath(){return n.resolveCodelinterPath(this._toolchainRoot,this._sourceType)}get javaPath(){return this._javaPath?this.verify(this._javaPath):""}get sdkPath(){return this._sdkPath}get hdcPath(){return this.verify(this._hdcPath)}get emulatorPath(){return this.verify(this._emulatorPath)}get emulatorLauncherPath(){return this.emulatorPath}get clangdPath(){return this.verify(this._clangdPath)}get lspServerPath(){return this.verify(this._lspServerPath)}verify(e){return e&&(n.verifiedPaths.has(e)||(n.verifySignature(e),n.verifiedPaths.add(e)),e)}assertJava(){if(!b()){if(this._sourceType==="clt"&&!this._javaPath&&(this._javaPath=n.resolveCltJava(!0)),!this._javaPath)throw new Error("Java runtime is required to run hvigor. Set JAVA_HOME or add Java to PATH.");this.verify(this._javaPath)}}assertEmulator(){this.verify(this._emulatorPath)}assertStudio(){if(this._sourceType==="clt")throw new Error("This operation requires DevEco Studio. Set DEVECO_CLI_STUDIO_PATH to a DevEco Studio installation.")}assertLsp(){this.assertStudio()}static compareVersion(e,t){return no(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 fromOpenHarmony(){let e=process.env.COMMAND_LINE_TOOL_PATH;if(!e)throw new Error("COMMAND_LINE_TOOL_PATH environment variable is not set.");let t=n.buildOpenHarmonyToolPaths(e);n.assertBuiltPathsInsideRoot(e,t,!1);let r=v.join(e,"clangd","clangd"),o=v.join(e,"ace-server","out","index.js");return new n("clt",e,void 0,t.nodePath,t.ohpmJsPath,t.hvigorJsPath,"",t.sdkPath,t.hdcPath,t.emulatorPath,r,o)}static buildOpenHarmonyToolPaths(e){let t=v.join(e,"sdk");return{nodePath:v.join(e,"node","bin","node"),ohpmJsPath:v.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:v.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:t,hdcPath:v.join(t,"default","openharmony","toolchains","hdc"),emulatorPath:""}}static devecoContentRootForClangd(e){return ve.platform()==="darwin"&&e.endsWith(".app")?v.join(e,"Contents"):e}static clangdCandidatesFromDevecoHome(e){let t=new Set,r=[e,n.devecoContentRootForClangd(e)];for(let o of r){let i=v.join(o,...mv);t.add(ve.platform()==="win32"?i+".exe":i)}return[...t]}static resolveClangdPath(e){let t=n.clangdCandidatesFromDevecoHome(e);for(let r of t)if(z.existsSync(r))return r;return""}static resolveLspServerPath(e){let t=ve.platform(),r;if(t==="win32")r=v.join(e,"plugins","openharmony");else if(t==="darwin")r=v.join(e,"Contents","plugins","openharmony");else return"";let o=v.join(r,"ace-server","out","index.js");return z.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(to(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(no(e,o)<0)throw new Error(`The detected ${t} version is ${e}, which is below the minimum required version ${o}. Upgrade before using deveco-cli:
5
+ ${hc}`)}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}
6
6
  Searched paths:
7
7
  ${r.join(`
8
- `)}`)}let i=ht(e),s=ht(o);return n.assertInsideRoot(s,i,"codelinter"),s}static getCodelinterCandidates(e,t){if(t==="studio"){let r=we.platform()==="darwin"?["Contents"]:[];return[v.join(e,...r,"plugins","codelinter","run","index.js"),v.join(e,...r,"plugins","codelinter","index.js"),v.join(e,...r,"tools","codelinter","bin","codelinter.js"),v.join(e,...r,"tools","codelinter","codelinter.js")]}return[v.join(e,"codelinter","index.js"),v.join(e,"codelinter","run","index.js"),v.join(e,"tool","codelinter","bin","codelinter.js"),v.join(e,"tool","codelinter","codelinter.js")]}static isValidRoot(e,t){if(!n.isDirectory(e))return!1;if(t==="clt")return z.existsSync(v.join(e,"version.txt"));let r=we.platform()==="darwin"?v.join(e,"Contents"):e,o=we.platform()==="darwin"?v.join(r,"Info.plist"):v.join(r,"product-info.json");if(!z.existsSync(o))return!1;let i=n.buildToolPaths(e,"studio");return[i.nodePath,i.ohpmJsPath,i.hvigorJsPath].every(z.existsSync)}static buildToolPaths(e,t){return t==="clt"?n.buildCltToolPaths(e):n.buildStudioToolPaths(e)}static buildCltToolPaths(e){let t=v.join(e,"sdk"),r=we.platform()==="win32",o=r?".exe":"";return{nodePath:r?v.join(e,"tool","node","node.exe"):v.join(e,"tool","node","bin","node"),ohpmJsPath:v.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:v.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:t,hdcPath:v.join(t,"default","openharmony","toolchains",`hdc${o}`),emulatorPath:v.join(e,"emulator",r?"Emulator.exe":"Emulator")}}static buildStudioToolPaths(e){let t=we.platform()==="darwin",r=we.platform()==="win32",o=t?v.join(e,"Contents"):e,i=v.join(o,"tools"),s=v.join(o,"sdk"),a=r?".exe":"";return{nodePath:r?v.join(i,"node","node.exe"):v.join(i,"node","bin","node"),ohpmJsPath:v.join(i,"ohpm","bin","pm-cli.js"),hvigorJsPath:v.join(i,"hvigor","bin","hvigorw.js"),javaPath:r?v.join(e,"jbr","bin","java.exe"):t?v.join(o,"jbr","Contents","Home","bin","java"):v.join(o,"jbr","bin","java"),sdkPath:s,hdcPath:v.join(s,"default","openharmony","toolchains",`hdc${a}`),emulatorPath:v.join(i,"emulator",r?"Emulator.exe":"Emulator")}}static isFile(e){try{return z.statSync(e).isFile()}catch{return!1}}static isDirectory(e){try{return z.existsSync(e)&&z.statSync(e).isDirectory()}catch{return!1}}static resolveInstallSource(){return n.installSourcePromise||(n.installSourcePromise=n.resolveInstallSourceUncached()),n.installSourcePromise}static async resolveInstallSourceUncached(){let e=[["DEVECO_CLI_STUDIO_PATH","studio","studio"],["DEVECO_CLI_CLT_PATH","clt","clt"],["DEVECO_HOME","studio","studio"],["DEVECO_PATH","studio","studio"]];for(let[r,o,i]of e){let s=process.env[r]?.trim();if(s){let a=n.resolveExplicitRoot(s,o,r);return m(`[ToolProvider] Using ${r} \u2192 ${a}`),{sourceType:i,toolchainRoot:a}}}let t=await Eu();return m(`[ToolProvider] Using auto \u2192 ${t.root} (${t.version})`),{sourceType:"studio",toolchainRoot:t.root}}static resolveExplicitRoot(e,t,r){let o;try{o=Ti(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=ht(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(Di(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=`${v.sep}Contents`,r=v.normalize(e);return r.endsWith(t)?r.slice(0,-t.length):r}static readCltVersion(e){try{return z.readFileSync(v.join(e,"version.txt"),"utf-8").split(/\r?\n/).map(t=>t.match(uv)?.[1]?.trim()).find(Boolean)}catch{return}}static resolveCltJava(e){let t=process.env.JAVA_HOME?.trim(),r=t&&(n.javaIn(v.join(t,"bin"))??n.javaIn(t)),o=(process.env.Path??process.env.PATH??"").split(v.delimiter).map(s=>n.javaIn(s.trim())).find(Boolean),i=r??o;if(i)return z.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=>v.join(e,r)).find(z.existsSync)}getMaxApiLevel(){for(let e of hv(this.sdkPath)){let t=mv(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=v.join(this._devecoStudioPath,t,"plugins","harmony","arkanalyzer-apiscan"),o=v.join(r,"resources","apiChange"),i=v.join(r,"api-change-scan.js");if(!z.existsSync(o)||!z.existsSync(i)){let s=Zr(this._toolchainRoot)??"unknown";throw new Error(`A required component is missing. The detected DevEco Studio version is ${s}. The minimum required version is ${pv}. Upgrade before using 'check compat' at ${mc}`)}return this._apiscanPaths={apiChangeDir:o,scriptPath:i},this._apiscanPaths}static verifySignature(e){if(!z.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=we.platform();if(t==="linux"){n.assertExecutable(e);return}if(t==="win32"&&v.extname(e).toLowerCase()===".exe"){n.assertSigned(n.verifyWindowsSignature(e),e);return}t==="darwin"&&(n.assertExecutable(e),n.assertSigned(n.verifyMacSignature(e),e))}static assertExecutable(e){try{if(!z.statSync(e).isFile())throw new Error;z.accessSync(e,z.constants.X_OK)}catch{throw new Error(`executable is not accessible: ${e}`)}}static assertSigned(e,t){if(!e.signed)throw new Error(`The executable is not digitally signed: ${t}`)}static findPowerShellPath(){if(n.powerShellPath!==void 0)return n.powerShellPath;let e=v.join(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return n.powerShellPath=z.existsSync(e)?e:"",n.powerShellPath&&(n.powerShellModulesPath=v.join(v.dirname(n.powerShellPath),"Modules")),n.powerShellPath}static verifyWindowsSignature(e){let t=n.findPowerShellPath();if(!t)throw new Error("The PowerShell application was not found");let r=z.mkdtempSync(v.join(we.tmpdir(),"deveco-verify-")),o=v.join(r,"Verify-Signature.ps1");z.writeFileSync(o,"Get-AuthenticodeSignature -FilePath $args[0] | ConvertTo-Json -Depth 3 -Compress","utf8");try{let i=ku(t,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",o,e],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"],env:{...process.env,PSModulePath:n.powerShellModulesPath}}),s=JSON.parse(i);return{signed:Number(s.Status)===0}}catch(i){return m(`[ToolProvider] verify Windows Signature, error msg: ${i}`),{signed:!1}}finally{z.rmSync(r,{recursive:!0,force:!0})}}static verifyMacSignature(e){try{return ku("codesign",["-v",e],{encoding:"utf8",timeout:5e3,stdio:["ignore","ignore","ignore"]}),{signed:!0}}catch{return{signed:!1}}}};import{execa as gv}from"execa";import*as It from"path";import*as Ni from"fs";import*as hc from"os";var Te=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=It.dirname(e.javaPath);o.PATH=`${i}${It.delimiter}${process.env.PATH||""}`,e.sourceType==="clt"&&(o.JAVA_HOME=It.dirname(i))}b()&&(o.HVIGOR_USER_HOME=It.join(hc.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()){m("[HvigorAdapter] Daemon already running.");return}m("[HvigorAdapter] No daemon running, starting via --sync --daemon (no hap build)."),await this.runHvigor(["--sync","--daemon"])}isDaemonRunning(e){return this.findProjectDaemon(e)!==null}findProjectDaemon(e){let t=this.getDaemonRegistryPath();if(!Ni.existsSync(t))return null;try{let r=Ni.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||It.join(hc.homedir(),".hvigor");return It.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];m(`Executing: ${t} ${r.join(" ")}`);let o=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit";await gv(t,r,{cwd:this.projectRoot,env:this.env,stdout:o,stderr:o})}};import{execa as yv}from"execa";var Jt=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"];m(`Executing: ${e} ${t.join(" ")}`),await yv(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"})}};import{mkdir as wv}from"fs/promises";import{dirname as vv,resolve as Sv}from"path";import{execa as bv}from"execa";import{lock as gc,check as cM}from"proper-lockfile";function yc(n){return Sv(n,".hvigor",".build-lock")}function Ev(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function xu(n){let e=vv(yc(n));if(await wv(e,{recursive:!0}),process.platform==="win32")try{await bv("attrib",["+h",e])}catch{}}async function Pv(n,e){let t=new AbortController,r=Ev(e);await xu(n);let o={lockfilePath:yc(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await gc(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 gc(n,{...o,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function At(n,e,t){let{release:r,signal:o}=await Pv(n,t);try{return await e(o)}finally{await r()}}async function Li(n,e){let t=new AbortController;await xu(n);let r={lockfilePath:yc(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},o;try{o=await gc(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 Yt from"fs";import*as Dn from"path";import Cv from"json5";var Iv=1e3;function Mi(n){m(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=Dn.join(n,it.SYNC_OUTPUT_PATH);if(!Yt.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return m(`[ProjectCheck] ${l.reason}`),l}let t=Yt.statSync(e).mtimeMs;m(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=Av(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return m(`[ProjectCheck] ${l.reason}`),l}let o=Dn.join(n,it.OH_PACKAGE_JSON5),i=Oi(o,t,"root");if(i.required)return m(`[ProjectCheck] Root check: ${i.reason}`),i;let s=Dn.join(n,it.BUILD_PROFILE_JSON5),a=Oi(s,t,"build-profile");if(a.required)return m(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let d=Dn.join(n,l.srcPath,it.OH_PACKAGE_JSON5),h=Oi(d,t,l.name);if(h.required)return m(`[ProjectCheck] Module '${l.name}' check: ${h.reason}`),h;let w=Dn.join(n,l.srcPath,it.BUILD_PROFILE_JSON5),S=Oi(w,t,l.name);if(S.required)return m(`[ProjectCheck] Module '${l.name}' build-profile check: ${S.reason}`),S}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return m(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function Oi(n,e,t){if(!Yt.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=Yt.statSync(n).mtimeMs;return r-e>Iv?{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 Av(n){let e=Dn.join(n,it.BUILD_PROFILE_JSON5);try{let t=Yt.readFileSync(e,"utf-8");if(!t.trim())return null;let r=Cv.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 $e from"fs";import*as Xt from"path";import*as $u from"util";import*as M from"fs";import*as Ui from"path";import ee from"fs";import*as _i from"os";import*as q from"path";import Dv from"json5";var Nu=3;function Fi(n){if(!ee.existsSync(n)||!ee.statSync(n).isDirectory())return!1;let e=ee.existsSync(q.join(n,"build-profile.json5")),t=ee.existsSync(q.join(n,"hvigorfile.js"))||ee.existsSync(q.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=ee.readFileSync(q.join(n,"build-profile.json5"),"utf-8");return Dv.parse(r).app!==void 0}catch{return!1}}function wc(n,e,t){if(e>=t)return null;let r=Rv(n),o=Tv(r);if(o)return o;for(let i of r){let s=wc(i,e+1,t);if(s)return s}return null}function Rv(n){try{let e=ee.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(q.join(n,r.name));return t}catch{return[]}}function Tv(n){for(let e of n)if(Fi(e))return e;return null}function Dt(n){if(!n||n.trim()==="")return null;let e=q.resolve(n),t;try{t=ee.realpathSync(e)}catch{t=e}if(!ee.existsSync(t))return null;if(Fi(t))return t;let r=t;for(let o=1;o<=3;o++){let i=q.dirname(r);if(i===r)break;if(Fi(i))return i;r=i}if(ee.statSync(t).isDirectory()){let o=wc(t,0,Nu);if(o)return o}return null}function ji(n){if(!n||n.trim()==="")return null;let e=q.resolve(n),t;try{t=ee.realpathSync(e)}catch{t=e}return!ee.existsSync(t)||!ee.statSync(t).isDirectory()?null:Fi(t)?t:wc(t,0,Nu)}var vc=[b()?".bitfun":".idea",".deveco",b()?".cxx":"cxx","compile_commands.json"];function Rn(n){return q.join(n,...vc)}function Lu(n){return new Promise(e=>setTimeout(e,n))}var kv=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function Tn(n){let e=q.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&kv.has(e)}function Hi(n){return q.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function ue(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function xv(n){return ue(n)}function kn(n){let e=xv(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function Kt(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??q.join(_i.homedir(),"AppData","Local");return q.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?q.join(_i.homedir(),"Library","Logs","devecocli-mcp-server"):q.join(_i.homedir(),".local","share","devecocli-mcp-server","logs")}function Ou(n,e){let t=Nv(e),r=Lv(t,n);if(r!==null)return r;let o=Date.now(),s=`${n.replace(/:/g,"\\:")}=${o}`,a=Ov(t,n,s);return Mv(e,a),o}function Nv(n){let e;try{e=ee.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function Lv(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 Ov(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 Mv(n,e){try{ee.mkdirSync(q.dirname(n),{recursive:!0})}catch{}try{ee.writeFileSync(n,e.join(`
8
+ `)}`)}let i=gt(e),s=gt(o);return n.assertInsideRoot(s,i,"codelinter"),s}static getCodelinterCandidates(e,t){if(t==="studio"){let r=ve.platform()==="darwin"?["Contents"]:[];return[v.join(e,...r,"plugins","codelinter","run","index.js"),v.join(e,...r,"plugins","codelinter","index.js"),v.join(e,...r,"tools","codelinter","bin","codelinter.js"),v.join(e,...r,"tools","codelinter","codelinter.js")]}return[v.join(e,"codelinter","index.js"),v.join(e,"codelinter","run","index.js"),v.join(e,"tool","codelinter","bin","codelinter.js"),v.join(e,"tool","codelinter","codelinter.js")]}static isValidRoot(e,t){if(!n.isDirectory(e))return!1;if(t==="clt")return z.existsSync(v.join(e,"version.txt"));let r=ve.platform()==="darwin"?v.join(e,"Contents"):e,o=ve.platform()==="darwin"?v.join(r,"Info.plist"):v.join(r,"product-info.json");if(!z.existsSync(o))return!1;let i=n.buildToolPaths(e,"studio");return[i.nodePath,i.ohpmJsPath,i.hvigorJsPath].every(z.existsSync)}static buildToolPaths(e,t){return t==="clt"?n.buildCltToolPaths(e):n.buildStudioToolPaths(e)}static buildCltToolPaths(e){let t=v.join(e,"sdk"),r=ve.platform()==="win32",o=r?".exe":"";return{nodePath:r?v.join(e,"tool","node","node.exe"):v.join(e,"tool","node","bin","node"),ohpmJsPath:v.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:v.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:t,hdcPath:v.join(t,"default","openharmony","toolchains",`hdc${o}`),emulatorPath:v.join(e,"emulator",r?"Emulator.exe":"Emulator")}}static buildStudioToolPaths(e){let t=ve.platform()==="darwin",r=ve.platform()==="win32",o=t?v.join(e,"Contents"):e,i=v.join(o,"tools"),s=v.join(o,"sdk"),a=r?".exe":"";return{nodePath:r?v.join(i,"node","node.exe"):v.join(i,"node","bin","node"),ohpmJsPath:v.join(i,"ohpm","bin","pm-cli.js"),hvigorJsPath:v.join(i,"hvigor","bin","hvigorw.js"),javaPath:r?v.join(e,"jbr","bin","java.exe"):t?v.join(o,"jbr","Contents","Home","bin","java"):v.join(o,"jbr","bin","java"),sdkPath:s,hdcPath:v.join(s,"default","openharmony","toolchains",`hdc${a}`),emulatorPath:v.join(i,"emulator",r?"Emulator.exe":"Emulator")}}static isFile(e){try{return z.statSync(e).isFile()}catch{return!1}}static isDirectory(e){try{return z.existsSync(e)&&z.statSync(e).isDirectory()}catch{return!1}}static resolveInstallSource(){return n.installSourcePromise||(n.installSourcePromise=n.resolveInstallSourceUncached()),n.installSourcePromise}static async resolveInstallSourceUncached(){let e=[["DEVECO_CLI_STUDIO_PATH","studio","studio"],["DEVECO_CLI_CLT_PATH","clt","clt"],["DEVECO_HOME","studio","studio"],["DEVECO_PATH","studio","studio"]];for(let[r,o,i]of e){let s=process.env[r]?.trim();if(s){let a=n.resolveExplicitRoot(s,o,r);return m(`[ToolProvider] Using ${r} \u2192 ${a}`),{sourceType:i,toolchainRoot:a}}}let t=await Pu();return m(`[ToolProvider] Using auto \u2192 ${t.root} (${t.version})`),{sourceType:"studio",toolchainRoot:t.root}}static resolveExplicitRoot(e,t,r){let o;try{o=xi(e)}catch(i){throw new Error(`Invalid ${r}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return t==="studio"&&ve.platform()==="darwin"&&(o=n.normalizeMacStudioRoot(o)),n.isValidRoot(o,t)?o:n.throwInvalidSource(o,t,r,e)}static assertBuiltPathsInsideRoot(e,t,r){let o=gt(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(Ti(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=`${v.sep}Contents`,r=v.normalize(e);return r.endsWith(t)?r.slice(0,-t.length):r}static readCltVersion(e){try{return z.readFileSync(v.join(e,"version.txt"),"utf-8").split(/\r?\n/).map(t=>t.match(pv)?.[1]?.trim()).find(Boolean)}catch{return}}static resolveCltJava(e){let t=process.env.JAVA_HOME?.trim(),r=t&&(n.javaIn(v.join(t,"bin"))??n.javaIn(t)),o=(process.env.Path??process.env.PATH??"").split(v.delimiter).map(s=>n.javaIn(s.trim())).find(Boolean),i=r??o;if(i)return z.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(ve.platform()==="win32"?["java.exe","java.cmd"]:["java"]).map(r=>v.join(e,r)).find(z.existsSync)}getMaxApiLevel(){for(let e of gv(this.sdkPath)){let t=hv(e);if(t!==void 0)return t}return 23}detectApiLevel(){return this.getMaxApiLevel()}_apiscanPaths;getApiscanPaths(){if(this._apiscanPaths)return this._apiscanPaths;let e=ve.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=v.join(this._devecoStudioPath,t,"plugins","harmony","arkanalyzer-apiscan"),o=v.join(r,"resources","apiChange"),i=v.join(r,"api-change-scan.js");if(!z.existsSync(o)||!z.existsSync(i)){let s=to(this._toolchainRoot)??"unknown";throw new Error(`A required component is missing. The detected DevEco Studio version is ${s}. The minimum required version is ${fv}. Upgrade before using 'check compat' at ${hc}`)}return this._apiscanPaths={apiChangeDir:o,scriptPath:i},this._apiscanPaths}static verifySignature(e){if(!z.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=ve.platform();if(t==="linux"){n.assertExecutable(e);return}if(t==="win32"&&v.extname(e).toLowerCase()===".exe"){n.assertSigned(n.verifyWindowsSignature(e),e);return}t==="darwin"&&(n.assertExecutable(e),n.assertSigned(n.verifyMacSignature(e),e))}static assertExecutable(e){try{if(!z.statSync(e).isFile())throw new Error;z.accessSync(e,z.constants.X_OK)}catch{throw new Error(`executable is not accessible: ${e}`)}}static assertSigned(e,t){if(!e.signed)throw new Error(`The executable is not digitally signed: ${t}`)}static findPowerShellPath(){if(n.powerShellPath!==void 0)return n.powerShellPath;let e=v.join(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return n.powerShellPath=z.existsSync(e)?e:"",n.powerShellPath&&(n.powerShellModulesPath=v.join(v.dirname(n.powerShellPath),"Modules")),n.powerShellPath}static verifyWindowsSignature(e){let t=n.findPowerShellPath();if(!t)throw new Error("The PowerShell application was not found");let r=z.mkdtempSync(v.join(ve.tmpdir(),"deveco-verify-")),o=v.join(r,"Verify-Signature.ps1");z.writeFileSync(o,"Get-AuthenticodeSignature -FilePath $args[0] | ConvertTo-Json -Depth 3 -Compress","utf8");try{let i=xu(t,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",o,e],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"],env:{...process.env,PSModulePath:n.powerShellModulesPath}}),s=JSON.parse(i);return{signed:Number(s.Status)===0}}catch(i){return m(`[ToolProvider] verify Windows Signature, error msg: ${i}`),{signed:!1}}finally{z.rmSync(r,{recursive:!0,force:!0})}}static verifyMacSignature(e){try{return xu("codesign",["-v",e],{encoding:"utf8",timeout:5e3,stdio:["ignore","ignore","ignore"]}),{signed:!0}}catch{return{signed:!1}}}};import{execa as yv}from"execa";import*as Dt from"path";import*as Oi from"fs";import*as gc from"os";var ke=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=Dt.dirname(e.javaPath);o.PATH=`${i}${Dt.delimiter}${process.env.PATH||""}`,e.sourceType==="clt"&&(o.JAVA_HOME=Dt.dirname(i))}b()&&(o.HVIGOR_USER_HOME=Dt.join(gc.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()){m("[HvigorAdapter] Daemon already running.");return}m("[HvigorAdapter] No daemon running, starting via --sync --daemon (no hap build)."),await this.runHvigor(["--sync","--daemon"])}isDaemonRunning(e){return this.findProjectDaemon(e)!==null}findProjectDaemon(e){let t=this.getDaemonRegistryPath();if(!Oi.existsSync(t))return null;try{let r=Oi.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||Dt.join(gc.homedir(),".hvigor");return Dt.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];m(`Executing: ${t} ${r.join(" ")}`);let o=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit";await yv(t,r,{cwd:this.projectRoot,env:this.env,stdout:o,stderr:o})}};import{execa as wv}from"execa";var Xt=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"];m(`Executing: ${e} ${t.join(" ")}`),await wv(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"})}};import{mkdir as vv}from"fs/promises";import{dirname as Sv,resolve as bv}from"path";import{execa as Ev}from"execa";import{lock as yc,check as lM}from"proper-lockfile";function wc(n){return bv(n,".hvigor",".build-lock")}function Pv(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function Nu(n){let e=Sv(wc(n));if(await vv(e,{recursive:!0}),process.platform==="win32")try{await Ev("attrib",["+h",e])}catch{}}async function Cv(n,e){let t=new AbortController,r=Pv(e);await Nu(n);let o={lockfilePath:wc(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await yc(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 yc(n,{...o,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function Rt(n,e,t){let{release:r,signal:o}=await Cv(n,t);try{return await e(o)}finally{await r()}}async function Mi(n,e){let t=new AbortController;await Nu(n);let r={lockfilePath:wc(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},o;try{o=await yc(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 Zt from"fs";import*as Tn from"path";import Iv from"json5";var Av=1e3;function Fi(n){m(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=Tn.join(n,it.SYNC_OUTPUT_PATH);if(!Zt.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return m(`[ProjectCheck] ${l.reason}`),l}let t=Zt.statSync(e).mtimeMs;m(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=Dv(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return m(`[ProjectCheck] ${l.reason}`),l}let o=Tn.join(n,it.OH_PACKAGE_JSON5),i=_i(o,t,"root");if(i.required)return m(`[ProjectCheck] Root check: ${i.reason}`),i;let s=Tn.join(n,it.BUILD_PROFILE_JSON5),a=_i(s,t,"build-profile");if(a.required)return m(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let d=Tn.join(n,l.srcPath,it.OH_PACKAGE_JSON5),h=_i(d,t,l.name);if(h.required)return m(`[ProjectCheck] Module '${l.name}' check: ${h.reason}`),h;let w=Tn.join(n,l.srcPath,it.BUILD_PROFILE_JSON5),S=_i(w,t,l.name);if(S.required)return m(`[ProjectCheck] Module '${l.name}' build-profile check: ${S.reason}`),S}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return m(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function _i(n,e,t){if(!Zt.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=Zt.statSync(n).mtimeMs;return r-e>Av?{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 Dv(n){let e=Tn.join(n,it.BUILD_PROFILE_JSON5);try{let t=Zt.readFileSync(e,"utf-8");if(!t.trim())return null;let r=Iv.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 Be from"fs";import*as at from"path";import*as Uu from"util";import*as M from"fs";import*as Wi from"path";import ee from"fs";import*as ji from"os";import*as q from"path";import Rv from"json5";var Lu=3;function Hi(n){if(!ee.existsSync(n)||!ee.statSync(n).isDirectory())return!1;let e=ee.existsSync(q.join(n,"build-profile.json5")),t=ee.existsSync(q.join(n,"hvigorfile.js"))||ee.existsSync(q.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=ee.readFileSync(q.join(n,"build-profile.json5"),"utf-8");return Rv.parse(r).app!==void 0}catch{return!1}}function vc(n,e,t){if(e>=t)return null;let r=Tv(n),o=kv(r);if(o)return o;for(let i of r){let s=vc(i,e+1,t);if(s)return s}return null}function Tv(n){try{let e=ee.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(q.join(n,r.name));return t}catch{return[]}}function kv(n){for(let e of n)if(Hi(e))return e;return null}function Tt(n){if(!n||n.trim()==="")return null;let e=q.resolve(n),t;try{t=ee.realpathSync(e)}catch{t=e}if(!ee.existsSync(t))return null;if(Hi(t))return t;let r=t;for(let o=1;o<=3;o++){let i=q.dirname(r);if(i===r)break;if(Hi(i))return i;r=i}if(ee.statSync(t).isDirectory()){let o=vc(t,0,Lu);if(o)return o}return null}function $i(n){if(!n||n.trim()==="")return null;let e=q.resolve(n),t;try{t=ee.realpathSync(e)}catch{t=e}return!ee.existsSync(t)||!ee.statSync(t).isDirectory()?null:Hi(t)?t:vc(t,0,Lu)}var Sc=[b()?".bitfun":".idea",".deveco",b()?".cxx":"cxx","compile_commands.json"];function tr(n){return q.join(n,...Sc)}function Ou(n){return new Promise(e=>setTimeout(e,n))}var xv=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function kn(n){let e=q.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&xv.has(e)}function Ui(n){return q.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function pe(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function Nv(n){return pe(n)}function xn(n){let e=Nv(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function Qt(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??q.join(ji.homedir(),"AppData","Local");return q.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?q.join(ji.homedir(),"Library","Logs","devecocli-mcp-server"):q.join(ji.homedir(),".local","share","devecocli-mcp-server","logs")}function Mu(n,e){let t=Lv(e),r=Ov(t,n);if(r!==null)return r;let o=Date.now(),s=`${n.replace(/:/g,"\\:")}=${o}`,a=Mv(t,n,s);return _v(e,a),o}function Lv(n){let e;try{e=ee.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function Ov(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 Mv(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 _v(n,e){try{ee.mkdirSync(q.dirname(n),{recursive:!0})}catch{}try{ee.writeFileSync(n,e.join(`
9
9
  `)+`
10
- `,"utf8")}catch{}}function Sc(n,e,t="[Cleanup]"){try{let r=q.dirname(n);if(!ee.existsSync(r))return;let o=Date.now();for(let i of ee.readdirSync(r,{withFileTypes:!0}))i.isDirectory()&&_v(q.join(r,i.name),o,e,t)}catch{}}function _v(n,e,t,r){try{let{mtimeMs:o}=ee.statSync(n);if(e-o<=t)return;ee.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 Mu="mcp-server.log",Fv="mcp-server",jv={maxSize:10*1024*1024,maxFiles:4},bc=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={...jv,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=Kt(),this.currentLogFile=Ui.join(this.logDir,Mu),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 Ui.join(this.logDir,`${Fv}-${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===Mu||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(o)){let i=Ui.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=>typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),i=o?`${t} ${o}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] ${i}
11
- `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);M.writeSync(this.fd,c),this.checkRotation(c.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(a)}debug(e,...t){this.write("debug",e,...t)}info(e,...t){this.write("info",e,...t)}warn(e,...t){this.write("warn",e,...t)}error(e,...t){this.write("error",e,...t)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{M.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},Ge=null;function xn(n=!1){Ge&&Ge.dispose(),Ge=new bc(n)}function _u(){Ge&&(Ge.dispose(),Ge=null)}function Fu(){Ge&&Ge.flush()}function ju(){return Ge?.getLogFilePath()??null}function Hu(){return Ge?.getLogDirectory()??null}function $i(){return Ge||xn(!1),Ge}var g={debug:(n,...e)=>$i().debug(n,...e),info:(n,...e)=>$i().info(n,...e),warn:(n,...e)=>$i().warn(n,...e),error:(n,...e)=>$i().error(n,...e)};var Ec="";function Wi(n){if(!n||n==="auto"||n==="stdout"||n==="none"){Ec="";return}Ec=n}function Uu(){return Ec||(Hu()??"")}function Bi(n,...e){if(e.length===0)return n;try{return $u.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var f={info(n,...e){g.info(`[lsp] ${Bi(n,...e)}`)},warn(n,...e){g.warn(`[lsp] ${Bi(n,...e)}`)},error(n,...e){g.error(`[lsp] ${Bi(n,...e)}`)},debug(n,...e){g.debug(`[lsp] ${Bi(n,...e)}`)}};import*as oo from"fs";import*as io from"os";import*as er from"path";import Hv from"json5";var y={INITIALIZE:"initialize",INITIALIZED:"initialized",SHUTDOWN:"shutdown",EXIT:"exit",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",DID_CLOSE:"textDocument/didClose",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",DECLARATION:"textDocument/declaration",REFERENCES:"textDocument/references",IMPLEMENTATION:"textDocument/implementation",COMPLETION:"textDocument/completion",COMPLETION_ITEM_RESOLVE:"completionItem/resolve",SIGNATURE_HELP:"textDocument/signatureHelp",CODE_ACTION:"textDocument/codeAction",PREPARE_RENAME:"textDocument/prepareRename",RENAME:"textDocument/rename",DOCUMENT_HIGHLIGHT:"textDocument/documentHighlight",DOCUMENT_LINK:"textDocument/documentLink",INLAY_HINT:"textDocument/inlayHint",DOCUMENT_SYMBOL:"textDocument/documentSymbol",WORKSPACE_SYMBOL:"workspace/symbol",DIAGNOSTIC:"textDocument/diagnostic",WORKSPACE_DIAGNOSTIC:"workspace/diagnostic",PREPARE_CALL_HIERARCHY:"textDocument/prepareCallHierarchy",INCOMING_CALLS:"callHierarchy/incomingCalls",OUTGOING_CALLS:"callHierarchy/outgoingCalls",PREPARE_TYPE_HIERARCHY:"textDocument/prepareTypeHierarchy",SUPERTYPES:"typeHierarchy/supertypes",SUBTYPES:"typeHierarchy/subtypes",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",DID_CREATE_FILES:"workspace/didCreateFiles",DID_DELETE_FILES:"workspace/didDeleteFiles",PROGRESS:"$/progress",WINDOW_SHOW_MESSAGE:"window/showMessage",WINDOW_LOG_MESSAGE:"window/logMessage",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing",ARKTS_ERROR:"arkts/error",CPP_INITIALIZED:"cpp/initialized",CPP_INITIALIZATION_FAILED:"cpp/initializationFailed",CPP_INDEXING_PROGRESS:"cpp/indexingProgress",CPP_SYNC_PROJECT:"cpp/syncProject",CPP_SYNC_COMPLETED:"cpp/syncCompleted",CPP_REINITIALIZING:"cpp/reinitializing",CPP_ERROR:"cpp/error",BROADCAST:"lsp/broadcast"},R="2.0";var Bu=8192,Pc=100,Wu=.03,Gu=.7,ze=900*1e3,Gi="/data/app/sdk.org/sdk_1.0.0";function He(n){if(!oo.existsSync(n))return null;try{let e=oo.readFileSync(n,"utf-8");return e.trim()?Hv.parse(e):null}catch{return null}}function zi(n,e){let t=Math.floor(io.totalmem()/1048576),r=Math.floor(t*Gu),o,i;e!==void 0&&Number.isFinite(e)&&e>0?(o=e,i=`override(${e})`):(o=Bu,n>Pc&&(o+=(n-Pc)*Wu*1024),i=`formula(moduleCount=${n})`);let s=r>0&&o>r;s&&(o=r);let a=Math.round(o);return f.info(`[computeLspServerMaxSize] source=${i}, physicalTotal=${t}MB, physicalCap(70%)=${r}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function st(n){if(n.startsWith("file:"))return n;try{let e=er.resolve(n),t=new URL(`file://${e}`).toString();if(io.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 tr(n){return n&&n.replace(/\\/g,"/")}function U(n){let e=er.normalize(n).replace(/\\/g,"/");if(io.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function zu(n){return er.join(n,"build-profile.json5")}var Rt=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=zu(this.projectRoot);try{let t=He(e);if(typeof t!="object"||t===null)return[];let r=t.modules;return Array.isArray(r)?r.filter(o=>{if(typeof o!="object"||o===null)return!1;let i=o;return typeof i.name=="string"&&typeof i.srcPath=="string"}):[]}catch(t){return f.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};import*as qu from"os";import*as Vu from"path";import{spawn as $v}from"child_process";var Uv=600*1e3;function Bv(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 qi(n){return n.join("")}function Wv(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
10
+ `,"utf8")}catch{}}function bc(n,e,t="[Cleanup]"){try{let r=q.dirname(n);if(!ee.existsSync(r))return;let o=Date.now();for(let i of ee.readdirSync(r,{withFileTypes:!0}))i.isDirectory()&&Fv(q.join(r,i.name),o,e,t)}catch{}}function Fv(n,e,t,r){try{let{mtimeMs:o}=ee.statSync(n);if(e-o<=t)return;ee.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",jv="mcp-server",Hv={maxSize:10*1024*1024,maxFiles:4},Ec=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={...Hv,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=Qt(),this.currentLogFile=Wi.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 Wi.join(this.logDir,`${jv}-${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=Wi.join(this.logDir,o),s=M.statSync(i);t.push({name:o,mtime:s.mtime,path:i})}t.sort((o,i)=>i.mtime.getTime()-o.mtime.getTime());let r=1+this.rotationOptions.maxFiles;for(let o=r;o<t.length;o++)try{M.unlinkSync(t[o].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let e=this.getCurrentDateString(),t=this.getRotatedFileName(e,this.rotationOptions.maxFiles);this.fileExists(t)&&M.unlinkSync(t);for(let o=this.rotationOptions.maxFiles-1;o>=1;o--){let i=this.getRotatedFileName(e,o),s=this.getRotatedFileName(e,o+1);this.fileExists(i)&&M.renameSync(i,s)}let r=this.getRotatedFileName(e,1);M.renameSync(this.currentLogFile,r),this.cleanupOrphanLogFiles(),this.openLogFile()}catch{this.openLogFile()}finally{this.isRotating=!1}}}openLogFile(){if(this.currentLogFile){this.currentDate=this.getCurrentDateString();try{if(this.fileExists(this.currentLogFile)){let e=M.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=M.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{M.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...r){if(this.mode==="silent"||n.LEVEL_ORDER[e]<n.LEVEL_ORDER[this.minLevel])return;let o=r.map(c=>c instanceof Error?`${c.name}: ${c.message}`:typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),i=o?`${t} ${o}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] ${i}
11
+ `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);M.writeSync(this.fd,c),this.checkRotation(c.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(a)}debug(e,...t){this.write("debug",e,...t)}info(e,...t){this.write("info",e,...t)}warn(e,...t){this.write("warn",e,...t)}error(e,...t){this.write("error",e,...t)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{M.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},ze=null;function Nn(n=!1){ze&&ze.dispose(),ze=new Ec(n)}function Fu(){ze&&(ze.dispose(),ze=null)}function ju(){ze&&ze.flush()}function Hu(){return ze?.getLogFilePath()??null}function $u(){return ze?.getLogDirectory()??null}function Bi(){return ze||Nn(!1),ze}var g={debug:(n,...e)=>Bi().debug(n,...e),info:(n,...e)=>Bi().info(n,...e),warn:(n,...e)=>Bi().warn(n,...e),error:(n,...e)=>Bi().error(n,...e)};var Pc="";function zi(n){if(!n||n==="auto"||n==="stdout"||n==="none"){Pc="";return}Pc=n}function Bu(){return Pc||($u()??"")}function Gi(n,...e){if(e.length===0)return n;try{return Uu.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var f={info(n,...e){g.info(`[lsp] ${Gi(n,...e)}`)},warn(n,...e){g.warn(`[lsp] ${Gi(n,...e)}`)},error(n,...e){g.error(`[lsp] ${Gi(n,...e)}`)},debug(n,...e){g.debug(`[lsp] ${Gi(n,...e)}`)}};import*as ao from"fs";import*as co from"os";import*as nr from"path";import $v from"json5";var y={INITIALIZE:"initialize",INITIALIZED:"initialized",SHUTDOWN:"shutdown",EXIT:"exit",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",DID_CLOSE:"textDocument/didClose",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",DECLARATION:"textDocument/declaration",REFERENCES:"textDocument/references",IMPLEMENTATION:"textDocument/implementation",COMPLETION:"textDocument/completion",COMPLETION_ITEM_RESOLVE:"completionItem/resolve",SIGNATURE_HELP:"textDocument/signatureHelp",CODE_ACTION:"textDocument/codeAction",PREPARE_RENAME:"textDocument/prepareRename",RENAME:"textDocument/rename",DOCUMENT_HIGHLIGHT:"textDocument/documentHighlight",DOCUMENT_LINK:"textDocument/documentLink",INLAY_HINT:"textDocument/inlayHint",DOCUMENT_SYMBOL:"textDocument/documentSymbol",WORKSPACE_SYMBOL:"workspace/symbol",DIAGNOSTIC:"textDocument/diagnostic",WORKSPACE_DIAGNOSTIC:"workspace/diagnostic",PREPARE_CALL_HIERARCHY:"textDocument/prepareCallHierarchy",INCOMING_CALLS:"callHierarchy/incomingCalls",OUTGOING_CALLS:"callHierarchy/outgoingCalls",PREPARE_TYPE_HIERARCHY:"textDocument/prepareTypeHierarchy",SUPERTYPES:"typeHierarchy/supertypes",SUBTYPES:"typeHierarchy/subtypes",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",DID_CREATE_FILES:"workspace/didCreateFiles",DID_DELETE_FILES:"workspace/didDeleteFiles",PROGRESS:"$/progress",WINDOW_SHOW_MESSAGE:"window/showMessage",WINDOW_LOG_MESSAGE:"window/logMessage",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing",ARKTS_ERROR:"arkts/error",CPP_INITIALIZED:"cpp/initialized",CPP_INITIALIZATION_FAILED:"cpp/initializationFailed",CPP_INDEXING_PROGRESS:"cpp/indexingProgress",CPP_SYNC_PROJECT:"cpp/syncProject",CPP_SYNC_COMPLETED:"cpp/syncCompleted",CPP_REINITIALIZING:"cpp/reinitializing",CPP_ERROR:"cpp/error",BROADCAST:"lsp/broadcast"},R="2.0";var Wu=8192,Cc=100,Gu=.03,zu=.7,qe=900*1e3,qi="/data/app/sdk.org/sdk_1.0.0";function Ue(n){if(!ao.existsSync(n))return null;try{let e=ao.readFileSync(n,"utf-8");return e.trim()?$v.parse(e):null}catch{return null}}function Vi(n,e){let t=Math.floor(co.totalmem()/1048576),r=Math.floor(t*zu),o,i;e!==void 0&&Number.isFinite(e)&&e>0?(o=e,i=`override(${e})`):(o=Wu,n>Cc&&(o+=(n-Cc)*Gu*1024),i=`formula(moduleCount=${n})`);let s=r>0&&o>r;s&&(o=r);let a=Math.round(o);return f.info(`[computeLspServerMaxSize] source=${i}, physicalTotal=${t}MB, physicalCap(70%)=${r}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function st(n){if(n.startsWith("file:"))return n;try{let e=nr.resolve(n),t=new URL(`file://${e}`).toString();if(co.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 rr(n){return n&&n.replace(/\\/g,"/")}function U(n){let e=nr.normalize(n).replace(/\\/g,"/");if(co.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function qu(n){return nr.join(n,"build-profile.json5")}var kt=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=qu(this.projectRoot);try{let t=Ue(e);if(typeof t!="object"||t===null)return[];let r=t.modules;return Array.isArray(r)?r.filter(o=>{if(typeof o!="object"||o===null)return!1;let i=o;return typeof i.name=="string"&&typeof i.srcPath=="string"}):[]}catch(t){return f.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};import*as Vu from"os";import*as Ju from"path";import{spawn as Uv}from"child_process";var Bv=600*1e3;function Wv(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 Ji(n){return n.join("")}function Gv(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
12
12
  Output so far:
13
- `+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function Gv(n,e,t){return new Promise(r=>{let o=$v(n[0],n[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:i,stderr:s}=Bv(o),a=setTimeout(()=>{o.kill();let c=[qi(i),qi(s)].filter(Boolean).join(`
13
+ `+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function zv(n,e,t){return new Promise(r=>{let o=Uv(n[0],n[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:i,stderr:s}=Wv(o),a=setTimeout(()=>{o.kill();let c=[Ji(i),Ji(s)].filter(Boolean).join(`
14
14
  `).trim();r({success:!1,output:`Build process timeout after 10 minutes.
15
15
  Output so far:
16
- `+c,exitCode:-1})},Uv);o.on("close",(c,l)=>{clearTimeout(a);let d=[qi(i),qi(s)].filter(Boolean).join(`
17
- `).trim()||"";r(Wv(c,l,d))}),o.on("error",c=>{clearTimeout(a),r({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function Cc(n,e,t,r,o){let i={...process.env,DEVECO_SDK_HOME:r};return b()&&(i.HVIGOR_USER_HOME=Vu.join(qu.homedir(),".hvigor")),await Gv([e,[t,...o]],n,i)}var zv=["--sync","-p","product=default","--analyze=normal","--parallel","--incremental","--no-daemon"];async function Ju(n,e){try{return(await Cc(n,e.nodePath,e.hvigorJsPath,e.sdkPath,zv)).success}catch(t){return f.info(`syncProject failed: ${JSON.stringify(t)}`),!1}}function qv(n){let e=Xt.extname(n).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh","c++","h++"].includes(e)}function Vv(n,e){let t=Xt.join(n,e.name);return e.isDirectory()?e.name===".cxx"||Yu(t):qv(t)}function Yu(n){if(!$e.existsSync(n))return!1;try{return $e.readdirSync(n,{withFileTypes:!0}).some(t=>Vv(n,t))}catch{}return!1}function Nn(n){let t=new Rt(n).getAllModuleInfo(),r=[];for(let o of t){let i=P.resolvePathWithinRoot(n,o.srcPath);Yu(i)&&r.push(o)}return r}function Jv(n){let e=[],r=new Rt(n).getAllModuleInfo();for(let o of r){let i=P.resolvePathWithinRoot(n,o.srcPath),s=Xt.join(i,".cxx");$e.existsSync(s)&&Ku(s,e)}return e}function Ku(n,e){try{let t=$e.readdirSync(n,{withFileTypes:!0});for(let r of t){let o=Xt.join(n,r.name);r.isDirectory()?Ku(o,e):r.name==="compile_commands.json"&&e.push(o)}}catch{}}function Yv(n){let e=[];for(let t of n)try{let r=$e.readFileSync(t,"utf8"),o=JSON.parse(r);e.push(...o)}catch{}return e}function Kv(n,e){let t=Xt.join(n,...vc.slice(0,-1));$e.mkdirSync(t,{recursive:!0});let r=Xt.join(t,"compile_commands.json");$e.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function Ic(n){let e=Jv(n);if(e.length>0){let t=Yv(e);Kv(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 Xv(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 Cc(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 Xu(n,e){let t=Nn(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 Xv(n,e,t),Ic(n)}function Qv(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 eS(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 ao(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 so(n,e){let t=e,r=`${n} failed`;console.error(Dc(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 co(n,e,t,r,o,i){let s=Mi(i);console.log(`
18
- [ohpm install] Running...`);try{await n.installAll()}catch(a){so("ohpm install",a)}if(s.required){console.log(`
19
- [hvigor sync] Running...`);try{await e.sync(t,r)}catch(a){so("hvigor sync",a)}}else console.log(`
16
+ `+c,exitCode:-1})},Bv);o.on("close",(c,l)=>{clearTimeout(a);let d=[Ji(i),Ji(s)].filter(Boolean).join(`
17
+ `).trim()||"";r(Gv(c,l,d))}),o.on("error",c=>{clearTimeout(a),r({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function Ic(n,e,t,r,o){let i={...process.env,DEVECO_SDK_HOME:r};return b()&&(i.HVIGOR_USER_HOME=Ju.join(Vu.homedir(),".hvigor")),await zv([e,[t,...o]],n,i)}var qv=["--sync","-p","product=default","--analyze=normal","--parallel","--incremental","--no-daemon"];async function Yu(n,e){try{return(await Ic(n,e.nodePath,e.hvigorJsPath,e.sdkPath,qv)).success}catch(t){return f.info(`syncProject failed: ${JSON.stringify(t)}`),!1}}function Vv(n){let e=at.extname(n).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh","c++","h++"].includes(e)}function Jv(n,e){let t=at.join(n,e.name);return e.isDirectory()?e.name===".cxx"||Ku(t):Vv(t)}function Ku(n){if(!Be.existsSync(n))return!1;try{return Be.readdirSync(n,{withFileTypes:!0}).some(t=>Jv(n,t))}catch{}return!1}function Ln(n){try{let t=new kt(n).getAllModuleInfo(),r=[];for(let o of t){let i=at.resolve(n,o.srcPath);Ku(i)&&r.push(o)}return r}catch(e){throw g.error(`[CppCompile] findCppModules threw: ${e instanceof Error?e.message:String(e)}`),e}}function Yv(n){let e=[],r=new kt(n).getAllModuleInfo();for(let o of r){let i=at.resolve(n,o.srcPath),s=at.join(i,".cxx");Be.existsSync(s)&&Xu(s,e)}return e}function Xu(n,e){try{let t=Be.readdirSync(n,{withFileTypes:!0});for(let r of t){let o=at.join(n,r.name);r.isDirectory()?Xu(o,e):r.name==="compile_commands.json"&&e.push(o)}}catch{}}function Kv(n){let e=[];for(let t of n)try{let r=Be.readFileSync(t,"utf8"),o=JSON.parse(r);e.push(...o)}catch{}return e}function Xv(n,e){let t=at.join(n,...Sc.slice(0,-1));Be.mkdirSync(t,{recursive:!0});let r=at.join(t,"compile_commands.json");Be.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function Ac(n){let e=Yv(n);if(e.length>0){let t=Kv(e);Xv(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 Zv(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 Ic(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 Zu(n,e){let t=Ln(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 Zv(n,e,t),Ac(n)}function eS(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 tS(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 uo(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 lo(n,e){let t=e,r=`${n} failed`;console.error(Rc(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 po(n,e,t,r,o,i){let s=Fi(i);console.log(`
18
+ [ohpm install] Running...`);try{await n.installAll()}catch(a){lo("ohpm install",a)}if(s.required){console.log(`
19
+ [hvigor sync] Running...`);try{await e.sync(t,r)}catch(a){lo("hvigor sync",a)}}else console.log(`
20
20
  [hvigor sync] Skipped (configurations unchanged)`);console.log(`
21
- [hvigor build] Running...`);try{o.type==="product"?await e.buildProduct(t,r):await e.buildModules(t,r,o.modulesToBuild,o.moduleTasks)}catch(a){so("hvigor build",a)}tS(i)}function tS(n){try{if(Nn(n).length===0)return;Ic(n),console.log(Ac(`
22
- Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(Rc(`
23
- Failed to merge compile_commands.json: ${e.message}`))}}var Zu=new Zv("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=G.discover(e);console.warn(Rc("Ensure the project source is trustworthy before proceeding."));let r=await A.new();r.assertJava(),Qv(t,n);let o=n.product||"default",i=n.buildMode||"debug",s;if(n.product&&!n.modules)s={type:"product"};else{let l=eS(t,n),d=ao(t,l);s={type:"modules",modulesToBuild:l,moduleTasks:d}}let a=new Jt(r,t.rootDir),c=new Te(r,t.rootDir);await At(t.rootDir,async()=>co(a,c,o,i,s,t.rootDir),()=>{console.log("Another build is already running for this project. Waiting for completion...")}),console.log(`
24
- `+Ac("Build completed successfully"))}catch(e){console.error(Dc(e.message)),process.exit(1)}});Zu.command("clean").description("Clean HarmonyOS project build outputs").action(async()=>{try{let n=process.cwd(),e=G.discover(n);console.warn(Rc("Ensure the project source is trusted before proceeding."));let t=await A.new();t.assertJava();let r=new Te(t,e.rootDir);await At(e.rootDir,async()=>{console.log(`
25
- [1/2] Running hvigor clean...`);try{await r.clean()}catch(o){so("hvigor clean",o)}console.log(`
26
- [2/2] Running hvigor --stop-daemon...`);try{await r.stopDaemon()}catch(o){so("hvigor --stop-daemon",o)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
27
- `+Ac("Clean completed successfully."))}catch(n){console.error(Dc(n.message)),process.exit(1)}});var Qu=Zu;import{Command as cb}from"commander";import{green as mo,red as lb,yellow as os}from"colorette";import*as is from"path";import{randomUUID as mS}from"crypto";import{execa as hS}from"execa";import{execa as fS}from"execa";import{execFile as nS,spawn as rS}from"child_process";import{promisify as oS}from"util";var iS=oS(nS);function ep(n,e,t){let o=n.replace(/\r\n/g,`
21
+ [hvigor build] Running...`);try{o.type==="product"?await e.buildProduct(t,r):await e.buildModules(t,r,o.modulesToBuild,o.moduleTasks)}catch(a){lo("hvigor build",a)}nS(i)}function nS(n){try{if(Ln(n).length===0)return;Ac(n),console.log(Dc(`
22
+ Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(Tc(`
23
+ Failed to merge compile_commands.json: ${e.message}`))}}var Qu=new Qv("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=G.discover(e);console.warn(Tc("Ensure the project source is trustworthy before proceeding."));let r=await I.new();r.assertJava(),eS(t,n);let o=n.product||"default",i=n.buildMode||"debug",s;if(n.product&&!n.modules)s={type:"product"};else{let l=tS(t,n),d=uo(t,l);s={type:"modules",modulesToBuild:l,moduleTasks:d}}let a=new Xt(r,t.rootDir),c=new ke(r,t.rootDir);await Rt(t.rootDir,async()=>po(a,c,o,i,s,t.rootDir),()=>{console.log("Another build is already running for this project. Waiting for completion...")}),console.log(`
24
+ `+Dc("Build completed successfully"))}catch(e){console.error(Rc(e.message)),process.exit(1)}});Qu.command("clean").description("Clean HarmonyOS project build outputs").action(async()=>{try{let n=process.cwd(),e=G.discover(n);console.warn(Tc("Ensure the project source is trusted before proceeding."));let t=await I.new();t.assertJava();let r=new ke(t,e.rootDir);await Rt(e.rootDir,async()=>{console.log(`
25
+ [1/2] Running hvigor clean...`);try{await r.clean()}catch(o){lo("hvigor clean",o)}console.log(`
26
+ [2/2] Running hvigor --stop-daemon...`);try{await r.stopDaemon()}catch(o){lo("hvigor --stop-daemon",o)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
27
+ `+Dc("Clean completed successfully."))}catch(n){console.error(Rc(n.message)),process.exit(1)}});var ep=Qu;import{Command as lb}from"commander";import{green as yo,red as db,yellow as ss}from"colorette";import*as as from"path";import{randomUUID as hS}from"crypto";import{execa as gS}from"execa";import{execa as mS}from"execa";import{execFile as rS,spawn as oS}from"child_process";import{promisify as iS}from"util";var sS=iS(rS);function tp(n,e,t){let o=n.replace(/\r\n/g,`
28
28
  `).split(`
29
- `),i=o.pop()??"",s=o.map(a=>a.endsWith("\r")?a.slice(0,-1):a).filter(a=>a.length>0);return s.length>0&&t.onData(s,e),i}function tp(n,e,t){let r=n.endsWith("\r")?n.slice(0,-1):n;r.length>0&&t.onData([r],e)}function sS(n,e){return{stdout:n.stdoutChunks.join(""),stderr:n.stderrChunks.join(""),exitCode:e??-1}}function aS(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function cS(n,e,t,r,o){n.stdout?.on("data",i=>{let s=i.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=ep(e.stdoutLineBuffer+s,"stdout",t)}),n.stderr?.on("data",i=>{let s=i.toString();e.stderrChunks.push(s),e.stderrLineBuffer=ep(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,tp(e.stdoutLineBuffer,"stdout",t),tp(e.stderrLineBuffer,"stderr",t),t.onClose(i);let s=sS(e,i);r(s)})}async function lo(n,e=[],t={}){try{let{stdout:r,stderr:o}=await iS(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 np(n,e,t){return await new Promise((r,o)=>{let i=rS(n,e,{stdio:["inherit","pipe","pipe"]}),s=aS();cS(i,s,t,r,o)})}function rp(n){let e=n.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var lS=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],dS=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function nr(n){return n?lS.some(e=>e.test(n))?"transient":dS.some(e=>e.test(n))?"fatal":"ok":"ok"}var Tc=[800,1500,2500];function uS(n){return new Promise(e=>setTimeout(e,n))}async function se(n,e){let t=1+Tc.length,r={stdout:"",stderr:"",exitCode:-1};for(let o=0;o<t;o++){if(r=await lo(n,e),r.exitCode===0||nr(r.stderr)!=="transient"||o>=t-1)return r;m(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${Tc[o]}ms`),await uS(Tc[o])}return r}var op=/^[\w.-]+$/;async function Vi(n,e,t){if(!op.test(t)){m(`Skipping invalid param key: ${JSON.stringify(t)}`);return}let r=["-t",e,"shell","param","get",t];m(`Executing: ${n} ${r.join(" ")}`);let o=await se(n,r);if(o.exitCode!==0)return;let i=o.stdout.trim();if(!(!i||nr(i)!=="ok"))return rp(i)}var kc="__DEVECO_PARAM_DELIM__";function pS(n,e){let t=new Map,r=n.split(kc);for(let o=0;o<e.length;o++){let i=(r[o]??"").trim();if(!i||nr(i)!=="ok")continue;let s=rp(i);s&&t.set(e[o],s)}return t}async function rr(n,e,t){let r=t.filter(a=>op.test(a)?!0:(m(`Skipping invalid param key: ${JSON.stringify(a)}`),!1));if(r.length===0)return new Map;if(r.length===1){let a=new Map,c=await Vi(n,e,r[0]);return c&&a.set(r[0],c),a}let o=r.map(a=>`param get ${a}`).join(`; echo ${kc}; `)+`; echo ${kc}`,i=await se(n,["-t",e,"shell",o]);if(i.exitCode===0){let a=pS(i.stdout,r);if(a.size>0)return a}m(`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 Vi(n,e,a);c&&s.set(a,c)}return s}function Ln(n){return n.startsWith("127.0.0.1:")}var ip=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],te=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 m(`Executing: ${this.hdcPath} ${e.join(" ")}`),fS(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let r of e.split(`
30
- `)){let 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"){m(`[DeviceManager] Skipping unauthorized device: ${s}`);continue}t.push({serial:s,status:a})}return t}extractDisplayName(e){let t=e.get("ohos.qemu.hvd.name");if(t)return t;let r=e.get("const.product.name");if(r&&r!=="emulator")return r;let 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 rr(this.hdcPath,e,[...ip]);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:
29
+ `),i=o.pop()??"",s=o.map(a=>a.endsWith("\r")?a.slice(0,-1):a).filter(a=>a.length>0);return s.length>0&&t.onData(s,e),i}function np(n,e,t){let r=n.endsWith("\r")?n.slice(0,-1):n;r.length>0&&t.onData([r],e)}function aS(n,e){return{stdout:n.stdoutChunks.join(""),stderr:n.stderrChunks.join(""),exitCode:e??-1}}function cS(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function lS(n,e,t,r,o){n.stdout?.on("data",i=>{let s=i.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=tp(e.stdoutLineBuffer+s,"stdout",t)}),n.stderr?.on("data",i=>{let s=i.toString();e.stderrChunks.push(s),e.stderrLineBuffer=tp(e.stderrLineBuffer+s,"stderr",t)}),n.on("error",i=>{e.settled||(e.settled=!0,t.onError(i),o(i))}),n.on("close",i=>{if(e.settled)return;e.settled=!0,np(e.stdoutLineBuffer,"stdout",t),np(e.stderrLineBuffer,"stderr",t),t.onClose(i);let s=aS(e,i);r(s)})}async function fo(n,e=[],t={}){try{let{stdout:r,stderr:o}=await sS(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 rp(n,e,t){return await new Promise((r,o)=>{let i=oS(n,e,{stdio:["inherit","pipe","pipe"]}),s=cS();lS(i,s,t,r,o)})}function op(n){let e=n.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var dS=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],uS=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function or(n){return n?dS.some(e=>e.test(n))?"transient":uS.some(e=>e.test(n))?"fatal":"ok":"ok"}var kc=[800,1500,2500];function pS(n){return new Promise(e=>setTimeout(e,n))}async function se(n,e){let t=1+kc.length,r={stdout:"",stderr:"",exitCode:-1};for(let o=0;o<t;o++){if(r=await fo(n,e),r.exitCode===0||or(r.stderr)!=="transient"||o>=t-1)return r;m(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${kc[o]}ms`),await pS(kc[o])}return r}var ip=/^[\w.-]+$/;async function Yi(n,e,t){if(!ip.test(t)){m(`Skipping invalid param key: ${JSON.stringify(t)}`);return}let r=["-t",e,"shell","param","get",t];m(`Executing: ${n} ${r.join(" ")}`);let o=await se(n,r);if(o.exitCode!==0)return;let i=o.stdout.trim();if(!(!i||or(i)!=="ok"))return op(i)}var xc="__DEVECO_PARAM_DELIM__";function fS(n,e){let t=new Map,r=n.split(xc);for(let o=0;o<e.length;o++){let i=(r[o]??"").trim();if(!i||or(i)!=="ok")continue;let s=op(i);s&&t.set(e[o],s)}return t}async function ir(n,e,t){let r=t.filter(a=>ip.test(a)?!0:(m(`Skipping invalid param key: ${JSON.stringify(a)}`),!1));if(r.length===0)return new Map;if(r.length===1){let a=new Map,c=await Yi(n,e,r[0]);return c&&a.set(r[0],c),a}let o=r.map(a=>`param get ${a}`).join(`; echo ${xc}; `)+`; echo ${xc}`,i=await se(n,["-t",e,"shell",o]);if(i.exitCode===0){let a=fS(i.stdout,r);if(a.size>0)return a}m(`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 Yi(n,e,a);c&&s.set(a,c)}return s}function On(n){return n.startsWith("127.0.0.1:")}var sp=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],te=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 m(`Executing: ${this.hdcPath} ${e.join(" ")}`),mS(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let r of e.split(`
30
+ `)){let 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"){m(`[DeviceManager] Skipping unauthorized device: ${s}`);continue}t.push({serial:s,status:a})}return t}extractDisplayName(e){let t=e.get("ohos.qemu.hvd.name");if(t)return t;let r=e.get("const.product.name");if(r&&r!=="emulator")return r;let 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 ir(this.hdcPath,e,[...sp]);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:
31
31
  `+i.map(s=>` - ${s.name} (${s.device.serial})`).join(`
32
- `)):new Error(`Device "${t}" not found. Use \`devecocli device list\` to see available targets.`)}return e[0]}async getDeviceDetail(e){let t={serial:e,status:"device"};try{let r=await rr(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:Ln(e),r,o;try{let i=await rr(this.hdcPath,e,[...ip]);r=this.extractDisplayName(i),o=i.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:o}}};var Tt=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=te.from(e)}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;m(`Executing: ${r} ${e.join(" ")}`);try{let{stdout:o}=await hS(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/${mS()}`;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(`
33
- `).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 xc from"fs";import*as On from"path";function uo(n,e){if(!xc.existsSync(n))throw new Error(`Apply file list not found: ${n}`);let r=xc.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=On.resolve(e),i=new Set,s=[];for(let a of r){let c=On.resolve(o,a),l=On.isAbsolute(a)?On.relative(o,a):a;if(l.startsWith(".."))throw new Error(`File path is outside the project directory: ${a}`);let d=P.isPathContainedWithSymlink(l,o);if(!d.contained){if(!xc.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 Nc from"fs";import or from"path";import{execa as wS}from"execa";import sp from"fs";import*as ap from"path";import gS from"json5";function yS(n,e){try{let r=gS.parse(sp.readFileSync(n,"utf-8")).modules?.find(o=>o.name===e);return r?.srcPath?r.srcPath.replace(/^\.\//,""):null}catch(t){return m(`[apply] resolveModuleSrcPath fallback (module=${e}): ${t.message}`),null}}function yt(n,e){let t=ap.join(n,"build-profile.json5");return sp.existsSync(t)?yS(t,e)??e:e}import*as cp from"os";async function lp(n,e,t,r){let o={...process.env,DEVECO_SDK_HOME:n.sdkPath};if(n.javaPath){let c=or.dirname(n.javaPath);o.PATH=`${c}${or.delimiter}${process.env.PATH||""}`}b()&&(o.HVIGOR_USER_HOME=or.join(cp.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"];m(`[buildSignedHqf] ${n.nodePath} ${i.join(" ")}`);let s=await wS(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=>SS(e,c,r))}function dp(n,e,t){let r=yt(n,e);return or.join(n,r,"build",t,"outputs")}function vS(n,e,t){return or.join(dp(n,e,t),`${e}-${t}-signed.hqf`)}function SS(n,e,t){let r=dp(n,e,t),o=vS(n,e,t);if(Nc.existsSync(o))return o;let i=Lc(r,"-signed.hqf")??Lc(r,".hqf");if(!i)throw new Error(`Signed hqf not found at ${o} (and no *.hqf under ${r})`);return m(`[buildSignedHqf] signed hqf not at exact path, using fallback: ${i}`),i}function Lc(n,e){if(!Nc.existsSync(n))return null;for(let t of Nc.readdirSync(n,{withFileTypes:!0})){let r=or.join(n,t.name);if(t.isDirectory()){let o=Lc(r,e);if(o)return o}else if(t.isFile()&&t.name.endsWith(e))return r}return null}import V from"fs";import*as x from"path";import Oc from"json5";var up="default",ir=class n{static writeChangedFileLists(e,t,r,o){let i=t||up,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||up,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=x.normalize(a),l=n.classifyFile(c,t,r);if(l.fileClass==="unknown"){s.push(c);continue}let d=n.findModuleByFilePath(c,t,r);if(!d){s.push(c);continue}let h=n.resolveTargetModules(d,t,r,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=x.join(e,r,"build",t,"intermediates","patch","default"),s=x.join(i,"changedFileList.json");if(V.existsSync(s)||(V.mkdirSync(i,{recursive:!0}),V.writeFileSync(s,JSON.stringify({resources:{resFile:[],rawFile:[]},modifiedFiles:[]}),"utf-8")),!o)return;let a=x.join(e,r,"build",t,"intermediates","hotReload"),c=x.join(a,"changedFileList.json");V.existsSync(c)||(V.mkdirSync(a,{recursive:!0}),V.writeFileSync(c,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=x.join(e,"build-profile.json5");if(!V.existsSync(t))return null;try{let r=V.readFileSync(t,"utf-8");return Oc.parse(r)}catch{return null}}static classifyFile(e,t,r){let o=x.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=x.normalize(e);for(let i of r){let s=x.normalize(x.join(t,i.srcPath)),a=s+x.sep;if(o.startsWith(a)||o===s)return i}return null}static getModuleType(e,t){let r=x.join(e,t,"src","main","module.json5");if(!V.existsSync(r))return"entry";try{let o=V.readFileSync(r,"utf-8");return Oc.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=x.join(e,t,"oh-package.json5");if(!V.existsSync(r))return[];try{let o=V.readFileSync(r,"utf-8"),i=Oc.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=x.resolve(e,t,i);return o.find(l=>x.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=x.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=x.join(e,i,"build",r,"intermediates","hotReload","changedFileList.json"),a=n.readExistingApply(s),c=n.mergeApplyEntries(a,o),l=x.dirname(s);V.existsSync(l)||V.mkdirSync(l,{recursive:!0}),V.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),m(`[ChangedFileListWriter] Written hotReload: ${s} (${c.length} entries)`)}static readExistingApply(e){if(!V.existsSync(e))return[];try{let t=V.readFileSync(e,"utf-8");return JSON.parse(t)?.modifiedFilesV2||[]}catch{return[]}}static writePatchFile(e,t,r,o,i,s){let a=t.replace(/^\.\//,""),c=x.join(e,a,"build",r,"intermediates","patch","default","changedFileList.json"),l=n.readExistingPatch(c),d=x.join(e,a,"src","main","ets"),h=o.map(De=>n.resolveRelativePathForPatch(De,d)),w=n.mergeStrings(l.modifiedFiles,h),S=n.mergePatchResources(l.rawFile,i),k=n.mergePatchResources(l.resFile,s),re=x.dirname(c);V.existsSync(re)||V.mkdirSync(re,{recursive:!0}),V.writeFileSync(c,JSON.stringify({resources:{resFile:k,rawFile:S},modifiedFiles:w}),"utf-8"),m(`[ChangedFileListWriter] Written patch: ${c}`)}static readExistingPatch(e){if(!V.existsSync(e))return{modifiedFiles:[],rawFile:[],resFile:[]};try{let t=V.readFileSync(e,"utf-8"),r=JSON.parse(t);return{modifiedFiles:r?.modifiedFiles||[],rawFile:r?.resources?.rawFile||[],resFile:r?.resources?.resFile||[]}}catch{return{modifiedFiles:[],rawFile:[],resFile:[]}}}static resolveRelativePathForPatch(e,t){return x.relative(x.normalize(t),x.normalize(e)).replace(/\\/g,"/")}static mergeApplyEntries(e,t){let r=new Set,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 bS from"fs";import{randomUUID as ES}from"crypto";import{execa as PS}from"execa";var sr=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,r){for(let a of t)if(!bS.existsSync(a)){let c=`Signed hqf file not found: ${a}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}let i=`/data/local/tmp/${ES()}`,s=[];try{for(let a=0;a<t.length;a++){let c=`${i}/${r}_${a}.hqf`;s.push(c),await this.pushHqf(e,t[a],i,c)}return await this.executeQuickfix(e,s)}catch(a){let c=`hqf install error: ${a.message}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}finally{await this.runHdc(["-t",e,"shell","rm","-rf",i],!1)}}async pushHqf(e,t,r,o){console.log(`[Apply] Pushing hqf to device ${e}: ${t}`),await this.runHdc(["-t",e,"shell","mkdir","-p",r]);let i=await this.runHdc(["-t",e,"file","send",t,o]);if(!i.startsWith("FileTransfer finish"))throw new Error(`Failed to send hqf: ${i}`)}async executeQuickfix(e,t){console.log(`[Apply] Installing ${t.length} hqf patch(es) via quickfix...`);let r=["-t",e,"shell","bm","quickfix","-a","-f",...t,"-d"];await this.getApiVersion(e)>17&&r.push("-o");let i=await this.runHdc(r,!1);if(m(`[InstallHqf] quickfix output: ${i}`),/succe(?:ed|ss)/i.test(i))return console.log("[Apply] hqf installed successfully."),{success:!0,message:"hqf quickfix installed successfully."};let s=`hqf quickfix install failed. Device response: ${i||"(empty)"}. Please try reinstalling the application.`;return console.error(`[Apply] ${s}`),{success:!1,message:s}}async getApiVersion(e){try{let t=await this.runHdc(["-t",e,"shell","param","get","const.ohos.apiversion"],!1),r=parseInt(t.trim(),10);if(!isNaN(r))return console.log(`[InstallHqf] device API version: ${r}`),r}catch{}return 0}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;m(`[InstallHqf] Executing: ${r} ${e.join(" ")}`);try{let{stdout:o}=await PS(r,e,{env:{...process.env}});return o}catch(o){if(t)throw o;return o.stdout||""}}};var CS="6.1.1",Ji=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}toolProvider;projectRoot;async execute(e){await At(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion(CS);let t=uo(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=ir.writeChangedFileLists(this.projectRoot,e.productName,t);if(r.writtenModules.length===0)throw new Error("No changed files belong to a runnable module");return console.log(`[Apply] changeFileList written for: ${r.writtenModules.join(", ")}`),r.writtenModules}async buildHqf(e,t){return m(`[Apply] hvigor assembleDevHqf --no-daemon (modules=${t.join(",")})`),await lp(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 sr(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 Tt(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 Tt(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 pp from"fs";import*as F from"path";var Yi=class n{static generate(e,t,r,o){let i=yt(e,t),s=F.join(e,i),a=F.join(s,"build","config"),c=n.buildConfig(e,s,r,o);pp.mkdirSync(a,{recursive:!0}),pp.writeFileSync(F.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),m(`[BuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,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 fp from"fs";import*as j from"path";var Ki=class n{static generate(e,t,r,o){let i=yt(e,t),s=j.join(e,i),a=j.join(s,"build","config"),c=n.buildConfig(e,s,r,o);fp.mkdirSync(a,{recursive:!0}),fp.writeFileSync(j.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),m(`[HotReloadBuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,o){let i=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 mp from"crypto";import qe from"fs";import Ve from"path";import hp from"os";import{io as IS}from"socket.io-client";var AS=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),ar=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;qe.mkdirSync(Ve.dirname(o),{recursive:!0}),qe.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(`
32
+ `)):new Error(`Device "${t}" not found. Use \`devecocli device list\` to see available targets.`)}return e[0]}async getDeviceDetail(e){let t={serial:e,status:"device"};try{let r=await ir(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:On(e),r,o;try{let i=await ir(this.hdcPath,e,[...sp]);r=this.extractDisplayName(i),o=i.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:o}}};var xt=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=te.from(e)}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;m(`Executing: ${r} ${e.join(" ")}`);try{let{stdout:o}=await gS(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/${hS()}`;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(`
33
+ `).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 Nc from"fs";import*as Mn from"path";function mo(n,e){if(!Nc.existsSync(n))throw new Error(`Apply file list not found: ${n}`);let r=Nc.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=Mn.resolve(e),i=new Set,s=[];for(let a of r){let c=Mn.resolve(o,a),l=Mn.isAbsolute(a)?Mn.relative(o,a):a;if(l.startsWith(".."))throw new Error(`File path is outside the project directory: ${a}`);let d=D.isPathContainedWithSymlink(l,o);if(!d.contained){if(!Nc.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 Lc from"fs";import sr from"path";import{execa as vS}from"execa";import ap from"fs";import*as cp from"path";import yS from"json5";function wS(n,e){try{let r=yS.parse(ap.readFileSync(n,"utf-8")).modules?.find(o=>o.name===e);return r?.srcPath?r.srcPath.replace(/^\.\//,""):null}catch(t){return m(`[apply] resolveModuleSrcPath fallback (module=${e}): ${t.message}`),null}}function wt(n,e){let t=cp.join(n,"build-profile.json5");return ap.existsSync(t)?wS(t,e)??e:e}import*as lp from"os";async function dp(n,e,t,r){let o={...process.env,DEVECO_SDK_HOME:n.sdkPath};if(n.javaPath){let c=sr.dirname(n.javaPath);o.PATH=`${c}${sr.delimiter}${process.env.PATH||""}`}b()&&(o.HVIGOR_USER_HOME=sr.join(lp.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"];m(`[buildSignedHqf] ${n.nodePath} ${i.join(" ")}`);let s=await vS(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=>bS(e,c,r))}function up(n,e,t){let r=wt(n,e);return sr.join(n,r,"build",t,"outputs")}function SS(n,e,t){return sr.join(up(n,e,t),`${e}-${t}-signed.hqf`)}function bS(n,e,t){let r=up(n,e,t),o=SS(n,e,t);if(Lc.existsSync(o))return o;let i=Oc(r,"-signed.hqf")??Oc(r,".hqf");if(!i)throw new Error(`Signed hqf not found at ${o} (and no *.hqf under ${r})`);return m(`[buildSignedHqf] signed hqf not at exact path, using fallback: ${i}`),i}function Oc(n,e){if(!Lc.existsSync(n))return null;for(let t of Lc.readdirSync(n,{withFileTypes:!0})){let r=sr.join(n,t.name);if(t.isDirectory()){let o=Oc(r,e);if(o)return o}else if(t.isFile()&&t.name.endsWith(e))return r}return null}import V from"fs";import*as x from"path";import Mc from"json5";var pp="default",ar=class n{static writeChangedFileLists(e,t,r,o){let i=t||pp,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||pp,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=x.normalize(a),l=n.classifyFile(c,t,r);if(l.fileClass==="unknown"){s.push(c);continue}let d=n.findModuleByFilePath(c,t,r);if(!d){s.push(c);continue}let h=n.resolveTargetModules(d,t,r,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=x.join(e,r,"build",t,"intermediates","patch","default"),s=x.join(i,"changedFileList.json");if(V.existsSync(s)||(V.mkdirSync(i,{recursive:!0}),V.writeFileSync(s,JSON.stringify({resources:{resFile:[],rawFile:[]},modifiedFiles:[]}),"utf-8")),!o)return;let a=x.join(e,r,"build",t,"intermediates","hotReload"),c=x.join(a,"changedFileList.json");V.existsSync(c)||(V.mkdirSync(a,{recursive:!0}),V.writeFileSync(c,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=x.join(e,"build-profile.json5");if(!V.existsSync(t))return null;try{let r=V.readFileSync(t,"utf-8");return Mc.parse(r)}catch{return null}}static classifyFile(e,t,r){let o=x.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=x.normalize(e);for(let i of r){let s=x.normalize(x.join(t,i.srcPath)),a=s+x.sep;if(o.startsWith(a)||o===s)return i}return null}static getModuleType(e,t){let r=x.join(e,t,"src","main","module.json5");if(!V.existsSync(r))return"entry";try{let o=V.readFileSync(r,"utf-8");return Mc.parse(o)?.module?.type||"entry"}catch{return"entry"}}static buildReverseDependencyMap(e,t){let r=new Map;for(let o of t){let i=n.readLocalDependencies(e,o.srcPath);for(let s of i){let a=r.get(s)||[];a.includes(o.name)||a.push(o.name),r.set(s,a)}}return r}static readLocalDependencies(e,t){let r=x.join(e,t,"oh-package.json5");if(!V.existsSync(r))return[];try{let o=V.readFileSync(r,"utf-8"),i=Mc.parse(o);return n.resolveDepModuleNames(e,t,i.dependencies||{})}catch{return[]}}static resolveDepModuleNames(e,t,r){let o=n.loadBuildProfile(e);if(!o)return[];let i=o.modules,s=[];for(let a of Object.values(r)){if(typeof a!="string")continue;let c=n.tryResolveDepModule(e,t,a,i);c&&s.push(c)}return s}static tryResolveDepModule(e,t,r,o){let i=r;if(!(i.startsWith("file:")||i.startsWith(".")||i.startsWith("..")))return null;i.startsWith("file:")&&(i=i.substring(5));let a=x.resolve(e,t,i);return o.find(l=>x.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=x.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=x.join(e,i,"build",r,"intermediates","hotReload","changedFileList.json"),a=n.readExistingApply(s),c=n.mergeApplyEntries(a,o),l=x.dirname(s);V.existsSync(l)||V.mkdirSync(l,{recursive:!0}),V.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),m(`[ChangedFileListWriter] Written hotReload: ${s} (${c.length} entries)`)}static readExistingApply(e){if(!V.existsSync(e))return[];try{let t=V.readFileSync(e,"utf-8");return JSON.parse(t)?.modifiedFilesV2||[]}catch{return[]}}static writePatchFile(e,t,r,o,i,s){let a=t.replace(/^\.\//,""),c=x.join(e,a,"build",r,"intermediates","patch","default","changedFileList.json"),l=n.readExistingPatch(c),d=x.join(e,a,"src","main","ets"),h=o.map(Re=>n.resolveRelativePathForPatch(Re,d)),w=n.mergeStrings(l.modifiedFiles,h),S=n.mergePatchResources(l.rawFile,i),k=n.mergePatchResources(l.resFile,s),re=x.dirname(c);V.existsSync(re)||V.mkdirSync(re,{recursive:!0}),V.writeFileSync(c,JSON.stringify({resources:{resFile:k,rawFile:S},modifiedFiles:w}),"utf-8"),m(`[ChangedFileListWriter] Written patch: ${c}`)}static readExistingPatch(e){if(!V.existsSync(e))return{modifiedFiles:[],rawFile:[],resFile:[]};try{let t=V.readFileSync(e,"utf-8"),r=JSON.parse(t);return{modifiedFiles:r?.modifiedFiles||[],rawFile:r?.resources?.rawFile||[],resFile:r?.resources?.resFile||[]}}catch{return{modifiedFiles:[],rawFile:[],resFile:[]}}}static resolveRelativePathForPatch(e,t){return x.relative(x.normalize(t),x.normalize(e)).replace(/\\/g,"/")}static mergeApplyEntries(e,t){let r=new Set,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 ES from"fs";import{randomUUID as PS}from"crypto";import{execa as CS}from"execa";var cr=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,r){for(let a of t)if(!ES.existsSync(a)){let c=`Signed hqf file not found: ${a}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}let i=`/data/local/tmp/${PS()}`,s=[];try{for(let a=0;a<t.length;a++){let c=`${i}/${r}_${a}.hqf`;s.push(c),await this.pushHqf(e,t[a],i,c)}return await this.executeQuickfix(e,s)}catch(a){let c=`hqf install error: ${a.message}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}finally{await this.runHdc(["-t",e,"shell","rm","-rf",i],!1)}}async pushHqf(e,t,r,o){console.log(`[Apply] Pushing hqf to device ${e}: ${t}`),await this.runHdc(["-t",e,"shell","mkdir","-p",r]);let i=await this.runHdc(["-t",e,"file","send",t,o]);if(!i.startsWith("FileTransfer finish"))throw new Error(`Failed to send hqf: ${i}`)}async executeQuickfix(e,t){console.log(`[Apply] Installing ${t.length} hqf patch(es) via quickfix...`);let r=["-t",e,"shell","bm","quickfix","-a","-f",...t,"-d"];await this.getApiVersion(e)>17&&r.push("-o");let i=await this.runHdc(r,!1);if(m(`[InstallHqf] quickfix output: ${i}`),/succe(?:ed|ss)/i.test(i))return console.log("[Apply] hqf installed successfully."),{success:!0,message:"hqf quickfix installed successfully."};let s=`hqf quickfix install failed. Device response: ${i||"(empty)"}. Please try reinstalling the application.`;return console.error(`[Apply] ${s}`),{success:!1,message:s}}async getApiVersion(e){try{let t=await this.runHdc(["-t",e,"shell","param","get","const.ohos.apiversion"],!1),r=parseInt(t.trim(),10);if(!isNaN(r))return console.log(`[InstallHqf] device API version: ${r}`),r}catch{}return 0}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;m(`[InstallHqf] Executing: ${r} ${e.join(" ")}`);try{let{stdout:o}=await CS(r,e,{env:{...process.env}});return o}catch(o){if(t)throw o;return o.stdout||""}}};var IS="6.1.1",Ki=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}toolProvider;projectRoot;async execute(e){await Rt(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion(IS);let t=mo(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=ar.writeChangedFileLists(this.projectRoot,e.productName,t);if(r.writtenModules.length===0)throw new Error("No changed files belong to a runnable module");return console.log(`[Apply] changeFileList written for: ${r.writtenModules.join(", ")}`),r.writtenModules}async buildHqf(e,t){return m(`[Apply] hvigor assembleDevHqf --no-daemon (modules=${t.join(",")})`),await dp(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 cr(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 xt(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 xt(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 fp from"fs";import*as F from"path";var Xi=class n{static generate(e,t,r,o){let i=wt(e,t),s=F.join(e,i),a=F.join(s,"build","config"),c=n.buildConfig(e,s,r,o);fp.mkdirSync(a,{recursive:!0}),fp.writeFileSync(F.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),m(`[BuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,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 mp from"fs";import*as j from"path";var Zi=class n{static generate(e,t,r,o){let i=wt(e,t),s=j.join(e,i),a=j.join(s,"build","config"),c=n.buildConfig(e,s,r,o);mp.mkdirSync(a,{recursive:!0}),mp.writeFileSync(j.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),m(`[HotReloadBuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,o){let i=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 hp from"crypto";import Ve from"fs";import Je from"path";import gp from"os";import{io as AS}from"socket.io-client";var DS=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),lr=class n{projectRoot;toolProvider;cachedSocket=null;cachedDaemonPort=0;constructor(e,t){this.projectRoot=e,this.toolProvider=t}async sendHotCompile(e){await this.waitForDaemonReady();let t=this.findProjectDaemon();if(!t?.sessionId)throw new Error("No running hvigor daemon with sessionId found. Run `devecocli run --hotreload` first.");return this.sendViaSocket(t,e)}async startWatchSession(e){await this.waitForDaemonReady(),console.log(`[DaemonClient] Compiling, build with: ${JSON.stringify(e)}`);let t=this.findProjectDaemon();if(!t?.sessionId)throw new Error("No running hvigor daemon with sessionId found. Build the hap first.");let r=await this.getOrCreateSocket(t),o=this.watchLogPath;Ve.mkdirSync(Je.dirname(o),{recursive:!0}),Ve.writeFileSync(o,"");let i=this.createWatchLogBuffer(o);r.on("WatchLog",i.onWatchLog),r.on("WatchResult",i.onWatchResult),await this.awaitInitialBuild(r,e)}createWatchLogBuffer(e){let r=[];return{onWatchLog:s=>{let a=n.extractText(s);a.trim()&&(r.push(a.endsWith(`
34
34
  `)?a:a+`
35
- `),r.length>100&&r.shift())},onWatchResult:s=>{let a=n.extractText(s);if(!a.trim())return;let c=`[WatchResult] ${a}`;console.log(c),qe.writeFileSync(e,[...r,c+`
36
- `].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 Ve.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=IS(`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(`
35
+ `),r.length>100&&r.shift())},onWatchResult:s=>{let a=n.extractText(s);if(!a.trim())return;let c=`[WatchResult] ${a}`;console.log(c),Ve.writeFileSync(e,[...r,c+`
36
+ `].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 Je.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=AS(`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(`
37
37
  `)?"":`
38
- `))},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(!qe.existsSync(e))return null;try{let t=qe.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=Ve.join(t,"fd"),o=Ve.join(t,"ac"),i=Ve.join(t,"ce"),s=this.readComponents(r),a=this.xorBuffers([s[0],s[1],s[2],Buffer.from(AS)]),c=this.readSingleFile(o),l=mp.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=mp.createDecipheriv("aes-128-gcm",e,i);return l.setAuthTag(c),Buffer.concat([l.update(a),l.final()])}readComponents(e){let t=qe.readdirSync(e).map(r=>Ve.join(e,r)).filter(r=>qe.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=qe.readdirSync(r);if(o.length===0)throw new Error(`No file in ${r}`);return qe.readFileSync(Ve.join(r,o[0]))})}readSingleFile(e){let t=qe.readdirSync(e).map(r=>Ve.join(e,r)).filter(r=>qe.statSync(r).isFile());if(t.length===0)throw new Error(`No file in ${e}`);return qe.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||Ve.join(hp.homedir(),".hvigor");return Ve.join(e,"daemon","cache","daemon-sec.json")}getMetaDir(){let e=process.env.HVIGOR_USER_HOME||Ve.join(hp.homedir(),".hvigor");return Ve.join(e,"meta")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}};import wp from"fs";import*as kt from"path";import{green as es,yellow as Mc}from"colorette";import Mn from"fs";import*as _n from"path";import DS from"json5";var RS=2e6,TS=1e6,kS="hotreload",Xi=class n{static generateOrUpdate(e,t,r){let o=n.readAppConfig(e),i=_n.resolve(e,t),s=_n.join(i,"patch.json"),a;return Mn.existsSync(s)?(m(`[PatchManager] patch.json found at ${s}, incrementing patchVersionCode`),a=n.readExistingPatch(s),a.app.patchVersionCode+=1):(m(`[PatchManager] patch.json not found, generating new one at ${s}`),a={app:{bundleName:o.bundleName,patchVersionCode:RS,versionCode:o.versionCode},module:{name:r,type:kS}}),n.writePatchJson(s,a),a}static readAppConfig(e){let t=_n.join(e,"AppScope","app.json5");if(!Mn.existsSync(t))throw new Error(`AppScope/app.json5 not found at ${t}. Unable to read bundleName and versionCode.`);let r=Mn.readFileSync(t,"utf-8"),o=DS.parse(r),i=o?.app?.bundleName;if(!i)throw new Error("bundleName is missing in AppScope/app.json5");let s=o?.app?.versionCode??TS;return{bundleName:i,versionCode:s}}static readExistingPatch(e){let t=Mn.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=_n.dirname(e);Mn.existsSync(r)||Mn.mkdirSync(r,{recursive:!0});let o=JSON.stringify(t,null,2);Mn.writeFileSync(e,o,"utf-8"),m(`[PatchManager] patch.json written to ${e}`),m(`[PatchManager] Content: ${o}`)}};import pe from"fs";import*as $ from"path";import gp from"crypto";import xS from"json5";import{execa as yp}from"execa";var Zi=class n{static COMPONENT=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]);static DIRS=["fd","ac","ce"];static decryptPwd(e,t,r){if(t.length<32||t.length%2!==0)throw new Error(`Invalid encrypted password for ${r}`);m(`[DecipherUtil] Decrypting ${r}, encrypted length: ${t.length}`);let o=$.resolve(e,"material"),i=n.getKey(o,r),s=new Int8Array(Buffer.from(t,"hex"));return m(`[DecipherUtil] Data length: ${s.length}, key length: ${i.length}`),n.decrypt(i,s).toString("utf-8")}static getKey(e,t){let r=$.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=gp.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=gp.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=pe.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(pe.statSync(e).isDirectory()){let o=pe.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(pe.readFileSync($.join(e,o[0])))}return new Int8Array(pe.readFileSync(e))}},Qi=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(pe.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(!pe.existsSync(e))return null;let t=pe.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=yt(this.projectRoot,e),o=$.join(this.projectRoot,r,"build",t,"outputs","default");return pe.existsSync(o)||pe.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"];m(`[GenSignHqf] Packing: ${s} ${a.join(" ")}`);try{let c=Date.now(),l=await yp(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):pe.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;m(`[GenSignHqf] Signing: ${i} ${o.join(" ")}`);try{let s=Date.now(),a=await yp(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}`):pe.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=Zi.decryptPwd(r,t.storePassword,"storePassword"),i=Zi.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 pe.existsSync(r)?t:null}readSigningConfig(e){let t=$.join(this.projectRoot,"build-profile.json5");if(!pe.existsSync(t))return null;try{let r=pe.readFileSync(t,"utf-8"),o=xS.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(pe.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(pe.existsSync(r))return r;return null}};async function vp(n){let e=Date.now(),t=yt(n.projectPath,n.moduleName),r=NS(n);console.log(Mc("[HotReload] Ensure the project source is trusted before proceeding."));let o=LS(n),i=uo(r,n.projectPath);console.log(`[HotReload] Parsed ${i.length} changed file(s) from ${n.applyFileName}`),OS(n,i),MS(n,t),await _S(n,o);let s=kt.join(n.projectPath,t,"patch.json"),a=await jS(n,t,s);return await HS(n,a),console.log(es("[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 NS(n){if(kt.basename(n.applyFileName)!==n.applyFileName)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${n.applyFileName}`);return kt.join(n.projectPath,".hvigor",n.applyFileName)}function LS(n){let{projectPath:e,toolProvider:t}=n,r=new ar(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 OS(n,e){let t=ir.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(es(`[HotReload] changedFileList written for: ${t.writtenModules.join(", ")}`)),t.skippedFiles.length>0&&console.warn(Mc(`[HotReload] skipped ${t.skippedFiles.length} file(s)`))}function MS(n,e){let t=Xi.generateOrUpdate(n.projectPath,e,n.moduleName);console.log(es(`[HotReload] patch.json ready (patchVersionCode=${t.app.patchVersionCode})`))}async function _S(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=FS(r);throw new Error(`Daemon hot compile exited with code ${o}`+(i?`
38
+ `))},onWatchResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchResult] ${a}`)},onWatchCompileResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileResult] ${a}`)},onWatchCompileData:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileData] ${a}`)}}}createOutputHandler(){return e=>{let t=typeof e.text=="string"?e.text:Buffer.from(e.text).toString(e.encoding??"utf-8");t.trim()&&(e.type==="stderr"?process.stderr.write(t):process.stdout.write(t))}}buildCompileOptions(e){let t={_:["assembleDevHqf"],daemon:!0,hotCompile:!0,mode:"module",prop:[`module=${e.moduleSpecs.join(",")}`,`product=${e.productName}`,"debuggable=true","hotReload=true","requiredDeviceType=phone"],parallel:!0,incremental:!0,analyze:"normal",env:{DEVECO_SDK_HOME:this.toolProvider.sdkPath}};return console.log("[DaemonClient] buildCompileOptions:",JSON.stringify(t,null,2)),t}async waitForDaemonReady(){let r=Date.now();for(;Date.now()-r<3e4;){let o=this.findProjectDaemon();if(o&&(o.state==="half_busy"||o.state==="idle"))return;await new Promise(i=>setTimeout(i,1e3))}throw new Error("No running hvigor daemon found. Run `devecocli run --hotreload` first.")}findProjectDaemon(){let e=this.getRegistryPath();if(!Ve.existsSync(e))return null;try{let t=Ve.readFileSync(e,"utf-8"),r=JSON.parse(t),o=Object.values(r).filter(i=>i.cwdPath===this.projectRoot&&(i.state==="idle"||i.state==="half_busy"||i.state==="busy")&&this.isProcessAlive(i.pid));return o.length>0?o[o.length-1]:null}catch{return null}}decryptSessionId(e){let t=this.getMetaDir(),r=Je.join(t,"fd"),o=Je.join(t,"ac"),i=Je.join(t,"ce"),s=this.readComponents(r),a=this.xorBuffers([s[0],s[1],s[2],Buffer.from(DS)]),c=this.readSingleFile(o),l=hp.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=hp.createDecipheriv("aes-128-gcm",e,i);return l.setAuthTag(c),Buffer.concat([l.update(a),l.final()])}readComponents(e){let t=Ve.readdirSync(e).map(r=>Je.join(e,r)).filter(r=>Ve.statSync(r).isDirectory()).sort();if(t.length<3)throw new Error(`Expected 3 subdirectories in ${e}, found ${t.length}`);return t.slice(0,3).map(r=>{let o=Ve.readdirSync(r);if(o.length===0)throw new Error(`No file in ${r}`);return Ve.readFileSync(Je.join(r,o[0]))})}readSingleFile(e){let t=Ve.readdirSync(e).map(r=>Je.join(e,r)).filter(r=>Ve.statSync(r).isFile());if(t.length===0)throw new Error(`No file in ${e}`);return Ve.readFileSync(t[0])}xorBuffers(e){let t=Buffer.alloc(e[0].length);t.set(e[0]);for(let r=1;r<e.length;r++){let o=Buffer.isBuffer(e[r])?e[r]:Buffer.from(e[r]);for(let i=0;i<t.length;i++)t[i]^=o[i]}return t}getRegistryPath(){let e=process.env.HVIGOR_USER_HOME||Je.join(gp.homedir(),".hvigor");return Je.join(e,"daemon","cache","daemon-sec.json")}getMetaDir(){let e=process.env.HVIGOR_USER_HOME||Je.join(gp.homedir(),".hvigor");return Je.join(e,"meta")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}};import vp from"fs";import*as Nt from"path";import{green as ns,yellow as _c}from"colorette";import _n from"fs";import*as Fn from"path";import RS from"json5";var TS=2e6,kS=1e6,xS="hotreload",Qi=class n{static generateOrUpdate(e,t,r){let o=n.readAppConfig(e),i=Fn.resolve(e,t),s=Fn.join(i,"patch.json"),a;return _n.existsSync(s)?(m(`[PatchManager] patch.json found at ${s}, incrementing patchVersionCode`),a=n.readExistingPatch(s),a.app.patchVersionCode+=1):(m(`[PatchManager] patch.json not found, generating new one at ${s}`),a={app:{bundleName:o.bundleName,patchVersionCode:TS,versionCode:o.versionCode},module:{name:r,type:xS}}),n.writePatchJson(s,a),a}static readAppConfig(e){let t=Fn.join(e,"AppScope","app.json5");if(!_n.existsSync(t))throw new Error(`AppScope/app.json5 not found at ${t}. Unable to read bundleName and versionCode.`);let r=_n.readFileSync(t,"utf-8"),o=RS.parse(r),i=o?.app?.bundleName;if(!i)throw new Error("bundleName is missing in AppScope/app.json5");let s=o?.app?.versionCode??kS;return{bundleName:i,versionCode:s}}static readExistingPatch(e){let t=_n.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=Fn.dirname(e);_n.existsSync(r)||_n.mkdirSync(r,{recursive:!0});let o=JSON.stringify(t,null,2);_n.writeFileSync(e,o,"utf-8"),m(`[PatchManager] patch.json written to ${e}`),m(`[PatchManager] Content: ${o}`)}};import fe from"fs";import*as $ from"path";import yp from"crypto";import NS from"json5";import{execa as wp}from"execa";var es=class n{static COMPONENT=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]);static DIRS=["fd","ac","ce"];static decryptPwd(e,t,r){if(t.length<32||t.length%2!==0)throw new Error(`Invalid encrypted password for ${r}`);m(`[DecipherUtil] Decrypting ${r}, encrypted length: ${t.length}`);let o=$.resolve(e,"material"),i=n.getKey(o,r),s=new Int8Array(Buffer.from(t,"hex"));return m(`[DecipherUtil] Data length: ${s.length}, key length: ${i.length}`),n.decrypt(i,s).toString("utf-8")}static getKey(e,t){let r=$.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=yp.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=yp.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=fe.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(fe.statSync(e).isDirectory()){let o=fe.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(fe.readFileSync($.join(e,o[0])))}return new Int8Array(fe.readFileSync(e))}},ts=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(fe.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(!fe.existsSync(e))return null;let t=fe.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=wt(this.projectRoot,e),o=$.join(this.projectRoot,r,"build",t,"outputs","default");return fe.existsSync(o)||fe.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"];m(`[GenSignHqf] Packing: ${s} ${a.join(" ")}`);try{let c=Date.now(),l=await wp(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):fe.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;m(`[GenSignHqf] Signing: ${i} ${o.join(" ")}`);try{let s=Date.now(),a=await wp(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}`):fe.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=es.decryptPwd(r,t.storePassword,"storePassword"),i=es.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 fe.existsSync(r)?t:null}readSigningConfig(e){let t=$.join(this.projectRoot,"build-profile.json5");if(!fe.existsSync(t))return null;try{let r=fe.readFileSync(t,"utf-8"),o=NS.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(fe.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(fe.existsSync(r))return r;return null}};async function Sp(n){let e=Date.now(),t=wt(n.projectPath,n.moduleName),r=LS(n);console.log(_c("[HotReload] Ensure the project source is trusted before proceeding."));let o=OS(n),i=mo(r,n.projectPath);console.log(`[HotReload] Parsed ${i.length} changed file(s) from ${n.applyFileName}`),MS(n,i),_S(n,t),await FS(n,o);let s=Nt.join(n.projectPath,t,"patch.json"),a=await HS(n,t,s);return await $S(n,a),console.log(ns("[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 LS(n){if(Nt.basename(n.applyFileName)!==n.applyFileName)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${n.applyFileName}`);return Nt.join(n.projectPath,".hvigor",n.applyFileName)}function OS(n){let{projectPath:e,toolProvider:t}=n,r=new lr(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 MS(n,e){let t=ar.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(ns(`[HotReload] changedFileList written for: ${t.writtenModules.join(", ")}`)),t.skippedFiles.length>0&&console.warn(_c(`[HotReload] skipped ${t.skippedFiles.length} file(s)`))}function _S(n,e){let t=Qi.generateOrUpdate(n.projectPath,e,n.moduleName);console.log(ns(`[HotReload] patch.json ready (patchVersionCode=${t.app.patchVersionCode})`))}async function FS(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=jS(r);throw new Error(`Daemon hot compile exited with code ${o}`+(i?`
39
39
  --- compile output (from watch session) ---
40
- ${i}`:""))}}finally{e.disconnect()}console.log(`[Timing] daemon hot compile: ${Date.now()-t}ms`)}function FS(n){try{return wp.existsSync(n)?wp.readFileSync(n,"utf8").split(/\r?\n/).filter(t=>t.trim()).slice(-40).join(`
41
- `):""}catch{return""}}async function jS(n,e,t){let r=kt.join(n.projectPath,e,"build",n.productName,"intermediates"),o=[kt.join(r,"hotReload","patchAbcPath"),kt.join(r,"patch","default")],i=Date.now(),s=new Qi(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 HS(n,e){let t=Date.now(),o=await new sr(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 _c(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 Sp(n,e,t){let r=kt.join(n.rootDir,".hvigor",t),o;try{o=uo(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(Mc(`[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 bp(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 Ep(n,e){await new Te(n,e.rootDir).stopDaemon(),console.log(es("Hvigor daemon stopped."))}import{execa as Hc}from"execa";import*as Pp from"readline/promises";import{stdin as zS,stdout as qS}from"process";import{green as cr,red as rs,yellow as $c}from"colorette";import ns from"fs";import*as fo from"path";import VS from"json5";var $S=[{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"}],po={productIndex:0,productName:"phone",productType:"phone",subProductType:"phone"};async function US(){return[]}async function Fc(){let n=await US();return n.length>0?n:$S}function ts(n){return n.toLowerCase().replace(/[\s\W]+/g,"")}var BS={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 WS(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 GS(n,e){let t=n.map(i=>({spec:i,dist:WS(e,ts(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 jc(n,e){if(/[\u4e00-\u9fff\u3400-\u4dbf\u3040-\u30ff\uac00-\ud7af]/.test(e))return{matchType:"none"};let t=ts(e);if(t.length===0)return{matchType:"none"};let r=n.find(a=>ts(a.productName)===t);if(r)return{spec:r,matchedName:r.productName,matchType:"exact"};let o=BS[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=ts(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=GS(n,t);return s||{matchType:"none"}}async function JS(n){for(let e of n){let{stdout:t}=await Hc("tasklist",["/FI",`IMAGENAME eq ${e}`,"/FO","CSV","/NH"],{reject:!1});if(t.toLowerCase().includes(e.toLowerCase()))return!0}return!1}async function YS(){try{let n=pc();if(n==="win32")return JS(["devecostudio64.exe","devecostudio.exe"]);if(n==="darwin"){let{stdout:e}=await Hc("pgrep",["-x","DevEco Studio"],{reject:!1});return e.trim().length>0}if(n==="openharmony"||n==="linux"){let{stdout:e}=await Hc("pgrep",["-f","com.huawei.devecostudio"],{reject:!1});return e.trim().length>0}}catch{}return!1}async function KS(n,e){if(!b()){if(await YS()){console.log("DevEco Studio is already running.");return}throw new Error(`DevEco Studio is not running. The previewer requires DevEco Studio to be running.
40
+ ${i}`:""))}}finally{e.disconnect()}console.log(`[Timing] daemon hot compile: ${Date.now()-t}ms`)}function jS(n){try{return vp.existsSync(n)?vp.readFileSync(n,"utf8").split(/\r?\n/).filter(t=>t.trim()).slice(-40).join(`
41
+ `):""}catch{return""}}async function HS(n,e,t){let r=Nt.join(n.projectPath,e,"build",n.productName,"intermediates"),o=[Nt.join(r,"hotReload","patchAbcPath"),Nt.join(r,"patch","default")],i=Date.now(),s=new ts(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 $S(n,e){let t=Date.now(),o=await new cr(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 Fc(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 bp(n,e,t){let r=Nt.join(n.rootDir,".hvigor",t),o;try{o=mo(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(_c(`[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 Ep(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 Pp(n,e){await new ke(n,e.rootDir).stopDaemon(),console.log(ns("Hvigor daemon stopped."))}import{execa as $c}from"execa";import*as Cp from"readline/promises";import{stdin as qS,stdout as VS}from"process";import{green as dr,red as is,yellow as Uc}from"colorette";import os from"fs";import*as go from"path";import JS from"json5";var US=[{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"}],ho={productIndex:0,productName:"phone",productType:"phone",subProductType:"phone"};async function BS(){return[]}async function jc(){let n=await BS();return n.length>0?n:US}function rs(n){return n.toLowerCase().replace(/[\s\W]+/g,"")}var WS={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 GS(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 zS(n,e){let t=n.map(i=>({spec:i,dist:GS(e,rs(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 Hc(n,e){if(/[\u4e00-\u9fff\u3400-\u4dbf\u3040-\u30ff\uac00-\ud7af]/.test(e))return{matchType:"none"};let t=rs(e);if(t.length===0)return{matchType:"none"};let r=n.find(a=>rs(a.productName)===t);if(r)return{spec:r,matchedName:r.productName,matchType:"exact"};let o=WS[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=rs(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=zS(n,t);return s||{matchType:"none"}}async function YS(n){for(let e of n){let{stdout:t}=await $c("tasklist",["/FI",`IMAGENAME eq ${e}`,"/FO","CSV","/NH"],{reject:!1});if(t.toLowerCase().includes(e.toLowerCase()))return!0}return!1}async function KS(){try{let n=fc();if(n==="win32")return YS(["devecostudio64.exe","devecostudio.exe"]);if(n==="darwin"){let{stdout:e}=await $c("pgrep",["-x","DevEco Studio"],{reject:!1});return e.trim().length>0}if(n==="openharmony"||n==="linux"){let{stdout:e}=await $c("pgrep",["-f","com.huawei.devecostudio"],{reject:!1});return e.trim().length>0}}catch{}return!1}async function XS(n,e){if(!b()){if(await KS()){console.log("DevEco Studio is already running.");return}throw new Error(`DevEco Studio is not running. The previewer requires DevEco Studio to be running.
42
42
  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.
43
- Please start DevEco Studio manually, then retry.`)}async function XS(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 Cp(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 XS(t,e))return!1;let r=await Fc(),o=r.length>0?r:[po];return t.every(i=>jc(o,i).spec!==void 0)}function ZS(n,e){if(!n)return[e[0]||po];let t=n.split(",").map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0)return[e[0]||po];let r=[],o=[];for(let i of t){let s=jc(e,i);if(s.spec)r.push(s.spec),s.matchType==="fuzzy"?console.warn($c(` [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:
43
+ Please start DevEco Studio manually, then retry.`)}async function ZS(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 Ip(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 ZS(t,e))return!1;let r=await jc(),o=r.length>0?r:[ho];return t.every(i=>Hc(o,i).spec!==void 0)}function QS(n,e){if(!n)return[e[0]||ho];let t=n.split(",").map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0)return[e[0]||ho];let r=[],o=[];for(let i of t){let s=Hc(e,i);if(s.spec)r.push(s.spec),s.matchType==="fuzzy"?console.warn(Uc(` [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:
44
44
  `+s.ambiguous.map(a=>` - ${a}`).join(`
45
45
  `)+`
46
46
  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(", ")}
47
- Available: ${i}`)}return QS(r)}function QS(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 eb(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=Pp.createInterface({input:zS,output:qS});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(cr(`Connected to local device: ${r}`)),r}}catch{}finally{e.close()}}async function tb(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($c(`DEVECO_HDC_PORT=${t} but connect failed, trying other methods...`))}}let r=await n.listRawTargets();if(r.length>0){let i=r[0];return m(`[preview] Found existing target: ${i}`),i}let o=await eb(n);if(o)return o;throw new Error(`Cannot connect to local HarmonyOS device.
47
+ Available: ${i}`)}return eb(r)}function eb(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 tb(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=Cp.createInterface({input:qS,output:VS});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(dr(`Connected to local device: ${r}`)),r}}catch{}finally{e.close()}}async function nb(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(Uc(`DEVECO_HDC_PORT=${t} but connect failed, trying other methods...`))}}let r=await n.listRawTargets();if(r.length>0){let i=r[0];return m(`[preview] Found existing target: ${i}`),i}let o=await tb(n);if(o)return o;throw new Error(`Cannot connect to local HarmonyOS device.
48
48
  Please either:
49
49
  1. Run with --device 127.0.0.1:<port>, or
50
50
  2. Set DEVECO_HDC_PORT env var, or
51
- 3. Open wireless debugging in system settings first.`)}async function nb(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(`
52
- `))}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 rb(n){if(!ns.existsSync(n))throw new Error(`app.json5 not found at ${n}`);let e=ns.readFileSync(n,"utf8"),t=VS.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},ns.writeFileSync(n,JSON.stringify(t,null,2),"utf8"),console.log(`[multi-preview] Injected multiAppMode into ${fo.basename(n)}`),()=>{ns.writeFileSync(n,e,"utf8"),console.log(`[multi-preview] Restored original ${fo.basename(n)}`)})}async function ob(n,e,t,r,o,i){let s=fo.join(e.rootDir,"AppScope","app.json5"),a=rb(s);try{let c=n.product||"default",l=n.buildMode||"debug",d="default",h=o.includes("127.0.0.1")||o.includes("localhost");console.log(`
53
- [multi-preview] Building with multiAppMode (appClone) for multi-instance preview...`);let w=new Jt(t,e.rootDir),S=new Te(t,e.rootDir),re=e.collectNonHarDependentModuleList(i).map(gu=>`${gu}@${d}`),De=ao(e,re),Pe={type:"modules",modulesToBuild:re,moduleTasks:De};await At(e.rootDir,async()=>{await co(w,S,c,l,Pe,e.rootDir)},()=>console.log("Another build is already running. Waiting...")),console.log(cr("[multi-preview] Build completed."));let We=e.findArtifactPath(i,d,h,c);console.log(`[multi-preview] Installing multiAppMode hap to ${o}...`),await r.installApp(o,[We]),console.log(cr("[multi-preview] Installed multiAppMode hap."))}finally{a()}}function ib(n,e,t,r,o,i,s){console.log(`
54
- Launching DevEco Studio previewer on ${n}...`),console.log(` bundleName : ${e}`),console.log(` abilityName : ${t}`),console.log(` moduleName : ${r}`),console.log(` instanceId : ${o}`),console.log(` mode : ${i?"multi":"single"}`),console.log(` previewers : ${s.map(a=>a.productName).join(", ")}`)}async function sb(n,e,t,r,o,i,s,a){let c=[];for(let l=0;l<e.length;l++){let d=e[l],h=t?l:-1;console.log(`
55
- [${l+1}/${e.length}] Launching ${d.productName} (${d.productType}/${d.subProductType})...`);try{let w=await n.launchPreview(r,o,i,d.productName,d.productType,s,d.subProductType,a,h),S=/start ability successfully/i.test(w);c.push({name:d.productName,success:S,output:w}),S?console.log(cr(` \u2713 ${d.productName}: ${w.trim()}`)):console.error(rs(` \u2717 ${d.productName}: ${w.trim()}`))}catch(w){let S=w.message;c.push({name:d.productName,success:!1,output:S}),console.error(rs(` \u2717 ${d.productName}: ${S}`))}}return c}function ab(n){console.log(`
56
- `+"\u2500".repeat(50));let e=n.filter(r=>r.success).length,t=n.length-e;console.log(`Previewer launch summary: ${cr(String(e))} succeeded, ${t>0?rs(String(t)):"0"} failed.`);for(let r of n){let o=r.success?cr("\u2713"):rs("\u2717");console.log(` ${o} ${r.name}`)}return t===0}async function Ip(n,e,t,r,o,i){let s=await Fc(),a=s.length>0?s:[po],c=ZS(n.device,a),l=c.length>1,d;if(b()){let Pe=(await r.listRawTargets()).find(We=>We.includes("127.0.0.1:"));Pe?(d=Pe,console.log(`Using self-connected device: ${d}`)):(console.warn($c("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 tb(r,void 0))}else d=await nb(o,void 0);l&&await ob(n,e,t,r,d,i),await KS(r,d);let h=e.getBundleName(),w=e.getMainAbility(i,n.ability),S=e.getModuleName(i),k=process.pid;ib(d,h,w,S,k,l,c);let re=await sb(r,c,l,d,h,w,S,k);return ab(re)}function Uc(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 ss(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. Specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+o.map(i=>` - ${i.name} (${i.serial})`).join(`
57
- `))}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 Bc(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>...].
51
+ 3. Open wireless debugging in system settings first.`)}async function rb(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(`
52
+ `))}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 ob(n){if(!os.existsSync(n))throw new Error(`app.json5 not found at ${n}`);let e=os.readFileSync(n,"utf8"),t=JS.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},os.writeFileSync(n,JSON.stringify(t,null,2),"utf8"),console.log(`[multi-preview] Injected multiAppMode into ${go.basename(n)}`),()=>{os.writeFileSync(n,e,"utf8"),console.log(`[multi-preview] Restored original ${go.basename(n)}`)})}async function ib(n,e,t,r,o,i){let s=go.join(e.rootDir,"AppScope","app.json5"),a=ob(s);try{let c=n.product||"default",l=n.buildMode||"debug",d="default",h=o.includes("127.0.0.1")||o.includes("localhost");console.log(`
53
+ [multi-preview] Building with multiAppMode (appClone) for multi-instance preview...`);let w=new Xt(t,e.rootDir),S=new ke(t,e.rootDir),re=e.collectNonHarDependentModuleList(i).map(yu=>`${yu}@${d}`),Re=uo(e,re),Pe={type:"modules",modulesToBuild:re,moduleTasks:Re};await Rt(e.rootDir,async()=>{await po(w,S,c,l,Pe,e.rootDir)},()=>console.log("Another build is already running. Waiting...")),console.log(dr("[multi-preview] Build completed."));let Ge=e.findArtifactPath(i,d,h,c);console.log(`[multi-preview] Installing multiAppMode hap to ${o}...`),await r.installApp(o,[Ge]),console.log(dr("[multi-preview] Installed multiAppMode hap."))}finally{a()}}function sb(n,e,t,r,o,i,s){console.log(`
54
+ Launching DevEco Studio previewer on ${n}...`),console.log(` bundleName : ${e}`),console.log(` abilityName : ${t}`),console.log(` moduleName : ${r}`),console.log(` instanceId : ${o}`),console.log(` mode : ${i?"multi":"single"}`),console.log(` previewers : ${s.map(a=>a.productName).join(", ")}`)}async function ab(n,e,t,r,o,i,s,a){let c=[];for(let l=0;l<e.length;l++){let d=e[l],h=t?l:-1;console.log(`
55
+ [${l+1}/${e.length}] Launching ${d.productName} (${d.productType}/${d.subProductType})...`);try{let w=await n.launchPreview(r,o,i,d.productName,d.productType,s,d.subProductType,a,h),S=/start ability successfully/i.test(w);c.push({name:d.productName,success:S,output:w}),S?console.log(dr(` \u2713 ${d.productName}: ${w.trim()}`)):console.error(is(` \u2717 ${d.productName}: ${w.trim()}`))}catch(w){let S=w.message;c.push({name:d.productName,success:!1,output:S}),console.error(is(` \u2717 ${d.productName}: ${S}`))}}return c}function cb(n){console.log(`
56
+ `+"\u2500".repeat(50));let e=n.filter(r=>r.success).length,t=n.length-e;console.log(`Previewer launch summary: ${dr(String(e))} succeeded, ${t>0?is(String(t)):"0"} failed.`);for(let r of n){let o=r.success?dr("\u2713"):is("\u2717");console.log(` ${o} ${r.name}`)}return t===0}async function Ap(n,e,t,r,o,i){let s=await jc(),a=s.length>0?s:[ho],c=QS(n.device,a),l=c.length>1,d;if(b()){let Pe=(await r.listRawTargets()).find(Ge=>Ge.includes("127.0.0.1:"));Pe?(d=Pe,console.log(`Using self-connected device: ${d}`)):(console.warn(Uc("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 nb(r,void 0))}else d=await rb(o,void 0);l&&await ib(n,e,t,r,d,i),await XS(r,d);let h=e.getBundleName(),w=e.getMainAbility(i,n.ability),S=e.getModuleName(i),k=process.pid;sb(d,h,w,S,k,l,c);let re=await ab(r,c,l,d,h,w,S,k);return cb(re)}function Bc(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 cs(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. Specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+o.map(i=>` - ${i.name} (${i.serial})`).join(`
57
+ `))}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 Wc(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>...].
58
58
  Available runnable modules:
59
59
  `+t.map(r=>` - ${r.name}`).join(`
60
- `))}function Ap(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 Dp(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(`
61
- 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(mo(`
60
+ `))}function Dp(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 Rp(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(`
61
+ 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(yo(`
62
62
  Application '${t}': ${s}`))}else console.log(`
63
- Application '${t}' installed successfully (no ability to launch).`)}var Wc=new cb("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()||Wc.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.");Wc.action(async n=>{try{await fb(n)}catch(e){console.error(lb(e.message)),process.exit(1)}});async function db(n,e,t,r,o){let i=new Jt(e,n.rootDir),s=new Te(e,n.rootDir),a=new Set,c=new Set;for(let{moduleName:w,targetName:S}of t)for(let k of n.collectNonHarDependentModuleList(w))a.add(`${k}@${S}`),c.add(k);let l=[...a],d=ao(n,l),h={type:"modules",modulesToBuild:l,moduleTasks:d};for(let w of c)Yi.generate(n.rootDir,w,r,e);await At(n.rootDir,()=>co(i,s,r,o,h,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion...")),console.log(`
64
- `+mo("Build completed successfully."))}async function ub(n,e,t,r,o){let i=new Tt(t),s=te.from(t),a=r[0]?.moduleName||o[0];await Ip(n,e,t,i,s,a)}function pb(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 fb(n){let e=G.discover(process.cwd());console.warn(os("Ensure the project source is trusted before proceeding."));let t=await A.new();if(n.skipBuild||t.assertJava(),n.hotreloadApply){await hb(n,e,t);return}if(n.hotreload){await mb(n,e,t);return}if(n.apply){await yb(n,e,t);return}await Rp(n,e,t)}async function mb(n,e,t){if(n.hotreload==="stop"){await Ep(t,e);return}let o=Bc(e,n.module).map(Uc),{moduleName:i,targetName:s}=o[0];_c(n.module,i);let a=new Tt(t),c=te.from(t),l=await ss(c,n.device),d=l.includes("127.0.0.1")||l.includes("localhost"),h=n.product||"default";e.validateProduct(h);let w=e.getBundleName(),S=Ap(e,o,n.ability);Ki.generate(e.rootDir,i,h,t);let k=new Te(t,e.rootDir);console.log(mo("Ensuring hvigor daemon is running (via --sync --daemon, no hap build)...")),await k.ensureDaemonRunning();let re=[`${i}@${h}`];for(let We of e.collectNonHarDependentModuleList(i))re.includes(`${We}@${h}`)||re.push(`${We}@${h}`);console.log(mo("Building hap + starting watch session (socket -> CommonBuild assembleHap --hot-reload-build --watch, kept open)..."));let De=new ar(e.rootDir,t);await De.startWatchSession({moduleSpecs:re,productName:h});let Pe=bp(e,i,s,d,h);await Dp(a,l,w,Pe,S,!!n.uninstall),console.log(mo("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.")),De.onSocketDisconnect(()=>{console.log("Daemon disconnected (likely via --hotreload stop). Exiting watch session."),process.exit(0)}),await new Promise(()=>{})}async function hb(n,e,t){let r=n.hotreloadApply;if(!r)throw new Error("hotreload-apply requires --hotreload-apply <fileName> (under .hvigor/)");let o=Bc(e,n.module),{moduleName:i}=Uc(o[0]);_c(n.module,i);let s=te.from(t),a=await ss(s,n.device),c=n.product||"default";e.validateProduct(c);let l=e.getBundleName();Sp(e,i,r);let d=[`${i}@${c}`],h=await vp({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 gb(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 Rp(n,e,t){let r=Bc(e,n.module),o=r.map(Uc),i=te.from(t);if(await Cp(n.device,i)){await ub(n,e,t,o,r);return}pb(e,o);let s=new Tt(t),a=await ss(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 db(e,t,o,l,d);let h=gb(e,o,c,l),w=e.getBundleName(),S=Ap(e,o,n.ability);await Dp(s,a,w,h,S,!!n.uninstall)}async function yb(n,e,t){let r=n.apply;if(!r)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(is.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let o=is.join(e.rootDir,".hvigor",r),i=te.from(t),s=await ss(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 Ji(t,e.rootDir);try{await h.execute({applyFile:o,productName:a,targetDeviceId:s,bundleName:c,abilityName:d}),console.log(os("[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(os(`[Apply] \u5931\u8D25\uFF1A${w.message}`)),console.warn(os("[Apply] \u81EA\u52A8\u56DE\u9000\u5230\u5168\u91CF devecocli run..."))}await Rp(n,e,t)}var Tp=Wc;import{Command as wb}from"commander";import{green as kp,red as xp,cyan as Gc}from"colorette";import{execa as Np}from"execa";function vb(){return"beta"}function Sb(){return"@deveco-test/hmos-deveco-cli"}function bb(){return"0.3.0-TD.1.3"}var Eb=new wb("update").description("Update deveco-cli to latest").action(async()=>{let n=Sb(),e=bb(),t=vb();console.log(Gc("Checking for updates..."));try{let{stdout:r}=await Np("npm",["view",n,`dist-tags.${t}`]),o=r.trim();if(!o||o===e){console.log(kp(`
65
- ${n} is already up to date (v${e}, tag: ${t})`));return}console.log(Gc(`
66
- New version found: ${o} (current: ${e})`)),console.log(Gc(`Updating ${n}...`)),await Np("npm",["install","-g",`${n}@${t}`],{stdio:"inherit"}),console.log(`
67
- `+kp(`${n} updated successfully to version ${o}.`))}catch(r){let o=r;console.error(xp(`Failed to update ${n}`)),o.message&&console.error(xp(o.message)),process.exit(1)}}),Lp=Eb;import{Command as Zb}from"commander";import{execa as cs}from"execa";function ve(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as Pb}from"child_process";var Cb=2500;function Ib(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 Ab(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,Cb);n.once("error",d=>c(d.message)),Ib(n,l,s,a,c,i)}function Op(n,e,t){return m(`Spawning emulator: ${n} ${t.join(" ")}`),new Promise((r,o)=>{let i=[],s=Pb(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)),Ab(s,i,r,o)})}import*as lr from"path";function Db(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 Rb(n){let e=n.instancePath?.trim();if(e)return lr.dirname(lr.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?lr.dirname(lr.normalize(t)).replace(/\\/g,"/"):""}function Tb(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function Mp(n,e){return e?[...n,"-bootmode",e]:n}function kb(n,e,t){let r=[Mp(["-start",n],t)],o=Rb(e);if(o)for(let i of Tb(e.imageRoot))r.push(Mp(["-hvd",n,"-path",o,...i],t));return Db(r)}async function _p(n,e,t,r){let o=new Error("No start strategy ran"),i=kb(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 zc(n){return(await te.withHdcPath(n).listDevices()).map(t=>t.serial).filter(Ln)}async function qc(n){let e=await zc(n);return e.length===0?[]:(await Promise.all(e.map(r=>Vi(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function Fp(n,e){return(await qc(n)).includes(e)}import*as ur from"path";import{existsSync as xb,statSync as Nb}from"fs";function dr(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function Lb(n){let e=dr(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 Ob(n){return dr(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function Mb(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=ur.dirname(ur.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let o=ur.join(t,r.name);xb(o)&&Nb(o).isDirectory()&&(r.instancePath=o.replace(/\\/g,"/"))}}function _b(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=Ob(t),o=dr(t,["deviceType","DeviceType","devicetype"]),i=dr(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:Lb(t),path:dr(t,["path","Path","hvdPath","hvd_path"]),imageRoot:dr(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 Fb(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 jp(n){let t=_b(n)??Fb(n);return Mb(t),t}function Vc(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function jb(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function Hb(n){if(!jb(n))return null;let e=Vc(n,["osVersion","OsVersion","OSVersion"]),t=Vc(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=Vc(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function as(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=Hb(o);i&&r.push(i)}return r}catch{return[]}}function Hp(n){let t=as(n).map(r=>r.osVersion).filter(Boolean);return[...new Set(t)]}var $p=/no images are available/i,$b="7.0.0",Ub={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 at(n){return n.normalize("NFKC").trim().toLowerCase()}function Bb(n,e){let t=n.deviceType?.trim(),r=t?Ub[at(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 Wb(n){let e=n.message||"";return $p.test(e)}function Gb(n){return n.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function ho(n,e){return`${n} ${e.join(" ")}`.trim()}function zb(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 pr=class n{static supportedControlPaths=new Set;emulatorPath;sdkPath;hdcPath;constructor(e,t,r){this.emulatorPath=e,this.sdkPath=t,this.hdcPath=r}static from(e){return new n(e.emulatorPath,e.sdkPath,e.hdcPath)}async executeEmulator(e){return m(`Executing: ${ho(this.emulatorPath,e)}`),cs(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return Op(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return jp(e)}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let r of t)r.name&&r.deviceType&&e.set(ve(r.name),r.deviceType)}catch{}return e}async startEmulator(e){let t=await this.listEmulators(),r=ve(e),o=t.find(a=>ve(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 _p(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.
68
- 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:Fp(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),r=ve(e),o=t.find(a=>ve(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"&&Bb(o,t.state);let i=this.buildControlArgs(o.name,t);m(`[EmulatorManager] control ${zb(t)} -> ${ho(this.emulatorPath,i)}`),await this.runEmulatorChecked(i,{printOutputOnSuccess:!1})}async assertControlCommandSupported(){let e=this.emulatorPath;if(n.supportedControlPaths.has(e))return;let t=["-version"];m(`Executing: ${ho(this.emulatorPath,t)}`);let{stdout:r,stderr:o,exitCode:i}=await cs(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(`
69
- `).trim(),a=Gb(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,$b)<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){m(`Executing: ${ho(this.emulatorPath,e)}`);let{exitCode:t}=await cs(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(!Wb(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 Hp(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}
70
- `:"";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=as(t),o=at(e.deviceType),i=at(e.osVersion);return r.filter(s=>at(s.deviceType)===o&&(at(s.osVersion)===i||at(s.softwareVersion)===i))}async hasDownloadedSystemImage(e,t){let r=await this.listEmulatorImages({downloaded:!0}),o=as(r),i=at(t),s=e?.trim()?at(e):void 0;return o.some(a=>at(a.osVersion)===i||at(a.softwareVersion)===i?s===void 0?!0:at(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:[$p]})}async runEmulatorChecked(e,t){m(`Executing: ${ho(this.emulatorPath,e)}`);let{stdout:r,stderr:o,exitCode:i}=await cs(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(`
71
- `).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=ve(e),i=r.find(s=>ve(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(`
72
- `)}),!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=>ve(a.name)===e))return!0;await new Promise(a=>setTimeout(a,r))}return!1}async deleteVirtualDevice(e){let t=await this.listEmulators(),r=ve(e),o=t.find(s=>ve(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}
73
- The device may be running.`);return await this.runEmulatorChecked(["-delete",i,"-force"],{printOutputOnSuccess:!1}),i}};import{red as Yc,yellow as Wp,gray as Gp}from"colorette";import Qb from"ora";import{red as qb}from"colorette";function ls(n,e){n?n.fail(e):console.error(qb(e)),process.exit(1)}import{green as Vb}from"colorette";var Jb=[[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]],Yb=[[0,31],[127,159],[768,879],[6832,6911],[7616,7679],[8203,8207],[8400,8447],[65024,65039],[65056,65071],[8205,8205]],Kb=new RegExp("\x1B\\[([0-9;]*)[a-zA-Z]","g");function Up(n,e){for(let[t,r]of e)if(n>=t&&n<=r)return!0;return!1}function Jc(n){let e=n.replace(Kb,""),t=0,r=0;for(;r<e.length;){let o=e.codePointAt(r);if(o===void 0)break;Up(o,Yb)||(Up(o,Jb)?t+=2:t+=1),r+=o>65535?2:1}return t}function Bp(n,e){let t=Jc(n);return n+" ".repeat(Math.max(0,e-t))}function Xb(n,e){return n.map((t,r)=>{let o=Jc(t);for(let i of e){let s=i.cells[r]??"";o=Math.max(o,Jc(s))}return o})}function xt(n,e){let t=Xb(n,e),r=[];r.push(n.map((o,i)=>Bp(o,t[i])).join(" ")),r.push(t.map(o=>"-".repeat(o)).join(" "));for(let o of e){let i=o.cells.map((s,a)=>Bp(s??"",t[a])).join(" ").trimEnd();r.push(o.highlight?Vb(i):i)}return r.join(`
74
- `)}function eE(n,e){if(e.size!==0)for(let t of n){if(!t.isEmulator||!t.name)continue;let r=e.get(ve(t.name));r&&(t.deviceType=r)}}var tE=["Name","Serial","Kind","Device Type"];function nE(n){return{cells:[n.name??n.serial,n.serial,n.isEmulator?"emulator":"device",n.deviceType??"-"],highlight:!0}}function rE(n,e){return n.isEmulator!==e.isEmulator?n.isEmulator?1:-1:(n.name??n.serial).localeCompare(e.name??e.serial)}function oE(){console.log(Wp(" No active devices.")),console.log(Gp(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 iE(n){let t=[...n].sort(rE).map(nE);console.log(xt(tE,t))}async function sE(n,e){if(b()||!n.some(o=>o.isEmulator)||!e.emulatorPath)return;let r=await pr.from(e).getDeviceTypeByName();eE(n,r)}async function aE(n,e,t){try{let r=await n.getConnectedEntries();await sE(r,e),t?.stop(),r.length===0?oE():iE(r)}catch(r){ls(t,`Failed to list devices: ${r.message}`)}}async function cE(n,e){let t=await n.listDevices();if(!(t.length<2)){console.error(Yc("Multiple devices connected. Specify a device with:"));for(let r of t){let o=await n.getDeviceName(r.serial);console.error(Gp(` ${e} -t ${r.serial} # ${o}`))}process.exit(1)}}async function lE(n,e){try{e||await cE(n,"devecocli device view");let t=await n.listDevices(),r=await n.getDeviceInfo(t,e);r||(console.log(Wp("No connected device found.")),process.exit(1));let o=await n.getDeviceDetail(r.serial),i=await n.getDeviceName(r.serial);console.log(` Serial: ${r.serial}`),console.log(` Device Name: ${i}`),o.deviceType&&console.log(` Device Type: ${o.deviceType}`),o.osVersion&&console.log(` OS Version: ${o.osVersion}`)}catch(t){console.error(Yc(`Failed to show device details: ${t.message}`)),process.exit(1)}}async function zp(){try{let n=await A.new();return{manager:te.from(n),toolProvider:n}}catch(n){console.error(Yc(`Failed to initialize device manager: ${n.message}`)),process.exit(1);return}}var Kc=new Zb("device").description("Manage connected devices");Kc.command("list").description("List all connected devices").action(async()=>{let{manager:n,toolProvider:e}=await zp(),t=Qb({text:"Querying connected devices\u2026",color:"cyan"}).start();await aE(n,e,t)});Kc.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").action(async n=>{let{manager:e}=await zp();await lE(e,n.target)});var qp=Kc;import{Argument as rl,Command as ol,Option as vo}from"commander";import{green as So,cyan as mr,red as Ie,yellow as wt,gray as wo}from"colorette";import IE from"ora";import dE from"readline/promises";import{execa as Jp}from"execa";import*as Zt from"fs/promises";import*as Zc from"os";import*as Fn from"path";var Xc=`1/4:\r
63
+ Application '${t}' installed successfully (no ability to launch).`)}var Gc=new lb("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()||Gc.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.");Gc.action(async n=>{try{await mb(n)}catch(e){console.error(db(e.message)),process.exit(1)}});async function ub(n,e,t,r,o){let i=new Xt(e,n.rootDir),s=new ke(e,n.rootDir),a=new Set,c=new Set;for(let{moduleName:w,targetName:S}of t)for(let k of n.collectNonHarDependentModuleList(w))a.add(`${k}@${S}`),c.add(k);let l=[...a],d=uo(n,l),h={type:"modules",modulesToBuild:l,moduleTasks:d};for(let w of c)Xi.generate(n.rootDir,w,r,e);await Rt(n.rootDir,()=>po(i,s,r,o,h,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion...")),console.log(`
64
+ `+yo("Build completed successfully."))}async function pb(n,e,t,r,o){let i=new xt(t),s=te.from(t),a=r[0]?.moduleName||o[0];await Ap(n,e,t,i,s,a)}function fb(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 mb(n){let e=G.discover(process.cwd());console.warn(ss("Ensure the project source is trusted before proceeding."));let t=await I.new();if(n.skipBuild||t.assertJava(),n.hotreloadApply){await gb(n,e,t);return}if(n.hotreload){await hb(n,e,t);return}if(n.apply){await wb(n,e,t);return}await Tp(n,e,t)}async function hb(n,e,t){if(n.hotreload==="stop"){await Pp(t,e);return}let o=Wc(e,n.module).map(Bc),{moduleName:i,targetName:s}=o[0];Fc(n.module,i);let a=new xt(t),c=te.from(t),l=await cs(c,n.device),d=l.includes("127.0.0.1")||l.includes("localhost"),h=n.product||"default";e.validateProduct(h);let w=e.getBundleName(),S=Dp(e,o,n.ability);Zi.generate(e.rootDir,i,h,t);let k=new ke(t,e.rootDir);console.log(yo("Ensuring hvigor daemon is running (via --sync --daemon, no hap build)...")),await k.ensureDaemonRunning();let re=[`${i}@${h}`];for(let Ge of e.collectNonHarDependentModuleList(i))re.includes(`${Ge}@${h}`)||re.push(`${Ge}@${h}`);console.log(yo("Building hap + starting watch session (socket -> CommonBuild assembleHap --hot-reload-build --watch, kept open)..."));let Re=new lr(e.rootDir,t);await Re.startWatchSession({moduleSpecs:re,productName:h});let Pe=Ep(e,i,s,d,h);await Rp(a,l,w,Pe,S,!!n.uninstall),console.log(yo("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.")),Re.onSocketDisconnect(()=>{console.log("Daemon disconnected (likely via --hotreload stop). Exiting watch session."),process.exit(0)}),await new Promise(()=>{})}async function gb(n,e,t){let r=n.hotreloadApply;if(!r)throw new Error("hotreload-apply requires --hotreload-apply <fileName> (under .hvigor/)");let o=Wc(e,n.module),{moduleName:i}=Bc(o[0]);Fc(n.module,i);let s=te.from(t),a=await cs(s,n.device),c=n.product||"default";e.validateProduct(c);let l=e.getBundleName();bp(e,i,r);let d=[`${i}@${c}`],h=await Sp({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 yb(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 Tp(n,e,t){let r=Wc(e,n.module),o=r.map(Bc),i=te.from(t);if(await Ip(n.device,i)){await pb(n,e,t,o,r);return}fb(e,o);let s=new xt(t),a=await cs(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 ub(e,t,o,l,d);let h=yb(e,o,c,l),w=e.getBundleName(),S=Dp(e,o,n.ability);await Rp(s,a,w,h,S,!!n.uninstall)}async function wb(n,e,t){let r=n.apply;if(!r)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(as.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let o=as.join(e.rootDir,".hvigor",r),i=te.from(t),s=await cs(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 Ki(t,e.rootDir);try{await h.execute({applyFile:o,productName:a,targetDeviceId:s,bundleName:c,abilityName:d}),console.log(ss("[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(ss(`[Apply] \u5931\u8D25\uFF1A${w.message}`)),console.warn(ss("[Apply] \u81EA\u52A8\u56DE\u9000\u5230\u5168\u91CF devecocli run..."))}await Tp(n,e,t)}var kp=Gc;import{Command as vb}from"commander";import{green as xp,red as Np,cyan as zc}from"colorette";import{execa as Lp}from"execa";function Sb(){return"beta"}function bb(){return"@deveco-test/hmos-deveco-cli"}function Eb(){return"0.3.0-TD.2-alpha2"}var Pb=new vb("update").description("Update deveco-cli to latest").action(async()=>{let n=bb(),e=Eb(),t=Sb();console.log(zc("Checking for updates..."));try{let{stdout:r}=await Lp("npm",["view",n,`dist-tags.${t}`]),o=r.trim();if(!o||o===e){console.log(xp(`
65
+ ${n} is already up to date (v${e}, tag: ${t})`));return}console.log(zc(`
66
+ New version found: ${o} (current: ${e})`)),console.log(zc(`Updating ${n}...`)),await Lp("npm",["install","-g",`${n}@${t}`],{stdio:"inherit"}),console.log(`
67
+ `+xp(`${n} updated successfully to version ${o}.`))}catch(r){let o=r;console.error(Np(`Failed to update ${n}`)),o.message&&console.error(Np(o.message)),process.exit(1)}}),Op=Pb;import{Command as Qb}from"commander";import{execa as ds}from"execa";function Se(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as Cb}from"child_process";var Ib=2500;function Ab(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 Db(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,Ib);n.once("error",d=>c(d.message)),Ab(n,l,s,a,c,i)}function Mp(n,e,t){return m(`Spawning emulator: ${n} ${t.join(" ")}`),new Promise((r,o)=>{let i=[],s=Cb(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)),Db(s,i,r,o)})}import*as ur from"path";function Rb(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 Tb(n){let e=n.instancePath?.trim();if(e)return ur.dirname(ur.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?ur.dirname(ur.normalize(t)).replace(/\\/g,"/"):""}function kb(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function _p(n,e){return e?[...n,"-bootmode",e]:n}function xb(n,e,t){let r=[_p(["-start",n],t)],o=Tb(e);if(o)for(let i of kb(e.imageRoot))r.push(_p(["-hvd",n,"-path",o,...i],t));return Rb(r)}async function Fp(n,e,t,r){let o=new Error("No start strategy ran"),i=xb(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 qc(n){return(await te.withHdcPath(n).listDevices()).map(t=>t.serial).filter(On)}async function Vc(n){let e=await qc(n);return e.length===0?[]:(await Promise.all(e.map(r=>Yi(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function jp(n,e){return(await Vc(n)).includes(e)}import*as fr from"path";import{existsSync as Nb,statSync as Lb}from"fs";function pr(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function Ob(n){let e=pr(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 Mb(n){return pr(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function _b(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=fr.dirname(fr.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let o=fr.join(t,r.name);Nb(o)&&Lb(o).isDirectory()&&(r.instancePath=o.replace(/\\/g,"/"))}}function Fb(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=Mb(t),o=pr(t,["deviceType","DeviceType","devicetype"]),i=pr(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:Ob(t),path:pr(t,["path","Path","hvdPath","hvd_path"]),imageRoot:pr(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 jb(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 Hp(n){let t=Fb(n)??jb(n);return _b(t),t}function Jc(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function Hb(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function $b(n){if(!Hb(n))return null;let e=Jc(n,["osVersion","OsVersion","OSVersion"]),t=Jc(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=Jc(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function ls(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=$b(o);i&&r.push(i)}return r}catch{return[]}}function $p(n){let t=ls(n).map(r=>r.osVersion).filter(Boolean);return[...new Set(t)]}var Up=/no images are available/i,Ub="7.0.0",Bb={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 ct(n){return n.normalize("NFKC").trim().toLowerCase()}function Wb(n,e){let t=n.deviceType?.trim(),r=t?Bb[ct(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 Gb(n){let e=n.message||"";return Up.test(e)}function zb(n){return n.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function wo(n,e){return`${n} ${e.join(" ")}`.trim()}function qb(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 mr=class n{static supportedControlPaths=new Set;emulatorPath;sdkPath;hdcPath;constructor(e,t,r){this.emulatorPath=e,this.sdkPath=t,this.hdcPath=r}static from(e){return new n(e.emulatorPath,e.sdkPath,e.hdcPath)}async executeEmulator(e){return m(`Executing: ${wo(this.emulatorPath,e)}`),ds(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return Mp(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return Hp(e)}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let r of t)r.name&&r.deviceType&&e.set(Se(r.name),r.deviceType)}catch{}return e}async startEmulator(e){let t=await this.listEmulators(),r=Se(e),o=t.find(a=>Se(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 Fp(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.
68
+ 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:jp(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),r=Se(e),o=t.find(a=>Se(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"&&Wb(o,t.state);let i=this.buildControlArgs(o.name,t);m(`[EmulatorManager] control ${qb(t)} -> ${wo(this.emulatorPath,i)}`),await this.runEmulatorChecked(i,{printOutputOnSuccess:!1})}async assertControlCommandSupported(){let e=this.emulatorPath;if(n.supportedControlPaths.has(e))return;let t=["-version"];m(`Executing: ${wo(this.emulatorPath,t)}`);let{stdout:r,stderr:o,exitCode:i}=await ds(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(`
69
+ `).trim(),a=zb(s);if(i!==0||!a)throw new Error("Emulator scene control commands require Emulator 7.0 or later. Unable to determine the current Emulator version.");if(I.compareVersion(a,Ub)<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){m(`Executing: ${wo(this.emulatorPath,e)}`);let{exitCode:t}=await ds(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(!Gb(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 $p(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}
70
+ `:"";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=ls(t),o=ct(e.deviceType),i=ct(e.osVersion);return r.filter(s=>ct(s.deviceType)===o&&(ct(s.osVersion)===i||ct(s.softwareVersion)===i))}async hasDownloadedSystemImage(e,t){let r=await this.listEmulatorImages({downloaded:!0}),o=ls(r),i=ct(t),s=e?.trim()?ct(e):void 0;return o.some(a=>ct(a.osVersion)===i||ct(a.softwareVersion)===i?s===void 0?!0:ct(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:[Up]})}async runEmulatorChecked(e,t){m(`Executing: ${wo(this.emulatorPath,e)}`);let{stdout:r,stderr:o,exitCode:i}=await ds(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(`
71
+ `).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=Se(e),i=r.find(s=>Se(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(`
72
+ `)}),!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=>Se(a.name)===e))return!0;await new Promise(a=>setTimeout(a,r))}return!1}async deleteVirtualDevice(e){let t=await this.listEmulators(),r=Se(e),o=t.find(s=>Se(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}
73
+ The device may be running.`);return await this.runEmulatorChecked(["-delete",i,"-force"],{printOutputOnSuccess:!1}),i}};import{red as Kc,yellow as Gp,gray as zp}from"colorette";import eE from"ora";import{red as Vb}from"colorette";function us(n,e){n?n.fail(e):console.error(Vb(e)),process.exit(1)}import{green as Jb}from"colorette";var Yb=[[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]],Kb=[[0,31],[127,159],[768,879],[6832,6911],[7616,7679],[8203,8207],[8400,8447],[65024,65039],[65056,65071],[8205,8205]],Xb=new RegExp("\x1B\\[([0-9;]*)[a-zA-Z]","g");function Bp(n,e){for(let[t,r]of e)if(n>=t&&n<=r)return!0;return!1}function Yc(n){let e=n.replace(Xb,""),t=0,r=0;for(;r<e.length;){let o=e.codePointAt(r);if(o===void 0)break;Bp(o,Kb)||(Bp(o,Yb)?t+=2:t+=1),r+=o>65535?2:1}return t}function Wp(n,e){let t=Yc(n);return n+" ".repeat(Math.max(0,e-t))}function Zb(n,e){return n.map((t,r)=>{let o=Yc(t);for(let i of e){let s=i.cells[r]??"";o=Math.max(o,Yc(s))}return o})}function Lt(n,e){let t=Zb(n,e),r=[];r.push(n.map((o,i)=>Wp(o,t[i])).join(" ")),r.push(t.map(o=>"-".repeat(o)).join(" "));for(let o of e){let i=o.cells.map((s,a)=>Wp(s??"",t[a])).join(" ").trimEnd();r.push(o.highlight?Jb(i):i)}return r.join(`
74
+ `)}function tE(n,e){if(e.size!==0)for(let t of n){if(!t.isEmulator||!t.name)continue;let r=e.get(Se(t.name));r&&(t.deviceType=r)}}var nE=["Name","Serial","Kind","Device Type"];function rE(n){return{cells:[n.name??n.serial,n.serial,n.isEmulator?"emulator":"device",n.deviceType??"-"],highlight:!0}}function oE(n,e){return n.isEmulator!==e.isEmulator?n.isEmulator?1:-1:(n.name??n.serial).localeCompare(e.name??e.serial)}function iE(){console.log(Gp(" No active devices.")),console.log(zp(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 sE(n){let t=[...n].sort(oE).map(rE);console.log(Lt(nE,t))}async function aE(n,e){if(b()||!n.some(o=>o.isEmulator)||!e.emulatorPath)return;let r=await mr.from(e).getDeviceTypeByName();tE(n,r)}async function cE(n,e,t){try{let r=await n.getConnectedEntries();await aE(r,e),t?.stop(),r.length===0?iE():sE(r)}catch(r){us(t,`Failed to list devices: ${r.message}`)}}async function lE(n,e){let t=await n.listDevices();if(!(t.length<2)){console.error(Kc("Multiple devices connected. Specify a device with:"));for(let r of t){let o=await n.getDeviceName(r.serial);console.error(zp(` ${e} -t ${r.serial} # ${o}`))}process.exit(1)}}async function dE(n,e){try{e||await lE(n,"devecocli device view");let t=await n.listDevices(),r=await n.getDeviceInfo(t,e);r||(console.log(Gp("No connected device found.")),process.exit(1));let o=await n.getDeviceDetail(r.serial),i=await n.getDeviceName(r.serial);console.log(` Serial: ${r.serial}`),console.log(` Device Name: ${i}`),o.deviceType&&console.log(` Device Type: ${o.deviceType}`),o.osVersion&&console.log(` OS Version: ${o.osVersion}`)}catch(t){console.error(Kc(`Failed to show device details: ${t.message}`)),process.exit(1)}}async function qp(){try{let n=await I.new();return{manager:te.from(n),toolProvider:n}}catch(n){console.error(Kc(`Failed to initialize device manager: ${n.message}`)),process.exit(1);return}}var Xc=new Qb("device").description("Manage connected devices");Xc.command("list").description("List all connected devices").action(async()=>{let{manager:n,toolProvider:e}=await qp(),t=eE({text:"Querying connected devices\u2026",color:"cyan"}).start();await cE(n,e,t)});Xc.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").action(async n=>{let{manager:e}=await qp();await dE(e,n.target)});var Vp=Xc;import{Argument as ol,Command as il,Option as Eo}from"commander";import{green as Po,cyan as gr,red as Ie,yellow as vt,gray as bo}from"colorette";import AE from"ora";import uE from"readline/promises";import{execa as Yp}from"execa";import*as en from"fs/promises";import*as Qc from"os";import*as jn from"path";var Zc=`1/4:\r
75
75
  ---------------------------------------\r
76
76
  Statement About HarmonyOS and Privacy\r
77
77
  \r
@@ -1241,13 +1241,13 @@ Part I: Chinese mainland.\r
1241
1241
  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
1242
1242
  \r
1243
1243
  Part III: Other countries and regions.\r
1244
- ---------------------------------------\r`;var uE=new Set,ds=new Map,Qc="HarmonyOS_Software_Service_Agreement",Yp=["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(`
1245
- `),Kp=Yp,el="HarmonyOS_SDK_Agreement";function Xp(n,e){return`${n}\0${e}`}function Zp(){uE.clear(),ds.clear()}var pE=Yp,Je=class extends Error{constructor(e=pE){super(e),this.name="EmulatorLicenseBlockedError"}};function Qp(n,e){return[n??"",e??""].join(`
1246
- `)}function ef(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 fE(n){return`Emulator${n.trim()}`}function tf(n){let e=fE(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 Fn.join(r,"Huawei",e,".emu_config")}if(process.platform==="darwin")return Fn.join(Zc.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||Fn.join(Zc.homedir(),".cache");return Fn.join(t,"Huawei",e,".emu_config")}async function mE(n,e,t){let r=Xp(n,e),o=ds.get(r);if(o!==void 0)return o;let i=await Jp(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=Qp(i.stdout,i.stderr).trim();if(i.exitCode!==0||!s)throw new Je(t);return ds.set(r,s),s}function hE(n){let e=n[0],t=n[n.length-1];return(e==='"'||e==="'")&&e===t?n.slice(1,-1):n}function gE(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 yE(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=hE(e.slice(r+1).trim());return{key:o,entry:{value:i,delimiter:t}}}}function wE(n){let e={};for(let t of n.split(/\r?\n/)){let r=yE(t);r&&(e[r.key]=r.entry)}return e}function vE(n){let e=n.trim();if(!e)return{};let t=gE(e);return t||wE(n)}function SE(n){return typeof n!="string"?!1:n.normalize("NFKC").trim().toLowerCase()==="agree"}async function nf(n,e,t,r){let o=await mE(n,e,r),i=ef(o);if(!i)throw new Je(r);let s=tf(i),a;try{a=await Zt.readFile(s,"utf8")}catch(d){throw d.code==="ENOENT"?new Je(r):d}let l=vE(a)[t];if(!l)throw new Je(r);if(l.delimiter==="=")throw new Je(r);if(!SE(l.value))throw new Je(r)}async function tl(n,e){await nf(n,e,Qc,Kp)}async function nl(n,e){await nf(n,e,el,Kp)}async function bE(n,e){let t=await Jp(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),r=Qp(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=Xp(n,e);return ds.set(o,r),r}async function rf(n,e){let t=await bE(n,e),r=ef(t);if(!r)throw new Error(`Cannot parse Emulator major.minor from:
1247
- ${t}.`);return tf(r)}function Vp(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function EE(n,e,t){if(!t.startsWith("{"))return!1;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return r[Qc]="agree",r[el]="agree",await Zt.writeFile(n,`${JSON.stringify(r,null,2)}
1248
- `,"utf8"),!0}catch{}return!1}async function PE(n,e){let t=Qc,r=el,o=[{k:t,re:new RegExp(`^\\s*${Vp(t)}\\s*[:=]`)},{k:r,re:new RegExp(`^\\s*${Vp(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 Zt.writeFile(n,s.join(`
1244
+ ---------------------------------------\r`;var pE=new Set,ps=new Map,el="HarmonyOS_Software_Service_Agreement",Kp=["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(`
1245
+ `),Xp=Kp,tl="HarmonyOS_SDK_Agreement";function Zp(n,e){return`${n}\0${e}`}function Qp(){pE.clear(),ps.clear()}var fE=Kp,Ye=class extends Error{constructor(e=fE){super(e),this.name="EmulatorLicenseBlockedError"}};function ef(n,e){return[n??"",e??""].join(`
1246
+ `)}function tf(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 mE(n){return`Emulator${n.trim()}`}function nf(n){let e=mE(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 jn.join(r,"Huawei",e,".emu_config")}if(process.platform==="darwin")return jn.join(Qc.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||jn.join(Qc.homedir(),".cache");return jn.join(t,"Huawei",e,".emu_config")}async function hE(n,e,t){let r=Zp(n,e),o=ps.get(r);if(o!==void 0)return o;let i=await Yp(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=ef(i.stdout,i.stderr).trim();if(i.exitCode!==0||!s)throw new Ye(t);return ps.set(r,s),s}function gE(n){let e=n[0],t=n[n.length-1];return(e==='"'||e==="'")&&e===t?n.slice(1,-1):n}function yE(n){try{let e=JSON.parse(n);if(e&&typeof e=="object"&&!Array.isArray(e)){let t={};for(let[r,o]of Object.entries(e))t[r]={value:typeof o=="string"?o:String(o),delimiter:"json"};return t}}catch{return}}function wE(n){let e=n.trim();if(!(!e||e.startsWith("#")))for(let t of["=",":"]){let r=e.indexOf(t);if(r<=0)continue;let o=e.slice(0,r).trim();if(!o||t===":"&&o.includes("//"))continue;let i=gE(e.slice(r+1).trim());return{key:o,entry:{value:i,delimiter:t}}}}function vE(n){let e={};for(let t of n.split(/\r?\n/)){let r=wE(t);r&&(e[r.key]=r.entry)}return e}function SE(n){let e=n.trim();if(!e)return{};let t=yE(e);return t||vE(n)}function bE(n){return typeof n!="string"?!1:n.normalize("NFKC").trim().toLowerCase()==="agree"}async function rf(n,e,t,r){let o=await hE(n,e,r),i=tf(o);if(!i)throw new Ye(r);let s=nf(i),a;try{a=await en.readFile(s,"utf8")}catch(d){throw d.code==="ENOENT"?new Ye(r):d}let l=SE(a)[t];if(!l)throw new Ye(r);if(l.delimiter==="=")throw new Ye(r);if(!bE(l.value))throw new Ye(r)}async function nl(n,e){await rf(n,e,el,Xp)}async function rl(n,e){await rf(n,e,tl,Xp)}async function EE(n,e){let t=await Yp(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),r=ef(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=Zp(n,e);return ps.set(o,r),r}async function of(n,e){let t=await EE(n,e),r=tf(t);if(!r)throw new Error(`Cannot parse Emulator major.minor from:
1247
+ ${t}.`);return nf(r)}function Jp(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function PE(n,e,t){if(!t.startsWith("{"))return!1;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return r[el]="agree",r[tl]="agree",await en.writeFile(n,`${JSON.stringify(r,null,2)}
1248
+ `,"utf8"),!0}catch{}return!1}async function CE(n,e){let t=el,r=tl,o=[{k:t,re:new RegExp(`^\\s*${Jp(t)}\\s*[:=]`)},{k:r,re:new RegExp(`^\\s*${Jp(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 en.writeFile(n,s.join(`
1249
1249
  `)+(s.length>0?`
1250
- `:""),"utf8")}async function of(n){await Zt.mkdir(Fn.dirname(n),{recursive:!0});let e="";try{e=await Zt.readFile(n,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}let t=e.trim();await EE(n,e,t)||await PE(n,e)}async function sf(n,e){return console.log(Xc),0}var CE="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function af(n,e){try{return await tl(n,e),await nl(n,e),!0}catch(t){if(t instanceof Je)return!1;throw t}}async function cf(n,e){if(await af(n,e))return console.log("Emulator license agreements are already accepted."),0;if(console.log(Xc),!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=dE.createInterface({input:process.stdin,output:process.stdout}),o;try{o=await r.question(CE)}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 rf(n,e);await of(s),Zp()}catch(s){return console.error(s.message),1}return console.log("Emulator license agreements accepted."),0}async function lf(n,e){if(await af(n,e))return console.log("Emulator license agreements are already accepted."),0;try{let t=await rf(n,e);await of(t),Zp()}catch(t){return console.error(t.message),1}return console.log("Emulator license agreements accepted."),0}var AE=["ohos.qemu.hvd.name","const.product.name","const.product.model"],df=["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"],DE=`
1250
+ `:""),"utf8")}async function sf(n){await en.mkdir(jn.dirname(n),{recursive:!0});let e="";try{e=await en.readFile(n,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}let t=e.trim();await PE(n,e,t)||await CE(n,e)}async function af(n,e){return console.log(Zc),0}var IE="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function cf(n,e){try{return await nl(n,e),await rl(n,e),!0}catch(t){if(t instanceof Ye)return!1;throw t}}async function lf(n,e){if(await cf(n,e))return console.log("Emulator license agreements are already accepted."),0;if(console.log(Zc),!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=uE.createInterface({input:process.stdin,output:process.stdout}),o;try{o=await r.question(IE)}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 of(n,e);await sf(s),Qp()}catch(s){return console.error(s.message),1}return console.log("Emulator license agreements accepted."),0}async function df(n,e){if(await cf(n,e))return console.log("Emulator license agreements are already accepted."),0;try{let t=await of(n,e);await sf(t),Qp()}catch(t){return console.error(t.message),1}return console.log("Emulator license agreements accepted."),0}var DE=["ohos.qemu.hvd.name","const.product.name","const.product.model"],uf=["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"],RE=`
1251
1251
  Folded state scene mappings:
1252
1252
  foldableFold (3):
1253
1253
  open Fully expanded state
@@ -1270,43 +1270,43 @@ Folded state scene mappings:
1270
1270
  left-half-folded-right-folded
1271
1271
  left-expanded-right-half-folded
1272
1272
  left-half-folded-right-half-folded
1273
- `;function RE(n){let e=n.trim();if(!e)throw new Error("--target must not be empty.");return e}function TE(n){let e=n.trim();if(!df.includes(e))throw new Error(`Invalid fold state "${n}". Available values: ${df.join(", ")}`);return e}function pf(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 ff(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&&!kE(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 kE(n,e){let t=n.split(".")[1];return t===void 0||t.length<=e}function xE(n,e,t,r,o){return Number(ff(n,e,t,r,o))}function NE(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 LE(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 OE(n,e){let t=o=>o.normalize("NFKC").trim(),r=t(n);if(e.length===0)throw console.error(wt("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(wt("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(Ie("--os-version does not match any downloaded image (exact string required).")),console.log(wt("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 ME=["Name","Status","Serial","Device Type","OS Version"];function _E(n,e,t){return{cells:[n.name,t?"running":"stopped",e??"-",n.deviceType??"-",n.osVersion??"-"],highlight:t}}async function FE(n,e){let t=await Promise.all(e.map(async r=>{let o=await rr(n,r,AE);return[r,o]}));return new Map(t)}async function jE(n){let e=await zc(n),t=await FE(n,e);return{serials:e,params:t}}function HE(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 $E(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&&HE(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 UE(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=>_E(o.emu,o.serial,o.effectiveRunning))}async function BE(n,e,t){try{let[r,o]=await Promise.all([n.listEmulators(),jE(e)]);if(r.length===0){t?.stop(),console.log(wt(" No emulator instances found."));return}let i=r.filter(l=>l.isRunning).map(l=>l.name),{productSerialMap:s,hvdSerialMap:a}=$E(o.serials,o.params,i);t?.stop();let c=UE(r,s,a);console.log(xt(ME,c))}catch(r){ls(t,`Failed to list emulators: ${r.message}`)}}function mf(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(Ie(`Failed to ${t} emulator "${e[o]}": ${s.message}`)),s.stdout&&console.error(wo(s.stdout)),s.stderr&&console.error(wo(s.stderr))}return r}var WE=2e3,GE=6e4;async function zE(n,e){let t=ve(e);return(await qc(n)).some(o=>ve(o)===t)}async function hf(n,e,t,r=GE,o=WE){let i=Date.now()+r;for(;Date.now()<i;){if(await zE(n,e)===t)return!0;await new Promise(a=>setTimeout(a,o))}return!1}async function qE(n,e,t){if(await n.startEmulator(t)==="already-running"){console.log(wt(`Emulator "${t}" is already running.`));return}console.log(mr(`Starting emulator "${t}"...`));let o=await hf(e,t,!0);console.log(o?So(`Emulator "${t}" started successfully.`):wt(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function VE(n,e,t){let r=await Promise.allSettled(t.map(i=>qE(n,e,i)));mf(r,t,"start")&&process.exit(1)}async function gf(n,e){let t=e.trim();if(!Ln(t))return t;let r=await te.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 JE(n,e,t){let r=await gf(e,t);if(console.log(mr(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(wt(`Emulator "${r}" is already stopped.`));return}let i=await hf(e,r,!1);console.log(i?So(`Emulator "${r}" stopped successfully.`):wt(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function YE(n,e,t){let r=await Promise.allSettled(t.map(i=>JE(n,e,i)));mf(r,t,"stop")&&process.exit(1)}async function Ye(){try{let n=await A.new();return{manager:pr.from(n),toolProvider:n}}catch(n){console.error(Ie(`Failed to initialize emulator: ${n.message}`)),process.exit(1);return}}async function Nt(n,e){try{let t=RE(n.target),r=e(),{manager:o,toolProvider:i}=await Ye(),s=await gf(i.hdcPath,t);await o.controlEmulator(s,r),console.log(So(`Emulator "${t}" operation completed.`))}catch(t){let r=n.target?.trim()||"<unknown>";console.error(Ie(`Failed to operate emulator "${r}": ${t.message}`)),process.exit(1)}}function KE(n){let e=[];return us(e,"longitude",n.longitude,-180,180,8),us(e,"latitude",n.latitude,-90,90,8),us(e,"altitude",n.altitude,-1e4,1e4,2),us(e,"bearing",n.direction,0,359.99,2,"--direction"),il(e,"Specify one geolocation option.")}function XE(n){let e=[];return go(e,"light",n.lightIntensity,0,1e5,!1,"--light-intensity"),go(e,"humidity",n.humidity,0,100,!1),go(e,"temperature",n.temperature,-273.1,100,!1),go(e,"steps",n.steps,0,1e4,!0),go(e,"heartrate",n.heartrate,0,255,!0),il(e,"Specify one sensor option.")}function il(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 us(n,e,t,r,o,i,s=`--${e}`){t!==void 0&&n.push({type:"gps",key:e,value:ff(s,t,r,o,i)})}function go(n,e,t,r,o,i,s=`--${e}`){if(t===void 0)return;let a=i?pf(s,t,r,o):xE(s,t,r,o,1);n.push({type:"sensor",key:e,value:a})}function ZE(n){let e=[];return n.level!==void 0&&e.push({type:"battery",level:pf("--level",n.level,1,100)}),n.status!==void 0&&e.push({type:"battery-status",status:n.status==="charging"?1:0}),il(e,"Specify --level or --status.")}var fe=new ol("emulator").description("Manage emulator instances"),QE=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function ps(n){let e=new vo("--device-type <type>","Emulator device type").choices([...QE]);return n?e.makeOptionMandatory():e}function fr(n,e){for(let t of e)if(t in n)return n[t]}function yo(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function uf(n){let e=yo(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var eP=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],tP="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function yf(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function wf(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let o=r,i=yo(fr(o,["osVersion","OsVersion","OSVersion","os_version"])),s=yo(fr(o,["deviceType","DeviceType","device_type"])),a=uf(fr(o,["downloaded","Downloaded","isDownloaded"])),c=yo(fr(o,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=yo(fr(o,["releaseType","ReleaseType","release_type"])),d=uf(fr(o,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[i,s,c,l,d,a],highlight:e&&a==="true"})}return t}function nP(n){let e=n.trim();if(!e)return!0;let t=yf(e);return t===null?!1:t.length===0?!0:wf(t,!0).length===0}function rP(n,e){let t=n.trim();if(!t)return"";let r=yf(t);if(!r)return n.trimEnd();let o=wf(r,e);return xt(eP,o)}var fs=new ol("image").description("HarmonyOS emulator system images (download, list, remove)");fs.command("download").description("Download system image").addOption(ps(!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 Ye();try{await nl(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof Je&&(console.error(Ie(r.message)),process.exit(1)),r}n.deviceType?.trim()||(console.error(Ie("Error: missing required option '--device-type <type>'")),process.exit(1)),n.osVersion?.trim()||(console.error(Ie("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(Ie(`Failed to download system image: ${r.message}`)),process.exit(1)}});fs.command("remove").description("Remove a downloaded system image").addOption(ps(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let{manager:e}=await Ye();try{await e.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})}catch(t){console.error(Ie(`Failed to remove system image: ${t.message}`)),process.exit(1)}});fs.command("list").description("List system images").addOption(ps(!1)).option("--all","List all images (local and remote)").addOption(new vo("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let{manager:e}=await Ye();try{let t;n.all?t=void 0:t=!0;let r=await e.listEmulatorImages({deviceType:n.deviceType,downloaded:t});if(nP(r)){console.log(wt(tP));return}if(n.format==="json"){console.log(r.trimEnd());return}let o=rP(r,n.all===!0);console.log(o)}catch(t){console.error(Ie(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});fe.addCommand(fs);var ms=new ol("license").description("Review and accept emulator license agreements interactively (prints full text + y/N prompt)");ms.command("view").description("Review agreement text (read-only, no changes)").action(async()=>{let{toolProvider:n}=await Ye(),e=await sf(n.emulatorPath,n.sdkPath);process.exit(e)});ms.command("accept").description("Accept all emulator license agreements non-interactively (skips review and prompt)").action(async()=>{let{toolProvider:n}=await Ye(),e=await lf(n.emulatorPath,n.sdkPath);process.exit(e)});ms.action(async()=>{let{toolProvider:n}=await Ye(),e=await cf(n.emulatorPath,n.sdkPath);process.exit(e)});fe.addCommand(ms);fe.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Nt(n,()=>({type:"shake"})));fe.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Nt(n,()=>({type:"power"})));fe.command("rotate").description("Rotate emulator").addOption(new vo("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new rl("<direction>").choices(["left","right"])).action((n,e)=>Nt(e,()=>({type:"rotation",direction:n})));fe.command("volume").description("Change volume").addOption(new vo("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new rl("<direction>").choices(["up","down"])).action((n,e)=>Nt(e,()=>({type:"volume",direction:n})));fe.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",DE).action((n,e)=>Nt(e,()=>({type:"folded-state",state:TE(n)})));fe.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 vo("--status <status>","Charging status").choices(["charging","discharging"])).action(n=>Nt(n,()=>ZE(n)));fe.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=>Nt(n,()=>KE(n)));fe.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new rl("<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 Nt(e,()=>t[n])});fe.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=>Nt(n,()=>XE(n)));fe.command("list").description("List all emulator instances").action(async()=>{let{manager:n,toolProvider:e}=await Ye(),t=IE({text:"Listing emulators\u2026",color:"cyan"}).start();await BE(n,e.hdcPath,t)});fe.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let{manager:e,toolProvider:t}=await Ye();try{await tl(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof Je&&(console.error(Ie(r.message)),process.exit(1)),r}n?.length||(console.error(Ie("Error: missing required argument 'names'")),process.exit(1)),await VE(e,t.hdcPath,n)});fe.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 Ye();n?.length||(console.error(Ie("Error: missing required argument 'names'")),process.exit(1)),await YE(e,t.hdcPath,n)});var vf=fe.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(ps(!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");vf.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
1274
- ${wt("Tip: ")}${wo("Unquoted --os-version values with spaces/parentheses are split into multiple arguments. Use:")}
1275
- ${mr('devecocli emulator create 123 --device-type phone --os-version "HarmonyOS 6.0.1(21)"')}
1276
- ${mr('devecocli emulator create 123 --device-type phone --os-version="HarmonyOS 6.0.1(21)"')}
1277
- `)}});vf.action(async(n,e)=>{try{NE(n),LE(e.osVersion);let{manager:t}=await Ye(),r=await t.listDownloadedImageOsVersions();OE(e.osVersion,r),console.log(mr(`Creating emulator "${n}"...`)),await t.createVirtualDevice({name:n,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(So(`Emulator "${n}" created successfully.`))}catch(t){console.error(Ie(`${t.message}`)),process.exit(1)}});fe.command("delete <name>").description("Delete a local emulator instance").action(async n=>{let{manager:e}=await Ye();console.log(mr(`Deleting emulator "${n}"...`));try{let t=await e.deleteVirtualDevice(n);console.log(So(`Emulator "${t}" deleted successfully.`))}catch(t){let r=t;console.error(Ie(r.message)),r.stdout&&console.error(wo(r.stdout)),r.stderr&&console.error(wo(r.stderr)),process.exit(1)}});var Sf=fe;import{Command as bP}from"commander";import{cyan as Xe}from"colorette";import*as $f from"readline";import*as Ff from"crypto";import*as bf from"http";import*as Ef from"crypto";import{URL as oP}from"url";var hs=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=bf.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 oP(e.url??"",`http://${r}`);if(i.pathname!==this.callbackPath){t.writeHead(404),t.end("Not Found");return}try{let s=i.searchParams;if(e.method==="POST"){let a="";e.on("data",c=>{a+=c.toString()}),e.on("end",()=>{this.handleCallbackRequest(e,t,s,a)})}else this.handleCallbackRequest(e,t,s,"")}catch(s){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(s)}}handleCallbackRequest(e,t,r,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&&Ef.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 xe from"fs";import*as gr from"path";import{homedir as uP}from"os";var Lt={};rv(Lt,{LocalCrypto:()=>Lt,decryptForLocalStorage:()=>cP,decryptForLocalStorageFromDirectory:()=>lP,encryptForLocalStorage:()=>aP,isEncryptedBlob:()=>dP});import*as J from"fs";import*as jn from"path";import*as ke from"crypto";import{homedir as Pf}from"os";var bo=An.ALGORITHM,Cf=An.IV_LENGTH,Eo=An.KEY_LENGTH,Po=An.KEY_LENGTH,Co=An.KEK_VERSIONS,sl=process.env.DEVECO_CLI_DATA_DIR||jn.join(Pf(),Ce.CONFIG_DIR_NAME,Ce.APP_NAME),al=jn.join(Pf(),".local","share",Ce.APP_NAME,"keys"),hr=jn.join(sl,Ce.KEY_FILE_NAME);function cl(n){return jn.join(al,`${n}.bin`)}function If(){J.existsSync(sl)||J.mkdirSync(sl,{recursive:!0,mode:448}),J.existsSync(al)||J.mkdirSync(al,{recursive:!0,mode:448})}function Af(){If();for(let n of Co){let e=cl(n);J.existsSync(e)||J.writeFileSync(e,ke.randomBytes(Eo),{mode:384})}}function Df(n){Af();let e=cl(n),t=J.readFileSync(e);if(t.length===Eo)return t;let r=ke.randomBytes(Eo);return J.writeFileSync(e,r,{mode:384}),r}function ll(n,e){let t=ke.randomBytes(Cf),r=Df(e),o=ke.createCipheriv(bo,r,t),i=Buffer.concat([o.update(n),o.final()]),s=o.getAuthTag();return{version:1,algorithm:bo,kekId:e,encryptedDek:i.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function Rf(n,e){return Tf(Buffer.from(n.encryptedDek,"base64"),e,n.iv,n.authTag)}function Tf(n,e,t,r){let o=ke.createDecipheriv(bo,e,Buffer.from(t,"base64"));return o.setAuthTag(Buffer.from(r,"base64")),Buffer.concat([o.update(n),o.final()])}function kf(n,e){return Tf(Buffer.from(n.ciphertext,"base64"),e,n.iv,n.authTag).toString("utf8")}function iP(){if(Af(),J.existsSync(hr))return;let n=ke.randomBytes(Po),e=ll(n,Co[0]);J.writeFileSync(hr,JSON.stringify(e,null,2),{mode:384})}function xf(){iP();let n=JSON.parse(J.readFileSync(hr,"utf8")),e=Rf(n,Df(n.kekId));if(e.length===Po)return e;let t=ke.randomBytes(Po),r=ll(t,Co[0]);return J.writeFileSync(hr,JSON.stringify(r,null,2),{mode:384}),t}function sP(){If();for(let t of Co){let r=cl(t);J.existsSync(r)||J.writeFileSync(r,ke.randomBytes(Eo),{mode:384})}if(J.existsSync(hr))return;let n=ke.randomBytes(Po),e=ll(n,Co[0]);J.writeFileSync(hr,JSON.stringify(e,null,2),{mode:384})}function aP(n){let e=xf(),t=ke.randomBytes(Cf),r=ke.createCipheriv(bo,e,t),o=Buffer.concat([r.update(n,"utf8"),r.final()]),i=r.getAuthTag();return{version:1,algorithm:bo,ciphertext:o.toString("base64"),iv:t.toString("base64"),authTag:i.toString("base64"),timeStamp:Date.now()}}function cP(n){try{return kf(n,xf())}catch{throw sP(),new Error("Failed to decrypt local ciphertext")}}function lP(n,e){let t=jn.join(e,Ce.KEY_FILE_NAME),r=JSON.parse(J.readFileSync(t,"utf8")),o=jn.join(e,"keys",`${r.kekId}.bin`),i=J.readFileSync(o);if(i.length!==Eo)throw new Error("Invalid external root key");let s=Rf(r,i);if(s.length!==Po)throw new Error("Invalid external data encryption key");return kf(n,s)}function dP(n){if(!n||typeof n!="object")return!1;let e=n;return e.algorithm==="aes-256-gcm"&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}var gs=class{tokenFilePath;constructor(e){let t=e||process.env.DEVECO_CLI_DATA_DIR||gr.join(uP(),Ce.CONFIG_DIR_NAME,Ce.APP_NAME);this.tokenFilePath=gr.join(t,Ce.TOKEN_FILE_NAME)}ensureConfigDir(){let e=gr.dirname(this.tokenFilePath);xe.existsSync(e)||xe.mkdirSync(e,{recursive:!0,mode:448})}async saveJwtToken(e){if(!e)throw new Error("Token is empty");let t=Lt.encryptForLocalStorage(e);this.ensureConfigDir(),xe.writeFileSync(this.tokenFilePath,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){return(await this.resolveJwtToken())?.token??null}async resolveJwtToken(){let e=this.loadDevecoCodeToken();if(e)return{token:e,source:"deveco-code"};let t=await this.loadLocalJwtToken();return t?{token:t,source:"deveco-cli"}:null}loadDevecoCodeToken(){if(process.env.DEVECO_CLI_AUTH_SOURCE!=="deveco-code")return null;let e=process.env.DEVECO_CODE_AUTH_DIR?.trim();if(!e)return null;try{let t=gr.join(e,Ce.TOKEN_FILE_NAME);if(!xe.existsSync(t))return null;let r=JSON.parse(xe.readFileSync(t,"utf8"));return Lt.isEncryptedBlob(r)?Lt.decryptForLocalStorageFromDirectory(r,e):null}catch{return null}}async loadLocalJwtToken(){try{if(!xe.existsSync(this.tokenFilePath))return null;let e=JSON.parse(xe.readFileSync(this.tokenFilePath,"utf8"));return Lt.isEncryptedBlob(e)?Lt.decryptForLocalStorage(e):null}catch{return await this.clearToken(),null}}async clearToken(){try{xe.existsSync(this.tokenFilePath)&&xe.unlinkSync(this.tokenFilePath)}catch(e){throw new Error("Failed to clear token",{cause:e})}}},Ke=new gs;var vt={CHINA:"CN",RUSSIA:"RU",SINGAPORE:"SG",EUROPE:"EU"},Io={CHINA:"zh_CN",RUSSIA:"ru_RU",EUROPE:"de_DE"},ys={CHINA:"1",SINGAPORE:"5",EUROPE:"7",RUSSIA:"8"},pP={[vt.CHINA]:Io.CHINA,[vt.RUSSIA]:Io.RUSSIA,[vt.EUROPE]:Io.EUROPE,[vt.SINGAPORE]:Io.CHINA},fP={[ys.CHINA]:vt.CHINA,[ys.SINGAPORE]:vt.SINGAPORE,[ys.EUROPE]:vt.EUROPE,[ys.RUSSIA]:vt.RUSSIA};function Nf(n){return pP[n]??Io.CHINA}function Lf(n){return fP[n]??vt.CHINA}function ws(n,e){return n?.toUpperCase()===vt.CHINA?rt.CN_LOGIN_URL:e}import{exec as mP}from"child_process";import{promisify as hP}from"util";var gP=hP(mP);async function Of(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 gP(t)}catch(r){throw new Error("Failed to open browser",{cause:r})}}import yP from"axios";var dl=class{client;constructor(){let e={timeout:to.HTTP_TIMEOUT_MS,headers:{"User-Agent":ki.USER_AGENT,"accept-language":ki.ACCEPT_LANGUAGE},transformResponse:[t=>t],proxy:!1};this.client=yP.create(e),this.client.interceptors.response.use(t=>t,t=>{let r=`Network connection failed (${t.code}). Please check your proxy configuration or network settings`;throw new Error(`${t.message}
1278
- ${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}}},N=new dl;var ul=class{async checkJwtToken(e,t,r){let o={refresh:"false",jwtToken:e},s=`${t()}/${r}`,a=await N.get(s,{headers:o});if(a.statusCode!==200)throw new Error(`Failed to check jwtToken: ${a.statusCode}`);return N.parseJson(a)}async refreshToken(e,t){let r=await Ke.loadJwtToken();return r?this.refreshTokenWithToken(r,e,t):null}async refreshTokenWithToken(e,t,r){try{let o={refresh:"true",jwtToken:e},s=`${t()}/${r}`,a=await N.get(s,{headers:o});if(a.statusCode!==200)return null;let c=N.parseJson(a);return!c.status||!c.userInfo?null:{accessToken:c.userInfo.accessToken,refreshToken:c.userInfo.refreshToken??""}}catch(o){let i=o;return console.error(`Failed to refresh token: ${i.code??""} ${i.message??""}`),null}}},Ao=new ul;function Mf(n){try{let e=n.split(".");if(e.length!==3)return null;let r=e[1].replace(/-/g,"+").replace(/_/g,"/"),o=r.padEnd(r.length+(4-r.length%4)%4,"="),i=Buffer.from(o,"base64").toString("utf8");return JSON.parse(i)}catch{return null}}function _f(n){let e=n.split(".");return e.length===3&&e.every(t=>t.length>0)}var pl=class{async getJwtToken(e,t,r,o,i){let s=e.split("&")[0],a=Lf(t),c=r(),l={tempToken:s,site:a,version:Ce.API_VERSION,appid:i},d=`${c}/${o}`,h=await N.get(d,{params:l});if(h.statusCode!==200)throw new Error(`Failed to get jwtToken: status=${h.statusCode}`);let w=h.data.trim();if(!_f(w))throw new Error("Invalid jwtToken format");return w}async getUserInfoFromJwt(e,t){let r=await t(e);if(!r.status||!r.userInfo)throw new Error("Invalid jwtToken");let o=Mf(e);if(!o)throw new Error("Invalid jwtToken: failed to parse payload");return{userId:o.userId,userName:o.userName,accessToken:r.userInfo.accessToken,refreshToken:r.userInfo.refreshToken??"",jwtToken:e,countryCode:r.userInfo.nationalCode,language:Nf(r.userInfo.nationalCode),isRealName:String(r.userInfo.realName)==="true"}}},vs=new pl;var Ss=class{config;server=null;constructor(e){this.config={...no,...e}}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}async login(){try{let e=this.generateClientSecret();this.server=new hs(e,this.getRegionalizedBaseUrl(),this.config.successRedirectUrl,this.config.failedRedirectUrl),await this.server.start(),await this.openLoginPage(this.server.getPort(),e);let t=await this.server.waitForCallback(this.config.timeout);if(t.siteId!=="1")throw new Error("Non-China accounts are not supported.");let r=await vs.getJwtToken(t.tempToken,t.siteId,()=>this.getRegionalizedBaseUrl(),this.config.tempTokenCheckUrl,this.config.appId),o=await vs.getUserInfoFromJwt(r,i=>Ao.checkJwtToken(i,()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl));return await Ke.saveJwtToken(r),o}finally{this.server&&(await this.server.stop(),this.server=null)}}async isLoggedIn(){let e=await Ke.resolveJwtToken();return e==null?!1:(await Ao.checkJwtToken(e.token,()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl)).status?!0:(e.source==="deveco-cli"&&await Ke.clearToken(),!1)}async logout(){let e=await Ke.resolveJwtToken();if(e==null)return!1;if(e.source==="deveco-code")throw new Error("Login is managed by deveco-code. Log out from deveco-code instead.");let r=`${this.getRegionalizedBaseUrl()}/${this.config.logoutUrl}?jwtToken=${e.token}`;try{await N.post(r,{timeout:5e3})}finally{await Ke.clearToken()}return!0}async getUserInfo(){let e=await Ke.loadJwtToken();return e?vs.getUserInfoFromJwt(e,t=>Ao.checkJwtToken(t,()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl)):null}generateClientSecret(){return Ff.randomUUID().replace(/-/g,"")}getRegionalizedBaseUrl(){return ws(this.config.countryCode??"",this.config.baseUrl)}async openLoginPage(e,t){let o=`${this.getRegionalizedBaseUrl()}/${this.config.authUrl}?port=${e}&appid=${this.config.appId}&code=${t}`;await Of(o)}async refreshToken(){return Ao.refreshToken(()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl)}},ae=new Ss;import jf from"axios";var vP="No JWT in local storage. Run `devecocli auth login` first.";function SP(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 bs=class{config;constructor(e){this.config={...no,...e}}updateConfig(e){this.config={...this.config,...e}}async listTeams(){let e=await Ke.loadJwtToken();if(!e)throw new Error(vP);let{accessToken:t,userId:r}=await this.fetchAccessToken(e);if(!t)throw new Error("Session expired. Run `devecocli auth login` again.");let o=await this.fetchTeamList(t,r??""),i=SP(o);return{userId:r??"",teamList:i}}async fetchTeamList(e,t){let r=this.config.agcTeamListUrl;m(`Executing: GET ${r}`);let o;try{o=await jf.request({method:"GET",url:r,headers:{oauth2Token:e,uid:t,source:"cli",lang:"zh_CN"},timeout:15e3,transformResponse:[i=>i],proxy:!1,validateStatus:()=>!0})}catch(i){throw new Error(`Network error while listing teams: ${i.message}`,{cause:i})}if(o.status===401)throw new Error("AGC rejected the AGC token. Run `devecocli auth login` again.");if(o.status!==200)throw new Error(`Failed to list teams: HTTP ${o.status}`);return typeof o.data=="string"?JSON.parse(o.data):o.data}async fetchAccessToken(e){let r=`${this.getRegionalizedBaseUrl()}/${this.config.jwtTokenCheckUrl}`;m(`Executing: GET ${r} (accessToken refresh)`);let o;try{o=await jf.request({method:"GET",url:r,headers:{refresh:"true",jwtToken:e},timeout:15e3,transformResponse:[a=>a],proxy:!1,validateStatus:()=>!0})}catch(a){throw new Error(`Network error while refreshing accessToken: ${a.message}`,{cause:a})}if(o.status!==200)throw new Error(`Failed to refresh accessToken: HTTP ${o.status}. Run \`devecocli auth login\` again.`);let s=typeof o.data=="string"?JSON.parse(o.data):o.data;if(!s.status)throw new Error("JWT is invalid. Run `devecocli auth login` again.");return{accessToken:s.userInfo?.accessToken,userId:s.userInfo?.userId}}getRegionalizedBaseUrl(){return ws(this.config.countryCode??"",this.config.baseUrl)}},Hf=new bs;async function Qt(){return Hf.listTeams()}function EP(n){if(n.length===0)return Xe("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(`
1279
- `)}function PP(){return new Promise(n=>{let e=$f.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),n()})})}var Do=new bP("auth").description("Authentication commands (login, logout, status, team)");Do.command("login").description("Log in to your Huawei Developer account").action(async()=>{try{if(await ae.isLoggedIn()){let t=await ae.getUserInfo();if(t){console.log(Xe(`Already logged in, User Name:${t.userName}`));return}}console.log(Xe("Starting login process...")),console.log(Xe("Press Enter to open browser for login...")),await PP();let e=await ae.login();console.log(Xe(`Login successful. Logged in as ${e.userName}.`))}catch(n){throw new Error("Login failed",{cause:n})}});Do.command("logout").description("Log out of your Huawei Developer account").action(async()=>{try{let n=await ae.logout();console.log(n?Xe("Logout successful"):Xe("Already logged out."))}catch(n){throw new Error("Logout failed",{cause:n})}});Do.command("status").description("Show the currently logged-in user").action(async()=>{try{if(!await ae.isLoggedIn()){console.log(Xe("Not logged in"));return}let e=await ae.getUserInfo();if(!e){console.log(Xe("Not logged in"));return}console.log(Xe(`Current user: ${e.userName}`))}catch{console.log(Xe("Not logged in"))}});var CP=Do.command("team").description("Team-related commands");CP.command("list").description("List team accounts the current user has joined").option("--json","output as JSON",!1).action(async n=>{try{if(!await ae.isLoggedIn()){console.log(Xe("Please run `devecocli auth login` first."));return}let t=await Qt();if(n.json){console.log(JSON.stringify(t,null,2));return}console.log(EP(t.teamList))}catch(e){throw new Error("Failed to list teams",{cause:e})}});var Uf=Do;import{Command as FP}from"commander";import{green as jP,red as No,cyan as lm,yellow as dm,dim as um}from"colorette";import HP from"p-limit";import IP from"ora";var ct=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=IP(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 Bf from"fs";import*as Wf from"path";var Gf=["DevEco"];async function Es(){let n=await N.get(ot.TAGS_API_URL),t=Ps(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 AP(n){let e=[],t=ot.DEFAULT_PAGE_SIZE,r=1;for(;;){let o=await N.post(ot.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:r,pageSize:t,tagIds:[n]}}),i=Ps(o,"Skills API");if(e.push(...i.data.list),i.data.list.length<t)break;r++}return e}async function fl(n){let e=new Map,t=n.map(o=>AP(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=>!Gf.includes(i.name)))}async function DP(n,e){let t=await N.post(ot.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:ot.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return Ps(t,"Skills API").data.list}async function ml(n,e){let t=new Map,r=e.map(i=>DP(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=>!Gf.includes(s.name)))}function zf(n){let e=[],t=Ct();for(let[,r]of Object.entries(t)){let o=Wf.join(r.path,n);Bf.existsSync(o)&&e.push(r.displayName)}return e.sort()}function Ps(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=N.parseJson(n);if(t.code!==ot.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function qf(n){let e=`${ot.SKILL_API_BASE}/${n}/checksum`,t=await N.get(e);return Ps(t,"Checksum API").data}import RP from"adm-zip";import TP from"crypto";import Jf from"fs";import oe from"path";import{fileURLToPath as kP}from"url";import{red as xP}from"colorette";var Ot=Jf.promises;function hl(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}function Vf(n,e){let t=oe.resolve(e),r=oe.resolve(n),o=oe.relative(r,t);if(o.startsWith("..")||oe.isAbsolute(o))throw new Error(`Path traversal detected: ${e}.`)}function gl(n){return oe.isAbsolute(n)?n:oe.resolve(process.cwd(),n)}function NP(n){return TP.createHash("sha256").update(n).digest("hex")}async function LP(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=NP(n),o=e.sha256.toLowerCase();if(r!==o)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function Yf(n){let e=`${ot.SKILL_API_BASE}/${n}/install?format=zip`,t=await N.getBinary(e),r=await qf(n);return await LP(t,r),t}async function OP(n,e,t){hl(t);let r=new RP(n),o=r.getEntries();try{await Ot.stat(e)}catch{await Ot.mkdir(e,{recursive:!0})}let i=oe.join(e,t);Vf(e,i);for(let s of o){let a=oe.join(i,s.entryName);Vf(i,a)}r.extractAllTo(i,!0)}async function yl(n){let e=Ct();if(!e[n])throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(e).join(", ")}`);let r=de[n];try{return await Ot.access(r),!0}catch{return!1}}function wl(n){return Ct()[n].path}function vl(n,e){let r=Ct()[e],o="projectPath"in r?r.projectPath:oe.join("."+e,"skills");return oe.join(n,o)}async function MP(n,e,t){hl(e);let r=oe.join(n,e);try{if(await Ot.access(r),t)await Ot.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 Sl(n,e,t){await OP(n,e,t),console.log(`Skill ${t} installed to ${oe.join(e,t)}.`)}async function bl(n,e,t){let r=oe.join(e,t);await Ot.mkdir(r,{recursive:!0});let o=oe.join(r,oe.basename(n));await Ot.copyFile(n,o),console.log(`Skill ${t} installed to ${r}.`)}function Kf(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(xP(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function yr(n,e,t,r){try{let o=await e(),{shouldSkip:i}=await MP(o,n,r);return i?{success:!0,skipped:!0}:(await t(o),{success:!0})}catch(o){return Kf(n,o,"Installation failed")}}async function El(n,e){try{hl(n);let t=await e(),r=oe.join(t,n);try{await Ot.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await Ot.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return Kf(n,t,"Removal failed")}}async function Xf(n,e,t,r=!1){return yr(n,()=>wl(e),o=>Sl(t,o,n),r)}async function Zf(n,e,t,r=!1){return yr(n,()=>t,o=>Sl(e,o,n),r)}async function Qf(n,e,t,r,o=!1){return yr(n,()=>vl(t,r),i=>Sl(e,i,n),o)}async function em(n,e,t,r=!1){return yr(n,()=>wl(t),o=>bl(e,o,n),r)}async function tm(n,e,t,r,o=!1){return yr(n,()=>vl(t,r),i=>bl(e,i,n),o)}async function nm(n,e,t,r=!1){return yr(n,()=>t,o=>bl(e,o,n),r)}async function rm(n,e){return El(n,()=>wl(e))}async function om(n,e){return El(n,()=>e)}async function im(n,e,t){return El(n,()=>vl(e,t))}function sm(){let e=oe.dirname(kP(import.meta.url));for(;;){let t=oe.join(e,"SKILL.md");if(Jf.existsSync(t))return t;let r=oe.dirname(e);if(r===e)break;e=r}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import am from"fs";import{cyan as _P}from"colorette";async function Ro(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await yl(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function To(){let n=[],e=Ct();for(let t of Object.keys(e))await yl(t)&&n.push(t);return n}function ko(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(_P("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function en(n,e,t){if(!am.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!am.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function xo(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?gl(n):void 0,resolvedProject:e?gl(e):void 0}}async function Cs(n,e,t){let r=[],o=[],i;if(e?i=e:t&&n.agent?o=(await Ro(n.agent)).map(a=>({project:t,agent:a})):t?o=(await To()).map(a=>({project:t,agent:a})):n.agent?r=await Ro(n.agent):r=await To(),!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 $P(n){let e=await Es();if(n.all)return(await fl(e)).map(r=>r.enName);{let r=(await ml(n.skill,e)).find(o=>o.enName===n.skill);if(!r)throw new Error(`Skill "${n.skill}" not found`);return[r.enName]}}async function UP(n,e,t,r){let o=[];if(t.customPath){let i=await Zf(n,e,t.customPath,r);return o.push(i),o}for(let i of t.agents){let s=await Xf(n,i,e,r);o.push(s)}for(let{project:i,agent:s}of t.projectAgents){let a=await Qf(n,e,i,s,r);o.push(a)}return o}function BP(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}=xo(n.path,n.project,n.agent);return t&&en(t,"Project directory",n.force),e&&en(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}async function WP(n,e,t){let r=await Cs(n,e,t);return{skillNames:await $P(n),targets:r}}async function GP(n,e,t,r){let o=[],i=n.length,s=HP(5),a=n.map(c=>s(()=>zP(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(No(`${l}: Download failed - ${h.error}`)),o.push({success:!1});continue}r.stop();let w=await UP(l,h.buffer,e,t);o.push(...w)}return o}async function zP(n){try{let e=await Yf(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 qP(n){let e=new ct;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=BP(n),{skillNames:o,targets:i}=await WP(n,t,r),s=await GP(o,i,n.force||!1,e);e.stop(),ko(s)}catch(t){throw e.stop(),t}}function VP(n){let{resolvedPath:e,resolvedProject:t}=xo(n.path,n.project,n.agent);return t&&en(t,"Project directory"),e&&en(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function JP(n,e){let t=new ct;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:o}=VP(e);t.stop();let i=await YP(e,n,r,o);t.stop(),ko(i)}catch(r){throw t.stop(),r}}function cm(n,e=""){if(n.length===0)throw new Error(`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function Is(n,e){let t=[];for(let r of e){let o=r.type==="agent"?await rm(n,r.agent):await im(n,r.project,r.agent);t.push(o)}return t}async function YP(n,e,t,r){if(t)return[await om(e,t)];if(r&&n.agent){let a=(await Ro(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return Is(e,a)}if(r){let s=await To();cm(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return Is(e,a)}if(n.agent){let a=(await Ro(n.agent)).map(c=>({type:"agent",agent:c}));return Is(e,a)}let o=await To();cm(o,"or use --path for a custom location.");let i=o.map(s=>({type:"agent",agent:s}));return Is(e,i)}var Lo=new FP("skills").description("Manage HarmonyOS skills");Lo.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 ct;try{e.start("Fetching skills...");let t=await Es(),r=await fl(t);if(r.length===0){e.stop(),console.log(dm("No skills available."));return}e.succeed(`Fetched ${r.length} skills`);for(let o of r)if(n.long){console.log(lm(o.enName)),console.log(um(o.description));let i=zf(o.enName);i.length>0&&console.log(jP(`Installed for: ${i.join(", ")}`)),console.log()}else console.log(o.enName)}catch(t){e.stop(),console.error(No(t.message)),process.exit(1)}});Lo.command("find <keyword>").description("Search skills by keyword").action(async n=>{let e=new ct;try{e.start("Searching skills...");let t=await Es(),r=await ml(n,t);if(r.length===0){console.log(dm(`No skills found matching '${n}'.`)),e.stop();return}e.succeed(`Found ${r.length} skills.`);for(let o of r)console.log(lm(o.enName)),console.log(um(o.description)),console.log()}catch(t){e.stop(),console.error(No(t.message)),process.exit(1)}});Lo.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 qP(n)}catch(e){console.error(No(e.message)),process.exit(1)}});Lo.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 JP(n.skill,n)}catch(e){console.error(No(e.message)),process.exit(1)}});var pm=Lo;import{Command as XP,InvalidArgumentError as Ds}from"commander";import{cyan as As}from"colorette";function Hn(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=nr(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 Pl=[800,1500,2500];function KP(n){return new Promise(e=>setTimeout(e,n))}function fm(){return b()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device."}var wr=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=te.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(`
1280
- `)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let o=t[0];return m(As(`Using device serial: ${o}`)),o}if(e&&t.includes(e))return m(As(`Using device serial: ${e}`)),e;let r=await this.loadConnectedDevicesByName();if(e){let o=this.findDeviceByArg(r,e);if(o)return m(As(`Using device: ${o.name} (${o.serial})`)),o.serial;let i=this.formatConnectedDeviceList(r);throw new Error(`Device '${e}' not found.
1273
+ `;function TE(n){let e=n.trim();if(!e)throw new Error("--target must not be empty.");return e}function kE(n){let e=n.trim();if(!uf.includes(e))throw new Error(`Invalid fold state "${n}". Available values: ${uf.join(", ")}`);return e}function ff(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 mf(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&&!xE(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 xE(n,e){let t=n.split(".")[1];return t===void 0||t.length<=e}function NE(n,e,t,r,o){return Number(mf(n,e,t,r,o))}function LE(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 OE(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 ME(n,e){let t=o=>o.normalize("NFKC").trim(),r=t(n);if(e.length===0)throw console.error(vt("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(vt("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(Ie("--os-version does not match any downloaded image (exact string required).")),console.log(vt("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 _E=["Name","Status","Serial","Device Type","OS Version"];function FE(n,e,t){return{cells:[n.name,t?"running":"stopped",e??"-",n.deviceType??"-",n.osVersion??"-"],highlight:t}}async function jE(n,e){let t=await Promise.all(e.map(async r=>{let o=await ir(n,r,DE);return[r,o]}));return new Map(t)}async function HE(n){let e=await qc(n),t=await jE(n,e);return{serials:e,params:t}}function $E(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 UE(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&&$E(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 BE(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=>FE(o.emu,o.serial,o.effectiveRunning))}async function WE(n,e,t){try{let[r,o]=await Promise.all([n.listEmulators(),HE(e)]);if(r.length===0){t?.stop(),console.log(vt(" No emulator instances found."));return}let i=r.filter(l=>l.isRunning).map(l=>l.name),{productSerialMap:s,hvdSerialMap:a}=UE(o.serials,o.params,i);t?.stop();let c=BE(r,s,a);console.log(Lt(_E,c))}catch(r){us(t,`Failed to list emulators: ${r.message}`)}}function hf(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(Ie(`Failed to ${t} emulator "${e[o]}": ${s.message}`)),s.stdout&&console.error(bo(s.stdout)),s.stderr&&console.error(bo(s.stderr))}return r}var GE=2e3,zE=6e4;async function qE(n,e){let t=Se(e);return(await Vc(n)).some(o=>Se(o)===t)}async function gf(n,e,t,r=zE,o=GE){let i=Date.now()+r;for(;Date.now()<i;){if(await qE(n,e)===t)return!0;await new Promise(a=>setTimeout(a,o))}return!1}async function VE(n,e,t){if(await n.startEmulator(t)==="already-running"){console.log(vt(`Emulator "${t}" is already running.`));return}console.log(gr(`Starting emulator "${t}"...`));let o=await gf(e,t,!0);console.log(o?Po(`Emulator "${t}" started successfully.`):vt(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function JE(n,e,t){let r=await Promise.allSettled(t.map(i=>VE(n,e,i)));hf(r,t,"start")&&process.exit(1)}async function yf(n,e){let t=e.trim();if(!On(t))return t;let r=await te.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 YE(n,e,t){let r=await yf(e,t);if(console.log(gr(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(vt(`Emulator "${r}" is already stopped.`));return}let i=await gf(e,r,!1);console.log(i?Po(`Emulator "${r}" stopped successfully.`):vt(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function KE(n,e,t){let r=await Promise.allSettled(t.map(i=>YE(n,e,i)));hf(r,t,"stop")&&process.exit(1)}async function Ke(){try{let n=await I.new();return{manager:mr.from(n),toolProvider:n}}catch(n){console.error(Ie(`Failed to initialize emulator: ${n.message}`)),process.exit(1);return}}async function Ot(n,e){try{let t=TE(n.target),r=e(),{manager:o,toolProvider:i}=await Ke(),s=await yf(i.hdcPath,t);await o.controlEmulator(s,r),console.log(Po(`Emulator "${t}" operation completed.`))}catch(t){let r=n.target?.trim()||"<unknown>";console.error(Ie(`Failed to operate emulator "${r}": ${t.message}`)),process.exit(1)}}function XE(n){let e=[];return fs(e,"longitude",n.longitude,-180,180,8),fs(e,"latitude",n.latitude,-90,90,8),fs(e,"altitude",n.altitude,-1e4,1e4,2),fs(e,"bearing",n.direction,0,359.99,2,"--direction"),sl(e,"Specify one geolocation option.")}function ZE(n){let e=[];return vo(e,"light",n.lightIntensity,0,1e5,!1,"--light-intensity"),vo(e,"humidity",n.humidity,0,100,!1),vo(e,"temperature",n.temperature,-273.1,100,!1),vo(e,"steps",n.steps,0,1e4,!0),vo(e,"heartrate",n.heartrate,0,255,!0),sl(e,"Specify one sensor option.")}function sl(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 fs(n,e,t,r,o,i,s=`--${e}`){t!==void 0&&n.push({type:"gps",key:e,value:mf(s,t,r,o,i)})}function vo(n,e,t,r,o,i,s=`--${e}`){if(t===void 0)return;let a=i?ff(s,t,r,o):NE(s,t,r,o,1);n.push({type:"sensor",key:e,value:a})}function QE(n){let e=[];return n.level!==void 0&&e.push({type:"battery",level:ff("--level",n.level,1,100)}),n.status!==void 0&&e.push({type:"battery-status",status:n.status==="charging"?1:0}),sl(e,"Specify --level or --status.")}var me=new il("emulator").description("Manage emulator instances"),eP=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function ms(n){let e=new Eo("--device-type <type>","Emulator device type").choices([...eP]);return n?e.makeOptionMandatory():e}function hr(n,e){for(let t of e)if(t in n)return n[t]}function So(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function pf(n){let e=So(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var tP=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],nP="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function wf(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function vf(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let o=r,i=So(hr(o,["osVersion","OsVersion","OSVersion","os_version"])),s=So(hr(o,["deviceType","DeviceType","device_type"])),a=pf(hr(o,["downloaded","Downloaded","isDownloaded"])),c=So(hr(o,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=So(hr(o,["releaseType","ReleaseType","release_type"])),d=pf(hr(o,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[i,s,c,l,d,a],highlight:e&&a==="true"})}return t}function rP(n){let e=n.trim();if(!e)return!0;let t=wf(e);return t===null?!1:t.length===0?!0:vf(t,!0).length===0}function oP(n,e){let t=n.trim();if(!t)return"";let r=wf(t);if(!r)return n.trimEnd();let o=vf(r,e);return Lt(tP,o)}var hs=new il("image").description("HarmonyOS emulator system images (download, list, remove)");hs.command("download").description("Download system image").addOption(ms(!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 Ke();try{await rl(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof Ye&&(console.error(Ie(r.message)),process.exit(1)),r}n.deviceType?.trim()||(console.error(Ie("Error: missing required option '--device-type <type>'")),process.exit(1)),n.osVersion?.trim()||(console.error(Ie("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(Ie(`Failed to download system image: ${r.message}`)),process.exit(1)}});hs.command("remove").description("Remove a downloaded system image").addOption(ms(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let{manager:e}=await Ke();try{await e.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})}catch(t){console.error(Ie(`Failed to remove system image: ${t.message}`)),process.exit(1)}});hs.command("list").description("List system images").addOption(ms(!1)).option("--all","List all images (local and remote)").addOption(new Eo("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let{manager:e}=await Ke();try{let t;n.all?t=void 0:t=!0;let r=await e.listEmulatorImages({deviceType:n.deviceType,downloaded:t});if(rP(r)){console.log(vt(nP));return}if(n.format==="json"){console.log(r.trimEnd());return}let o=oP(r,n.all===!0);console.log(o)}catch(t){console.error(Ie(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});me.addCommand(hs);var gs=new il("license").description("Review and accept emulator license agreements interactively (prints full text + y/N prompt)");gs.command("view").description("Review agreement text (read-only, no changes)").action(async()=>{let{toolProvider:n}=await Ke(),e=await af(n.emulatorPath,n.sdkPath);process.exit(e)});gs.command("accept").description("Accept all emulator license agreements non-interactively (skips review and prompt)").action(async()=>{let{toolProvider:n}=await Ke(),e=await df(n.emulatorPath,n.sdkPath);process.exit(e)});gs.action(async()=>{let{toolProvider:n}=await Ke(),e=await lf(n.emulatorPath,n.sdkPath);process.exit(e)});me.addCommand(gs);me.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Ot(n,()=>({type:"shake"})));me.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Ot(n,()=>({type:"power"})));me.command("rotate").description("Rotate emulator").addOption(new Eo("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new ol("<direction>").choices(["left","right"])).action((n,e)=>Ot(e,()=>({type:"rotation",direction:n})));me.command("volume").description("Change volume").addOption(new Eo("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new ol("<direction>").choices(["up","down"])).action((n,e)=>Ot(e,()=>({type:"volume",direction:n})));me.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",RE).action((n,e)=>Ot(e,()=>({type:"folded-state",state:kE(n)})));me.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 Eo("--status <status>","Charging status").choices(["charging","discharging"])).action(n=>Ot(n,()=>QE(n)));me.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=>Ot(n,()=>XE(n)));me.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new ol("<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 Ot(e,()=>t[n])});me.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=>Ot(n,()=>ZE(n)));me.command("list").description("List all emulator instances").action(async()=>{let{manager:n,toolProvider:e}=await Ke(),t=AE({text:"Listing emulators\u2026",color:"cyan"}).start();await WE(n,e.hdcPath,t)});me.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let{manager:e,toolProvider:t}=await Ke();try{await nl(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof Ye&&(console.error(Ie(r.message)),process.exit(1)),r}n?.length||(console.error(Ie("Error: missing required argument 'names'")),process.exit(1)),await JE(e,t.hdcPath,n)});me.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 Ke();n?.length||(console.error(Ie("Error: missing required argument 'names'")),process.exit(1)),await KE(e,t.hdcPath,n)});var Sf=me.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(ms(!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");Sf.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
1274
+ ${vt("Tip: ")}${bo("Unquoted --os-version values with spaces/parentheses are split into multiple arguments. Use:")}
1275
+ ${gr('devecocli emulator create 123 --device-type phone --os-version "HarmonyOS 6.0.1(21)"')}
1276
+ ${gr('devecocli emulator create 123 --device-type phone --os-version="HarmonyOS 6.0.1(21)"')}
1277
+ `)}});Sf.action(async(n,e)=>{try{LE(n),OE(e.osVersion);let{manager:t}=await Ke(),r=await t.listDownloadedImageOsVersions();ME(e.osVersion,r),console.log(gr(`Creating emulator "${n}"...`)),await t.createVirtualDevice({name:n,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(Po(`Emulator "${n}" created successfully.`))}catch(t){console.error(Ie(`${t.message}`)),process.exit(1)}});me.command("delete <name>").description("Delete a local emulator instance").action(async n=>{let{manager:e}=await Ke();console.log(gr(`Deleting emulator "${n}"...`));try{let t=await e.deleteVirtualDevice(n);console.log(Po(`Emulator "${t}" deleted successfully.`))}catch(t){let r=t;console.error(Ie(r.message)),r.stdout&&console.error(bo(r.stdout)),r.stderr&&console.error(bo(r.stderr)),process.exit(1)}});var bf=me;import{Command as EP}from"commander";import{cyan as Ze}from"colorette";import*as Uf from"readline";import*as jf from"crypto";import*as Ef from"http";import*as Pf from"crypto";import{URL as iP}from"url";var ys=class{server=null;port=0;clientSecret;callbackPath="/callback";resolveCallback=null;rejectCallback=null;timeoutId=null;baseUrl;successRedirectUrl;failedRedirectUrl;constructor(e,t,r,o){this.clientSecret=e,this.baseUrl=t,this.successRedirectUrl=r,this.failedRedirectUrl=o}async start(){return new Promise((e,t)=>{let r=Ef.createServer((o,i)=>{this.handleRequest(o,i)});r.keepAliveTimeout=1,r.on("error",o=>{t(new Error("Failed to start local auth server",{cause:o}))}),r.listen(0,"127.0.0.1",()=>{this.server=r;let o=r.address();this.port=o.port,e()})})}async waitForCallback(e=3e4){return new Promise((t,r)=>{this.resolveCallback=o=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),t(o)},this.rejectCallback=o=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),r(o)},this.timeoutId=setTimeout(()=>{this.timeoutId=null,this.rejectCallback?.(new Error("Callback timeout"))},e)})}async stop(){return this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.server?new Promise(e=>{let t=this.server;this.server=null,typeof t.closeAllConnections=="function"&&t.closeAllConnections();let r=setTimeout(()=>{e()},100);t.close(()=>{clearTimeout(r),e()})}):Promise.resolve()}handleRequest(e,t){let r=e.headers.host||"";if(![`127.0.0.1:${this.port}`,`localhost:${this.port}`].includes(r.toLowerCase())){t.writeHead(400),t.end("Bad Host");return}let i=new iP(e.url??"",`http://${r}`);if(i.pathname!==this.callbackPath){t.writeHead(404),t.end("Not Found");return}try{let s=i.searchParams;if(e.method==="POST"){let a="";e.on("data",c=>{a+=c.toString()}),e.on("end",()=>{this.handleCallbackRequest(e,t,s,a)})}else this.handleCallbackRequest(e,t,s,"")}catch(s){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(s)}}handleCallbackRequest(e,t,r,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&&Pf.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 Ne from"fs";import*as wr from"path";import{homedir as pP}from"os";var Mt={};ov(Mt,{LocalCrypto:()=>Mt,decryptForLocalStorage:()=>lP,decryptForLocalStorageFromDirectory:()=>dP,encryptForLocalStorage:()=>cP,isEncryptedBlob:()=>uP});import*as J from"fs";import*as Hn from"path";import*as xe from"crypto";import{homedir as Cf}from"os";var Co=Rn.ALGORITHM,If=Rn.IV_LENGTH,Io=Rn.KEY_LENGTH,Ao=Rn.KEY_LENGTH,Do=Rn.KEK_VERSIONS,al=process.env.DEVECO_CLI_DATA_DIR||Hn.join(Cf(),Ce.CONFIG_DIR_NAME,Ce.APP_NAME),cl=Hn.join(Cf(),".local","share",Ce.APP_NAME,"keys"),yr=Hn.join(al,Ce.KEY_FILE_NAME);function ll(n){return Hn.join(cl,`${n}.bin`)}function Af(){J.existsSync(al)||J.mkdirSync(al,{recursive:!0,mode:448}),J.existsSync(cl)||J.mkdirSync(cl,{recursive:!0,mode:448})}function Df(){Af();for(let n of Do){let e=ll(n);J.existsSync(e)||J.writeFileSync(e,xe.randomBytes(Io),{mode:384})}}function Rf(n){Df();let e=ll(n),t=J.readFileSync(e);if(t.length===Io)return t;let r=xe.randomBytes(Io);return J.writeFileSync(e,r,{mode:384}),r}function dl(n,e){let t=xe.randomBytes(If),r=Rf(e),o=xe.createCipheriv(Co,r,t),i=Buffer.concat([o.update(n),o.final()]),s=o.getAuthTag();return{version:1,algorithm:Co,kekId:e,encryptedDek:i.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function Tf(n,e){return kf(Buffer.from(n.encryptedDek,"base64"),e,n.iv,n.authTag)}function kf(n,e,t,r){let o=xe.createDecipheriv(Co,e,Buffer.from(t,"base64"));return o.setAuthTag(Buffer.from(r,"base64")),Buffer.concat([o.update(n),o.final()])}function xf(n,e){return kf(Buffer.from(n.ciphertext,"base64"),e,n.iv,n.authTag).toString("utf8")}function sP(){if(Df(),J.existsSync(yr))return;let n=xe.randomBytes(Ao),e=dl(n,Do[0]);J.writeFileSync(yr,JSON.stringify(e,null,2),{mode:384})}function Nf(){sP();let n=JSON.parse(J.readFileSync(yr,"utf8")),e=Tf(n,Rf(n.kekId));if(e.length===Ao)return e;let t=xe.randomBytes(Ao),r=dl(t,Do[0]);return J.writeFileSync(yr,JSON.stringify(r,null,2),{mode:384}),t}function aP(){Af();for(let t of Do){let r=ll(t);J.existsSync(r)||J.writeFileSync(r,xe.randomBytes(Io),{mode:384})}if(J.existsSync(yr))return;let n=xe.randomBytes(Ao),e=dl(n,Do[0]);J.writeFileSync(yr,JSON.stringify(e,null,2),{mode:384})}function cP(n){let e=Nf(),t=xe.randomBytes(If),r=xe.createCipheriv(Co,e,t),o=Buffer.concat([r.update(n,"utf8"),r.final()]),i=r.getAuthTag();return{version:1,algorithm:Co,ciphertext:o.toString("base64"),iv:t.toString("base64"),authTag:i.toString("base64"),timeStamp:Date.now()}}function lP(n){try{return xf(n,Nf())}catch{throw aP(),new Error("Failed to decrypt local ciphertext")}}function dP(n,e){let t=Hn.join(e,Ce.KEY_FILE_NAME),r=JSON.parse(J.readFileSync(t,"utf8")),o=Hn.join(e,"keys",`${r.kekId}.bin`),i=J.readFileSync(o);if(i.length!==Io)throw new Error("Invalid external root key");let s=Tf(r,i);if(s.length!==Ao)throw new Error("Invalid external data encryption key");return xf(n,s)}function uP(n){if(!n||typeof n!="object")return!1;let e=n;return e.algorithm==="aes-256-gcm"&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}var ws=class{tokenFilePath;constructor(e){let t=e||process.env.DEVECO_CLI_DATA_DIR||wr.join(pP(),Ce.CONFIG_DIR_NAME,Ce.APP_NAME);this.tokenFilePath=wr.join(t,Ce.TOKEN_FILE_NAME)}ensureConfigDir(){let e=wr.dirname(this.tokenFilePath);Ne.existsSync(e)||Ne.mkdirSync(e,{recursive:!0,mode:448})}async saveJwtToken(e){if(!e)throw new Error("Token is empty");let t=Mt.encryptForLocalStorage(e);this.ensureConfigDir(),Ne.writeFileSync(this.tokenFilePath,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){return(await this.resolveJwtToken())?.token??null}async resolveJwtToken(){let e=this.loadDevecoCodeToken();if(e)return{token:e,source:"deveco-code"};let t=await this.loadLocalJwtToken();return t?{token:t,source:"deveco-cli"}:null}loadDevecoCodeToken(){if(process.env.DEVECO_CLI_AUTH_SOURCE!=="deveco-code")return null;let e=process.env.DEVECO_CODE_AUTH_DIR?.trim();if(!e)return null;try{let t=wr.join(e,Ce.TOKEN_FILE_NAME);if(!Ne.existsSync(t))return null;let r=JSON.parse(Ne.readFileSync(t,"utf8"));return Mt.isEncryptedBlob(r)?Mt.decryptForLocalStorageFromDirectory(r,e):null}catch{return null}}async loadLocalJwtToken(){try{if(!Ne.existsSync(this.tokenFilePath))return null;let e=JSON.parse(Ne.readFileSync(this.tokenFilePath,"utf8"));return Mt.isEncryptedBlob(e)?Mt.decryptForLocalStorage(e):null}catch{return await this.clearToken(),null}}async clearToken(){try{Ne.existsSync(this.tokenFilePath)&&Ne.unlinkSync(this.tokenFilePath)}catch(e){throw new Error("Failed to clear token",{cause:e})}}},Xe=new ws;var St={CHINA:"CN",RUSSIA:"RU",SINGAPORE:"SG",EUROPE:"EU"},Ro={CHINA:"zh_CN",RUSSIA:"ru_RU",EUROPE:"de_DE"},vs={CHINA:"1",SINGAPORE:"5",EUROPE:"7",RUSSIA:"8"},fP={[St.CHINA]:Ro.CHINA,[St.RUSSIA]:Ro.RUSSIA,[St.EUROPE]:Ro.EUROPE,[St.SINGAPORE]:Ro.CHINA},mP={[vs.CHINA]:St.CHINA,[vs.SINGAPORE]:St.SINGAPORE,[vs.EUROPE]:St.EUROPE,[vs.RUSSIA]:St.RUSSIA};function Lf(n){return fP[n]??Ro.CHINA}function Of(n){return mP[n]??St.CHINA}function Ss(n,e){return n?.toUpperCase()===St.CHINA?rt.CN_LOGIN_URL:e}import{exec as hP}from"child_process";import{promisify as gP}from"util";var yP=gP(hP);async function Mf(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 yP(t)}catch(r){throw new Error("Failed to open browser",{cause:r})}}import wP from"axios";var ul=class{client;constructor(){let e={timeout:oo.HTTP_TIMEOUT_MS,headers:{"User-Agent":Ni.USER_AGENT,"accept-language":Ni.ACCEPT_LANGUAGE},transformResponse:[t=>t],proxy:!1};this.client=wP.create(e),this.client.interceptors.response.use(t=>t,t=>{let r=`Network connection failed (${t.code}). Please check your proxy configuration or network settings`;throw new Error(`${t.message}
1278
+ ${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}}},N=new ul;var pl=class{async checkJwtToken(e,t,r){let o={refresh:"false",jwtToken:e},s=`${t()}/${r}`,a=await N.get(s,{headers:o});if(a.statusCode!==200)throw new Error(`Failed to check jwtToken: ${a.statusCode}`);return N.parseJson(a)}async refreshToken(e,t){let r=await Xe.loadJwtToken();return r?this.refreshTokenWithToken(r,e,t):null}async refreshTokenWithToken(e,t,r){try{let o={refresh:"true",jwtToken:e},s=`${t()}/${r}`,a=await N.get(s,{headers:o});if(a.statusCode!==200)return null;let c=N.parseJson(a);return!c.status||!c.userInfo?null:{accessToken:c.userInfo.accessToken,refreshToken:c.userInfo.refreshToken??""}}catch(o){let i=o;return console.error(`Failed to refresh token: ${i.code??""} ${i.message??""}`),null}}},To=new pl;function _f(n){try{let e=n.split(".");if(e.length!==3)return null;let r=e[1].replace(/-/g,"+").replace(/_/g,"/"),o=r.padEnd(r.length+(4-r.length%4)%4,"="),i=Buffer.from(o,"base64").toString("utf8");return JSON.parse(i)}catch{return null}}function Ff(n){let e=n.split(".");return e.length===3&&e.every(t=>t.length>0)}var fl=class{async getJwtToken(e,t,r,o,i){let s=e.split("&")[0],a=Of(t),c=r(),l={tempToken:s,site:a,version:Ce.API_VERSION,appid:i},d=`${c}/${o}`,h=await N.get(d,{params:l});if(h.statusCode!==200)throw new Error(`Failed to get jwtToken: status=${h.statusCode}`);let w=h.data.trim();if(!Ff(w))throw new Error("Invalid jwtToken format");return w}async getUserInfoFromJwt(e,t){let r=await t(e);if(!r.status||!r.userInfo)throw new Error("Invalid jwtToken");let o=_f(e);if(!o)throw new Error("Invalid jwtToken: failed to parse payload");return{userId:o.userId,userName:o.userName,accessToken:r.userInfo.accessToken,refreshToken:r.userInfo.refreshToken??"",jwtToken:e,countryCode:r.userInfo.nationalCode,language:Lf(r.userInfo.nationalCode),isRealName:String(r.userInfo.realName)==="true"}}},bs=new fl;var Es=class{config;server=null;constructor(e){this.config={...io,...e}}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}async login(){try{let e=this.generateClientSecret();this.server=new ys(e,this.getRegionalizedBaseUrl(),this.config.successRedirectUrl,this.config.failedRedirectUrl),await this.server.start(),await this.openLoginPage(this.server.getPort(),e);let t=await this.server.waitForCallback(this.config.timeout);if(t.siteId!=="1")throw new Error("Non-China accounts are not supported.");let r=await bs.getJwtToken(t.tempToken,t.siteId,()=>this.getRegionalizedBaseUrl(),this.config.tempTokenCheckUrl,this.config.appId),o=await bs.getUserInfoFromJwt(r,i=>To.checkJwtToken(i,()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl));return await Xe.saveJwtToken(r),o}finally{this.server&&(await this.server.stop(),this.server=null)}}async isLoggedIn(){let e=await Xe.resolveJwtToken();return e==null?!1:(await To.checkJwtToken(e.token,()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl)).status?!0:(e.source==="deveco-cli"&&await Xe.clearToken(),!1)}async logout(){let e=await Xe.resolveJwtToken();if(e==null)return!1;if(e.source==="deveco-code")throw new Error("Login is managed by deveco-code. Log out from deveco-code instead.");let r=`${this.getRegionalizedBaseUrl()}/${this.config.logoutUrl}?jwtToken=${e.token}`;try{await N.post(r,{timeout:5e3})}finally{await Xe.clearToken()}return!0}async getUserInfo(){let e=await Xe.loadJwtToken();return e?bs.getUserInfoFromJwt(e,t=>To.checkJwtToken(t,()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl)):null}generateClientSecret(){return jf.randomUUID().replace(/-/g,"")}getRegionalizedBaseUrl(){return Ss(this.config.countryCode??"",this.config.baseUrl)}async openLoginPage(e,t){let o=`${this.getRegionalizedBaseUrl()}/${this.config.authUrl}?port=${e}&appid=${this.config.appId}&code=${t}`;await Mf(o)}async refreshToken(){return To.refreshToken(()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl)}},ae=new Es;import Hf from"axios";var SP="No JWT in local storage. Run `devecocli auth login` first.";function bP(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 Ps=class{config;constructor(e){this.config={...io,...e}}updateConfig(e){this.config={...this.config,...e}}async listTeams(){let e=await Xe.loadJwtToken();if(!e)throw new Error(SP);let{accessToken:t,userId:r}=await this.fetchAccessToken(e);if(!t)throw new Error("Session expired. Run `devecocli auth login` again.");let o=await this.fetchTeamList(t,r??""),i=bP(o);return{userId:r??"",teamList:i}}async fetchTeamList(e,t){let r=this.config.agcTeamListUrl;m(`Executing: GET ${r}`);let o;try{o=await Hf.request({method:"GET",url:r,headers:{oauth2Token:e,uid:t,source:"cli",lang:"zh_CN"},timeout:15e3,transformResponse:[i=>i],proxy:!1,validateStatus:()=>!0})}catch(i){throw new Error(`Network error while listing teams: ${i.message}`,{cause:i})}if(o.status===401)throw new Error("AGC rejected the AGC token. Run `devecocli auth login` again.");if(o.status!==200)throw new Error(`Failed to list teams: HTTP ${o.status}`);return typeof o.data=="string"?JSON.parse(o.data):o.data}async fetchAccessToken(e){let r=`${this.getRegionalizedBaseUrl()}/${this.config.jwtTokenCheckUrl}`;m(`Executing: GET ${r} (accessToken refresh)`);let o;try{o=await Hf.request({method:"GET",url:r,headers:{refresh:"true",jwtToken:e},timeout:15e3,transformResponse:[a=>a],proxy:!1,validateStatus:()=>!0})}catch(a){throw new Error(`Network error while refreshing accessToken: ${a.message}`,{cause:a})}if(o.status!==200)throw new Error(`Failed to refresh accessToken: HTTP ${o.status}. Run \`devecocli auth login\` again.`);let s=typeof o.data=="string"?JSON.parse(o.data):o.data;if(!s.status)throw new Error("JWT is invalid. Run `devecocli auth login` again.");return{accessToken:s.userInfo?.accessToken,userId:s.userInfo?.userId}}getRegionalizedBaseUrl(){return Ss(this.config.countryCode??"",this.config.baseUrl)}},$f=new Ps;async function tn(){return $f.listTeams()}function PP(n){if(n.length===0)return Ze("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(`
1279
+ `)}function CP(){return new Promise(n=>{let e=Uf.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),n()})})}var ko=new EP("auth").description("Authentication commands (login, logout, status, team)");ko.command("login").description("Log in to your Huawei Developer account").action(async()=>{try{if(await ae.isLoggedIn()){let t=await ae.getUserInfo();if(t){console.log(Ze(`Already logged in, User Name:${t.userName}`));return}}console.log(Ze("Starting login process...")),console.log(Ze("Press Enter to open browser for login...")),await CP();let e=await ae.login();console.log(Ze(`Login successful. Logged in as ${e.userName}.`))}catch(n){throw new Error("Login failed",{cause:n})}});ko.command("logout").description("Log out of your Huawei Developer account").action(async()=>{try{let n=await ae.logout();console.log(n?Ze("Logout successful"):Ze("Already logged out."))}catch(n){throw new Error("Logout failed",{cause:n})}});ko.command("status").description("Show the currently logged-in user").action(async()=>{try{if(!await ae.isLoggedIn()){console.log(Ze("Not logged in"));return}let e=await ae.getUserInfo();if(!e){console.log(Ze("Not logged in"));return}console.log(Ze(`Current user: ${e.userName}`))}catch{console.log(Ze("Not logged in"))}});var IP=ko.command("team").description("Team-related commands");IP.command("list").description("List team accounts the current user has joined").option("--json","output as JSON",!1).action(async n=>{try{if(!await ae.isLoggedIn()){console.log(Ze("Please run `devecocli auth login` first."));return}let t=await tn();if(n.json){console.log(JSON.stringify(t,null,2));return}console.log(PP(t.teamList))}catch(e){throw new Error("Failed to list teams",{cause:e})}});var Bf=ko;import{Command as jP}from"commander";import{green as HP,red as Mo,cyan as dm,yellow as um,dim as pm}from"colorette";import $P from"p-limit";import AP from"ora";var lt=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=AP(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 Wf from"fs";import*as Gf from"path";var zf=["DevEco"];async function Cs(){let n=await N.get(ot.TAGS_API_URL),t=Is(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 DP(n){let e=[],t=ot.DEFAULT_PAGE_SIZE,r=1;for(;;){let o=await N.post(ot.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:r,pageSize:t,tagIds:[n]}}),i=Is(o,"Skills API");if(e.push(...i.data.list),i.data.list.length<t)break;r++}return e}async function ml(n){let e=new Map,t=n.map(o=>DP(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 RP(n,e){let t=await N.post(ot.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:ot.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return Is(t,"Skills API").data.list}async function hl(n,e){let t=new Map,r=e.map(i=>RP(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 qf(n){let e=[],t=At();for(let[,r]of Object.entries(t)){let o=Gf.join(r.path,n);Wf.existsSync(o)&&e.push(r.displayName)}return e.sort()}function Is(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=N.parseJson(n);if(t.code!==ot.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Vf(n){let e=`${ot.SKILL_API_BASE}/${n}/checksum`,t=await N.get(e);return Is(t,"Checksum API").data}import TP from"adm-zip";import kP from"crypto";import Yf from"fs";import oe from"path";import{fileURLToPath as xP}from"url";import{red as NP}from"colorette";var _t=Yf.promises;function gl(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}function Jf(n,e){let t=oe.resolve(e),r=oe.resolve(n),o=oe.relative(r,t);if(o.startsWith("..")||oe.isAbsolute(o))throw new Error(`Path traversal detected: ${e}.`)}function yl(n){return oe.isAbsolute(n)?n:oe.resolve(process.cwd(),n)}function LP(n){return kP.createHash("sha256").update(n).digest("hex")}async function OP(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=LP(n),o=e.sha256.toLowerCase();if(r!==o)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function Kf(n){let e=`${ot.SKILL_API_BASE}/${n}/install?format=zip`,t=await N.getBinary(e),r=await Vf(n);return await OP(t,r),t}async function MP(n,e,t){gl(t);let r=new TP(n),o=r.getEntries();try{await _t.stat(e)}catch{await _t.mkdir(e,{recursive:!0})}let i=oe.join(e,t);Jf(e,i);for(let s of o){let a=oe.join(i,s.entryName);Jf(i,a)}r.extractAllTo(i,!0)}async function wl(n){let e=At();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 vl(n){return At()[n].path}function Sl(n,e){let r=At()[e],o="projectPath"in r?r.projectPath:oe.join("."+e,"skills");return oe.join(n,o)}async function _P(n,e,t){gl(e);let r=oe.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 bl(n,e,t){await MP(n,e,t),console.log(`Skill ${t} installed to ${oe.join(e,t)}.`)}async function El(n,e,t){let r=oe.join(e,t);await _t.mkdir(r,{recursive:!0});let o=oe.join(r,oe.basename(n));await _t.copyFile(n,o),console.log(`Skill ${t} installed to ${r}.`)}function Xf(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(NP(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function vr(n,e,t,r){try{let o=await e(),{shouldSkip:i}=await _P(o,n,r);return i?{success:!0,skipped:!0}:(await t(o),{success:!0})}catch(o){return Xf(n,o,"Installation failed")}}async function Pl(n,e){try{gl(n);let t=await e(),r=oe.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 Xf(n,t,"Removal failed")}}async function Zf(n,e,t,r=!1){return vr(n,()=>vl(e),o=>bl(t,o,n),r)}async function Qf(n,e,t,r=!1){return vr(n,()=>t,o=>bl(e,o,n),r)}async function em(n,e,t,r,o=!1){return vr(n,()=>Sl(t,r),i=>bl(e,i,n),o)}async function tm(n,e,t,r=!1){return vr(n,()=>vl(t),o=>El(e,o,n),r)}async function nm(n,e,t,r,o=!1){return vr(n,()=>Sl(t,r),i=>El(e,i,n),o)}async function rm(n,e,t,r=!1){return vr(n,()=>t,o=>El(e,o,n),r)}async function om(n,e){return Pl(n,()=>vl(e))}async function im(n,e){return Pl(n,()=>e)}async function sm(n,e,t){return Pl(n,()=>Sl(e,t))}function am(){let e=oe.dirname(xP(import.meta.url));for(;;){let t=oe.join(e,"SKILL.md");if(Yf.existsSync(t))return t;let r=oe.dirname(e);if(r===e)break;e=r}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import cm from"fs";import{cyan as FP}from"colorette";async function xo(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await wl(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function No(){let n=[],e=At();for(let t of Object.keys(e))await wl(t)&&n.push(t);return n}function Lo(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(FP("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function nn(n,e,t){if(!cm.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!cm.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function Oo(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?yl(n):void 0,resolvedProject:e?yl(e):void 0}}async function As(n,e,t){let r=[],o=[],i;if(e?i=e:t&&n.agent?o=(await xo(n.agent)).map(a=>({project:t,agent:a})):t?o=(await No()).map(a=>({project:t,agent:a})):n.agent?r=await xo(n.agent):r=await No(),!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 UP(n){let e=await Cs();if(n.all)return(await ml(e)).map(r=>r.enName);{let r=(await hl(n.skill,e)).find(o=>o.enName===n.skill);if(!r)throw new Error(`Skill "${n.skill}" not found`);return[r.enName]}}async function BP(n,e,t,r){let o=[];if(t.customPath){let i=await Qf(n,e,t.customPath,r);return o.push(i),o}for(let i of t.agents){let s=await Zf(n,i,e,r);o.push(s)}for(let{project:i,agent:s}of t.projectAgents){let a=await em(n,e,i,s,r);o.push(a)}return o}function WP(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}=Oo(n.path,n.project,n.agent);return t&&nn(t,"Project directory",n.force),e&&nn(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}async function GP(n,e,t){let r=await As(n,e,t);return{skillNames:await UP(n),targets:r}}async function zP(n,e,t,r){let o=[],i=n.length,s=$P(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(Mo(`${l}: Download failed - ${h.error}`)),o.push({success:!1});continue}r.stop();let w=await BP(l,h.buffer,e,t);o.push(...w)}return o}async function qP(n){try{let e=await Kf(n);return{name:n,buffer:e,success:!0}}catch(e){let t=e instanceof Error?e.message:"unknown error";return{name:n,error:t,success:!1}}}async function VP(n){let e=new lt;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=WP(n),{skillNames:o,targets:i}=await GP(n,t,r),s=await zP(o,i,n.force||!1,e);e.stop(),Lo(s)}catch(t){throw e.stop(),t}}function JP(n){let{resolvedPath:e,resolvedProject:t}=Oo(n.path,n.project,n.agent);return t&&nn(t,"Project directory"),e&&nn(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function YP(n,e){let t=new lt;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:o}=JP(e);t.stop();let i=await KP(e,n,r,o);t.stop(),Lo(i)}catch(r){throw t.stop(),r}}function lm(n,e=""){if(n.length===0)throw new Error(`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function Ds(n,e){let t=[];for(let r of e){let o=r.type==="agent"?await om(n,r.agent):await sm(n,r.project,r.agent);t.push(o)}return t}async function KP(n,e,t,r){if(t)return[await im(e,t)];if(r&&n.agent){let a=(await xo(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return Ds(e,a)}if(r){let s=await No();lm(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return Ds(e,a)}if(n.agent){let a=(await xo(n.agent)).map(c=>({type:"agent",agent:c}));return Ds(e,a)}let o=await No();lm(o,"or use --path for a custom location.");let i=o.map(s=>({type:"agent",agent:s}));return Ds(e,i)}var _o=new jP("skills").description("Manage HarmonyOS skills");_o.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 lt;try{e.start("Fetching skills...");let t=await Cs(),r=await ml(t);if(r.length===0){e.stop(),console.log(um("No skills available."));return}e.succeed(`Fetched ${r.length} skills`);for(let o of r)if(n.long){console.log(dm(o.enName)),console.log(pm(o.description));let i=qf(o.enName);i.length>0&&console.log(HP(`Installed for: ${i.join(", ")}`)),console.log()}else console.log(o.enName)}catch(t){e.stop(),console.error(Mo(t.message)),process.exit(1)}});_o.command("find <keyword>").description("Search skills by keyword").action(async n=>{let e=new lt;try{e.start("Searching skills...");let t=await Cs(),r=await hl(n,t);if(r.length===0){console.log(um(`No skills found matching '${n}'.`)),e.stop();return}e.succeed(`Found ${r.length} skills.`);for(let o of r)console.log(dm(o.enName)),console.log(pm(o.description)),console.log()}catch(t){e.stop(),console.error(Mo(t.message)),process.exit(1)}});_o.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 VP(n)}catch(e){console.error(Mo(e.message)),process.exit(1)}});_o.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 YP(n.skill,n)}catch(e){console.error(Mo(e.message)),process.exit(1)}});var fm=_o;import{Command as ZP,InvalidArgumentError as Ts}from"commander";import{cyan as Rs}from"colorette";function $n(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=or(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 Cl=[800,1500,2500];function XP(n){return new Promise(e=>setTimeout(e,n))}function mm(){return b()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device."}var Sr=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=te.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(`
1280
+ `)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let o=t[0];return m(Rs(`Using device serial: ${o}`)),o}if(e&&t.includes(e))return m(Rs(`Using device serial: ${e}`)),e;let r=await this.loadConnectedDevicesByName();if(e){let o=this.findDeviceByArg(r,e);if(o)return m(Rs(`Using device: ${o.name} (${o.serial})`)),o.serial;let i=this.formatConnectedDeviceList(r);throw new Error(`Device '${e}' not found.
1281
1281
  Available devices:
1282
- ${i}`)}if(r.length===1){let o=r[0];return m(As(`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(fm());return e.map(t=>t.serial)}async getConnectedDevices(){let e=await this.deviceManager.listDevicesWithName();if(e.length===0)throw new Error(fm());return e}async getPidForBundle(e,t,r){m(`Retrieving PID for bundle ${r}`),P.assertBundleNameStrict(r);let o=await se(e,["-t",t,"shell","pidof",r]),i=Hn(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 m(`Found PID for ${r}: ${a}`),a}return m(`No PID found for bundle: ${r}`),null}async resizeHilogBuffer(e,t,r){m(`Setting hilog buffer size to: ${r}`);let o=await se(e,["-t",t,"shell","hilog","-G",r]),i=Hn(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&&(P.assertHilogToken(e.tag,"tag"),r.push("-T",e.tag)),e.level&&(P.assertHilogLevel(e.level),r.push("-L",e.level)),e.domain&&(P.assertHilogToken(e.domain,"domain"),r.push("-D",e.domain)),t&&r.push("-P",t),e.keyword&&(P.assertHilogKeyword(e.keyword),r.push("-e",P.quotePosixShellArg(e.keyword))),r.join(" ")}async followHilog(e,t,r,o,i){let a=await np(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+Pl.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||nr(a.stderr)!=="transient"||c>=s-1)return a;m(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${Pl[c]}ms`),await KP(Pl[c])}return a}async runHilogStreamingCollect(e,t,r){return this.runHilogWithSpawnRetry(e,t,()=>{},o=>{m(`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);m(`Ready to run hilog snapshot command: ${s} ${a.join(" ")}`);let c=await this.runHilogStreamingCollect(s,a,"a hilog snapshot streaming read"),l=Hn(c,"Failed to get hilog");if(l)throw l;if(c.exitCode!==0&&c.stderr)throw new Error(`Failed to get hilog: ${c.stderr}`);let d=P.filterLogsByRelativeWindow(c.stdout||c.stderr,r.fromSeconds,r.toSeconds);d=P.getLastLines(d,r.tail),d.trim()&&console.log(d)}async getHilogOnce(e,t,r,o){let[i,s]=this.buildHilogCommand(e,t,r,o);m(`Ready to run hilog command: ${i} ${s.join(" ")}`);let a=await this.runHilogStreamingCollect(i,s,"a single hilog streaming read"),c=Hn(a,"Failed to get hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to get hilog: ${a.stderr}`);let l=a.stdout||a.stderr,d=P.filterLogsByRelativeWindow(l,r.fromSeconds,r.toSeconds);return d=P.getLastLines(d,r.tail),d}async runHilogFollow(e,t,r,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);m(`Ready to run hilog command which contain \`follow\` and \`tail\`: ${i} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(i,s,this.createFollowLineHandler(),l=>{m(`Spawn error during hilog follow: ${l.message}`)},()=>{}),c=Hn(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){m(`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"];m(`Running command: ${e} ${o.join(" ")}`);let i=await this.runHilogStreamingCollect(e,o,"a crash log list streaming read"),s=Hn(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 m(`Crash logs list output:
1282
+ ${i}`)}if(r.length===1){let o=r[0];return m(Rs(`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(mm());return e.map(t=>t.serial)}async getConnectedDevices(){let e=await this.deviceManager.listDevicesWithName();if(e.length===0)throw new Error(mm());return e}async getPidForBundle(e,t,r){m(`Retrieving PID for bundle ${r}`),D.assertBundleNameStrict(r);let o=await se(e,["-t",t,"shell","pidof",r]),i=$n(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 m(`Found PID for ${r}: ${a}`),a}return m(`No PID found for bundle: ${r}`),null}async resizeHilogBuffer(e,t,r){m(`Setting hilog buffer size to: ${r}`);let o=await se(e,["-t",t,"shell","hilog","-G",r]),i=$n(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&&(D.assertHilogToken(e.tag,"tag"),r.push("-T",e.tag)),e.level&&(D.assertHilogLevel(e.level),r.push("-L",e.level)),e.domain&&(D.assertHilogToken(e.domain,"domain"),r.push("-D",e.domain)),t&&r.push("-P",t),e.keyword&&(D.assertHilogKeyword(e.keyword),r.push("-e",D.quotePosixShellArg(e.keyword))),r.join(" ")}async followHilog(e,t,r,o,i){let a=await rp(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+Cl.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||or(a.stderr)!=="transient"||c>=s-1)return a;m(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${Cl[c]}ms`),await XP(Cl[c])}return a}async runHilogStreamingCollect(e,t,r){return this.runHilogWithSpawnRetry(e,t,()=>{},o=>{m(`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);m(`Ready to run hilog snapshot command: ${s} ${a.join(" ")}`);let c=await this.runHilogStreamingCollect(s,a,"a hilog snapshot streaming read"),l=$n(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=D.filterLogsByRelativeWindow(c.stdout||c.stderr,r.fromSeconds,r.toSeconds);d=D.getLastLines(d,r.tail),d.trim()&&console.log(d)}async getHilogOnce(e,t,r,o){let[i,s]=this.buildHilogCommand(e,t,r,o);m(`Ready to run hilog command: ${i} ${s.join(" ")}`);let a=await this.runHilogStreamingCollect(i,s,"a single hilog streaming read"),c=$n(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=D.filterLogsByRelativeWindow(l,r.fromSeconds,r.toSeconds);return d=D.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);m(`Ready to run hilog command which contain \`follow\` and \`tail\`: ${i} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(i,s,this.createFollowLineHandler(),l=>{m(`Spawn error during hilog follow: ${l.message}`)},()=>{}),c=$n(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){m(`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"];m(`Running command: ${e} ${o.join(" ")}`);let i=await this.runHilogStreamingCollect(e,o,"a crash log list streaming read"),s=$n(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 m(`Crash logs list output:
1283
1283
  ${i.stdout}`),this.parseCrashLogFilenames(i.stdout,r)}parseCrashLogFilenames(e,t){return e.split(`
1284
- `).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>{try{return P.assertCrashFilename(r),!0}catch{return!1}}).filter(r=>t?r.toLowerCase().includes(t.toLowerCase()):!0)}async fetchCrashLogContent(e,t,r){m(`Fetching latest crash log file: ${r}`);let o=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];m(`Executing command: ${e} ${o.join(" ")}`);let i=await this.runHilogStreamingCollect(e,o,"a crash log streaming read"),s=Hn(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 Cl,red as hm}from"colorette";import ZP from"ora";function QP(n){try{return P.parsePositiveInteger(n,"tail")}catch{throw new Ds("`tail` must be a positive integer.")}}function mm(n,e){try{return P.parseDurationToSeconds(n,e)}catch{throw new Ds(`${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 eC(n){try{return P.assertHilogLevel(n),n}catch{throw new Ds("`level` must be one of: D, I, W, E, F.")}}function tC(n){try{return P.assertBundleNameStrict(n),n}catch(e){throw new Ds(e.message)}}function nC(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.");P.assertRelativeTimeRange(n.from,n.to)}async function rC(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 oC(n,e,t,r){let o=P.filterLogsByRelativeWindow(n,t,r);return e.tail?P.getLastLines(o,e.tail):o}var iC=new XP("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(hm(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",eC).option("--bundle-name <bundle-name>","Filter by application bundle name",tC).option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",QP).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>mm(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>mm(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await sC(n)});async function sC(n){let e=ZP({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),nC(n);let r=n.from,o=n.to,i=await A.new(),s=new wr(i),a=await s.selectDevice(n.device);a||(t(),process.exit(1)),m(Cl(`deviceId: ${a}`)),m(Cl(`type: ${n.crash?"Crash logs":"Common logs"}`)),m(Cl("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await rC(s,a,n,r,o);t(),n.crash&&c&&(c=oC(c,n,r,o)),c&&console.log(c)}catch(r){t(),console.error(hm(r.message)),process.exit(1)}}var gm=iC;import Mo from"path";import Mt from"fs";import Dl from"process";import Cm from"os";import{Command as vC}from"commander";import{green as bm,red as Il,cyan as SC,yellow as Al}from"colorette";import ce from"fs-extra";import _ from"path";import*as wm from"os";import{fileURLToPath as aC}from"url";var ym={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"}},cC=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function lC(){let n=import.meta.url,e=aC(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 vm(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()){vm(r,o);continue}ce.existsSync(o)||(ce.mkdirSync(_.dirname(o),{recursive:!0}),ce.copyFileSync(r,o))}}function Oo(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 dC(n){if(ym[n])return ym[n];if(n>=26){let e=`${n}.0.0`;return{sdkVersion:e,modelVersion:e}}}function uC(n,e){if(e===22)return;let t=dC(e);t&&(Oo(_.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),Oo(_.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),Oo(_.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function pC(n){return cC.filter(t=>!ce.existsSync(_.join(n,t))).length===0}function fC(){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 mC(n){return wm.platform()==="darwin"?_.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):_.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function hC(n,e){let t=mC(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 gC(n){let e=fC(),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 yC(n,e){e&&hC(n,e)||gC(n)}function wC(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 Sm(n,e,t,r,o){let i=lC();if(!ce.existsSync(i))throw new Error(`Template directory not found: ${i}`);ce.mkdirSync(n,{recursive:!0}),vm(i,n),wC(n),yC(n,o),Oo(_.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),Oo(_.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),uC(n,r);let s=pC(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function bC(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 Im(n){if(Cm.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function Em(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=Cm.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=Im(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 EC(n){let e=n,t=Mo.parse(n).root;for(;e!==t;){if(Mt.existsSync(e))return e;e=Mo.dirname(e)}return Mt.existsSync(t)?t:null}function Pm(n){let e=EC(n);if(!e)throw new Error(`No existing parent directory found for '${n}'. Cannot create project directory.`);try{Mt.accessSync(e,Mt.constants.W_OK)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}let t=Mo.join(e,`.deveco_write_test_${Date.now()}`);try{Mt.writeFileSync(t,"test"),Mt.unlinkSync(t)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}}function PC(n){return`com.example.${n.toLowerCase()}`}function CC(n,e){if(e){let o=Im(e),i=Mo.resolve(o);if(Mt.existsSync(i)){if(Mt.readdirSync(i).length>0)throw new Error(`Directory '${i}' is not empty. Cannot create project here.`)}else Pm(i);return i}let t=Dl.cwd(),r=Mo.join(t,n);if(Mt.existsSync(r))throw new Error(`Directory '${r}' already exists. Cannot create project here.`);return Pm(r),r}function IC(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){let i=b()?"commandLineTools":"DevEco Studio";throw new Error(`Invalid API version ${n.apiLevel}. Without ${i}, supported range is API version 17-${r}`)}return o}return t!==void 0?t:23}async function AC(){try{return await A.new()}catch(n){let e=n,t=b()?"Toolchain not found":"DevEco Studio not found";console.error(Al(`${t}: ${e.message}`)),b()?console.log(Al("Please install commandLineTools. Use placeholder API level instead.")):console.log(Al("Use placeholder API level instead."));return}}var DC=new vC("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(Il("Error: --app-name is required")),Dl.exit(1));let e=n.appName;bC(e);let t=n.bundleName||PC(e);P.assertBundleNameStrict(t),n.projectPath&&Em(n.projectPath);let r=CC(e,n.projectPath);Em(r),console.log(SC("Initializing project...")),console.log(`Project path: ${r}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let o=await AC(),i=IC(n,o);console.log(`API level: ${i}`);let s=o?.devecoStudioPath,a=Sm(r,e,t,i,s);console.log(`
1285
- `+bm("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(bm("Template integrity check passed."))}catch(e){let t=e;console.error(Il(`
1286
- Failed to create project.`)),console.error(Il(t.message)),Dl.exit(1)}}),Am=DC;import{Command as OC}from"commander";import{red as MC,cyan as Lm}from"colorette";import RC from"fs";import Rs from"path";import{cyan as TC}from"colorette";import*as Ts from"smol-toml";var vr=RC.promises;async function kC(n){try{let e=await vr.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 xC(n){try{let e=await vr.readFile(n,"utf8");return e.trim()===""?{}:Ts.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 NC(n,e){let t=Rs.dirname(n);await vr.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await vr.writeFile(n,r,"utf8")}async function LC(n,e){let t=Rs.dirname(n);await vr.mkdir(t,{recursive:!0});let r=Ts.stringify(e);await vr.writeFile(n,r,"utf8")}function Dm(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function Rm(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 Tm(n,e){return n.format==="codex"?xC(e):kC(e)}async function km(n,e,t){return n.format==="codex"?LC(e,t):NC(e,t)}async function xm(n,e,t=!1){let r=Vt[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Vt).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 Tm(r,r.globalConfigPath);if(Dm(o,r.mcpServersKey,gt)&&!t)return console.log(`MCP server ${gt} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let i=xi(r,void 0);return Rm(o,r.mcpServersKey,gt,i,t),await km(r,r.globalConfigPath,o),console.log(`MCP server ${gt} 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 Rl(n,e,t=!1){let r=Vt[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Vt).join(", ")}`};let o=Rs.isAbsolute(r.projectConfigPath)?r.projectConfigPath:Rs.join(e,r.projectConfigPath);try{let i=await Tm(r,o);if(Dm(i,r.mcpServersKey,gt)&&!t)return console.log(`MCP server ${gt} already configured in ${o}.`),{success:!0,skipped:!0,configPath:o,agentName:n,installType:"project"};let s=xi(r,e);return Rm(i,r.mcpServersKey,gt,s,t),await km(r,o,i),console.log(`MCP server ${gt} 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 Nm(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(TC("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 Tl="deveco-cli";async function _C(n,e,t){if(n.customPath)return[await nm(Tl,e,n.customPath,t.force)];let r=[...n.projectAgents.map(({project:s,agent:a})=>()=>tm(Tl,e,s,a,t.force)),...n.agents.map(s=>()=>em(Tl,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 FC(n,e,t){let r=[];for(let{project:o,agent:i}of n.projectAgents){let s=await Rl(i,o,t);r.push(s)}for(let o of n.agents){let i=await Rl(o,e,t);r.push(i)}return r}async function jC(n,e){let t=[];for(let r of n){if(!Vt[r])continue;let i=await xm(r,process.cwd(),e);t.push(i)}return t}async function HC(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 FC(s,e,r):await jC(s.agents,r);a.length>0&&(console.log(Lm("MCP Configuration:")),Nm(a))}async function $C(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}=xo(n.path,n.project,n.agent);t&&en(t,"Project directory",n.force),e&&en(e,"Directory",n.force);let r=await Cs(n,e,t);if(n.mcp){await HC(r,t,n);return}let o=sm(),i=await _C(r,o,n);console.log(),i.length>0&&(console.log(Lm("Skill Installation:")),ko(i))}var UC=new OC("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 $C(n)}catch(e){console.error(MC(e.message)),process.exit(1)}}),Om=UC;import{Command as LI}from"commander";import{McpServer as wI}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as vI}from"@modelcontextprotocol/sdk/server/stdio.js";import*as cn from"path";import*as Ym from"fs";import{z as Se}from"zod";var ks=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 kl(){return new ks}import*as Ne from"fs";import*as me from"path";import{z as Nl}from"zod";function Mm(n){return"method"in n&&!("id"in n)}import{spawn as BC}from"child_process";import{EventEmitter as WC}from"events";import*as Sr from"fs";import*as _m from"path";var tn=class extends WC{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;ensureDirectories(){let t=_m.join(this.config.logPath,"lspLog");return Sr.existsSync(t)||Sr.mkdirSync(t,{recursive:!0}),Sr.existsSync(this.config.indexingDataLocation)||Sr.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){let r=this.ensureDirectories();f.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"];f.info(`[LspClient] Starting process: node ${i.join(" ")}`);let s=this.config.nodePath;f.info(`[LspClient] nodePath: ${s}`),this.process=BC(s,i,{cwd:this.config.cwd||process.cwd(),stdio:["pipe","pipe","pipe"],windowsHide:!0}),this.bindProcessEvents(),await new Promise(a=>setTimeout(a,500)),f.info("[LspClient] start lsp process success")}attachProcess(t,r){if(this.process)throw new Error("[LspClient] process already attached");this.process=t,this.bindProcessEvents(r?.stderrAsError??!0),f.info("[LspClient] attached to external process")}bindProcessEvents(t=!0){this.process&&(this.process.stdout?.on("data",r=>{this.handleData(r)}),this.process.stderr?.on("data",r=>{let o=r.toString("utf8").trim();f.error(`[LspClient] stderr: ${o}`),!this.isClosing&&t&&this.emit("error",new Error(`[LspClient] stderr: ${o}`))}),this.process.on("exit",r=>{f.info(`[LSP EXIT] code=${r}`),this.isClosing||this.emit("error",new Error(`LSP process exited with code ${r}`))}))}sendRaw(t,r){if(!this.process?.stdin?.writable){f.warn("[LspClient] Cannot send message, stdin not writable");return}f.info(`[LspClient] send message: ${r}`);let 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
1284
+ `).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>{try{return D.assertCrashFilename(r),!0}catch{return!1}}).filter(r=>t?r.toLowerCase().includes(t.toLowerCase()):!0)}async fetchCrashLogContent(e,t,r){m(`Fetching latest crash log file: ${r}`);let o=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];m(`Executing command: ${e} ${o.join(" ")}`);let i=await this.runHilogStreamingCollect(e,o,"a crash log streaming read"),s=$n(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 Il,red as gm}from"colorette";import QP from"ora";function eC(n){try{return D.parsePositiveInteger(n,"tail")}catch{throw new Ts("`tail` must be a positive integer.")}}function hm(n,e){try{return D.parseDurationToSeconds(n,e)}catch{throw new Ts(`${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 tC(n){try{return D.assertHilogLevel(n),n}catch{throw new Ts("`level` must be one of: D, I, W, E, F.")}}function nC(n){try{return D.assertBundleNameStrict(n),n}catch(e){throw new Ts(e.message)}}function rC(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.");D.assertRelativeTimeRange(n.from,n.to)}async function oC(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 iC(n,e,t,r){let o=D.filterLogsByRelativeWindow(n,t,r);return e.tail?D.getLastLines(o,e.tail):o}var sC=new ZP("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(gm(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",tC).option("--bundle-name <bundle-name>","Filter by application bundle name",nC).option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",eC).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>hm(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>hm(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await aC(n)});async function aC(n){let e=QP({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),rC(n);let r=n.from,o=n.to,i=await I.new(),s=new Sr(i),a=await s.selectDevice(n.device);a||(t(),process.exit(1)),m(Il(`deviceId: ${a}`)),m(Il(`type: ${n.crash?"Crash logs":"Common logs"}`)),m(Il("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await oC(s,a,n,r,o);t(),n.crash&&c&&(c=iC(c,n,r,o)),c&&console.log(c)}catch(r){t(),console.error(gm(r.message)),process.exit(1)}}var ym=sC;import jo from"path";import Ft from"fs";import Rl from"process";import Im from"os";import{Command as SC}from"commander";import{green as Em,red as Al,cyan as bC,yellow as Dl}from"colorette";import ce from"fs-extra";import _ from"path";import*as vm from"os";import{fileURLToPath as cC}from"url";var wm={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"}},lC=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function dC(){let n=import.meta.url,e=cC(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 Sm(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()){Sm(r,o);continue}ce.existsSync(o)||(ce.mkdirSync(_.dirname(o),{recursive:!0}),ce.copyFileSync(r,o))}}function Fo(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 uC(n){if(wm[n])return wm[n];if(n>=26){let e=`${n}.0.0`;return{sdkVersion:e,modelVersion:e}}}function pC(n,e){if(e===22)return;let t=uC(e);t&&(Fo(_.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),Fo(_.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),Fo(_.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function fC(n){return lC.filter(t=>!ce.existsSync(_.join(n,t))).length===0}function mC(){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 hC(n){return vm.platform()==="darwin"?_.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):_.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function gC(n,e){let t=hC(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 yC(n){let e=mC(),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 wC(n,e){e&&gC(n,e)||yC(n)}function vC(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 bm(n,e,t,r,o){let i=dC();if(!ce.existsSync(i))throw new Error(`Template directory not found: ${i}`);ce.mkdirSync(n,{recursive:!0}),Sm(i,n),vC(n),wC(n,o),Fo(_.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),Fo(_.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),pC(n,r);let s=fC(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function EC(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 Am(n){if(Im.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function Pm(n){if(n.length===0)throw new Error("Project path cannot be empty.");if(n.length>120)throw new Error(`Project path cannot exceed 120 characters (current: ${n.length}).`);let e=Im.platform();if(!(e==="win32"?/^[a-zA-Z0-9._\-:\\/]+$/:/^[a-zA-Z0-9._\-/]+$/).test(n)){let 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=Am(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 PC(n){let e=n,t=jo.parse(n).root;for(;e!==t;){if(Ft.existsSync(e))return e;e=jo.dirname(e)}return Ft.existsSync(t)?t:null}function Cm(n){let e=PC(n);if(!e)throw new Error(`No existing parent directory found for '${n}'. Cannot create project directory.`);try{Ft.accessSync(e,Ft.constants.W_OK)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}let t=jo.join(e,`.deveco_write_test_${Date.now()}`);try{Ft.writeFileSync(t,"test"),Ft.unlinkSync(t)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}}function CC(n){return`com.example.${n.toLowerCase()}`}function IC(n,e){if(e){let o=Am(e),i=jo.resolve(o);if(Ft.existsSync(i)){if(Ft.readdirSync(i).length>0)throw new Error(`Directory '${i}' is not empty. Cannot create project here.`)}else Cm(i);return i}let t=Rl.cwd(),r=jo.join(t,n);if(Ft.existsSync(r))throw new Error(`Directory '${r}' already exists. Cannot create project here.`);return Cm(r),r}function AC(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){let i=b()?"commandLineTools":"DevEco Studio";throw new Error(`Invalid API version ${n.apiLevel}. Without ${i}, supported range is API version 17-${r}`)}return o}return t!==void 0?t:23}async function DC(){try{return await I.new()}catch(n){let e=n,t=b()?"Toolchain not found":"DevEco Studio not found";console.error(Dl(`${t}: ${e.message}`)),b()?console.log(Dl("Please install commandLineTools. Use placeholder API level instead.")):console.log(Dl("Use placeholder API level instead."));return}}var RC=new SC("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(Al("Error: --app-name is required")),Rl.exit(1));let e=n.appName;EC(e);let t=n.bundleName||CC(e);D.assertBundleNameStrict(t),n.projectPath&&Pm(n.projectPath);let r=IC(e,n.projectPath);Pm(r),console.log(bC("Initializing project...")),console.log(`Project path: ${r}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let o=await DC(),i=AC(n,o);console.log(`API level: ${i}`);let s=o?.devecoStudioPath,a=bm(r,e,t,i,s);console.log(`
1285
+ `+Em("Project created successfully.")),console.log(`Project root: ${a.projectRoot}`),console.log(`App name: ${a.appName}`),console.log(`Bundle name: ${a.bundleName}`),console.log(`API level: ${a.apiLevel}`),console.log(Em("Template integrity check passed."))}catch(e){let t=e;console.error(Al(`
1286
+ Failed to create project.`)),console.error(Al(t.message)),Rl.exit(1)}}),Dm=RC;import{Command as MC}from"commander";import{red as _C,cyan as Om}from"colorette";import TC from"fs";import ks from"path";import{cyan as kC}from"colorette";import*as xs from"smol-toml";var br=TC.promises;async function xC(n){try{let e=await br.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 NC(n){try{let e=await br.readFile(n,"utf8");return e.trim()===""?{}:xs.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 LC(n,e){let t=ks.dirname(n);await br.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await br.writeFile(n,r,"utf8")}async function OC(n,e){let t=ks.dirname(n);await br.mkdir(t,{recursive:!0});let r=xs.stringify(e);await br.writeFile(n,r,"utf8")}function Rm(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function Tm(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 km(n,e){return n.format==="codex"?NC(e):xC(e)}async function xm(n,e,t){return n.format==="codex"?OC(e,t):LC(e,t)}async function Nm(n,e,t=!1){let r=Kt[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Kt).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 km(r,r.globalConfigPath);if(Rm(o,r.mcpServersKey,yt)&&!t)return console.log(`MCP server ${yt} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let i=Li(r,void 0);return Tm(o,r.mcpServersKey,yt,i,t),await xm(r,r.globalConfigPath,o),console.log(`MCP server ${yt} 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 Tl(n,e,t=!1){let r=Kt[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Kt).join(", ")}`};let o=ks.isAbsolute(r.projectConfigPath)?r.projectConfigPath:ks.join(e,r.projectConfigPath);try{let i=await km(r,o);if(Rm(i,r.mcpServersKey,yt)&&!t)return console.log(`MCP server ${yt} already configured in ${o}.`),{success:!0,skipped:!0,configPath:o,agentName:n,installType:"project"};let s=Li(r,e);return Tm(i,r.mcpServersKey,yt,s,t),await xm(r,o,i),console.log(`MCP server ${yt} 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 Lm(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(kC("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 kl="deveco-cli";async function FC(n,e,t){if(n.customPath)return[await rm(kl,e,n.customPath,t.force)];let r=[...n.projectAgents.map(({project:s,agent:a})=>()=>nm(kl,e,s,a,t.force)),...n.agents.map(s=>()=>tm(kl,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 jC(n,e,t){let r=[];for(let{project:o,agent:i}of n.projectAgents){let s=await Tl(i,o,t);r.push(s)}for(let o of n.agents){let i=await Tl(o,e,t);r.push(i)}return r}async function HC(n,e){let t=[];for(let r of n){if(!Kt[r])continue;let i=await Nm(r,process.cwd(),e);t.push(i)}return t}async function $C(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 jC(s,e,r):await HC(s.agents,r);a.length>0&&(console.log(Om("MCP Configuration:")),Lm(a))}async function UC(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}=Oo(n.path,n.project,n.agent);t&&nn(t,"Project directory",n.force),e&&nn(e,"Directory",n.force);let r=await As(n,e,t);if(n.mcp){await $C(r,t,n);return}let o=am(),i=await FC(r,o,n);console.log(),i.length>0&&(console.log(Om("Skill Installation:")),Lo(i))}var BC=new MC("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 UC(n)}catch(e){console.error(_C(e.message)),process.exit(1)}}),Mm=BC;import{Command as OI}from"commander";import{McpServer as vI}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as SI}from"@modelcontextprotocol/sdk/server/stdio.js";import*as dn from"path";import*as Km from"fs";import{z as de}from"zod";var Ns=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 xl(){return new Ns}import*as Oe from"fs";import*as le from"path";import{z as Ll}from"zod";function _m(n){return"method"in n&&!("id"in n)}import{spawn as WC}from"child_process";import{EventEmitter as GC}from"events";import*as Er from"fs";import*as Fm from"path";var rn=class extends GC{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;ensureDirectories(){let t=Fm.join(this.config.logPath,"lspLog");return Er.existsSync(t)||Er.mkdirSync(t,{recursive:!0}),Er.existsSync(this.config.indexingDataLocation)||Er.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){let r=this.ensureDirectories();f.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"];f.info(`[LspClient] Starting process: node ${i.join(" ")}`);let s=this.config.nodePath;f.info(`[LspClient] nodePath: ${s}`),this.process=WC(s,i,{cwd:this.config.cwd||process.cwd(),stdio:["pipe","pipe","pipe"],windowsHide:!0}),this.bindProcessEvents(),await new Promise(a=>setTimeout(a,500)),f.info("[LspClient] start lsp process success")}attachProcess(t,r){if(this.process)throw new Error("[LspClient] process already attached");this.process=t,this.bindProcessEvents(r?.stderrAsError??!0),f.info("[LspClient] attached to external process")}bindProcessEvents(t=!0){this.process&&(this.process.stdout?.on("data",r=>{this.handleData(r)}),this.process.stderr?.on("data",r=>{let o=r.toString("utf8").trim();f.error(`[LspClient] stderr: ${o}`),!this.isClosing&&t&&this.emit("error",new Error(`[LspClient] stderr: ${o}`))}),this.process.on("exit",r=>{f.info(`[LSP EXIT] code=${r}`),this.isClosing||this.emit("error",new Error(`LSP process exited with code ${r}`))}))}sendRaw(t,r){if(!this.process?.stdin?.writable){f.warn("[LspClient] Cannot send message, stdin not writable");return}f.info(`[LspClient] send message: ${r}`);let 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
1287
1287
  \r
1288
1288
  ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this.buffer.indexOf(`\r
1289
1289
  \r
1290
- `);if(r===-1)break;let i=this.buffer.slice(0,r).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!i){f.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(r+4);continue}let s=parseInt(i[1],10),a=r+4,c=a+s;if(this.buffer.length<c)break;let l=this.buffer.slice(a,c).toString("utf8"),d=this.recoverFramedJson(l);if(d&&d.rest.length>0){f.warn(`[LspClient] recovered mixed LSP frame, bodyLen=${l.length}, restLen=${d.rest.length}`),this.emit("message",d.json),this.buffer=Buffer.concat([Buffer.from(d.rest,"utf8"),this.buffer.slice(c)]);continue}this.emit("message",l),this.buffer=this.buffer.slice(c)}}waitForExitOrTimeout(t){let r=this.process;return!r||r.exitCode!==null||r.signalCode!==null?Promise.resolve():new Promise(o=>{let i=!1,s=()=>{i||(i=!0,clearTimeout(c),r.off("exit",a),o())},a=()=>s();r.once("exit",a);let c=setTimeout(s,t)})}recoverFramedJson(t){let r=t.search(/\S/);if(r<0||t[r]!=="{"&&t[r]!=="[")return null;let o=0,i=!1,s=!1;for(let a=r;a<t.length;a++){let c=t[a];if(i){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(i=!1);continue}if(c==='"'){i=!0;continue}if(c==="{"||c==="["){o++;continue}if((c==="}"||c==="]")&&(o--,o===0)){let l=t.slice(r,a+1),d=t.slice(a+1);return{json:l,rest:d}}}return null}stop(){this.isClosing=!0;let t=this.process;if(!t)return;if(this.process=null,t.exitCode===null&&t.signalCode===null)try{t.kill()}catch{}}};var nn=class{callbacks=new Map;pending=new Map;timeouts=new Map;registerPending(e,t,r){return new Promise((o,i)=>{let s;r>0&&(s=setTimeout(()=>{this.pending.delete(e),this.timeouts.delete(e),i(new Error(`LSP request '${t}' (id=${e}) timeout after ${r}ms`))},r),this.timeouts.set(e,s)),this.pending.set(e,{resolve:o,reject:i,method:t,timer:s})})}resolvePending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.resolve(t),this.pending.delete(e),!0):!1}rejectPending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.reject(t),this.pending.delete(e),!0):!1}register(e,t){this.callbacks.set(e,t)}emit(e,t,r){f.info(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let o=this.callbacks.get(e);if(o)o(t,r),this.callbacks.delete(e);else{let i=[...this.callbacks.keys()].map(s=>String(s));f.info(`[RequestCallbackManager] emit: NO callback for key='${e}', registered keys=[${i.join(",")}]`)}}registerTimeout(e,t,r,o){let i=this.timeouts.get(e);i&&clearTimeout(i);let s=setTimeout(()=>{f.info(`[RequestCallbackManager] timeout, key=${e}, method=${t}`),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 xs=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var br=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 Fm=20*1e3,GC=30*1e3,Ns=class{client;nextRequestId=1;stopOnce=null;callbacks=new br;requestCallbacks=new nn;diagnosticMap=new Map;initProgressReset=null;constructor(e){this.client=new tn(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{f.info("[ClientMessageHandle] Sending shutdown request"),this.client.sendRequest(y.SHUTDOWN,null,this.nextRequestId++),f.info("[ClientMessageHandle] Sending exit notification"),this.client.sendNotification(y.EXIT,null),f.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),f.info("[ClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(y.BROADCAST),this.callbacks.register(y.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(y.BROADCAST,e)}async sendInitialize(e){let t=this.nextRequestId++,r=this.requestCallbacks.registerPending(t,y.INITIALIZE,ze);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 xs(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=GC){let o=this.nextRequestId++,i=this.requestCallbacks.registerPending(o,e,r);return this.client.sendRequest(e,t,o),i}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}onDidChangeWatchedFiles(e){e.length!==0&&this.client.sendNotification(y.WORKSPACE_DID_CHANGE_WATCHED_FILES,{changes:e})}sendDidChangeConfiguration(e){this.client.sendNotification(y.WORKSPACE_DID_CHANGE_CONFIGURATION,{settings:e})}sendNotification(e,t){this.client.sendNotification(e,t)}getDiagnosticMessages(e){let t=this.diagnosticMap.get(e);return t?t.get():[]}clearDiagnostic(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let o=r instanceof Error?r.message:String(r);f.error(`[LSP] JSON parse error: ${o}, raw: ${e}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotificationOrRequest(t):f.warn(`[LSP] Unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t===void 0)return;let r=t;if(e.error){let o=new Error(`LSP error ${e.error.code}: ${e.error.message}`);this.requestCallbacks.rejectPending(r,o)}else this.requestCallbacks.resolvePending(r,e.result)}handleNotificationOrRequest(e){let t=e.method;if(t)switch(this.initProgressReset?.(),t){case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.handleProgress(e.params);break;case y.WINDOW_SHOW_MESSAGE:f.info(`[LSP] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:f.info(`[LSP] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.broadcastToClients(e)}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=e.uri,r=this.diagnosticMap.get(t);if(!r)return;let o=e.diagnostics||[];this.normalizeDiagnostics(o),r.set(o),this.finalizeDiagnostic(t,o)}normalizeDiagnostics(e){for(let t of e)if(t.severity!==void 0){let r={1:"Error",2:"Warning",3:"Information",4:"Hint"};t.severityStr=r[t.severity]||"Unknown"}}handleProgress(e){D(e)&&this.broadcastToClients({jsonrpc:R,method:y.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,y.PUBLISH_DIAGNOSTICS,Fm,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${Fm}ms, uri: ${e}`)})}finalizeDiagnostic(e,t,r){let o={uri:e,diagnostics:t,...r?{errorMessage:r}:{}};this.requestCallbacks.emit(e,y.PUBLISH_DIAGNOSTICS,o),this.diagnosticMap.get(e)?.clear()}handleError(e){let t=Array.from(this.diagnosticMap.keys()).filter(r=>this.requestCallbacks.hasCallback(r));if(t.length>0){let r={range:{start:{line:0,character:0},end:{line:0,character:0}},severity:1,message:e.message};for(let o of t)this.finalizeDiagnostic(o,[r]);return}this.broadcastToClients({jsonrpc:R,method:y.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var Ls=class{uri;messages=[];receivedTypes=new Set;uniqueMessages=new Set;isFromEditor=!1;constructor(e){this.uri=e}setReceivedType(e){this.receivedTypes.add(e)}addMessage(e,t){this.receivedTypes.add(e);let r=`${e}:${t}`;if(this.uniqueMessages.has(r)){f.info(`[LegacyDiagnostic] addMessage: duplicate message=${r}`);return}this.uniqueMessages.add(r),this.messages.push(new xl(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)}},xl=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var zC={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"},qC={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate",ON_FORCE_OPEN_FILE:"aceProject/onForceOpenFile",ON_PACKAGE_CHANGE_FINISH:"aceProject/onPackageChangeFinish",TEXT_DOCUMENT_ON_ASYNC_DEFINITION:"textDocument/onAsyncDefinition",ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:"textDocument/onDidChangePackageDependencies",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",REFERENCES:"textDocument/references",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",BROADCAST:"lsp/broadcast",ARKTS_ERROR:"arkts/error",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing"},T={...zC,...qC},rn={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"},jm=new Set([1e3,2e3,3e3,3001]);function VC(n){if(!D(n))return!1;let e=n.textDocument;return D(e)&&typeof e.uri=="string"}function JC(n){return D(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function YC(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 Os=class n{client;isInitialized=!1;stopOnce=null;callbacks=new br;requestCallbacks=new nn;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;constructor(e){this.client=new tn(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{f.info("[LegacyClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:T.EXIT,params:{}}),rn.EXIT),f.info("[LegacyClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),f.info("[LegacyClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(T.BROADCAST),this.callbacks.register(T.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(T.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(T.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(T.INDEXING_PROGRESS_UPDATE,e)}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}sendInitialize(e,t){this.client.send("initialize",e,t)}sendInitialized(e){this.client.sendRaw(JSON.stringify({jsonrpc:R,method:T.INITIALIZED,params:{editors:e}}),rn.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:R,id:0,result:{}}),rn.EMPTY)}sendAsyncRequest(e,t,r,o){if(!D(t)){f.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!VC(t)){f.warn(`[LSP] sendAsyncRequest missing textDocument.uri, method=${e}, params=${JSON.stringify(t)}`);return}if(typeof r!="number"){f.warn(`[LSP] sendAsyncRequest invalid requestId, method=${e}, requestId=${String(r)}`);return}let i=t.textDocument.uri,s=st(i);t.textDocument.uri=s,delete t.requestId;let a=o??e;f.info(`[LSP] sendAsyncRequest ${a}, filePath: ${i}`),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:e,params:{params:t,requestId:r}}),a)}onDidChangeWatchedFiles(e){if(f.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let r of e){if(!JC(r)){f.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:R,method:T.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),T.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!D(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){f.warn("[LSP] sendModuleDependencyUpdate, moduleSet is empty or null");return}let t=e.moduleSet;f.info(`[LSP] sending module dependency updated, count: ${t.length}`),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:T.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),rn.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let o=st(t);e.textDocument.uri=o,f.info(`[LSP] onAsyncOpenFile, uri: ${o}`);let i=this.diagnosticMap.get(o);i||(i=new Ls(o),this.diagnosticMap.set(o,i),this.registerDiagnosticTimeout(o,T.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(i.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:T.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),rn.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=st(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,T.PUBLISH_DIAGNOSTICS)),f.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:T.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),rn.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=st(e);f.info(`[LSP] didClose, uri: ${r}`);let o=this.diagnosticMap.get(r);if(!t&&(!o||o.isFromEditor)){f.info(`[LSP] closeFile skip, !diagnostic: ${!o}, isFromEditor: ${o?.isFromEditor}`);return}this.cleanupDiagnosticState(r),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:T.DID_CLOSE,params:{textDocument:{uri:r}}}),rn.DID_CLOSE)}getDiagnosticMessage(e){let t=st(e),r=this.diagnosticMap.get(t);return r?r.getMessages():[]}clear(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){try{let t=JSON.parse(e);this.handleLspMessage(t)}catch(t){let r=t instanceof Error?t.message:String(t);f.error(`[LSP] JSON parse error: ${r}, raw: ${e}`)}}handleError(e){let t=this.getPendingDiagnosticUris();if(t.length>0){let r=JSON.stringify({message:e.message,severity:"Error",severityStr:"Error"});for(let o of t)this.finalizeDiagnostic(o,T.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:R,method:T.ARKTS_ERROR,params:{message:e.message}})}handleLspMessage(e){let t=e.method;t!==void 0&&(!this.isInitialized&&this.handlePreInitMessage(t,e)||this.handlePostInitMessage(t,e))}handlePreInitMessage(e,t){switch(e){case T.MODULE_INIT_FINISH:return f.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(T.MODULE_INIT_FINISH),this.callbacks.unregister(T.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case T.INDEXING_PROGRESS_UPDATE:return f.info(`[LSP] onIndexingProgressUpdate: ${YC(t.params)}`),this.callbacks.invoke(T.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case T.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case T.ON_PACKAGE_CHANGE_FINISH:f.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case T.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case T.ON_ASYNC_HOVER:this.handleAsyncResponse(t,T.HOVER);return;case T.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,T.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case T.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,T.REFERENCES);return;default:f.warn(`[LSP] handleLspMessage: no handler for notification, ignoring, method: ${e}, initialized: ${this.isInitialized}`)}}handleOnForceOpenFile(e){f.info("[LSP] handleLspMessage, receive onForceOpenFile");let t=e.params;D(t)&&D(t.result)&&typeof t.result.uri=="string"&&this.handleForceOpenFile(t.result.uri)}handlePublishDiagnostics(e){f.info("[LSP] handleLspMessage, receive publishDiagnostics");let t=e.params;t&&this.parseDiagnostics(t)}handlePackageChangeFinish(e){let t=e.params,r={jsonrpc:R,method:T.ON_PACKAGE_CHANGE_FINISH,params:[!1]};if(!t||!Array.isArray(t)){f.warn("[LSP] aceProject/onPackageChangeFinish params invalid"),this.broadcastToClients(r);return}if(!(t.length>0&&t[0]===!0)){f.warn("[LSP] aceProject/onPackageChangeFinish: package request failed"),this.broadcastToClients(r);return}f.info("[LSP] aceProject/onPackageChangeFinish: success"),this.broadcastToClients(e)}handleAsyncResponse(e,t){f.info(`[LSP] handleAsyncResponse\uFF0C method: ${t}`);let r=e.params;if(!D(r)){f.warn("[LSP] aceProject/onAsyncHover message invalid");return}let o=r.requestId;if(typeof o!="number"){f.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(o,t,r)}handleForceOpenFile(e){if(!e){f.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,T.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){f.info("[LSP] publishDiagnostics uri is null");return}let r=e.version??-1;if(r===-1)return;let o=this.diagnosticMap.get(t);if(!o){f.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let i=e.diagnostics||[];i.length!==0?i.forEach(s=>{this.normalizeDiagnostic(s),o.addMessage(r,JSON.stringify(s))}):o.setReceivedType(r),o.hasReceivedAllTypes(jm)&&this.finalizeDiagnostic(t,T.PUBLISH_DIAGNOSTICS,o.getMessages())}normalizeDiagnostic(e){let t=e;if(delete t.source,t.severity!==void 0){let r=typeof t.severity=="number"?t.severity:parseInt(t.severity),i={1:"Error",2:"Warning",3:"Information",4:"Hint"}[r]||"Unknown";t.severityStr=i,t.severity=i}e.range&&(this.adjustPositionLine(e.range,"start"),this.adjustPositionLine(e.range,"end"))}adjustPositionLine(e,t){let r=e[t];r&&typeof r.line=="number"&&(r.line=r.line+1)}registerDiagnosticTimeout(e,t){this.requestCallbacks.registerTimeout(e,t,n.DIAGNOSTIC_TIMEOUT_MS,()=>{let r=this.diagnosticMap.get(e),o=r?r.getMessages():[];this.finalizeDiagnostic(e,t,o,o.length>0?void 0:`received no diagnostics within ${n.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,r,o){let i={uri:e,diagnostics:r,...o?{errorMessage:o}:{}};this.requestCallbacks.emit(e,t,i),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import Uo from"path";import*as Us from"path";var Ms=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var _s=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var Fs=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var js=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var Hs=class{typeSetting=new Fs;parameterNames=new js};var $s=class{constructor(e,t,r,o){this.rootUri=e;this.lspServerWorkspacePath=U(Us.dirname(t)),this.indexingDataLocation=U(o),this.loggerPath=U(Us.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new Ms;gutterIconsSetting=new _s;inlayHintsSetting=new Hs;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as Hm 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(Hm.join(e,"src","main","resources")))}};var KC="OS",Er=class{deviceType=[5];aceLoaderPath;modulePath;jsComponentType="declarative";sdkJsPath;compatibleSdkVersion;compatibleSdkLevel;compileSdkLevel;compileSdkVersion="6.0.1.112";compileSdkType="Release";syscap={NDeviceSysCaps:[],addedSysCaps:[]};apiType="stageMode";hosSdkPath;runtimeOs=`Harmony${KC}`;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 Pr=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as Ze from"path";import*as Ar from"fs";var Bs=class{modulePath;dependencies={};dynamicDependencies={}};var $n=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 Cr=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 _t from"path";import*as Ws from"fs";var Ir=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:it.OH_PACKAGE_JSON5},Fo=`${L.HVIGOR_CACHE}/${L.DEPENDENCY}`,Un=`${L.DEPENDENCY}${L.JSON5}`,vW=it.SYNC_OUTPUT_PATH;var jo=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=_t.join(this.dependencyPath,L.OH_PACKAGE_JSON5),r=He(t);r&&(this.dependencies=this.getDependencyList(r,L.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(r,L.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(r,L.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let r=[];if(!D(e))return r;let o=e[t];if(!D(o))return r;for(let[i,s]of Object.entries(o)){if(typeof s!="string"){f.error(`${i} package dependency value is not String ${t}`);continue}let a=new Ir;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=_t.normalize(_t.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)),_t.isAbsolute(s)){r.dependencyPath=i;return}if(!o){let a=_t.resolve(this.modulePath,s);i=P.ensurePathWithinRoot(this.projectPath,a)}Ws.existsSync(i)&&Ws.statSync(i).isDirectory()&&(r.dependencyPath=i)}catch(i){f.error("parser dependency path is invalid",i)}}};import*as Ho from"fs";import*as $o from"path";import XC from"json5";var Gs=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 $o.join(this.projectPath,L.OH_MODULES_PATH,L.OHPM_PATH,L.LOCK_JSON5_FILE)}readLockFile(e){if(!Ho.existsSync(e))return f.error("lock file does not exist"),this.clearDependencies(),null;try{let t=Ho.readFileSync(e,"utf8"),r=XC.parse(t);return r||(f.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return f.error("Error parsing lock.json5:",t),this.clearDependencies(),null}}validateLockFile(e){if(!D(e))return f.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return f.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let r=e.packages;return r?{valid:!0,modules:t,packages:r}:(f.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,r){this.storePathMap=t,this.finalDependencies=this.getDependencyList(e,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)){f.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 f.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 Ir;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=P.resolvePathWithinRoot(this.projectPath,$o.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=$o.isAbsolute(a)?P.ensurePathWithinRoot(this.projectPath,a):P.resolvePathWithinRoot(this.projectPath,a);Ho.existsSync(c)?(e.path=o,e.dependencyPath=this.fileNameForOhpm.test(i)?s:c):e.dependencyPath=s}catch(a){f.error("Invalid dependency path in lock.json5",a)}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};function $m(n){return D(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var Bn=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new Rt(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=Ze.join(t,Fo),o=Ze.join(r,Un);if(!Ar.existsSync(r)||!Ar.existsSync(o)){let c="Dependency map or JSON not found";return f.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let i=new Cr(this.projectPath,".",this.projectPath);this.parseProjectDependencies(r,i),this.parseLockJson(i);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let c="No modules found in build-profile.json5";return f.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:c}}let a=Date.now();for(let c=0;c<s.length;c++){let l=s[c];$m(l)&&(this.parseSingleModule(l,r,i,e),(c+1)%100===0&&f.info(`[Parser] getAllDependencyMap progress: ${c+1}/${s.length} (${Date.now()-a}ms)`))}return f.info(`[Parser] getAllDependencyMap parsed ${e.length} modules in ${Date.now()-a}ms`),{status:"OK"}}getDependenciesOnly(e){let t=[],r=this.projectPath,o=Ze.join(r,Fo),i=Ze.join(o,Un);if(!Ar.existsSync(o)||!Ar.existsSync(i))return f.warn("[Parser] Dependency map or JSON not found."),t;let s=e&&e.length>0?new Set(e.map(l=>l.trim()).filter(Boolean)):null,a=new Cr(this.projectPath,".",this.projectPath);this.parseProjectDependencies(o,a),this.parseLockJson(a);let c=this.moduleInfoParse.getAllModuleInfo();if(c.length===0)return f.warn("[Parser] getAllDependencyMap failed: No modules found in build-profile.json5."),t;for(let l of c){if(!$m(l))continue;let d=l.name;if(s&&!s.has(d))continue;let h=P.resolvePathWithinRoot(this.projectPath,l.srcPath),w=Ze.join(o,d),S=U(h),k=this.buildModuleDependencies(d,S,w,a);k.moduleName=d,t.push(k)}return t}parseSingleModule(e,t,r,o){let i=e.name,s=P.resolvePathWithinRoot(this.projectPath,e.srcPath),a=Ze.join(t,i),c=U(s),l=new Er(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 Pr(h),o.push(l)}buildModuleDependencies(e,t,r,o){let i=new Cr(this.projectPath,e,t);jo.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 Bs;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 $n(i);for(let i of e.finalDynamicDependencies)o[i.name]=new $n(i);t.dependencies=r,t.dynamicDependencies=o}parseProjectDependencies(e,t){let r=Ze.join(e,L.OH_PACKAGE_JSON5);if(!Ar.existsSync(r))return;jo.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 Gs(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=Ze.join(e,"src","main","module.json5"),o=He(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=Ze.join(e,"src","main","resources","base","profile","main_pages.json"),r=He(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=Ze.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=He(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=Ze.join(this.projectPath,"build-profile.json5");this.buildProfileCache=He(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 zs=class{constructor(e=[]){this.valueSet=e}valueSet};var Dr=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var Um=(C=>(C[C.File=1]="File",C[C.Module=2]="Module",C[C.Namespace=3]="Namespace",C[C.Package=4]="Package",C[C.Class=5]="Class",C[C.Method=6]="Method",C[C.Property=7]="Property",C[C.Field=8]="Field",C[C.Constructor=9]="Constructor",C[C.Enum=10]="Enum",C[C.Interface=11]="Interface",C[C.Function=12]="Function",C[C.Variable=13]="Variable",C[C.Constant=14]="Constant",C[C.String=15]="String",C[C.Number=16]="Number",C[C.Boolean=17]="Boolean",C[C.Array=18]="Array",C[C.Object=19]="Object",C[C.Key=20]="Key",C[C.Null=21]="Null",C[C.EnumMember=22]="EnumMember",C[C.Struct=23]="Struct",C[C.Event=24]="Event",C[C.Operator=25]="Operator",C[C.TypeParameter=26]="TypeParameter",C))(Um||{}),Bm=()=>Object.values(Um).filter(n=>typeof n=="number");var qs=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Vs=class{applyEdit=!0;workspaceEdit=new qs;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new zs(Bm());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Dr;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Js=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Ys=class{constructor(e=[]){this.valueSet=e}valueSet};var Ks=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var Wm=(I=>(I[I.Text=1]="Text",I[I.Method=2]="Method",I[I.Function=3]="Function",I[I.Constructor=4]="Constructor",I[I.Field=5]="Field",I[I.Variable=6]="Variable",I[I.Class=7]="Class",I[I.Interface=8]="Interface",I[I.Module=9]="Module",I[I.Property=10]="Property",I[I.Unit=11]="Unit",I[I.Value=12]="Value",I[I.Enum=13]="Enum",I[I.Keyword=14]="Keyword",I[I.Snippet=15]="Snippet",I[I.Color=16]="Color",I[I.File=17]="File",I[I.Reference=18]="Reference",I[I.Folder=19]="Folder",I[I.EnumMember=20]="EnumMember",I[I.Constant=21]="Constant",I[I.Struct=22]="Struct",I[I.Event=23]="Event",I[I.Operator=24]="Operator",I[I.TypeParameter=25]="TypeParameter",I))(Wm||{}),Gm=()=>Object.values(Wm).filter(n=>typeof n=="number");var Xs=class{completionItemKind=new Ys(Gm());completionItem=new Ks;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var Zs=class{synchronization=new Js;completion=new Xs;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 Dr;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var Qs=class{workspace=new Vs;textDocument=new Zs;notebookDocument=null;window=null;general=null;experimental=null};var ea=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};var ta=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?Uo.resolve(Uo.dirname(e.arktsLangServerPath),"standardIndex","index.js"):e.arktsLangServerPath,this.logPath=Uu(),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 Ns(t):new Os(t),this.messageHandle.setBroadcastToClients(r=>this.onLspMessage(r))}async start(e,t){let r=!1;try{f.info(`serverPath: ${this.serverPath}`),f.info(`rootUri: ${this.rootUri}`),f.info(`sdkPath: ${this.sdkPath}`),f.info(`logPath: ${this.logPath}`);let o=st(this.rootUri),i=new $s(o,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new Bn(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),i.modules=s;let l=zi(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(l),this.currentParams=new ea(o,i,new Qs),this.useStandardProtocol){let d=this.messageHandle;await d.sendInitializeResettable(this.currentParams,ze),f.info("[LSP] initialize response received"),d.broadcastToClients({jsonrpc:R,method:y.ARKTS_INDEXING_PROGRESS,params:{}}),d.sendInitialized()}else await this.startLegacy(this.currentParams,e);r=!0}catch(o){this.lastStartErrorMessage=o instanceof Error?o.message:String(o),f.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(r)}async startLegacy(e,t){let r=this.messageHandle;r.sendInitialize(e,1),r.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:R,method:y.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((o,i)=>{r.onIndexingProgressUpdate(i),r.onInitializationCompleted(o)},"LSP initialization",ze),r.sendInitialized(t)}withResettableTimeout(e,t,r){return new Promise((o,i)=>{let s,a=()=>{s=setTimeout(()=>{i(new Error(`${t} timeout after ${r}ms`))},r)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),o()},c)})}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){f.info(`[LSP] registerDiagnosticCallback uri='${e}', useStandardProtocol=${this.useStandardProtocol}`),this.messageHandle.registerRequestCallback(e,(t,r)=>{let o=D(r)?r:{};f.info(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let i={jsonrpc:R,method:t,params:{uri:typeof o.uri=="string"?o.uri:e,diagnostics:Array.isArray(o.diagnostics)?o.diagnostics:[],...typeof o.errorMessage=="string"?{errorMessage:o.errorMessage}:{}}};this.onLspMessage(i)})}async hover(e){let t=e.textDocument.uri;return this.registerDiagnosticCallback(t),this.stdHandle.sendLspRequest(y.HOVER,e)}async definition(e){return this.stdHandle.sendLspRequest(y.DEFINITION,e)}async references(e){return this.stdHandle.sendLspRequest(y.REFERENCES,e)}async completion(e){return this.stdHandle.sendLspRequest(y.COMPLETION,e)}async documentSymbol(e){return this.stdHandle.sendLspRequest(y.DOCUMENT_SYMBOL,e)}async diagnostic(e){return this.stdHandle.sendLspRequest(y.DIAGNOSTIC,e,120*1e3)}async sendFeatureRequest(e,t){return this.stdHandle.sendLspRequest(e,t)}reloadDependenciesOnly(e){let t=e?.fullReload??!1,r=new Bn(this.rootUri,this.sdkPath),o=this.getModuleModelsByName();if(t){f.info("[LspServerProxy] Project-level oh-package changed, parsing all modules' dependencies");let l=r.getDependenciesOnly();this.markDependencyTypesIncremental(l);let d=this.mergeDepsOnlyIntoModuleList(l,o);return this.applyModuleModelsUpdate(d),this.sendDidChangeConfiguration({moduleSet:d}),f.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${d.length}`),this.lastDepsOnlyForDiff=l,l}let i=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(i.length===0&&s.size===0)return f.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];f.info(`[LspServerProxy] Module-level deps changed, parsing: [${i.join(", ")}]`);let a=r.getDependenciesOnly(i);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),this.sendDidChangeConfiguration({moduleSet:c}),f.info(`[LspServerProxy] Dependencies only (incremental) reloaded, count: ${c.length}`),this.lastDepsOnlyForDiff=a,a}sendDidChangeConfiguration(e){this.stdHandle.sendDidChangeConfiguration(e)}getModuleModelsByName(){return new Map(this.currentModuleModels.map(e=>[e.moduleName??"",e]))}markDependencyTypesIncremental(e){let t=this.getModuleModelsByName(),r=new Map(this.lastDepsOnlyForDiff.map(o=>[o.moduleName??"",o]));for(let o of e){let i=o.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(i,t,r),c=o.dependencies??{},l=o.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(d,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 $n({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Er(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new Pr([]),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=tr(Uo.join(t,"default/openharmony/ets/build-tools/ets-loader")),o=tr(Uo.join(t,"default/openharmony/ets/api")),i=tr(Uo.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=o,s.hosSdkPath=i}sendRequest(e){switch(e.method){case y.HOVER:this.stdHandle.sendLspRequest(y.HOVER,e.params).then(t=>this.onLspMessage({jsonrpc:R,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:R,id:e.id,error:{code:-32603,message:t.message}}));break;case y.DEFINITION:this.stdHandle.sendLspRequest(y.DEFINITION,e.params).then(t=>this.onLspMessage({jsonrpc:R,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:R,id:e.id,error:{code:-32603,message:t.message}}));break;case y.REFERENCES:this.stdHandle.sendLspRequest(y.REFERENCES,e.params).then(t=>this.onLspMessage({jsonrpc:R,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:R,id:e.id,error:{code:-32603,message:t.message}}));break;default:f.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!Mm(e)){f.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case y.DID_OPEN:this.handleDidOpenNotification(e);break;case y.DID_CHANGE:this.handleDidChangeNotification(e);break;case y.DID_CLOSE:this.handleDidCloseNotification(e);break;case y.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;case y.DID_CREATE_FILES:this.handleDidCreateFiles(e);break;case y.DID_DELETE_FILES:this.handleDidDeleteFiles(e);break;default:f.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){f.error("Invalid textDocument/didOpen params");return}this.stdHandle.sendDidOpen(t)}handleDidChangeNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){f.error("Invalid textDocument/didChange params");return}this.stdHandle.sendDidChange(t)}handleDidCloseNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){f.error("Invalid textDocument/didClose params");return}this.stdHandle.closeFile(t)}handleDidChangeWatchedFiles(e){let t=e.params;!t||!Array.isArray(t.changes)||this.messageHandle.onDidChangeWatchedFiles(t.changes)}handleDidCreateFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(y.DID_CREATE_FILES,t)}handleDidDeleteFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(y.DID_DELETE_FILES,t)}async dispose(){await this.messageHandle.stop()}};import*as Ft from"fs";import*as on from"path";import{createHash as QC}from"crypto";import{EventEmitter as eI}from"events";var na=class extends eI{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r}projectRoot;watchers=new Map;debounceTimers=new Map;contentHashes=new Map;buildProfileWatcher=null;lastModulesSnapshot="";lastModules=[];debounceMs;start(){let t=this.parseModulesFromBuildProfile();this.lastModules=t,this.lastModulesSnapshot=this.computeModulesSnapshot(t),this.refreshWatchTargets(),this.watchBuildProfile()}refreshWatchTargets(){let t=new Set(this.collectWatchTargets()),r=new Set(this.watchers.keys());for(let o of t)r.has(o)||this.watchFile(o);for(let o of r)t.has(o)||(this.unwatchFile(o),f.info(`[ConfigFileWatcher] Stopped watching: ${o}`));f.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!Ft.existsSync(t)){f.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Ft.watch(t,r=>{r==="change"&&this.onBuildProfileChanged()}),this.buildProfileWatcher.on("error",r=>{f.error(`[ConfigFileWatcher] build-profile.json5 watch error: ${r.message}`)}),f.info(`[ConfigFileWatcher] Watching module registry: ${t}`)}catch(r){f.error(`[ConfigFileWatcher] Failed to watch build-profile.json5: ${r instanceof Error?r.message:String(r)}`)}}emitModuleAddedEvents(t,r){for(let o of t){let i=P.resolvePathWithinRoot(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=P.resolvePathWithinRoot(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=P.resolvePathWithinRoot(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=P.resolvePathWithinRoot(this.projectRoot,o.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:i,relativePath:o.after.srcPath,timestamp:r,moduleName:o.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let r=Date.now();this.emitModuleAddedEvents(t.added,r),this.emitModuleRemovedEvents(t.removed,r),this.emitModuleRenamedEvents(t.renamed,r),this.emitModuleMovedEvents(t.moved,r)}onBuildProfileChanged(){let t="__build_profile__",r=this.debounceTimers.get(t);r&&clearTimeout(r);let o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(i);if(s===this.lastModulesSnapshot){f.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,i);this.lastModules=i,this.lastModulesSnapshot=s,f.info(`[ConfigFileWatcher] build-profile.json5 modules changed, added=${a.added.length}, removed=${a.removed.length}, renamed=${a.renamed.length}, moved=${a.moved.length}`),this.processBuildProfileDiff(a)},this.debounceMs);this.debounceTimers.set(t,o)}computeModulesSnapshot(t){return t.map(o=>`${o.name}::${o.srcPath}`).sort().join("|")}diffModules(t,r){let o=this.buildModuleMatchState(r),i={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,o),this.matchRenamedModules(t,o,i),this.matchMovedModules(t,o,i),this.collectRemovedModules(t,o,i),this.collectAddedModules(r,o,i),i}buildModuleMatchState(t){let r=new Map,o=new Map;for(let i of t)r.set(i.srcPath,i),o.set(i.name,i);return{matchedOld:new Set,matchedNew:new Set,newBySrc:r,newByName:o}}matchExactModules(t,r){for(let o of t){let i=r.newBySrc.get(o.srcPath);i&&i.name===o.name&&(r.matchedOld.add(o),r.matchedNew.add(i))}}matchRenamedModules(t,r,o){for(let i of t){if(r.matchedOld.has(i))continue;let s=r.newBySrc.get(i.srcPath);s&&!r.matchedNew.has(s)&&s.name!==i.name&&(o.renamed.push({before:i,after:s}),r.matchedOld.add(i),r.matchedNew.add(s))}}matchMovedModules(t,r,o){for(let i of t){if(r.matchedOld.has(i))continue;let s=r.newByName.get(i.name);s&&!r.matchedNew.has(s)&&s.srcPath!==i.srcPath&&(o.moved.push({before:i,after:s}),r.matchedOld.add(i),r.matchedNew.add(s))}}collectRemovedModules(t,r,o){for(let i of t)r.matchedOld.has(i)||o.removed.push(i)}collectAddedModules(t,r,o){for(let i of t)r.matchedNew.has(i)||o.added.push(i)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let r=He(t);if(typeof r!="object"||r===null)return[];let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return f.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${r instanceof Error?r.message:String(r)}`),[]}}collectWatchTargets(){let t=[],r=on.join(this.projectRoot,L.OH_PACKAGE_JSON5);Ft.existsSync(r)&&t.push(r);let o=this.parseModulesFromBuildProfile();for(let i of o){let s=P.resolvePathWithinRoot(this.projectRoot,i.srcPath),a=on.join(s,L.OH_PACKAGE_JSON5);Ft.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return on.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Ft.readFileSync(t,"utf-8");return QC("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=Ft.watch(t,i=>{i==="change"&&this.onFileChanged(t)});o.on("error",i=>{f.error(`[ConfigFileWatcher] Watch error for ${t}: ${i.message}`)}),this.watchers.set(t,o)}catch(r){f.error(`[ConfigFileWatcher] Failed to watch ${t}: ${r instanceof Error?r.message:String(r)}`)}}unwatchFile(t){let r=this.watchers.get(t);r&&(r.close(),this.watchers.delete(t)),this.contentHashes.delete(t);let o=this.debounceTimers.get(t);o&&(clearTimeout(o),this.debounceTimers.delete(t))}onFileChanged(t){let r=this.debounceTimers.get(t);r&&clearTimeout(r);let o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.computeFileHash(t);if(!i){f.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===i){f.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,i),f.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:on.basename(t),relativePath:on.relative(this.projectRoot,t),timestamp:Date.now()};this.emit("configChanged",a)},this.debounceMs);this.debounceTimers.set(t,o)}stop(){for(let[,t]of this.watchers)t.close();this.watchers.clear(),this.buildProfileWatcher&&(this.buildProfileWatcher.close(),this.buildProfileWatcher=null);for(let t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.contentHashes.clear(),f.info("[ConfigFileWatcher] All watchers stopped")}};import*as sn from"fs";import*as lt from"path";import{createHash as tI}from"crypto";import{EventEmitter as nI}from"events";var ra=class extends nI{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=lt.join(t,Fo)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!sn.existsSync(this.depMapDir)){f.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=sn.watch(this.depMapDir,{recursive:!0},(t,r)=>this.onDirEvent(t,r)),this.dirWatcher.on("error",t=>{f.error(`[DependencyMapWatcher] Directory watch error for ${this.depMapDir}: ${t.message}`)})}catch(t){f.error(`[DependencyMapWatcher] Failed to watch directory ${this.depMapDir}: ${t instanceof Error?t.message:String(t)}`);return}this.pollInterval=setInterval(()=>this.scanAllCacheFiles(),2500),f.info(`[DependencyMapWatcher] Started, watching directory (recursive): ${this.depMapDir}, modules: [${this.lastModules.map(t=>t.name).join(", ")}]`)}canonicalPath(t){return U(lt.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===Un)i="dep-map-json";else{let a=o.match(/^([^/]+)\/oh-package\.json5$/);i=a?`module:${a[1]}`:""}if(!i)return;let s=lt.join(this.depMapDir,r);sn.existsSync(s)&&this.scheduleDebouncedFullScan()}stop(){this.dirWatcher&&(this.dirWatcher.close(),this.dirWatcher=null),this.fullScanTimer&&(clearTimeout(this.fullScanTimer),this.fullScanTimer=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.coalesceTimer&&(clearTimeout(this.coalesceTimer),this.coalesceTimer=null),this.pendingTags=[],this.pendingRenames=[],this.contentHashes.clear(),this.initialScanDone=!1,f.info("[DependencyMapWatcher] All watchers stopped")}scheduleDebouncedFullScan(){this.fullScanTimer&&clearTimeout(this.fullScanTimer),this.fullScanTimer=setTimeout(()=>{this.fullScanTimer=null,this.scanAllCacheFiles()},this.debounceMs)}scanAllCacheFiles(){let t=lt.join(this.depMapDir,L.OH_PACKAGE_JSON5),r=lt.join(this.depMapDir,Un),o=this.parseModulesFromDepMap(),i=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...o.map(s=>({path:lt.join(this.depMapDir,s.name,L.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of i){if(!sn.existsSync(s))continue;let c=this.canonicalPath(s),l=this.computeFileHash(s);if(!l)continue;let d=this.contentHashes.get(c);if(!this.initialScanDone){this.contentHashes.set(c,l);continue}d!==l&&(this.contentHashes.set(c,l),f.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=lt.join(this.depMapDir,Un);try{let r=He(t);if(typeof r!="object"||r===null)return[];let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return f.warn(`[DependencyMapWatcher] Failed to parse dependencyMap.json5: ${r instanceof Error?r.message:String(r)}`),[]}}scheduleCoalescedReload(t){this.pendingTags.push(t),t==="dep-map-json"&&this.applyDepMapJsonDiff(),this.coalesceTimer&&clearTimeout(this.coalesceTimer),this.coalesceTimer=setTimeout(()=>{this.coalesceTimer=null,this.flushPendingReload()},this.coalesceMs)}collectPendingState(){let t=this.pendingTags,r=this.pendingRenames;return this.pendingTags=[],this.pendingRenames=[],{tags:t,renameEntries:r}}processTagsIntoSets(t,r,o,i){for(let s of t)s.startsWith("module:")?(o.add(s.substring(7)),r.add("moduleDepsChanged")):s.startsWith("dep-added:")?(o.add(s.substring(10)),r.add("moduleAdded")):s.startsWith("dep-removed:")&&(i.add(s.substring(12)),r.add("moduleRemoved"))}processRenameEntries(t,r,o,i,s){for(let a of t)s.push(a.info),o.add(a.info.newName),i.add(a.info.oldName),r.add(a.kind)}buildAddedNamesSet(t,r){let o=new Set;for(let i of t)i.startsWith("dep-added:")&&o.add(i.substring(10));for(let i of r)o.add(i.info.newName);return o}emitIncrementalReload(t,r,o,i,s){f.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...r].join(",")}], removed=[${[...o].join(",")}], added=[${[...i].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...r],removedModuleNames:[...o],addedModuleNames:[...i],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:r}=this.collectPendingState();if(t.length===0&&r.length===0)return;if(f.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${r.length}`),t.includes("root-oh-package")){f.info("[DependencyMapWatcher] Root oh-package.json5 in batch \u2192 full reload"),this.emit("reload",{fullReload:!0,kinds:["projectDepsChanged"]});return}let o=new Set,i=new Set,s=new Set,a=[];this.processTagsIntoSets(t,o,i,s),this.processRenameEntries(r,o,i,s,a);for(let l of i)s.delete(l);if(i.size===0&&s.size===0&&a.length===0){f.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,r);this.emitIncrementalReload(o,i,s,c,a)}normalizeSrcPath(t){return 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=lt.join(this.depMapDir,a.name,L.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(l)),f.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,r,o,i){for(let[s,a]of t){if(o.has(s))continue;let c=r.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),o.add(s),i.add(s),f.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,r,o){for(let[i]of t)o.has(i)||r.has(i)||(this.pendingTags.push(`dep-added:${i}`),o.add(i))}detectRemovedModules(t,r,o){for(let[i]of t)if(!o.has(i)&&!r.has(i)){this.pendingTags.push(`dep-removed:${i}`),o.add(i);let s=lt.join(this.depMapDir,i,L.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(o=>o.startsWith("dep-")),r=this.pendingRenames.map(o=>`${o.kind}(${o.info.oldName}\u2192${o.info.newName})`);f.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${r.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:r,bySrcPath:o}=this.buildModuleLookupMaps(this.lastModules),{byName:i,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(o,s,a,c),this.detectModuleMoves(r,i,a,c),this.detectAddedModules(i,r,c),this.detectRemovedModules(r,i,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let r=sn.readFileSync(t,"utf-8");return tI("sha256").update(r).digest("hex")}catch{return null}}};import{spawn as rI}from"child_process";var oI=["install","--all"];async function iI(n,e,t,r){return new Promise(o=>{let i=rI(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(`
1290
+ `);if(r===-1)break;let i=this.buffer.slice(0,r).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!i){f.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(r+4);continue}let s=parseInt(i[1],10),a=r+4,c=a+s;if(this.buffer.length<c)break;let l=this.buffer.slice(a,c).toString("utf8"),d=this.recoverFramedJson(l);if(d&&d.rest.length>0){f.warn(`[LspClient] recovered mixed LSP frame, bodyLen=${l.length}, restLen=${d.rest.length}`),this.emit("message",d.json),this.buffer=Buffer.concat([Buffer.from(d.rest,"utf8"),this.buffer.slice(c)]);continue}this.emit("message",l),this.buffer=this.buffer.slice(c)}}waitForExitOrTimeout(t){let r=this.process;return!r||r.exitCode!==null||r.signalCode!==null?Promise.resolve():new Promise(o=>{let i=!1,s=()=>{i||(i=!0,clearTimeout(c),r.off("exit",a),o())},a=()=>s();r.once("exit",a);let c=setTimeout(s,t)})}recoverFramedJson(t){let r=t.search(/\S/);if(r<0||t[r]!=="{"&&t[r]!=="[")return null;let o=0,i=!1,s=!1;for(let a=r;a<t.length;a++){let c=t[a];if(i){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(i=!1);continue}if(c==='"'){i=!0;continue}if(c==="{"||c==="["){o++;continue}if((c==="}"||c==="]")&&(o--,o===0)){let l=t.slice(r,a+1),d=t.slice(a+1);return{json:l,rest:d}}}return null}stop(){this.isClosing=!0;let t=this.process;if(!t)return;if(this.process=null,t.exitCode===null&&t.signalCode===null)try{t.kill()}catch{}}};var on=class{callbacks=new Map;pending=new Map;timeouts=new Map;registerPending(e,t,r){return new Promise((o,i)=>{let s;r>0&&(s=setTimeout(()=>{this.pending.delete(e),this.timeouts.delete(e),i(new Error(`LSP request '${t}' (id=${e}) timeout after ${r}ms`))},r),this.timeouts.set(e,s)),this.pending.set(e,{resolve:o,reject:i,method:t,timer:s})})}resolvePending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.resolve(t),this.pending.delete(e),!0):!1}rejectPending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.reject(t),this.pending.delete(e),!0):!1}register(e,t){this.callbacks.set(e,t)}emit(e,t,r){f.info(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let o=this.callbacks.get(e);if(o)o(t,r),this.callbacks.delete(e);else{let i=[...this.callbacks.keys()].map(s=>String(s));f.info(`[RequestCallbackManager] emit: NO callback for key='${e}', registered keys=[${i.join(",")}]`)}}registerTimeout(e,t,r,o){let i=this.timeouts.get(e);i&&clearTimeout(i);let s=setTimeout(()=>{f.info(`[RequestCallbackManager] timeout, key=${e}, method=${t}`),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 Ls=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var Pr=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 A(n){return typeof n=="object"&&n!==null}var jm=20*1e3,zC=30*1e3,Os=class{client;nextRequestId=1;stopOnce=null;callbacks=new Pr;requestCallbacks=new on;diagnosticMap=new Map;initProgressReset=null;constructor(e){this.client=new rn(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{f.info("[ClientMessageHandle] Sending shutdown request"),this.client.sendRequest(y.SHUTDOWN,null,this.nextRequestId++),f.info("[ClientMessageHandle] Sending exit notification"),this.client.sendNotification(y.EXIT,null),f.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),f.info("[ClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(y.BROADCAST),this.callbacks.register(y.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(y.BROADCAST,e)}async sendInitialize(e){let t=this.nextRequestId++,r=this.requestCallbacks.registerPending(t,y.INITIALIZE,qe);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 Ls(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);f.error(`[LSP] JSON parse error: ${o}, raw: ${e}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotificationOrRequest(t):f.warn(`[LSP] Unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t===void 0)return;let r=t;if(e.error){let o=new Error(`LSP error ${e.error.code}: ${e.error.message}`);this.requestCallbacks.rejectPending(r,o)}else this.requestCallbacks.resolvePending(r,e.result)}handleNotificationOrRequest(e){let t=e.method;if(t)switch(this.initProgressReset?.(),t){case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.handleProgress(e.params);break;case y.WINDOW_SHOW_MESSAGE:f.info(`[LSP] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:f.info(`[LSP] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.broadcastToClients(e)}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=e.uri,r=this.diagnosticMap.get(t);if(!r)return;let o=e.diagnostics||[];this.normalizeDiagnostics(o),r.set(o),this.finalizeDiagnostic(t,o)}normalizeDiagnostics(e){for(let t of e)if(t.severity!==void 0){let r={1:"Error",2:"Warning",3:"Information",4:"Hint"};t.severityStr=r[t.severity]||"Unknown"}}handleProgress(e){A(e)&&this.broadcastToClients({jsonrpc:R,method:y.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,y.PUBLISH_DIAGNOSTICS,jm,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${jm}ms, uri: ${e}`)})}finalizeDiagnostic(e,t,r){let o={uri:e,diagnostics:t,...r?{errorMessage:r}:{}};this.requestCallbacks.emit(e,y.PUBLISH_DIAGNOSTICS,o),this.diagnosticMap.get(e)?.clear()}handleError(e){let t=Array.from(this.diagnosticMap.keys()).filter(r=>this.requestCallbacks.hasCallback(r));if(t.length>0){let r={range:{start:{line:0,character:0},end:{line:0,character:0}},severity:1,message:e.message};for(let o of t)this.finalizeDiagnostic(o,[r]);return}this.broadcastToClients({jsonrpc:R,method:y.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var Ms=class{uri;messages=[];receivedTypes=new Set;uniqueMessages=new Set;isFromEditor=!1;constructor(e){this.uri=e}setReceivedType(e){this.receivedTypes.add(e)}addMessage(e,t){this.receivedTypes.add(e);let r=`${e}:${t}`;if(this.uniqueMessages.has(r)){f.info(`[LegacyDiagnostic] addMessage: duplicate message=${r}`);return}this.uniqueMessages.add(r),this.messages.push(new Nl(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)}},Nl=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"},VC={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate",ON_FORCE_OPEN_FILE:"aceProject/onForceOpenFile",ON_PACKAGE_CHANGE_FINISH:"aceProject/onPackageChangeFinish",TEXT_DOCUMENT_ON_ASYNC_DEFINITION:"textDocument/onAsyncDefinition",ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:"textDocument/onDidChangePackageDependencies",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",REFERENCES:"textDocument/references",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",BROADCAST:"lsp/broadcast",ARKTS_ERROR:"arkts/error",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing"},T={...qC,...VC},sn={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"},Hm=new Set([1e3,2e3,3e3,3001]);function JC(n){if(!A(n))return!1;let e=n.textDocument;return A(e)&&typeof e.uri=="string"}function YC(n){return A(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function KC(n){return A(n)&&typeof n.moduleName=="string"&&typeof n.current=="number"&&typeof n.total=="number"?`indexing module '${n.moduleName}', ${n.current} of total ${n.total} modules`:`params=${JSON.stringify(n??null)}`}var _s=class n{client;isInitialized=!1;stopOnce=null;callbacks=new Pr;requestCallbacks=new on;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;constructor(e){this.client=new rn(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{f.info("[LegacyClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:T.EXIT,params:{}}),sn.EXIT),f.info("[LegacyClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),f.info("[LegacyClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(T.BROADCAST),this.callbacks.register(T.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(T.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(T.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(T.INDEXING_PROGRESS_UPDATE,e)}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}sendInitialize(e,t){this.client.send("initialize",e,t)}sendInitialized(e){this.client.sendRaw(JSON.stringify({jsonrpc:R,method:T.INITIALIZED,params:{editors:e}}),sn.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:R,id:0,result:{}}),sn.EMPTY)}sendAsyncRequest(e,t,r,o){if(!A(t)){f.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!JC(t)){f.warn(`[LSP] sendAsyncRequest missing textDocument.uri, method=${e}, params=${JSON.stringify(t)}`);return}if(typeof r!="number"){f.warn(`[LSP] sendAsyncRequest invalid requestId, method=${e}, requestId=${String(r)}`);return}let i=t.textDocument.uri,s=st(i);t.textDocument.uri=s,delete t.requestId;let a=o??e;f.info(`[LSP] sendAsyncRequest ${a}, filePath: ${i}`),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:e,params:{params:t,requestId:r}}),a)}onDidChangeWatchedFiles(e){if(f.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let r of e){if(!YC(r)){f.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:R,method:T.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),T.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!A(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){f.warn("[LSP] sendModuleDependencyUpdate, moduleSet is empty or null");return}let t=e.moduleSet;f.info(`[LSP] sending module dependency updated, count: ${t.length}`),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:T.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),sn.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let o=st(t);e.textDocument.uri=o,f.info(`[LSP] onAsyncOpenFile, uri: ${o}`);let i=this.diagnosticMap.get(o);i||(i=new Ms(o),this.diagnosticMap.set(o,i),this.registerDiagnosticTimeout(o,T.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(i.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:T.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),sn.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=st(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,T.PUBLISH_DIAGNOSTICS)),f.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:T.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),sn.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=st(e);f.info(`[LSP] didClose, uri: ${r}`);let o=this.diagnosticMap.get(r);if(!t&&(!o||o.isFromEditor)){f.info(`[LSP] closeFile skip, !diagnostic: ${!o}, isFromEditor: ${o?.isFromEditor}`);return}this.cleanupDiagnosticState(r),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:T.DID_CLOSE,params:{textDocument:{uri:r}}}),sn.DID_CLOSE)}getDiagnosticMessage(e){let t=st(e),r=this.diagnosticMap.get(t);return r?r.getMessages():[]}clear(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){try{let t=JSON.parse(e);this.handleLspMessage(t)}catch(t){let r=t instanceof Error?t.message:String(t);f.error(`[LSP] JSON parse error: ${r}, raw: ${e}`)}}handleError(e){let t=this.getPendingDiagnosticUris();if(t.length>0){let r=JSON.stringify({message:e.message,severity:"Error",severityStr:"Error"});for(let o of t)this.finalizeDiagnostic(o,T.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:R,method:T.ARKTS_ERROR,params:{message:e.message}})}handleLspMessage(e){let t=e.method;t!==void 0&&(!this.isInitialized&&this.handlePreInitMessage(t,e)||this.handlePostInitMessage(t,e))}handlePreInitMessage(e,t){switch(e){case T.MODULE_INIT_FINISH:return f.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(T.MODULE_INIT_FINISH),this.callbacks.unregister(T.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case T.INDEXING_PROGRESS_UPDATE:return f.info(`[LSP] onIndexingProgressUpdate: ${KC(t.params)}`),this.callbacks.invoke(T.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case T.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case T.ON_PACKAGE_CHANGE_FINISH:f.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case T.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case T.ON_ASYNC_HOVER:this.handleAsyncResponse(t,T.HOVER);return;case T.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,T.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case T.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,T.REFERENCES);return;default:f.warn(`[LSP] handleLspMessage: no handler for notification, ignoring, method: ${e}, initialized: ${this.isInitialized}`)}}handleOnForceOpenFile(e){f.info("[LSP] handleLspMessage, receive onForceOpenFile");let t=e.params;A(t)&&A(t.result)&&typeof t.result.uri=="string"&&this.handleForceOpenFile(t.result.uri)}handlePublishDiagnostics(e){f.info("[LSP] handleLspMessage, receive publishDiagnostics");let t=e.params;t&&this.parseDiagnostics(t)}handlePackageChangeFinish(e){let t=e.params,r={jsonrpc:R,method:T.ON_PACKAGE_CHANGE_FINISH,params:[!1]};if(!t||!Array.isArray(t)){f.warn("[LSP] aceProject/onPackageChangeFinish params invalid"),this.broadcastToClients(r);return}if(!(t.length>0&&t[0]===!0)){f.warn("[LSP] aceProject/onPackageChangeFinish: package request failed"),this.broadcastToClients(r);return}f.info("[LSP] aceProject/onPackageChangeFinish: success"),this.broadcastToClients(e)}handleAsyncResponse(e,t){f.info(`[LSP] handleAsyncResponse\uFF0C method: ${t}`);let r=e.params;if(!A(r)){f.warn("[LSP] aceProject/onAsyncHover message invalid");return}let o=r.requestId;if(typeof o!="number"){f.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(o,t,r)}handleForceOpenFile(e){if(!e){f.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,T.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){f.info("[LSP] publishDiagnostics uri is null");return}let r=e.version??-1;if(r===-1)return;let o=this.diagnosticMap.get(t);if(!o){f.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let i=e.diagnostics||[];i.length!==0?i.forEach(s=>{this.normalizeDiagnostic(s),o.addMessage(r,JSON.stringify(s))}):o.setReceivedType(r),o.hasReceivedAllTypes(Hm)&&this.finalizeDiagnostic(t,T.PUBLISH_DIAGNOSTICS,o.getMessages())}normalizeDiagnostic(e){let t=e;if(delete t.source,t.severity!==void 0){let r=typeof t.severity=="number"?t.severity:parseInt(t.severity),i={1:"Error",2:"Warning",3:"Information",4:"Hint"}[r]||"Unknown";t.severityStr=i,t.severity=i}e.range&&(this.adjustPositionLine(e.range,"start"),this.adjustPositionLine(e.range,"end"))}adjustPositionLine(e,t){let r=e[t];r&&typeof r.line=="number"&&(r.line=r.line+1)}registerDiagnosticTimeout(e,t){this.requestCallbacks.registerTimeout(e,t,n.DIAGNOSTIC_TIMEOUT_MS,()=>{let r=this.diagnosticMap.get(e),o=r?r.getMessages():[];this.finalizeDiagnostic(e,t,o,o.length>0?void 0:`received no diagnostics within ${n.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,r,o){let i={uri:e,diagnostics:r,...o?{errorMessage:o}:{}};this.requestCallbacks.emit(e,t,i),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import Wo from"path";import*as Ws from"path";var Fs=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var js=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var Hs=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var $s=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var Us=class{typeSetting=new Hs;parameterNames=new $s};var Bs=class{constructor(e,t,r,o){this.rootUri=e;this.lspServerWorkspacePath=U(Ws.dirname(t)),this.indexingDataLocation=U(o),this.loggerPath=U(Ws.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new Fs;gutterIconsSetting=new js;inlayHintsSetting=new Us;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as $m from"path";var Ho=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($m.join(e,"src","main","resources")))}};var XC="OS",Cr=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${XC}`;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 Ho(e)):this.buildProfileParam=new Ho}toString(){return JSON.stringify(this)}};var Ir=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as Ae from"path";import*as Rr from"fs";var Gs=class{modulePath;dependencies={};dynamicDependencies={}};var Un=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 Ar=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 jt from"path";import*as zs from"fs";var Dr=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:it.OH_PACKAGE_JSON5},$o=`${L.HVIGOR_CACHE}/${L.DEPENDENCY}`,Bn=`${L.DEPENDENCY}${L.JSON5}`,v1=it.SYNC_OUTPUT_PATH;var Uo=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=jt.join(this.dependencyPath,L.OH_PACKAGE_JSON5),r=Ue(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(!A(e))return r;let o=e[t];if(!A(o))return r;for(let[i,s]of Object.entries(o)){if(typeof s!="string"){f.error(`${i} package dependency value is not String ${t}`);continue}let a=new Dr;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=jt.normalize(jt.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)),jt.isAbsolute(s)){r.dependencyPath=i;return}o||(i=jt.resolve(this.modulePath,s)),zs.existsSync(i)&&zs.statSync(i).isDirectory()&&(r.dependencyPath=i)}catch(i){f.error("parser dependency path is invalid",i)}}};import*as Bo from"fs";import*as an from"path";import ZC from"json5";var qs=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 an.join(this.projectPath,L.OH_MODULES_PATH,L.OHPM_PATH,L.LOCK_JSON5_FILE)}readLockFile(e){if(!Bo.existsSync(e))return f.error("lock file does not exist"),this.clearDependencies(),null;try{let t=Bo.readFileSync(e,"utf8"),r=ZC.parse(t);return r||(f.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return f.error("Error parsing lock.json5:",t),this.clearDependencies(),null}}validateLockFile(e){if(!A(e))return f.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return f.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let r=e.packages;return r?{valid:!0,modules:t,packages:r}:(f.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,r){this.storePathMap=t,this.finalDependencies=this.getDependencyList(e,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(!A(e))return t;for(let[r,o]of Object.entries(e)){if(!A(o)){f.error(`${r} value is not json object`);continue}typeof o.storePath=="string"&&t.set(r,o.storePath)}return t}getDependencyList(e,t,r){if(!A(e))return[];for(let[o,i]of Object.entries(e))if(A(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(!A(o))return f.error("moduleJsonObject is null"),[];let i=[],s=o[t];if(!A(s))return[];for(let[a,c]of Object.entries(s)){if(!A(c))continue;let l=typeof c.specifier=="string"?c.specifier:"",d=typeof c.version=="string"?c.version:"",h=new Dr;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=an.resolve(this.projectPath,an.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=an.isAbsolute(a)?a:an.resolve(this.projectPath,a);Bo.existsSync(c)?(e.path=o,e.dependencyPath=this.fileNameForOhpm.test(i)?s:c):e.dependencyPath=s}catch(a){f.error("Invalid dependency path in lock.json5",a)}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};function Um(n){return A(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var Wn=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new kt(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=Ae.join(t,$o),o=Ae.join(r,Bn);if(!Rr.existsSync(r)||!Rr.existsSync(o)){let c="Dependency map or JSON not found";return f.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let i=new Ar(this.projectPath,".",this.projectPath);this.parseProjectDependencies(r,i),this.parseLockJson(i);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let c="No modules found in build-profile.json5";return f.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:c}}let a=Date.now();for(let c=0;c<s.length;c++){let l=s[c];Um(l)&&(this.parseSingleModule(l,r,i,e),(c+1)%100===0&&f.info(`[Parser] getAllDependencyMap progress: ${c+1}/${s.length} (${Date.now()-a}ms)`))}return f.info(`[Parser] getAllDependencyMap parsed ${e.length} modules in ${Date.now()-a}ms`),{status:"OK"}}getDependenciesOnly(e){let t=[],r=this.projectPath,o=Ae.join(r,$o),i=Ae.join(o,Bn);if(!Rr.existsSync(o)||!Rr.existsSync(i))return f.warn("[Parser] Dependency map or JSON not found."),t;let s=e&&e.length>0?new Set(e.map(l=>l.trim()).filter(Boolean)):null,a=new Ar(this.projectPath,".",this.projectPath);this.parseProjectDependencies(o,a),this.parseLockJson(a);let c=this.moduleInfoParse.getAllModuleInfo();if(c.length===0)return f.warn("[Parser] getAllDependencyMap failed: No modules found in build-profile.json5."),t;for(let l of c){if(!Um(l))continue;let d=l.name;if(s&&!s.has(d))continue;let h=Ae.resolve(this.projectPath,l.srcPath),w=Ae.join(o,d),S=U(h),k=this.buildModuleDependencies(d,S,w,a);k.moduleName=d,t.push(k)}return t}parseSingleModule(e,t,r,o){let i=e.name,s=Ae.resolve(this.projectPath,e.srcPath),a=Ae.join(t,i),c=U(s),l=new Cr(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 Ir(h),o.push(l)}buildModuleDependencies(e,t,r,o){let i=new Ar(this.projectPath,e,t);Uo.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 Gs;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 Un(i);for(let i of e.finalDynamicDependencies)o[i.name]=new Un(i);t.dependencies=r,t.dynamicDependencies=o}parseProjectDependencies(e,t){let r=Ae.join(e,L.OH_PACKAGE_JSON5);if(!Rr.existsSync(r))return;Uo.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 qs(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=Ae.join(e,"src","main","module.json5"),o=Ue(r);if(!A(o)||!A(o.module))return;let i=o.module;t.permissions=this.parseRequestPermissions(i),t.deviceType=this.parseDeviceTypes(i)}parseRequestPermissions(e){let t=[];if(A(e)&&Array.isArray(e.requestPermissions))for(let r of e.requestPermissions)A(r)&&typeof r.name=="string"&&t.push(r.name);return t}parseMainPages(e){let t=Ae.join(e,"src","main","resources","base","profile","main_pages.json"),r=Ue(t);return!A(r)||!Array.isArray(r.src)?[]:r.src.filter(o=>typeof o=="string")}parseSdkJson(e){let t=this.getSdkPkg();if(!(!A(t)||!A(t.data))){if(typeof t.data.apiVersion=="string"){let r=parseInt(t.data.apiVersion,10);!Number.isNaN(r)&&r>=26&&typeof t.data.platformVersion=="string"?e.compileSdkLevel=t.data.platformVersion:e.compileSdkLevel=t.data.apiVersion}typeof t.data.releaseType=="string"&&(e.compileSdkType=t.data.releaseType),typeof t.data.version=="string"&&(e.compileSdkVersion=t.data.version)}}getSdkPkg(){if(this.sdkPkgCache===void 0){let e=Ae.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=Ue(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!A(t)||!A(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let r=t.app.products[0];if(!A(r)||typeof r.compatibleSdkVersion!="string")return;let[o,i]=this.parseBySplit(r.compatibleSdkVersion);e.compatibleSdkVersion=o,e.compatibleSdkLevel=i}getBuildProfile(){if(this.buildProfileCache===void 0){let e=Ae.join(this.projectPath,"build-profile.json5");this.buildProfileCache=Ue(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!A(e)||!Array.isArray(e.deviceTypes)?[]:e.deviceTypes.filter(t=>typeof t=="string").map(t=>this.getDeviceType(t))}getDeviceType(e){return{liteWearable:1,wearable:2,tv:3,car:4,phone:5,default:5,smartVision:6,tablet:7,router:8,pc:9,"2in1":10}[e]||0}};var Vs=class{constructor(e=[]){this.valueSet=e}valueSet};var Tr=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var Bm=(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))(Bm||{}),Wm=()=>Object.values(Bm).filter(n=>typeof n=="number");var Js=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Ys=class{applyEdit=!0;workspaceEdit=new Js;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new Vs(Wm());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Tr;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Ks=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Xs=class{constructor(e=[]){this.valueSet=e}valueSet};var Zs=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var Gm=(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))(Gm||{}),zm=()=>Object.values(Gm).filter(n=>typeof n=="number");var Qs=class{completionItemKind=new Xs(zm());completionItem=new Zs;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var ea=class{synchronization=new Ks;completion=new Qs;hover={contentFormat:{},dynamicRegistration:{}};signatureHelp={signatureInformation:{},contextSupport:{},dynamicRegistration:{}};references={dynamicRegistration:{}};documentHighlight={dynamicRegistration:!0};documentSymbol=null;formatting={dynamicRegistration:{}};rangeFormatting={dynamicRegistration:{}};onTypeFormatting={dynamicRegistration:{}};declaration={};definition={linkSupport:{},dynamicRegistration:{}};codeLens=null;documentLink={tooltipSupport:{},dynamicRegistration:{}};colorProvider=null;rename={prepareSupport:!0,prepareSupportDefaultBehavior:null,honorsChangeAnnotations:null,dynamicRegistrationSupport:null};publishDiagnostics=null;foldingRage=null;typeHierarchy=null;callHierarchy={dynamicRegistration:{}};selectionRange=null;semanticTokens=new Tr;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var ta=class{workspace=new Ys;textDocument=new ea;notebookDocument=null;window=null;general=null;experimental=null};var na=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};var ra=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?Wo.resolve(Wo.dirname(e.arktsLangServerPath),"standardIndex","index.js"):e.arktsLangServerPath,this.logPath=Bu(),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 Os(t):new _s(t),this.messageHandle.setBroadcastToClients(r=>this.onLspMessage(r))}async start(e,t){let r=!1;try{f.info(`serverPath: ${this.serverPath}`),f.info(`rootUri: ${this.rootUri}`),f.info(`sdkPath: ${this.sdkPath}`),f.info(`logPath: ${this.logPath}`);let o=st(this.rootUri),i=new Bs(o,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new Wn(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),i.modules=s;let l=Vi(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(l),this.currentParams=new na(o,i,new ta),this.useStandardProtocol){let d=this.messageHandle;await d.sendInitializeResettable(this.currentParams,qe),f.info("[LSP] initialize response received"),d.broadcastToClients({jsonrpc:R,method:y.ARKTS_INDEXING_PROGRESS,params:{}}),d.sendInitialized()}else await this.startLegacy(this.currentParams,e);r=!0}catch(o){this.lastStartErrorMessage=o instanceof Error?o.message:String(o),f.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(r)}async startLegacy(e,t){let r=this.messageHandle;r.sendInitialize(e,1),r.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:R,method:y.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((o,i)=>{r.onIndexingProgressUpdate(i),r.onInitializationCompleted(o)},"LSP initialization",qe),r.sendInitialized(t)}withResettableTimeout(e,t,r){return new Promise((o,i)=>{let s,a=()=>{s=setTimeout(()=>{i(new Error(`${t} timeout after ${r}ms`))},r)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),o()},c)})}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){f.info(`[LSP] registerDiagnosticCallback uri='${e}', useStandardProtocol=${this.useStandardProtocol}`),this.messageHandle.registerRequestCallback(e,(t,r)=>{let o=A(r)?r:{};f.info(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let i={jsonrpc:R,method:t,params:{uri:typeof o.uri=="string"?o.uri:e,diagnostics:Array.isArray(o.diagnostics)?o.diagnostics:[],...typeof o.errorMessage=="string"?{errorMessage:o.errorMessage}:{}}};this.onLspMessage(i)})}async hover(e){let t=e.textDocument.uri;return this.registerDiagnosticCallback(t),this.stdHandle.sendLspRequest(y.HOVER,e)}async definition(e){return this.stdHandle.sendLspRequest(y.DEFINITION,e)}async references(e){return this.stdHandle.sendLspRequest(y.REFERENCES,e)}async completion(e){return this.stdHandle.sendLspRequest(y.COMPLETION,e)}async documentSymbol(e){return this.stdHandle.sendLspRequest(y.DOCUMENT_SYMBOL,e)}async diagnostic(e){return this.stdHandle.sendLspRequest(y.DIAGNOSTIC,e,120*1e3)}async sendFeatureRequest(e,t){return this.stdHandle.sendLspRequest(e,t)}reloadDependenciesOnly(e){let t=e?.fullReload??!1,r=new Wn(this.rootUri,this.sdkPath),o=this.getModuleModelsByName();if(t){f.info("[LspServerProxy] Project-level oh-package changed, parsing all modules' dependencies");let l=r.getDependenciesOnly();this.markDependencyTypesIncremental(l);let d=this.mergeDepsOnlyIntoModuleList(l,o);return this.applyModuleModelsUpdate(d),this.sendDidChangeConfiguration({moduleSet:d}),f.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${d.length}`),this.lastDepsOnlyForDiff=l,l}let i=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(i.length===0&&s.size===0)return f.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];f.info(`[LspServerProxy] Module-level deps changed, parsing: [${i.join(", ")}]`);let a=r.getDependenciesOnly(i);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),this.sendDidChangeConfiguration({moduleSet:c}),f.info(`[LspServerProxy] Dependencies only (incremental) reloaded, count: ${c.length}`),this.lastDepsOnlyForDiff=a,a}sendDidChangeConfiguration(e){this.stdHandle.sendDidChangeConfiguration(e)}getModuleModelsByName(){return new Map(this.currentModuleModels.map(e=>[e.moduleName??"",e]))}markDependencyTypesIncremental(e){let t=this.getModuleModelsByName(),r=new Map(this.lastDepsOnlyForDiff.map(o=>[o.moduleName??"",o]));for(let o of e){let i=o.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(i,t,r),c=o.dependencies??{},l=o.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(d,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 Un({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Cr(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new Ir([]),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=rr(Wo.join(t,"default/openharmony/ets/build-tools/ets-loader")),o=rr(Wo.join(t,"default/openharmony/ets/api")),i=rr(Wo.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=o,s.hosSdkPath=i}sendRequest(e){switch(e.method){case y.HOVER:this.stdHandle.sendLspRequest(y.HOVER,e.params).then(t=>this.onLspMessage({jsonrpc:R,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:R,id:e.id,error:{code:-32603,message:t.message}}));break;case y.DEFINITION:this.stdHandle.sendLspRequest(y.DEFINITION,e.params).then(t=>this.onLspMessage({jsonrpc:R,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:R,id:e.id,error:{code:-32603,message:t.message}}));break;case y.REFERENCES:this.stdHandle.sendLspRequest(y.REFERENCES,e.params).then(t=>this.onLspMessage({jsonrpc:R,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:R,id:e.id,error:{code:-32603,message:t.message}}));break;default:f.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!_m(e)){f.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case y.DID_OPEN:this.handleDidOpenNotification(e);break;case y.DID_CHANGE:this.handleDidChangeNotification(e);break;case y.DID_CLOSE:this.handleDidCloseNotification(e);break;case y.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;case y.DID_CREATE_FILES:this.handleDidCreateFiles(e);break;case y.DID_DELETE_FILES:this.handleDidDeleteFiles(e);break;default:f.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){f.error("Invalid textDocument/didOpen params");return}this.stdHandle.sendDidOpen(t)}handleDidChangeNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){f.error("Invalid textDocument/didChange params");return}this.stdHandle.sendDidChange(t)}handleDidCloseNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){f.error("Invalid textDocument/didClose params");return}this.stdHandle.closeFile(t)}handleDidChangeWatchedFiles(e){let t=e.params;!t||!Array.isArray(t.changes)||this.messageHandle.onDidChangeWatchedFiles(t.changes)}handleDidCreateFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(y.DID_CREATE_FILES,t)}handleDidDeleteFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(y.DID_DELETE_FILES,t)}async dispose(){await this.messageHandle.stop()}};import*as Ht from"fs";import*as Le from"path";import{createHash as eI}from"crypto";import{EventEmitter as tI}from"events";var oa=class extends tI{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r}projectRoot;watchers=new Map;debounceTimers=new Map;contentHashes=new Map;buildProfileWatcher=null;lastModulesSnapshot="";lastModules=[];debounceMs;start(){let t=this.parseModulesFromBuildProfile();this.lastModules=t,this.lastModulesSnapshot=this.computeModulesSnapshot(t),this.refreshWatchTargets(),this.watchBuildProfile()}refreshWatchTargets(){let t=new Set(this.collectWatchTargets()),r=new Set(this.watchers.keys());for(let o of t)r.has(o)||this.watchFile(o);for(let o of r)t.has(o)||(this.unwatchFile(o),f.info(`[ConfigFileWatcher] Stopped watching: ${o}`));f.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!Ht.existsSync(t)){f.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Ht.watch(t,r=>{r==="change"&&this.onBuildProfileChanged()}),this.buildProfileWatcher.on("error",r=>{f.error(`[ConfigFileWatcher] build-profile.json5 watch error: ${r.message}`)}),f.info(`[ConfigFileWatcher] Watching module registry: ${t}`)}catch(r){f.error(`[ConfigFileWatcher] Failed to watch build-profile.json5: ${r instanceof Error?r.message:String(r)}`)}}emitModuleAddedEvents(t,r){for(let o of t){let i=Le.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=Le.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=Le.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=Le.resolve(this.projectRoot,o.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:i,relativePath:o.after.srcPath,timestamp:r,moduleName:o.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let r=Date.now();this.emitModuleAddedEvents(t.added,r),this.emitModuleRemovedEvents(t.removed,r),this.emitModuleRenamedEvents(t.renamed,r),this.emitModuleMovedEvents(t.moved,r)}onBuildProfileChanged(){let t="__build_profile__",r=this.debounceTimers.get(t);r&&clearTimeout(r);let o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(i);if(s===this.lastModulesSnapshot){f.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,i);this.lastModules=i,this.lastModulesSnapshot=s,f.info(`[ConfigFileWatcher] build-profile.json5 modules changed, added=${a.added.length}, removed=${a.removed.length}, renamed=${a.renamed.length}, moved=${a.moved.length}`),this.processBuildProfileDiff(a)},this.debounceMs);this.debounceTimers.set(t,o)}computeModulesSnapshot(t){return t.map(o=>`${o.name}::${o.srcPath}`).sort().join("|")}diffModules(t,r){let o=this.buildModuleMatchState(r),i={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,o),this.matchRenamedModules(t,o,i),this.matchMovedModules(t,o,i),this.collectRemovedModules(t,o,i),this.collectAddedModules(r,o,i),i}buildModuleMatchState(t){let r=new Map,o=new Map;for(let i of t)r.set(i.srcPath,i),o.set(i.name,i);return{matchedOld:new Set,matchedNew:new Set,newBySrc:r,newByName:o}}matchExactModules(t,r){for(let o of t){let i=r.newBySrc.get(o.srcPath);i&&i.name===o.name&&(r.matchedOld.add(o),r.matchedNew.add(i))}}matchRenamedModules(t,r,o){for(let i of t){if(r.matchedOld.has(i))continue;let s=r.newBySrc.get(i.srcPath);s&&!r.matchedNew.has(s)&&s.name!==i.name&&(o.renamed.push({before:i,after:s}),r.matchedOld.add(i),r.matchedNew.add(s))}}matchMovedModules(t,r,o){for(let i of t){if(r.matchedOld.has(i))continue;let s=r.newByName.get(i.name);s&&!r.matchedNew.has(s)&&s.srcPath!==i.srcPath&&(o.moved.push({before:i,after:s}),r.matchedOld.add(i),r.matchedNew.add(s))}}collectRemovedModules(t,r,o){for(let i of t)r.matchedOld.has(i)||o.removed.push(i)}collectAddedModules(t,r,o){for(let i of t)r.matchedNew.has(i)||o.added.push(i)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let r=Ue(t);if(typeof r!="object"||r===null)return[];let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return f.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${r instanceof Error?r.message:String(r)}`),[]}}collectWatchTargets(){let t=[],r=Le.join(this.projectRoot,L.OH_PACKAGE_JSON5);Ht.existsSync(r)&&t.push(r);let o=this.parseModulesFromBuildProfile();for(let i of o){let s=Le.resolve(this.projectRoot,i.srcPath),a=Le.join(s,L.OH_PACKAGE_JSON5);Ht.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return Le.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Ht.readFileSync(t,"utf-8");return eI("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=Ht.watch(t,i=>{i==="change"&&this.onFileChanged(t)});o.on("error",i=>{f.error(`[ConfigFileWatcher] Watch error for ${t}: ${i.message}`)}),this.watchers.set(t,o)}catch(r){f.error(`[ConfigFileWatcher] Failed to watch ${t}: ${r instanceof Error?r.message:String(r)}`)}}unwatchFile(t){let r=this.watchers.get(t);r&&(r.close(),this.watchers.delete(t)),this.contentHashes.delete(t);let o=this.debounceTimers.get(t);o&&(clearTimeout(o),this.debounceTimers.delete(t))}onFileChanged(t){let r=this.debounceTimers.get(t);r&&clearTimeout(r);let o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.computeFileHash(t);if(!i){f.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===i){f.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,i),f.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:Le.basename(t),relativePath:Le.relative(this.projectRoot,t),timestamp:Date.now()};this.emit("configChanged",a)},this.debounceMs);this.debounceTimers.set(t,o)}stop(){for(let[,t]of this.watchers)t.close();this.watchers.clear(),this.buildProfileWatcher&&(this.buildProfileWatcher.close(),this.buildProfileWatcher=null);for(let t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.contentHashes.clear(),f.info("[ConfigFileWatcher] All watchers stopped")}};import*as cn from"fs";import*as dt from"path";import{createHash as nI}from"crypto";import{EventEmitter as rI}from"events";var ia=class extends rI{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=dt.join(t,$o)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!cn.existsSync(this.depMapDir)){f.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=cn.watch(this.depMapDir,{recursive:!0},(t,r)=>this.onDirEvent(t,r)),this.dirWatcher.on("error",t=>{f.error(`[DependencyMapWatcher] Directory watch error for ${this.depMapDir}: ${t.message}`)})}catch(t){f.error(`[DependencyMapWatcher] Failed to watch directory ${this.depMapDir}: ${t instanceof Error?t.message:String(t)}`);return}this.pollInterval=setInterval(()=>this.scanAllCacheFiles(),2500),f.info(`[DependencyMapWatcher] Started, watching directory (recursive): ${this.depMapDir}, modules: [${this.lastModules.map(t=>t.name).join(", ")}]`)}canonicalPath(t){return U(dt.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===Bn)i="dep-map-json";else{let a=o.match(/^([^/]+)\/oh-package\.json5$/);i=a?`module:${a[1]}`:""}if(!i)return;let s=dt.join(this.depMapDir,r);cn.existsSync(s)&&this.scheduleDebouncedFullScan()}stop(){this.dirWatcher&&(this.dirWatcher.close(),this.dirWatcher=null),this.fullScanTimer&&(clearTimeout(this.fullScanTimer),this.fullScanTimer=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.coalesceTimer&&(clearTimeout(this.coalesceTimer),this.coalesceTimer=null),this.pendingTags=[],this.pendingRenames=[],this.contentHashes.clear(),this.initialScanDone=!1,f.info("[DependencyMapWatcher] All watchers stopped")}scheduleDebouncedFullScan(){this.fullScanTimer&&clearTimeout(this.fullScanTimer),this.fullScanTimer=setTimeout(()=>{this.fullScanTimer=null,this.scanAllCacheFiles()},this.debounceMs)}scanAllCacheFiles(){let t=dt.join(this.depMapDir,L.OH_PACKAGE_JSON5),r=dt.join(this.depMapDir,Bn),o=this.parseModulesFromDepMap(),i=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...o.map(s=>({path:dt.join(this.depMapDir,s.name,L.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of i){if(!cn.existsSync(s))continue;let c=this.canonicalPath(s),l=this.computeFileHash(s);if(!l)continue;let d=this.contentHashes.get(c);if(!this.initialScanDone){this.contentHashes.set(c,l);continue}d!==l&&(this.contentHashes.set(c,l),f.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=dt.join(this.depMapDir,Bn);try{let r=Ue(t);if(typeof r!="object"||r===null)return[];let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return f.warn(`[DependencyMapWatcher] Failed to parse dependencyMap.json5: ${r instanceof Error?r.message:String(r)}`),[]}}scheduleCoalescedReload(t){this.pendingTags.push(t),t==="dep-map-json"&&this.applyDepMapJsonDiff(),this.coalesceTimer&&clearTimeout(this.coalesceTimer),this.coalesceTimer=setTimeout(()=>{this.coalesceTimer=null,this.flushPendingReload()},this.coalesceMs)}collectPendingState(){let t=this.pendingTags,r=this.pendingRenames;return this.pendingTags=[],this.pendingRenames=[],{tags:t,renameEntries:r}}processTagsIntoSets(t,r,o,i){for(let s of t)s.startsWith("module:")?(o.add(s.substring(7)),r.add("moduleDepsChanged")):s.startsWith("dep-added:")?(o.add(s.substring(10)),r.add("moduleAdded")):s.startsWith("dep-removed:")&&(i.add(s.substring(12)),r.add("moduleRemoved"))}processRenameEntries(t,r,o,i,s){for(let a of t)s.push(a.info),o.add(a.info.newName),i.add(a.info.oldName),r.add(a.kind)}buildAddedNamesSet(t,r){let o=new Set;for(let i of t)i.startsWith("dep-added:")&&o.add(i.substring(10));for(let i of r)o.add(i.info.newName);return o}emitIncrementalReload(t,r,o,i,s){f.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...r].join(",")}], removed=[${[...o].join(",")}], added=[${[...i].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...r],removedModuleNames:[...o],addedModuleNames:[...i],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:r}=this.collectPendingState();if(t.length===0&&r.length===0)return;if(f.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${r.length}`),t.includes("root-oh-package")){f.info("[DependencyMapWatcher] Root oh-package.json5 in batch \u2192 full reload"),this.emit("reload",{fullReload:!0,kinds:["projectDepsChanged"]});return}let o=new Set,i=new Set,s=new Set,a=[];this.processTagsIntoSets(t,o,i,s),this.processRenameEntries(r,o,i,s,a);for(let l of i)s.delete(l);if(i.size===0&&s.size===0&&a.length===0){f.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,r);this.emitIncrementalReload(o,i,s,c,a)}normalizeSrcPath(t){return 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=dt.join(this.depMapDir,a.name,L.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(l)),f.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,r,o,i){for(let[s,a]of t){if(o.has(s))continue;let c=r.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),o.add(s),i.add(s),f.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,r,o){for(let[i]of t)o.has(i)||r.has(i)||(this.pendingTags.push(`dep-added:${i}`),o.add(i))}detectRemovedModules(t,r,o){for(let[i]of t)if(!o.has(i)&&!r.has(i)){this.pendingTags.push(`dep-removed:${i}`),o.add(i);let s=dt.join(this.depMapDir,i,L.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(o=>o.startsWith("dep-")),r=this.pendingRenames.map(o=>`${o.kind}(${o.info.oldName}\u2192${o.info.newName})`);f.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${r.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:r,bySrcPath:o}=this.buildModuleLookupMaps(this.lastModules),{byName:i,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(o,s,a,c),this.detectModuleMoves(r,i,a,c),this.detectAddedModules(i,r,c),this.detectRemovedModules(r,i,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let r=cn.readFileSync(t,"utf-8");return nI("sha256").update(r).digest("hex")}catch{return null}}};import{spawn as oI}from"child_process";var iI=["install","--all"];async function sI(n,e,t,r){return new Promise(o=>{let i=oI(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(`
1291
1291
  `);o({exitCode:c??-1,output:l})}),i.on("error",c=>{let l=[s,a].filter(Boolean).join(`
1292
1292
  `);o({exitCode:-1,output:l+`
1293
- `+c.message})})})}function sI(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>f.info("[ohpm] %s",e))}async function zm(n,e){try{let{exitCode:t,output:r}=await iI(e.nodePath,[e.ohpmJsPath,...oI],n,e.sdkPath);return sI(r),t===0?(f.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(f.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",t),f.error("ohpm \u8F93\u51FA: %s",r),!1)}catch(t){return f.error("ohpm \u5B89\u88C5\u5F02\u5E38",t),!1}}var qm={UNINITIALIZED:-32099,UNKNOWN:-32e3},Bo=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 Rr=class{config;lspProxy=null;configWatcher=null;depMapWatcher=null;isInitialized=!1;lastEditorOpenFiles=[];onMessage=()=>{};onConfigChanged=null;disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}async start(e=[]){this.lastEditorOpenFiles=e,this.startConfigWatcher(),this.startLspProxy(e)}sendNotification(e){if(!this.lspProxy){f.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){f.warn("[ArktsLspManager] sendRequest before LSP ready, dropped");return}this.lspProxy.sendRequest(e)}async diagnostic(e){if(!this.lspProxy)throw new Error("[ArktsLspManager] diagnostic before LSP ready");return this.lspProxy.diagnostic(e)}async sendFeatureRequest(e,t){if(!this.useStandardProtocol)throw new Error(`Language feature '${e}' is not supported on the installed DevEco Studio. The standard LSP protocol entry (plugins/openharmony/ace-server/out/standardIndex/index.js) was not found. Please upgrade DevEco Studio to version 26.0.0.610 or later to use this tool.`);if(!this.lspProxy)throw new Error("LSP not ready");return this.lspProxy.sendFeatureRequest(e,t)}get useStandardProtocol(){return this.config.useStandardProtocol}onAsyncOpenFile(e){this.lspProxy?.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.lspProxy?.closeFileLegacy(e,t)}registerDiagnosticCallback(e){this.lspProxy?.registerDiagnosticCallback(e)}static async handleSyncProject(e,t,r){if(f.info("[ArktsLspManager] Received arkts/syncProject"),!e)return f.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let o=r?.skipHvigorSync===!0,i=await Li(e,async()=>await zm(e,t)?o?(f.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await Ju(e,t)?(f.info("[ArktsLspManager] syncProject completed successfully"),{status:"success"}):(f.error("[ArktsLspManager] syncProject failed"),{status:"failed",reason:"hvigor sync failed"}):(f.error("[ArktsLspManager] ohpm install failed"),{status:"failed",reason:"ohpm install failed"}));return i.acquired?i.result:(f.info("[ArktsLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){try{this.configWatcher?.stop()}catch(e){f.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){f.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){f.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e){let t=new ta(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)f.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:R,method:y.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();f.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?Bo.uninitialized(t):Bo.unknown();this.onMessage({jsonrpc:R,method:y.ARKTS_INITIALIZATION_FAILED,params:r.toJsonRpcErrorParams()}),this.lspProxy=null}};handleLspMessage(e){this.onMessage(e)}maybeRetryLspAfterSuccessfulSync(){this.isInitialized||this.lspProxy!==null||(f.info("[ArktsLspManager] Retrying LSP startup after successful sync"),this.onMessage({jsonrpc:R,method:y.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new na(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new ra(this.config.workspaceRoot),this.depMapWatcher.on("reload",e=>{if(!this.lspProxy){f.warn("[ArktsLspManager] LspServerProxy not initialized, skip reload");return}let r=this.lspProxy.reloadDependenciesOnly(e).map(o=>({modulePath:o.modulePath??"",dependencies:o.dependencies??{},dynamicDependencies:o.dynamicDependencies??{}}));this.onMessage({jsonrpc:R,method:y.ARKTS_SYNC_COMPLETED,params:{success:!0,moduleSet:r}})}),this.depMapWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){f.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),this.onConfigChanged?.()}};var aI=10080*60*1e3,cI=7200*60*1e3,lI=120*1e3,Tr=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:Nl.object({files:Nl.array(Nl.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=ue(e),{logPath:s,indexPath:a}=this.getLogAndIndexPath(i);setImmediate(()=>{Sc(a,aI,"[ArkTS-Check]"),Sc(s,cI,"[ArkTS-Check]")}),Wi(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 Rr({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(ze),this.manager.start([]).catch(S=>{let k=S instanceof Error?S:new Error(String(S));this.failInit(k)})})}resolveProjectAndDeveco(){let e=Dt(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=me.resolve(me.dirname(r),"standardIndex","index.js"),i=Ne.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=kn(e),o=await Ne.promises.readFile(e,"utf8"),s=`deveco.apptool.${me.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 dI(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"))},lI);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(`
1294
- `):"\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 Ne.promises.readFile(t,"utf8")).split(`
1295
- `).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=kn(e),o=await Ne.promises.readFile(e,"utf8"),s=`deveco.apptool.${me.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=me.isAbsolute(e)?e:me.join(this.projectPath,e);return!Ne.existsSync(t)||!Ne.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=me.isAbsolute(i)?i:me.join(r,i);if(!Ne.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${i}`);continue}if(!Ne.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 Lu(500);try{let i=await this.checkFile(o);r.push(uI(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(`
1293
+ `+c.message})})})}function aI(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>f.info("[ohpm] %s",e))}async function qm(n,e){try{let{exitCode:t,output:r}=await sI(e.nodePath,[e.ohpmJsPath,...iI],n,e.sdkPath);return aI(r),t===0?(f.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(f.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",t),f.error("ohpm \u8F93\u51FA: %s",r),!1)}catch(t){return f.error("ohpm \u5B89\u88C5\u5F02\u5E38",t),!1}}var Vm={UNINITIALIZED:-32099,UNKNOWN:-32e3},Go=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,Vm.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,Vm.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var kr=class{config;lspProxy=null;configWatcher=null;depMapWatcher=null;isInitialized=!1;lastEditorOpenFiles=[];onMessage=()=>{};onConfigChanged=null;disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}async start(e=[]){this.lastEditorOpenFiles=e;try{this.startConfigWatcher(),this.startLspProxy(e)}catch(t){throw f.error(`[ArktsLspManager] start() synchronous failure: ${t instanceof Error?t.message:String(t)}`),t}}sendNotification(e){if(!this.lspProxy){f.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){f.warn("[ArktsLspManager] sendRequest before LSP ready, dropped");return}this.lspProxy.sendRequest(e)}async diagnostic(e){if(!this.lspProxy)throw new Error("[ArktsLspManager] diagnostic before LSP ready");return this.lspProxy.diagnostic(e)}async sendFeatureRequest(e,t){if(!this.useStandardProtocol)throw new Error(`Language feature '${e}' is not supported on the installed DevEco Studio. The standard LSP protocol entry (plugins/openharmony/ace-server/out/standardIndex/index.js) was not found. Please upgrade DevEco Studio to version 26.0.0.610 or later to use this tool.`);if(!this.lspProxy)throw new Error("LSP not ready");return this.lspProxy.sendFeatureRequest(e,t)}get useStandardProtocol(){return this.config.useStandardProtocol}onAsyncOpenFile(e){this.lspProxy?.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.lspProxy?.closeFileLegacy(e,t)}registerDiagnosticCallback(e){this.lspProxy?.registerDiagnosticCallback(e)}static async handleSyncProject(e,t,r){if(f.info("[ArktsLspManager] Received arkts/syncProject"),!e)return f.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let o=r?.skipHvigorSync===!0,i=await Mi(e,async()=>await qm(e,t)?o?(f.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await Yu(e,t)?(f.info("[ArktsLspManager] syncProject completed successfully"),{status:"success"}):(f.error("[ArktsLspManager] syncProject failed"),{status:"failed",reason:"hvigor sync failed"}):(f.error("[ArktsLspManager] ohpm install failed"),{status:"failed",reason:"ohpm install failed"}));return i.acquired?i.result:(f.info("[ArktsLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){try{this.configWatcher?.stop()}catch(e){f.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){f.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){f.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e){let t=new ra(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)f.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:R,method:y.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();f.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?Go.uninitialized(t):Go.unknown();this.onMessage({jsonrpc:R,method:y.ARKTS_INITIALIZATION_FAILED,params:r.toJsonRpcErrorParams()}),this.lspProxy=null}};handleLspMessage(e){this.onMessage(e)}maybeRetryLspAfterSuccessfulSync(){this.isInitialized||this.lspProxy!==null||(f.info("[ArktsLspManager] Retrying LSP startup after successful sync"),this.onMessage({jsonrpc:R,method:y.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new oa(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new ia(this.config.workspaceRoot),this.depMapWatcher.on("reload",e=>{if(!this.lspProxy){f.warn("[ArktsLspManager] LspServerProxy not initialized, skip reload");return}let r=this.lspProxy.reloadDependenciesOnly(e).map(o=>({modulePath:o.modulePath??"",dependencies:o.dependencies??{},dynamicDependencies:o.dynamicDependencies??{}}));this.onMessage({jsonrpc:R,method:y.ARKTS_SYNC_COMPLETED,params:{success:!0,moduleSet:r}})}),this.depMapWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){f.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),this.onConfigChanged?.()}};var cI=10080*60*1e3,lI=7200*60*1e3,dI=120*1e3,xr=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:Ll.object({files:Ll.array(Ll.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=pe(e),{logPath:s,indexPath:a}=this.getLogAndIndexPath(i);setImmediate(()=>{bc(a,cI,"[ArkTS-Check]"),bc(s,lI,"[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 kr({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(qe),this.manager.start([]).catch(S=>{let k=S instanceof Error?S:new Error(String(S));this.failInit(k)})})}resolveProjectAndDeveco(){let e=Tt(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=Oe.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=xn(e),o=await Oe.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 uI(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"))},dI);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(`
1294
+ `):"\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 Oe.promises.readFile(t,"utf8")).split(`
1295
+ `).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=xn(e),o=await Oe.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!Oe.existsSync(t)||!Oe.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(!Oe.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${i}`);continue}if(!Oe.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 Ou(500);try{let i=await this.checkFile(o);r.push(pI(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(`
1296
1296
  `)),t.length>0&&r.push(t.join(`
1297
1297
  `));let o=r.join(`
1298
- `).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(ze),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=me.join(Kt(),"ArkTSCheck"),r=me.join(t,"mapping-config.properties"),o=Ou(e,r),i=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=me.join(t,"lsp-log",String(o),i),a=me.join(t,"lsp-index",String(o));return Ne.mkdirSync(s,{recursive:!0}),Ne.mkdirSync(a,{recursive:!0}),{logPath:ue(s),indexPath:ue(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function dI(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 uI(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 Ue from"fs";import*as ia from"path";import{z as Ll}from"zod";function kr(){return{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}}function oa(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 pI=500,xr=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:Ll.object({files:Ll.array(Ll.string()).describe('List of C/C++ file paths to check, format: ["file1.cpp","file2.hpp",...]')})}}async handleCall(e){if(!this.manager.ready)return kr();let t=[],r=[],o=this.collectValidFiles(e.files,t);if(o.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
1299
- `):"No valid C/C++ files"}],isError:!0};this.patchSdkPathInCompileCommands(this.manager.projectRoot,this.toolProvider.sdkPath);for(let c of o){await mI(pI);try{let l=await this.checkFile(c);r.push(fI(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(`
1298
+ `).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(qe),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(Qt(),"ArkTSCheck"),r=le.join(t,"mapping-config.properties"),o=Mu(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 Oe.mkdirSync(s,{recursive:!0}),Oe.mkdirSync(a,{recursive:!0}),{logPath:pe(s),indexPath:pe(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function uI(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 pI(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 ln from"fs";import*as Or from"path";import{z as Ol}from"zod";function Nr(){return{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}}function sa(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 fI=500,Lr=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:Ol.object({files:Ol.array(Ol.string()).describe('List of C/C++ file paths to check, format: ["file1.cpp","file2.hpp",...]')})}}async handleCall(e){if(!this.manager.ready)return Nr();let t=[],r=[],o=this.collectValidFiles(e.files,t);if(o.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
1299
+ `):"No valid C/C++ files"}],isError:!0};this.manager.patchSdkPathInCompileCommands();for(let c of o){await hI(fI);try{let l=await this.checkFile(c);r.push(mI(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(`
1300
1300
  `)),r.length>0&&s.push(r.join(`
1301
1301
  `));let a=s.join(`
1302
- `).trim();return!i&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:i}}patchSdkPathInCompileCommands(e,t){if(!b())return;let r=Rn(e);if(!Ue.existsSync(r))return;let o=Ue.readFileSync(r,"utf8");if(!o.includes(Gi))return;let i=o.replaceAll(Gi,t);Ue.writeFileSync(r,i,"utf8"),f.info(`[CppCheck] Patched SDK path in compile_commands.json: ${Gi} -> ${t}`)}async checkFile(e){let t=kn(e),r=await Ue.promises.readFile(e,"utf8"),o=Hi(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=ia.isAbsolute(i)?i:ia.join(r,i);if(!Ue.existsSync(s)){t.push(`File does not exist: ${i}`);continue}if(!Ue.statSync(s).isFile()){t.push(`Not a regular file: ${i}`);continue}if(!Tn(s)){t.push(`Not a supported C/C++ file: ${i}`);continue}try{o.push(Ue.realpathSync(s))}catch{o.push(s)}}return o}};function fI(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 mI(n){return new Promise(e=>setTimeout(e,n))}import*as Lr from"fs";import*as sa from"path";var Nr=class n{manager;static FEATURE_METHOD_MAP={hover:y.HOVER,definition:y.DEFINITION,declaration:y.DECLARATION,references:y.REFERENCES,implementation:y.IMPLEMENTATION};constructor(e){this.manager=e}async handleLspFeature(e,t){if(!this.manager.ready)return kr();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${t.file}`}],isError:!0};let o=n.FEATURE_METHOD_MAP[e];if(!o)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};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 oa(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 kr();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e}`}],isError:!0};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 oa("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return kr();if(e.direction==="outgoing")return{content:[{type:"text",text:"callHierarchy outgoing is not supported by clangd (incoming only)"}],isError:!0};let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e.file}`}],isError:!0};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 oa("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=kn(e),o=await Lr.promises.readFile(e,"utf8"),i=Hi(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=sa.isAbsolute(e)?e:sa.join(this.manager.projectRoot,e);return!Lr.existsSync(t)||!Lr.statSync(t).isFile()||!Tn(t)?null:t}};import{spawn as hI}from"child_process";import*as ca from"fs";import*as Vm from"path";var gI=30*1e3,yI=30*1e3,aa=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new nn;diagnosticWaiters=new Map;lastStartErrorMessage=null;onMessage=()=>{};disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}async start(e){let t=!1;try{f.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),f.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),f.info(`[ClangdLspProxy] compileCommandsDir: ${this.config.compileCommandsDir}`),this.ensureLogDir(),this.clangdProcess=this.spawnClangd();let r={serverPath:"",logPath:this.config.logPath,indexingDataLocation:this.config.logPath,cwd:this.config.workspaceRoot,nodePath:this.config.nodePath};this.client=new tn(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,ze),f.info("[ClangdLspProxy] initialize response received"),this.sendNotification(y.INITIALIZED,{}),t=!0}catch(r){this.lastStartErrorMessage=r instanceof Error?r.message:String(r),f.error(`[ClangdLspProxy] initialization failed: ${this.lastStartErrorMessage}`),await this.dispose()}e?.(t)}async hover(e){return this.sendLspRequest(y.HOVER,e)}async definition(e){return this.sendLspRequest(y.DEFINITION,e)}async declaration(e){return this.sendLspRequest(y.DECLARATION,e)}async references(e){return this.sendLspRequest(y.REFERENCES,e)}async implementation(e){return this.sendLspRequest(y.IMPLEMENTATION,e)}async documentSymbol(e){return this.sendLspRequest(y.DOCUMENT_SYMBOL,e)}async workspaceSymbol(e){return this.sendLspRequest(y.WORKSPACE_SYMBOL,e)}async prepareCallHierarchy(e){return this.sendLspRequest(y.PREPARE_CALL_HIERARCHY,e)}async incomingCalls(e){return this.sendLspRequest(y.INCOMING_CALLS,e)}async sendFeatureRequest(e,t){return this.sendLspRequest(e,t)}sendDidOpen(e){this.sendNotification(y.DID_OPEN,e)}sendDidChange(e){this.sendNotification(y.DID_CHANGE,e)}sendDidClose(e){this.sendNotification(y.DID_CLOSE,e)}sendNotification(e,t){if(!this.client){f.warn("[ClangdLspProxy] sendNotification before ready, dropped");return}this.client.sendNotification(e,t)}registerDiagnosticCallback(e){let t=this.normalizeClangdUri(e);if(this.diagnosticWaiters.has(t)){f.warn(`[ClangdLspProxy] overwrite existing diagnostic waiter for ${t}`);let r=this.diagnosticWaiters.get(t);clearTimeout(r.timer),this.diagnosticWaiters.delete(t)}return new Promise((r,o)=>{let i=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&o(new Error(`Wait for clangd diagnostics timeout, uri: ${t}`))},yI);this.diagnosticWaiters.set(t,{resolve:r,reject:o,timer:i})})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){this.requestCallbacks.rejectAll(new Error("ClangdLspProxy disposing"));for(let[,e]of this.diagnosticWaiters)clearTimeout(e.timer),e.reject(new Error("ClangdLspProxy disposing"));if(this.diagnosticWaiters.clear(),this.client&&this.clangdProcess)try{await this.sendLspRequest(y.SHUTDOWN,null,3e3).catch(e=>{f.warn(`[ClangdLspProxy] shutdown request failed: ${e}`)}),this.sendNotification(y.EXIT,null),await this.client.waitForExitOrTimeout(300)}catch(e){f.warn(`[ClangdLspProxy] dispose error: ${e}`)}if(this.clangdProcess){try{this.clangdProcess.exitCode===null&&this.clangdProcess.signalCode===null&&this.clangdProcess.kill()}catch{}this.clangdProcess=null}this.client=null}spawnClangd(){let e=[`--compile-commands-dir=${U(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];f.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=hI(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=tr(this.config.workspaceRoot),t=st(e),r=Vm.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"0.3.0-TD.1.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=gI){if(!this.client)return Promise.reject(new Error("[ClangdLspProxy] client not ready"));let o=this.nextRequestId++,i=this.requestCallbacks.registerPending(o,e,r);return this.client.sendRequest(e,t,o),i}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let o=r instanceof Error?r.message:String(r);f.error(`[ClangdLspProxy] JSON parse error: ${o}, raw: ${e.slice(0,200)}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotification(t):f.warn(`[ClangdLspProxy] unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t==null||typeof t!="string"&&typeof t!="number")return;let r=t;if(e.error!==void 0){let o=e.error;f.warn(`[ClangdLspProxy] LSP error id=${r}: code=${o.code??-1} message=${o.message??"unknown"}`),this.requestCallbacks.rejectPending(r,new Error(`LSP error ${o.code??-1}: ${o.message??"unknown"}`))}else this.requestCallbacks.resolvePending(r,e.result)}handleNotification(e){let t=e.method;if(t)switch(t){case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.onMessage({jsonrpc:R,method:y.PROGRESS,params:e.params});break;case y.WINDOW_SHOW_MESSAGE:f.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:f.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:R,method:t,params:e.params})}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=this.normalizeClangdUri(e.uri),r=this.diagnosticWaiters.get(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.diagnosticWaiters.get(s),r&&this.diagnosticWaiters.delete(s)}else r&&this.diagnosticWaiters.delete(t);if(!r)return;clearTimeout(r.timer);let o=Array.isArray(e.diagnostics)?e.diagnostics:[],i=o.length;f.info(`[ClangdLspProxy] diagnostics received uri=${t} count=${i}`),r.resolve(o)}handleError(e){for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear(),this.requestCallbacks.rejectAll(e),this.onMessage({jsonrpc:R,method:y.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{ca.existsSync(this.config.logPath)||ca.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)),st(r)}}catch{}return e}};import*as Wo from"path";import*as Ol from"fs";var Go=class{config;proxy=null;isInitialized=!1;onMessage=()=>{};disposeOnce=null;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;resolvedRoot="";constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}get ready(){return this.isInitialized&&this.proxy!==null}get projectRoot(){return this.resolvedRoot}async start(){if(!this.isInitialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doStart();try{await this.initPromise}catch(e){throw this.initPromise=null,e}}}sendNotification(e){if(!this.proxy){f.warn("[ClangdLspManager] sendNotification before LSP ready, dropped");return}this.dispatchNotification(e)}async sendFeatureRequest(e,t){if(!this.proxy)throw new Error("[ClangdLspManager] LSP not ready");return this.proxy.sendFeatureRequest(e,t)}registerDiagnosticCallback(e){return this.proxy?this.proxy.registerDiagnosticCallback(e):Promise.reject(new Error("[ClangdLspManager] LSP not ready"))}static async handleSyncCppProject(e,t){if(f.info("[ClangdLspManager] Received cpp/syncProject"),!e)return f.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or devecoPath is empty"),{status:"failed",reason:"workspaceRoot or devecoPath is empty"};if(Nn(e).length===0)return f.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let o=await Li(e,async()=>{try{return await Xu(e,t),f.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(i){let s=i instanceof Error?i.message:String(i);return f.error(`[ClangdLspManager] compileNative failed: ${s}`),{status:"failed",reason:s}}});return o.acquired?o.result:(f.info("[ClangdLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}doStart(){return new Promise((e,t)=>{this.initResolve=e,this.initReject=t,this.armInitTimer(ze);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=Dt(this.config.workspaceRoot);this.resolvedRoot=e?ue(e):ue(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();Wi(t);let r=this.config.toolProvider.clangdPath;if(!r){let s="clangd executable not found inside DevEco Studio SDK";f.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let o=Wo.dirname(Rn(this.resolvedRoot));try{Ol.mkdirSync(o,{recursive:!0})}catch(s){f.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${s}`)}f.info(`[ClangdLspManager] clangdPath: ${r}`),f.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),f.info(`[ClangdLspManager] compileCommandsDir: ${o}`);let i=new aa({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,f.info("[ClangdLspManager] clangd initialized");let r=this.initResolve;this.clearInitHandlers(),r?.()}else{let r=t??this.proxy?.consumeStartErrorMessage()??"unknown error";f.error(`[ClangdLspManager] clangd initialization failed: ${r}`),this.isInitialized=!1,this.proxy=null;let o=this.initReject;this.clearInitHandlers(),o?.(new Error(`C++ LSP initialize failed: ${r}`))}};handleLspMessage(e){this.onMessage(e)}dispatchNotification(e){if(!this.proxy)return;let t=e,r=t.method;if(!r){f.warn("[ClangdLspManager] dispatchNotification: missing method");return}let o=t.params;switch(r){case y.DID_OPEN:this.proxy.sendDidOpen(o);break;case y.DID_CHANGE:this.proxy.sendDidChange(o);break;case y.DID_CLOSE:this.proxy.sendDidClose(o);break;default:this.proxy.sendNotification(r,o)}}armInitTimer(e){this.clearInitTimer(),this.initDeadlineTimer=setTimeout(()=>{this.failInit(new Error("C++ LSP initialize timeout"))},e)}clearInitTimer(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null)}clearInitHandlers(){this.clearInitTimer(),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async performDispose(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("ClangdLspManager disposing")),this.proxy){try{await this.proxy.dispose()}catch(t){f.warn(`[ClangdLspManager] proxy dispose error: ${t}`)}this.proxy=null}this.isInitialized=!1,this.initPromise=null}getLogPath(){try{let e=Wo.join(Kt(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=Wo.join(e,"lsp-log",t);return Ol.mkdirSync(r,{recursive:!0}),ue(r)}catch{return"auto"}}};function Jm(n){let e=Mi(n);return f.info(`[SyncGuard] ${e.reason}`),e}var _l=(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))(_l||{}),Km=(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))(Km||{}),an=3,Ml=600*1e3,la=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,xn(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=Dt(t);g.info(`Constructor: findHarmonyProject('${t}') => ${o??"null"}`),this.config.projectPath=o??void 0,this.server=new wI({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=kl(),this.standardProtocolAvailable=this.detectStandardProtocolAvailable(),this.registerTools()}registerTools(){this.registerCheckTool(),b()||this.registerLspFeatureTools()}registerCheckTool(){this.toolRouter.add({name:"check",description:"Perform static syntax analysis on HarmonyOS project source files and return structured diagnostics. Supported languages: ArkTS and C/C++.",inputSchema:Se.object({files:Se.array(Se.string()).min(1).describe("List of source file paths to check, relative to the project root. Supports ArkTS and C/C++ files in the same call.")})},async e=>this.handleCheckCall(e))}registerLspFeatureTools(){if(!this.standardProtocolAvailable){g.info("Skip registering LSP feature tools (hover/definition/declaration/references/implementation, workspaceSymbol, documentSymbol, callHierarchy): standard LSP protocol unavailable (standardIndex/index.js not found). These tools require a DevEco Studio version that ships the standard LSP server entry.");return}let e=Se.object({file:Se.string().describe("Source file path, relative to the project root. Supports .ets (ArkTS) and C/C++ extensions."),line:Se.number().describe("Line number (0-based)"),character:Se.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:Se.object({query:Se.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:Se.object({file:Se.string().describe("Source file path, relative to the project root. Supports .ets and C/C++ extensions.")})},async e=>this.handleDocumentSymbolCall(e))}registerCallHierarchyTool(){this.toolRouter.add({name:"callHierarchy",description:'Query call hierarchy for a function at the given position. Use direction "incoming" to find callers, "outgoing" to find callees. ArkTS supports both directions; C/C++ (clangd) supports incoming only.',inputSchema:Se.object({file:Se.string().describe("Source file path, relative to the project root. Supports .ets and C/C++ extensions."),line:Se.number().describe("Line number (0-based)"),character:Se.number().describe("Character offset in the line (0-based)"),direction:Se.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=cn.join(cn.dirname(e),"standardIndex","index.js"),r=Ym.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=P.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(`
1303
- `)}],isError:!0}:null}let r=e.filter(o=>cn.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(`
1304
- `)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(h=>typeof h=="string"):[];if(t.length===0)return g.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};let r=this.validateContainment(t);if(r)return r;let{etsFiles:o,cppFiles:i,unsupported:s}=SI(t);s.length>0&&g.warn(`Unsupported file types in check request: ${s.join(", ")}`);let a=s.map(h=>`Unsupported file type: ${h} (only .ets and C/C++ source/header files are supported)`),c=[];o.length>0&&this.mergeCheckResult(await this.callArktsCheck(o),a,c),i.length>0&&this.mergeCheckResult(await this.callCppCheck(i),a,c);let l=a.length>0;return{content:[{type:"text",text:[c.join(`
1305
- `),a.join(`
1306
- `)].filter(h=>h.trim().length>0).join(`
1307
- `).trim()||"No diagnostics collected"}],isError:l}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return g.warn(`ArkTS check rejected: project is ${_l[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;if(typeof r!="string"||typeof o!="number"||typeof i!="number")return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};let s=this.validateContainment([r]);return s||this.routeLspRequest(r,e,async()=>{if(r.endsWith(".ets"))return this.arktsCheckTool.handleLspFeature(e,{file:r,line:o,character:i});let a=e;return this.cppLspTool.handleLspFeature(a,{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}/${an})`;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}/${an})`;case 4:return this.cppHasNoCppCode?"ready (no C++ code)":"ready";default:return"unknown"}}async handleDocumentSymbolCall(e){let t=e.file;if(typeof t!="string")return{content:[{type:"text",text:"Missing or invalid parameter: file (string required)."}],isError:!0};let r=this.validateContainment([t]);return r||this.routeLspRequest(t,"documentSymbol",async()=>t.endsWith(".ets")?this.arktsCheckTool.handleDocumentSymbol(t):this.cppLspTool.handleDocumentSymbol(t))}async handleCallHierarchyCall(e){let t=e.file,r=e.line,o=e.character,i=e.direction;if(typeof t!="string"||typeof r!="number"||typeof o!="number")return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};if(i!=="incoming"&&i!=="outgoing")return{content:[{type:"text",text:'Parameter direction must be "incoming" or "outgoing".'}],isError:!0};let s=this.validateContainment([t]);return s||this.routeLspRequest(t,`callHierarchy(${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);if(!t)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};let i=this.validateContainment([t]);return i||this.routeArktsRequest("codeAction",()=>this.arktsCheckTool.handleCodeAction({file:t,line:r,character:o}))}async handleRenameCall(e){let{file:t,line:r,character:o}=this.extractPositionArgs(e),i=e.newName;if(!t||typeof i!="string"||i.trim().length===0)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number), newName (non-empty string)."}],isError:!0};let s=this.validateContainment([t]);return s||this.routeArktsRequest("rename",()=>this.arktsCheckTool.handleRename({file:t,line:r,character:o,newName:i}))}async handleTypeHierarchyCall(e){let{file:t,line:r,character:o}=this.extractPositionArgs(e),i=e.direction;if(!t)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};if(i!=="supertypes"&&i!=="subtypes")return{content:[{type:"text",text:'Parameter direction must be "supertypes" or "subtypes".'}],isError:!0};let s=this.validateContainment([t]);return s||this.routeArktsRequest(`typeHierarchy(${i})`,()=>this.arktsCheckTool.handleTypeHierarchy({file:t,line:r,character:o,direction:i}))}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 ${_l[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>=an?(g.error(`Init retry limit reached (${this.initRetryCount}/${an}), will not auto-retry`),{content:[{type:"text",text:"Project initialization failed multiple times. Please check project configuration and restart the MCP Server."}],isError:!0}):(g.info(`Error check: auto-retrying (${this.initRetryCount}/${an})`),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 ${Km[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):Tn(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>=an?(g.error(`C++ init retry limit reached (${this.cppInitRetryCount}/${an}), will not auto-retry`),{content:[{type:"text",text:"C++ project initialization failed multiple times. Please check project configuration and restart the MCP Server."}],isError:!0}):(g.info(`C++ error check: auto-retrying (${this.cppInitRetryCount}/${an})`),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(`
1308
- `);o&&(e.isError?t.push(o):r.push(o))}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 vI;if(await this.server.connect(e),g.info("devecocli-mcp-server started"),!this.config.debug){let t=ju();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=Dt(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?Dt(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=Dt(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 Tr(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=Jm(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 Rr.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>=Ml?(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 / ${Ml/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=Nn(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 Go({workspaceRoot:e,toolProvider:this.config.toolProvider});try{await this.cppLspManager.start(),this.cppCheckTool=new xr(this.cppLspManager,this.config.toolProvider),this.cppLspTool=new Nr(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 Go.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>=Ml?(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"),Fu(),_u()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function SI(n){let e=[],t=[],r=[];for(let o of n)cn.extname(o).toLowerCase()===".ets"?e.push(o):Tn(o)?t.push(o):r.push(o);return{etsFiles:e,cppFiles:t,unsupported:r}}function Fl(n){return new la(n)}import*as jl from"fs";import*as ln from"path";import{spawn as bI}from"child_process";async function Xm(n){xn(!1);let{serverPath:e,logPath:t,projectPath:r,sdkPath:o,serverMaxSize:i}=await EI(n),s=II(e,t,r,o,i);g.info("ace-server started, bridging stdio (initialize is left to the client)"),DI(s)}async function EI(n){let e=await A.new();b()||e.require({clt:!1});let t;if(n.projectPath)t=ue(ln.resolve(n.projectPath)),g.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let c=ji(process.cwd());t=ue(c??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${c??"null, fallback to cwd"}`)}else t=ue(process.cwd()),g.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=e.sdkPath,o=e.lspServerPath;o||(g.error("ace-server not found in DevEco Studio installation."),process.exit(1));let i=ln.resolve(ln.dirname(o),"standardIndex","index.js"),s=ln.join(Kt(),"lsp-server",String(Date.now()));jl.mkdirSync(s,{recursive:!0});let a=PI(t,r);return g.info(`projectPath=${t}, sdkPath=${r}, serverPath=${i}, logPath=${s}, serverMaxSize=${a}MB`),{projectPath:t,sdkPath:r,serverPath:i,logPath:s,serverMaxSize:a}}function PI(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=CI(n,e),s=zi(i,o);return g.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${i}, override=${o??"none"})`),s}function CI(n,e){try{let t=[];return new Bn(n,e).getAllDependencyMap(t).status==="OK"?t.length:new Rt(n).getAllModuleInfo().length}catch{return 0}}function II(n,e,t,r,o){let i=ln.join(e,"lspLog");jl.mkdirSync(i,{recursive:!0});let s=AI(n,i,t,r,o),a=process.execPath??"node";return g.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),bI(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function AI(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 DI(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 Zm from"fs";import*as Wn from"path";import{spawn as RI}from"child_process";async function Qm(n){xn(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await TI(n),o=Wn.join(t,"compile_commands.json");Zm.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=kI(e,t,r);g.info("clangd started, bridging stdio (initialize is left to the client)"),NI(i)}async function TI(n){let e=await A.new(),t;if(n.projectPath)t=ue(Wn.resolve(n.projectPath)),g.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let s=ji(process.cwd());t=ue(s??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${s??"null, fallback to cwd"}`)}else t=ue(Wn.resolve(process.cwd())),g.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=e.clangdPath;r||(g.error("clangd not found in DevEco Studio SDK. Expected at <deveco>/sdk/default/openharmony/native/llvm/bin/clangd"),process.exit(1));let o=Rn(t),i=Wn.dirname(o);return g.info(`projectPath=${t}, clangdPath=${r}, compileCommandsDir=${i}`),{projectPath:t,clangdPath:r,compileCommandsDir:i}}function kI(n,e,t){let r=xI(e);return g.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),RI(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function xI(n){return[`--compile-commands-dir=${U(n)}`,"--log=info","--pch-storage=memory"]}function NI(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 OI(){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=Fl({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 Hl=new LI("serve").description("Host bundled auxiliary protocol servers");Hl.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await OI()});b()||Hl.command("lsp").description("Start a bundled LSP language server").option("--arkts","Start the ArkTS language server (ace-server)").option("--cpp","Start the C/C++ language server (clangd)").option("--project-path <path>","project root path (used as-is, no search)").option("--auto-detect","When --project-path is not specified, search the current directory and its subdirectories for the project root (no upward search)").action(async n=>{n.arkts&&n.cpp&&(console.error("--arkts and --cpp are mutually exclusive. Specify only one."),process.exit(1)),n.arkts?await Xm({projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await Qm({projectPath:n.projectPath,autoDetect:n.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var eh=Hl;import{Command as _R,InvalidArgumentError as Td}from"commander";import{red as Fa,dim as FR}from"colorette";import*as ne from"fs";import*as St from"path";import SR from"adm-zip";import bR from"proper-lockfile";import cy from"ora";import*as dt from"fs";import*as ei from"path";var dn=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],Gn={"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 Or="1.9.1",Uq=48*1024*1024,th=280,nh=6,rh=100,oh=3,ih=28,$l=10,sh=/API参考|APIReference/i,zo=200,ah=12,ch=4,Ul=8,lh=6,da=700,Bl=250,Wl=400,dh=1320,uh=120,ph=450,fh=250,mh=500,hh=480,gh=80,yh=200,wh=60,vh=200,Sh=40,bh=200,Eh=200,Ph=40,Mr=500,Ch=Object.fromEntries(dn.map((n,e)=>[Gn[n],e])),un=Object.fromEntries(dn.map((n,e)=>[n,e]));import*as qo from"fs";import*as O from"path";import{fileURLToPath as Rh}from"url";import*as pn from"fs";import*as Ih from"path";import{homedir as MI}from"os";var _I="deveco-cli",Gl,zn=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function FI(){let n=process.env.DEVECO_CLI_DATA_DIR;return n!==void 0&&Ri(n)!==""}function Ah(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":Ri(n))||Ih.join(MI(),".local","share",_I);try{return Ti(t)}catch(r){throw new zn(r instanceof Error?r.message:String(r))}}async function Dh(){let n=Ah();await pn.promises.mkdir(n,{recursive:!0});let e;try{e=await pn.promises.realpath(n)}catch(r){throw new zn(`DEVECO_CLI_DATA_DIR is not usable: ${r instanceof Error?r.message:String(r)}`)}if(!(await pn.promises.stat(e)).isDirectory())throw new zn("DEVECO_CLI_DATA_DIR must be a writable directory.");return Gl=e,e}function ua(n){let e=_r();return FI()?[`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 _r(){if(Gl!==void 0)return Gl;let n=Ah();try{if(pn.existsSync(n))return pn.realpathSync(n)}catch{}return n}var jI="docs";function Fr(){return O.join(_r(),jI)}function Z(){return O.join(Fr(),".index")}function pa(){return O.join(Z(),"build.lock")}function Vo(){return O.join(Z(),"build-status.json")}function jr(){return O.join(Z(),"build-meta.json")}function qn(){return O.join(Z(),"search.db")}function Jo(){return O.join(Z(),"sqlite-backend.json")}function Yo(){return O.join(Z(),"jieba-backend.json")}function jt(){return O.join(Z(),".tmp")}function HI(){return O.join(_r(),"logs")}function Hr(){return O.join(HI(),"doc-init.log")}function $I(n,e){let t=e;for(;!t.endsWith(`${O.sep}dist`)&&t!==O.dirname(t);)t=O.dirname(t);return t}function Th(n,e){return O.dirname($I(n,e))}function kh(){let n=Rh(import.meta.url),e=O.dirname(n);return n.includes(`${O.sep}dist${O.sep}`)?Th(n,e):O.join(e,"..","..","..")}function UI(...n){let e=Rh(import.meta.url),t=O.dirname(e);return e.includes(`${O.sep}dist${O.sep}`)?[O.join(Th(e,t),...n)]:[O.join(t,"..","..","..",...n)]}function xh(...n){let e=kh(),t=qo.realpathSync(e);for(let r of UI(...n))try{let o=qo.lstatSync(r);if(o.isSymbolicLink()||!o.isFile())throw new Error(`Unsafe documentation package asset: ${n.join("/")} must be a regular file.`);let i=qo.realpathSync(r);if(!eo(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 fn(){return xh("docs.zip")}function zl(){return xh("index.zip")}function Nh(){return O.join(kh(),"index","data")}import*as Ht from"fs";import*as Vn from"path";var $t=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],fa=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};function Lh(n){return n instanceof fa}var ql=null;function Vl(n){ql=n}function Jl(){if(ql)return ql;let n=Z();if($t.every(o=>Ht.existsSync(Vn.join(n,o))))return n;let t=Nh();if($t.every(o=>Ht.existsSync(Vn.join(t,o))))return t;throw new fa("Lexicon files not found. Install the documentation index first (index.zip).")}function Oh(){Jl()}function Jn(n){let e=Vn.join(Jl(),n);return Ht.readFileSync(e,"utf-8")}function Mh(n,e){return Ht.readFileSync(Vn.join(e,n),"utf-8")}async function _h(n,e=Jl()){await Ht.promises.mkdir(n,{recursive:!0});for(let t of $t){let r=Vn.join(e,t),o=Vn.join(n,t);await Ht.promises.copyFile(r,o)}}import*as ma from"fs";import*as Fh from"path";import*as jh from"yauzl";var Ko=null;function BI(n){return new Promise((e,t)=>{jh.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 WI(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function GI(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",o=>{let i=WI(o);i.endsWith("/")||e.set(i,o),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function zI(){Ko?.zipfile.close(),Ko=null}async function qI(n){let e=Fh.resolve(n),t=await ma.promises.stat(e),r=Ko;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;zI();let o=await BI(e),i=await GI(o);return Ko={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:o,entries:i,readChain:Promise.resolve()},Ko}function VI(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 JI(n,e){let t=n.readChain,r;n.readChain=new Promise(o=>{r=o}),await t;try{return await VI(n.zipfile,e)}finally{r()}}function YI(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 KI(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function Hh(n){let e=fn();if(!e)throw new Error("docs.zip not found");let t=await qI(e),r=KI(t.entries,YI(n));if(!r)throw new Error(`Document not found: ${n}`);return(await JI(t,r)).toString("utf-8")}function Yl(){let n=fn();return n!==null&&ma.existsSync(n)}import*as he from"fs";import*as Ut from"path";import $h from"adm-zip";import*as Xo from"fs";import*as ga from"path";var ha=class extends Error{constructor(e){super(`Unsafe documentation path: ${e}`),this.name="DocPathSafetyError"}};function Zo(n){return n instanceof zn||n instanceof ha||n instanceof Error&&(n.name==="CliDataDirError"||n.name==="DocPathSafetyError")}function Zl(n){return new ha(n)}function XI(){return ht(_r())}function Xl(n,e,t){let r=Di(n,e);if(r===null)throw Zl(`${t} resolves outside the data directory.`);return r}async function Kl(n,e){await Xo.promises.mkdir(n,{recursive:!0});let t=Xl(n,e,"directory");if(!(await Xo.promises.stat(t)).isDirectory())throw Zl("path must be a directory.")}function Qo(n){let e=XI();try{let t=Xl(n,e,"file");if(!Xo.statSync(t).isFile())throw Zl("path must be a regular file.")}catch(t){if(t.code==="ENOENT"){Xl(ga.dirname(n),e,"file parent");return}throw t}}async function $r(n={}){let e=n.mode??"write",t=await Dh();await Kl(Fr(),t),await Kl(Z(),t),e==="write"&&await Kl(jt(),t);for(let r of[qn(),jr(),Vo(),pa(),Yo(),Jo(),...$t.map(o=>ga.join(Z(),o))])Qo(r)}var Ql=["search.db","build-meta.json",...$t],ZI=["corpus.json","corpus-offsets.json","orama.dpack"];async function QI(n){for(let e of ZI)await he.promises.rm(Ut.join(n,e),{force:!0})}async function eA(n){let e=await he.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await he.promises.rm(Ut.join(n,t.name),{recursive:!0,force:!0})}function Uh(n){let t=new $h(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 tA(n){let e=Z();await he.promises.mkdir(e,{recursive:!0});for(let t of Ql){let r=Ut.join(e,t);await he.promises.rm(r,{force:!0}),await he.promises.rename(Ut.join(n,t),r)}await QI(e),await he.promises.rm(jt(),{recursive:!0,force:!0})}function Bh(n){let e=zl();if(!e)return!1;try{let t=Uh(e);return t.indexVersion===Or&&t.docsZipSha256===n&&t.segmentCount>0}catch{return!1}}async function Wh(n){await $r({mode:"write"});let e=zl();if(!e)throw new Error("index.zip not found");let t=Uh(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=jt();await he.promises.rm(r,{recursive:!0,force:!0}),await he.promises.mkdir(r,{recursive:!0});let o=new $h(e);for(let s of Ql){let a=o.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await he.promises.writeFile(Ut.join(r,s),a.getData())}let i=JSON.parse(await he.promises.readFile(Ut.join(r,"build-meta.json"),"utf-8"));if(!he.existsSync(Ut.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await tA(r),await he.promises.mkdir(Fr(),{recursive:!0}),await eA(Fr()),i}async function Gh(){await he.promises.rm(jt(),{recursive:!0,force:!0});let n=Z();for(let e of Ql)await he.promises.rm(Ut.join(n,e),{force:!0})}import{createHash as zh}from"crypto";import*as qh from"fs";async function ya(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 Vh(n){return zh("sha256").update(n,"utf8").digest("hex")}var ed=null;function nA(){let n=Jn("harmonyos-synonyms.json");return JSON.parse(n)}function rA(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 oA(){let n=rA(nA()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function iA(){return ed||(ed=oA()),ed}function td(n,e){let t=iA(),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 Jh(n,e){let t=e?Mh(n,e):Jn(n);return Vh(t)}function wa(n){return Jh("harmonyos-synonyms.json",n)}function va(n){return Jh("harmonyos-terms.txt",n)}var sA={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function Sa(){try{let n=await dt.promises.readFile(Vo(),"utf-8");return JSON.parse(n)}catch{return{...sA}}}async function nd(n){let e=Vo();await dt.promises.mkdir(ei.dirname(e),{recursive:!0}),await dt.promises.writeFile(e,JSON.stringify(n,null,2))}function Yh(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 mn(n){let t={...await Sa(),...n,updatedAt:Date.now()};return await nd(t),t}async function rd(){let n=fn();return n?ya(n):null}async function od(){try{let n=await dt.promises.readFile(jr(),"utf-8");return JSON.parse(n)}catch{return null}}async function ba(n=!1){if(n)return"no-index";let e=await od();if(!e||e.segmentCount===0)return"no-index";let t=await rd();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==Or?"engine-upgraded":e.termsHash!==va()?"terms-changed":e.synonymsHash!==wa()?"synonyms-changed":null}function ti(){if(!Yl()||!dt.existsSync(qn())||!dt.existsSync(jr()))return!1;let n=ei.dirname(qn());if(!$t.every(e=>dt.existsSync(ei.join(n,e))))return!1;try{let e=dt.readFileSync(jr(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function id(n=!1){return n?!0:Yl()?ti()?await ba()!==null:!0:!1}async function Kh(){let n=await Sa();return["installing","indexing","persisting"].includes(n.state)}import*as be from"fs";import*as ty from"os";import*as Le from"path";var Xh=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),sd=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),Zh=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"]),Qh=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 aA=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,cA=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,lA=/[A-Z][a-zA-Z0-9]{2,}/g,dA=/@[A-Z][a-zA-Z0-9]*/g,uA=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,eg=6,pA=/^[a-z][a-z0-9]{2,}$/,fA=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,mA=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,hA=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,gA=/^[A-Z][a-zA-Z0-9]+$/;function yA(n){return`"${n.replace(/"/g,'""')}"`}function ri(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(yA).join(` ${e} `)}function ni(n){return ri(n,"OR")}function tg(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?ni([...t,...r]):`(${ni(t)}) AND (${ni(r)})`}function oi(n){return mA.test(n)}function ng(n){return hA.test(n)&&n.length>=eg}function wA(n){return gA.test(n)}function ii(n){return oi(n)||ng(n)||wA(n)}function vA(n){let e=n.trim().toLowerCase();return Qh.has(e)?!1:Xh.has(e)}function SA(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function Ea(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function ad(n){return[...n.matchAll(aA)].map(e=>e[0])}function cd(n,e=eg){let t=[];for(let r of n.matchAll(cA))r[0].length>=e&&t.push(r[0]);return t}function Ur(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 ut(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function bA(n){let e=new Set;ut(e,n);let t=Ea(n);return t&&ut(e,t),Ur([...e])}function Pa(n){if(oi(n))return bA(n);let e=new Set;return ut(e,n),Ur([...e])}function Ca(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(fA);if(!t)return null;let r=t[1].toLowerCase(),o=t[2].toLowerCase();if(!pA.test(r)||Zh.has(r)||!vA(o))return null;let i=SA(r,o);return{first:r,second:o,camelCase:i,lower:i.toLowerCase()}}function ld(n){let e=Ca(n.trim());return!e||e.second!=="manager"?null:e}function EA(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function rg(n){let e=n.trim(),t=ld(e);if(t&&sd.has(t.first))return!0;if(ng(e)){let r=EA(e);return r!==null&&sd.has(r)}return!1}function dd(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 ud(n){let e=n.trim();if(ii(e))return Pa(e);let t=new Set;for(let r of ad(n)){ut(t,r);let o=Ea(r);o&&ut(t,o)}for(let r of cd(n))ut(t,r);for(let r of n.matchAll(dA))t.add(r[0]);for(let r of n.matchAll(uA))t.add(r[0]);for(let r of n.matchAll(lA))r[0].length>=4&&t.add(r[0]);return Ur([...t])}function og(n){let e=n.trim();if(ii(e))return Pa(e);let t=new Set,r=Ca(e);r&&ut(t,r.camelCase);for(let o of ud(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 Ur([...t])}function ig(n){return ii(n)}var Y={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 sg(n){return Y.pureApiSymbol.test(n.trim())}function si(n){let e=n.trim();return Y.stageModelExact.test(e)||Y.stageModelEnglishExact.test(e)}function ag(n){let e=[];return si(n.trim())&&e.push("Stage\u6A21\u578B","Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0"),Y.declarePermissionTokens.test(n)&&e.push("\u58F0\u660E\u6743\u9650"),Y.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 cg(n){return si(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var PA=[{matches:n=>Y.uiAbilityLifecycleBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:n=>si(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!si(n)&&Y.stageModel.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:n=>Y.entryAbilityPage.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:n=>Y.declarePermissionBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:n=>Y.stateDecoratorBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:n=>Y.stateManagement.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:n=>Y.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=>Y.dialogPopupBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function CA(n,e){for(let{catalog:t,multiplier:r}of e){let o=un[t];n.set(o,(n.get(o)??1)*r)}}function lg(n,e){for(let t of PA)t.matches(n)&&CA(e,t.weights)}function dg(n,e){if(e!==void 0)return!1;let t=n.trim();return oi(t)||Y.pureApiSymbol.test(t)||rg(t)}function ug(n){let e=n.trim();if(oi(e)||Y.pureApiSymbol.test(e))return"harmonyos-references";if(si(e)||Y.uiAbilityLifecycleCatalog.test(e)||Y.stateDecoratorCatalog.test(e)||Y.stateManagement.test(e)||Y.declarePermissionCatalog.test(e)||Y.stageModelEntryPage.test(e)||Y.routerRoute.test(e)||Y.dialogPopupExact.test(e))return"harmonyos-guides"}import*as Br from"fs";import*as fg from"path";var Ia=null,pd=null,fd=null;function IA(){return Br.existsSync(Yo())}function AA(n){let e=Yo(),t={backend:"jieba-wasm",reason:"native-jieba-load-failed",message:n,createdAt:new Date().toISOString()};Br.mkdirSync(fg.dirname(e),{recursive:!0}),Qo(e),Br.writeFileSync(e,JSON.stringify(t,null,2))}function DA(){if(Ia)return Ia;let n=Jn("harmonyos-stopwords.txt");return Ia=new Set(n.split(`
1309
- `).map(e=>e.trim()).filter(Boolean)),Ia}function RA(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 mg(n){let e=DA(),t=[];for(let r of RA(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 hg(n){let{dict:e}=await import("@node-rs/jieba/dict.js"),t=n.withDict(e),r=Jn("harmonyos-terms.txt");return t.loadDict(Buffer.from(r,"utf-8")),t}async function TA(){let{Jieba:n}=await import("@node-rs/jieba");return hg(n)}async function pg(){let{Jieba:n}=await import("@node-rs/jieba-wasm32-wasi");return hg(n)}async function kA(){let n=await import("jieba-wasm"),e=Jn("harmonyos-terms.txt");return n.with_dict(e),{cut:n.cut,cutForSearch:n.cut_for_search}}async function xA(){if(b())return kA();if(IA())return pg();try{let e=await TA();return m("doc-index: using @node-rs/jieba backend"),e}catch(e){let t=e instanceof Error?e.message:String(e);AA(t),m(`doc-index: @node-rs/jieba unavailable (${t}); falling back to wasm32-wasi`)}let n=await pg();return m("doc-index: using @node-rs/jieba-wasm32-wasi backend"),n}async function hn(){return pd||(fd||(fd=xA().then(n=>(pd=n,n))),fd)}async function NA(n){let e=await hn();return mg(e.cutForSearch(n,!0))}async function gg(n){let e=await hn();return mg(e.cut(n,!0))}async function Aa(n,e){let t=n.trim();if(!t||e<=0)return"";let r=(await NA(t)).join(" ");return r.length<=e?r:r.slice(0,e)}async function LA(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 Da(n){let e=!!n.sectionTitle.trim(),t=n.titleTokens.trim(),r=e?hh:dh,o=e?yh:ph,i=e?await LA(n.apiSymbols,o):await Aa(n.apiSymbols.join(" "),o),a=(await Promise.all([Aa(t,e?gh:uh),Promise.resolve(i),Aa(n.headingsText,e?wh:fh),Aa(n.bodySample,e?vh:mh)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}function OA(n){return n.join(" ").replace(/\s+/g," ").trim().slice(0,zo)}function md(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>=ah))break}return r}function MA(n){return n.length>=2&&n.length<=ch}function _A(n,e){let t=td(n,Ul),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=md(o,i);return{rawQuery:n,expandedQuery:t,tokens:s,preferAnd:!1,ftsMatch:tg(o,i)}}function FA(n,e){let t=md(Pa(e),[]);return{rawQuery:n,expandedQuery:n,tokens:t,preferAnd:!1,ftsMatch:ni(t)}}async function yg(n){let e=OA(n),t=e.trim(),r=cg(t);if(r)return{rawQuery:e,expandedQuery:r.expandedQuery,tokens:r.tokens,preferAnd:!1};let o=Ca(t);if(o)return _A(e,o);if(ii(t))return FA(e,t);let i=ag(e),s=[...ud(e),...i],c=ig(t)?e:td(e,Ul),l=await gg(c),d=md(s,l);return{rawQuery:e,expandedQuery:c,tokens:d,preferAnd:i.length===0&&MA(d)}}var wg=["harmonyos-releases","harmonyos-roadmap"],jA=new Set(wg.map(n=>un[n])),HA=wg.map(n=>`${Gn[n]}/`);function $A(n){return jA.has(n)}function UA(n){return HA.some(e=>n.startsWith(e))}function vg(n){let e=[],t=[];for(let r of n)$A(r.catalog_id)?t.push(r):e.push(r);return[...e,...t]}function Sg(n){let e=[],t=[];for(let r of n)UA(r.documentId)?t.push(r):e.push(r);return[...e,...t]}var BA=[{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 ai(n,e,t){let r=un[e];n.set(r,(n.get(r)??1)*t)}function WA(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)){ai(e,"harmonyos-guides",1.45),ai(e,"harmonyos-references",1.35);return}(o||i)&&ai(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(t)&&ai(e,"harmonyos-references",1.75)}function bg(n){let e=new Map,t=n.trim();if(!t)return e;let r=sg(t);WA(t,e),lg(t,e);for(let o of BA)o.pattern.test(t)&&(o.skipForPureApiSymbol&&r||ai(e,o.catalog,o.multiplier));return e}function Eg(n){return ug(n)}import*as Gr from"fs";import*as kg from"path";var GA=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function Pg(n,e){let t=-1;for(let r of GA){let o=n.lastIndexOf(r);o>t&&(t=o)}return t>=e?t:-1}function Cg(n,e){let t=n.trim();if(t.length<=e)return{text:t,excerptTruncated:!1};let r=t.slice(0,e),o=Pg(r,e-20),i=o>=0?o:e;return{text:t.slice(0,i).trimEnd(),excerptTruncated:!0}}function Ig(n,e,t={}){let{maxLen:r=Eh,contextChars:o=Ph,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(De=>De.trim()).filter(Boolean),c=0;for(let De of a){let Pe=s.toLowerCase().indexOf(De.toLowerCase());if(Pe>=0){c=Pe;break}}let l=Math.max(0,c-o),d=Math.min(s.length,l+r),h=s.slice(l,d),w=Pg(h,r-25);w>=0&&(d=l+w);let S=s.slice(l,d).trim(),k=l>0?"...":"",re=d<s.length||i?"...":"";return`${k}${S}${re}`}var zA=`
1302
+ `).trim();return!i&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:i}}async checkFile(e){let t=xn(e),r=await ln.promises.readFile(e,"utf8"),o=Ui(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=Or.resolve(Or.isAbsolute(i)?i:Or.join(r,i));if(!ln.existsSync(s)){t.push(`File does not exist: ${i}`);continue}if(!ln.statSync(s).isFile()){t.push(`Not a regular file: ${i}`);continue}if(!kn(s)){t.push(`Not a supported C/C++ file: ${i}`);continue}try{o.push(ln.realpathSync(s))}catch{o.push(s)}}return o}};function mI(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 hI(n){return new Promise(e=>setTimeout(e,n))}import*as _r from"fs";import*as aa from"path";var Mr=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 Nr();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 sa(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 Nr();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 sa("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return Nr();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 sa("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=xn(e),o=await _r.promises.readFile(e,"utf8"),i=Ui(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=aa.isAbsolute(e)?e:aa.join(this.manager.projectRoot,e);return!_r.existsSync(t)||!_r.statSync(t).isFile()||!kn(t)?null:t}};import{spawn as gI}from"child_process";import*as la from"fs";import*as Jm from"path";var yI=30*1e3,wI=30*1e3,ca=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new on;diagnosticWaiters=new Map;lastStartErrorMessage=null;onMessage=()=>{};disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}async start(e){let t=!1;try{f.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),f.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),f.info(`[ClangdLspProxy] compileCommandsDir: ${this.config.compileCommandsDir}`),this.ensureLogDir(),this.clangdProcess=this.spawnClangd();let r={serverPath:"",logPath:this.config.logPath,indexingDataLocation:this.config.logPath,cwd:this.config.workspaceRoot,nodePath:this.config.nodePath};this.client=new rn(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,qe),f.info("[ClangdLspProxy] initialize response received"),this.sendNotification(y.INITIALIZED,{}),t=!0}catch(r){this.lastStartErrorMessage=r instanceof Error?r.message:String(r),f.error(`[ClangdLspProxy] initialization failed: ${this.lastStartErrorMessage}`),await this.dispose()}e?.(t)}async hover(e){return this.sendLspRequest(y.HOVER,e)}async definition(e){return this.sendLspRequest(y.DEFINITION,e)}async declaration(e){return this.sendLspRequest(y.DECLARATION,e)}async references(e){return this.sendLspRequest(y.REFERENCES,e)}async implementation(e){return this.sendLspRequest(y.IMPLEMENTATION,e)}async documentSymbol(e){return this.sendLspRequest(y.DOCUMENT_SYMBOL,e)}async workspaceSymbol(e){return this.sendLspRequest(y.WORKSPACE_SYMBOL,e)}async prepareCallHierarchy(e){return this.sendLspRequest(y.PREPARE_CALL_HIERARCHY,e)}async incomingCalls(e){return this.sendLspRequest(y.INCOMING_CALLS,e)}async sendFeatureRequest(e,t){return this.sendLspRequest(e,t)}sendDidOpen(e){this.sendNotification(y.DID_OPEN,e)}sendDidChange(e){this.sendNotification(y.DID_CHANGE,e)}sendDidClose(e){this.sendNotification(y.DID_CLOSE,e)}sendNotification(e,t){if(!this.client){f.warn("[ClangdLspProxy] sendNotification before ready, dropped");return}this.client.sendNotification(e,t)}registerDiagnosticCallback(e){let t=this.normalizeClangdUri(e);if(this.diagnosticWaiters.has(t)){f.warn(`[ClangdLspProxy] overwrite existing diagnostic waiter for ${t}`);let r=this.diagnosticWaiters.get(t);clearTimeout(r.timer),this.diagnosticWaiters.delete(t)}return new Promise((r,o)=>{let i=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&o(new Error(`Wait for clangd diagnostics timeout, uri: ${t}`))},wI);this.diagnosticWaiters.set(t,{resolve:r,reject:o,timer:i})})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){this.requestCallbacks.rejectAll(new Error("ClangdLspProxy disposing"));for(let[,e]of this.diagnosticWaiters)clearTimeout(e.timer),e.reject(new Error("ClangdLspProxy disposing"));if(this.diagnosticWaiters.clear(),this.client&&this.clangdProcess)try{await this.sendLspRequest(y.SHUTDOWN,null,3e3).catch(e=>{f.warn(`[ClangdLspProxy] shutdown request failed: ${e}`)}),this.sendNotification(y.EXIT,null),await this.client.waitForExitOrTimeout(300)}catch(e){f.warn(`[ClangdLspProxy] dispose error: ${e}`)}if(this.clangdProcess){try{this.clangdProcess.exitCode===null&&this.clangdProcess.signalCode===null&&this.clangdProcess.kill()}catch{}this.clangdProcess=null}this.client=null}spawnClangd(){let e=[`--compile-commands-dir=${U(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];f.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=gI(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=rr(this.config.workspaceRoot),t=st(e),r=Jm.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"0.3.0-TD.2-alpha2"},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=yI){if(!this.client)return Promise.reject(new Error("[ClangdLspProxy] client not ready"));let o=this.nextRequestId++,i=this.requestCallbacks.registerPending(o,e,r);return this.client.sendRequest(e,t,o),i}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let o=r instanceof Error?r.message:String(r);f.error(`[ClangdLspProxy] JSON parse error: ${o}, raw: ${e.slice(0,200)}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotification(t):f.warn(`[ClangdLspProxy] unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t==null||typeof t!="string"&&typeof t!="number")return;let r=t;if(e.error!==void 0){let o=e.error;f.warn(`[ClangdLspProxy] LSP error id=${r}: code=${o.code??-1} message=${o.message??"unknown"}`),this.requestCallbacks.rejectPending(r,new Error(`LSP error ${o.code??-1}: ${o.message??"unknown"}`))}else this.requestCallbacks.resolvePending(r,e.result)}handleNotification(e){let t=e.method;if(t)switch(t){case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.onMessage({jsonrpc:R,method:y.PROGRESS,params:e.params});break;case y.WINDOW_SHOW_MESSAGE:f.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:f.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:R,method:t,params:e.params})}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=this.normalizeClangdUri(e.uri),r=this.diagnosticWaiters.get(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.diagnosticWaiters.get(s),r&&this.diagnosticWaiters.delete(s)}else r&&this.diagnosticWaiters.delete(t);if(!r)return;clearTimeout(r.timer);let o=Array.isArray(e.diagnostics)?e.diagnostics:[],i=o.length;f.info(`[ClangdLspProxy] diagnostics received uri=${t} count=${i}`),r.resolve(o)}handleError(e){for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear(),this.requestCallbacks.rejectAll(e),this.onMessage({jsonrpc:R,method:y.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{la.existsSync(this.config.logPath)||la.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)),st(r)}}catch{}return e}};import*as zo from"path";import*as $t from"fs";var qo=class{config;proxy=null;isInitialized=!1;onMessage=()=>{};disposeOnce=null;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;resolvedRoot="";constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}get ready(){return this.isInitialized&&this.proxy!==null}get projectRoot(){return this.resolvedRoot}async start(){if(!this.isInitialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doStart();try{await this.initPromise}catch(e){throw this.initPromise=null,e}}}sendNotification(e){if(!this.proxy){f.warn("[ClangdLspManager] sendNotification before LSP ready, dropped");return}this.dispatchNotification(e)}async sendFeatureRequest(e,t){if(!this.proxy)throw new Error("[ClangdLspManager] LSP not ready");return this.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())return;let e=tr(this.projectRoot);if(!$t.existsSync(e))return;let t=$t.readFileSync(e,"utf8");if(!t.includes(qi))return;let r=t.replaceAll(qi,this.config.toolProvider.sdkPath);$t.writeFileSync(e,r,"utf8"),f.info(`[CppCheck] Patched SDK path in compile_commands.json: ${qi} -> ${this.config.toolProvider.sdkPath}`)}static async handleSyncCppProject(e,t){if(f.info("[ClangdLspManager] Received cpp/syncProject"),!e)return f.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or devecoPath is empty"),{status:"failed",reason:"workspaceRoot or devecoPath is empty"};if(Ln(e).length===0)return f.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let o=await Mi(e,async()=>{try{return await Zu(e,t),f.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(i){let s=i instanceof Error?i.message:String(i);return f.error(`[ClangdLspManager] compileNative failed: ${s}`),{status:"failed",reason:s}}});return o.acquired?o.result:(f.info("[ClangdLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}doStart(){return new Promise((e,t)=>{this.initResolve=e,this.initReject=t,this.armInitTimer(qe);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=Tt(this.config.workspaceRoot);this.resolvedRoot=e?pe(e):pe(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";f.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let o=zo.dirname(tr(this.resolvedRoot));try{$t.mkdirSync(o,{recursive:!0})}catch(s){f.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${s}`)}f.info(`[ClangdLspManager] clangdPath: ${r}`),f.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),f.info(`[ClangdLspManager] compileCommandsDir: ${o}`);let i=new ca({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,f.info("[ClangdLspManager] clangd initialized");let r=this.initResolve;this.clearInitHandlers(),r?.()}else{let r=t??this.proxy?.consumeStartErrorMessage()??"unknown error";f.error(`[ClangdLspManager] clangd initialization failed: ${r}`),this.isInitialized=!1,this.proxy=null;let o=this.initReject;this.clearInitHandlers(),o?.(new Error(`C++ LSP initialize failed: ${r}`))}};handleLspMessage(e){this.onMessage(e)}dispatchNotification(e){if(!this.proxy)return;let t=e,r=t.method;if(!r){f.warn("[ClangdLspManager] dispatchNotification: missing method");return}let o=t.params;switch(r){case y.DID_OPEN:this.proxy.sendDidOpen(o);break;case y.DID_CHANGE:this.proxy.sendDidChange(o);break;case y.DID_CLOSE:this.proxy.sendDidClose(o);break;default:this.proxy.sendNotification(r,o)}}armInitTimer(e){this.clearInitTimer(),this.initDeadlineTimer=setTimeout(()=>{this.failInit(new Error("C++ LSP initialize timeout"))},e)}clearInitTimer(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null)}clearInitHandlers(){this.clearInitTimer(),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async performDispose(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("ClangdLspManager disposing")),this.proxy){try{await this.proxy.dispose()}catch(t){f.warn(`[ClangdLspManager] proxy dispose error: ${t}`)}this.proxy=null}this.isInitialized=!1,this.initPromise=null}getLogPath(){try{let e=zo.join(Qt(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=zo.join(e,"lsp-log",t);return $t.mkdirSync(r,{recursive:!0}),pe(r)}catch{return"auto"}}};function Ym(n){let e=Fi(n);return f.info(`[SyncGuard] ${e.reason}`),e}var Fl=(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))(Fl||{}),Xm=(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))(Xm||{}),bt=3,Ml=600*1e3,_l=100,da=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,Nn(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=Tt(t);g.info(`Constructor: findHarmonyProject('${t}') => ${o??"null"}`),this.config.projectPath=o??void 0,this.server=new vI({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=xl(),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=dn.join(dn.dirname(e),"standardIndex","index.js"),r=Km.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=D.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(`
1303
+ `)}],isError:!0}:null}let r=e.filter(o=>dn.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(`
1304
+ `)}],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>_l)return g.warn(`check tool called with ${t.length} files (max: ${_l})`),{content:[{type:"text",text:`Too many files: ${t.length}. Maximum allowed is ${_l}.`}],isError:!0};let{etsFiles:r,cppFiles:o,unsupported:i}=bI(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(`
1305
+ `),s.join(`
1306
+ `)].filter(d=>d.trim().length>0).join(`
1307
+ `).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 ${Fl[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}/${bt})`;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}/${bt})`;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 ${Fl[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>=bt?(g.error(`Init retry limit reached (${this.initRetryCount}/${bt}), will not auto-retry`),{content:[{type:"text",text:`Project initialization failed repeatedly (auto-retry exhausted: ${this.initRetryCount}/${bt}). 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}/${bt})`),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 ${Xm[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):kn(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>=bt?(g.error(`C++ init retry limit reached (${this.cppInitRetryCount}/${bt}), will not auto-retry`),{content:[{type:"text",text:`C++ project initialization failed repeatedly (auto-retry exhausted: ${this.cppInitRetryCount}/${bt}). 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}/${bt})`),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(`
1308
+ `);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 SI;if(await this.server.connect(e),g.info("devecocli-mcp-server started"),!this.config.debug){let t=Hu();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=Tt(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?Tt(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=Tt(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 xr(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=Ym(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 kr.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>=Ml?(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 / ${Ml/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=Ln(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 qo({workspaceRoot:e,toolProvider:this.config.toolProvider});try{await this.cppLspManager.start(),this.cppCheckTool=new Lr(this.cppLspManager,this.config.toolProvider),this.cppLspTool=new Mr(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 qo.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>=Ml?(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"),ju(),Fu()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function bI(n){let e=[],t=[],r=[];for(let o of n)dn.extname(o).toLowerCase()===".ets"?e.push(o):kn(o)?t.push(o):r.push(o);return{etsFiles:e,cppFiles:t,unsupported:r}}function jl(n){return new da(n)}import*as Hl from"fs";import*as un from"path";import{spawn as EI}from"child_process";async function Zm(n){Nn(!1);let{serverPath:e,logPath:t,projectPath:r,serverMaxSize:o}=await PI(n),i=AI(e,t,r,n.toolProvider,o);g.info("ace-server started, bridging stdio (initialize is left to the client)"),RI(i)}async function PI(n){b()||n.toolProvider.require({clt:!1});let e;if(n.projectPath)e=pe(un.resolve(n.projectPath)),g.info(`projectPath=specified ('${e}'), no search`);else if(n.autoDetect){let a=$i(process.cwd());e=pe(a??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${a??"null, fallback to cwd"}`)}else e=pe(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=un.resolve(un.dirname(r),"standardIndex","index.js"),i=un.join(Qt(),"lsp-server",String(Date.now()));Hl.mkdirSync(i,{recursive:!0});let s=CI(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 CI(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=II(n,e),s=Vi(i,o);return g.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${i}, override=${o??"none"})`),s}function II(n,e){try{let t=[];return new Wn(n,e).getAllDependencyMap(t).status==="OK"?t.length:new kt(n).getAllModuleInfo().length}catch{return 0}}function AI(n,e,t,r,o){let i=un.join(e,"lspLog");Hl.mkdirSync(i,{recursive:!0});let s=DI(n,i,t,r.sdkPath,o),a=r.nodePath;return g.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),EI(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function DI(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 RI(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 Qm from"fs";import*as Gn from"path";import{spawn as TI}from"child_process";async function eh(n){Nn(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await kI(n),o=Gn.join(t,"compile_commands.json");Qm.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=xI(e,t,r);g.info("clangd started, bridging stdio (initialize is left to the client)"),LI(i)}async function kI(n){let e;if(n.projectPath)e=pe(Gn.resolve(n.projectPath)),g.info(`projectPath=specified ('${e}'), no search`);else if(n.autoDetect){let i=$i(process.cwd());e=pe(i??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${i??"null, fallback to cwd"}`)}else e=pe(Gn.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=tr(e),o=Gn.dirname(r);return g.info(`projectPath=${e}, clangdPath=${t}, compileCommandsDir=${o}`),{projectPath:e,clangdPath:t,compileCommandsDir:o}}function xI(n,e,t){let r=NI(e);return g.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),TI(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function NI(n){return[`--compile-commands-dir=${U(n)}`,"--log=info","--pch-storage=memory"]}function LI(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 MI(){let n=process.env.PROJECT_PATH||"",e=process.env.NODE_MAX_OLD_SPACE_SIZE,t=process.env.DEBUG==="true"||process.env.DEBUG==="1",r=await I.new();b()||r.require({clt:!1});let i=jl({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 $l=new OI("serve").description("Host bundled auxiliary protocol servers");$l.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await MI()});$l.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 I.new();n.arkts?await Zm({toolProvider:e,projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await eh({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 th=$l;import{Command as FR,InvalidArgumentError as kd}from"commander";import{red as ja,dim as jR}from"colorette";import*as ne from"fs";import*as Et from"path";import bR from"adm-zip";import ER from"proper-lockfile";import ly from"ora";import*as ut from"fs";import*as ni from"path";var pn=["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 Fr="1.9.1",Nq=48*1024*1024,nh=280,rh=6,oh=100,ih=3,sh=28,Ul=10,ah=/API参考|APIReference/i,Vo=200,ch=12,lh=4,Bl=8,dh=6,ua=700,Wl=250,Gl=400,uh=1320,ph=120,fh=450,mh=250,hh=500,gh=480,yh=80,wh=200,vh=60,Sh=200,bh=40,Eh=200,Ph=200,Ch=40,jr=500,Ih=Object.fromEntries(pn.map((n,e)=>[zn[n],e])),fn=Object.fromEntries(pn.map((n,e)=>[n,e]));import*as Jo from"fs";import*as O from"path";import{fileURLToPath as Th}from"url";import*as mn from"fs";import*as Ah from"path";import{homedir as _I}from"os";var FI="deveco-cli",zl,qn=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function jI(){let n=process.env.DEVECO_CLI_DATA_DIR;return n!==void 0&&ki(n)!==""}function Dh(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":ki(n))||Ah.join(_I(),".local","share",FI);try{return xi(t)}catch(r){throw new qn(r instanceof Error?r.message:String(r))}}async function Rh(){let n=Dh();await mn.promises.mkdir(n,{recursive:!0});let e;try{e=await mn.promises.realpath(n)}catch(r){throw new qn(`DEVECO_CLI_DATA_DIR is not usable: ${r instanceof Error?r.message:String(r)}`)}if(!(await mn.promises.stat(e)).isDirectory())throw new qn("DEVECO_CLI_DATA_DIR must be a writable directory.");return zl=e,e}function pa(n){let e=Hr();return jI()?[`Data directory (DEVECO_CLI_DATA_DIR): ${e}`,"If you changed this in System Environment Variables, open a new terminal and retry.",`Log file: ${n}`]:[`Data directory (default): ${e}`,"To use a custom location, set DEVECO_CLI_DATA_DIR and open a new terminal.",`Log file: ${n}`]}function Hr(){if(zl!==void 0)return zl;let n=Dh();try{if(mn.existsSync(n))return mn.realpathSync(n)}catch{}return n}var HI="docs";function $r(){return O.join(Hr(),HI)}function Z(){return O.join($r(),".index")}function fa(){return O.join(Z(),"build.lock")}function Yo(){return O.join(Z(),"build-status.json")}function Ur(){return O.join(Z(),"build-meta.json")}function Vn(){return O.join(Z(),"search.db")}function Ko(){return O.join(Z(),"sqlite-backend.json")}function Xo(){return O.join(Z(),"jieba-backend.json")}function Ut(){return O.join(Z(),".tmp")}function $I(){return O.join(Hr(),"logs")}function Br(){return O.join($I(),"doc-init.log")}function UI(n,e){let t=e;for(;!t.endsWith(`${O.sep}dist`)&&t!==O.dirname(t);)t=O.dirname(t);return t}function kh(n,e){return O.dirname(UI(n,e))}function xh(){let n=Th(import.meta.url),e=O.dirname(n);return n.includes(`${O.sep}dist${O.sep}`)?kh(n,e):O.join(e,"..","..","..")}function BI(...n){let e=Th(import.meta.url),t=O.dirname(e);return e.includes(`${O.sep}dist${O.sep}`)?[O.join(kh(e,t),...n)]:[O.join(t,"..","..","..",...n)]}function Nh(...n){let e=xh(),t=Jo.realpathSync(e);for(let r of BI(...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(!ro(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 hn(){return Nh("docs.zip")}function ql(){return Nh("index.zip")}function Lh(){return O.join(xh(),"index","data")}import*as Bt from"fs";import*as Jn from"path";var Wt=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],ma=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};function Oh(n){return n instanceof ma}var Vl=null;function Jl(n){Vl=n}function Yl(){if(Vl)return Vl;let n=Z();if(Wt.every(o=>Bt.existsSync(Jn.join(n,o))))return n;let t=Lh();if(Wt.every(o=>Bt.existsSync(Jn.join(t,o))))return t;throw new ma("Lexicon files not found. Install the documentation index first (index.zip).")}function Mh(){Yl()}function Yn(n){let e=Jn.join(Yl(),n);return Bt.readFileSync(e,"utf-8")}function _h(n,e){return Bt.readFileSync(Jn.join(e,n),"utf-8")}async function Fh(n,e=Yl()){await Bt.promises.mkdir(n,{recursive:!0});for(let t of Wt){let r=Jn.join(e,t),o=Jn.join(n,t);await Bt.promises.copyFile(r,o)}}import*as ha from"fs";import*as jh from"path";import*as Hh from"yauzl";var Zo=null;function WI(n){return new Promise((e,t)=>{Hh.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 GI(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=GI(o);i.endsWith("/")||e.set(i,o),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function qI(){Zo?.zipfile.close(),Zo=null}async function VI(n){let e=jh.resolve(n),t=await ha.promises.stat(e),r=Zo;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;qI();let o=await WI(e),i=await zI(o);return Zo={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:o,entries:i,readChain:Promise.resolve()},Zo}function JI(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 YI(n,e){let t=n.readChain,r;n.readChain=new Promise(o=>{r=o}),await t;try{return await JI(n.zipfile,e)}finally{r()}}function KI(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 XI(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function $h(n){let e=hn();if(!e)throw new Error("docs.zip not found");let t=await VI(e),r=XI(t.entries,KI(n));if(!r)throw new Error(`Document not found: ${n}`);return(await YI(t,r)).toString("utf-8")}function Kl(){let n=hn();return n!==null&&ha.existsSync(n)}import*as he from"fs";import*as Gt from"path";import Uh from"adm-zip";import*as Qo from"fs";import*as ya from"path";var ga=class extends Error{constructor(e){super(`Unsafe documentation path: ${e}`),this.name="DocPathSafetyError"}};function ei(n){return n instanceof qn||n instanceof ga||n instanceof Error&&(n.name==="CliDataDirError"||n.name==="DocPathSafetyError")}function Ql(n){return new ga(n)}function ZI(){return gt(Hr())}function Zl(n,e,t){let r=Ti(n,e);if(r===null)throw Ql(`${t} resolves outside the data directory.`);return r}async function Xl(n,e){await Qo.promises.mkdir(n,{recursive:!0});let t=Zl(n,e,"directory");if(!(await Qo.promises.stat(t)).isDirectory())throw Ql("path must be a directory.")}function ti(n){let e=ZI();try{let t=Zl(n,e,"file");if(!Qo.statSync(t).isFile())throw Ql("path must be a regular file.")}catch(t){if(t.code==="ENOENT"){Zl(ya.dirname(n),e,"file parent");return}throw t}}async function Wr(n={}){let e=n.mode??"write",t=await Rh();await Xl($r(),t),await Xl(Z(),t),e==="write"&&await Xl(Ut(),t);for(let r of[Vn(),Ur(),Yo(),fa(),Xo(),Ko(),...Wt.map(o=>ya.join(Z(),o))])ti(r)}var ed=["search.db","build-meta.json",...Wt],QI=["corpus.json","corpus-offsets.json","orama.dpack"];async function eA(n){for(let e of QI)await he.promises.rm(Gt.join(n,e),{force:!0})}async function tA(n){let e=await he.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await he.promises.rm(Gt.join(n,t.name),{recursive:!0,force:!0})}function Bh(n){let t=new Uh(n).getEntry("build-meta.json");if(!t)throw new Error("index.zip is missing build-meta.json");return JSON.parse(t.getData().toString("utf-8"))}async function nA(n){let e=Z();await he.promises.mkdir(e,{recursive:!0});for(let t of ed){let r=Gt.join(e,t);await he.promises.rm(r,{force:!0}),await he.promises.rename(Gt.join(n,t),r)}await eA(e),await he.promises.rm(Ut(),{recursive:!0,force:!0})}function Wh(n){let e=ql();if(!e)return!1;try{let t=Bh(e);return t.indexVersion===Fr&&t.docsZipSha256===n&&t.segmentCount>0}catch{return!1}}async function Gh(n){await Wr({mode:"write"});let e=ql();if(!e)throw new Error("index.zip not found");let t=Bh(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=Ut();await he.promises.rm(r,{recursive:!0,force:!0}),await he.promises.mkdir(r,{recursive:!0});let o=new Uh(e);for(let s of ed){let a=o.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await he.promises.writeFile(Gt.join(r,s),a.getData())}let i=JSON.parse(await he.promises.readFile(Gt.join(r,"build-meta.json"),"utf-8"));if(!he.existsSync(Gt.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await nA(r),await he.promises.mkdir($r(),{recursive:!0}),await tA($r()),i}async function zh(){await he.promises.rm(Ut(),{recursive:!0,force:!0});let n=Z();for(let e of ed)await he.promises.rm(Gt.join(n,e),{force:!0})}import{createHash as qh}from"crypto";import*as Vh from"fs";async function wa(n){return new Promise((e,t)=>{let r=qh("sha256"),o=Vh.createReadStream(n);o.on("data",i=>r.update(i)),o.on("error",t),o.on("end",()=>e(r.digest("hex")))})}function Jh(n){return qh("sha256").update(n,"utf8").digest("hex")}var td=null;function rA(){let n=Yn("harmonyos-synonyms.json");return JSON.parse(n)}function oA(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 iA(){let n=oA(rA()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function sA(){return td||(td=iA()),td}function nd(n,e){let t=sA(),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 Yh(n,e){let t=e?_h(n,e):Yn(n);return Jh(t)}function va(n){return Yh("harmonyos-synonyms.json",n)}function Sa(n){return Yh("harmonyos-terms.txt",n)}var aA={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function ba(){try{let n=await ut.promises.readFile(Yo(),"utf-8");return JSON.parse(n)}catch{return{...aA}}}async function rd(n){let e=Yo();await ut.promises.mkdir(ni.dirname(e),{recursive:!0}),await ut.promises.writeFile(e,JSON.stringify(n,null,2))}function Kh(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 gn(n){let t={...await ba(),...n,updatedAt:Date.now()};return await rd(t),t}async function od(){let n=hn();return n?wa(n):null}async function id(){try{let n=await ut.promises.readFile(Ur(),"utf-8");return JSON.parse(n)}catch{return null}}async function Ea(n=!1){if(n)return"no-index";let e=await id();if(!e||e.segmentCount===0)return"no-index";let t=await od();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==Fr?"engine-upgraded":e.termsHash!==Sa()?"terms-changed":e.synonymsHash!==va()?"synonyms-changed":null}function ri(){if(!Kl()||!ut.existsSync(Vn())||!ut.existsSync(Ur()))return!1;let n=ni.dirname(Vn());if(!Wt.every(e=>ut.existsSync(ni.join(n,e))))return!1;try{let e=ut.readFileSync(Ur(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function sd(n=!1){return n?!0:Kl()?ri()?await Ea()!==null:!0:!1}async function Xh(){let n=await ba();return["installing","indexing","persisting"].includes(n.state)}import*as be from"fs";import*as ny from"os";import*as Me from"path";var Zh=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),ad=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),Qh=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"]),eg=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 cA=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,lA=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,dA=/[A-Z][a-zA-Z0-9]{2,}/g,uA=/@[A-Z][a-zA-Z0-9]*/g,pA=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,tg=6,fA=/^[a-z][a-z0-9]{2,}$/,mA=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,hA=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,gA=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,yA=/^[A-Z][a-zA-Z0-9]+$/;function wA(n){return`"${n.replace(/"/g,'""')}"`}function ii(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(wA).join(` ${e} `)}function oi(n){return ii(n,"OR")}function ng(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?oi([...t,...r]):`(${oi(t)}) AND (${oi(r)})`}function si(n){return hA.test(n)}function rg(n){return gA.test(n)&&n.length>=tg}function vA(n){return yA.test(n)}function ai(n){return si(n)||rg(n)||vA(n)}function SA(n){let e=n.trim().toLowerCase();return eg.has(e)?!1:Zh.has(e)}function bA(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function Pa(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function cd(n){return[...n.matchAll(cA)].map(e=>e[0])}function ld(n,e=tg){let t=[];for(let r of n.matchAll(lA))r[0].length>=e&&t.push(r[0]);return t}function Gr(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 pt(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function EA(n){let e=new Set;pt(e,n);let t=Pa(n);return t&&pt(e,t),Gr([...e])}function Ca(n){if(si(n))return EA(n);let e=new Set;return pt(e,n),Gr([...e])}function Ia(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(mA);if(!t)return null;let r=t[1].toLowerCase(),o=t[2].toLowerCase();if(!fA.test(r)||Qh.has(r)||!SA(o))return null;let i=bA(r,o);return{first:r,second:o,camelCase:i,lower:i.toLowerCase()}}function dd(n){let e=Ia(n.trim());return!e||e.second!=="manager"?null:e}function PA(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function og(n){let e=n.trim(),t=dd(e);if(t&&ad.has(t.first))return!0;if(rg(e)){let r=PA(e);return r!==null&&ad.has(r)}return!1}function ud(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 pd(n){let e=n.trim();if(ai(e))return Ca(e);let t=new Set;for(let r of cd(n)){pt(t,r);let o=Pa(r);o&&pt(t,o)}for(let r of ld(n))pt(t,r);for(let r of n.matchAll(uA))t.add(r[0]);for(let r of n.matchAll(pA))t.add(r[0]);for(let r of n.matchAll(dA))r[0].length>=4&&t.add(r[0]);return Gr([...t])}function ig(n){let e=n.trim();if(ai(e))return Ca(e);let t=new Set,r=Ia(e);r&&pt(t,r.camelCase);for(let o of pd(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 Gr([...t])}function sg(n){return ai(n)}var Y={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 ag(n){return Y.pureApiSymbol.test(n.trim())}function ci(n){let e=n.trim();return Y.stageModelExact.test(e)||Y.stageModelEnglishExact.test(e)}function cg(n){let e=[];return ci(n.trim())&&e.push("Stage\u6A21\u578B","Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0"),Y.declarePermissionTokens.test(n)&&e.push("\u58F0\u660E\u6743\u9650"),Y.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 lg(n){return ci(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var CA=[{matches:n=>Y.uiAbilityLifecycleBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:n=>ci(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!ci(n)&&Y.stageModel.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:n=>Y.entryAbilityPage.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:n=>Y.declarePermissionBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:n=>Y.stateDecoratorBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:n=>Y.stateManagement.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:n=>Y.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=>Y.dialogPopupBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function IA(n,e){for(let{catalog:t,multiplier:r}of e){let o=fn[t];n.set(o,(n.get(o)??1)*r)}}function dg(n,e){for(let t of CA)t.matches(n)&&IA(e,t.weights)}function ug(n,e){if(e!==void 0)return!1;let t=n.trim();return si(t)||Y.pureApiSymbol.test(t)||og(t)}function pg(n){let e=n.trim();if(si(e)||Y.pureApiSymbol.test(e))return"harmonyos-references";if(ci(e)||Y.uiAbilityLifecycleCatalog.test(e)||Y.stateDecoratorCatalog.test(e)||Y.stateManagement.test(e)||Y.declarePermissionCatalog.test(e)||Y.stageModelEntryPage.test(e)||Y.routerRoute.test(e)||Y.dialogPopupExact.test(e))return"harmonyos-guides"}import*as zr from"fs";import*as mg from"path";var Aa=null,fd=null,md=null;function AA(){return zr.existsSync(Xo())}function DA(n){let e=Xo(),t={backend:"jieba-wasm",reason:"native-jieba-load-failed",message:n,createdAt:new Date().toISOString()};zr.mkdirSync(mg.dirname(e),{recursive:!0}),ti(e),zr.writeFileSync(e,JSON.stringify(t,null,2))}function RA(){if(Aa)return Aa;let n=Yn("harmonyos-stopwords.txt");return Aa=new Set(n.split(`
1309
+ `).map(e=>e.trim()).filter(Boolean)),Aa}function TA(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 hg(n){let e=RA(),t=[];for(let r of TA(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 gg(n){let{dict:e}=await import("@node-rs/jieba/dict.js"),t=n.withDict(e),r=Yn("harmonyos-terms.txt");return t.loadDict(Buffer.from(r,"utf-8")),t}async function kA(){let{Jieba:n}=await import("@node-rs/jieba");return gg(n)}async function fg(){let{Jieba:n}=await import("@node-rs/jieba-wasm32-wasi");return gg(n)}async function xA(){let n=await import("jieba-wasm"),e=Yn("harmonyos-terms.txt");return n.with_dict(e),{cut:n.cut,cutForSearch:n.cut_for_search}}async function NA(){if(b())return xA();if(AA())return fg();try{let e=await kA();return m("doc-index: using @node-rs/jieba backend"),e}catch(e){let t=e instanceof Error?e.message:String(e);DA(t),m(`doc-index: @node-rs/jieba unavailable (${t}); falling back to wasm32-wasi`)}let n=await fg();return m("doc-index: using @node-rs/jieba-wasm32-wasi backend"),n}async function yn(){return fd||(md||(md=NA().then(n=>(fd=n,n))),md)}async function LA(n){let e=await yn();return hg(e.cutForSearch(n,!0))}async function yg(n){let e=await yn();return hg(e.cut(n,!0))}async function Da(n,e){let t=n.trim();if(!t||e<=0)return"";let r=(await LA(t)).join(" ");return r.length<=e?r:r.slice(0,e)}async function OA(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 Ra(n){let e=!!n.sectionTitle.trim(),t=n.titleTokens.trim(),r=e?gh:uh,o=e?wh:fh,i=e?await OA(n.apiSymbols,o):await Da(n.apiSymbols.join(" "),o),a=(await Promise.all([Da(t,e?yh:ph),Promise.resolve(i),Da(n.headingsText,e?vh:mh),Da(n.bodySample,e?Sh:hh)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}function MA(n){return n.join(" ").replace(/\s+/g," ").trim().slice(0,Vo)}function hd(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>=ch))break}return r}function _A(n){return n.length>=2&&n.length<=lh}function FA(n,e){let t=nd(n,Bl),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=hd(o,i);return{rawQuery:n,expandedQuery:t,tokens:s,preferAnd:!1,ftsMatch:ng(o,i)}}function jA(n,e){let t=hd(Ca(e),[]);return{rawQuery:n,expandedQuery:n,tokens:t,preferAnd:!1,ftsMatch:oi(t)}}async function wg(n){let e=MA(n),t=e.trim(),r=lg(t);if(r)return{rawQuery:e,expandedQuery:r.expandedQuery,tokens:r.tokens,preferAnd:!1};let o=Ia(t);if(o)return FA(e,o);if(ai(t))return jA(e,t);let i=cg(e),s=[...pd(e),...i],c=sg(t)?e:nd(e,Bl),l=await yg(c),d=hd(s,l);return{rawQuery:e,expandedQuery:c,tokens:d,preferAnd:i.length===0&&_A(d)}}var vg=["harmonyos-releases","harmonyos-roadmap"],HA=new Set(vg.map(n=>fn[n])),$A=vg.map(n=>`${zn[n]}/`);function UA(n){return HA.has(n)}function BA(n){return $A.some(e=>n.startsWith(e))}function Sg(n){let e=[],t=[];for(let r of n)UA(r.catalog_id)?t.push(r):e.push(r);return[...e,...t]}function bg(n){let e=[],t=[];for(let r of n)BA(r.documentId)?t.push(r):e.push(r);return[...e,...t]}var WA=[{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 li(n,e,t){let r=fn[e];n.set(r,(n.get(r)??1)*t)}function GA(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)){li(e,"harmonyos-guides",1.45),li(e,"harmonyos-references",1.35);return}(o||i)&&li(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(t)&&li(e,"harmonyos-references",1.75)}function Eg(n){let e=new Map,t=n.trim();if(!t)return e;let r=ag(t);GA(t,e),dg(t,e);for(let o of WA)o.pattern.test(t)&&(o.skipForPureApiSymbol&&r||li(e,o.catalog,o.multiplier));return e}function Pg(n){return pg(n)}import*as Vr from"fs";import*as xg from"path";var zA=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function Cg(n,e){let t=-1;for(let r of zA){let o=n.lastIndexOf(r);o>t&&(t=o)}return t>=e?t:-1}function Ig(n,e){let t=n.trim();if(t.length<=e)return{text:t,excerptTruncated:!1};let r=t.slice(0,e),o=Cg(r,e-20),i=o>=0?o:e;return{text:t.slice(0,i).trimEnd(),excerptTruncated:!0}}function Ag(n,e,t={}){let{maxLen:r=Ph,contextChars:o=Ch,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(Re=>Re.trim()).filter(Boolean),c=0;for(let Re of a){let Pe=s.toLowerCase().indexOf(Re.toLowerCase());if(Pe>=0){c=Pe;break}}let l=Math.max(0,c-o),d=Math.min(s.length,l+r),h=s.slice(l,d),w=Cg(h,r-25);w>=0&&(d=l+w);let S=s.slice(l,d).trim(),k=l>0?"...":"",re=d<s.length||i?"...":"";return`${k}${S}${re}`}var qA=`
1310
1310
  SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
1311
1311
  d.catalog_id, bm25(segments_fts) AS bm25
1312
1312
  FROM segments_fts
@@ -1315,7 +1315,7 @@ ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this
1315
1315
  WHERE segments_fts MATCH ?
1316
1316
  ORDER BY bm25(segments_fts)
1317
1317
  LIMIT ?
1318
- `,qA=`
1318
+ `,VA=`
1319
1319
  SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
1320
1320
  d.catalog_id, bm25(segments_fts) AS bm25
1321
1321
  FROM segments_fts
@@ -1324,7 +1324,7 @@ ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this
1324
1324
  WHERE segments_fts MATCH ? AND d.catalog_id = ?
1325
1325
  ORDER BY bm25(segments_fts)
1326
1326
  LIMIT ?
1327
- `,VA=3.5,JA=1.4,YA=4,KA=1.8,XA=1.35,ZA=3.5,QA=1.8,eD=120,Ag=6;function gd(n){return n.toLowerCase().replace(/[^\p{L}\p{N}@.]+/gu,"")}function tD(n){return n.split(/[^\p{L}\p{N}@.]+/u).map(gd).filter(e=>e.length>=2)}function nD(n,e){return e.length>1&&e.every(t=>n.includes(t))}function rD(n){return/^[a-z0-9]{1,4}$/.test(n.trim().toLowerCase())}function oD(n,e){return n===e?ZA:n.startsWith(e)||n.includes(`@ohos.${e}`)?QA:1}function iD(n,e){let t=gd(e);if(t.length<2)return 1;let r=gd(n.doc_title);if(rD(e))return oD(r,t);if(r.includes(t))return YA;if(t.length>=Ag&&r.includes(t.slice(0,Ag)))return KA;let o=tD(e);return nD(r,o)?XA:1}function sD(n,e){return e<=1?n:n<0?n*e:n/e}function Ra(n,e,t,r){let o=n.bm25/(e.get(n.catalog_id)??1);return o=sD(o,iD(n,t)),r&&dd(n.doc_title,n.section_title,r)&&(o/=VA,n.catalog_id===un["harmonyos-references"]&&(o/=JA)),o}function hd(n,e,t,r){return n.reduce((o,i)=>Ra(i,e,t,r)<Ra(o,e,t,r)?i:o)}function aD(n,e){return e.some(t=>n.section_title.includes(t)||n.doc_title.includes(t))}function cD(n,e,t,r,o){if(o){let i=n.filter(s=>dd(s.doc_title,s.section_title,o));if(i.length>0)return hd(i,t,r,o)}if(e.length>0){let i=n.filter(s=>aD(s,e));if(i.length>0)return hd(i,t,r,o)}return hd(n,t,r,o)}function Dg(n,e,t,r,o){let i=bg(e),s=og(e),c=ld(e)?.camelCase,l=new Map;for(let S of n){let k=l.get(S.document_id)??[];k.push(S),l.set(S.document_id,k)}let d=[];for(let S of l.values())d.push(cD(S,s,i,t,c));let h=d.sort((S,k)=>Ra(S,i,t,c)-Ra(k,i,t,c));return(o?vg(h):h).slice(0,r)}function Ta(n,e,t,r,o,i){let s=e?un[e]:void 0,a=Math.max(t,t*lh,eD),c=s===void 0?n.all(zA,r,a):n.all(qA,r,s,a);return(s===void 0?Dg(c,i,o,t,!0):Dg(c,i,o,t,!1)).map(d=>({title:d.doc_title,documentId:d.document_id,sectionTitle:d.section_title||void 0,snippet:Ig(d.lead_text,o,{excerptTruncated:!!d.excerpt_truncated})}))}var ka=`
1327
+ `,JA=3.5,YA=1.4,KA=4,XA=1.8,ZA=1.35,QA=3.5,eD=1.8,tD=120,Dg=6;function yd(n){return n.toLowerCase().replace(/[^\p{L}\p{N}@.]+/gu,"")}function nD(n){return n.split(/[^\p{L}\p{N}@.]+/u).map(yd).filter(e=>e.length>=2)}function rD(n,e){return e.length>1&&e.every(t=>n.includes(t))}function oD(n){return/^[a-z0-9]{1,4}$/.test(n.trim().toLowerCase())}function iD(n,e){return n===e?QA:n.startsWith(e)||n.includes(`@ohos.${e}`)?eD:1}function sD(n,e){let t=yd(e);if(t.length<2)return 1;let r=yd(n.doc_title);if(oD(e))return iD(r,t);if(r.includes(t))return KA;if(t.length>=Dg&&r.includes(t.slice(0,Dg)))return XA;let o=nD(e);return rD(r,o)?ZA:1}function aD(n,e){return e<=1?n:n<0?n*e:n/e}function Ta(n,e,t,r){let o=n.bm25/(e.get(n.catalog_id)??1);return o=aD(o,sD(n,t)),r&&ud(n.doc_title,n.section_title,r)&&(o/=JA,n.catalog_id===fn["harmonyos-references"]&&(o/=YA)),o}function gd(n,e,t,r){return n.reduce((o,i)=>Ta(i,e,t,r)<Ta(o,e,t,r)?i:o)}function cD(n,e){return e.some(t=>n.section_title.includes(t)||n.doc_title.includes(t))}function lD(n,e,t,r,o){if(o){let i=n.filter(s=>ud(s.doc_title,s.section_title,o));if(i.length>0)return gd(i,t,r,o)}if(e.length>0){let i=n.filter(s=>cD(s,e));if(i.length>0)return gd(i,t,r,o)}return gd(n,t,r,o)}function Rg(n,e,t,r,o){let i=Eg(e),s=ig(e),c=dd(e)?.camelCase,l=new Map;for(let S of n){let k=l.get(S.document_id)??[];k.push(S),l.set(S.document_id,k)}let d=[];for(let S of l.values())d.push(lD(S,s,i,t,c));let h=d.sort((S,k)=>Ta(S,i,t,c)-Ta(k,i,t,c));return(o?Sg(h):h).slice(0,r)}function ka(n,e,t,r,o,i){let s=e?fn[e]:void 0,a=Math.max(t,t*dh,tD),c=s===void 0?n.all(qA,r,a):n.all(VA,r,s,a);return(s===void 0?Rg(c,i,o,t,!0):Rg(c,i,o,t,!1)).map(d=>({title:d.doc_title,documentId:d.document_id,sectionTitle:d.section_title||void 0,snippet:Ag(d.lead_text,o,{excerptTruncated:!!d.excerpt_truncated})}))}var xa=`
1328
1328
  CREATE TABLE documents (
1329
1329
  id INTEGER PRIMARY KEY,
1330
1330
  document_id TEXT NOT NULL UNIQUE,
@@ -1362,54 +1362,54 @@ CREATE TRIGGER segments_au AFTER UPDATE ON segments BEGIN
1362
1362
  END;
1363
1363
 
1364
1364
  CREATE INDEX segments_doc_id_idx ON segments(doc_id);
1365
- `;var Wr=null,yd=null;function lD(){Wr?.close(),Wr=null,yd=null}function dD(n,e){if(Wr&&yd===e)return Wr;Wr?.close();let t=new n(e,{readonly:!0,fileMustExist:!0});return Wr=t,yd=e,t.pragma("mmap_size = 268435456"),t.pragma("cache_size = -8000"),t.pragma("query_only = ON"),t}function uD(n,e){let t=new n(e);return t.pragma("journal_mode = OFF"),t.pragma("synchronous = OFF"),t.pragma("temp_store = MEMORY"),t.exec(ka),t}function pD(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(`
1365
+ `;var qr=null,wd=null;function dD(){qr?.close(),qr=null,wd=null}function uD(n,e){if(qr&&wd===e)return qr;qr?.close();let t=new n(e,{readonly:!0,fileMustExist:!0});return qr=t,wd=e,t.pragma("mmap_size = 268435456"),t.pragma("cache_size = -8000"),t.pragma("query_only = ON"),t}function pD(n,e){let t=new n(e);return t.pragma("journal_mode = OFF"),t.pragma("synchronous = OFF"),t.pragma("temp_store = MEMORY"),t.exec(xa),t}function fD(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(`
1366
1366
  INSERT INTO documents(document_id, catalog_id, doc_title)
1367
1367
  VALUES (?, ?, ?)
1368
- `).run(t.documentId,t.catalogId,t.docTitle),c=Number(a.lastInsertRowid);return e.set(t.documentId,c),c}async function fD(n,e,t,r){await hn();let o=uD(n,e),i=new Map,s=o.prepare(`
1368
+ `).run(t.documentId,t.catalogId,t.docTitle),c=Number(a.lastInsertRowid);return e.set(t.documentId,c),c}async function mD(n,e,t,r){await yn();let o=pD(n,e),i=new Map,s=o.prepare(`
1369
1369
  INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated)
1370
1370
  VALUES (?, ?, ?, ?, ?)
1371
- `),a=t.length;for(let c=0;c<a;c+=Mr){let l=t.slice(c,c+Mr),d=await Promise.all(l.map(async w=>({source:w,searchText:await Da(w)})));o.transaction(w=>{for(let S of w){let k=pD(o,i,S.source);s.run(k,S.source.sectionTitle,S.source.leadText,S.searchText,S.source.excerptTruncated?1:0)}})(d),await r?.(Math.min(c+l.length,a),a)}o.exec("ANALYZE"),o.exec("VACUUM"),o.close()}function mD(n,e,t,r,o,i,s){let a=dD(n,e);return Ta({all(c,...l){return a.prepare(c).all(...l)}},t,r,o,i,s)}async function Rg(){let e=(await import("better-sqlite3")).default;return{kind:"better-sqlite3",resetCache:lD,buildSearchIndex:(t,r,o)=>fD(e,t,r,o),searchIndex:(t,r,o,i,s,a,c)=>Promise.resolve(mD(e,i,r,o,s,a,c))}}import{readFile as hD,stat as gD,writeFile as yD}from"fs/promises";var wd=null,gn=null;async function vd(){return wd||(wd=(async()=>{let n=(await import("@sqlite.org/sqlite-wasm")).default;return n()})()),wd}function wD(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 vD(n){let e=await gD(n);if(gn&&gn.dbPath===n&&gn.mtimeMs===e.mtimeMs)return gn.db;gn?.db.close();let t=await vd(),r=t.capi,o=t.wasm,i=new Uint8Array(await hD(n)),s=o.allocFromTypedArray(i),a=new t.oo1.DB(":memory:"),c=r.SQLITE_DESERIALIZE_READONLY|r.SQLITE_DESERIALIZE_RESIZEABLE|r.SQLITE_DESERIALIZE_FREEONCLOSE;return r.sqlite3_deserialize(a.pointer,"main",s,i.byteLength,i.byteLength,c),gn={dbPath:n,mtimeMs:e.mtimeMs,db:a},a}function Tg(){gn?.db.close(),gn=null}async function SD(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 bD(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 ED(n,e,t){await hn();let r=await vd(),o=new r.oo1.DB(":memory:","c");o.exec(ka);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=bD(o,i,s),l=e.length;for(let h=0;h<l;h+=Mr){let w=e.slice(h,h+Mr),S=await Promise.all(w.map(async k=>({source:k,searchText:await Da(k)})));await SD(o,a,c,S),await t?.(Math.min(h+w.length,l),l)}o.exec("ANALYZE");let d=r.capi.sqlite3_js_db_export(o);await yD(n,d),o.close(),Tg()}async function PD(n,e,t,r,o,i){let s=await vD(n);return Ta(wD(s),e,t,r,o,i)}async function Sd(){return await vd(),{kind:"sqlite-wasm",resetCache:Tg,buildSearchIndex:ED,searchIndex:(n,e,t,r,o,i,s)=>PD(r,e,t,o,i,s)}}var xa=null,bd=null;function CD(){return Gr.existsSync(Jo())}function ID(n){let e=Jo(),t={backend:"sqlite-wasm",reason:"better-sqlite3-load-failed",message:n,createdAt:new Date().toISOString()};Gr.mkdirSync(kg.dirname(e),{recursive:!0}),Qo(e),Gr.writeFileSync(e,JSON.stringify(t,null,2))}async function AD(){if(CD())return Sd();try{let n=await Rg();return m("doc-index: using better-sqlite3 SQLite backend"),n}catch(n){let e=n instanceof Error?n.message:String(n);ID(e),m(`doc-index: better-sqlite3 unavailable (${e}); falling back to sqlite-wasm`)}return Sd()}async function ci(){return xa||(xa=AD().then(n=>(bd=n,n))),xa}function xg(){bd?.resetCache(),xa=null,bd=null}async function DD(n,e,t,r,o,i,s){let a=await ci(),c=s??qn();return a.searchIndex(n,e,t,c,r,o,i)}function zr(){xg()}async function Lg(n,e,t){await(await ci()).buildSearchIndex(n,e,t)}function Og(n,e,t){let r=new Set,o=[];for(let i of[...n,...e])if(!r.has(i.documentId)&&(r.add(i.documentId),o.push(i),o.length>=t))break;return o}function Na(n,e,t,r,o,i){return DD(n,e,t,o,r.expandedQuery,r.rawQuery,i)}async function RD(n,e,t,r,o){let i=await Na(n,e,t,r,ri(r.tokens,"AND"),o);if(i.length>=t)return i;let s=await Na(n,e,t,r,ri(r.tokens,"OR"),o);return Og(i,s,t)}async function Ed(n,e,t,r,o){return r.ftsMatch?Na(n,e,t,r,r.ftsMatch,o):r.preferAnd?RD(n,e,t,r,o):Na(n,e,t,r,ri(r.tokens,"OR"),o)}async function TD(n,e,t,r){let o=await Ed(n,"harmonyos-references",e,t,r);if(o.length>=e)return o;let i=await Ed(n,void 0,e,t,r);return Og(o,i,e)}function Ng(n,e){return e!==void 0?n:Sg(n)}async function Pd(n,e,t=20,r){let o=await yg(n);if(dg(o.rawQuery,e)){let a=await TD(n,t,o,r);return Ng(a,e)}let i=e??Eg(o.rawQuery),s=await Ed(n,i,t,o,r);return Ng(s,e)}import{unified as Bg}from"unified";import Wg from"remark-parse";import Gg from"remark-gfm";import{toString as Oa}from"mdast-util-to-string";var kD=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,xD=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,ND=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,LD=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,OD=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function La(n){let e=n.trim(),t=e.match(LD);return t?t[1]:e}function MD(n){let e=n.match(kD);if(!e)return;let t=La(e[1].trim());return{displayTitle:n,symbolName:t,searchExtras:[t,e[3]]}}function _D(n){let e=La(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 li(n){let e=n.trim();return e?MD(e)??(()=>{let t=e.match(xD);if(t){let r=t[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let t=e.match(ND);if(!t)return;let r=t[1].trim(),o=t[2].trim();return{displayTitle:e,symbolName:o,searchExtras:[r,o]}})()??_D(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function FD(n){if(n.length<2||n.length>36||OD.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 Mg(n){for(let e of n){let t=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(FD(t))return t}return""}function _g(n,e,t){let r=[n,...t.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var jD=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,di=/@[A-Z][a-zA-Z]+/g,HD=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,$D=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,UD=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,BD=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),WD=new Set(["HAP","HSP","HAR","NAPI","CAPI","NDK","ArkTS","ArkUI","OHPM"]),GD=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 ad(o)){ut(t,i);let s=Ea(i);s&&ut(t,s)}for(let i of cd(o))ut(t,i);for(let i of o.matchAll(jD)){let s=i[0];zD(s)&&t.add(s)}for(let i of o.matchAll(di))t.add(i[0])}return Ur([...t])}function zD(n){let e=n.trim();if(!e||di.test(e))return!!e;if(e.includes(".")){let t=e.split(".")[0]??"";return GD.has(t)?!1:/^[A-Z]/.test(t)}return BD.has(e)?!1:WD.has(e)?!0:e.length<=3?!1:/^[A-Z][a-z]+[A-Z]/.test(e)?!0:e.length>=6&&/^[A-Z][A-Za-z0-9]+$/.test(e)}function Fg(n){let e=n.trim();return!!(!e||UD.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=YD(n,"").trim(),o=e.fileName.trim();return t&&!Fg(t)?t:r&&!Fg(r)?r:t||r||o}function Vg(n){return HD.test(n.trim())}function Cd(n){let e=n.trim().replace(/\([^)]*\)$/,""),t=La(e);return $D.test(t)}function Ma(n){let e=n.trim();return e?di.test(e)||Vg(e)||Cd(e)?!0:!!li(e).symbolName:!1}function qD(n){let e=n.trim();return!(!e||Vg(e)||Cd(e))}function VD(n){let e=new Set,t=[];for(let r of n){let o=r.trim();!qD(o)||e.has(o)||(e.add(o),t.push(o))}return t}function jg(n){if(!n.includes("."))return 0;let e=n.split(".").pop()??"";return/^[a-z]/.test(e)?1:2}function JD(n,e){let t=jg(n)-jg(e);return t!==0?t:n.localeCompare(e)}function Jg(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(JD),[...t,...o].slice(0,Sh)}function _a(n){return n.replace(/\s+/g," ").trim()}function Hg(n){return n.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function YD(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=Hg(t[r].trim()),i=o.match(/^#+\s+(.+)$/);if(i)return Hg(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 Yg(n){let e=_a(n.join(" "));if(e.length<=da)return e;let t=e.slice(0,da);return e.length<=da+Bl?t:`${t} ${e.slice(-Bl)}`}function KD(n){let e=VD(n).join(" ");return e.length<=Wl?e:e.slice(0,Wl)}function Kg(n){let e=_a(n),{text:t,excerptTruncated:r}=Cg(e,bh);return{leadText:t,excerptTruncated:r}}function XD(n,e){let{leadText:t,excerptTruncated:r}=Kg(n);return{leadText:t,excerptTruncated:r||!!e.trim()}}function Xg(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)Xg(r,e);return}let t=_a(Oa(n));t&&e.bodyParts.push(t)}function ZD(n){let e=Bg().use(Wg).use(Gg).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=Oa(a).trim();if(a.depth>=4&&c&&Ma(c)){o(),r={sectionTitle:c,bodyParts:[],codeBlocks:[]};continue}i(),c&&r.bodyParts.push(c);continue}i(),Xg(s,r)}return o(),t.length===0?[{sectionTitle:"",bodyParts:[],codeBlocks:[]}]:t}function QD(n){return sh.test(n)}function eR(n){return n.filter(e=>e.sectionTitle&&Ma(e.sectionTitle)).length}function tR(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 $g(n){let e=n.trim();return!e||di.test(e)?di.test(e):/对象说明$|枚举说明$/.test(e)?!0:Cd(e)}function nR(n){let e=n.filter(h=>!h.sectionTitle||!Ma(h.sectionTitle)),t=n.filter(h=>h.sectionTitle&&Ma(h.sectionTitle)),r=t.filter(h=>$g(h.sectionTitle)),o=t.filter(h=>!$g(h.sectionTitle)),i=Math.max(0,ih-r.length),s=o.slice(0,i),a=o.slice(i),c=a.filter(h=>Ug(h.sectionTitle)),l=a.filter(h=>!Ug(h.sectionTitle)),d=[];for(let h=0;h<l.length;h+=$l)d.push(tR(l.slice(h,h+$l)));return[...e,...r,...s,...c,...d]}function rR(n,e,t){let r=n.split(/\r?\n/).length,o=eR(e);return o===0?!1:QD(t)?r>=rh&&o>=oh:r>=th&&o>=nh}var oR=/^\[h2\][A-Za-z]/;function Ug(n){return oR.test(n.trim())}function Zg(n){if(!n.includes(" | ")){let t=li(n);return t.symbolName?[t.symbolName]:[]}let e=[];for(let t of n.split(" | ")){let r=li(t.trim()).symbolName;r&&e.push(r)}return e}function iR(n,e,t,r){let o=Zg(n),i=zg(t,r);return e.symbolName&&i.push(e.symbolName),Jg([...o,...i],o)}function sR(n,e){let t=Yg(n.bodyParts),r=n.sectionTitle.trim(),o=li(r),i=Mg(n.bodyParts),s=_g(r,i,o),a=Zg(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}=XD(t,r);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:e.docTitle,sectionTitle:r,titleTokens:c,headingsText:s,apiSymbols:iR(r,o,l,n.codeBlocks),bodySample:t,leadText:d,excerptTruncated:h}}function Qg(n,e){for(let t of n){if(t.type==="heading"){let o=Oa(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)){Qg(t.children,e);continue}let r=_a(Oa(t));r&&e.bodyParts.push(r)}}function aR(n){let e=Bg().use(Wg).use(Gg).parse(n),t={headings:[],bodyParts:[],codeBlocks:[]};return Qg(e.children,t),t}function cR(n,e){let t=aR(n),r=e.docTitle?.trim()||e.documentId,o=Yg(t.bodyParts),i=[r,...t.headings,o].join(" "),{leadText:s,excerptTruncated:a}=Kg(o);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:r,sectionTitle:"",titleTokens:r,headingsText:KD(t.headings),apiSymbols:Jg(zg(i,t.codeBlocks)),bodySample:o,leadText:s,excerptTruncated:a}}function ey(n,e){let t=e.docTitle?.trim()||e.documentId,r=ZD(n);return rR(n,r,e.documentId)?nR(r).filter(o=>o.sectionTitle||o.bodyParts.length>0||o.codeBlocks.length>0).map(o=>sR(o,{...e,docTitle:t})):[cR(n,{...e,docTitle:t})]}async function lR(n){let e=[];async function t(r){let o=await be.promises.readdir(r,{withFileTypes:!0});for(let i of o){if(i.name.startsWith("."))continue;let s=Le.join(r,i.name);i.isDirectory()?await t(s):i.isFile()&&i.name.endsWith(".md")&&e.push(s)}}return await t(n),e}function dR(n,e){let t=Le.relative(e,n).split(Le.sep).join("/").split("/");if(t[0]==="docs"&&(t=t.slice(1)),t.length<2)return null;let r=t[0],o=Ch[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 uR(n){let e=n.replace(/\.md$/,".json");try{let t=await be.promises.readFile(e,"utf-8");return JSON.parse(t).title?.trim()||void 0}catch{return}}async function pR(n,e){let t=dR(n,e);if(!t)return[];let r=await be.promises.readFile(n,"utf-8"),o=qg(r,{jsonTitle:await uR(n),fileName:t.docTitle});return ey(r,{...t,docTitle:o})}async function fR(n,e,t){let r=Le.join(e,"search.db");return await Lg(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 mR(n){let e=await lR(n),t=[];for(let r of e){let o=await pR(r,n);t.push(...o)}return t}function hR(n,e){return{indexVersion:Or,docsZipSha256:n.docsZipSha256,termsHash:n.termsHash,synonymsHash:n.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:n.builtBy}}async function ny(n){n.lexiconDir&&Vl(n.lexiconDir);try{let e=await mR(n.docsDir);await n.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await be.promises.mkdir(n.tmpDir,{recursive:!0});let t=await fR(e,n.tmpDir,n.onProgress),r=hR(n,t);return await be.promises.writeFile(Le.join(n.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await _h(n.tmpDir),r}finally{n.lexiconDir&&Vl(null)}}async function ry(){return be.promises.mkdtemp(Le.join(ty.tmpdir(),"deveco-docs-"))}async function gR(n,e){try{await be.promises.rename(n,e)}catch(t){let r=t.code;if(r!=="EPERM"&&r!=="EXDEV")throw t;await be.promises.cp(n,e,{recursive:!0}),await be.promises.rm(n,{recursive:!0,force:!0})}}async function oy(n){let e=Le.join(n,"docs");try{await be.promises.access(e)}catch{return}let t=new Set(["docs","docs.zip"]);for(let r of await be.promises.readdir(e,{withFileTypes:!0})){if(t.has(r.name))continue;let o=Le.join(e,r.name),i=Le.join(n,r.name);await be.promises.rm(i,{recursive:!0,force:!0}),await gR(o,i)}await be.promises.rm(Le.join(e,"docs"),{recursive:!0,force:!0}),await be.promises.rm(Le.join(e,"docs.zip"),{force:!0}),await be.promises.rm(e,{recursive:!0,force:!0})}var ui=class extends Error{constructor(e){super(e),this.name="NativeDepsError"}};function yR(){let n=Hr(),e=Z();return["Documentation search index is not installed yet.","",...ua(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(`
1372
- `)}function wR(){let n=Hr();return[`Chinese tokenizer (${b()?"jieba-wasm":"@node-rs/jieba"}) failed to load.`,"",`Node.js: ${process.version} (required: >=18)`,"",...ua(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(`
1373
- `)}function vR(n){let e=Hr();return[n,"",...ua(e)].join(`
1374
- `)}async function iy(){try{Oh()}catch(n){throw Lh(n)?new ui(`${yR()}
1371
+ `),a=t.length;for(let c=0;c<a;c+=jr){let l=t.slice(c,c+jr),d=await Promise.all(l.map(async w=>({source:w,searchText:await Ra(w)})));o.transaction(w=>{for(let S of w){let k=fD(o,i,S.source);s.run(k,S.source.sectionTitle,S.source.leadText,S.searchText,S.source.excerptTruncated?1:0)}})(d),await r?.(Math.min(c+l.length,a),a)}o.exec("ANALYZE"),o.exec("VACUUM"),o.close()}function hD(n,e,t,r,o,i,s){let a=uD(n,e);return ka({all(c,...l){return a.prepare(c).all(...l)}},t,r,o,i,s)}async function Tg(){let e=(await import("better-sqlite3")).default;return{kind:"better-sqlite3",resetCache:dD,buildSearchIndex:(t,r,o)=>mD(e,t,r,o),searchIndex:(t,r,o,i,s,a,c)=>Promise.resolve(hD(e,i,r,o,s,a,c))}}import{readFile as gD,stat as yD,writeFile as wD}from"fs/promises";var vd=null,wn=null;async function Sd(){return vd||(vd=(async()=>{let n=(await import("@sqlite.org/sqlite-wasm")).default;return n()})()),vd}function vD(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 SD(n){let e=await yD(n);if(wn&&wn.dbPath===n&&wn.mtimeMs===e.mtimeMs)return wn.db;wn?.db.close();let t=await Sd(),r=t.capi,o=t.wasm,i=new Uint8Array(await gD(n)),s=o.allocFromTypedArray(i),a=new t.oo1.DB(":memory:"),c=r.SQLITE_DESERIALIZE_READONLY|r.SQLITE_DESERIALIZE_RESIZEABLE|r.SQLITE_DESERIALIZE_FREEONCLOSE;return r.sqlite3_deserialize(a.pointer,"main",s,i.byteLength,i.byteLength,c),wn={dbPath:n,mtimeMs:e.mtimeMs,db:a},a}function kg(){wn?.db.close(),wn=null}async function bD(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 ED(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 PD(n,e,t){await yn();let r=await Sd(),o=new r.oo1.DB(":memory:","c");o.exec(xa);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=ED(o,i,s),l=e.length;for(let h=0;h<l;h+=jr){let w=e.slice(h,h+jr),S=await Promise.all(w.map(async k=>({source:k,searchText:await Ra(k)})));await bD(o,a,c,S),await t?.(Math.min(h+w.length,l),l)}o.exec("ANALYZE");let d=r.capi.sqlite3_js_db_export(o);await wD(n,d),o.close(),kg()}async function CD(n,e,t,r,o,i){let s=await SD(n);return ka(vD(s),e,t,r,o,i)}async function bd(){return await Sd(),{kind:"sqlite-wasm",resetCache:kg,buildSearchIndex:PD,searchIndex:(n,e,t,r,o,i,s)=>CD(r,e,t,o,i,s)}}var Na=null,Ed=null;function ID(){return Vr.existsSync(Ko())}function AD(n){let e=Ko(),t={backend:"sqlite-wasm",reason:"better-sqlite3-load-failed",message:n,createdAt:new Date().toISOString()};Vr.mkdirSync(xg.dirname(e),{recursive:!0}),ti(e),Vr.writeFileSync(e,JSON.stringify(t,null,2))}async function DD(){if(ID())return bd();try{let n=await Tg();return m("doc-index: using better-sqlite3 SQLite backend"),n}catch(n){let e=n instanceof Error?n.message:String(n);AD(e),m(`doc-index: better-sqlite3 unavailable (${e}); falling back to sqlite-wasm`)}return bd()}async function di(){return Na||(Na=DD().then(n=>(Ed=n,n))),Na}function Ng(){Ed?.resetCache(),Na=null,Ed=null}async function RD(n,e,t,r,o,i,s){let a=await di(),c=s??Vn();return a.searchIndex(n,e,t,c,r,o,i)}function Jr(){Ng()}async function Og(n,e,t){await(await di()).buildSearchIndex(n,e,t)}function Mg(n,e,t){let r=new Set,o=[];for(let i of[...n,...e])if(!r.has(i.documentId)&&(r.add(i.documentId),o.push(i),o.length>=t))break;return o}function La(n,e,t,r,o,i){return RD(n,e,t,o,r.expandedQuery,r.rawQuery,i)}async function TD(n,e,t,r,o){let i=await La(n,e,t,r,ii(r.tokens,"AND"),o);if(i.length>=t)return i;let s=await La(n,e,t,r,ii(r.tokens,"OR"),o);return Mg(i,s,t)}async function Pd(n,e,t,r,o){return r.ftsMatch?La(n,e,t,r,r.ftsMatch,o):r.preferAnd?TD(n,e,t,r,o):La(n,e,t,r,ii(r.tokens,"OR"),o)}async function kD(n,e,t,r){let o=await Pd(n,"harmonyos-references",e,t,r);if(o.length>=e)return o;let i=await Pd(n,void 0,e,t,r);return Mg(o,i,e)}function Lg(n,e){return e!==void 0?n:bg(n)}async function Cd(n,e,t=20,r){let o=await wg(n);if(ug(o.rawQuery,e)){let a=await kD(n,t,o,r);return Lg(a,e)}let i=e??Pg(o.rawQuery),s=await Pd(n,i,t,o,r);return Lg(s,e)}import{unified as Wg}from"unified";import Gg from"remark-parse";import zg from"remark-gfm";import{toString as Ma}from"mdast-util-to-string";var xD=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,ND=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,LD=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,OD=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,MD=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function Oa(n){let e=n.trim(),t=e.match(OD);return t?t[1]:e}function _D(n){let e=n.match(xD);if(!e)return;let t=Oa(e[1].trim());return{displayTitle:n,symbolName:t,searchExtras:[t,e[3]]}}function FD(n){let e=Oa(n.replace(/\([^)]*\)$/,""));if(/^[A-Z][A-Za-z0-9]*$/.test(e))return{displayTitle:n,symbolName:e,searchExtras:[e]};if(/^[A-Z][A-Za-z0-9]*(\([^)]*\))?$/.test(n))return{displayTitle:n,symbolName:e,searchExtras:[e]}}function ui(n){let e=n.trim();return e?_D(e)??(()=>{let t=e.match(ND);if(t){let r=t[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let t=e.match(LD);if(!t)return;let r=t[1].trim(),o=t[2].trim();return{displayTitle:e,symbolName:o,searchExtras:[r,o]}})()??FD(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function jD(n){if(n.length<2||n.length>36||MD.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 _g(n){for(let e of n){let t=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(jD(t))return t}return""}function Fg(n,e,t){let r=[n,...t.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var HD=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,pi=/@[A-Z][a-zA-Z]+/g,$D=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,UD=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,BD=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,WD=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),GD=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 qg(n,e){let t=new Set,r=[n,...e];for(let o of r){for(let i of cd(o)){pt(t,i);let s=Pa(i);s&&pt(t,s)}for(let i of ld(o))pt(t,i);for(let i of o.matchAll(HD)){let s=i[0];qD(s)&&t.add(s)}for(let i of o.matchAll(pi))t.add(i[0])}return Gr([...t])}function qD(n){let e=n.trim();if(!e||pi.test(e))return!!e;if(e.includes(".")){let t=e.split(".")[0]??"";return zD.has(t)?!1:/^[A-Z]/.test(t)}return WD.has(e)?!1:GD.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 jg(n){let e=n.trim();return!!(!e||BD.test(e)||e.length>28&&!/[A-Z\u4e00-\u9fff]/.test(e)&&/^[a-z0-9_-]+$/.test(e))}function Vg(n,e){let t=e.jsonTitle?.trim(),r=KD(n,"").trim(),o=e.fileName.trim();return t&&!jg(t)?t:r&&!jg(r)?r:t||r||o}function Jg(n){return $D.test(n.trim())}function Id(n){let e=n.trim().replace(/\([^)]*\)$/,""),t=Oa(e);return UD.test(t)}function _a(n){let e=n.trim();return e?pi.test(e)||Jg(e)||Id(e)?!0:!!ui(e).symbolName:!1}function VD(n){let e=n.trim();return!(!e||Jg(e)||Id(e))}function JD(n){let e=new Set,t=[];for(let r of n){let o=r.trim();!VD(o)||e.has(o)||(e.add(o),t.push(o))}return t}function Hg(n){if(!n.includes("."))return 0;let e=n.split(".").pop()??"";return/^[a-z]/.test(e)?1:2}function YD(n,e){let t=Hg(n)-Hg(e);return t!==0?t:n.localeCompare(e)}function Yg(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(YD),[...t,...o].slice(0,bh)}function Fa(n){return n.replace(/\s+/g," ").trim()}function $g(n){return n.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function KD(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=$g(t[r].trim()),i=o.match(/^#+\s+(.+)$/);if(i)return $g(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 Kg(n){let e=Fa(n.join(" "));if(e.length<=ua)return e;let t=e.slice(0,ua);return e.length<=ua+Wl?t:`${t} ${e.slice(-Wl)}`}function XD(n){let e=JD(n).join(" ");return e.length<=Gl?e:e.slice(0,Gl)}function Xg(n){let e=Fa(n),{text:t,excerptTruncated:r}=Ig(e,Eh);return{leadText:t,excerptTruncated:r}}function ZD(n,e){let{leadText:t,excerptTruncated:r}=Xg(n);return{leadText:t,excerptTruncated:r||!!e.trim()}}function Zg(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)Zg(r,e);return}let t=Fa(Ma(n));t&&e.bodyParts.push(t)}function QD(n){let e=Wg().use(Gg).use(zg).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=Ma(a).trim();if(a.depth>=4&&c&&_a(c)){o(),r={sectionTitle:c,bodyParts:[],codeBlocks:[]};continue}i(),c&&r.bodyParts.push(c);continue}i(),Zg(s,r)}return o(),t.length===0?[{sectionTitle:"",bodyParts:[],codeBlocks:[]}]:t}function eR(n){return ah.test(n)}function tR(n){return n.filter(e=>e.sectionTitle&&_a(e.sectionTitle)).length}function nR(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 Ug(n){let e=n.trim();return!e||pi.test(e)?pi.test(e):/对象说明$|枚举说明$/.test(e)?!0:Id(e)}function rR(n){let e=n.filter(h=>!h.sectionTitle||!_a(h.sectionTitle)),t=n.filter(h=>h.sectionTitle&&_a(h.sectionTitle)),r=t.filter(h=>Ug(h.sectionTitle)),o=t.filter(h=>!Ug(h.sectionTitle)),i=Math.max(0,sh-r.length),s=o.slice(0,i),a=o.slice(i),c=a.filter(h=>Bg(h.sectionTitle)),l=a.filter(h=>!Bg(h.sectionTitle)),d=[];for(let h=0;h<l.length;h+=Ul)d.push(nR(l.slice(h,h+Ul)));return[...e,...r,...s,...c,...d]}function oR(n,e,t){let r=n.split(/\r?\n/).length,o=tR(e);return o===0?!1:eR(t)?r>=oh&&o>=ih:r>=nh&&o>=rh}var iR=/^\[h2\][A-Za-z]/;function Bg(n){return iR.test(n.trim())}function Qg(n){if(!n.includes(" | ")){let t=ui(n);return t.symbolName?[t.symbolName]:[]}let e=[];for(let t of n.split(" | ")){let r=ui(t.trim()).symbolName;r&&e.push(r)}return e}function sR(n,e,t,r){let o=Qg(n),i=qg(t,r);return e.symbolName&&i.push(e.symbolName),Yg([...o,...i],o)}function aR(n,e){let t=Kg(n.bodyParts),r=n.sectionTitle.trim(),o=ui(r),i=_g(n.bodyParts),s=Fg(r,i,o),a=Qg(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}=ZD(t,r);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:e.docTitle,sectionTitle:r,titleTokens:c,headingsText:s,apiSymbols:sR(r,o,l,n.codeBlocks),bodySample:t,leadText:d,excerptTruncated:h}}function ey(n,e){for(let t of n){if(t.type==="heading"){let o=Ma(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)){ey(t.children,e);continue}let r=Fa(Ma(t));r&&e.bodyParts.push(r)}}function cR(n){let e=Wg().use(Gg).use(zg).parse(n),t={headings:[],bodyParts:[],codeBlocks:[]};return ey(e.children,t),t}function lR(n,e){let t=cR(n),r=e.docTitle?.trim()||e.documentId,o=Kg(t.bodyParts),i=[r,...t.headings,o].join(" "),{leadText:s,excerptTruncated:a}=Xg(o);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:r,sectionTitle:"",titleTokens:r,headingsText:XD(t.headings),apiSymbols:Yg(qg(i,t.codeBlocks)),bodySample:o,leadText:s,excerptTruncated:a}}function ty(n,e){let t=e.docTitle?.trim()||e.documentId,r=QD(n);return oR(n,r,e.documentId)?rR(r).filter(o=>o.sectionTitle||o.bodyParts.length>0||o.codeBlocks.length>0).map(o=>aR(o,{...e,docTitle:t})):[lR(n,{...e,docTitle:t})]}async function dR(n){let e=[];async function t(r){let o=await be.promises.readdir(r,{withFileTypes:!0});for(let i of o){if(i.name.startsWith("."))continue;let s=Me.join(r,i.name);i.isDirectory()?await t(s):i.isFile()&&i.name.endsWith(".md")&&e.push(s)}}return await t(n),e}function uR(n,e){let t=Me.relative(e,n).split(Me.sep).join("/").split("/");if(t[0]==="docs"&&(t=t.slice(1)),t.length<2)return null;let r=t[0],o=Ih[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 pR(n){let e=n.replace(/\.md$/,".json");try{let t=await be.promises.readFile(e,"utf-8");return JSON.parse(t).title?.trim()||void 0}catch{return}}async function fR(n,e){let t=uR(n,e);if(!t)return[];let r=await be.promises.readFile(n,"utf-8"),o=Vg(r,{jsonTitle:await pR(n),fileName:t.docTitle});return ty(r,{...t,docTitle:o})}async function mR(n,e,t){let r=Me.join(e,"search.db");return await Og(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 hR(n){let e=await dR(n),t=[];for(let r of e){let o=await fR(r,n);t.push(...o)}return t}function gR(n,e){return{indexVersion:Fr,docsZipSha256:n.docsZipSha256,termsHash:n.termsHash,synonymsHash:n.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:n.builtBy}}async function ry(n){n.lexiconDir&&Jl(n.lexiconDir);try{let e=await hR(n.docsDir);await n.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await be.promises.mkdir(n.tmpDir,{recursive:!0});let t=await mR(e,n.tmpDir,n.onProgress),r=gR(n,t);return await be.promises.writeFile(Me.join(n.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await Fh(n.tmpDir),r}finally{n.lexiconDir&&Jl(null)}}async function oy(){return be.promises.mkdtemp(Me.join(ny.tmpdir(),"deveco-docs-"))}async function yR(n,e){try{await be.promises.rename(n,e)}catch(t){let r=t.code;if(r!=="EPERM"&&r!=="EXDEV")throw t;await be.promises.cp(n,e,{recursive:!0}),await be.promises.rm(n,{recursive:!0,force:!0})}}async function iy(n){let e=Me.join(n,"docs");try{await be.promises.access(e)}catch{return}let t=new Set(["docs","docs.zip"]);for(let r of await be.promises.readdir(e,{withFileTypes:!0})){if(t.has(r.name))continue;let o=Me.join(e,r.name),i=Me.join(n,r.name);await be.promises.rm(i,{recursive:!0,force:!0}),await yR(o,i)}await be.promises.rm(Me.join(e,"docs"),{recursive:!0,force:!0}),await be.promises.rm(Me.join(e,"docs.zip"),{force:!0}),await be.promises.rm(e,{recursive:!0,force:!0})}var fi=class extends Error{constructor(e){super(e),this.name="NativeDepsError"}};function wR(){let n=Br(),e=Z();return["Documentation search index is not installed yet.","",...pa(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(`
1372
+ `)}function vR(){let n=Br();return[`Chinese tokenizer (${b()?"jieba-wasm":"@node-rs/jieba"}) failed to load.`,"",`Node.js: ${process.version} (required: >=18)`,"",...pa(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(`
1373
+ `)}function SR(n){let e=Br();return[n,"",...pa(e)].join(`
1374
+ `)}async function sy(){try{Mh()}catch(n){throw Oh(n)?new fi(`${wR()}
1375
1375
 
1376
- Detail: ${n.message}`):n}try{await hn()}catch(n){let e=n instanceof Error?n.message:String(n);throw new ui(`${wR()}
1376
+ Detail: ${n.message}`):n}try{await yn()}catch(n){let e=n instanceof Error?n.message:String(n);throw new fi(`${vR()}
1377
1377
 
1378
- Detail: ${e}`)}try{await ci()}catch(n){let e=n instanceof Error?n.message:String(n);throw new ui(vR(e))}}var Id=class extends Error{constructor(t,r){super(r);this.code=t;this.name="DocNotReadyError"}code};function ER(n){return new Promise(e=>setTimeout(e,n))}async function ly(n){let e=Hr();await ne.promises.mkdir(St.dirname(e),{recursive:!0}),await ne.promises.appendFile(e,`${new Date().toISOString()} ${n}
1379
- `)}async function PR(n){let e=fn();if(!e)throw new Error("docs.zip not found");await ne.promises.rm(n,{recursive:!0,force:!0}),await ne.promises.mkdir(n,{recursive:!0});let t=St.resolve(n),r=new SR(e);for(let o of r.getEntries()){let i=St.resolve(t,o.entryName);if(!eo(i,t))throw new Error(`Unsafe docs.zip entry path: ${o.entryName}`);if(o.isDirectory){await ne.promises.mkdir(i,{recursive:!0});continue}await ne.promises.mkdir(St.dirname(i),{recursive:!0}),await ne.promises.writeFile(i,o.getData())}await oy(n)}async function CR(){await $r({mode:"write"});let n=Z(),e=jt(),t=await ne.promises.readdir(e);for(let r of t){let o=St.join(n,r);await ne.promises.rm(o,{force:!0}),await ne.promises.rename(St.join(e,r),o)}await ne.promises.rm(e,{recursive:!0,force:!0}),await ne.promises.rm(St.join(n,"orama.dpack"),{force:!0})}async function sy(n,e,t){e?.start(t),await mn({state:"installing",phase:1,phaseLabel:"Installing index",message:t}),await Wh(n),zr(),e&&(e.text="Documentation index installed.")}async function IR(n,e){try{return await sy(n,e,"Installing documentation index\u2026"),await Ad(e),!0}catch(t){if(Zo(t))throw t}try{return await Gh(),zr(),await sy(n,e,"Retrying documentation index install\u2026"),await Ad(e),!0}catch(t){if(Zo(t))throw t;let r=t instanceof Error?t.message:String(t);return await ly(`Bundled index install failed; falling back to local rebuild: ${r}`),!1}}async function AR(n,e,t){let r=jt(),o=await ry();await ne.promises.mkdir(Z(),{recursive:!0}),await ne.promises.rm(r,{recursive:!0,force:!0}),t?.start("Building search index\u2026"),await mn({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"});try{await PR(o),await ny({docsDir:o,tmpDir:r,docsZipSha256:e,termsHash:va(),synonymsHash:wa(),builtBy:n.builtBy??"doc-init",onProgress:async i=>{t&&(t.text=i.message),await mn({state:"indexing",current:i.current,total:i.total,message:i.message})}})}finally{await ne.promises.rm(o,{recursive:!0,force:!0})}await mn({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await CR(),zr()}async function Ad(n){await mn({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function DR(n){let e=await od(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";n?.succeed(t),await mn({state:"done",message:t,error:null})}async function RR(n,e){let t=n instanceof Error?n.message:String(n);throw await mn({state:"error",error:t}),await ly(`ERROR: ${t}`),e?.fail(t),n}async function TR(){let n=Z();await ne.promises.mkdir(n,{recursive:!0});let e=pa();return ne.existsSync(e)||await ne.promises.writeFile(e,"","utf-8"),e}async function kR(){let n=await TR();return bR.lock(n,{stale:1800*1e3})}async function xR(){let n=fn(),e=(n?await ya(n):null)??await rd();if(!e)throw new Error("docs.zip not found");return e}async function NR(n,e){let t=await xR(),r=n.force||await id(n.force),o=await ba(n.force);if(!r&&!o&&ti()){await DR(e);return}!n.force&&Bh(t)&&await IR(t,e)||(await AR(n,t,e),await Ad(e))}var pi=class{static async run(e={}){let t=e.background??!1,o=e.quiet??t?void 0:cy({text:"Checking documentation\u2026",color:"cyan"}),i;try{e.assumeStorageSafe||await $r({mode:"write"}),i=await kR(),await nd(Yh("Starting documentation setup\u2026")),await NR(e,o)}catch(s){throw i&&await RR(s,o),s}finally{i&&await i()}}};async function LR(n){for(;;){let e=await Sa();if(e.state==="done"&&ti())return;if(e.state==="error")throw new Id("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 ER(500)}}async function ay(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await pi.run({builtBy:"doc-init",force:e,quiet:!0})}async function OR(){let n=await ba()!==null;if(ti()&&!n)return;let e=cy({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await Kh()){await LR(e),e.succeed("Documentation ready.");return}if(await id()){await ay(e),e.succeed("Documentation ready.");return}await ay(e,!0),e.succeed("Documentation ready.")}catch(t){throw e.fail(t.message),t}}async function fi(){await $r({mode:"read"}),await OR(),await iy()}function MR(n){let e=n instanceof Error?n.message:String(n);return/file is not a database|database disk image is malformed|SQLITE_CORRUPT/i.test(e)}var Dd=class{async search(e,t,r=20){await fi();try{return await Pd(e,t,r)}catch(o){if(!MR(o))throw o;return zr(),await pi.run({builtBy:"doc-init",force:!0,quiet:!0,assumeStorageSafe:!0}),Pd(e,t,r)}}async readDocument(e){return await fi(),Hh(e)}},Rd=new Dd;function dy(...n){return e=>{if(!n.includes(e))throw new Td(`Allowed values: ${n.join(", ")}`);return e}}function jR(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new Td("Must be a positive integer.");return e}var HR=dy("json","default"),$R=dy("json","default");function kd(n){let e=n instanceof Error?n.message:String(n);return Zo(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 ja=new _R("docs").description("Search and read HarmonyOS documentation from local docs directory");ja.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",BR,"all").option("--format <fmt>","Output format (default, json)",HR,"default").option("--limit <n>","Max number of results",jR,20).action(async(n,e)=>{try{let t=UR(n),r=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=await Rd.search(t,r,e.limit);e.format==="json"?console.log(JSON.stringify(o,null,2)):WR(o)}catch(t){console.error(Fa(kd(t))),process.exit(1)}});ja.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{try{let e=n.trim();e||(console.error(Fa("Document ID cannot be empty.")),process.exit(1));let t=await Rd.readDocument(e);console.log(t)}catch(e){console.error(Fa(kd(e))),process.exit(1)}});ja.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",$R,"default").action(async n=>{try{if(await fi(),n.format==="json"){let e=dn.map(t=>({name:t,title:Gn[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of dn)console.log(` ${e.padEnd(20)} ${FR(Gn[e])}`)}catch(e){console.error(Fa(kd(e))),process.exit(1)}});function UR(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>zo)throw new Error(`Query exceeds ${zo} characters.`);return e}function BR(n){if(n==="all")return"all";if(!dn.includes(n))throw new Td(`Invalid catalog "${n}". Allowed: all, ${dn.join(", ")}`);return n}function WR(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 uy=ja;import{Command as GT}from"commander";import{Command as tT,InvalidArgumentError as nT,Option as Nd}from"commander";import{readFileSync as zR,unlinkSync as qR}from"fs";import{tmpdir as VR}from"os";import{join as JR}from"path";var Bt=class{constructor(e,t){this.hdcPath=e;this.serial=t}hdcPath;serial;async listWindows(e){let t=await this.fetchDump(),r=GR(t);return e?.all||(r=r.filter(o=>o.type===1)),r}async fetchDump(){let e=["-t",this.serial,"shell","hidumper","-s","WindowManagerService","-a","-a"];m(`Executing: ${this.hdcPath} ${e.join(" ")}`);let t=await se(this.hdcPath,e);if(t.exitCode!==0)throw new Error(`Failed to query windows: ${(t.stderr||t.stdout).trim()}`);return t.stdout}};function GR(n){let e=n.split(`
1380
- `),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]),S=Number(c[4]);Number.isFinite(w)&&Number.isFinite(d)&&Number.isFinite(h)&&r.push({id:w,name:l,pid:h,displayId:d,type:S})}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 py(n){if(!(!n||n==="HitTestMode.Default"))return n.startsWith("HitTestMode.")?n.slice(12):n}function mi(n){if(!(n==null||n==="")){if(typeof n=="boolean")return n;if(n==="true")return!0;if(n==="false")return!1}}function fy(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 my(n){return n.originalText||void 0}function qr(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 hy(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:"#";m(`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 YR(n){let e=zR(n,"utf-8").trim();if(!e)throw new Error("Empty dumpLayout response from device");return JSON.parse(e)}function KR(n){return n.attributes??{}}function Ha(n,e,t){let r=KR(n),o={id:r.id||void 0,type:r.type||void 0,text:my(r),bounds:fy(r.bounds),clickable:mi(r.clickable)||void 0,longClickable:mi(r.longClickable)||void 0,scrollable:mi(r.scrollable)||void 0,checkable:mi(r.checkable)||void 0,hitTestBehavior:py(r.hitTestBehavior),children:[]};return e>0&&t+1>=e||n.children&&(o.children=n.children.map(i=>Ha(i,e,t+1))),o}function XR(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 Yn=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),m(`Executing: ${this.hdcPath} ${i.join(" ")}`);let s=await se(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=JR(VR(),`deveco_cli_dump_${Date.now()}_${process.pid}.json`);try{return await this.recvDumpFile(e,t,r),YR(r)}finally{await this.cleanupDumpArtifacts(e,r,t)}}async recvDumpFile(e,t,r){let o=["-t",e,"file","recv",t,r];m(`Executing: ${this.hdcPath} ${o.join(" ")}`);let i=await se(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{m(`Removing local dump file: ${t}`),qR(t)}catch(i){m(`Failed to clean local dump file ${t}: ${i.message}`)}let o=["-t",e,"shell","rm","-f",r];m(`Executing: ${this.hdcPath} ${o.join(" ")}`),await se(this.hdcPath,o).catch(i=>{m(`Failed to clean remote dump file ${r}: ${i.message}`)})}async dumpRawNodes(e,t,r){let i=await new Bt(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=XR(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=>Ha(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:Ha(s,t,0)})}return o}async dumpCollapsedTree(e,t,r,o){return(await this.dumpRawNodes(e,r,o)).flatMap(s=>hy(Ha(s,0,0),t))}};var $a={left:"0",right:"1",up:"2",down:"3"};function Ae(n,e){let t=Number(n);if(!Number.isInteger(t)||t<=0)throw new Error(`${e} must be a positive integer`)}function xd(n,e){n!==void 0&&Ae(n,e)}function gy(n,e){if(n===void 0!=(e===void 0))throw new Error("x and y must be provided together")}function Ua(n,e){if(n!==void 0&&n.length===0)throw new Error(`${e} must not be empty`)}function hi(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 yy(n){if(n!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(n))throw new Error("--window must consist of letters, digits, - or _")}function wy(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 Vr(n,e,t,r,o=!0){gy(n,e),Ua(t,"--id"),xd(n,"x"),xd(e,"y"),yy(r),wy(n!==void 0,!!t,!!r,o)}async function yn(n,e){let r=await new wr(n).selectDevice(e);if(!r)throw new Error("No device selected. Use `devecocli device list` to see targets.");return r}async function bt(n){let e=await A.new(),t=await yn(e,n);return{hdcPath:e.hdcPath,deviceId:t}}async function Jr(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 Bt(n,e).listWindows({all:!0}),c=new Yn(n);return ZR(c,e,a,o,i)}async function ZR(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 eT(s,r)}return QR(n,e,t,r)}async function QR(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 qr([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 vy(s[0].node,r)}function eT(n,e){let t=qr(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 vy(t[0],e)}function vy(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],o=await se(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 rT from"ora";function oT(n){let e=parseInt(n,10);if(!Number.isInteger(e)||e<0||String(e)!==n.trim())throw new nT("depth must be a non-negative integer");return e}function iT(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 Sy(n,e=0){let t=[],r=" ".repeat(e);for(let o of n)t.push(`${r}${iT(o)}`),o.children.length>0&&t.push(...Sy(o.children,e+1).split(`
1378
+ Detail: ${e}`)}try{await di()}catch(n){let e=n instanceof Error?n.message:String(n);throw new fi(SR(e))}}var Ad=class extends Error{constructor(t,r){super(r);this.code=t;this.name="DocNotReadyError"}code};function PR(n){return new Promise(e=>setTimeout(e,n))}async function dy(n){let e=Br();await ne.promises.mkdir(Et.dirname(e),{recursive:!0}),await ne.promises.appendFile(e,`${new Date().toISOString()} ${n}
1379
+ `)}async function CR(n){let e=hn();if(!e)throw new Error("docs.zip not found");await ne.promises.rm(n,{recursive:!0,force:!0}),await ne.promises.mkdir(n,{recursive:!0});let t=Et.resolve(n),r=new bR(e);for(let o of r.getEntries()){let i=Et.resolve(t,o.entryName);if(!ro(i,t))throw new Error(`Unsafe docs.zip entry path: ${o.entryName}`);if(o.isDirectory){await ne.promises.mkdir(i,{recursive:!0});continue}await ne.promises.mkdir(Et.dirname(i),{recursive:!0}),await ne.promises.writeFile(i,o.getData())}await iy(n)}async function IR(){await Wr({mode:"write"});let n=Z(),e=Ut(),t=await ne.promises.readdir(e);for(let r of t){let o=Et.join(n,r);await ne.promises.rm(o,{force:!0}),await ne.promises.rename(Et.join(e,r),o)}await ne.promises.rm(e,{recursive:!0,force:!0}),await ne.promises.rm(Et.join(n,"orama.dpack"),{force:!0})}async function ay(n,e,t){e?.start(t),await gn({state:"installing",phase:1,phaseLabel:"Installing index",message:t}),await Gh(n),Jr(),e&&(e.text="Documentation index installed.")}async function AR(n,e){try{return await ay(n,e,"Installing documentation index\u2026"),await Dd(e),!0}catch(t){if(ei(t))throw t}try{return await zh(),Jr(),await ay(n,e,"Retrying documentation index install\u2026"),await Dd(e),!0}catch(t){if(ei(t))throw t;let r=t instanceof Error?t.message:String(t);return await dy(`Bundled index install failed; falling back to local rebuild: ${r}`),!1}}async function DR(n,e,t){let r=Ut(),o=await oy();await ne.promises.mkdir(Z(),{recursive:!0}),await ne.promises.rm(r,{recursive:!0,force:!0}),t?.start("Building search index\u2026"),await gn({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"});try{await CR(o),await ry({docsDir:o,tmpDir:r,docsZipSha256:e,termsHash:Sa(),synonymsHash:va(),builtBy:n.builtBy??"doc-init",onProgress:async i=>{t&&(t.text=i.message),await gn({state:"indexing",current:i.current,total:i.total,message:i.message})}})}finally{await ne.promises.rm(o,{recursive:!0,force:!0})}await gn({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await IR(),Jr()}async function Dd(n){await gn({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function RR(n){let e=await id(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";n?.succeed(t),await gn({state:"done",message:t,error:null})}async function TR(n,e){let t=n instanceof Error?n.message:String(n);throw await gn({state:"error",error:t}),await dy(`ERROR: ${t}`),e?.fail(t),n}async function kR(){let n=Z();await ne.promises.mkdir(n,{recursive:!0});let e=fa();return ne.existsSync(e)||await ne.promises.writeFile(e,"","utf-8"),e}async function xR(){let n=await kR();return ER.lock(n,{stale:1800*1e3})}async function NR(){let n=hn(),e=(n?await wa(n):null)??await od();if(!e)throw new Error("docs.zip not found");return e}async function LR(n,e){let t=await NR(),r=n.force||await sd(n.force),o=await Ea(n.force);if(!r&&!o&&ri()){await RR(e);return}!n.force&&Wh(t)&&await AR(t,e)||(await DR(n,t,e),await Dd(e))}var mi=class{static async run(e={}){let t=e.background??!1,o=e.quiet??t?void 0:ly({text:"Checking documentation\u2026",color:"cyan"}),i;try{e.assumeStorageSafe||await Wr({mode:"write"}),i=await xR(),await rd(Kh("Starting documentation setup\u2026")),await LR(e,o)}catch(s){throw i&&await TR(s,o),s}finally{i&&await i()}}};async function OR(n){for(;;){let e=await ba();if(e.state==="done"&&ri())return;if(e.state==="error")throw new Ad("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 PR(500)}}async function cy(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await mi.run({builtBy:"doc-init",force:e,quiet:!0})}async function MR(){let n=await Ea()!==null;if(ri()&&!n)return;let e=ly({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await Xh()){await OR(e),e.succeed("Documentation ready.");return}if(await sd()){await cy(e),e.succeed("Documentation ready.");return}await cy(e,!0),e.succeed("Documentation ready.")}catch(t){throw e.fail(t.message),t}}async function hi(){await Wr({mode:"read"}),await MR(),await sy()}function _R(n){let e=n instanceof Error?n.message:String(n);return/file is not a database|database disk image is malformed|SQLITE_CORRUPT/i.test(e)}var Rd=class{async search(e,t,r=20){await hi();try{return await Cd(e,t,r)}catch(o){if(!_R(o))throw o;return Jr(),await mi.run({builtBy:"doc-init",force:!0,quiet:!0,assumeStorageSafe:!0}),Cd(e,t,r)}}async readDocument(e){return await hi(),$h(e)}},Td=new Rd;function uy(...n){return e=>{if(!n.includes(e))throw new kd(`Allowed values: ${n.join(", ")}`);return e}}function HR(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new kd("Must be a positive integer.");return e}var $R=uy("json","default"),UR=uy("json","default");function xd(n){let e=n instanceof Error?n.message:String(n);return ei(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 Ha=new FR("docs").description("Search and read HarmonyOS documentation from local docs directory");Ha.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",WR,"all").option("--format <fmt>","Output format (default, json)",$R,"default").option("--limit <n>","Max number of results",HR,20).action(async(n,e)=>{try{let t=BR(n),r=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=await Td.search(t,r,e.limit);e.format==="json"?console.log(JSON.stringify(o,null,2)):GR(o)}catch(t){console.error(ja(xd(t))),process.exit(1)}});Ha.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{try{let e=n.trim();e||(console.error(ja("Document ID cannot be empty.")),process.exit(1));let t=await Td.readDocument(e);console.log(t)}catch(e){console.error(ja(xd(e))),process.exit(1)}});Ha.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",UR,"default").action(async n=>{try{if(await hi(),n.format==="json"){let e=pn.map(t=>({name:t,title:zn[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of pn)console.log(` ${e.padEnd(20)} ${jR(zn[e])}`)}catch(e){console.error(ja(xd(e))),process.exit(1)}});function BR(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>Vo)throw new Error(`Query exceeds ${Vo} characters.`);return e}function WR(n){if(n==="all")return"all";if(!pn.includes(n))throw new kd(`Invalid catalog "${n}". Allowed: all, ${pn.join(", ")}`);return n}function GR(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 py=Ha;import{Command as zT}from"commander";import{Command as nT,InvalidArgumentError as rT,Option as Ld}from"commander";import{readFileSync as qR,unlinkSync as VR}from"fs";import{tmpdir as JR}from"os";import{join as YR}from"path";var zt=class{constructor(e,t){this.hdcPath=e;this.serial=t}hdcPath;serial;async listWindows(e){let t=await this.fetchDump(),r=zR(t);return e?.all||(r=r.filter(o=>o.type===1)),r}async fetchDump(){let e=["-t",this.serial,"shell","hidumper","-s","WindowManagerService","-a","-a"];m(`Executing: ${this.hdcPath} ${e.join(" ")}`);let t=await se(this.hdcPath,e);if(t.exitCode!==0)throw new Error(`Failed to query windows: ${(t.stderr||t.stdout).trim()}`);return t.stdout}};function zR(n){let e=n.split(`
1380
+ `),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]),S=Number(c[4]);Number.isFinite(w)&&Number.isFinite(d)&&Number.isFinite(h)&&r.push({id:w,name:l,pid:h,displayId:d,type:S})}let o=e.find(s=>s.trim().startsWith("Focus window")),i=o?Number(o.replace(/.*:\s*/,"").trim()):NaN;return r.map(s=>({...s,focused:s.id===i}))}function fy(n){if(!(!n||n==="HitTestMode.Default"))return n.startsWith("HitTestMode.")?n.slice(12):n}function gi(n){if(!(n==null||n==="")){if(typeof n=="boolean")return n;if(n==="true")return!0;if(n==="false")return!1}}function my(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 hy(n){return n.originalText||void 0}function Yr(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 gy(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:"#";m(`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 KR(n){let e=qR(n,"utf-8").trim();if(!e)throw new Error("Empty dumpLayout response from device");return JSON.parse(e)}function XR(n){return n.attributes??{}}function $a(n,e,t){let r=XR(n),o={id:r.id||void 0,type:r.type||void 0,text:hy(r),bounds:my(r.bounds),clickable:gi(r.clickable)||void 0,longClickable:gi(r.longClickable)||void 0,scrollable:gi(r.scrollable)||void 0,checkable:gi(r.checkable)||void 0,hitTestBehavior:fy(r.hitTestBehavior),children:[]};return e>0&&t+1>=e||n.children&&(o.children=n.children.map(i=>$a(i,e,t+1))),o}function ZR(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 Kn=class{hdcPath;constructor(e){this.hdcPath=e}buildRemoteDumpPath(){return`/data/local/tmp/deveco_cli_dump_${Date.now()}_${process.pid}.json`}async fetchRawDump(e,t,r){let o=this.buildRemoteDumpPath(),i=["-t",e,"shell","uitest","dumpLayout","-p",o];r!==void 0&&i.push("-d",String(r)),t&&i.push("-w",t),m(`Executing: ${this.hdcPath} ${i.join(" ")}`);let s=await se(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=YR(JR(),`deveco_cli_dump_${Date.now()}_${process.pid}.json`);try{return await this.recvDumpFile(e,t,r),KR(r)}finally{await this.cleanupDumpArtifacts(e,r,t)}}async recvDumpFile(e,t,r){let o=["-t",e,"file","recv",t,r];m(`Executing: ${this.hdcPath} ${o.join(" ")}`);let i=await se(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{m(`Removing local dump file: ${t}`),VR(t)}catch(i){m(`Failed to clean local dump file ${t}: ${i.message}`)}let o=["-t",e,"shell","rm","-f",r];m(`Executing: ${this.hdcPath} ${o.join(" ")}`),await se(this.hdcPath,o).catch(i=>{m(`Failed to clean remote dump file ${r}: ${i.message}`)})}async dumpRawNodes(e,t,r){let i=await new zt(this.hdcPath,e).listWindows({all:!0});if(r){let a=[...new Set(i.map(l=>l.displayId))],c=[];for(let l of a)c.push(await this.fetchRawDump(e,void 0,l));return c}let s=ZR(i,t);return[await this.fetchRawDump(e,String(s.id),s.displayId)]}async dumpFullTree(e,t,r,o){return(await this.dumpRawNodes(e,r,o)).map(s=>$a(s,t,0))}async dumpFullTreeByDisplays(e,t,r){let o=[];for(let i of r){let s=await this.fetchRawDump(e,void 0,i);o.push({displayId:i,tree:$a(s,t,0)})}return o}async dumpCollapsedTree(e,t,r,o){return(await this.dumpRawNodes(e,r,o)).flatMap(s=>gy($a(s,0,0),t))}};var Ua={left:"0",right:"1",up:"2",down:"3"};function De(n,e){let t=Number(n);if(!Number.isInteger(t)||t<=0)throw new Error(`${e} must be a positive integer`)}function Nd(n,e){n!==void 0&&De(n,e)}function yy(n,e){if(n===void 0!=(e===void 0))throw new Error("x and y must be provided together")}function Ba(n,e){if(n!==void 0&&n.length===0)throw new Error(`${e} must not be empty`)}function yi(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 wy(n){if(n!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(n))throw new Error("--window must consist of letters, digits, - or _")}function vy(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 Kr(n,e,t,r,o=!0){yy(n,e),Ba(t,"--id"),Nd(n,"x"),Nd(e,"y"),wy(r),vy(n!==void 0,!!t,!!r,o)}async function vn(n,e){let r=await new Sr(n).selectDevice(e);if(!r)throw new Error("No device selected. Use `devecocli device list` to see targets.");return r}async function Pt(n){let e=await I.new(),t=await vn(e,n);return{hdcPath:e.hdcPath,deviceId:t}}async function Xr(n,e,t,r,o,i){if(t!==void 0&&r!==void 0)return{x:t,y:r};if(o===void 0)throw new Error("Either provide x y coordinates or use --id");let a=await new zt(n,e).listWindows({all:!0}),c=new Kn(n);return QR(c,e,a,o,i)}async function QR(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 tT(s,r)}return eT(n,e,t,r)}async function eT(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 Yr([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 Sy(s[0].node,r)}function tT(n,e){let t=Yr(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 Sy(t[0],e)}function Sy(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],o=await se(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 oT from"ora";function iT(n){let e=parseInt(n,10);if(!Number.isInteger(e)||e<0||String(e)!==n.trim())throw new rT("depth must be a non-negative integer");return e}function sT(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 by(n,e=0){let t=[],r=" ".repeat(e);for(let o of n)t.push(`${r}${sT(o)}`),o.children.length>0&&t.push(...by(o.children,e+1).split(`
1381
1381
  `));return t.join(`
1382
- `)}function sT(n){if(n.allWindows&&n.window)throw new Error("--all-windows and --window are mutually exclusive.")}function aT(n,e){let t=qr(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 cT(n,e){console.log(e==="json"?JSON.stringify(n,null,2):Sy(n))}async function lT(n){sT(n);let e=rT({text:"Dumping layout\u2026",color:"cyan"}).start(),t;try{let r=await A.new(),o=await yn(r,n.device),i=new Yn(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){aT(t,n.id);return}cT(t,n.format)}var by=new tT("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 Nd("--depth <n>","Tree depth limit (0=unlimited, 1=root only, 2=root+children)").argParser(oT).default(0)).addOption(new Nd("--format <format>","Output format").choices(["default","json"]).default("default")).addOption(new Nd("--mode <mode>","Output mode: full | simplified").choices(["full","simplified"]).default("simplified")).action(async n=>{await lT(n)});import{Command as dT,Option as uT}from"commander";import{yellow as pT}from"colorette";import fT from"ora";var mT=["Id","Name","Pid","DisplayId","Focused"];function hT(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(xt(mT,t))}async function gT(n){let e=fT({text:"Listing windows\u2026",color:"cyan"}).start(),t;try{let r=await A.new(),o=await yn(r,n.device);t=await new Bt(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(pT(" No windows found."));return}hT(t,n.format)}var Ld=new dT("window").description("Manage device windows");Ld.command("list").description("List windows on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new uT("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show all windows including system windows").action(async n=>{await gT(n)});import{Command as yT}from"commander";import Oe from"fs";import et from"path";import{randomUUID as wT}from"crypto";import{green as vT}from"colorette";function ST(){return String(Date.now())}function Ey(n){let e;try{e=Oe.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{Oe.accessSync(n,Oe.constants.W_OK|Oe.constants.X_OK)}catch(t){throw new Error(`Screenshot directory is not writable: ${n}`,{cause:t})}}function Py(n,e){try{throw Oe.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 bT(n){if(!n?.trim())throw new Error("--path is required.");let e=n.trim(),t=et.resolve(e);try{if(Oe.statSync(t).isDirectory()){Ey(t);let o=et.join(t,`screenshot-${ST()}.png`);return Py(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 Ey(r),Py(t,r),t}function Cy(n){if(!Oe.existsSync(n))throw new Error(`Screenshot file was not created: ${n}`);let e=Oe.statSync(n);if(!e.isFile()||e.size===0)throw new Error(`Screenshot file is empty: ${n}`);let t=Oe.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 ET(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 PT(n){let e=n.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}function CT(n,e){try{Oe.copyFileSync(n,e,Oe.constants.COPYFILE_EXCL)}catch(t){throw t.code==="EEXIST"?new Error(`Screenshot file already exists: ${e}`,{cause:t}):t}Cy(e)}function IT(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 AT(n){let e=["-t",n.serial,"shell","ls","-l",n.remotePath];m(`Executing: ${n.hdcPath} ${e.join(" ")}`);let t=await se(n.hdcPath,e);return t.exitCode===0?IT(t.stdout):void 0}function DT(n){return[n.stdout,n.stderr].filter(Boolean).join(`
1383
- `).trim()}function RT(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 TT(n,e){let t=ET(n,e);m(`Executing: ${n.hdcPath} ${t.join(" ")}`);let r=await se(n.hdcPath,t),o=await AT(n);return{created:o!==void 0&&o>0,output:DT(r)}}async function kT(n){let e="";for(let t of[void 0,"png"]){let r=await TT(n,t);if(r.created)return;if(n.display!==void 0&&RT(r.output))throw new Error(`Screenshot was not created on device: ${n.remotePath}.
1382
+ `)}function aT(n){if(n.allWindows&&n.window)throw new Error("--all-windows and --window are mutually exclusive.")}function cT(n,e){let t=Yr(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 lT(n,e){console.log(e==="json"?JSON.stringify(n,null,2):by(n))}async function dT(n){aT(n);let e=oT({text:"Dumping layout\u2026",color:"cyan"}).start(),t;try{let r=await I.new(),o=await vn(r,n.device),i=new Kn(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){cT(t,n.id);return}lT(t,n.format)}var Ey=new nT("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 Ld("--depth <n>","Tree depth limit (0=unlimited, 1=root only, 2=root+children)").argParser(iT).default(0)).addOption(new Ld("--format <format>","Output format").choices(["default","json"]).default("default")).addOption(new Ld("--mode <mode>","Output mode: full | simplified").choices(["full","simplified"]).default("simplified")).action(async n=>{await dT(n)});import{Command as uT,Option as pT}from"commander";import{yellow as fT}from"colorette";import mT from"ora";var hT=["Id","Name","Pid","DisplayId","Focused"];function gT(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(Lt(hT,t))}async function yT(n){let e=mT({text:"Listing windows\u2026",color:"cyan"}).start(),t;try{let r=await I.new(),o=await vn(r,n.device);t=await new zt(r.hdcPath,o).listWindows({all:n.all})}catch(r){throw e.stop(),new Error(`Failed to list windows: ${r.message}`,{cause:r})}if(e.stop(),t.length===0){console.log(fT(" No windows found."));return}gT(t,n.format)}var Od=new uT("window").description("Manage device windows");Od.command("list").description("List windows on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new pT("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show all windows including system windows").action(async n=>{await yT(n)});import{Command as wT}from"commander";import _e from"fs";import et from"path";import{randomUUID as vT}from"crypto";import{green as ST}from"colorette";function bT(){return String(Date.now())}function Py(n){let e;try{e=_e.statSync(n)}catch(t){let r=t.code;throw r==="ENOENT"?new Error(`Screenshot directory does not exist: ${n}`,{cause:t}):r==="EACCES"||r==="EPERM"?new Error(`Screenshot directory is not writable: ${n}`,{cause:t}):new Error(`Invalid screenshot path: ${t.message}${r?` (${r})`:""}`,{cause:t})}if(!e.isDirectory())throw new Error(`Screenshot parent path is not a directory: ${n}`);try{_e.accessSync(n,_e.constants.W_OK|_e.constants.X_OK)}catch(t){throw new Error(`Screenshot directory is not writable: ${n}`,{cause:t})}}function Cy(n,e){try{throw _e.lstatSync(n),new Error(`Screenshot file already exists: ${n}`)}catch(t){let r=t.code;if(r==="ENOENT")return;throw r==="EACCES"||r==="EPERM"?new Error(`Screenshot directory is not writable: ${e}`,{cause:t}):t instanceof Error&&!r?t:new Error(`Invalid screenshot path: ${t.message}${r?` (${r})`:""}`,{cause:t})}}function ET(n){if(!n?.trim())throw new Error("--path is required.");let e=n.trim(),t=et.resolve(e);try{if(_e.statSync(t).isDirectory()){Py(t);let o=et.join(t,`screenshot-${bT()}.png`);return Cy(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 Py(r),Cy(t,r),t}function Iy(n){if(!_e.existsSync(n))throw new Error(`Screenshot file was not created: ${n}`);let e=_e.statSync(n);if(!e.isFile()||e.size===0)throw new Error(`Screenshot file is empty: ${n}`);let t=_e.readFileSync(n).subarray(0,8),r=Buffer.from([137,80,78,71,13,10,26,10]);if(!t.equals(r))throw new Error(`Screenshot file is not a valid PNG: ${n}`)}function PT(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 CT(n){let e=n.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}function IT(n,e){try{_e.copyFileSync(n,e,_e.constants.COPYFILE_EXCL)}catch(t){throw t.code==="EEXIST"?new Error(`Screenshot file already exists: ${e}`,{cause:t}):t}Iy(e)}function AT(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 DT(n){let e=["-t",n.serial,"shell","ls","-l",n.remotePath];m(`Executing: ${n.hdcPath} ${e.join(" ")}`);let t=await se(n.hdcPath,e);return t.exitCode===0?AT(t.stdout):void 0}function RT(n){return[n.stdout,n.stderr].filter(Boolean).join(`
1383
+ `).trim()}function TT(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 kT(n,e){let t=PT(n,e);m(`Executing: ${n.hdcPath} ${t.join(" ")}`);let r=await se(n.hdcPath,t),o=await DT(n);return{created:o!==void 0&&o>0,output:RT(r)}}async function xT(n){let e="";for(let t of[void 0,"png"]){let r=await kT(n,t);if(r.created)return;if(n.display!==void 0&&TT(r.output))throw new Error(`Screenshot was not created on device: ${n.remotePath}.
1384
1384
  snapshot_display output:
1385
1385
  ${r.output}`);r.output&&(e=r.output)}throw new Error(e?`Screenshot was not created on device: ${n.remotePath}.
1386
1386
  snapshot_display output:
1387
- ${e}`:`Screenshot was not created on device: ${n.remotePath}.`)}function Iy(n){try{return Cy(n),!0}catch{return!1}}function Ay(n){let e=[];for(let t of Oe.readdirSync(n,{withFileTypes:!0})){let r=et.join(n,t.name);if(t.isDirectory()){e.push(...Ay(r));continue}t.isFile()&&Iy(r)&&e.push(r)}return e}function xT(n,e){let t=et.join(n,et.basename(e));if(Iy(t))return t;let r=Ay(n);if(r.length===1)return r[0];if(r.length>1)throw new Error(`Multiple screenshot files were received in ${n}.`)}async function Od(n,e,t){let r=["-t",n.serial,"file","recv",n.remotePath,t];m(`Executing: ${n.hdcPath} ${r.join(" ")}`);let o=await se(n.hdcPath,r);return o.exitCode!==0&&m(`hdc file recv failed: ${o.stderr||o.stdout||`exit code ${o.exitCode}`}`),xT(e,n.remotePath)}async function NT(n){let e=Oe.mkdtempSync(et.join(et.dirname(n.localPath),".devecocli-screenshot-"));try{let t=await Od(n,e,et.join(e,et.basename(n.remotePath)))??await Od(n,e,e)??await Od(n,e,et.join(e,"screenshot.png"));if(!t)throw new Error(`Screenshot file was not created in ${e}.`);CT(t,n.localPath)}finally{Oe.rmSync(e,{recursive:!0,force:!0})}}async function LT(n){let e=["-t",n.serial,"shell","rm","-f",n.remotePath];m(`Executing: ${n.hdcPath} ${e.join(" ")}`),await se(n.hdcPath,e)}async function OT(n){try{await kT(n),await NT(n)}finally{await LT(n)}}async function MT(n){let e=bT(n.path),t=n.display!==void 0?PT(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 yn(r,n.device),i=`/data/local/tmp/devecocli-${wT()}.png`;await OT({hdcPath:r.hdcPath,serial:o,localPath:e,remotePath:i,display:t}),console.log(vT(`Screenshot saved to ${e}`))}var Dy=new yT("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(MT);import{Command as wn}from"commander";async function vn(n,e,t){let r=new ct;r.start(n);try{await t(r)}catch(o){throw r.stop(),new Error(`${e}: ${o.message}`,{cause:o})}}async function _T(n,e,t){await vn("Executing click...","click failed",async r=>{Vr(n,e,t.id,t.window);let{hdcPath:o,deviceId:i}=await bt(t.device),{x:s,y:a}=await Jr(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 FT(n,e,t){await vn("Executing doubleclick...","doubleclick failed",async r=>{Vr(n,e,t.id,t.window);let{hdcPath:o,deviceId:i}=await bt(t.device),{x:s,y:a}=await Jr(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 jT(n,e,t){await vn("Executing longclick...","longclick failed",async r=>{Vr(n,e,t.id,t.window);let{hdcPath:o,deviceId:i}=await bt(t.device),{x:s,y:a}=await Jr(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 HT(n,e,t,r,o){await vn("Executing swipe...","swipe failed",async i=>{Ae(n,"x1"),Ae(e,"y1"),Ae(t,"x2"),Ae(r,"y2");let s=hi(o.speed),{hdcPath:a,deviceId:c}=await bt(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 $T(n,e,t,r,o){await vn("Executing fling...","fling failed",async i=>{Ae(n,"x1"),Ae(e,"y1"),Ae(t,"x2"),Ae(r,"y2");let s=hi(o.speed),{hdcPath:a,deviceId:c}=await bt(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 UT(n,e,t,r,o){await vn("Executing drag...","drag failed",async i=>{Ae(n,"x1"),Ae(e,"y1"),Ae(t,"x2"),Ae(r,"y2");let s=hi(o.speed),{hdcPath:a,deviceId:c}=await bt(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 BT(n,e){await vn("Executing dircfling...","dircfling failed",async t=>{let r=$a[n];if(r===void 0)throw new Error(`Invalid direction "${n}". Valid values: ${Object.keys($a).join(", ")}`);let{hdcPath:o,deviceId:i}=await bt(e.device);await Qe(o,i,["uitest","uiInput","dircFling",r]),t.succeed(`dircfling ${n}`)})}async function WT(n,e,t,r){await vn("Executing text input...","input failed",async o=>{Vr(e,t,r.id,r.window,!1),Ua(n,"text");let{hdcPath:i,deviceId:s}=await bt(r.device);if(e!==void 0)await Qe(i,s,["uitest","uiInput","inputText",`${e}`,`${t}`,n]),o.succeed(`input ${n} at (${e}, ${t})`);else if(r.id){let{x:a,y:c}=await Jr(i,s,void 0,void 0,r.id,r.window);await Qe(i,s,["uitest","uiInput","inputText",`${a}`,`${c}`,n]),o.succeed(`input ${n} at (${a}, ${c})`)}else await Qe(i,s,["uitest","uiInput","text",n]),o.succeed(`input ${n}`)})}var Ry=new wn("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(_T),Ty=new wn("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(FT),ky=new wn("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(jT),xy=new wn("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(HT),Ny=new wn("fling").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Fling from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action($T),Ly=new wn("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(UT),Oy=new wn("dircfling").argument("<direction>","Direction: up, down, left, right").description("Fling in a specified direction").option("--device <name|serial>","Target device (name or serial)").action(BT),My=new wn("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(WT);var tt=new GT("ui").description("Inspect and interact with UI on a connected device");tt.addCommand(by);tt.addCommand(Ld);tt.addCommand(Dy);tt.addCommand(Ry);tt.addCommand(Ty);tt.addCommand(ky);tt.addCommand(xy);tt.addCommand(Ny);tt.addCommand(Ly);tt.addCommand(Oy);tt.addCommand(My);var _y=tt;import{Command as Rx}from"commander";import{execa as pk}from"execa";import Wt from"fs";import*as jd from"os";import*as B from"path";var zT=new RegExp("\x1B\\[[0-?]*[ -/]*[@-~]","g"),qT=/\r/g,VT=/^(Working|Finished)\.\.\.\[[^\]]*\]\d+%$/,JT=/^<+\s*/,YT=/\s*>+$/,KT=[/^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 Md(n){if(!n)return"";let e=n.replace(zT,"").replace(qT,`
1387
+ ${e}`:`Screenshot was not created on device: ${n.remotePath}.`)}function Ay(n){try{return Iy(n),!0}catch{return!1}}function Dy(n){let e=[];for(let t of _e.readdirSync(n,{withFileTypes:!0})){let r=et.join(n,t.name);if(t.isDirectory()){e.push(...Dy(r));continue}t.isFile()&&Ay(r)&&e.push(r)}return e}function NT(n,e){let t=et.join(n,et.basename(e));if(Ay(t))return t;let r=Dy(n);if(r.length===1)return r[0];if(r.length>1)throw new Error(`Multiple screenshot files were received in ${n}.`)}async function Md(n,e,t){let r=["-t",n.serial,"file","recv",n.remotePath,t];m(`Executing: ${n.hdcPath} ${r.join(" ")}`);let o=await se(n.hdcPath,r);return o.exitCode!==0&&m(`hdc file recv failed: ${o.stderr||o.stdout||`exit code ${o.exitCode}`}`),NT(e,n.remotePath)}async function LT(n){let e=_e.mkdtempSync(et.join(et.dirname(n.localPath),".devecocli-screenshot-"));try{let t=await Md(n,e,et.join(e,et.basename(n.remotePath)))??await Md(n,e,e)??await Md(n,e,et.join(e,"screenshot.png"));if(!t)throw new Error(`Screenshot file was not created in ${e}.`);IT(t,n.localPath)}finally{_e.rmSync(e,{recursive:!0,force:!0})}}async function OT(n){let e=["-t",n.serial,"shell","rm","-f",n.remotePath];m(`Executing: ${n.hdcPath} ${e.join(" ")}`),await se(n.hdcPath,e)}async function MT(n){try{await xT(n),await LT(n)}finally{await OT(n)}}async function _T(n){let e=ET(n.path),t=n.display!==void 0?CT(n.display):void 0;if(n.device!==void 0&&!n.device.trim())throw new Error("--device must not be empty.");let r=await I.new(),o=await vn(r,n.device),i=`/data/local/tmp/devecocli-${vT()}.png`;await MT({hdcPath:r.hdcPath,serial:o,localPath:e,remotePath:i,display:t}),console.log(ST(`Screenshot saved to ${e}`))}var Ry=new wT("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(_T);import{Command as Sn}from"commander";async function bn(n,e,t){let r=new lt;r.start(n);try{await t(r)}catch(o){throw r.stop(),new Error(`${e}: ${o.message}`,{cause:o})}}async function FT(n,e,t){await bn("Executing click...","click failed",async r=>{Kr(n,e,t.id,t.window);let{hdcPath:o,deviceId:i}=await Pt(t.device),{x:s,y:a}=await Xr(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 jT(n,e,t){await bn("Executing doubleclick...","doubleclick failed",async r=>{Kr(n,e,t.id,t.window);let{hdcPath:o,deviceId:i}=await Pt(t.device),{x:s,y:a}=await Xr(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 HT(n,e,t){await bn("Executing longclick...","longclick failed",async r=>{Kr(n,e,t.id,t.window);let{hdcPath:o,deviceId:i}=await Pt(t.device),{x:s,y:a}=await Xr(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 $T(n,e,t,r,o){await bn("Executing swipe...","swipe failed",async i=>{De(n,"x1"),De(e,"y1"),De(t,"x2"),De(r,"y2");let s=yi(o.speed),{hdcPath:a,deviceId:c}=await Pt(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 UT(n,e,t,r,o){await bn("Executing fling...","fling failed",async i=>{De(n,"x1"),De(e,"y1"),De(t,"x2"),De(r,"y2");let s=yi(o.speed),{hdcPath:a,deviceId:c}=await Pt(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 BT(n,e,t,r,o){await bn("Executing drag...","drag failed",async i=>{De(n,"x1"),De(e,"y1"),De(t,"x2"),De(r,"y2");let s=yi(o.speed),{hdcPath:a,deviceId:c}=await Pt(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 WT(n,e){await bn("Executing dircfling...","dircfling failed",async t=>{let r=Ua[n];if(r===void 0)throw new Error(`Invalid direction "${n}". Valid values: ${Object.keys(Ua).join(", ")}`);let{hdcPath:o,deviceId:i}=await Pt(e.device);await Qe(o,i,["uitest","uiInput","dircFling",r]),t.succeed(`dircfling ${n}`)})}async function GT(n,e,t,r){await bn("Executing text input...","input failed",async o=>{Kr(e,t,r.id,r.window,!1),Ba(n,"text");let{hdcPath:i,deviceId:s}=await Pt(r.device);if(e!==void 0)await Qe(i,s,["uitest","uiInput","inputText",`${e}`,`${t}`,n]),o.succeed(`input ${n} at (${e}, ${t})`);else if(r.id){let{x:a,y:c}=await Xr(i,s,void 0,void 0,r.id,r.window);await Qe(i,s,["uitest","uiInput","inputText",`${a}`,`${c}`,n]),o.succeed(`input ${n} at (${a}, ${c})`)}else await Qe(i,s,["uitest","uiInput","text",n]),o.succeed(`input ${n}`)})}var Ty=new Sn("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(FT),ky=new Sn("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(jT),xy=new Sn("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(HT),Ny=new Sn("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($T),Ly=new Sn("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(UT),Oy=new Sn("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(BT),My=new Sn("dircfling").argument("<direction>","Direction: up, down, left, right").description("Fling in a specified direction").option("--device <name|serial>","Target device (name or serial)").action(WT),_y=new Sn("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(GT);var tt=new zT("ui").description("Inspect and interact with UI on a connected device");tt.addCommand(Ey);tt.addCommand(Od);tt.addCommand(Ry);tt.addCommand(Ty);tt.addCommand(ky);tt.addCommand(xy);tt.addCommand(Ny);tt.addCommand(Ly);tt.addCommand(Oy);tt.addCommand(My);tt.addCommand(_y);var Fy=tt;import{Command as Tx}from"commander";import{execa as fk}from"execa";import qt from"fs";import*as Hd from"os";import*as B from"path";var qT=new RegExp("\x1B\\[[0-?]*[ -/]*[@-~]","g"),VT=/\r/g,JT=/^(Working|Finished)\.\.\.\[[^\]]*\]\d+%$/,YT=/^<+\s*/,KT=/\s*>+$/,XT=[/^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 _d(n){if(!n)return"";let e=n.replace(qT,"").replace(VT,`
1388
1388
  `).split(`
1389
- `).map(t=>t.trimEnd()).filter(t=>ZT(t));return e.length>0?`${e.join(`
1389
+ `).map(t=>t.trimEnd()).filter(t=>QT(t));return e.length>0?`${e.join(`
1390
1390
  `)}
1391
- `:""}function $y(n){let e=Md(n).trim();if(!e)return{jsonText:void 0,diagnostics:""};if(Uy(e))return{jsonText:e,diagnostics:""};let t=QT(e);if(!t)return{jsonText:void 0,diagnostics:`${e}
1391
+ `:""}function Uy(n){let e=_d(n).trim();if(!e)return{jsonText:void 0,diagnostics:""};if(By(e))return{jsonText:e,diagnostics:""};let t=ek(e);if(!t)return{jsonText:void 0,diagnostics:`${e}
1392
1392
  `};let r=[e.slice(0,t.start).trim(),e.slice(t.end).trim()].filter(Boolean).join(`
1393
1393
  `);return{jsonText:e.slice(t.start,t.end),diagnostics:r?`${r}
1394
- `:""}}function XT(n){return VT.test(n.trim())}function ZT(n){let e=n.trim();return!!e&&!XT(e)&&!KT.some(t=>t.test(e))}function Uy(n){try{return JSON.parse(n),!0}catch{return!1}}function QT(n){for(let e=0;e<n.length;e++){if(n[e]!=="["&&n[e]!=="{")continue;let t=ek(n,e);if(t)return t}}function ek(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(Uy(o))return{start:e,end:t}}}var Fy=["Error","Warning","Suggestion","Info","Off","Unknown"];function By(n){let e=_d(n);return{issues:ok(e),summary:tk(n,e)}}function tk(n,e){let t=sk(e);return{filesChecked:ak(n).size,issues:e.length,errors:t.get("Error")??0,warnings:t.get("Warning")??0,suggestions:t.get("Suggestion")??0}}function _d(n,e=""){if(Array.isArray(n))return n.flatMap(i=>_d(i,e));if(!Wy(n))return[];let t=gi(n,["filePath","file","path"])??e,r=nk(n,t);if(r.length>0)return r;let o=rk(n,t);return o?[o]:[]}function nk(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=>_d(s,e));if(i.length>0)return i}}return[]}function rk(n,e){let t=gi(n,["message","description","desc","detail"])??"",r=uk(gi(n,["rule","ruleId","ruleName"])),o=lk(n,["severity","level"]),i=gi(n,["filePath","file","path"])??e;if(!(!t&&!r&&o==="Unknown"))return{file:i,line:Hy(n,["line","reportLine"]),column:Hy(n,["column","reportColumn"]),severity:o,rule:r,message:t}}function ok(n){return[...n].sort((e,t)=>{let r=jy(e.severity)-jy(t.severity);return r===0?ik(e,t):r})}function ik(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 ak(n){let e=new Set;return Fd(e,n,""),e}function Fd(n,e,t){if(Array.isArray(e)){for(let o of e)Fd(n,o,t);return}if(!Wy(e))return;let r=gi(e,["filePath","file","path"])??t;r&&n.add(r),ck(n,e,r)}function ck(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)Fd(n,s,t)}}function lk(n,e){for(let t of e){let r=n[t];if(typeof r=="string"||typeof r=="number")return dk(r)}return"Unknown"}function dk(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 uk(n){let e=n?.normalize("NFKC").trim();if(e)return e.replace(JT,"").replace(YT,"").toLowerCase()}function jy(n){let e=Fy.indexOf(n);return e===-1?Fy.length:e}function gi(n,e){for(let t of e){let r=n[t];if(typeof r=="string")return r}}function Hy(n,e){for(let t of e){let r=n[t];if(typeof r=="number")return r}}function Wy(n){return typeof n=="object"&&n!==null}var Gy="deveco-codelinter-",zy=[".ets",".ts",".js"],yi=class n{resolution;cwd;constructor(e,t){this.resolution=n.resolveWithToolProvider(e),this.cwd=t}static resolveProjectRoot(e){try{return G.discover(e).rootDir}catch{return e}}async check(e){let t=Wt.mkdtempSync(B.join(jd.tmpdir(),Gy)),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=$y(c.stdout),d=l.diagnostics+Md(c.stderr);try{let h=this.readJsonReport(r,l.jsonText);return{exitCode:c.exitCode,diagnostics:d,report:By(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=Wt.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(!Wt.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 Wt.realpathSync(G.discover(r).rootDir)}catch{return}}resolveRealPath(e,t){try{return Wt.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(),m(`Executing: ${this.resolution.command} ${t.join(" ")}`),m(`[CodelinterAdapter] Working directory: ${r}`);let o=await pk(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??[])Wt.mkdirSync(e,{recursive:!0})}readJsonReport(e,t){let o=(Wt.existsSync(e)?Wt.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(jd.tmpdir());!(t.startsWith(`${r}${B.sep}`)||t===r)||!B.basename(t).startsWith(Gy)||Wt.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)]),m(`[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 Wa,yellow as Pk}from"colorette";import{Argument as Ck,Command as Ik,InvalidArgumentError as bn}from"commander";import vi from"fs";import*as Me from"path";import*as wi from"path";var qy="n/a",Vy=/\\/g,fk=/\|/g,mk=/\r?\n/g;function Jy(n,e){if(n.issues.length===0)return`No defects found.
1395
- ${Hd(n.summary)}
1396
- `;let t=e===void 0?n.issues:n.issues.slice(0,e),r=[gk(t),Hd(n.summary)];return e!==void 0&&t.length<n.issues.length&&r.push(hk(n.issues.length,t.length)),`${r.join(`
1394
+ `:""}}function ZT(n){return JT.test(n.trim())}function QT(n){let e=n.trim();return!!e&&!ZT(e)&&!XT.some(t=>t.test(e))}function By(n){try{return JSON.parse(n),!0}catch{return!1}}function ek(n){for(let e=0;e<n.length;e++){if(n[e]!=="["&&n[e]!=="{")continue;let t=tk(n,e);if(t)return t}}function tk(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(By(o))return{start:e,end:t}}}var jy=["Error","Warning","Suggestion","Info","Off","Unknown"];function Wy(n){let e=Fd(n);return{issues:ik(e),summary:nk(n,e)}}function nk(n,e){let t=ak(e);return{filesChecked:ck(n).size,issues:e.length,errors:t.get("Error")??0,warnings:t.get("Warning")??0,suggestions:t.get("Suggestion")??0}}function Fd(n,e=""){if(Array.isArray(n))return n.flatMap(i=>Fd(i,e));if(!Gy(n))return[];let t=wi(n,["filePath","file","path"])??e,r=rk(n,t);if(r.length>0)return r;let o=ok(n,t);return o?[o]:[]}function rk(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=>Fd(s,e));if(i.length>0)return i}}return[]}function ok(n,e){let t=wi(n,["message","description","desc","detail"])??"",r=pk(wi(n,["rule","ruleId","ruleName"])),o=dk(n,["severity","level"]),i=wi(n,["filePath","file","path"])??e;if(!(!t&&!r&&o==="Unknown"))return{file:i,line:$y(n,["line","reportLine"]),column:$y(n,["column","reportColumn"]),severity:o,rule:r,message:t}}function ik(n){return[...n].sort((e,t)=>{let r=Hy(e.severity)-Hy(t.severity);return r===0?sk(e,t):r})}function sk(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 ak(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 ck(n){let e=new Set;return jd(e,n,""),e}function jd(n,e,t){if(Array.isArray(e)){for(let o of e)jd(n,o,t);return}if(!Gy(e))return;let r=wi(e,["filePath","file","path"])??t;r&&n.add(r),lk(n,e,r)}function lk(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)jd(n,s,t)}}function dk(n,e){for(let t of e){let r=n[t];if(typeof r=="string"||typeof r=="number")return uk(r)}return"Unknown"}function uk(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 pk(n){let e=n?.normalize("NFKC").trim();if(e)return e.replace(YT,"").replace(KT,"").toLowerCase()}function Hy(n){let e=jy.indexOf(n);return e===-1?jy.length:e}function wi(n,e){for(let t of e){let r=n[t];if(typeof r=="string")return r}}function $y(n,e){for(let t of e){let r=n[t];if(typeof r=="number")return r}}function Gy(n){return typeof n=="object"&&n!==null}var zy="deveco-codelinter-",qy=[".ets",".ts",".js"],vi=class n{resolution;cwd;constructor(e,t){this.resolution=n.resolveWithToolProvider(e),this.cwd=t}static resolveProjectRoot(e){try{return G.discover(e).rootDir}catch{return e}}async check(e){let t=qt.mkdtempSync(B.join(Hd.tmpdir(),zy)),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=Uy(c.stdout),d=l.diagnostics+_d(c.stderr);try{let h=this.readJsonReport(r,l.jsonText);return{exitCode:c.exitCode,diagnostics:d,report:Wy(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=qt.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(!qy.some(l=>l===a))throw new Error(`Unsupported lint file extension "${a||"<none>"}": ${o}. Supported extensions: ${qy.join(", ")}.`)}let s=this.discoverProjectRoot(o,i.isDirectory());if(e!==void 0&&s===void 0)throw new 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(!qt.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 qt.realpathSync(G.discover(r).rootDir)}catch{return}}resolveRealPath(e,t){try{return qt.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(),m(`Executing: ${this.resolution.command} ${t.join(" ")}`),m(`[CodelinterAdapter] Working directory: ${r}`);let o=await fk(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??[])qt.mkdirSync(e,{recursive:!0})}readJsonReport(e,t){let o=(qt.existsSync(e)?qt.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(Hd.tmpdir());!(t.startsWith(`${r}${B.sep}`)||t===r)||!B.basename(t).startsWith(zy)||qt.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)]),m(`[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 Ga,yellow as Ck}from"colorette";import{Argument as Ik,Command as Ak,InvalidArgumentError as Pn}from"commander";import bi from"fs";import*as Fe from"path";import*as Si from"path";var Vy="n/a",Jy=/\\/g,mk=/\|/g,hk=/\r?\n/g;function Yy(n,e){if(n.issues.length===0)return`No defects found.
1395
+ ${$d(n.summary)}
1396
+ `;let t=e===void 0?n.issues:n.issues.slice(0,e),r=[yk(t),$d(n.summary)];return e!==void 0&&t.length<n.issues.length&&r.push(gk(n.issues.length,t.length)),`${r.join(`
1397
1397
  `)}
1398
- `}function Yy(n,e){return[Hd(n.summary),`Full report: ${$d(e)}`,""].join(`
1399
- `)}function Ky(n){let e=["# CodeLinter report",""];return n.issues.length===0?e.push("No defects found.",""):e.push(...yk(n.issues),""),e.push("## Summary","",...vk(n.summary),""),e.join(`
1400
- `)}function Xy(n){return`${JSON.stringify(n,null,2)}
1401
- `}function Hd(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 hk(n,e){return`Showing ${nt(e)} of ${nt(n)} issues. Use --output-path <path> to write all results.`}function gk(n){let e=["No","File","Line","Column","Severity","Rule","Message"],t=n.map((r,o)=>({cells:bk(r,o+1)}));return["CodeLinter report","",xt(e,t)].join(`
1402
- `)}function yk(n){let e=["| No | File | Line | Column | Severity | Rule | Message |","| ---: | --- | ---: | ---: | --- | --- | --- |"];for(let[t,r]of n.entries())e.push(wk(r,t+1));return e}function wk(n,e){return`| ${[String(e),$d(Sn(n.file)),Ba(n.line),Ba(n.column),Sn(n.severity),Sn(n.rule),Sn(n.message)].map(Sk).join(" | ")} |`}function vk(n){return[`- Issues: ${nt(n.issues)}`,`- Errors: ${nt(n.errors)}`,`- Warnings: ${nt(n.warnings)}`,`- Suggestions: ${nt(n.suggestions)}`,`- Files checked: ${nt(n.filesChecked)}`]}function Sk(n){return n.replace(Vy,"\\\\").replace(fk,"\\|").replace(mk,"<br>")}function bk(n,e){return[String(e),$d(Sn(Ek(n.file))),Ba(n.line),Ba(n.column),Sn(n.severity),Sn(n.rule),Sn(n.message)]}function Ek(n){if(!wi.isAbsolute(n))return n;let e=wi.relative(process.cwd(),n);return!e||e.startsWith("..")||wi.isAbsolute(e)?n:e}function $d(n){return n.replace(Vy,"/")}function Sn(n){let e=n?.trim();return e||qy}function Ba(n){return n===void 0?qy:String(n)}function nt(n){return n.toLocaleString("en-US")}var Ak=/^-?\d+$/;function Ud(){return new Ik("lint").description("Run DevEco Code Linter checks for TS/ArkTS code").addArgument(new Ck("[path]","File or directory to lint").argParser(xk)).option("--fix","Auto-fix fixable code issues").option("--incremental","Only check uncommitted files").option("--config-path <path>","Path to lint configuration file",Rk).option("--product <product>","Product name defined in build-profile.json5",Tk,"default").option("--format <format>","Report format (choices: default, json)",Dk,"default").option("--output-path <path>","Complete report file or directory",kk).option("--limit <number>","Maximum terminal issues to display when --output-path is omitted",Nk).action(async(n,e)=>{await Lk(n,e)})}function Dk(n){if(n==="default"||n==="json")return n;throw new bn("Invalid --format. Expected one of: default, json.")}function Rk(n){Bd(n,"--config-path");let e=Me.extname(n).toLowerCase();if(e!==".json"&&e!==".json5")throw new bn("`--config-path` must point to a .json or .json5 file.");return n}function Tk(n){return Zy(n,"product"),n}function kk(n){return Bd(n,"--output-path"),n}function xk(n){return Bd(n,"path"),n}function Nk(n){if(Zy(n,"limit"),!Ak.test(n))throw new bn("`--limit` must be a positive integer.");let e=Number.parseInt(n,10);if(e<=0||!Number.isSafeInteger(e))throw new bn("`--limit` must be an integer greater than 0.");return e}function Zy(n,e){if(n.trim().length===0||tw(n))throw new bn(`Invalid --${e} value.`)}function Bd(n,e){let t=`\`${e}\``;if(n.length===0||tw(n))throw new bn(`${t} must be a non-empty path without control characters.`)}async function Lk(n,e){let t=process.cwd(),r=jk(e.outputPath,e.format,t);e.fix&&console.warn(Pk("Running codelinter with --fix. Ensure your project source is trusted."));let o=await Ok(n,e,t);Wk(o.diagnostics),process.exitCode=_k(o,r,e.format,e.limit,t)}async function Ok(n,e,t){let r=await A.new(),o=new yi(r,t);return Mk(o,{lintPath:n,configPath:e.configPath,product:e.product,fix:e.fix,incremental:e.incremental})}async function Mk(n,e){let t=new ct;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 _k(n,e,t,r,o){if(!n.report)return console.error(Wa("Failed to generate Code Linter report.")),console.error(Wa(n.reportError?.message??"Native JSON report was not generated.")),n.exitCode===0?1:n.exitCode;try{if(e){Fk(e,t,n.report);let i=ew(e,o);process.stdout.write(Yy(n.report,i))}else process.stdout.write(Jy(n.report,r));return n.exitCode}catch(i){return console.error(Wa("Failed to generate Code Linter report.")),console.error(Wa(i.message)),n.exitCode===0?1:n.exitCode}}function Fk(n,e,t){vi.mkdirSync(Me.dirname(n),{recursive:!0});let r=e==="json"?Xy(t):Ky(t);try{vi.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 jk(n,e,t){if(!n)return;let r=Uk(n,t),o=$k(n,r),i=o?Me.join(r,Bk(e)):r;if(o||Hk(n,e),vi.existsSync(i))throw new bn(`Output file already exists: ${ew(i,t)}`);return i}function Hk(n,e){let t=Qy(e);if(Me.extname(n).toLowerCase()!==t)throw new bn(`--output-path must use the ${t} extension for --format ${e}.`)}function $k(n,e){return vi.existsSync(e)?vi.statSync(e).isDirectory():n.endsWith("/")||n.endsWith("\\")||Me.extname(n)===""}function Uk(n,e){return Me.resolve(e,n)}function Bk(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}${Qy(n)}`}function Qy(n){return n==="json"?".json":".md"}function ew(n,e){let t=Me.relative(e,n);return t&&!t.startsWith("..")&&!Me.isAbsolute(t)?t:n}function Wk(n){n&&process.stderr.write(n)}function tw(n){for(let e of n){let t=e.charCodeAt(0);if(t<=31||t===127)return!0}return!1}import{Command as Gk,InvalidArgumentError as iw}from"commander";import*as W from"path";import*as Wd from"os";import{readdirSync as zk,existsSync as Ga,readFileSync as qk,unlinkSync as Vk,copyFileSync as sw,writeFileSync as aw}from"fs";import{execa as Jk}from"execa";import{cyan as ge,yellow as cw}from"colorette";import Yk from"ora";var nw=["default","csv","json"];function lw(n){if(nw.includes(n))return n;throw new iw(`--format must be one of: ${nw.join(", ")} (got "${n}")`)}function Kk(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new iw(`--limit must be a positive integer (got "${n}")`);return e}function Xk(n){return[...n].sort((e,t)=>{let r=rw(e),o=rw(t);return r.apiVersion-o.apiVersion||r.suffix.localeCompare(o.suffix)})}function rw(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 dw(n){let t=zk(n,{withFileTypes:!0}).filter(r=>r.isFile()&&r.name.toLowerCase().endsWith(".json")).map(r=>r.name.slice(0,-5));return Xk(t)}function Zk(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=lw(o);return i==="default"?"csv":i}}return n}async function Qk(n){let e=await A.new(),{apiChangeDir:t}=e.getApiscanPaths();m(ge(`[compat:versions] apiChangeDir: "${t}"`));let r=dw(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(`
1403
- `))}}var ow=new Set([".ets",".c",".cpp"]);function ex(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 tx(n){for(let e of n){let t=W.resolve(e);if(!Ga(t))throw new Error(`File "${e}" does not exist.`);let r=W.extname(t).toLowerCase();if(!ow.has(r)){let o=Array.from(ow).join(", ");throw new Error(`Unsupported file extension "${r}" for "${e}". Supported: ${o}.`)}}}function nx(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 rx(n){let e=[],t=[],r="",o=!1,i=0;for(;i<n.length;){let s=n[i];o?{field:r,inQuotes:o,i}=ox(n,i,s,r,o):s==='"'?(o=!0,i+=1):s===","?(t.push(r),r="",i+=1):s===`
1404
- `?(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 ox(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 ix(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=qk(n,"utf8"),t=e.startsWith("\uFEFF")?e.slice(1):e,r=rx(t);if(r.length<2)return[];let[o,...i]=r;return ix(o,i)}function ax(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 cx(n,e){let t=new Map;for(let i of n){let s=i.changeType||"(unknown)";t.set(s,(t.get(s)??0)+1)}let r=Array.from(t.entries()).sort((i,s)=>s[1]-i[1]||i[0].localeCompare(s[0])),o=Math.max(5,...r.map(([i])=>i.length));console.log(ge("API change scan summary:")),console.log(` ${"Total".padEnd(o)} ${n.length}`);for(let[i,s]of r)console.log(` ${i.padEnd(o)} ${s}`);e&&console.log(` ${"Report".padEnd(o)} ${e}`)}function lx(n,e){if(console.log(),n.length===0){console.log("No API changes detected.");return}let t=n.slice(0,e),r=n.length-t.length;console.log(ge(`Details (showing ${t.length}${r>0?` of ${n.length}`:""}):`));let o=[["Title","title"],["Language","language"],["ChangeId","changeId"],["Changed in","changedInSdk"],["Affected Versions","affectedVersions"],["Code Location","codeLocation"]],i=Math.max(...o.map(([a])=>a.length)),s=a=>a||"<unknown>";for(let a of t){console.log(` [${s(a.changeType)}] ${s(a.apiDefinition)}`);for(let[c,l]of o)console.log(` ${c.padEnd(i)} ${s(a[l])}`)}r>0&&console.log(cw(` ... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function dx(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(cw(`... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function ux(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 px(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}=nx(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=ux(t,r.modules);o.push("--modulePaths",i.join(","))}else o.push("--projectPath",t.rootDir);return o.push("--outputPath",Wd.tmpdir()),o}async function fx(n,e){let t=W.dirname(e[0]);try{let o=(await Jk(n.nodePath,e,{cwd:t,stdin:"ignore",stdout:"pipe",stderr:"inherit"})).stdout;return process.env.DEVECO_CLI_DEBUG&&(console.log(ge("[compat:check] === scan stdout ===")),process.stdout.write(o),o.endsWith(`
1398
+ `}function Ky(n,e){return[$d(n.summary),`Full report: ${Ud(e)}`,""].join(`
1399
+ `)}function Xy(n){let e=["# CodeLinter report",""];return n.issues.length===0?e.push("No defects found.",""):e.push(...wk(n.issues),""),e.push("## Summary","",...Sk(n.summary),""),e.join(`
1400
+ `)}function Zy(n){return`${JSON.stringify(n,null,2)}
1401
+ `}function $d(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 gk(n,e){return`Showing ${nt(e)} of ${nt(n)} issues. Use --output-path <path> to write all results.`}function yk(n){let e=["No","File","Line","Column","Severity","Rule","Message"],t=n.map((r,o)=>({cells:Ek(r,o+1)}));return["CodeLinter report","",Lt(e,t)].join(`
1402
+ `)}function wk(n){let e=["| No | File | Line | Column | Severity | Rule | Message |","| ---: | --- | ---: | ---: | --- | --- | --- |"];for(let[t,r]of n.entries())e.push(vk(r,t+1));return e}function vk(n,e){return`| ${[String(e),Ud(En(n.file)),Wa(n.line),Wa(n.column),En(n.severity),En(n.rule),En(n.message)].map(bk).join(" | ")} |`}function Sk(n){return[`- Issues: ${nt(n.issues)}`,`- Errors: ${nt(n.errors)}`,`- Warnings: ${nt(n.warnings)}`,`- Suggestions: ${nt(n.suggestions)}`,`- Files checked: ${nt(n.filesChecked)}`]}function bk(n){return n.replace(Jy,"\\\\").replace(mk,"\\|").replace(hk,"<br>")}function Ek(n,e){return[String(e),Ud(En(Pk(n.file))),Wa(n.line),Wa(n.column),En(n.severity),En(n.rule),En(n.message)]}function Pk(n){if(!Si.isAbsolute(n))return n;let e=Si.relative(process.cwd(),n);return!e||e.startsWith("..")||Si.isAbsolute(e)?n:e}function Ud(n){return n.replace(Jy,"/")}function En(n){let e=n?.trim();return e||Vy}function Wa(n){return n===void 0?Vy:String(n)}function nt(n){return n.toLocaleString("en-US")}var Dk=/^-?\d+$/;function Bd(){return new Ak("lint").description("Run DevEco Code Linter checks for TS/ArkTS code").addArgument(new Ik("[path]","File or directory to lint").argParser(Nk)).option("--fix","Auto-fix fixable code issues").option("--incremental","Only check uncommitted files").option("--config-path <path>","Path to lint configuration file",Tk).option("--product <product>","Product name defined in build-profile.json5",kk,"default").option("--format <format>","Report format (choices: default, json)",Rk,"default").option("--output-path <path>","Complete report file or directory",xk).option("--limit <number>","Maximum terminal issues to display when --output-path is omitted",Lk).action(async(n,e)=>{await Ok(n,e)})}function Rk(n){if(n==="default"||n==="json")return n;throw new Pn("Invalid --format. Expected one of: default, json.")}function Tk(n){Wd(n,"--config-path");let e=Fe.extname(n).toLowerCase();if(e!==".json"&&e!==".json5")throw new Pn("`--config-path` must point to a .json or .json5 file.");return n}function kk(n){return Qy(n,"product"),n}function xk(n){return Wd(n,"--output-path"),n}function Nk(n){return Wd(n,"path"),n}function Lk(n){if(Qy(n,"limit"),!Dk.test(n))throw new Pn("`--limit` must be a positive integer.");let e=Number.parseInt(n,10);if(e<=0||!Number.isSafeInteger(e))throw new Pn("`--limit` must be an integer greater than 0.");return e}function Qy(n,e){if(n.trim().length===0||nw(n))throw new Pn(`Invalid --${e} value.`)}function Wd(n,e){let t=`\`${e}\``;if(n.length===0||nw(n))throw new Pn(`${t} must be a non-empty path without control characters.`)}async function Ok(n,e){let t=process.cwd(),r=Hk(e.outputPath,e.format,t);e.fix&&console.warn(Ck("Running codelinter with --fix. Ensure your project source is trusted."));let o=await Mk(n,e,t);Gk(o.diagnostics),process.exitCode=Fk(o,r,e.format,e.limit,t)}async function Mk(n,e,t){let r=await I.new(),o=new vi(r,t);return _k(o,{lintPath:n,configPath:e.configPath,product:e.product,fix:e.fix,incremental:e.incremental})}async function _k(n,e){let t=new lt;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 Fk(n,e,t,r,o){if(!n.report)return console.error(Ga("Failed to generate Code Linter report.")),console.error(Ga(n.reportError?.message??"Native JSON report was not generated.")),n.exitCode===0?1:n.exitCode;try{if(e){jk(e,t,n.report);let i=tw(e,o);process.stdout.write(Ky(n.report,i))}else process.stdout.write(Yy(n.report,r));return n.exitCode}catch(i){return console.error(Ga("Failed to generate Code Linter report.")),console.error(Ga(i.message)),n.exitCode===0?1:n.exitCode}}function jk(n,e,t){bi.mkdirSync(Fe.dirname(n),{recursive:!0});let r=e==="json"?Zy(t):Xy(t);try{bi.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 Hk(n,e,t){if(!n)return;let r=Bk(n,t),o=Uk(n,r),i=o?Fe.join(r,Wk(e)):r;if(o||$k(n,e),bi.existsSync(i))throw new Pn(`Output file already exists: ${tw(i,t)}`);return i}function $k(n,e){let t=ew(e);if(Fe.extname(n).toLowerCase()!==t)throw new Pn(`--output-path must use the ${t} extension for --format ${e}.`)}function Uk(n,e){return bi.existsSync(e)?bi.statSync(e).isDirectory():n.endsWith("/")||n.endsWith("\\")||Fe.extname(n)===""}function Bk(n,e){return Fe.resolve(e,n)}function Wk(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}${ew(n)}`}function ew(n){return n==="json"?".json":".md"}function tw(n,e){let t=Fe.relative(e,n);return t&&!t.startsWith("..")&&!Fe.isAbsolute(t)?t:n}function Gk(n){n&&process.stderr.write(n)}function nw(n){for(let e of n){let t=e.charCodeAt(0);if(t<=31||t===127)return!0}return!1}import{Command as zk,InvalidArgumentError as sw}from"commander";import*as W from"path";import*as Gd from"os";import{readdirSync as qk,existsSync as za,readFileSync as Vk,unlinkSync as Jk,copyFileSync as aw,writeFileSync as cw}from"fs";import{execa as Yk}from"execa";import{cyan as ge,yellow as lw}from"colorette";import Kk from"ora";var rw=["default","csv","json"];function dw(n){if(rw.includes(n))return n;throw new sw(`--format must be one of: ${rw.join(", ")} (got "${n}")`)}function Xk(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new sw(`--limit must be a positive integer (got "${n}")`);return e}function Zk(n){return[...n].sort((e,t)=>{let r=ow(e),o=ow(t);return r.apiVersion-o.apiVersion||r.suffix.localeCompare(o.suffix)})}function ow(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 uw(n){let t=qk(n,{withFileTypes:!0}).filter(r=>r.isFile()&&r.name.toLowerCase().endsWith(".json")).map(r=>r.name.slice(0,-5));return Zk(t)}function Qk(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=dw(o);return i==="default"?"csv":i}}return n}async function ex(n){let e=await I.new(),{apiChangeDir:t}=e.getApiscanPaths();m(ge(`[compat:versions] apiChangeDir: "${t}"`));let r=uw(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(`
1403
+ `))}}var iw=new Set([".ets",".c",".cpp"]);function tx(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 nx(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(!iw.has(r)){let o=Array.from(iw).join(", ");throw new Error(`Unsupported file extension "${r}" for "${e}". Supported: ${o}.`)}}}function rx(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 ox(n){let e=[],t=[],r="",o=!1,i=0;for(;i<n.length;){let s=n[i];o?{field:r,inQuotes:o,i}=ix(n,i,s,r,o):s==='"'?(o=!0,i+=1):s===","?(t.push(r),r="",i+=1):s===`
1404
+ `?(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 ix(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 sx(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 ax(n){let e=Vk(n,"utf8"),t=e.startsWith("\uFEFF")?e.slice(1):e,r=ox(t);if(r.length<2)return[];let[o,...i]=r;return sx(o,i)}function cx(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 lx(n,e){let t=new Map;for(let i of n){let s=i.changeType||"(unknown)";t.set(s,(t.get(s)??0)+1)}let r=Array.from(t.entries()).sort((i,s)=>s[1]-i[1]||i[0].localeCompare(s[0])),o=Math.max(5,...r.map(([i])=>i.length));console.log(ge("API change scan summary:")),console.log(` ${"Total".padEnd(o)} ${n.length}`);for(let[i,s]of r)console.log(` ${i.padEnd(o)} ${s}`);e&&console.log(` ${"Report".padEnd(o)} ${e}`)}function dx(n,e){if(console.log(),n.length===0){console.log("No API changes detected.");return}let t=n.slice(0,e),r=n.length-t.length;console.log(ge(`Details (showing ${t.length}${r>0?` of ${n.length}`:""}):`));let o=[["Title","title"],["Language","language"],["ChangeId","changeId"],["Changed in","changedInSdk"],["Affected Versions","affectedVersions"],["Code Location","codeLocation"]],i=Math.max(...o.map(([a])=>a.length)),s=a=>a||"<unknown>";for(let a of t){console.log(` [${s(a.changeType)}] ${s(a.apiDefinition)}`);for(let[c,l]of o)console.log(` ${c.padEnd(i)} ${s(a[l])}`)}r>0&&console.log(lw(` ... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function ux(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(lw(`... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function px(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 fx(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}=rx(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=px(t,r.modules);o.push("--modulePaths",i.join(","))}else o.push("--projectPath",t.rootDir);return o.push("--outputPath",Gd.tmpdir()),o}async function mx(n,e){let t=W.dirname(e[0]);try{let o=(await Yk(n.nodePath,e,{cwd:t,stdin:"ignore",stdout:"pipe",stderr:"inherit"})).stdout;return process.env.DEVECO_CLI_DEBUG&&(console.log(ge("[compat:check] === scan stdout ===")),process.stdout.write(o),o.endsWith(`
1405
1405
  `)||process.stdout.write(`
1406
1406
  `),console.log(ge("[compat:check] === end stdout ==="))),o}catch(r){let o=r;process.env.DEVECO_CLI_DEBUG&&o.stdout&&(console.log(ge("[compat:check] === scan stdout (on error) ===")),process.stdout.write(o.stdout),o.stdout.endsWith(`
1407
1407
  `)||process.stdout.write(`
1408
1408
  `),console.log(ge("[compat:check] === end stdout ===")));let i=new Error(`Compatibility scan failed: ${o.message}`+(o.stderr?`
1409
- ${o.stderr}`:""));throw o.stdout&&(i.stdout=o.stdout),i}}function mx(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 hx(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.
1410
- 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 gx(n,e,t,r,o){o==="none"&&(t==="json"?dx(n,r):lx(n,r)),cx(n,e)}function yx(n,e){let t=W.dirname(n),r=W.basename(n),o=e.slice(1).map(i=>i.startsWith("--")?i:`"${i}"`).join(" ");m(ge(`[compat:check] command: cd "${t}" && node "${r}" ${o}`))}function wx(n){try{Vk(n),m(ge(`[compat:check] cleaned up tmp report: "${n}"`))}catch(e){m(ge(`[compat:check] failed to clean up tmp report: ${e.message}`))}}var vx=[".csv",".json"];function Sx(n){return vx.includes(n.toLowerCase())}function bx(n,e){if(!n)return{kind:"none"};let t=W.extname(n).toLowerCase();if(!Sx(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 Ex(n){if(n.kind==="file"){if(Ga(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(!Ga(e))throw new Error(`Target directory "${e}" does not exist. Create it first, or choose a different --output-path.`)}else if(n.kind==="dir"&&!Ga(n.dirPath))throw new Error(`Target directory "${n.dirPath}" does not exist. Create it first, or choose a different --output-path.`)}function uw(n){return JSON.stringify({count:n.length,records:n},null,2)+`
1411
- `}function Px(n,e,t,r){r===".csv"?sw(n,t):aw(t,uw(e),"utf8"),m(ge(`[compat:check] saved report: "${t}"`))}function Cx(n,e,t,r){if(r==="json"){let i=W.basename(n,".csv"),s=W.join(t,`${i}.json`);return aw(s,uw(e),"utf8"),m(ge(`[compat:check] saved report: "${s}"`)),s}let o=W.join(t,W.basename(n));return sw(n,o),m(ge(`[compat:check] saved report: "${o}"`)),o}async function Ix(n,e){let t=new Te(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 Ax(n,e){mx(n,e);let t=G.discover(process.cwd());e.modules&&e.modules.length>0&&ex(t,e.modules),n.length>0&&tx(n);let r=await A.new(),{apiChangeDir:o,scriptPath:i}=r.getApiscanPaths();m(ge(`[compat:check] script: "${i}"`));let s=dw(o);hx(e,s),e.outputPath&&m(ge(`[compat:check] outputPath: "${e.outputPath}"`));let a=bx(e.outputPath,e.format);return m(ge(`[compat:check] outputTarget: ${a.kind}`)),Ex(a),{project:t,scriptPath:i,target:a,toolProvider:r}}async function Dx(n,e){let{project:t,scriptPath:r,target:o,toolProvider:i}=await Ax(n,e),s=Yk({text:"Running compatibility check...",color:"cyan"}).start();try{await Ix(i,e);let a=px(r,n,t,e);yx(r,a);let c=await fx(i,a),l=ax(c,Wd.tmpdir());if(!l)throw new Error("Scanner output format unexpected: missing report path.");m(ge(`[compat:check] tmp csv: "${l}"`));let d=sx(l),h=null;if(o.kind==="file")Px(l,d,o.filePath,o.ext),h=o.filePath;else if(o.kind==="dir")h=Cx(l,d,o.dirPath,e.format);else if(o.kind!=="none")throw new Error(`Unexpected output target kind: ${o.kind}`);wx(l),s.stop(),gx(d,h,e.format,e.limit,o.kind)}catch(a){throw s.fail("Compatibility check failed"),a}}var Gd=new Gk("compat").description("Compatibility checking utilities.");Gd.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.',lw,"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)",Kk,100).action(async(n,e)=>{await Dx(n,e)});Gd.command("versions").description("List all available target SDK versions for compatibility checking").action(async()=>{let n=Zk("csv");await Qk(n)});var pw=Gd;var fw=new Rx("check").description("Run DevEco project checks").addCommand(Ud());b()||fw.addCommand(pw);var mw=fw;import{Command as mL}from"commander";import{green as fu,red as hL}from"colorette";import mu from"fs";import Xw from"path";import gL from"json5";import{readFileSync as tN}from"fs";import{join as Tx}from"path";var Q={BASE_URL:"https://connect-api.cloud.huawei.com",CERT_LIST_PATH:"/api/cps/harmony-cert-manage/v1/cert/list",CERT_DELETE_PATH:"/api/cps/harmony-cert-manage/v1/cert/delete",CERT_ADD_PATH:"/api/cps/harmony-cert-manage/v1/cert/add",CERT_DOWNLOAD_URL_PATH:"/api/amis/app-manage/v1/objects/url/reapply",DEVICE_ADD_PATH:"/api/cps/device-manage/v1/device/add",DEVICE_LIST_PATH:"/api/cps/device-manage/v1/device/list",PROVISION_ADD_REAL_PATH:"/api/cps/provision-manage/v1/ide/real/provision/add",PROVISION_ADD_TEST_PATH:"/api/cps/provision-manage/v1/ide/test/provision/add",PROVISION_DELETE_PATH:"/api/cps/provision-manage/v1/provision/delete"},_e={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:Tx(".ohos","config"),DOWNLOAD_CONNECT_TIMEOUT_MS:5e3},ye={SUCCESS_MARKER:'"code":0',SQUARE_BRACKETS:"[]",OPENPROXY_BLOCKED_URL:"Openproxy_Blocked_URL_list",CERT_LIMIT_CODE:"205389872",USER_NOT_HARMONY_CODE:"205389904",DEVICE_EXCEEDS_LIMIT_CODE:"205389859",DEVICE_NAME_REPEAT_CODE:"205389857",PROVISION_EXCEEDS_LIMIT_CODE:"205389938",PROVISION_NAME_REPEAT_CODE:"205389830"},pt={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."},K={TOOLCHAIN_INIT_FAILED:"Auto-sign failed: unable to initialize toolchain",LOGIN_REQUIRED:"Failed to automatically generate signatures.Run devecocli auth login to sign in.",TEAM_INFO_FAILED:"Failed to obtain user team information.Check the network connection, HTTP proxy, and other configurations.",REALNAME_REQUIRED:"Users without real-name verification are not supported.Complete real-name verification in AppGallery Connect.",SESSION_EXPIRED:"User session expired or token invalid. Please login again.",REGION_CHINA_ONLY:"This feature is only available for accounts registered in Chinese mainland.",DEVICE_MISSING:"Unable to create the profile file due to missing devices.Connect a device through IP or USB, or manually add a device in AppGallery Connect first.If you are installing the HAP package on an emulator, you can skip the signing step.",DEVICE_DETECT_FAILED:"Unable to detect devices. Please check hdc status. If installing HAP on an emulator, signature step can be skipped.",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 zd(n){let e=n.replace(_e.TEAM_ID_INVALID_CHARS,"");return`${_e.CERT_NAME_PREFIX}${e}.cer`}function Yr(n,e,t){if(n===pt.FORBIDDEN)return e===ye.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN);if(n===pt.UNAUTHORIZED)return new Error(E.ERR_UNAUTHORIZED);if(t.includes(ye.USER_NOT_HARMONY_CODE))return new Error(E.ERR_USER_NOT_HARMONY);if(t.includes(ye.CERT_LIMIT_CODE))return new Error(E.ERR_CERT_LIMIT_REACHED);let r=kx(t);return new Error(r??E.ERR_DOWNLOAD_CER)}function kx(n){let e=hw(n);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let r=typeof t=="string"?hw(t):t;if(r&&typeof r=="object"){let o=r.msg;if(typeof o=="string"&&o.trim()!=="")return o}return null}function hw(n){try{return JSON.parse(n)}catch{return null}}function qd(n){return JSON.parse(n)}async function gw(n){let e=`${Q.BASE_URL}${Q.CERT_LIST_PATH}`,t=await N.postAllowFailure(e,{headers:za(n)});if(t.statusCode!==200)throw Yr(t.statusCode,t.statusText,t.data);return qd(t.data)?.certList??[]}async function qa(n,e){return(await gw(n)).find(r=>r.certName===e)??null}async function Vd(n,e){let t=`${Q.BASE_URL}${Q.CERT_DELETE_PATH}`,r=await N.deleteAllowFailure(t,{headers:za(n),params:{certIds:[e]}});if(r.statusCode!==200)throw Yr(r.statusCode,r.statusText,r.data);return qd(r.data)?.ret?.code===0}async function Jd(n,e,t){let r=`${Q.BASE_URL}${Q.CERT_ADD_PATH}`,o={csr:e,certName:t,certType:_e.CERT_TYPE_DEBUG},i=await N.postAllowFailure(r,{headers:za(n),params:o});if(i.statusCode!==200)throw Yr(i.statusCode,i.statusText,i.data);if(!i.data.includes(ye.SUCCESS_MARKER))throw Yr(void 0,i.statusText,i.data)}async function Yd(n,e){let t=`${Q.BASE_URL}${Q.CERT_DOWNLOAD_URL_PATH}`,r=await N.postAllowFailure(t,{headers:za(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw Yr(r.statusCode,r.statusText,r.data);return qd(r.data)?.urlsInfo?.[0]?.newUrl??null}import{mkdirSync as xx,writeFileSync as Nx,existsSync as Lx}from"fs";import{dirname as Ox}from"path";async function Si(n,e){let{statusCode:t,statusText:r,buffer:o}=await N.getBinaryAllowFailure(n,{timeout:_e.DOWNLOAD_CONNECT_TIMEOUT_MS});if(t!==200)throw t===pt.FORBIDDEN&&r===ye.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_DOWNLOAD_CER);let i=Ox(e);Lx(i)||xx(i,{recursive:!0}),Nx(e,o)}import Zx from"fs/promises";import{readFileSync as Qx}from"fs";import Va from"path";import vw from"crypto";import Mx from"os";import bi from"fs/promises";var Sw={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},yw=["ECC","RSA"],ww=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],_x={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},Fx=8,Kd=64,jx=/[\\:*?"<>|=-]/g,ft={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function Hx(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>Kd)throw new Error(`The length of keyAlias cannot exceed ${Kd}`);if(!yw.includes(n.keyAlg))throw new Error(`Invalid key algorithm ${n.keyAlg}, available: ${yw.join(" / ")}`);let e=_x[n.keyAlg];if(!e.includes(n.keySize))throw new Error(`Key algorithm ${n.keyAlg} does not support size ${n.keySize}, available: ${e.join(", ")}`)}function $x(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(!ww.includes(n.signAlg))throw new Error(`Invalid sign algorithm ${n.signAlg}, available: ${ww.join(" / ")}`)}function Ux(n){return vw.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function Bx(n){let e=n?.trim()??"";return e&&e.replace(jx,"_").slice(0,Kd)||ft.productName}async function bw(){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;f.info(`\u8BFB\u53D6SDK\u6839\u76EE\u5F55\uFF1A${t}`);let r=b()?"hap-sign-tool":"hap-sign-tool.jar",o=Va.join(t,"default","openharmony","toolchains","lib",r);try{await bi.access(o)}catch(i){throw new Error(`${r} not found: ${o}`,{cause:i})}return{javaPath:e,toolPath:o}}async function Wx(n){let{javaPath:e,toolPath:t}=await bw(),r=[Sw.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 f.debug("generate-keypair \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),b()?[t,...r]:[e,"-jar",t,...r]}async function Gx(n){let{javaPath:e,toolPath:t}=await bw(),r=[Sw.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 f.debug("generate-csr \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),b()?[t,...r]:[e,"-jar",t,...r]}async function zx(n){f.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),Hx(n);let e=await Wx(n),t=await lo(e[0],e.slice(1));if(t.exitCode!==0){let r=t.stderr||t.stdout||"Unknown tool error";throw new Error(`An error occurred while generating the private key P12, exit code${t.exitCode}\uFF1A${r}`)}return f.info("\u751F\u6210P12\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}async function qx(n){f.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),$x(n);let e=await Gx(n),t=await lo(e[0],e.slice(1));if(t.exitCode!==0){let r=t.stderr||t.stdout||"Unknown tool error";throw new Error(`An error occurred while generating the CSR, exit code${t.exitCode}\uFF1A${r}`)}return f.info("\u751F\u6210CSR\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}function Vx(n=Fx){return vw.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function Jx(){let n=Mx.homedir();try{await bi.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=Va.join(n,b()?"Documents":"",".ohos","config");try{await bi.mkdir(e,{recursive:!0,mode:448})}catch(t){throw new Error(`Failed to create directory ${e}`,{cause:t})}return f.info(`\u7B7E\u540D\u914D\u7F6E\u76EE\u5F55\u5C31\u7EEA\uFF1A${e}`),e}async function Ee(n,e,t){let r=Bx(n),o=Va.basename(e),i=Ux(e),s=`${r}_${o}_${i}=.${t}`,a=await Jx();return Va.join(a,s)}function Yx(n){let e;try{e=G.discover(n).rootDir}catch(t){throw new Error(`Current directory ${n} is not a valid project root`,{cause:t})}return e}async function Kx(n){try{await bi.access(n)}catch(e){throw new Error(`Project directory ${n} is not accessible, missing read/write permissions`,{cause:e})}}async function Xx(n){try{await bi.access(n)}catch(e){throw new Error(`P12 file ${n} does not exist, terminating CSR generation.`,{cause:e})}}async function Xd(n,e,t){let r=process.cwd(),o=Yx(r);await Kx(o),f.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${o}`);let i=Vx(),s=await Ee(n??"",o,"p12"),a=await Ee(n??"",o,"csr");return console.log("Start generating p12"),await zx({keyAlias:e?.keyAlias??ft.keyAlias,keyPwd:i,keyAlg:e?.keyAlg??ft.keyAlg,keySize:e?.keySize??ft.keySize,keystoreFile:s,keystorePwd:i}),await Xx(s),console.log("Start generating csr"),await qx({subject:t?.subject??ft.csrSubject,outFile:a,keyAlias:t?.keyAlias??ft.keyAlias,keyPwd:i,signAlg:t?.signAlg??ft.signAlg,keystoreFile:s,keystorePwd:i}),{p12FilePath:s,csrFilePath:a,keyPwd:i,keyAlias:e?.keyAlias??ft.keyAlias}}var eN=["p12","cer","csr","p7b"];async function Zd(n,e){for(let t of eN){let r=await Ee(n,e,t);await Zx.rm(r,{force:!0})}}function Qd(n){let e;try{e=Qx(n,"utf-8")}catch{throw new Error(E.ERR_CERT_INVALIDATE)}if(!_e.CERT_PATTERN.test(e))throw new Error(E.ERR_CERT_INVALIDATE)}async function Ew(n,e){return{certPath:await Ee(n,e,"cer"),csrPath:await Ee(n,e,"csr"),p12Path:await Ee(n,e,"p12"),profilePath:await Ee(n,e,"p7b")}}async function eu(n,e){let t=e??"",r=G.discover(process.cwd()).rootDir;await Zd(t,r);let o=zd(n.teamId),i=await qa(n,o);if(i&&!await Vd(n,i.id))throw new Error(E.ERR_DOWNLOAD_CER);let s=await Xd(e),a;try{a=tN(s.csrFilePath,"utf-8")}catch{throw new Error(E.ERR_READ_CSR)}console.log("Start generating certificate"),await Jd(n,a,o);let c=await qa(n,o);if(!c)throw new Error(E.ERR_DOWNLOAD_CER);let l=await Yd(n,c.certObjectId);if(!l)throw new Error(E.ERR_DOWNLOAD_CER);let d=await Ee(t,r,"cer");await Si(l,d),Qd(d);let h=await Ee(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 rc from"crypto";import In from"fs";import*as Fw from"path";import PN from"json5";import{execa as Ow}from"execa";import Mw from"node-forge";import{createCipheriv as nN,createDecipheriv as rN,pbkdf2Sync as oN,randomBytes as ou}from"crypto";import{promises as Xn}from"fs";import{dirname as iN,join as mt}from"path";var Ja=3,Ei=16,sN=1e4,Pw="material",aN=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Dw="aes-128-gcm",Kn=12,Ya=16,En=4;function tu(n){return new Uint8Array(ou(n))}function cN(n){return ou(n).toString("hex")}function lN(...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 Cw(n,e,t=sN,r=Ei){let o=[...n,aN],i=lN(...o),s=Buffer.from(i).toString("utf8"),a=Buffer.from(s,"utf8"),c=oN(a,e,t,r,"sha256");return new Uint8Array(c)}function Iw(n,e){let t=ou(Kn),r=nN(Dw,n,t),o=Buffer.concat([r.update(e),r.final()]),i=r.getAuthTag(),s=Buffer.concat([o,i]),a=s.length,c=Buffer.alloc(En+Kn+s.length);return c.writeUInt32BE(a,0),t.copy(c,En),s.copy(c,En+Kn),c}function Aw(n,e){if(e.length<En+Kn+Ya)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(En,En+Kn),o=e.subarray(En+Kn,En+Kn+t);if(o.length<Ya)throw new Error("Ciphertext too short for auth tag");let i=o.subarray(0,o.length-Ya),s=o.subarray(o.length-Ya),a=rN(Dw,n,r);return a.setAuthTag(s),Buffer.concat([a.update(i),a.final()])}async function dN(n){try{await Xn.rm(n,{recursive:!0,force:!0})}catch{}}async function nu(n){let e=await Xn.readdir(n),t=e.filter(r=>r!==".DS_Store");if(t.length!==1)throw new Error(`Expected exactly 1 file in ${n}, but found ${t.length} (filtered from ${e.length})`);return Xn.readFile(mt(n,t[0]))}async function ru(n,e){let t=cN(Ei),r=mt(n,t);return await Xn.writeFile(r,e),t}var Pn=class{static async generateMaterial(e){let t=mt(e,Pw);await dN(t);let r=mt(t,"ac"),o=mt(t,"ce");await Xn.mkdir(r,{recursive:!0}),await Xn.mkdir(o,{recursive:!0});for(let d=0;d<Ja;d++)await Xn.mkdir(mt(t,"fd",String(d)),{recursive:!0});let i=tu(Ei),s=[];for(let d=0;d<Ja;d++)s.push(tu(Ei));let a=tu(Ei),c=Cw(s,i),l=Iw(c,a);await ru(r,i),await ru(o,l);for(let d=0;d<Ja;d++){let h=mt(t,"fd",String(d));await ru(h,s[d])}return a}static async readMaterial(e){let t=mt(e,Pw),r=mt(t,"ac"),o=new Uint8Array(await nu(r)),i=[];for(let d=0;d<Ja;d++){let h=mt(t,"fd",String(d)),w=await nu(h);i.push(new Uint8Array(w))}let s=mt(t,"ce"),a=await nu(s),c=Cw(i,o),l=Aw(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t=iN(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 Iw(r,o).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let r=await this.getStoreKey(t),o=Buffer.from(e,"hex");return Aw(r,o).toString("utf8")}};import Nw from"fs";import tc from"path";import gN from"json5";import*as Ka from"fs";import*as Rw from"path";function Xa(n){let e=Rw.resolve(n);if(!Ka.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=Ka.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 Xr from"fs";import*as Fe from"path";import{debuglog as Kr}from"util";var Tw={"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 uN(n){return Object.prototype.hasOwnProperty.call(Tw,n)}function Za(n){if(uN(n))return Tw[n]}var kw={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as pN}from"url";var ec=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 Qa(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function xw(n){return n==null||n.length===0}function fN(n){return!xw(n)}function iu(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function mN(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 hN(n,e){let t=n[e];if(typeof t=="number")return Math.trunc(t);if(typeof t=="string"){let r=Number.parseInt(t,10);return Number.isNaN(r)?0:r}return 0}var Cn=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=Fe.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=Fe.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=Fe.join(t.sdkPath,"default","sdk-pkg.json"),a=Xa(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=Fe.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(Xr.existsSync(e))return Xr.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=pN(e);if(t.includes("dist")){let s=Fe.dirname(t),a=Fe.dirname(s);return Fe.join(a,"src","resources")}let r=Fe.dirname(t),o=Fe.dirname(r),i=Fe.dirname(o);return Fe.join(i,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let r;try{r=this.readBuiltInConfigText()}catch{Kr("read builtin acl permission failed.");return}if(r!==void 0)try{let o=JSON.parse(r),s=(Array.isArray(o)?o:Qa(o)?Object.values(o):[]).filter(Qa).map(a=>new ec(a));s.forEach(a=>{let c=a.permissionInsteadName;fN(c)&&(a.permissionInsteadName=Za(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(o){Kr(`failed to parse aclPermissionsInfo.json: ${o}`)}}static initAclPermissionFromSDK(e,t,r){let o=this.parsePermissionDefinitionFile(e);o&&o.forEach(i=>{if(!Qa(i))return;let s=i,a=iu(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(xw(a)||(this.generateAclInfos(r,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||iu(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||iu(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:mN(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let o=new ec;o.permissionName=t;let i=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;o.permissionDisplayName=i;let s=hN(r,this.ACL_SINCE_KEY);o.minSupportApiLevel=String(s),this.handleInsteadName(o,i),e.add(o)}static parsePermissionDefinitionFile(e){let t=Fe.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!Xr.existsSync(t))return;let r;try{r=Xr.readFileSync(t,"utf-8")}catch(s){Kr(`failed to load permissionDefinitions.json: ${s}`);return}let o;try{let s=JSON.parse(r);if(!Qa(s)){Kr("json object is null");return}o=s}catch(s){Kr(`failed to parse permissionDefinitions.json: ${s}`);return}let i=o[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(i)){Kr("definePermissions is not an array");return}return i}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=Za(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=Za(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function nc(n,e){let t=new Set,r=new Set;Cn.handleSpecificAclPermissions(),Cn.initAclPermission(n,e);for(let o of n.profile.modules){let i=Lw(o,n,e,r,tc.join("src","main"));for(let a of i)t.add(a);let s=Lw(o,n,e,r,tc.join("src","ohosTest"));for(let a of s)t.add(a)}return yN(r),t}function yN(n){if(n.size>0)throw new Error(kw.DUPLICATE_PERMISSION)}function Lw(n,e,t,r,o){let i=vN(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 S=wN(w,"name");S&&s.push(S)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=tc.join(t.sdkPath,"default","sdk-pkg.json"),l=Xa(c),d=Cn.getAclPermissionInfos(e),h=new Set(Array.from(d).filter(w=>{let S=Number(w.minSupportApiLevel);return Number.isFinite(S)&&S<=l}).map(w=>w.permissionName));for(let w of Array.from(a))h.has(w)||a.delete(w);return a}function wN(n,e){let t=n[e];return typeof t=="string"?t:""}function vN(n,e,t){let r=tc.join(n,e.srcPath,t,"module.json5"),o=SN(r);if(o==null)return null;let i=bN(o,"module");return i==null?null:EN(i,"requestPermissions")}function SN(n){try{if(!Nw.existsSync(n))return null;let e=Nw.readFileSync(n,"utf-8");return gN.parse(e)}catch{return null}}function bN(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 EN(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}var au=class{verifyStorePassword(e,t){try{let r=In.readFileSync(e),o=Mw.asn1.fromDer(r.toString("binary"));return Mw.pkcs12.pkcs12FromAsn1(o,t),!0}catch{return!1}}getLocalCerFingerprints(e){let r=In.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(r&&r.length>0)return r.map(o=>this.formatFp(new rc.X509Certificate(o).fingerprint256));try{return[this.formatFp(new rc.X509Certificate(In.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let o=In.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let i of o)try{let s=new rc.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 CN(n){let e=In.readFileSync(n,"utf-8"),t=IN(e),r=null;if(t)try{r=JSON.parse(t)}catch{r=null}let o=r?.["bundle-info"]??{};return{rawContent:e,bundleNameInProfile:su(o["bundle-name"]),expiryDate:AN(r?.validity?.["not-after"]),cerFingerprintInProfile:DN(su(o["development-certificate"])),deviceUdidsInProfile:RN(r?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:TN(r?.acls?.["allowed-acls"]),teamIdInProfile:su(o["developer-id"])}}function IN(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 AN(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function DN(n){if(!n)return null;try{let t=new rc.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function RN(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 TN(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 su(n){return typeof n=="string"?n:null}var Pi=class n{static async shouldRegenerate(e,t){let r=await n.#e(e,t);return n.#t(r)??n.#n(r)??n.#r(r)??n.#o(r)??n.#i(r)??n.#s(r)??n.#a(r)??n.#c(r)??n.#l(r)??n.#d(r)??await n.#u(r)??n.#p()}static async#e(e,t){let r=e.force,o=e.teamId,i=e.productName??"default",s=G.discover(process.cwd()),a=s.rootDir,[c,l]=await Promise.all([kN(i,a),NN(t.hdcPath)]),d=null;if(_w(c).allExist)try{d=CN(c.profileFile)}catch{}return{force:r,teamId:o,productName:i,projectPath:a,materialPaths:c,bundleName:s.getBundleName(),deviceUdids:l,storePassword:await xN(a,i,c.storeFile),localAclPermissions:[...nc(s,t)].sort(),hapSignTool:new au,profileInfo:d}}static#t(e){return e.force?(m("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:Be({force:!0})}):null}static#n(e){let t=_w(e.materialPaths);return t.allExist?null:(m(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:Be({allFilesExist:!1,missingFiles:t.missing})})}static#r(e){return(e.profileInfo?.rawContent??"").trim().length>0?null:(m("[reGenerateSign] profile content is empty"),{shouldRegenerate:!0,reason:"Profile file content is empty",checkDetails:Be({allFilesExist:!0,profileContentNotEmpty:!1})})}static#o(e){let t=e.profileInfo?.expiryDate;return!t||t>=new Date?null:(m(`[reGenerateSign] profile expired at ${t.toISOString()}`),{shouldRegenerate:!0,reason:`Profile expired at ${t.toISOString()}`,checkDetails:Be({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!1})})}static#i(e){let t=e.profileInfo?.bundleNameInProfile;return t&&t===e.bundleName?null:(m(`[reGenerateSign] bundleName mismatch \u2014 current=${e.bundleName}, profile=${t}`),{shouldRegenerate:!0,reason:`bundleName mismatch: current=${e.bundleName}, in profile=${t}`,checkDetails:Be({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!1})})}static#s(e){let t=e.profileInfo?.teamIdInProfile;return t&&t===e.teamId?null:(m(`[reGenerateSign] teamId mismatch \u2014 current=${e.teamId}, profile=${t}`),{shouldRegenerate:!0,reason:`teamId mismatch: current=${e.teamId}, in profile=${t}`,checkDetails:Be({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=ON(e.profileInfo?.deviceUdidsInProfile??[],e.deviceUdids);return t.allPresent?null:(m(`[reGenerateSign] missing device UDIDs: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Device UDID(s) not in profile: ${t.missing.join(", ")}`,checkDetails:Be({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return MN(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(m("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:Be({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!1})})}static#l(e){let t=e.hapSignTool.getLocalCerFingerprints(e.materialPaths.cerFile),r=e.profileInfo?.cerFingerprintInProfile;return r&&t.includes(r)?null:(m("[reGenerateSign] certificate mismatch"),{shouldRegenerate:!0,reason:"Certificate mismatch between profile and local .cer file",checkDetails:Be({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!1})})}static#d(e){let t=e.profileInfo?.cerFingerprintInProfile,r=e.hapSignTool.getLocalCerExpiry(e.materialPaths.cerFile,t);return!r||r>=new Date?null:(m(`[reGenerateSign] local certificate expired at ${r.toISOString()}`),{shouldRegenerate:!0,reason:`Local certificate expired at ${r.toISOString()}`,checkDetails:Be({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!1})})}static async#u(e){return e.storePassword?e.hapSignTool.verifyStorePassword(e.materialPaths.storeFile,e.storePassword)?null:(m("[reGenerateSign] keystore password verification failed"),{shouldRegenerate:!0,reason:"Keystore password verification failed (storeFile may be corrupted or password changed)",checkDetails:Be({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})}):(m("[reGenerateSign] no stored keystore password"),{shouldRegenerate:!0,reason:"No stored keystore password available for verification",checkDetails:Be({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})})}static#p(){return m("[reGenerateSign] all checks passed \u2014 skip regeneration"),{shouldRegenerate:!1,reason:"",checkDetails:Be({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function kN(n,e){let[t,r,o,i]=await Promise.all([Ee(n,e,"p12"),Ee(n,e,"csr"),Ee(n,e,"cer"),Ee(n,e,"p7b")]);return{storeFile:t,csrFile:r,cerFile:o,profileFile:i}}async function xN(n,e,t){let r=Fw.join(n,"build-profile.json5");if(!In.existsSync(r))return;let o;try{o=PN.parse(In.readFileSync(r,"utf-8"))}catch{return}let a=(o?.app?.signingConfigs??[]).find(c=>c.name===e)?.material?.storePassword;if(a)try{return await Pn.decryptPassword(a,t)}catch{return}}async function NN(n){m(`Executing: ${n} list targets`);let{stdout:e}=await Ow(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let o of e.split(`
1412
- `)){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{m(`Executing: ${n} -t ${o} shell bm get -u`);let{stdout:i}=await Ow(n,["-t",o,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),s=LN(i);s&&r.push(s)}catch{m(`[reGenerateSign] Failed to get UDID for ${o}, skipping`)}return r}function LN(n){let e=n.trim();if(!e)return null;let t=e.split(`
1413
- `);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 _w(n){let e=[n.storeFile,n.csrFile,n.cerFile,n.profileFile],t=[];for(let r of e)In.existsSync(r)||t.push(r);return{allExist:t.length===0,missing:t}}function ON(n,e){let t=[];for(let r of e)n.includes(r)||t.push(r);return{allPresent:t.length===0,missing:t}}function MN(n,e){let t=[...n].sort(),r=[...e].sort();return t.length!==r.length?!1:t.every((o,i)=>o===r[i])}function Be(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 cu}from"util";import{execa as lu}from"execa";async function Hw(n,e){let t=await oc(n);if(!t)throw new Error(E.DEVICE_LIST_EMPTY);let r=await jN(e);if(t.length===0)for(let s of r)await _N(n,s.udid,s.deviceName);else for(let s of r)await FN(n,t,s.udid,s.deviceName);let i=(await oc(n)).map(s=>s.id);if(i.length===0)throw new Error(E.DEVICE_LIST_EMPTY);return i}async function _N(n,e,t){await Bw(n,e,$w(t))}async function FN(n,e,t,r){for(let o=0;o<e.length;o++){if(t===e[o].udid)return;if(o===e.length-1){await Bw(n,t,$w(r));return}}}function $w(n){switch(n){case"liteWearable":return"1";case"wearable":return"2";case"tv":return"3";default:return"4"}}async function jw(n,e=1,t=100){let r=`${Q.BASE_URL}${Q.DEVICE_LIST_PATH}?encodeFlag=0&start=${e}&pageSize=${t}`,o=Ww(n),i=await N.get(r,{headers:o});if(!i)throw cu("query devices failed: response is null"),new Error(E.ERROR_WHILE_ADD_DEVICE);if(i.statusCode!==200)throw Uw(i.statusCode,i.statusText,i.data);let s=JSON.parse(i.data);if(!s||!s.list)throw cu("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 Uw(n,e,t){return n===pt.FORBIDDEN?e===ye.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN):n===pt.UNAUTHORIZED?new Error(E.ERR_UNAUTHORIZED):t.includes(ye.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(E.DEVICE_LIMIT_REACHED):new Error(E.ERROR_WHILE_ADD_DEVICE)}async function oc(n){let t=await jw(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 jw(n,s,100);if(!a||!a.deviceList||a.deviceList.length===0)break;r.push(...a.deviceList)}return r}async function Bw(n,e,t){let r=`${Q.BASE_URL}${Q.DEVICE_ADD_PATH}`,o=Ww(n),s={deviceName:`auto_sign_device_No.${Math.floor(Math.random()*3e3)}${Date.now()}`,udid:e,deviceType:t},a=await N.postAllowFailure(r,{headers:o,params:s});if(!a)throw cu("add device failed: response is null"),new Error(E.ERROR_WHILE_ADD_DEVICE);if(a.statusCode!==200)throw Uw(a.statusCode,a.statusText,a.data);let c=a.data,l=JSON.parse(a.data);if(!l||!l.ret||l.ret.code!==0)throw c.includes(ye.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(E.DEVICE_LIMIT_REACHED):c.includes(ye.DEVICE_NAME_REPEAT_CODE)?new Error(E.DEVICE_NAME_REPEAT):new Error(E.ERROR_WHILE_ADD_DEVICE)}function Ww(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}async function jN(n){let{stdout:e}=await lu(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{let i=await HN(o,n),s=await $N(o,n);i.length>0&&r.push({id:"",udid:i,deviceName:s})}catch{m(`Failed to get device info for ${o}, skipping`)}return r}async function HN(n,e){let{stdout:t}=await lu(e,["-t",n,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),r=t.trim();if(!r)return"";let o=r.split(`
1415
- `);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 $N(n,e){let{stdout:t}=await lu(e,["-c","-t",n,"shell","getprop","hw_sc.build.os.deviceType"],{stdio:["ignore","pipe","pipe"]});return UN(t)}function UN(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 Zn from"fs";import{createHash as BN}from"crypto";import{debuglog as Gt}from"util";import{Buffer as zw}from"buffer";import{createPublicKey as WN,X509Certificate as du}from"crypto";import{readFileSync as GN}from"fs";import Qn from"node-forge";async function qw(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=`${Q.BASE_URL}${Q.PROVISION_ADD_TEST_PATH}`,h=zN(t,r),w=await VN(n,d,a||[],r,s,h,i||[]);if(!w||!w.profileInfo||!w.profileInfo.provisionFileUrl)throw Gt("add provision failed, the provision file url is null"),new Error(E.ADD_PROFILE_FAIL);let S=w.profileInfo,re=(await XN(n,S.provisionFileUrl)).urlList,De=w.profileInfo.id;if(re&&re.length>0){let Pe=await Ew(t,o),We=Pe.profilePath;if(!await ZN(re,We))throw await Gw(n,De),new Error(E.ERROR_WHILE_DOWNLOAD_PROFILE);if(await Gw(n,De),Zn.existsSync(Pe.certPath)&&Zn.existsSync(We)&&Zn.existsSync(Pe.p12Path)){let ev=Zn.readFileSync(Pe.certPath,"utf8"),tv=Zn.readFileSync(We,"utf8");return QN(tv,ev,Pe.p12Path,c,l)||KN(We),We}}throw new Error(E.ADD_PROFILE_FAIL)}function zN(n,e){let t=n?`${n}_`:"";return`${qN(`${t}${e}_${e}`)}`}function qN(n){return BN("sha256").update(n).digest("hex").substring(0,16)}async function VN(n,e,t,r,o,i,s){JN(r);let a=pu(n),c={certList:t,packageName:r,deviceList:o,provisionName:i};s.length&&(c.aclPermissionList=s);let l=await N.postAllowFailure(e,{headers:a,params:c});if(!l)throw Gt("add provision failed: response is null"),new Error(E.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw uu(l.statusCode,l.statusText,l.data);let d=JSON.parse(l.data);if(!d||!d.ret||d.ret.code!==0)throw Gt(`add provision fail: ${l.data}`),YN(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 uu(n,e,t){return n===pt.FORBIDDEN?e===ye.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN):n===pt.UNAUTHORIZED?new Error(E.ERR_UNAUTHORIZED):t.includes(ye.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(E.TEST_PROVISION_EXCEEDS_LIMIT):new Error(E.ADD_PROFILE_FAIL)}function JN(n){if(!n||n.trim().length===0)throw new Error(E.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!_e.BUNDLE_NAME_REGEX.test(n))throw new Error(E.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function YN(n,e){if(n.includes(ye.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(E.TEST_PROVISION_EXCEEDS_LIMIT);if(n.includes(ye.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(E.PROFILE_NAME_REPEAT)}async function Gw(n,e){if(!e||e.trim().length===0)return;let t=`${Q.BASE_URL}${Q.PROVISION_DELETE_PATH}?id=${e}`,r=await N.deleteAllowFailure(t,{headers:pu(n)});if(r.statusCode!==200)throw uu(r.statusCode,r.statusText,r.data);let o=JSON.parse(r.data);(!o||!o.ret||o.ret.code!==0)&&Gt(`delete provision failed: ${r.data}`)}function KN(...n){for(let e of n)try{Zn.existsSync(e)&&Zn.unlinkSync(e)}catch(t){Gt(`delete local sign file error: ${t.message}`)}}async function XN(n,e){let t=`${Q.BASE_URL}${Q.CERT_DOWNLOAD_URL_PATH}`,r=pu(n),o={sourceUrls:e},i=await N.postAllowFailure(t,{headers:r,params:o});if(!i)throw Gt("get download list failed: response is null"),new Error(E.ADD_PROFILE_FAIL);if(i.statusCode!==200)throw uu(i.statusCode,i.statusText,i.data);let s=JSON.parse(i.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw Gt("download: The application does not exist"),new Error(s.ret?.msg||E.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function ZN(n,e){if(!n||n.length===0)return!1;let t=n[0].newUrl;return await Si(t,e),!0}function QN(n,e,t,r,o){return eL(n,e),r=r||_e.TARGET_FRIENDLY_NAME,o=o||"",tL(e,t,r,o),!0}function eL(n,e){if(e.lastIndexOf(_e.CERT_BEGIN_HEADER)<0)throw new Error(E.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(_e.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!n.includes(t))throw new Error(E.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}function tL(n,e,t,r){let o=n.matchAll(_e.CERTIFICATE_PATTERN_GLOBAL),i=[],s=new Date;for(let c of o)try{let l=c[0],d=nL(l),h=new Date(d.validFrom),w=new Date(d.validTo);if(s<h||s>w){let S=`Certificate is not valid, Valid from ${h} to ${w}`;throw console.warn(`checkCertificateInValidityPeriod: ${S}`),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(!oL(e,t,r,i))throw new Error(E.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function nL(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new du(t);let r=zw.from(t,"base64");return new du(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}function rL(n){if(n.cert){let e=Qn.pki.publicKeyToPem(n.cert.publicKey);return WN(e).export({type:"spki",format:"der"})}if(n.asn1)try{let e=Qn.asn1.toDer(n.asn1).getBytes(),t=zw.from(e,"binary");return new du(t).publicKey.export({type:"spki",format:"der"})}catch(e){return Gt(`Failed to parse cert from asn1: ${e}`),null}return null}function oL(n,e,t,r){try{let o=GN(n),i=Qn.asn1.fromDer(Qn.util.createBuffer(o)),c=Qn.pkcs12.pkcs12FromAsn1(i,t).getBags({bagType:Qn.pki.oids.certBag})[Qn.pki.oids.certBag]||[];for(let l of c){let d=l.attributes?.friendlyName?.[0];if(!d||d.toLowerCase()!==e.toLowerCase())continue;let h=rL(l);if(!h)continue;if(r.some(S=>{let k=S.publicKey.export({type:"spki",format:"der"});return h.equals(k)}))return!0}return!1}catch(o){let i=o instanceof Error?o.message:String(o);return Gt(`Failed to process P12 file: ${n}, error: ${i}`),!1}}function pu(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var Jw="https://developer.huawei.com",iL={"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"},sL="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function aL(n){let e=iL[n];return e?`${Jw}${e}`:void 0}function cL(){return`${Jw}${sL}`}var lL={"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 Vw(n,e){return(lL[n]??n).replace(/\{(\d+)\}/g,(r,o)=>String(e[Number(o)]??""))}function dL(n){return Array.from(n).join(", ")}function Yw(n,e){if(n.size===0)return;let t=Cn.getAclPermissionInfos(e),r=new Set;for(let h of t)n.has(h.permissionName)&&r.add(h);for(let h of r){let w=aL(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=cL(),a=Vw("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=i.size>0?Array.from(i).join(", ")+".":"",d=Vw("acl.permissions.warn",[dL(o),l,c]);console.log(d)}var ic=class{_project=null;get project(){if(!this._project)throw new Error("Project not initialized. Call checkProjectDir first.");return this._project}checkProjectDir(e){try{return this._project=G.discover(process.cwd()),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Project.discover() failed: ${t.message}`),e(K.PROJECT_DIR_MISSING)}}checkProduct(e,t){try{return this._project.validateProduct(e),{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Product validation failed: ${r.message}`),t(`Product "${e}" not found.Check the product property in the build-profile.json5 file.`)}}checkBundleName(e,t){try{return this._project.getBundleName(),{passed:!0,message:""}}catch(r){return m(`[EnvCheck] BundleName check failed: ${r.message}`),t(`bundleName was not found under product "${e}".Check the bundleName configuration.`)}}checkAtomicService(){return this._project.isAtomicService()?{passed:!1,message:K.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import uL from"fs";import Kw from"path";var sc=class{constructor(e){this.toolProvider=e}toolProvider;checkJava(e){try{return this.toolProvider.assertJava(),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Java check failed: ${t.message}`),e(K.JAVA_PLATFORM_UNSUPPORTED)}}checkHapSignTools(e){let t=this.toolProvider.sdkPath,r=b()?"hap-sign-tool":"hap-sign-tool.jar",o=Kw.join(t,"default","openharmony","toolchains","lib",r);if(!uL.existsSync(o)){let i=Kw.join("sdk","default","openharmony","toolchains","lib",r);return e(`${r} not found.Check whether ${i} exists.`)}return{passed:!0,message:""}}};var ac=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await ae.getUserInfo()}catch(e){return m(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await ae.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(K.LOGIN_REQUIRED)}catch(t){return m(`[EnvCheck] Login check failed: ${t.message}`),e(K.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(K.TEAM_INFO_FAILED);try{if((await Qt()).teamList.length>0)return{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Team API error: ${r.message}`),e(K.TEAM_INFO_FAILED)}return m("[EnvCheck] No teams found for current user"),e(K.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(K.REALNAME_REQUIRED):t.isRealName!==!0?(m("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(K.REALNAME_REQUIRED)):{passed:!0,message:""}:e(K.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let r=e??"";try{let o=await Qt();if(r=e??(o.teamList.length>0?o.teamList[0].id:t.userId)??"",!o.teamList.some(s=>s.id===r)){let s=`team-id for ${r} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`;return m(`[EnvCheck] ${s}`),{passed:!1,message:s}}return{passed:!0,message:""}}catch(o){return m(`[EnvCheck] Team ID check failed: ${o.message}`),{passed:!1,message:`team-id for ${r} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`}}}async checkRegion(e){let t=await this.ensureUserInfo();return t?t.countryCode?t.countryCode!=="CN"?e(K.REGION_CHINA_ONLY):{passed:!0,message:""}:(m("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(K.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function pL(n){try{let{teamList:e}=await Qt();if(e.length>0)return e[0].id}catch(e){m(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function fL(n){let e=await ae.getUserInfo(),t=await ae.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await pL(e.userId);if(!r)throw new Error("No team found");let o={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await oc(o)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var cc=class{constructor(e){this.toolProvider=e}toolProvider;async checkDevice(e,t){try{let r=await fL(t);if(r.length>0)return m(`[EnvCheck] Scenario 4 Device check: ${r.length} device(s) found in AGC cloud, skipping local device check`),{passed:!0,message:""};m("[EnvCheck] Scenario 4 Device check: no cloud devices found, falling back to local hdc");let i=await te.from(this.toolProvider).listDevices();return i.length===0?(m("[EnvCheck] Scenario 4 Device check: no local devices found"),e(K.DEVICE_MISSING)):i.some(a=>Ln(a.serial))?{passed:!0,message:""}:(m("[EnvCheck] Scenario 4 Device check: local device found but not an emulator"),e(K.DEVICE_MISSING))}catch(r){return m(`[EnvCheck] Scenario 4 Device check failed: ${r.message}`),e(K.DEVICE_DETECT_FAILED)}}};var lc=class{projectChecker=new ic;toolchainChecker=null;authChecker=new ac;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.checkTeamInfo(t),()=>this.authChecker.checkRealname(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 sc(e),this.deviceChecker=new cc(e),!0}catch(e){throw m(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(K.TOOLCHAIN_INIT_FAILED,{cause:e})}}async runDeviceCheck(e,t){return(o=>o.passed?!0:(this.fail(o),!1))(await this.deviceChecker.checkDevice(t,e.teamId))}async runProjectChecks(e,t){let r=i=>i.passed?!0:(this.fail(i),!1);if(!r(this.projectChecker.checkProjectDir(t))||!r(this.projectChecker.checkAtomicService()))return!1;let o=[()=>this.projectChecker.checkProduct(e.productName,t),()=>this.projectChecker.checkBundleName(e.productName,t),()=>this.toolchainChecker.checkJava(t),()=>this.toolchainChecker.checkHapSignTools(t)];for(let i of o)if(!r(i()))return!1;return!0}async runAuxChecks(e){let t=r=>r.passed?!0:(this.fail(r),!1);return!e.teamId&&!t(await this.authChecker.checkTeamId(e.teamId))?!1:(await this.authChecker.checkRegion(r=>this.blockingFail(r)),!0)}blockingFail(e){return{passed:!1,message:e}}fail(e){throw m(`[EnvCheck] FAIL: ${e.message}`),new Error(e.message)}};function yL(n){if(mu.existsSync(n)){let e=mu.readFileSync(n,"utf-8");return gL.parse(e)}return{app:{signingConfigs:[],products:[]}}}function wL(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function vL(n){if(n.keyPwd===n.storePassword){let r=await Pn.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await Pn.encryptedPassword(n.keyPwd,n.p12FilePath),t=await Pn.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function SL(n,e,t){let r=Xw.join(n,"build-profile.json5"),o=yL(r);wL(o);let i=t??"default",{keyPassword:s,storePassword:a}=await vL(e),c={name:i,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:s,profile:e.profileFilePath,signAlg:ft.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}),mu.writeFileSync(r,JSON.stringify(o,null,2),"utf-8")}async function bL(n){let e=await ae.getUserInfo(),t=await ae.refreshToken();if(!e||!t)throw new Error("Failed to obtain login credentials. Run `devecocli login` again.");return{uid:e.userId??"",teamId:n.teamId??e.userId??"",accessToken:t.accessToken??""}}async function EL(n){let e=n.product||"default";await new lc().preflight({productName:e,teamId:n.teamId}),console.log("Executing signature generate command");let r=await bL(n),o=await A.new(),{shouldRegenerate:i}=await Pi.shouldRegenerate({force:n.force??!1,teamId:r.teamId,productName:n.product},o);if(!i){console.log(fu("Signature generation completed successfully."));return}await PL(n,r,o),console.log(fu("Signature generation completed successfully."))}async function PL(n,e,t){let r=await eu(e,n.product),o=CL(n,e,r,t);o.allDeviceIds=await Hw(e,t.hdcPath),await qw(e,o);let i=G.discover(process.cwd()).rootDir;await SL(i,r,n.product??"default"),console.log(fu(`Signing config written to ${Xw.join(i,"build-profile.json5")}`))}function CL(n,e,t,r){let o=process.cwd(),i=G.discover(o),s=nc(i,r);return Yw(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 Zw=new mL("signature").description("Generate application signature.");Zw.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 EL(n)}catch(e){console.error(hL(e.message)),process.exit(1)}});var Qw=Zw;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";IL();ie.name("devecocli").description("HarmonyOS application development command line tool").version("0.3.0-TD.1.3");ie.addCommand(Qu);ie.addCommand(Tp);ie.addCommand(Lp);ie.addCommand(qp);ie.addCommand(Uf);ie.addCommand(pm);ie.addCommand(gm);ie.addCommand(Am);ie.addCommand(Om);ie.addCommand(eh);ie.addCommand(uy);ie.addCommand(Qw);ie.addCommand(mw);ie.addCommand(_y);b()||ie.addCommand(Sf);var hu=process.argv.slice(2);hu.length>=2&&hu[hu.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var DL=new Set(["update","auth"]);ie.hook("preAction",async(n,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==ie;)t=t.parent;DL.has(t.name())||await A.checkVersion()});ie.parseAsync(process.argv).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(AL(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
1409
+ ${o.stderr}`:""));throw o.stdout&&(i.stdout=o.stdout),i}}function hx(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 gx(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.
1410
+ 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 yx(n,e,t,r,o){o==="none"&&(t==="json"?ux(n,r):dx(n,r)),lx(n,e)}function wx(n,e){let t=W.dirname(n),r=W.basename(n),o=e.slice(1).map(i=>i.startsWith("--")?i:`"${i}"`).join(" ");m(ge(`[compat:check] command: cd "${t}" && node "${r}" ${o}`))}function vx(n){try{Jk(n),m(ge(`[compat:check] cleaned up tmp report: "${n}"`))}catch(e){m(ge(`[compat:check] failed to clean up tmp report: ${e.message}`))}}var Sx=[".csv",".json"];function bx(n){return Sx.includes(n.toLowerCase())}function Ex(n,e){if(!n)return{kind:"none"};let t=W.extname(n).toLowerCase();if(!bx(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 Px(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 pw(n){return JSON.stringify({count:n.length,records:n},null,2)+`
1411
+ `}function Cx(n,e,t,r){r===".csv"?aw(n,t):cw(t,pw(e),"utf8"),m(ge(`[compat:check] saved report: "${t}"`))}function Ix(n,e,t,r){if(r==="json"){let i=W.basename(n,".csv"),s=W.join(t,`${i}.json`);return cw(s,pw(e),"utf8"),m(ge(`[compat:check] saved report: "${s}"`)),s}let o=W.join(t,W.basename(n));return aw(n,o),m(ge(`[compat:check] saved report: "${o}"`)),o}async function Ax(n,e){let t=new ke(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 Dx(n,e){hx(n,e);let t=G.discover(process.cwd());e.modules&&e.modules.length>0&&tx(t,e.modules),n.length>0&&nx(n);let r=await I.new(),{apiChangeDir:o,scriptPath:i}=r.getApiscanPaths();m(ge(`[compat:check] script: "${i}"`));let s=uw(o);gx(e,s),e.outputPath&&m(ge(`[compat:check] outputPath: "${e.outputPath}"`));let a=Ex(e.outputPath,e.format);return m(ge(`[compat:check] outputTarget: ${a.kind}`)),Px(a),{project:t,scriptPath:i,target:a,toolProvider:r}}async function Rx(n,e){let{project:t,scriptPath:r,target:o,toolProvider:i}=await Dx(n,e),s=Kk({text:"Running compatibility check...",color:"cyan"}).start();try{await Ax(i,e);let a=fx(r,n,t,e);wx(r,a);let c=await mx(i,a),l=cx(c,Gd.tmpdir());if(!l)throw new Error("Scanner output format unexpected: missing report path.");m(ge(`[compat:check] tmp csv: "${l}"`));let d=ax(l),h=null;if(o.kind==="file")Cx(l,d,o.filePath,o.ext),h=o.filePath;else if(o.kind==="dir")h=Ix(l,d,o.dirPath,e.format);else if(o.kind!=="none")throw new Error(`Unexpected output target kind: ${o.kind}`);vx(l),s.stop(),yx(d,h,e.format,e.limit,o.kind)}catch(a){throw s.fail("Compatibility check failed"),a}}var zd=new zk("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.',dw,"default").option("--output-path <path>","Directory to write the detailed report CSV to (default: ./compat-output)").option("--limit <num>","Maximum number of change records to display (default: 100)",Xk,100).action(async(n,e)=>{await Rx(n,e)});zd.command("versions").description("List all available target SDK versions for compatibility checking").action(async()=>{let n=Qk("csv");await ex(n)});var fw=zd;var mw=new Tx("check").description("Run DevEco project checks").addCommand(Bd());b()||mw.addCommand(fw);var hw=mw;import{Command as hL}from"commander";import{green as mu,red as gL}from"colorette";import hu from"fs";import Zw from"path";import yL from"json5";import{readFileSync as nN}from"fs";import{join as kx}from"path";var Q={BASE_URL:"https://connect-api.cloud.huawei.com",CERT_LIST_PATH:"/api/cps/harmony-cert-manage/v1/cert/list",CERT_DELETE_PATH:"/api/cps/harmony-cert-manage/v1/cert/delete",CERT_ADD_PATH:"/api/cps/harmony-cert-manage/v1/cert/add",CERT_DOWNLOAD_URL_PATH:"/api/amis/app-manage/v1/objects/url/reapply",DEVICE_ADD_PATH:"/api/cps/device-manage/v1/device/add",DEVICE_LIST_PATH:"/api/cps/device-manage/v1/device/list",PROVISION_ADD_REAL_PATH:"/api/cps/provision-manage/v1/ide/real/provision/add",PROVISION_ADD_TEST_PATH:"/api/cps/provision-manage/v1/ide/test/provision/add",PROVISION_DELETE_PATH:"/api/cps/provision-manage/v1/provision/delete"},je={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:kx(".ohos","config"),DOWNLOAD_CONNECT_TIMEOUT_MS:5e3},ye={SUCCESS_MARKER:'"code":0',SQUARE_BRACKETS:"[]",OPENPROXY_BLOCKED_URL:"Openproxy_Blocked_URL_list",CERT_LIMIT_CODE:"205389872",USER_NOT_HARMONY_CODE:"205389904",DEVICE_EXCEEDS_LIMIT_CODE:"205389859",DEVICE_NAME_REPEAT_CODE:"205389857",PROVISION_EXCEEDS_LIMIT_CODE:"205389938",PROVISION_NAME_REPEAT_CODE:"205389830"},ft={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."},K={TOOLCHAIN_INIT_FAILED:"Auto-sign failed: unable to initialize toolchain",LOGIN_REQUIRED:"Failed to automatically generate signatures.Run devecocli auth login to sign in.",TEAM_INFO_FAILED:"Failed to obtain user team information.Check the network connection, HTTP proxy, and other configurations.",REALNAME_REQUIRED:"Users without real-name verification are not supported.Complete real-name verification in AppGallery Connect.",SESSION_EXPIRED:"User session expired or token invalid. Please login again.",REGION_CHINA_ONLY:"This feature is only available for accounts registered in Chinese mainland.",DEVICE_MISSING:"Unable to create the profile file due to missing devices.Connect a device through IP or USB, or manually add a device in AppGallery Connect first.If you are installing the HAP package on an emulator, you can skip the signing step.",DEVICE_DETECT_FAILED:"Unable to detect devices. Please check hdc status. If installing HAP on an emulator, signature step can be skipped.",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 qa(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}function qd(n){let e=n.replace(je.TEAM_ID_INVALID_CHARS,"");return`${je.CERT_NAME_PREFIX}${e}.cer`}function Zr(n,e,t){if(n===ft.FORBIDDEN)return e===ye.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN);if(n===ft.UNAUTHORIZED)return new Error(E.ERR_UNAUTHORIZED);if(t.includes(ye.USER_NOT_HARMONY_CODE))return new Error(E.ERR_USER_NOT_HARMONY);if(t.includes(ye.CERT_LIMIT_CODE))return new Error(E.ERR_CERT_LIMIT_REACHED);let r=xx(t);return new Error(r??E.ERR_DOWNLOAD_CER)}function xx(n){let e=gw(n);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let r=typeof t=="string"?gw(t):t;if(r&&typeof r=="object"){let o=r.msg;if(typeof o=="string"&&o.trim()!=="")return o}return null}function gw(n){try{return JSON.parse(n)}catch{return null}}function Vd(n){return JSON.parse(n)}async function yw(n){let e=`${Q.BASE_URL}${Q.CERT_LIST_PATH}`,t=await N.postAllowFailure(e,{headers:qa(n)});if(t.statusCode!==200)throw Zr(t.statusCode,t.statusText,t.data);return Vd(t.data)?.certList??[]}async function Va(n,e){return(await yw(n)).find(r=>r.certName===e)??null}async function Jd(n,e){let t=`${Q.BASE_URL}${Q.CERT_DELETE_PATH}`,r=await N.deleteAllowFailure(t,{headers:qa(n),params:{certIds:[e]}});if(r.statusCode!==200)throw Zr(r.statusCode,r.statusText,r.data);return Vd(r.data)?.ret?.code===0}async function Yd(n,e,t){let r=`${Q.BASE_URL}${Q.CERT_ADD_PATH}`,o={csr:e,certName:t,certType:je.CERT_TYPE_DEBUG},i=await N.postAllowFailure(r,{headers:qa(n),params:o});if(i.statusCode!==200)throw Zr(i.statusCode,i.statusText,i.data);if(!i.data.includes(ye.SUCCESS_MARKER))throw Zr(void 0,i.statusText,i.data)}async function Kd(n,e){let t=`${Q.BASE_URL}${Q.CERT_DOWNLOAD_URL_PATH}`,r=await N.postAllowFailure(t,{headers:qa(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw Zr(r.statusCode,r.statusText,r.data);return Vd(r.data)?.urlsInfo?.[0]?.newUrl??null}import{mkdirSync as Nx,writeFileSync as Lx,existsSync as Ox}from"fs";import{dirname as Mx}from"path";async function Ei(n,e){let{statusCode:t,statusText:r,buffer:o}=await N.getBinaryAllowFailure(n,{timeout:je.DOWNLOAD_CONNECT_TIMEOUT_MS});if(t!==200)throw t===ft.FORBIDDEN&&r===ye.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_DOWNLOAD_CER);let i=Mx(e);Ox(i)||Nx(i,{recursive:!0}),Lx(e,o)}import Qx from"fs/promises";import{readFileSync as eN}from"fs";import Ja from"path";import Sw from"crypto";import _x from"os";import Pi from"fs/promises";var bw={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},ww=["ECC","RSA"],vw=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],Fx={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},jx=8,Xd=64,Hx=/[\\:*?"<>|=-]/g,mt={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function $x(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>Xd)throw new Error(`The length of keyAlias cannot exceed ${Xd}`);if(!ww.includes(n.keyAlg))throw new Error(`Invalid key algorithm ${n.keyAlg}, available: ${ww.join(" / ")}`);let e=Fx[n.keyAlg];if(!e.includes(n.keySize))throw new Error(`Key algorithm ${n.keyAlg} does not support size ${n.keySize}, available: ${e.join(", ")}`)}function Ux(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(!vw.includes(n.signAlg))throw new Error(`Invalid sign algorithm ${n.signAlg}, available: ${vw.join(" / ")}`)}function Bx(n){return Sw.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function Wx(n){let e=n?.trim()??"";return e&&e.replace(Hx,"_").slice(0,Xd)||mt.productName}async function Ew(){let n=await I.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;f.info(`\u8BFB\u53D6SDK\u6839\u76EE\u5F55\uFF1A${t}`);let r=b()?"hap-sign-tool":"hap-sign-tool.jar",o=Ja.join(t,"default","openharmony","toolchains","lib",r);try{await Pi.access(o)}catch(i){throw new Error(`${r} not found: ${o}`,{cause:i})}return{javaPath:e,toolPath:o}}async function Gx(n){let{javaPath:e,toolPath:t}=await Ew(),r=[bw.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 f.debug("generate-keypair \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),b()?[t,...r]:[e,"-jar",t,...r]}async function zx(n){let{javaPath:e,toolPath:t}=await Ew(),r=[bw.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 f.debug("generate-csr \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),b()?[t,...r]:[e,"-jar",t,...r]}async function qx(n){f.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),$x(n);let e=await Gx(n),t=await fo(e[0],e.slice(1));if(t.exitCode!==0){let r=t.stderr||t.stdout||"Unknown tool error";throw new Error(`An error occurred while generating the private key P12, exit code${t.exitCode}\uFF1A${r}`)}return f.info("\u751F\u6210P12\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}async function Vx(n){f.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),Ux(n);let e=await zx(n),t=await fo(e[0],e.slice(1));if(t.exitCode!==0){let r=t.stderr||t.stdout||"Unknown tool error";throw new Error(`An error occurred while generating the CSR, exit code${t.exitCode}\uFF1A${r}`)}return f.info("\u751F\u6210CSR\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}function Jx(n=jx){return Sw.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function Yx(){let n=_x.homedir();try{await Pi.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=Ja.join(n,b()?"Documents":"",".ohos","config");try{await Pi.mkdir(e,{recursive:!0,mode:448})}catch(t){throw new Error(`Failed to create directory ${e}`,{cause:t})}return f.info(`\u7B7E\u540D\u914D\u7F6E\u76EE\u5F55\u5C31\u7EEA\uFF1A${e}`),e}async function Ee(n,e,t){let r=Wx(n),o=Ja.basename(e),i=Bx(e),s=`${r}_${o}_${i}=.${t}`,a=await Yx();return Ja.join(a,s)}function Kx(n){let e;try{e=G.discover(n).rootDir}catch(t){throw new Error(`Current directory ${n} is not a valid project root`,{cause:t})}return e}async function Xx(n){try{await Pi.access(n)}catch(e){throw new Error(`Project directory ${n} is not accessible, missing read/write permissions`,{cause:e})}}async function Zx(n){try{await Pi.access(n)}catch(e){throw new Error(`P12 file ${n} does not exist, terminating CSR generation.`,{cause:e})}}async function Zd(n,e,t){let r=process.cwd(),o=Kx(r);await Xx(o),f.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${o}`);let i=Jx(),s=await Ee(n??"",o,"p12"),a=await Ee(n??"",o,"csr");return console.log("Start generating p12"),await qx({keyAlias:e?.keyAlias??mt.keyAlias,keyPwd:i,keyAlg:e?.keyAlg??mt.keyAlg,keySize:e?.keySize??mt.keySize,keystoreFile:s,keystorePwd:i}),await Zx(s),console.log("Start generating csr"),await Vx({subject:t?.subject??mt.csrSubject,outFile:a,keyAlias:t?.keyAlias??mt.keyAlias,keyPwd:i,signAlg:t?.signAlg??mt.signAlg,keystoreFile:s,keystorePwd:i}),{p12FilePath:s,csrFilePath:a,keyPwd:i,keyAlias:e?.keyAlias??mt.keyAlias}}var tN=["p12","cer","csr","p7b"];async function Qd(n,e){for(let t of tN){let r=await Ee(n,e,t);await Qx.rm(r,{force:!0})}}function eu(n){let e;try{e=eN(n,"utf-8")}catch{throw new Error(E.ERR_CERT_INVALIDATE)}if(!je.CERT_PATTERN.test(e))throw new Error(E.ERR_CERT_INVALIDATE)}async function Pw(n,e){return{certPath:await Ee(n,e,"cer"),csrPath:await Ee(n,e,"csr"),p12Path:await Ee(n,e,"p12"),profilePath:await Ee(n,e,"p7b")}}async function tu(n,e){let t=e??"",r=G.discover(process.cwd()).rootDir;await Qd(t,r);let o=qd(n.teamId),i=await Va(n,o);if(i&&!await Jd(n,i.id))throw new Error(E.ERR_DOWNLOAD_CER);let s=await Zd(e),a;try{a=nN(s.csrFilePath,"utf-8")}catch{throw new Error(E.ERR_READ_CSR)}console.log("Start generating certificate"),await Yd(n,a,o);let c=await Va(n,o);if(!c)throw new Error(E.ERR_DOWNLOAD_CER);let l=await Kd(n,c.certObjectId);if(!l)throw new Error(E.ERR_DOWNLOAD_CER);let d=await Ee(t,r,"cer");await Ei(l,d),eu(d);let h=await Ee(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 oc from"crypto";import Dn from"fs";import*as jw from"path";import CN from"json5";import{execa as Mw}from"execa";import _w from"node-forge";import{createCipheriv as rN,createDecipheriv as oN,pbkdf2Sync as iN,randomBytes as iu}from"crypto";import{promises as Zn}from"fs";import{dirname as sN,join as ht}from"path";var Ya=3,Ci=16,aN=1e4,Cw="material",cN=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Rw="aes-128-gcm",Xn=12,Ka=16,Cn=4;function nu(n){return new Uint8Array(iu(n))}function lN(n){return iu(n).toString("hex")}function dN(...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 Iw(n,e,t=aN,r=Ci){let o=[...n,cN],i=dN(...o),s=Buffer.from(i).toString("utf8"),a=Buffer.from(s,"utf8"),c=iN(a,e,t,r,"sha256");return new Uint8Array(c)}function Aw(n,e){let t=iu(Xn),r=rN(Rw,n,t),o=Buffer.concat([r.update(e),r.final()]),i=r.getAuthTag(),s=Buffer.concat([o,i]),a=s.length,c=Buffer.alloc(Cn+Xn+s.length);return c.writeUInt32BE(a,0),t.copy(c,Cn),s.copy(c,Cn+Xn),c}function Dw(n,e){if(e.length<Cn+Xn+Ka)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(Cn,Cn+Xn),o=e.subarray(Cn+Xn,Cn+Xn+t);if(o.length<Ka)throw new Error("Ciphertext too short for auth tag");let i=o.subarray(0,o.length-Ka),s=o.subarray(o.length-Ka),a=oN(Rw,n,r);return a.setAuthTag(s),Buffer.concat([a.update(i),a.final()])}async function uN(n){try{await Zn.rm(n,{recursive:!0,force:!0})}catch{}}async function ru(n){let e=await Zn.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 Zn.readFile(ht(n,t[0]))}async function ou(n,e){let t=lN(Ci),r=ht(n,t);return await Zn.writeFile(r,e),t}var In=class{static async generateMaterial(e){let t=ht(e,Cw);await uN(t);let r=ht(t,"ac"),o=ht(t,"ce");await Zn.mkdir(r,{recursive:!0}),await Zn.mkdir(o,{recursive:!0});for(let d=0;d<Ya;d++)await Zn.mkdir(ht(t,"fd",String(d)),{recursive:!0});let i=nu(Ci),s=[];for(let d=0;d<Ya;d++)s.push(nu(Ci));let a=nu(Ci),c=Iw(s,i),l=Aw(c,a);await ou(r,i),await ou(o,l);for(let d=0;d<Ya;d++){let h=ht(t,"fd",String(d));await ou(h,s[d])}return a}static async readMaterial(e){let t=ht(e,Cw),r=ht(t,"ac"),o=new Uint8Array(await ru(r)),i=[];for(let d=0;d<Ya;d++){let h=ht(t,"fd",String(d)),w=await ru(h);i.push(new Uint8Array(w))}let s=ht(t,"ce"),a=await ru(s),c=Iw(i,o),l=Dw(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t=sN(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 Aw(r,o).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let r=await this.getStoreKey(t),o=Buffer.from(e,"hex");return Dw(r,o).toString("utf8")}};import Lw from"fs";import nc from"path";import yN from"json5";import*as Xa from"fs";import*as Tw from"path";function Za(n){let e=Tw.resolve(n);if(!Xa.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=Xa.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 eo from"fs";import*as He from"path";import{debuglog as Qr}from"util";var kw={"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 pN(n){return Object.prototype.hasOwnProperty.call(kw,n)}function Qa(n){if(pN(n))return kw[n]}var xw={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as fN}from"url";var tc=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 ec(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Nw(n){return n==null||n.length===0}function mN(n){return!Nw(n)}function su(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function hN(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 gN(n,e){let t=n[e];if(typeof t=="number")return Math.trunc(t);if(typeof t=="string"){let r=Number.parseInt(t,10);return Number.isNaN(r)?0:r}return 0}var An=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=He.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=He.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=He.join(t.sdkPath,"default","sdk-pkg.json"),a=Za(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=He.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(eo.existsSync(e))return eo.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=fN(e);if(t.includes("dist")){let s=He.dirname(t),a=He.dirname(s);return He.join(a,"src","resources")}let r=He.dirname(t),o=He.dirname(r),i=He.dirname(o);return He.join(i,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let r;try{r=this.readBuiltInConfigText()}catch{Qr("read builtin acl permission failed.");return}if(r!==void 0)try{let o=JSON.parse(r),s=(Array.isArray(o)?o:ec(o)?Object.values(o):[]).filter(ec).map(a=>new tc(a));s.forEach(a=>{let c=a.permissionInsteadName;mN(c)&&(a.permissionInsteadName=Qa(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(o){Qr(`failed to parse aclPermissionsInfo.json: ${o}`)}}static initAclPermissionFromSDK(e,t,r){let o=this.parsePermissionDefinitionFile(e);o&&o.forEach(i=>{if(!ec(i))return;let s=i,a=su(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(Nw(a)||(this.generateAclInfos(r,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||su(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||su(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:hN(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let o=new tc;o.permissionName=t;let i=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;o.permissionDisplayName=i;let s=gN(r,this.ACL_SINCE_KEY);o.minSupportApiLevel=String(s),this.handleInsteadName(o,i),e.add(o)}static parsePermissionDefinitionFile(e){let t=He.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!eo.existsSync(t))return;let r;try{r=eo.readFileSync(t,"utf-8")}catch(s){Qr(`failed to load permissionDefinitions.json: ${s}`);return}let o;try{let s=JSON.parse(r);if(!ec(s)){Qr("json object is null");return}o=s}catch(s){Qr(`failed to parse permissionDefinitions.json: ${s}`);return}let i=o[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(i)){Qr("definePermissions is not an array");return}return i}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=Qa(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=Qa(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function rc(n,e){let t=new Set,r=new Set;An.handleSpecificAclPermissions(),An.initAclPermission(n,e);for(let o of n.profile.modules){let i=Ow(o,n,e,r,nc.join("src","main"));for(let a of i)t.add(a);let s=Ow(o,n,e,r,nc.join("src","ohosTest"));for(let a of s)t.add(a)}return wN(r),t}function wN(n){if(n.size>0)throw new Error(xw.DUPLICATE_PERMISSION)}function Ow(n,e,t,r,o){let i=SN(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 S=vN(w,"name");S&&s.push(S)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=nc.join(t.sdkPath,"default","sdk-pkg.json"),l=Za(c),d=An.getAclPermissionInfos(e),h=new Set(Array.from(d).filter(w=>{let S=Number(w.minSupportApiLevel);return Number.isFinite(S)&&S<=l}).map(w=>w.permissionName));for(let w of Array.from(a))h.has(w)||a.delete(w);return a}function vN(n,e){let t=n[e];return typeof t=="string"?t:""}function SN(n,e,t){let r=nc.join(n,e.srcPath,t,"module.json5"),o=bN(r);if(o==null)return null;let i=EN(o,"module");return i==null?null:PN(i,"requestPermissions")}function bN(n){try{if(!Lw.existsSync(n))return null;let e=Lw.readFileSync(n,"utf-8");return yN.parse(e)}catch{return null}}function EN(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 PN(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}var cu=class{verifyStorePassword(e,t){try{let r=Dn.readFileSync(e),o=_w.asn1.fromDer(r.toString("binary"));return _w.pkcs12.pkcs12FromAsn1(o,t),!0}catch{return!1}}getLocalCerFingerprints(e){let r=Dn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(r&&r.length>0)return r.map(o=>this.formatFp(new oc.X509Certificate(o).fingerprint256));try{return[this.formatFp(new oc.X509Certificate(Dn.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let o=Dn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let i of o)try{let s=new oc.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 IN(n){let e=Dn.readFileSync(n,"utf-8"),t=AN(e),r=null;if(t)try{r=JSON.parse(t)}catch{r=null}let o=r?.["bundle-info"]??{};return{rawContent:e,bundleNameInProfile:au(o["bundle-name"]),expiryDate:DN(r?.validity?.["not-after"]),cerFingerprintInProfile:RN(au(o["development-certificate"])),deviceUdidsInProfile:TN(r?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:kN(r?.acls?.["allowed-acls"]),teamIdInProfile:au(o["developer-id"])}}function AN(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 DN(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function RN(n){if(!n)return null;try{let t=new oc.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function TN(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 kN(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 au(n){return typeof n=="string"?n:null}var Ii=class n{static async shouldRegenerate(e,t){let r=await n.#e(e,t);return n.#t(r)??n.#n(r)??n.#r(r)??n.#o(r)??n.#i(r)??n.#s(r)??n.#a(r)??n.#c(r)??n.#l(r)??n.#d(r)??await n.#u(r)??n.#p()}static async#e(e,t){let r=e.force,o=e.teamId,i=e.productName??"default",s=G.discover(process.cwd()),a=s.rootDir,[c,l]=await Promise.all([xN(i,a),LN(t.hdcPath)]),d=null;if(Fw(c).allExist)try{d=IN(c.profileFile)}catch{}return{force:r,teamId:o,productName:i,projectPath:a,materialPaths:c,bundleName:s.getBundleName(),deviceUdids:l,storePassword:await NN(a,i,c.storeFile),localAclPermissions:[...rc(s,t)].sort(),hapSignTool:new cu,profileInfo:d}}static#t(e){return e.force?(m("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:We({force:!0})}):null}static#n(e){let t=Fw(e.materialPaths);return t.allExist?null:(m(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:We({allFilesExist:!1,missingFiles:t.missing})})}static#r(e){return(e.profileInfo?.rawContent??"").trim().length>0?null:(m("[reGenerateSign] profile content is empty"),{shouldRegenerate:!0,reason:"Profile file content is empty",checkDetails:We({allFilesExist:!0,profileContentNotEmpty:!1})})}static#o(e){let t=e.profileInfo?.expiryDate;return!t||t>=new Date?null:(m(`[reGenerateSign] profile expired at ${t.toISOString()}`),{shouldRegenerate:!0,reason:`Profile expired at ${t.toISOString()}`,checkDetails:We({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!1})})}static#i(e){let t=e.profileInfo?.bundleNameInProfile;return t&&t===e.bundleName?null:(m(`[reGenerateSign] bundleName mismatch \u2014 current=${e.bundleName}, profile=${t}`),{shouldRegenerate:!0,reason:`bundleName mismatch: current=${e.bundleName}, in profile=${t}`,checkDetails:We({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!1})})}static#s(e){let t=e.profileInfo?.teamIdInProfile;return t&&t===e.teamId?null:(m(`[reGenerateSign] teamId mismatch \u2014 current=${e.teamId}, profile=${t}`),{shouldRegenerate:!0,reason:`teamId mismatch: current=${e.teamId}, in profile=${t}`,checkDetails:We({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=MN(e.profileInfo?.deviceUdidsInProfile??[],e.deviceUdids);return t.allPresent?null:(m(`[reGenerateSign] missing device UDIDs: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Device UDID(s) not in profile: ${t.missing.join(", ")}`,checkDetails:We({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return _N(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(m("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:We({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!1})})}static#l(e){let t=e.hapSignTool.getLocalCerFingerprints(e.materialPaths.cerFile),r=e.profileInfo?.cerFingerprintInProfile;return r&&t.includes(r)?null:(m("[reGenerateSign] certificate mismatch"),{shouldRegenerate:!0,reason:"Certificate mismatch between profile and local .cer file",checkDetails:We({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!1})})}static#d(e){let t=e.profileInfo?.cerFingerprintInProfile,r=e.hapSignTool.getLocalCerExpiry(e.materialPaths.cerFile,t);return!r||r>=new Date?null:(m(`[reGenerateSign] local certificate expired at ${r.toISOString()}`),{shouldRegenerate:!0,reason:`Local certificate expired at ${r.toISOString()}`,checkDetails:We({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!1})})}static async#u(e){return e.storePassword?e.hapSignTool.verifyStorePassword(e.materialPaths.storeFile,e.storePassword)?null:(m("[reGenerateSign] keystore password verification failed"),{shouldRegenerate:!0,reason:"Keystore password verification failed (storeFile may be corrupted or password changed)",checkDetails:We({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})}):(m("[reGenerateSign] no stored keystore password"),{shouldRegenerate:!0,reason:"No stored keystore password available for verification",checkDetails:We({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})})}static#p(){return m("[reGenerateSign] all checks passed \u2014 skip regeneration"),{shouldRegenerate:!1,reason:"",checkDetails:We({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function xN(n,e){let[t,r,o,i]=await Promise.all([Ee(n,e,"p12"),Ee(n,e,"csr"),Ee(n,e,"cer"),Ee(n,e,"p7b")]);return{storeFile:t,csrFile:r,cerFile:o,profileFile:i}}async function NN(n,e,t){let r=jw.join(n,"build-profile.json5");if(!Dn.existsSync(r))return;let o;try{o=CN.parse(Dn.readFileSync(r,"utf-8"))}catch{return}let a=(o?.app?.signingConfigs??[]).find(c=>c.name===e)?.material?.storePassword;if(a)try{return await In.decryptPassword(a,t)}catch{return}}async function LN(n){m(`Executing: ${n} list targets`);let{stdout:e}=await Mw(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let o of e.split(`
1412
+ `)){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{m(`Executing: ${n} -t ${o} shell bm get -u`);let{stdout:i}=await Mw(n,["-t",o,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),s=ON(i);s&&r.push(s)}catch{m(`[reGenerateSign] Failed to get UDID for ${o}, skipping`)}return r}function ON(n){let e=n.trim();if(!e)return null;let t=e.split(`
1413
+ `);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 Fw(n){let e=[n.storeFile,n.csrFile,n.cerFile,n.profileFile],t=[];for(let r of e)Dn.existsSync(r)||t.push(r);return{allExist:t.length===0,missing:t}}function MN(n,e){let t=[];for(let r of e)n.includes(r)||t.push(r);return{allPresent:t.length===0,missing:t}}function _N(n,e){let t=[...n].sort(),r=[...e].sort();return t.length!==r.length?!1:t.every((o,i)=>o===r[i])}function We(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 lu}from"util";import{execa as du}from"execa";async function $w(n,e){let t=await ic(n);if(!t)throw new Error(E.DEVICE_LIST_EMPTY);let r=await HN(e);if(t.length===0)for(let s of r)await FN(n,s.udid,s.deviceName);else for(let s of r)await jN(n,t,s.udid,s.deviceName);let i=(await ic(n)).map(s=>s.id);if(i.length===0)throw new Error(E.DEVICE_LIST_EMPTY);return i}async function FN(n,e,t){await Ww(n,e,Uw(t))}async function jN(n,e,t,r){for(let o=0;o<e.length;o++){if(t===e[o].udid)return;if(o===e.length-1){await Ww(n,t,Uw(r));return}}}function Uw(n){switch(n){case"liteWearable":return"1";case"wearable":return"2";case"tv":return"3";default:return"4"}}async function Hw(n,e=1,t=100){let r=`${Q.BASE_URL}${Q.DEVICE_LIST_PATH}?encodeFlag=0&start=${e}&pageSize=${t}`,o=Gw(n),i=await N.get(r,{headers:o});if(!i)throw lu("query devices failed: response is null"),new Error(E.ERROR_WHILE_ADD_DEVICE);if(i.statusCode!==200)throw Bw(i.statusCode,i.statusText,i.data);let s=JSON.parse(i.data);if(!s||!s.list)throw lu("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 Bw(n,e,t){return n===ft.FORBIDDEN?e===ye.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN):n===ft.UNAUTHORIZED?new Error(E.ERR_UNAUTHORIZED):t.includes(ye.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(E.DEVICE_LIMIT_REACHED):new Error(E.ERROR_WHILE_ADD_DEVICE)}async function ic(n){let t=await Hw(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 Hw(n,s,100);if(!a||!a.deviceList||a.deviceList.length===0)break;r.push(...a.deviceList)}return r}async function Ww(n,e,t){let r=`${Q.BASE_URL}${Q.DEVICE_ADD_PATH}`,o=Gw(n),s={deviceName:`auto_sign_device_No.${Math.floor(Math.random()*3e3)}${Date.now()}`,udid:e,deviceType:t},a=await N.postAllowFailure(r,{headers:o,params:s});if(!a)throw lu("add device failed: response is null"),new Error(E.ERROR_WHILE_ADD_DEVICE);if(a.statusCode!==200)throw Bw(a.statusCode,a.statusText,a.data);let c=a.data,l=JSON.parse(a.data);if(!l||!l.ret||l.ret.code!==0)throw c.includes(ye.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(E.DEVICE_LIMIT_REACHED):c.includes(ye.DEVICE_NAME_REPEAT_CODE)?new Error(E.DEVICE_NAME_REPEAT):new Error(E.ERROR_WHILE_ADD_DEVICE)}function Gw(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}async function HN(n){let{stdout:e}=await du(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{let i=await $N(o,n),s=await UN(o,n);i.length>0&&r.push({id:"",udid:i,deviceName:s})}catch{m(`Failed to get device info for ${o}, skipping`)}return r}async function $N(n,e){let{stdout:t}=await du(e,["-t",n,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),r=t.trim();if(!r)return"";let o=r.split(`
1415
+ `);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 UN(n,e){let{stdout:t}=await du(e,["-c","-t",n,"shell","getprop","hw_sc.build.os.deviceType"],{stdio:["ignore","pipe","pipe"]});return BN(t)}function BN(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 Qn from"fs";import{createHash as WN}from"crypto";import{debuglog as Vt}from"util";import{Buffer as qw}from"buffer";import{createPublicKey as GN,X509Certificate as uu}from"crypto";import{readFileSync as zN}from"fs";import er from"node-forge";async function Vw(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=`${Q.BASE_URL}${Q.PROVISION_ADD_TEST_PATH}`,h=qN(t,r),w=await JN(n,d,a||[],r,s,h,i||[]);if(!w||!w.profileInfo||!w.profileInfo.provisionFileUrl)throw Vt("add provision failed, the provision file url is null"),new Error(E.ADD_PROFILE_FAIL);let S=w.profileInfo,re=(await ZN(n,S.provisionFileUrl)).urlList,Re=w.profileInfo.id;if(re&&re.length>0){let Pe=await Pw(t,o),Ge=Pe.profilePath;if(!await QN(re,Ge))throw await zw(n,Re),new Error(E.ERROR_WHILE_DOWNLOAD_PROFILE);if(await zw(n,Re),Qn.existsSync(Pe.certPath)&&Qn.existsSync(Ge)&&Qn.existsSync(Pe.p12Path)){let tv=Qn.readFileSync(Pe.certPath,"utf8"),nv=Qn.readFileSync(Ge,"utf8");return eL(nv,tv,Pe.p12Path,c,l)||XN(Ge),Ge}}throw new Error(E.ADD_PROFILE_FAIL)}function qN(n,e){let t=n?`${n}_`:"";return`${VN(`${t}${e}_${e}`)}`}function VN(n){return WN("sha256").update(n).digest("hex").substring(0,16)}async function JN(n,e,t,r,o,i,s){YN(r);let a=fu(n),c={certList:t,packageName:r,deviceList:o,provisionName:i};s.length&&(c.aclPermissionList=s);let l=await N.postAllowFailure(e,{headers:a,params:c});if(!l)throw Vt("add provision failed: response is null"),new Error(E.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw pu(l.statusCode,l.statusText,l.data);let d=JSON.parse(l.data);if(!d||!d.ret||d.ret.code!==0)throw Vt(`add provision fail: ${l.data}`),KN(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 pu(n,e,t){return n===ft.FORBIDDEN?e===ye.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN):n===ft.UNAUTHORIZED?new Error(E.ERR_UNAUTHORIZED):t.includes(ye.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(E.TEST_PROVISION_EXCEEDS_LIMIT):new Error(E.ADD_PROFILE_FAIL)}function YN(n){if(!n||n.trim().length===0)throw new Error(E.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!je.BUNDLE_NAME_REGEX.test(n))throw new Error(E.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function KN(n,e){if(n.includes(ye.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(E.TEST_PROVISION_EXCEEDS_LIMIT);if(n.includes(ye.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(E.PROFILE_NAME_REPEAT)}async function zw(n,e){if(!e||e.trim().length===0)return;let t=`${Q.BASE_URL}${Q.PROVISION_DELETE_PATH}?id=${e}`,r=await N.deleteAllowFailure(t,{headers:fu(n)});if(r.statusCode!==200)throw pu(r.statusCode,r.statusText,r.data);let o=JSON.parse(r.data);(!o||!o.ret||o.ret.code!==0)&&Vt(`delete provision failed: ${r.data}`)}function XN(...n){for(let e of n)try{Qn.existsSync(e)&&Qn.unlinkSync(e)}catch(t){Vt(`delete local sign file error: ${t.message}`)}}async function ZN(n,e){let t=`${Q.BASE_URL}${Q.CERT_DOWNLOAD_URL_PATH}`,r=fu(n),o={sourceUrls:e},i=await N.postAllowFailure(t,{headers:r,params:o});if(!i)throw Vt("get download list failed: response is null"),new Error(E.ADD_PROFILE_FAIL);if(i.statusCode!==200)throw pu(i.statusCode,i.statusText,i.data);let s=JSON.parse(i.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw Vt("download: The application does not exist"),new Error(s.ret?.msg||E.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function QN(n,e){if(!n||n.length===0)return!1;let t=n[0].newUrl;return await Ei(t,e),!0}function eL(n,e,t,r,o){return tL(n,e),r=r||je.TARGET_FRIENDLY_NAME,o=o||"",nL(e,t,r,o),!0}function tL(n,e){if(e.lastIndexOf(je.CERT_BEGIN_HEADER)<0)throw new Error(E.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(je.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!n.includes(t))throw new Error(E.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}function nL(n,e,t,r){let o=n.matchAll(je.CERTIFICATE_PATTERN_GLOBAL),i=[],s=new Date;for(let c of o)try{let l=c[0],d=rL(l),h=new Date(d.validFrom),w=new Date(d.validTo);if(s<h||s>w){let S=`Certificate is not valid, Valid from ${h} to ${w}`;throw console.warn(`checkCertificateInValidityPeriod: ${S}`),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(!iL(e,t,r,i))throw new Error(E.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function rL(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new uu(t);let r=qw.from(t,"base64");return new uu(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}function oL(n){if(n.cert){let e=er.pki.publicKeyToPem(n.cert.publicKey);return GN(e).export({type:"spki",format:"der"})}if(n.asn1)try{let e=er.asn1.toDer(n.asn1).getBytes(),t=qw.from(e,"binary");return new uu(t).publicKey.export({type:"spki",format:"der"})}catch(e){return Vt(`Failed to parse cert from asn1: ${e}`),null}return null}function iL(n,e,t,r){try{let o=zN(n),i=er.asn1.fromDer(er.util.createBuffer(o)),c=er.pkcs12.pkcs12FromAsn1(i,t).getBags({bagType:er.pki.oids.certBag})[er.pki.oids.certBag]||[];for(let l of c){let d=l.attributes?.friendlyName?.[0];if(!d||d.toLowerCase()!==e.toLowerCase())continue;let h=oL(l);if(!h)continue;if(r.some(S=>{let k=S.publicKey.export({type:"spki",format:"der"});return h.equals(k)}))return!0}return!1}catch(o){let i=o instanceof Error?o.message:String(o);return Vt(`Failed to process P12 file: ${n}, error: ${i}`),!1}}function fu(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var Yw="https://developer.huawei.com",sL={"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"},aL="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function cL(n){let e=sL[n];return e?`${Yw}${e}`:void 0}function lL(){return`${Yw}${aL}`}var dL={"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 Jw(n,e){return(dL[n]??n).replace(/\{(\d+)\}/g,(r,o)=>String(e[Number(o)]??""))}function uL(n){return Array.from(n).join(", ")}function Kw(n,e){if(n.size===0)return;let t=An.getAclPermissionInfos(e),r=new Set;for(let h of t)n.has(h.permissionName)&&r.add(h);for(let h of r){let w=cL(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=lL(),a=Jw("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=i.size>0?Array.from(i).join(", ")+".":"",d=Jw("acl.permissions.warn",[uL(o),l,c]);console.log(d)}var sc=class{_project=null;get project(){if(!this._project)throw new Error("Project not initialized. Call checkProjectDir first.");return this._project}checkProjectDir(e){try{return this._project=G.discover(process.cwd()),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Project.discover() failed: ${t.message}`),e(K.PROJECT_DIR_MISSING)}}checkProduct(e,t){try{return this._project.validateProduct(e),{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Product validation failed: ${r.message}`),t(`Product "${e}" not found.Check the product property in the build-profile.json5 file.`)}}checkBundleName(e,t){try{return this._project.getBundleName(),{passed:!0,message:""}}catch(r){return m(`[EnvCheck] BundleName check failed: ${r.message}`),t(`bundleName was not found under product "${e}".Check the bundleName configuration.`)}}checkAtomicService(){return this._project.isAtomicService()?{passed:!1,message:K.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import pL from"fs";import Xw from"path";var ac=class{constructor(e){this.toolProvider=e}toolProvider;checkJava(e){try{return this.toolProvider.assertJava(),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Java check failed: ${t.message}`),e(K.JAVA_PLATFORM_UNSUPPORTED)}}checkHapSignTools(e){let t=this.toolProvider.sdkPath,r=b()?"hap-sign-tool":"hap-sign-tool.jar",o=Xw.join(t,"default","openharmony","toolchains","lib",r);if(!pL.existsSync(o)){let i=Xw.join("sdk","default","openharmony","toolchains","lib",r);return e(`${r} not found.Check whether ${i} exists.`)}return{passed:!0,message:""}}};var cc=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await ae.getUserInfo()}catch(e){return m(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await ae.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(K.LOGIN_REQUIRED)}catch(t){return m(`[EnvCheck] Login check failed: ${t.message}`),e(K.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(K.TEAM_INFO_FAILED);try{if((await tn()).teamList.length>0)return{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Team API error: ${r.message}`),e(K.TEAM_INFO_FAILED)}return m("[EnvCheck] No teams found for current user"),e(K.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(K.REALNAME_REQUIRED):t.isRealName!==!0?(m("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(K.REALNAME_REQUIRED)):{passed:!0,message:""}:e(K.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let r=e??"";try{let o=await tn();if(r=e??(o.teamList.length>0?o.teamList[0].id:t.userId)??"",!o.teamList.some(s=>s.id===r)){let s=`team-id for ${r} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`;return m(`[EnvCheck] ${s}`),{passed:!1,message:s}}return{passed:!0,message:""}}catch(o){return m(`[EnvCheck] Team ID check failed: ${o.message}`),{passed:!1,message:`team-id for ${r} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`}}}async checkRegion(e){let t=await this.ensureUserInfo();return t?t.countryCode?t.countryCode!=="CN"?e(K.REGION_CHINA_ONLY):{passed:!0,message:""}:(m("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(K.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function fL(n){try{let{teamList:e}=await tn();if(e.length>0)return e[0].id}catch(e){m(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function mL(n){let e=await ae.getUserInfo(),t=await ae.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await fL(e.userId);if(!r)throw new Error("No team found");let o={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await ic(o)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var lc=class{constructor(e){this.toolProvider=e}toolProvider;async checkDevice(e,t){try{let r=await mL(t);if(r.length>0)return m(`[EnvCheck] Scenario 4 Device check: ${r.length} device(s) found in AGC cloud, skipping local device check`),{passed:!0,message:""};m("[EnvCheck] Scenario 4 Device check: no cloud devices found, falling back to local hdc");let i=await te.from(this.toolProvider).listDevices();return i.length===0?(m("[EnvCheck] Scenario 4 Device check: no local devices found"),e(K.DEVICE_MISSING)):i.some(a=>On(a.serial))?{passed:!0,message:""}:(m("[EnvCheck] Scenario 4 Device check: local device found but not an emulator"),e(K.DEVICE_MISSING))}catch(r){return m(`[EnvCheck] Scenario 4 Device check failed: ${r.message}`),e(K.DEVICE_DETECT_FAILED)}}};var dc=class{projectChecker=new sc;toolchainChecker=null;authChecker=new cc;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.checkTeamInfo(t),()=>this.authChecker.checkRealname(t)];for(let i of o)if(!r(await i()))return!1;return!(e.teamId&&!r(await this.authChecker.checkTeamId(e.teamId)))}async initToolchain(){try{let e=await I.new();return this.toolchainChecker=new ac(e),this.deviceChecker=new lc(e),!0}catch(e){throw m(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(K.TOOLCHAIN_INIT_FAILED,{cause:e})}}async runDeviceCheck(e,t){return(o=>o.passed?!0:(this.fail(o),!1))(await this.deviceChecker.checkDevice(t,e.teamId))}async runProjectChecks(e,t){let r=i=>i.passed?!0:(this.fail(i),!1);if(!r(this.projectChecker.checkProjectDir(t))||!r(this.projectChecker.checkAtomicService()))return!1;let o=[()=>this.projectChecker.checkProduct(e.productName,t),()=>this.projectChecker.checkBundleName(e.productName,t),()=>this.toolchainChecker.checkJava(t),()=>this.toolchainChecker.checkHapSignTools(t)];for(let i of o)if(!r(i()))return!1;return!0}async runAuxChecks(e){let t=r=>r.passed?!0:(this.fail(r),!1);return!e.teamId&&!t(await this.authChecker.checkTeamId(e.teamId))?!1:(await this.authChecker.checkRegion(r=>this.blockingFail(r)),!0)}blockingFail(e){return{passed:!1,message:e}}fail(e){throw m(`[EnvCheck] FAIL: ${e.message}`),new Error(e.message)}};function wL(n){if(hu.existsSync(n)){let e=hu.readFileSync(n,"utf-8");return yL.parse(e)}return{app:{signingConfigs:[],products:[]}}}function vL(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function SL(n){if(n.keyPwd===n.storePassword){let r=await In.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await In.encryptedPassword(n.keyPwd,n.p12FilePath),t=await In.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function bL(n,e,t){let r=Zw.join(n,"build-profile.json5"),o=wL(r);vL(o);let i=t??"default",{keyPassword:s,storePassword:a}=await SL(e),c={name:i,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:s,profile:e.profileFilePath,signAlg:mt.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}),hu.writeFileSync(r,JSON.stringify(o,null,2),"utf-8")}async function EL(n){let e=await ae.getUserInfo(),t=await ae.refreshToken();if(!e||!t)throw new Error("Failed to obtain login credentials. Run `devecocli login` again.");return{uid:e.userId??"",teamId:n.teamId??e.userId??"",accessToken:t.accessToken??""}}async function PL(n){let e=n.product||"default";await new dc().preflight({productName:e,teamId:n.teamId}),console.log("Executing signature generate command");let r=await EL(n),o=await I.new(),{shouldRegenerate:i}=await Ii.shouldRegenerate({force:n.force??!1,teamId:r.teamId,productName:n.product},o);if(!i){console.log(mu("Signature generation completed successfully."));return}await CL(n,r,o),console.log(mu("Signature generation completed successfully."))}async function CL(n,e,t){let r=await tu(e,n.product),o=IL(n,e,r,t);o.allDeviceIds=await $w(e,t.hdcPath),await Vw(e,o);let i=G.discover(process.cwd()).rootDir;await bL(i,r,n.product??"default"),console.log(mu(`Signing config written to ${Zw.join(i,"build-profile.json5")}`))}function IL(n,e,t,r){let o=process.cwd(),i=G.discover(o),s=rc(i,r);return Kw(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 Qw=new hL("signature").description("Generate application signature.");Qw.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 PL(n)}catch(e){console.error(gL(e.message)),process.exit(1)}});var ev=Qw;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";AL();ie.name("devecocli").description("HarmonyOS application development command line tool").version("0.3.0-TD.2-alpha2");ie.addCommand(ep);ie.addCommand(kp);ie.addCommand(Op);ie.addCommand(Vp);ie.addCommand(Bf);ie.addCommand(fm);ie.addCommand(ym);ie.addCommand(Dm);ie.addCommand(Mm);ie.addCommand(th);ie.addCommand(py);ie.addCommand(ev);ie.addCommand(hw);ie.addCommand(Fy);b()||ie.addCommand(bf);var gu=process.argv.slice(2);gu.length>=2&&gu[gu.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var RL=new Set(["update","auth"]);ie.hook("preAction",async(n,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==ie;)t=t.parent;RL.has(t.name())||await I.checkVersion()});ie.parseAsync(process.argv).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(DL(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});