@deveco-test/hmos-deveco-cli 0.1.0-TD.5 → 0.1.0-TD.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -11,12 +11,11 @@ Please reinstall DevEco Studio or download the latest version from:
11
11
  `+Es)}return t.reduce((r,o)=>n.compareVersion(o.version,r.version)>0?o:r)}static assertMinVersion(e,t){n.compareVersion(t,Is)>=0||(g(`[ToolProvider] Selected DevEco Studio ${t} at ${e} \u2014 below minimum`),console.error(Iu(`Error: The detected DevEco Studio version is ${t}, which is below the minimum required version ${Is}. Upgrade to the latest version before using deveco-cli:`)+`
12
12
  `+Es),process.exit(1))}static isExistingDirectory(e){return!!e&&M.existsSync(e)&&M.statSync(e).isDirectory()}static resolveWindowsTools(e){let t=E.join(e,"tools");return{nodePath:E.join(t,"node","node.exe"),ohpmJsPath:E.join(t,"ohpm","bin","pm-cli.js"),hvigorJsPath:E.join(t,"hvigor","bin","hvigorw.js"),javaPath:E.join(e,"jbr","bin","java.exe"),sdkPath:E.join(e,"sdk")}}static resolveMacTools(e){let t=E.join(e,"Contents","tools");return{nodePath:E.join(t,"node","bin","node"),ohpmJsPath:E.join(t,"ohpm","bin","pm-cli.js"),hvigorJsPath:E.join(t,"hvigor","bin","hvigorw.js"),javaPath:E.join(e,"Contents","jbr","Contents","Home","bin","java"),sdkPath:E.join(e,"Contents","sdk")}}static resolveTools(e){let t=B.platform(),r=t==="win32"?n.resolveWindowsTools(e):t==="darwin"?n.resolveMacTools(e):(()=>{throw new Error("Linux is not fully supported yet.")})();n.verifyTools(r.nodePath,r.ohpmJsPath,r.hvigorJsPath,r.javaPath);let o=n.resolveHdcPath(r.sdkPath,t),i=n.resolveEmulatorPath(e,t),s=n.resolveClangdPath(e),a=n.resolveLspServerPath(e);return{...r,hdcPath:o,emulatorPath:i,clangdPath:s,lspServerPath:a}}static resolveHdcPath(e,t){let r=t==="win32"?".exe":"",o=[E.join(e,"default","openharmony","toolchains",`hdc${r}`),E.join(e,"toolchains",`hdc${r}`)];for(let i of o)if(M.existsSync(i))return i;throw new Error(`hdc executable not found. Searched in:
13
13
  ${o.join(`
14
- `)}`)}static resolveEmulatorPath(e,t){let r;if(t==="win32")r=E.join(e,"tools","emulator","Emulator.exe");else if(t==="darwin")r=E.join(e,"Contents","tools","emulator","Emulator");else throw new Error("Linux is not fully supported yet");if(!M.existsSync(r))throw new Error(`Emulator executable not found at: ${r}`);return r}static verifyTools(e,t,r,o){if(!M.existsSync(e))throw new Error(`Node executable not found at: ${e}`);if(!M.existsSync(t))throw new Error(`ohpm js file not found at: ${t}`);if(!M.existsSync(r))throw new Error(`hvigor js file not found at: ${r}`);if(o&&!M.existsSync(o))throw new Error(`java executable not found at: ${o}`)}static getEmulatorExe(e){let t=B.platform(),r;if(t==="win32")r=Ps(e,"tools","emulator","Emulator.exe");else if(t==="darwin")r=Ps(e,"Contents","tools","emulator","Emulator");else return;return Ss(r)?r:void 0}static isValidApiLevel(e,t){let r=t??23;return Number.isInteger(e)&&e>=17&&e<=r}static parseApiLevelFromFile(e){if(M.existsSync(e))try{let t=M.readFileSync(e,"utf-8"),r=JSON.parse(t),o=r?.apiVersion??r?.data?.apiVersion;if(typeof o!="string"&&typeof o!="number")return;let i=Number(o);return Number.isInteger(i)&&i>=17?i:void 0}catch{return}}static detectFromSdkPkg(e){let t=E.join(e,"default","sdk-pkg.json");return n.parseApiLevelFromFile(t)}static detectFromOhUniPackage(e){let t=[E.join(e,"default","openharmony","toolchains","oh-uni-package.json"),E.join(e,"default","openharmony","native","oh-uni-package.json"),E.join(e,"default","openharmony","previewer","oh-uni-package.json")];for(let r of t){let o=n.parseApiLevelFromFile(r);if(o!==void 0)return o}}getMaxApiLevel(){let e=n.detectFromSdkPkg(this.sdkPath);if(e!==void 0)return e;let t=n.detectFromOhUniPackage(this.sdkPath);return t!==void 0?t:23}detectApiLevel(){return this.getMaxApiLevel()}static findPowerShellPath(){if(n._powerShellPath)return n._powerShellPath;if(B.platform()!=="win32")return n._powerShellPath="",n._powerShellPath;let e=E.join(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return Ss(e)?(g(`[ToolProvider] Found PowerShell at: ${e}`),n._powerShellPath=e,e):(n._powerShellPath="",n._powerShellPath)}static verifySignature(e){if(!M.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=B.platform();if(n.isExecutableFile(e,t)){if(t==="win32"){if(!n.verifyWindowsSignature(e).signed)throw new Error(`The executable is not digitally signed: ${e}`)}else if(t==="darwin"&&!n.verifyMacSignature(e).signed)throw new Error(`The executable is not digitally signed: ${e}`)}}static isExecutableFile(e,t){if(t==="win32")return E.extname(e).toLowerCase()===".exe";if(t==="darwin")try{return M.accessSync(e,M.constants.X_OK),!0}catch{return!1}return!1}static createSignatureScript(){let e=M.mkdtempSync(E.join(B.tmpdir(),"deveco-verify-")),t=E.join(e,"Verify-Signature.ps1");return M.writeFileSync(t,"$env:PSModulePath = ($env:PSModulePath -split ';' | Where-Object { $_ -notmatch 'windowsapps' }) -join ';'; Get-AuthenticodeSignature -FilePath $args[0] | ConvertTo-Json -Depth 3 -Compress","utf-8"),{tmpDir:e,scriptPath:t}}static verifyWindowsSignature(e){let t=n.findPowerShellPath();if(!t)throw new Error("PowerShell application not found");let{tmpDir:r,scriptPath:o}=n.createSignatureScript();try{let i=Do(t,["-NoProfile","-ExecutionPolicy","Bypass","-File",o,e],{encoding:"utf-8",timeout:5e3,stdio:["pipe","pipe","ignore"]}),s=JSON.parse(i);return{signed:s?.Status===0,signer:s?.SignerCertificate?.Subject??void 0}}catch(i){return g(`[ToolProvider] verify Windows Signature, error msg: ${i}`),{signed:!0}}finally{try{M.rmSync(r,{recursive:!0,force:!0})}catch{}}}static verifyMacSignature(e){try{return Do("codesign",["-v",e],{encoding:"utf-8",timeout:5e3}),{signed:!0}}catch{return{signed:!1}}}};import{execa as Cu}from"execa";import*as pt from"path";import*as Ds from"os";var be=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let r={...process.env,DEVECO_SDK_HOME:e.sdkPath};if(e.javaPath){let o=pt.dirname(e.javaPath);r.PATH=`${o}${pt.delimiter}${process.env.PATH||""}`}D()&&(r.HVIGOR_USER_HOME=pt.join(Ds.homedir(),".hvigor")),this.env=r}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(){D()||await this.runHvigor(["--stop-daemon"])}async runHvigor(e){D()&&(e=e.includes("--no-daemon")?e:["--no-daemon",...e]);let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];g(`Executing: ${t} ${r.join(" ")}`),await Cu(t,r,{cwd:this.projectRoot,env:this.env,stdout:"inherit",stderr:"inherit"})}};import{execa as Au}from"execa";var Oe=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"];g(`Executing: ${e} ${t.join(" ")}`),await Au(e,t,{cwd:this.projectRoot,stdout:"inherit",stderr:"inherit"})}};import{mkdir as Tu}from"fs/promises";import{dirname as xu,resolve as ku}from"path";import{execa as Mu}from"execa";import{lock as Co,check as Cb}from"proper-lockfile";function Ao(n){return ku(n,".hvigor",".build-lock")}function Ru(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function Cs(n){let e=xu(Ao(n));if(await Tu(e,{recursive:!0}),process.platform==="win32")try{await Mu("attrib",["+h",e])}catch{}}async function Ou(n,e){let t=new AbortController,r=Ru(e);await Cs(n);let o={lockfilePath:Ao(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await Co(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 Co(n,{...o,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function Xe(n,e,t){let{release:r,signal:o}=await Ou(n,t);try{return await e(o)}finally{await r()}}async function As(n,e){let t=new AbortController;await Cs(n);let r={lockfilePath:Ao(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},o;try{o=await Co(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 He from"fs";import*as Qe from"path";import Lu from"json5";var To={HTTP_TIMEOUT_MS:2e4},jn={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"};import{homedir as Ne}from"os";import Se from"path";import{xdgConfig as Nu}from"xdg-basedir";var W={"trae-cn":Se.join(Ne(),".trae-cn"),opencode:Se.join(Nu,"opencode"),cursor:Se.join(Ne(),".cursor"),codebuddy:Se.join(Ne(),".codebuddy"),qoder:Se.join(Ne(),".qoder"),"claude-code":Se.join(Ne(),".claude"),codex:Se.join(Ne(),".codex"),bitfun:Se.join(Ne(),".bitfun"),opendesk:Se.join(Ne(),".opendesk")};import Le from"path";var xo="https://matrix.openharmony.cn",ce={TAGS_API_URL:`${xo}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${xo}/api/registry/skill/skills`,SKILL_API_BASE:`${xo}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},Ts={"trae-cn":{path:Le.join(W["trae-cn"],"skills"),displayName:"trae-cn"},opencode:{path:Le.join(W.opencode,"skills"),displayName:"opencode"},cursor:{path:Le.join(W.cursor,"skills"),displayName:"cursor"},codebuddy:{path:Le.join(W.codebuddy,"skills"),displayName:"codebuddy"},qoder:{path:Le.join(W.qoder,"skills"),displayName:"qoder"},"claude-code":{path:Le.join(W["claude-code"],"skills"),projectPath:".claude/skills",displayName:"claude-code"},codex:{path:Le.join(W.codex,"skills"),displayName:"codex"}},xs={opencode:{path:Le.join(W.opencode,"skills"),displayName:"opencode"}};function Pe(){return D()?xs:Ts}import{homedir as Ut}from"os";import re from"path";var fe="deveco-mcp";var _e={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:re.join(W.opencode,"opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:re.join(process.platform==="win32"?re.join(process.env.APPDATA??re.join(Ut(),"AppData","Roaming"),"Trae CN","User"):re.join(Ut(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:re.join(W.cursor,"mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:re.join(W.codebuddy,"mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:re.join(process.platform==="win32"?re.join(process.env.APPDATA??re.join(Ut(),"AppData","Roaming"),"Qoder","SharedClientCache"):re.join(Ut(),"Library","Application Support","Qoder","SharedClientCache"),"mcp.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"standard"},"claude-code":{name:"claude-code",displayName:"Claude Code",supportsGlobal:!0,globalConfigPath:re.join(Ut(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:re.join(W.codex,"config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function Ms(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function ks(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function Rs(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function Fn(n,e){return n.format==="opencode"?Ms(e):n.format==="claude-code"||n.format==="codex"?ks(e):Rs(e)}var le={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var _u=1e3;function Bn(n){g(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=Qe.join(n,le.SYNC_OUTPUT_PATH);if(!He.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return g(`[ProjectCheck] ${l.reason}`),l}let t=He.statSync(e).mtimeMs;g(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=Hu(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return g(`[ProjectCheck] ${l.reason}`),l}let o=Qe.join(n,le.OH_PACKAGE_JSON5),i=$n(o,t,"root");if(i.required)return g(`[ProjectCheck] Root check: ${i.reason}`),i;let s=Qe.join(n,le.BUILD_PROFILE_JSON5),a=$n(s,t,"build-profile");if(a.required)return g(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let u=Qe.join(n,l.srcPath,le.OH_PACKAGE_JSON5),h=$n(u,t,l.name);if(h.required)return g(`[ProjectCheck] Module '${l.name}' check: ${h.reason}`),h;let v=Qe.join(n,l.srcPath,le.BUILD_PROFILE_JSON5),I=$n(v,t,l.name);if(I.required)return g(`[ProjectCheck] Module '${l.name}' build-profile check: ${I.reason}`),I}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return g(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function $n(n,e,t){if(!He.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=He.statSync(n).mtimeMs;return r-e>_u?{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 Hu(n){let e=Qe.join(n,le.BUILD_PROFILE_JSON5);try{let t=He.readFileSync(e,"utf-8");if(!t.trim())return null;let r=Lu.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}}function Fu(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 $u(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 qt(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 zt(n,e){let t=e,r=`${n} failed`;console.error(ko(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 Vt(n,e,t,r,o,i){if(Bn(i).required){console.log(`
15
- [1/3] Running ohpm install...`);try{await n.installAll()}catch(a){zt("ohpm install",a)}console.log(`
16
- [2/3] Running hvigor sync...`);try{await e.sync(t,r)}catch(a){zt("hvigor sync",a)}console.log(`
17
- [3/3] Running hvigor build...`)}else console.log(`
18
- [skip] ohpm install & hvigor sync (configurations unchanged)`),console.log(`
19
- [1/1] Running hvigor build...`);try{o.type==="product"?await e.buildProduct(t,r):await e.buildModules(t,r,o.modulesToBuild,o.moduleTasks)}catch(a){zt("hvigor build",a)}}var Ls=new ju("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=Ze.discover(e);console.warn(Ns("Ensure the project source is trustworthy before proceeding."));let r=await _.new();Fu(t,n);let o=n.product||"default",i=n.buildMode||"debug",s;if(n.product&&!n.modules)s={type:"product"};else{let l=$u(t,n),u=qt(t,l);s={type:"modules",modulesToBuild:l,moduleTasks:u}}let a=new Oe(r,t.rootDir),c=new be(r,t.rootDir);await Xe(t.rootDir,async()=>Vt(a,c,o,i,s,t.rootDir),()=>{console.log("Another build is already running for this project. Waiting for completion...")}),console.log(`
14
+ `)}`)}static resolveEmulatorPath(e,t){let r;if(t==="win32")r=E.join(e,"tools","emulator","Emulator.exe");else if(t==="darwin")r=E.join(e,"Contents","tools","emulator","Emulator");else throw new Error("Linux is not fully supported yet");if(!M.existsSync(r))throw new Error(`Emulator executable not found at: ${r}`);return r}static verifyTools(e,t,r,o){if(!M.existsSync(e))throw new Error(`Node executable not found at: ${e}`);if(!M.existsSync(t))throw new Error(`ohpm js file not found at: ${t}`);if(!M.existsSync(r))throw new Error(`hvigor js file not found at: ${r}`);if(o&&!M.existsSync(o))throw new Error(`java executable not found at: ${o}`)}static getEmulatorExe(e){let t=B.platform(),r;if(t==="win32")r=Ps(e,"tools","emulator","Emulator.exe");else if(t==="darwin")r=Ps(e,"Contents","tools","emulator","Emulator");else return;return Ss(r)?r:void 0}static isValidApiLevel(e,t){let r=t??23;return Number.isInteger(e)&&e>=17&&e<=r}static parseApiLevelFromFile(e){if(M.existsSync(e))try{let t=M.readFileSync(e,"utf-8"),r=JSON.parse(t),o=r?.apiVersion??r?.data?.apiVersion;if(typeof o!="string"&&typeof o!="number")return;let i=Number(o);return Number.isInteger(i)&&i>=17?i:void 0}catch{return}}static detectFromSdkPkg(e){let t=E.join(e,"default","sdk-pkg.json");return n.parseApiLevelFromFile(t)}static detectFromOhUniPackage(e){let t=[E.join(e,"default","openharmony","toolchains","oh-uni-package.json"),E.join(e,"default","openharmony","native","oh-uni-package.json"),E.join(e,"default","openharmony","previewer","oh-uni-package.json")];for(let r of t){let o=n.parseApiLevelFromFile(r);if(o!==void 0)return o}}getMaxApiLevel(){let e=n.detectFromSdkPkg(this.sdkPath);if(e!==void 0)return e;let t=n.detectFromOhUniPackage(this.sdkPath);return t!==void 0?t:23}detectApiLevel(){return this.getMaxApiLevel()}static findPowerShellPath(){if(n._powerShellPath)return n._powerShellPath;if(B.platform()!=="win32")return n._powerShellPath="",n._powerShellPath;let e=E.join(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return Ss(e)?(g(`[ToolProvider] Found PowerShell at: ${e}`),n._powerShellPath=e,e):(n._powerShellPath="",n._powerShellPath)}static verifySignature(e){if(!M.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=B.platform();if(n.isExecutableFile(e,t)){if(t==="win32"){if(!n.verifyWindowsSignature(e).signed)throw new Error(`The executable is not digitally signed: ${e}`)}else if(t==="darwin"&&!n.verifyMacSignature(e).signed)throw new Error(`The executable is not digitally signed: ${e}`)}}static isExecutableFile(e,t){if(t==="win32")return E.extname(e).toLowerCase()===".exe";if(t==="darwin")try{return M.accessSync(e,M.constants.X_OK),!0}catch{return!1}return!1}static createSignatureScript(){let e=M.mkdtempSync(E.join(B.tmpdir(),"deveco-verify-")),t=E.join(e,"Verify-Signature.ps1");return M.writeFileSync(t,"$env:PSModulePath = ($env:PSModulePath -split ';' | Where-Object { $_ -notmatch 'windowsapps' }) -join ';'; Get-AuthenticodeSignature -FilePath $args[0] | ConvertTo-Json -Depth 3 -Compress","utf-8"),{tmpDir:e,scriptPath:t}}static verifyWindowsSignature(e){let t=n.findPowerShellPath();if(!t)throw new Error("PowerShell application not found");let{tmpDir:r,scriptPath:o}=n.createSignatureScript();try{let i=Do(t,["-NoProfile","-ExecutionPolicy","Bypass","-File",o,e],{encoding:"utf-8",timeout:5e3,stdio:["pipe","pipe","ignore"]}),s=JSON.parse(i);return{signed:s?.Status===0,signer:s?.SignerCertificate?.Subject??void 0}}catch(i){return g(`[ToolProvider] verify Windows Signature, error msg: ${i}`),{signed:!0}}finally{try{M.rmSync(r,{recursive:!0,force:!0})}catch{}}}static verifyMacSignature(e){try{return Do("codesign",["-v",e],{encoding:"utf-8",timeout:5e3}),{signed:!0}}catch{return{signed:!1}}}};import{execa as Cu}from"execa";import*as pt from"path";import*as Ds from"os";var be=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let r={...process.env,DEVECO_SDK_HOME:e.sdkPath};if(e.javaPath){let o=pt.dirname(e.javaPath);r.PATH=`${o}${pt.delimiter}${process.env.PATH||""}`}D()&&(r.HVIGOR_USER_HOME=pt.join(Ds.homedir(),".hvigor")),this.env=r}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(){D()||await this.runHvigor(["--stop-daemon"])}async runHvigor(e){D()&&(e=e.includes("--no-daemon")?e:["--no-daemon",...e]);let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];g(`Executing: ${t} ${r.join(" ")}`),await Cu(t,r,{cwd:this.projectRoot,env:this.env,stdout:"inherit",stderr:"inherit"})}};import{execa as Au}from"execa";var Oe=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"];g(`Executing: ${e} ${t.join(" ")}`),await Au(e,t,{cwd:this.projectRoot,stdout:"inherit",stderr:"inherit"})}};import{mkdir as Tu}from"fs/promises";import{dirname as xu,resolve as ku}from"path";import{execa as Mu}from"execa";import{lock as Co,check as Cb}from"proper-lockfile";function Ao(n){return ku(n,".hvigor",".build-lock")}function Ru(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function Cs(n){let e=xu(Ao(n));if(await Tu(e,{recursive:!0}),process.platform==="win32")try{await Mu("attrib",["+h",e])}catch{}}async function Ou(n,e){let t=new AbortController,r=Ru(e);await Cs(n);let o={lockfilePath:Ao(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await Co(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 Co(n,{...o,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function Xe(n,e,t){let{release:r,signal:o}=await Ou(n,t);try{return await e(o)}finally{await r()}}async function As(n,e){let t=new AbortController;await Cs(n);let r={lockfilePath:Ao(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},o;try{o=await Co(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 He from"fs";import*as Qe from"path";import Lu from"json5";var To={HTTP_TIMEOUT_MS:2e4},jn={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"};import{homedir as Ne}from"os";import Se from"path";import{xdgConfig as Nu}from"xdg-basedir";var W={"trae-cn":Se.join(Ne(),".trae-cn"),opencode:Se.join(Nu,"opencode"),cursor:Se.join(Ne(),".cursor"),codebuddy:Se.join(Ne(),".codebuddy"),qoder:Se.join(Ne(),".qoder"),"claude-code":Se.join(Ne(),".claude"),codex:Se.join(Ne(),".codex"),bitfun:Se.join(Ne(),".bitfun"),opendesk:Se.join(Ne(),".opendesk")};import Le from"path";var xo="https://matrix.openharmony.cn",ce={TAGS_API_URL:`${xo}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${xo}/api/registry/skill/skills`,SKILL_API_BASE:`${xo}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},Ts={"trae-cn":{path:Le.join(W["trae-cn"],"skills"),displayName:"trae-cn"},opencode:{path:Le.join(W.opencode,"skills"),displayName:"opencode"},cursor:{path:Le.join(W.cursor,"skills"),displayName:"cursor"},codebuddy:{path:Le.join(W.codebuddy,"skills"),displayName:"codebuddy"},qoder:{path:Le.join(W.qoder,"skills"),displayName:"qoder"},"claude-code":{path:Le.join(W["claude-code"],"skills"),projectPath:".claude/skills",displayName:"claude-code"},codex:{path:Le.join(W.codex,"skills"),displayName:"codex"}},xs={opencode:{path:Le.join(W.opencode,"skills"),displayName:"opencode"}};function Pe(){return D()?xs:Ts}import{homedir as Ut}from"os";import re from"path";var fe="deveco-mcp";var _e={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:re.join(W.opencode,"opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:re.join(process.platform==="win32"?re.join(process.env.APPDATA??re.join(Ut(),"AppData","Roaming"),"Trae CN","User"):re.join(Ut(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:re.join(W.cursor,"mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:re.join(W.codebuddy,"mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:re.join(process.platform==="win32"?re.join(process.env.APPDATA??re.join(Ut(),"AppData","Roaming"),"Qoder","SharedClientCache"):re.join(Ut(),"Library","Application Support","Qoder","SharedClientCache"),"mcp.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"standard"},"claude-code":{name:"claude-code",displayName:"Claude Code",supportsGlobal:!0,globalConfigPath:re.join(Ut(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:re.join(W.codex,"config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function Ms(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function ks(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function Rs(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function Fn(n,e){return n.format==="opencode"?Ms(e):n.format==="claude-code"||n.format==="codex"?ks(e):Rs(e)}var le={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var _u=1e3;function Bn(n){g(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=Qe.join(n,le.SYNC_OUTPUT_PATH);if(!He.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return g(`[ProjectCheck] ${l.reason}`),l}let t=He.statSync(e).mtimeMs;g(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=Hu(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return g(`[ProjectCheck] ${l.reason}`),l}let o=Qe.join(n,le.OH_PACKAGE_JSON5),i=$n(o,t,"root");if(i.required)return g(`[ProjectCheck] Root check: ${i.reason}`),i;let s=Qe.join(n,le.BUILD_PROFILE_JSON5),a=$n(s,t,"build-profile");if(a.required)return g(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let u=Qe.join(n,l.srcPath,le.OH_PACKAGE_JSON5),h=$n(u,t,l.name);if(h.required)return g(`[ProjectCheck] Module '${l.name}' check: ${h.reason}`),h;let v=Qe.join(n,l.srcPath,le.BUILD_PROFILE_JSON5),I=$n(v,t,l.name);if(I.required)return g(`[ProjectCheck] Module '${l.name}' build-profile check: ${I.reason}`),I}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return g(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function $n(n,e,t){if(!He.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=He.statSync(n).mtimeMs;return r-e>_u?{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 Hu(n){let e=Qe.join(n,le.BUILD_PROFILE_JSON5);try{let t=He.readFileSync(e,"utf-8");if(!t.trim())return null;let r=Lu.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}}function Fu(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 $u(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 qt(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 zt(n,e){let t=e,r=`${n} failed`;console.error(ko(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 Vt(n,e,t,r,o,i){let s=Bn(i);console.log(`
15
+ [ohpm install] Running...`);try{await n.installAll()}catch(a){zt("ohpm install",a)}if(s.required){console.log(`
16
+ [hvigor sync] Running...`);try{await e.sync(t,r)}catch(a){zt("hvigor sync",a)}}else console.log(`
17
+ [hvigor sync] Skipped (configurations unchanged)`);console.log(`
18
+ [hvigor build] Running...`);try{o.type==="product"?await e.buildProduct(t,r):await e.buildModules(t,r,o.modulesToBuild,o.moduleTasks)}catch(a){zt("hvigor build",a)}}var Ls=new ju("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=Ze.discover(e);console.warn(Ns("Ensure the project source is trustworthy before proceeding."));let r=await _.new();Fu(t,n);let o=n.product||"default",i=n.buildMode||"debug",s;if(n.product&&!n.modules)s={type:"product"};else{let l=$u(t,n),u=qt(t,l);s={type:"modules",modulesToBuild:l,moduleTasks:u}}let a=new Oe(r,t.rootDir),c=new be(r,t.rootDir);await Xe(t.rootDir,async()=>Vt(a,c,o,i,s,t.rootDir),()=>{console.log("Another build is already running for this project. Waiting for completion...")}),console.log(`
20
19
  `+Os("Build completed successfully"))}catch(e){console.error(ko(e.message)),process.exit(1)}});Ls.command("clean").description("Clean HarmonyOS project build outputs").action(async()=>{try{let n=process.cwd(),e=Ze.discover(n);console.warn(Ns("Ensure the project source is trusted before proceeding."));let t=await _.new(),r=new be(t,e.rootDir);await Xe(e.rootDir,async()=>{console.log(`
21
20
  [1/2] Running hvigor clean...`);try{await r.clean()}catch(o){zt("hvigor clean",o)}console.log(`
22
21
  [2/2] Running hvigor --stop-daemon...`);try{await r.stopDaemon()}catch(o){zt("hvigor --stop-daemon",o)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
@@ -52,7 +51,7 @@ Available runnable modules:
52
51
  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(Ys(`
53
52
  Application '${t}': ${s}`))}else console.log(`
54
53
  Application '${t}' installed successfully (no ability to launch).`)}var Rp=new Ip("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("--preview","Launch DevEco Studio previewer instead of installing/running the app").option("--count <n>","Previewer only: number of previewer windows to launch (multi-previewer mode)").option("--devices <names>",`Previewer only: comma-separated device product names (e.g. "Pura 90 Pro,MatePad 11.5'S"). Takes priority over --count`).action(async n=>{try{await Hp(n)}catch(e){console.error(Dp(e.message)),process.exit(1)}});async function Op(n,e,t,r,o){let i=new Oe(e,n.rootDir),s=new be(e,n.rootDir),a=new Set;for(let{moduleName:h,targetName:v}of t)for(let I of n.collectNonHarDependentModuleList(h))a.add(`${I}@${v}`);let c=[...a],l=qt(n,c),u={type:"modules",modulesToBuild:c,moduleTasks:l};await Xe(n.rootDir,()=>Vt(i,s,r,o,u,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion...")),console.log(`
55
- `+Ys("Build completed successfully."))}async function Np(n,e,t,r,o){let i=new Jt(t),s=K.from(t),a=r[0]?.moduleName||o[0];await Gs(n,e,t,i,s,a)||process.exit(1)}function Lp(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.`)}}function _p(n,e,t,r){let o=new Set;for(let{moduleName:i,targetName:s}of e){let a=n.collectNonHarDependentModuleList(i);for(let c of a)o.add(n.findArtifactPath(c,s,t,r));o.add(n.findArtifactPath(i,s,t,r))}return[...o]}async function Hp(n){let e=Ze.discover(process.cwd());console.warn(Cp("Ensure the project source is trusted before proceeding."));let t=await _.new(),r=xp(e,n.module),o=r.map(Ap);if(n.preview){await Np(n,e,t,o,r);return}Lp(e,o);let i=new Jt(t),s=K.from(t),a=await Tp(s,n.device),c=a.includes("127.0.0.1")||a.includes("localhost"),l=n.product||"default";e.validateProduct(l);let u=n.buildMode||"debug";n.skipBuild||await Op(e,t,o,l,u);let h=_p(e,o,c,l),v=e.getBundleName(),I=kp(e,o,n.ability);await Mp(i,a,v,h,I,!!n.uninstall)}var Js=Rp;import{Command as jp}from"commander";import{green as Ks,red as Zs,cyan as Lo}from"colorette";import{execa as Xs}from"execa";function Fp(){return"@deveco-test/hmos-deveco-cli"}function $p(){return"0.1.0-TD.5"}var Bp=new jp("update").description("Update deveco-cli to latest").action(async()=>{let n=Fp(),e=$p();console.log(Lo("Checking for updates..."));try{let{stdout:t}=await Xs("npm",["view",n,"version"]),r=t.trim();if(r===e){console.log(Ks(`
54
+ `+Ys("Build completed successfully."))}async function Np(n,e,t,r,o){let i=new Jt(t),s=K.from(t),a=r[0]?.moduleName||o[0];await Gs(n,e,t,i,s,a)||process.exit(1)}function Lp(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.`)}}function _p(n,e,t,r){let o=new Set;for(let{moduleName:i,targetName:s}of e){let a=n.collectNonHarDependentModuleList(i);for(let c of a)o.add(n.findArtifactPath(c,s,t,r));o.add(n.findArtifactPath(i,s,t,r))}return[...o]}async function Hp(n){let e=Ze.discover(process.cwd());console.warn(Cp("Ensure the project source is trusted before proceeding."));let t=await _.new(),r=xp(e,n.module),o=r.map(Ap);if(n.preview){await Np(n,e,t,o,r);return}Lp(e,o);let i=new Jt(t),s=K.from(t),a=await Tp(s,n.device),c=a.includes("127.0.0.1")||a.includes("localhost"),l=n.product||"default";e.validateProduct(l);let u=n.buildMode||"debug";n.skipBuild||await Op(e,t,o,l,u);let h=_p(e,o,c,l),v=e.getBundleName(),I=kp(e,o,n.ability);await Mp(i,a,v,h,I,!!n.uninstall)}var Js=Rp;import{Command as jp}from"commander";import{green as Ks,red as Zs,cyan as Lo}from"colorette";import{execa as Xs}from"execa";function Fp(){return"@deveco-test/hmos-deveco-cli"}function $p(){return"0.1.0-TD.5.1"}var Bp=new jp("update").description("Update deveco-cli to latest").action(async()=>{let n=Fp(),e=$p();console.log(Lo("Checking for updates..."));try{let{stdout:t}=await Xs("npm",["view",n,"version"]),r=t.trim();if(r===e){console.log(Ks(`
56
55
  ${n} is already up to date (version ${e}.)`));return}console.log(Lo(`
57
56
  New version found: ${r} (current: ${e})`)),console.log(Lo(`Updating ${n}...`)),await Xs("npm",["install","-g",`${n}@latest`],{stdio:"inherit"}),console.log(`
58
57
  `+Ks(`${n} updated successfully to version ${r}.`))}catch(t){let r=t;console.error(Zs(`Failed to update ${n}`)),r.message&&console.error(Zs(r.message)),process.exit(1)}}),Qs=Bp;import{Command as lm}from"commander";import{execa as Fo}from"execa";function V(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as Wp}from"child_process";var Up=2500;function zp(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 qp(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=u=>{if(!o){o=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners();try{n.kill()}catch{}r(new Error(u))}},l=setTimeout(a,Up);n.once("error",u=>c(u.message)),zp(n,l,s,a,c,i)}function ea(n,e,t){return g(`Spawning emulator: ${n} ${t.join(" ")}`),new Promise((r,o)=>{let i=[],s=Wp(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)),qp(s,i,r,o)})}import*as gt from"path";function Vp(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 Gp(n){let e=n.instancePath?.trim();if(e)return gt.dirname(gt.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?gt.dirname(gt.normalize(t)).replace(/\\/g,"/"):""}function Yp(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function ta(n,e){return e?[...n,"-bootmode",e]:n}function Jp(n,e,t){let r=[ta(["-start",n],t)],o=Gp(e);if(o)for(let i of Yp(e.imageRoot))r.push(ta(["-hvd",n,"-path",o,...i],t));return Vp(r)}async function na(n,e,t,r){let o=new Error("No start strategy ran"),i=Jp(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 _o(n){return(await K.withHdcPath(n).listDevices()).map(t=>t.serial).filter(Yt)}async function Ho(n){let e=await _o(n);return e.length===0?[]:(await Promise.all(e.map(r=>Wn(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function ra(n,e){return(await Ho(n)).includes(e)}import*as vt from"path";import{existsSync as Kp,statSync as Zp}from"fs";function yt(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function Xp(n){let e=yt(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 Qp(n){return yt(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function em(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=vt.dirname(vt.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let o=vt.join(t,r.name);Kp(o)&&Zp(o).isDirectory()&&(r.instancePath=o.replace(/\\/g,"/"))}}function tm(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=Qp(t),o=yt(t,["deviceType","DeviceType","devicetype"]),i=yt(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:Xp(t),path:yt(t,["path","Path","hvdPath","hvd_path"]),imageRoot:yt(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 nm(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 oa(n){let t=tm(n)??nm(n);return em(t),t}function jo(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function rm(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function om(n){if(!rm(n))return null;let e=jo(n,["osVersion","OsVersion","OSVersion"]),t=jo(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=jo(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function Vn(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=om(o);i&&r.push(i)}return r}catch{return[]}}function ia(n){let t=Vn(n).map(r=>r.osVersion).filter(Boolean);return[...new Set(t)]}var sa=/no images are available/i;function he(n){return n.normalize("NFKC").trim().toLowerCase()}function im(n){let e=n.message||"";return sa.test(e)}var wt=class n{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 Fo(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return ea(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return oa(e)}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let r of t)r.name&&r.deviceType&&e.set(V(r.name),r.deviceType)}catch{}return e}async startEmulator(e){let t=await this.listEmulators(),r=V(e),o=t.find(a=>V(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 na(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.
@@ -1265,11 +1264,11 @@ Output so far:
1265
1264
  `).trim()||"";r(rg(c,l,u))}),o.on("error",c=>{clearTimeout(a),r({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function Ii(n,e,t,r,o){let i={...process.env,DEVECO_SDK_HOME:r};return D()&&(i.HVIGOR_USER_HOME=tl.join(el.homedir(),".hvigor")),await og([e,[t,...o]],n,i)}var ig=["--sync","-p","product=default","--analyze=normal","--parallel","--incremental","--no-daemon"];async function nl(n,e){try{return(await Ii(n,e.nodePath,e.hvigorJsPath,e.sdkPath,ig)).success}catch(t){return d.info(`syncProject failed: ${JSON.stringify(t)}`),!1}}import{spawn as sg}from"child_process";var ag=["install","--all"];async function cg(n,e,t,r){return new Promise(o=>{let i=sg(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(`
1266
1265
  `);o({exitCode:c??-1,output:l})}),i.on("error",c=>{let l=[s,a].filter(Boolean).join(`
1267
1266
  `);o({exitCode:-1,output:l+`
1268
- `+c.message})})})}function lg(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>d.info("[ohpm] %s",e))}async function rl(n,e){try{let{exitCode:t,output:r}=await cg(e.nodePath,[e.ohpmJsPath,...ag],n,e.sdkPath);return lg(r),t===0?(d.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(d.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",t),d.error("ohpm \u8F93\u51FA: %s",r),!1)}catch(t){return d.error("ohpm \u5B89\u88C5\u5F02\u5E38",t),!1}}var ol={UNINITIALIZED:-32099,UNKNOWN:-32e3},bn=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,ol.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,ol.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var Ot=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){d.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){d.warn("[ArktsLspManager] sendRequest before LSP ready, dropped");return}this.lspProxy.sendRequest(e)}static async handleSyncProject(e,t){if(d.info("[ArktsLspManager] Received arkts/syncProject"),!e)return d.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let r=await As(e,async()=>await rl(e,t)?await nl(e,t)?(d.info("[ArktsLspManager] syncProject completed successfully"),{status:"success"}):(d.error("[ArktsLspManager] syncProject failed"),{status:"failed",reason:"hvigor sync failed"}):(d.error("[ArktsLspManager] ohpm install failed"),{status:"failed",reason:"ohpm install failed"}));return r.acquired?r.result:(d.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){d.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){d.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){d.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e){let t=new $r(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)d.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:O,method:b.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();d.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?bn.uninitialized(t):bn.unknown();this.onMessage({jsonrpc:O,method:b.ARKTS_INITIALIZATION_FAILED,params:r.toJsonRpcErrorParams()}),this.lspProxy=null}};handleLspMessage(e){this.onMessage(e)}maybeRetryLspAfterSuccessfulSync(){this.isInitialized||this.lspProxy!==null||(d.info("[ArktsLspManager] Retrying LSP startup after successful sync"),this.onMessage({jsonrpc:O,method:b.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new Br(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new Wr(this.config.workspaceRoot),this.depMapWatcher.on("reload",e=>{if(!this.lspProxy){d.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.lspProxy.sendNotification({jsonrpc:O,method:b.ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT,params:{moduleSet:r}}),this.onMessage({jsonrpc:O,method:b.ARKTS_SYNC_COMPLETED,params:{success:!0}})}),this.depMapWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){d.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),this.onConfigChanged?.()}};var dg=120*1e3,ug=10080*60*1e3,pg=7200*60*1e3,Nt=class{manager=null;diagnosticWaiters=new Map;initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;toolProvider;nodeMaxOldSpaceSize;onConfigChangedCallback=null;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:Di.object({files:Di.array(Di.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,devecoStudioPath:t,arktsLangServerPath:r}=this.resolveProjectAndDeveco(),o=ve(e),{logPath:i,indexPath:s}=this.getLogAndIndexPath(o);setImmediate(()=>{gi(s,ug,"[ArkTS-Check]"),gi(i,pg,"[ArkTS-Check]")}),jc(i);let a=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,c=Number.isNaN(a)?void 0:a;f.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${c??"undefined \u2192 dynamic formula applies"}`);let l=this.toolProvider.sdkPath;f.info(`ArktsCheck devecoStudioPath: ${t}, sdkPath: ${l}`),this.manager=new Ot({sdkPath:l,arktsLangServerPath:r,workspaceRoot:G(o),indexLogPath:s,nodeMaxOldSpaceSize:c,nodePath:this.toolProvider.nodePath}),this.manager.setOnMessage(u=>this.handleLspMessage(u)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((u,h)=>{this.initResolve=u,this.initReject=h,this.armInitTimer(un),this.manager.start([]).catch(v=>{let I=v instanceof Error?v:new Error(String(v));this.failInit(I)})})}resolveProjectAndDeveco(){let e=De(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.toolProvider.devecoStudioPath??"";f.debug(`DevEco Studio installation path: ${t}`);let r=this.toolProvider.lspServerPath;if(!r)throw new Error("arkts-lang-server path not found");return{harmonyRoot:e,devecoStudioPath:t,arktsLangServerPath:r}}armInitTimer(e){this.initDeadlineTimer&&clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=setTimeout(()=>{let t=this.initReject;this.clearInitHandlers(),t?.(new Error("LSP initialize timeout"))},e)}clearInitHandlers(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async checkFile(e){this.initialized||await this.initialize();let t=ln(rt(e)),r=hi(e),o=await xe.promises.readFile(e,"utf8"),s=`deveco.apptool.${we.extname(e).replace(/^\./,"")||"plaintext"}`,a=new Promise((l,u)=>{let h=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&u(new Error("Wait for diagnostics timeout"))},dg);this.diagnosticWaiters.set(t,{resolve:l,reject:u,timer:h})}),c={textDocument:{uri:r,text:o,languageId:s,version:o.length},editorFiles:[r],isFromEditor:!1};f.debug(`textDocument/didOpen uri=${r} content_len=${o.length}`),this.sendNotification("textDocument/didOpen",c);try{return await a}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:r},isManual:!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(`
1267
+ `+c.message})})})}function lg(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>d.info("[ohpm] %s",e))}async function rl(n,e){try{let{exitCode:t,output:r}=await cg(e.nodePath,[e.ohpmJsPath,...ag],n,e.sdkPath);return lg(r),t===0?(d.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(d.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",t),d.error("ohpm \u8F93\u51FA: %s",r),!1)}catch(t){return d.error("ohpm \u5B89\u88C5\u5F02\u5E38",t),!1}}var ol={UNINITIALIZED:-32099,UNKNOWN:-32e3},bn=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,ol.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,ol.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var Ot=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){d.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){d.warn("[ArktsLspManager] sendRequest before LSP ready, dropped");return}this.lspProxy.sendRequest(e)}static async handleSyncProject(e,t,r){if(d.info("[ArktsLspManager] Received arkts/syncProject"),!e)return d.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let o=r?.skipHvigorSync===!0,i=await As(e,async()=>await rl(e,t)?o?(d.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await nl(e,t)?(d.info("[ArktsLspManager] syncProject completed successfully"),{status:"success"}):(d.error("[ArktsLspManager] syncProject failed"),{status:"failed",reason:"hvigor sync failed"}):(d.error("[ArktsLspManager] ohpm install failed"),{status:"failed",reason:"ohpm install failed"}));return i.acquired?i.result:(d.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){d.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){d.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){d.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e){let t=new $r(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)d.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:O,method:b.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();d.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?bn.uninitialized(t):bn.unknown();this.onMessage({jsonrpc:O,method:b.ARKTS_INITIALIZATION_FAILED,params:r.toJsonRpcErrorParams()}),this.lspProxy=null}};handleLspMessage(e){this.onMessage(e)}maybeRetryLspAfterSuccessfulSync(){this.isInitialized||this.lspProxy!==null||(d.info("[ArktsLspManager] Retrying LSP startup after successful sync"),this.onMessage({jsonrpc:O,method:b.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new Br(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new Wr(this.config.workspaceRoot),this.depMapWatcher.on("reload",e=>{if(!this.lspProxy){d.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.lspProxy.sendNotification({jsonrpc:O,method:b.ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT,params:{moduleSet:r}}),this.onMessage({jsonrpc:O,method:b.ARKTS_SYNC_COMPLETED,params:{success:!0}})}),this.depMapWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){d.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),this.onConfigChanged?.()}};var dg=120*1e3,ug=10080*60*1e3,pg=7200*60*1e3,Nt=class{manager=null;diagnosticWaiters=new Map;initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;toolProvider;nodeMaxOldSpaceSize;onConfigChangedCallback=null;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:Di.object({files:Di.array(Di.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,devecoStudioPath:t,arktsLangServerPath:r}=this.resolveProjectAndDeveco(),o=ve(e),{logPath:i,indexPath:s}=this.getLogAndIndexPath(o);setImmediate(()=>{gi(s,ug,"[ArkTS-Check]"),gi(i,pg,"[ArkTS-Check]")}),jc(i);let a=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,c=Number.isNaN(a)?void 0:a;f.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${c??"undefined \u2192 dynamic formula applies"}`);let l=this.toolProvider.sdkPath;f.info(`ArktsCheck devecoStudioPath: ${t}, sdkPath: ${l}`),this.manager=new Ot({sdkPath:l,arktsLangServerPath:r,workspaceRoot:G(o),indexLogPath:s,nodeMaxOldSpaceSize:c,nodePath:this.toolProvider.nodePath}),this.manager.setOnMessage(u=>this.handleLspMessage(u)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((u,h)=>{this.initResolve=u,this.initReject=h,this.armInitTimer(un),this.manager.start([]).catch(v=>{let I=v instanceof Error?v:new Error(String(v));this.failInit(I)})})}resolveProjectAndDeveco(){let e=De(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.toolProvider.devecoStudioPath??"";f.debug(`DevEco Studio installation path: ${t}`);let r=this.toolProvider.lspServerPath;if(!r)throw new Error("arkts-lang-server path not found");return{harmonyRoot:e,devecoStudioPath:t,arktsLangServerPath:r}}armInitTimer(e){this.initDeadlineTimer&&clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=setTimeout(()=>{let t=this.initReject;this.clearInitHandlers(),t?.(new Error("LSP initialize timeout"))},e)}clearInitHandlers(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async checkFile(e){this.initialized||await this.initialize();let t=ln(rt(e)),r=hi(e),o=await xe.promises.readFile(e,"utf8"),s=`deveco.apptool.${we.extname(e).replace(/^\./,"")||"plaintext"}`,a=new Promise((l,u)=>{let h=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&u(new Error("Wait for diagnostics timeout"))},dg);this.diagnosticWaiters.set(t,{resolve:l,reject:u,timer:h})}),c={textDocument:{uri:r,text:o,languageId:s,version:o.length},editorFiles:[r],isFromEditor:!1};f.debug(`textDocument/didOpen uri=${r} content_len=${o.length}`),this.sendNotification("textDocument/didOpen",c);try{return await a}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:r},isManual:!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(`
1269
1268
  `):"\u6CA1\u6709\u6709\u6548\u7684 .ets \u6587\u4EF6"}],isError:!0}:(await this.runDiagnosticsForFiles(o,t,r),this.formatCallResult(t,r))}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=we.isAbsolute(i)?i:we.join(r,i);if(!xe.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${i}`);continue}if(!xe.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 Ac(500);try{let i=await this.checkFile(o);r.push(mg(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(`
1270
1269
  `)),t.length>0&&r.push(t.join(`
1271
1270
  `));let o=r.join(`
1272
- `).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(){if(this.failAllPending(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(e){f.warn(`Failed to dispose ArktsLspManager: ${e}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null,this.clearInitHandlers()}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":case"textDocument/didOpen":this.handleDiagnosticsNotification(t.params);break;case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(un),f.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{f.info("Received arkts/initialized");let o=this.initResolve;this.clearInitHandlers(),o?.();break}case"arkts/initializationFailed":{let i=t.params?.message??"unknown";f.error(`LSP initialization failed: ${i}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${i}`));break}case"workspace/didChangeConfiguration":f.info("Received workspace/didChangeConfiguration, sync deferred to next check");break;default:break}}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let r=this.resolveDiagnosticWaiter(t);if(!r)return;if(typeof e.errorMessage=="string"){f.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),r.resolve({errorMessage:e.errorMessage});return}let o=e.diagnostics,i=Array.isArray(o)?o.length:0;f.debug(`diagnostics received uri=${t} count=${i}`),r.resolve(Array.isArray(o)?o:[])}resolveDiagnosticWaiter(e){let t=ln(e),r=this.popDiagnosticWaiter(t);if(r)return r;for(let o of xc(e)){let i=this.popDiagnosticWaiter(o);if(i)return i}}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}failAllPending(e){for(let[,r]of this.diagnosticWaiters)clearTimeout(r.timer),r.reject(e);this.diagnosticWaiters.clear();let t=this.initReject;this.clearInitHandlers(),t?.(e)}getLogAndIndexPath(e){try{let t=we.join(lr(),"ArkTSCheck"),r=we.join(t,"mapping-config.properties"),o=kc(e,r),i=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=we.join(t,"lsp-log",String(o),i),a=we.join(t,"lsp-index",String(o));return xe.mkdirSync(s,{recursive:!0}),xe.mkdirSync(a,{recursive:!0}),{logPath:ve(s),indexPath:ve(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function mg(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{spawn as fg}from"child_process";import*as C from"fs";import*as Z from"path";import{z as Ci}from"zod";var il=60*1e3,hg=30*1e3,gg=new Set(["textDocument/didOpen","textDocument/didChange","textDocument/didClose","textDocument/didSave"]),yg=1e3,Ti=class{nextRequestId=1;pendingRequests=new Map;diagnosticWaiters=new Map;fileCheckLock=Promise.resolve();closed=!1;wrapperState="preInitialize";queuedDocumentNotifications=[];backendReady=!1;projectPath=null;clangdStdin=null;clangdStdout=null;clangdBuffer=Buffer.alloc(0);constructor(){}isClosed(){return this.closed}async initialize(e){this.projectPath=e,this.wrapperState="waitingForDatabase"}async connectClangdProcess(e,t){if(this.closed)throw new Error("Client is already closed");this.clangdStdin=e,this.clangdStdout=t,this.wrapperState="startingBackend",this.clangdStdout.on("data",a=>this.handleClangdData(a)),this.clangdStdout.on("error",a=>{f.warn(`[CppCheck] clangd stdout error: ${a}`),this.failAll(new Error(`clangd stdout error: ${a}`))}),this.clangdStdout.on("end",()=>{this.failAll(new Error("C++ language server connection closed"))});let r=ve(this.projectPath),o=rt(r),i=Z.basename(r)||"workspace",s={processId:null,clientInfo:{name:"devecocli-mcp-server",version:"0.1.0-TD.5"},rootPath:r,rootUri:o,workspaceFolders:[{uri:o,name:i}],capabilities:{}};await this.sendRequestToClangd("initialize",s,il),await this.sendNotificationToClangd("initialized",{}),this.backendReady=!0,this.wrapperState="proxying";for(let a of this.queuedDocumentNotifications)await this.writeToClangd(a);this.queuedDocumentNotifications.length=0,f.info("[CppCheck] clangd backend ready, switched to proxying mode")}async waitForBackendReady(){if(this.backendReady)return;let e=il,t=Date.now();for(;!this.backendReady&&!this.closed&&Date.now()-t<e;)await new Promise(r=>setTimeout(r,500));if(!this.backendReady)throw new Error("Timed out waiting for clangd backend to be ready")}async checkFile(e){await this.waitForBackendReady();let t=await this.acquireFileCheckLock();try{return await this.doCheckFile(e)}finally{t()}}async doCheckFile(e){let t;try{t=C.realpathSync(e)}catch{t=e}let r=rt(t),o=Tc(t),i=await C.promises.readFile(t,"utf8"),s=new Promise((a,c)=>{let l=setTimeout(()=>{this.diagnosticWaiters.delete(r)&&c(new Error(`Timed out waiting for diagnostics: ${e}`))},hg);this.diagnosticWaiters.set(r,{resolve:a,reject:c,timer:l})});try{await this.sendNotification("textDocument/didOpen",{textDocument:{uri:r,languageId:o,version:1,text:i}})}catch(a){let c=this.diagnosticWaiters.get(r);throw c&&(clearTimeout(c.timer),this.diagnosticWaiters.delete(r)),a}try{return await s}finally{await this.closeFile(r).catch(a=>{f.warn(`[CppCheck] didClose failed for ${r}: ${a}`)})}}async close(){if(!this.closed&&(this.closed=!0,this.wrapperState="shuttingDown",this.backendReady&&this.clangdStdin)){try{await this.sendRequestToClangd("shutdown",null,3e3)}catch(e){f.warn(`[CppCheck] shutdown request failed: ${e}`)}try{await this.sendNotificationToClangd("exit",null)}catch(e){f.warn(`[CppCheck] exit notification failed: ${e}`)}try{this.clangdStdin.end()}catch(e){f.warn(`[CppCheck] stdin.end() failed: ${e}`)}}}async sendNotification(e,t){let r={jsonrpc:"2.0",method:e,params:t??void 0};if(this.backendReady&&this.clangdStdin){await this.writeToClangd(r);return}gg.has(e)&&this.queuedDocumentNotifications.push(r)}async closeFile(e){await this.sendNotification("textDocument/didClose",{textDocument:{uri:e}})}async sendRequestToClangd(e,t,r){let o=this.nextRequestId++;return new Promise((i,s)=>{let a=setTimeout(()=>{this.pendingRequests.delete(o)&&s(new Error(`Timed out waiting for ${e} response`))},r);this.pendingRequests.set(o,{resolve:i,reject:s,timer:a}),this.writeToClangd({jsonrpc:"2.0",id:o,method:e,params:t??void 0}).catch(c=>{this.pendingRequests.delete(o)&&(clearTimeout(a),s(c))})})}async sendNotificationToClangd(e,t){await this.writeToClangd({jsonrpc:"2.0",method:e,params:t??void 0})}async writeToClangd(e){if(!this.clangdStdin)throw new Error("clangd stdin not available");return new Promise((t,r)=>{let o;try{o=JSON.stringify(e)}catch(u){r(new Error(`Failed to encode LSP message: ${u}`));return}let i=Buffer.from(o,"utf8"),s=Buffer.from(`Content-Length: ${i.length}\r
1271
+ `).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(){if(this.failAllPending(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(e){f.warn(`Failed to dispose ArktsLspManager: ${e}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null,this.clearInitHandlers()}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":case"textDocument/didOpen":this.handleDiagnosticsNotification(t.params);break;case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(un),f.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{f.info("Received arkts/initialized");let o=this.initResolve;this.clearInitHandlers(),o?.();break}case"arkts/initializationFailed":{let i=t.params?.message??"unknown";f.error(`LSP initialization failed: ${i}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${i}`));break}case"workspace/didChangeConfiguration":f.info("Received workspace/didChangeConfiguration, sync deferred to next check");break;default:break}}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let r=this.resolveDiagnosticWaiter(t);if(!r)return;if(typeof e.errorMessage=="string"){f.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),r.resolve({errorMessage:e.errorMessage});return}let o=e.diagnostics,i=Array.isArray(o)?o.length:0;f.debug(`diagnostics received uri=${t} count=${i}`),r.resolve(Array.isArray(o)?o:[])}resolveDiagnosticWaiter(e){let t=ln(e),r=this.popDiagnosticWaiter(t);if(r)return r;for(let o of xc(e)){let i=this.popDiagnosticWaiter(o);if(i)return i}}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}failAllPending(e){for(let[,r]of this.diagnosticWaiters)clearTimeout(r.timer),r.reject(e);this.diagnosticWaiters.clear();let t=this.initReject;this.clearInitHandlers(),t?.(e)}getLogAndIndexPath(e){try{let t=we.join(lr(),"ArkTSCheck"),r=we.join(t,"mapping-config.properties"),o=kc(e,r),i=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=we.join(t,"lsp-log",String(o),i),a=we.join(t,"lsp-index",String(o));return xe.mkdirSync(s,{recursive:!0}),xe.mkdirSync(a,{recursive:!0}),{logPath:ve(s),indexPath:ve(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function mg(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{spawn as fg}from"child_process";import*as C from"fs";import*as Z from"path";import{z as Ci}from"zod";var il=60*1e3,hg=30*1e3,gg=new Set(["textDocument/didOpen","textDocument/didChange","textDocument/didClose","textDocument/didSave"]),yg=1e3,Ti=class{nextRequestId=1;pendingRequests=new Map;diagnosticWaiters=new Map;fileCheckLock=Promise.resolve();closed=!1;wrapperState="preInitialize";queuedDocumentNotifications=[];backendReady=!1;projectPath=null;clangdStdin=null;clangdStdout=null;clangdBuffer=Buffer.alloc(0);constructor(){}isClosed(){return this.closed}async initialize(e){this.projectPath=e,this.wrapperState="waitingForDatabase"}async connectClangdProcess(e,t){if(this.closed)throw new Error("Client is already closed");this.clangdStdin=e,this.clangdStdout=t,this.wrapperState="startingBackend",this.clangdStdout.on("data",a=>this.handleClangdData(a)),this.clangdStdout.on("error",a=>{f.warn(`[CppCheck] clangd stdout error: ${a}`),this.failAll(new Error(`clangd stdout error: ${a}`))}),this.clangdStdout.on("end",()=>{this.failAll(new Error("C++ language server connection closed"))});let r=ve(this.projectPath),o=rt(r),i=Z.basename(r)||"workspace",s={processId:null,clientInfo:{name:"devecocli-mcp-server",version:"0.1.0-TD.5.1"},rootPath:r,rootUri:o,workspaceFolders:[{uri:o,name:i}],capabilities:{}};await this.sendRequestToClangd("initialize",s,il),await this.sendNotificationToClangd("initialized",{}),this.backendReady=!0,this.wrapperState="proxying";for(let a of this.queuedDocumentNotifications)await this.writeToClangd(a);this.queuedDocumentNotifications.length=0,f.info("[CppCheck] clangd backend ready, switched to proxying mode")}async waitForBackendReady(){if(this.backendReady)return;let e=il,t=Date.now();for(;!this.backendReady&&!this.closed&&Date.now()-t<e;)await new Promise(r=>setTimeout(r,500));if(!this.backendReady)throw new Error("Timed out waiting for clangd backend to be ready")}async checkFile(e){await this.waitForBackendReady();let t=await this.acquireFileCheckLock();try{return await this.doCheckFile(e)}finally{t()}}async doCheckFile(e){let t;try{t=C.realpathSync(e)}catch{t=e}let r=rt(t),o=Tc(t),i=await C.promises.readFile(t,"utf8"),s=new Promise((a,c)=>{let l=setTimeout(()=>{this.diagnosticWaiters.delete(r)&&c(new Error(`Timed out waiting for diagnostics: ${e}`))},hg);this.diagnosticWaiters.set(r,{resolve:a,reject:c,timer:l})});try{await this.sendNotification("textDocument/didOpen",{textDocument:{uri:r,languageId:o,version:1,text:i}})}catch(a){let c=this.diagnosticWaiters.get(r);throw c&&(clearTimeout(c.timer),this.diagnosticWaiters.delete(r)),a}try{return await s}finally{await this.closeFile(r).catch(a=>{f.warn(`[CppCheck] didClose failed for ${r}: ${a}`)})}}async close(){if(!this.closed&&(this.closed=!0,this.wrapperState="shuttingDown",this.backendReady&&this.clangdStdin)){try{await this.sendRequestToClangd("shutdown",null,3e3)}catch(e){f.warn(`[CppCheck] shutdown request failed: ${e}`)}try{await this.sendNotificationToClangd("exit",null)}catch(e){f.warn(`[CppCheck] exit notification failed: ${e}`)}try{this.clangdStdin.end()}catch(e){f.warn(`[CppCheck] stdin.end() failed: ${e}`)}}}async sendNotification(e,t){let r={jsonrpc:"2.0",method:e,params:t??void 0};if(this.backendReady&&this.clangdStdin){await this.writeToClangd(r);return}gg.has(e)&&this.queuedDocumentNotifications.push(r)}async closeFile(e){await this.sendNotification("textDocument/didClose",{textDocument:{uri:e}})}async sendRequestToClangd(e,t,r){let o=this.nextRequestId++;return new Promise((i,s)=>{let a=setTimeout(()=>{this.pendingRequests.delete(o)&&s(new Error(`Timed out waiting for ${e} response`))},r);this.pendingRequests.set(o,{resolve:i,reject:s,timer:a}),this.writeToClangd({jsonrpc:"2.0",id:o,method:e,params:t??void 0}).catch(c=>{this.pendingRequests.delete(o)&&(clearTimeout(a),s(c))})})}async sendNotificationToClangd(e,t){await this.writeToClangd({jsonrpc:"2.0",method:e,params:t??void 0})}async writeToClangd(e){if(!this.clangdStdin)throw new Error("clangd stdin not available");return new Promise((t,r)=>{let o;try{o=JSON.stringify(e)}catch(u){r(new Error(`Failed to encode LSP message: ${u}`));return}let i=Buffer.from(o,"utf8"),s=Buffer.from(`Content-Length: ${i.length}\r
1273
1272
  \r
1274
1273
  `,"ascii"),a=!1,c=u=>{a||(a=!0,u?r(u):t())};if(this.clangdStdin.write(Buffer.concat([s,i]),u=>{u?c(u):a||c()}))c();else{let u=()=>c();this.clangdStdin.once("drain",u)}})}handleClangdData(e){for(this.clangdBuffer=this.clangdBuffer.length===0?e:Buffer.concat([this.clangdBuffer,e]);;){let t=this.clangdBuffer.indexOf(`\r
1275
1274
  \r
@@ -1284,8 +1283,8 @@ Output so far:
1284
1283
  `),a.join(`
1285
1284
  `)].filter(h=>h.trim().length>0).join(`
1286
1285
  `).trim()||"No diagnostics collected"}],isError:l}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return f.warn(`ArkTS check rejected: project is ${ul[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return f.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return this.arktsCheckTool.handleCall({files:e});default:return{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"),f.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(f.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:"Initializing, please retry in 10 seconds"}],isError:!0}):(f.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"No HarmonyOS project detected. Please verify the project directory or create a project first."}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=ki?(f.error(`Init retry limit reached (${this.initRetryCount}/${ki}), will not auto-retry`),{content:[{type:"text",text:"Project initialization failed multiple times. Please check project configuration and restart the MCP Server."}],isError:!0}):(f.info(`Error check: auto-retrying (${this.initRetryCount}/${ki})`),this.ensureProjectReady(),{content:[{type:"text",text:"Project initialization failed, auto-retrying, please retry in 10 seconds"}],isError:!0})}async callCppCheck(e){if(!this.cppCheckTool){let t=this.config.projectPath?"C++ LSP is not ready, please retry later":"Project path is not configured. Set the PROJECT_PATH parameter or open a project in DevEco Studio.";return f.warn(`C++ check rejected: ${t}, files: ${e.join(", ")}`),{content:[{type:"text",text:t}],isError:!0}}return 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(`
1287
- `);o&&(e.isError?t.push(o):r.push(o))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{f.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool&&(this.cppCheckTool.shutdown().catch(t=>{f.warn("Failed to shutdown CppCheckTool during setProjectPath:",t)}),this.cppCheckTool=null),this.initPromise?(this.needsReinit=!0,f.info("Project path changed while init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{f.warn("Failed to re-init project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new Ng;if(await this.server.connect(e),f.info("devecocli-mcp-server started"),!this.config.debug){let t=Nc();t&&f.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=De(t);r?(f.info(`Detected project path from client root: ${r}`),this.config.projectPath=r):f.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?f.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):f.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{f.warn("Background project init failed:",t)}),this.initializeCppCheck()}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return f.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return f.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){f.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,f.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{f.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{f.error("shutdown failed:",r),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}initializeCppCheck(){let e=this.config.projectPath;if(!e){f.warn("C++ LSP initialization skipped: project path is not configured");return}this.cppCheckTool=new Lt(e,this.toolProvider),f.info("CppCheckTool created (lazy initialization)")}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{f.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?De(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=De(this.originalProjectPath),t&&f.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(this.discoverProject()&&await this.ensureProjectSynced()){this.projectState=3,this.arktsCheckTool=new Nt(this.config.projectPath,this.toolProvider,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{f.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,f.info("Project fully initialized, check tool is available")}catch(e){f.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=ll(e);return t.required?(f.info(`Sync required: ${t.reason}`),this.runSync(e)):(f.info(`Sync skipped: ${t.reason}`),!0)}async runSync(e){this.projectState=2,f.info("Starting project sync...");let t=await Ot.handleSyncProject(e,this.toolProvider);switch(t.status){case"success":return this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,!0;case"skipped":{this.syncSkippedDueToLock=!0,this.syncSkipStartedAt===0&&(this.syncSkipStartedAt=Date.now());let r=Date.now()-this.syncSkipStartedAt,o=Math.round(r/1e3);return r>=dl?(f.error(`Sync skipped for ${o}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(f.warn(`Sync skipped: ${t.reason}, resetting to IDLE for retry (elapsed ${o}s / ${dl/1e3}s)`),this.projectState=0,!1)}case"failed":return f.error(`Project sync failed: ${t.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:{let r=t;return f.error(`Unknown sync result status: ${JSON.stringify(r)}`),this.projectState=5,!1}}}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppCheckTool&&await this.cppCheckTool.shutdown();try{await this.server.close()}catch(e){f.warn("Failed to close MCP server connection:",e)}f.info("devecocli-mcp-server stopped"),Oc(),Rc()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function Lg(n){let e=[],t=[],r=[];for(let o of n)qr.extname(o).toLowerCase()===".ets"?e.push(o):cr(o)?t.push(o):r.push(o);return{etsFiles:e,cppFiles:t,unsupported:r}}function Mi(n){return new zr(n)}async function Hg(){let n=process.env.PROJECT_PATH||"",e=process.env.DEVECO_PATH,t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=process.env.DEBUG==="true"||process.env.DEBUG==="1",o=await _.new(e),s=Mi({toolProvider:o,projectPath:n,nodeMaxOldSpaceSize:t,debug:r}),a=async()=>{await s.shutdown(),process.exit(0)};process.once("SIGINT",a),process.once("SIGTERM",a),process.platform==="win32"&&process.once("SIGBREAK",a);try{await s.start()}catch(c){console.error("Failed to start MCP server:",c),process.exit(1)}}var pl=new _g("serve").description("Host bundled auxiliary protocol servers");pl.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await Hg()});var ml=pl;import{Command as Lw,InvalidArgumentError as vs}from"commander";import{red as So,dim as _w}from"colorette";import*as z from"fs";import*as Bt from"path";import ww from"adm-zip";import bw from"proper-lockfile";import wu from"ora";import*as pe from"fs";import*as In from"path";var ze=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],at={"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 Vr="1.9.1",xk=48*1024*1024,fl=280,hl=6,gl=100,yl=3,vl=28,Ri=10,wl=/API参考|APIReference/i,Sn=200,bl=12,Sl=4,Oi=8,Pl=6,Gr=700,Ni=250,Li=400,El=1320,Il=120,Dl=450,Cl=250,Al=500,Tl=480,xl=80,kl=200,Ml=60,Rl=200,Ol=40,Nl=200,Ll=200,_l=40,_t=500,Hl=Object.fromEntries(ze.map((n,e)=>[at[n],e])),qe=Object.fromEntries(ze.map((n,e)=>[n,e]));import*as $l from"fs";import*as x from"path";import{fileURLToPath as Bl}from"url";import*as Yr from"path";import{homedir as jg}from"os";var Fg="deveco-cli";function Fl(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function $g(){let n=process.env.DEVECO_CLI_DATA_DIR;return n!==void 0&&Fl(n)!==""}function jl(){return Yr.join(jg(),".local","share",Fg)}function Jr(n){let e=Kr();return $g()?[`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 Kr(){let n=process.env.DEVECO_CLI_DATA_DIR;if(n===void 0||n==="")return jl();let e=Fl(n);return e?Yr.resolve(e):jl()}var Bg="docs";function Zr(){return x.join(Kr(),Bg)}function X(){return x.join(Zr(),".index")}function Wl(){return x.join(X(),"build.lock")}function _i(){return x.join(X(),"build-status.json")}function Xr(){return x.join(X(),"build-meta.json")}function Pn(){return x.join(X(),"search.db")}function Ht(){return x.join(X(),".tmp")}function Wg(){return x.join(Kr(),"logs")}function jt(){return x.join(Wg(),"doc-init.log")}function Ug(n,e){let t=e;for(;!t.endsWith(`${x.sep}dist`)&&t!==x.dirname(t);)t=x.dirname(t);return t}function Ul(n,e){return x.dirname(Ug(n,e))}function zg(){let n=Bl(import.meta.url),e=x.dirname(n);return n.includes(`${x.sep}dist${x.sep}`)?Ul(n,e):x.join(e,"..","..","..")}function qg(...n){let e=Bl(import.meta.url),t=x.dirname(e);return e.includes(`${x.sep}dist${x.sep}`)?[x.join(Ul(e,t),...n)]:[x.join(t,"..","..","..",...n)]}function zl(...n){for(let e of qg(...n))if($l.existsSync(e))return e;return null}function Ve(){return zl("docs.zip")}function Hi(){return zl("index.zip")}function ql(){return x.join(zg(),"index","data")}import*as ke from"fs";import*as ct from"path";var lt=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],Qr=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};function Vl(n){return n instanceof Qr}var ji=null;function Fi(n){ji=n}function $i(){if(ji)return ji;let n=X();if(lt.every(o=>ke.existsSync(ct.join(n,o))))return n;let t=ql();if(lt.every(o=>ke.existsSync(ct.join(t,o))))return t;throw new Qr("Lexicon files not found. Install the documentation index first (index.zip).")}function Gl(){$i()}function dt(n){let e=ct.join($i(),n);return ke.readFileSync(e,"utf-8")}function Yl(n,e){return ke.readFileSync(ct.join(e,n),"utf-8")}async function Jl(n,e=$i()){await ke.promises.mkdir(n,{recursive:!0});for(let t of lt){let r=ct.join(e,t),o=ct.join(n,t);await ke.promises.copyFile(r,o)}}import*as eo from"fs";import*as Kl from"path";import*as Zl from"yauzl";var En=null;function Vg(n){return new Promise((e,t)=>{Zl.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 Gg(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function Yg(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",o=>{let i=Gg(o);i.endsWith("/")||e.set(i,o),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function Jg(){En?.zipfile.close(),En=null}async function Kg(n){let e=Kl.resolve(n),t=await eo.promises.stat(e),r=En;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;Jg();let o=await Vg(e),i=await Yg(o);return En={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:o,entries:i,readChain:Promise.resolve()},En}function Zg(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 Xg(n,e){let t=n.readChain,r;n.readChain=new Promise(o=>{r=o}),await t;try{return await Zg(n.zipfile,e)}finally{r()}}function Qg(n){let e=n.replace(/\\/g,"/").replace(/\.md$/,"");return[`docs/${e}.md`,`${e}.md`,`docs/${e}`,e]}function ey(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function Xl(n){let e=Ve();if(!e)throw new Error("docs.zip not found");let t=await Kg(e),r=ey(t.entries,Qg(n));if(!r)throw new Error(`Document not found: ${n}`);return(await Xg(t,r)).toString("utf-8")}function Bi(){let n=Ve();return n!==null&&eo.existsSync(n)}import*as Y from"fs";import*as Ge from"path";import Ql from"adm-zip";var ed=["search.db","build-meta.json",...lt],ty=["corpus.json","corpus-offsets.json","orama.dpack"];async function ny(n){for(let e of ty)await Y.promises.rm(Ge.join(n,e),{force:!0})}async function ry(n){let e=await Y.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await Y.promises.rm(Ge.join(n,t.name),{recursive:!0,force:!0})}function oy(n){let t=new Ql(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 iy(n){let e=X();await Y.promises.mkdir(e,{recursive:!0});for(let t of ed){let r=Ge.join(e,t);await Y.promises.rm(r,{force:!0}),await Y.promises.rename(Ge.join(n,t),r)}await ny(e),await Y.promises.rm(Ht(),{recursive:!0,force:!0})}function Wi(){let n=Hi();return n!==null&&Y.existsSync(n)}async function td(n){let e=Hi();if(!e)throw new Error("index.zip not found");let t=oy(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=Ht();await Y.promises.rm(r,{recursive:!0,force:!0}),await Y.promises.mkdir(r,{recursive:!0});let o=new Ql(e);for(let s of ed){let a=o.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await Y.promises.writeFile(Ge.join(r,s),a.getData())}let i=JSON.parse(await Y.promises.readFile(Ge.join(r,"build-meta.json"),"utf-8"));if(!Y.existsSync(Ge.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await iy(r),await Y.promises.mkdir(Zr(),{recursive:!0}),await ry(Zr()),i}import{createHash as nd}from"crypto";import*as rd from"fs";async function to(n){return new Promise((e,t)=>{let r=nd("sha256"),o=rd.createReadStream(n);o.on("data",i=>r.update(i)),o.on("error",t),o.on("end",()=>e(r.digest("hex")))})}function od(n){return nd("sha256").update(n,"utf8").digest("hex")}var Ui=null;function sy(){let n=dt("harmonyos-synonyms.json");return JSON.parse(n)}function ay(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 cy(){let n=ay(sy()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function ly(){return Ui||(Ui=cy()),Ui}function zi(n,e){let t=ly(),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 id(n,e){let t=e?Yl(n,e):dt(n);return od(t)}function no(n){return id("harmonyos-synonyms.json",n)}function ro(n){return id("harmonyos-terms.txt",n)}var dy={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function oo(){try{let n=await pe.promises.readFile(_i(),"utf-8");return JSON.parse(n)}catch{return{...dy}}}async function qi(n){let e=_i();await pe.promises.mkdir(In.dirname(e),{recursive:!0}),await pe.promises.writeFile(e,JSON.stringify(n,null,2))}function sd(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 Ye(n){let t={...await oo(),...n,updatedAt:Date.now()};return await qi(t),t}async function Vi(){let n=Ve();return n?to(n):null}async function Gi(){try{let n=await pe.promises.readFile(Xr(),"utf-8");return JSON.parse(n)}catch{return null}}async function Yi(n=!1){if(n)return"no-index";let e=await Gi();if(!e||e.segmentCount===0)return"no-index";let t=await Vi();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==Vr?"engine-upgraded":e.termsHash!==ro()?"terms-changed":e.synonymsHash!==no()?"synonyms-changed":null}function Dn(){if(!Bi()||!pe.existsSync(Pn())||!pe.existsSync(Xr()))return!1;let n=In.dirname(Pn());if(!lt.every(e=>pe.existsSync(In.join(n,e))))return!1;try{let e=pe.readFileSync(Xr(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function Ji(n=!1){return n?!0:Bi()?Dn()?await Yi()!==null:!0:!1}async function ad(){let n=await oo();return["installing","indexing","persisting"].includes(n.state)}import*as J from"fs";import*as pu from"os";import*as ne from"path";var cd=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),Ki=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),ld=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"]),dd=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 uy=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,py=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,my=/[A-Z][a-zA-Z0-9]{2,}/g,fy=/@[A-Z][a-zA-Z0-9]*/g,hy=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,ud=6,gy=/^[a-z][a-z0-9]{2,}$/,yy=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,vy=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,wy=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,by=/^[A-Z][a-zA-Z0-9]+$/;function Sy(n){return`"${n.replace(/"/g,'""')}"`}function An(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(Sy).join(` ${e} `)}function Cn(n){return An(n,"OR")}function pd(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?Cn([...t,...r]):`(${Cn(t)}) AND (${Cn(r)})`}function Tn(n){return vy.test(n)}function md(n){return wy.test(n)&&n.length>=ud}function Py(n){return by.test(n)}function xn(n){return Tn(n)||md(n)||Py(n)}function Ey(n){let e=n.trim().toLowerCase();return dd.has(e)?!1:cd.has(e)}function Iy(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function io(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function Zi(n){return[...n.matchAll(uy)].map(e=>e[0])}function Xi(n,e=ud){let t=[];for(let r of n.matchAll(py))r[0].length>=e&&t.push(r[0]);return t}function Ft(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 me(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function Dy(n){let e=new Set;me(e,n);let t=io(n);return t&&me(e,t),Ft([...e])}function so(n){if(Tn(n))return Dy(n);let e=new Set;return me(e,n),Ft([...e])}function ao(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(yy);if(!t)return null;let r=t[1].toLowerCase(),o=t[2].toLowerCase();if(!gy.test(r)||ld.has(r)||!Ey(o))return null;let i=Iy(r,o);return{first:r,second:o,camelCase:i,lower:i.toLowerCase()}}function Qi(n){let e=ao(n.trim());return!e||e.second!=="manager"?null:e}function Cy(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function fd(n){let e=n.trim(),t=Qi(e);if(t&&Ki.has(t.first))return!0;if(md(e)){let r=Cy(e);return r!==null&&Ki.has(r)}return!1}function es(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 ts(n){let e=n.trim();if(xn(e))return so(e);let t=new Set;for(let r of Zi(n)){me(t,r);let o=io(r);o&&me(t,o)}for(let r of Xi(n))me(t,r);for(let r of n.matchAll(fy))t.add(r[0]);for(let r of n.matchAll(hy))t.add(r[0]);for(let r of n.matchAll(my))r[0].length>=4&&t.add(r[0]);return Ft([...t])}function hd(n){let e=n.trim();if(xn(e))return so(e);let t=new Set,r=ao(e);r&&me(t,r.camelCase);for(let o of ts(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 Ft([...t])}function gd(n){return xn(n)}var N={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 yd(n){return N.pureApiSymbol.test(n.trim())}function kn(n){let e=n.trim();return N.stageModelExact.test(e)||N.stageModelEnglishExact.test(e)}function vd(n){let e=[];return kn(n.trim())&&e.push("Stage\u6A21\u578B","Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0"),N.declarePermissionTokens.test(n)&&e.push("\u58F0\u660E\u6743\u9650"),N.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 wd(n){return kn(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var Ay=[{matches:n=>N.uiAbilityLifecycleBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:n=>kn(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!kn(n)&&N.stageModel.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:n=>N.entryAbilityPage.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:n=>N.declarePermissionBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:n=>N.stateDecoratorBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:n=>N.stateManagement.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:n=>N.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=>N.dialogPopupBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function Ty(n,e){for(let{catalog:t,multiplier:r}of e){let o=qe[t];n.set(o,(n.get(o)??1)*r)}}function bd(n,e){for(let t of Ay)t.matches(n)&&Ty(e,t.weights)}function Sd(n,e){if(e!==void 0)return!1;let t=n.trim();return Tn(t)||N.pureApiSymbol.test(t)||fd(t)}function Pd(n){let e=n.trim();if(Tn(e)||N.pureApiSymbol.test(e))return"harmonyos-references";if(kn(e)||N.uiAbilityLifecycleCatalog.test(e)||N.stateDecoratorCatalog.test(e)||N.stateManagement.test(e)||N.declarePermissionCatalog.test(e)||N.stageModelEntryPage.test(e)||N.routerRoute.test(e)||N.dialogPopupExact.test(e))return"harmonyos-guides"}var co=null,rs=null,os=null,Ed=!1,ns=null;function xy(){if(co)return co;let n=dt("harmonyos-stopwords.txt");return co=new Set(n.split(`
1288
- `).map(e=>e.trim()).filter(Boolean)),co}function ky(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 Id(n){let e=xy(),t=[];for(let r of ky(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 My(){let n=await import("jieba-wasm");rs=n.cut,os=n.cut_for_search;let e=dt("harmonyos-terms.txt");n.with_dict(e)}async function Ry(){let{Jieba:n}=await import("@node-rs/jieba"),e=dt("harmonyos-terms.txt"),t=n.withDict(Buffer.from(e,"utf-8"));rs=t.cut.bind(t),os=t.cutForSearch.bind(t)}async function Je(){Ed||(ns||(ns=(D()?My():Ry()).then(()=>{Ed=!0})),await ns)}async function Oy(n){return await Je(),Id(os(n,!0))}async function Dd(n){return await Je(),Id(rs(n,!0))}async function lo(n,e){let t=n.trim();if(!t||e<=0)return"";let r=(await Oy(t)).join(" ");return r.length<=e?r:r.slice(0,e)}async function Ny(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 uo(n){let e=!!n.sectionTitle.trim(),t=n.titleTokens.trim(),r=e?Tl:El,o=e?kl:Dl,i=e?await Ny(n.apiSymbols,o):await lo(n.apiSymbols.join(" "),o),a=(await Promise.all([lo(t,e?xl:Il),Promise.resolve(i),lo(n.headingsText,e?Ml:Cl),lo(n.bodySample,e?Rl:Al)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}function Ly(n){return n.join(" ").replace(/\s+/g," ").trim().slice(0,Sn)}function is(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>=bl))break}return r}function _y(n){return n.length>=2&&n.length<=Sl}function Hy(n,e){let t=zi(n,Oi),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=is(o,i);return{rawQuery:n,expandedQuery:t,tokens:s,preferAnd:!1,ftsMatch:pd(o,i)}}function jy(n,e){let t=is(so(e),[]);return{rawQuery:n,expandedQuery:n,tokens:t,preferAnd:!1,ftsMatch:Cn(t)}}async function Cd(n){let e=Ly(n),t=e.trim(),r=wd(t);if(r)return{rawQuery:e,expandedQuery:r.expandedQuery,tokens:r.tokens,preferAnd:!1};let o=ao(t);if(o)return Hy(e,o);if(xn(t))return jy(e,t);let i=vd(e),s=[...ts(e),...i],c=gd(t)?e:zi(e,Oi),l=await Dd(c),u=is(s,l);return{rawQuery:e,expandedQuery:c,tokens:u,preferAnd:i.length===0&&_y(u)}}var Ad=["harmonyos-releases","harmonyos-roadmap"],Fy=new Set(Ad.map(n=>qe[n])),$y=Ad.map(n=>`${at[n]}/`);function By(n){return Fy.has(n)}function Wy(n){return $y.some(e=>n.startsWith(e))}function Td(n){let e=[],t=[];for(let r of n)By(r.catalog_id)?t.push(r):e.push(r);return[...e,...t]}function xd(n){let e=[],t=[];for(let r of n)Wy(r.documentId)?t.push(r):e.push(r);return[...e,...t]}var Uy=[{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 Mn(n,e,t){let r=qe[e];n.set(r,(n.get(r)??1)*t)}function zy(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)){Mn(e,"harmonyos-guides",1.45),Mn(e,"harmonyos-references",1.35);return}(o||i)&&Mn(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(t)&&Mn(e,"harmonyos-references",1.75)}function kd(n){let e=new Map,t=n.trim();if(!t)return e;let r=yd(t);zy(t,e),bd(t,e);for(let o of Uy)o.pattern.test(t)&&(o.skipForPureApiSymbol&&r||Mn(e,o.catalog,o.multiplier));return e}function Md(n){return Pd(n)}var qy=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function Rd(n,e){let t=-1;for(let r of qy){let o=n.lastIndexOf(r);o>t&&(t=o)}return t>=e?t:-1}function Od(n,e){let t=n.trim();if(t.length<=e)return{text:t,excerptTruncated:!1};let r=t.slice(0,e),o=Rd(r,e-20),i=o>=0?o:e;return{text:t.slice(0,i).trimEnd(),excerptTruncated:!0}}function Nd(n,e,t={}){let{maxLen:r=Ll,contextChars:o=_l,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(Me=>Me.trim()).filter(Boolean),c=0;for(let Me of a){let ut=s.toLowerCase().indexOf(Me.toLowerCase());if(ut>=0){c=ut;break}}let l=Math.max(0,c-o),u=Math.min(s.length,l+r),h=s.slice(l,u),v=Rd(h,r-25);v>=0&&(u=l+v);let I=s.slice(l,u).trim(),k=l>0?"...":"",ee=u<s.length||i?"...":"";return`${k}${I}${ee}`}var Vy=`
1286
+ `);o&&(e.isError?t.push(o):r.push(o))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{f.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool&&(this.cppCheckTool.shutdown().catch(t=>{f.warn("Failed to shutdown CppCheckTool during setProjectPath:",t)}),this.cppCheckTool=null),this.initPromise?(this.needsReinit=!0,f.info("Project path changed while init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{f.warn("Failed to re-init project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new Ng;if(await this.server.connect(e),f.info("devecocli-mcp-server started"),!this.config.debug){let t=Nc();t&&f.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=De(t);r?(f.info(`Detected project path from client root: ${r}`),this.config.projectPath=r):f.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?f.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):f.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{f.warn("Background project init failed:",t)}),this.initializeCppCheck()}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return f.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return f.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){f.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,f.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{f.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{f.error("shutdown failed:",r),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}initializeCppCheck(){let e=this.config.projectPath;if(!e){f.warn("C++ LSP initialization skipped: project path is not configured");return}this.cppCheckTool=new Lt(e,this.toolProvider),f.info("CppCheckTool created (lazy initialization)")}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{f.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?De(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=De(this.originalProjectPath),t&&f.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(this.discoverProject()&&await this.ensureProjectSynced()){this.projectState=3,this.arktsCheckTool=new Nt(this.config.projectPath,this.toolProvider,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{f.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,f.info("Project fully initialized, check tool is available")}catch(e){f.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=ll(e),r=!t.required;return f.info(`Sync check: skipHvigor=${r}, reason=${t.reason}`),this.runSync(e,{skipHvigorSync:r})}async runSync(e,t){this.projectState=2,f.info("Starting project sync...");let r=await Ot.handleSyncProject(e,this.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>=dl?(f.error(`Sync skipped for ${i}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(f.warn(`Sync skipped: ${r.reason}, resetting to IDLE for retry (elapsed ${i}s / ${dl/1e3}s)`),this.projectState=0,!1)}case"failed":return f.error(`Project sync failed: ${r.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:{let o=r;return f.error(`Unknown sync result status: ${JSON.stringify(o)}`),this.projectState=5,!1}}}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppCheckTool&&await this.cppCheckTool.shutdown();try{await this.server.close()}catch(e){f.warn("Failed to close MCP server connection:",e)}f.info("devecocli-mcp-server stopped"),Oc(),Rc()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function Lg(n){let e=[],t=[],r=[];for(let o of n)qr.extname(o).toLowerCase()===".ets"?e.push(o):cr(o)?t.push(o):r.push(o);return{etsFiles:e,cppFiles:t,unsupported:r}}function Mi(n){return new zr(n)}async function Hg(){let n=process.env.PROJECT_PATH||"",e=process.env.DEVECO_PATH,t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=process.env.DEBUG==="true"||process.env.DEBUG==="1",o=await _.new(e),s=Mi({toolProvider:o,projectPath:n,nodeMaxOldSpaceSize:t,debug:r}),a=async()=>{await s.shutdown(),process.exit(0)};process.once("SIGINT",a),process.once("SIGTERM",a),process.platform==="win32"&&process.once("SIGBREAK",a);try{await s.start()}catch(c){console.error("Failed to start MCP server:",c),process.exit(1)}}var pl=new _g("serve").description("Host bundled auxiliary protocol servers");pl.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await Hg()});var ml=pl;import{Command as Lw,InvalidArgumentError as vs}from"commander";import{red as So,dim as _w}from"colorette";import*as z from"fs";import*as Bt from"path";import ww from"adm-zip";import bw from"proper-lockfile";import wu from"ora";import*as pe from"fs";import*as In from"path";var ze=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],at={"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 Vr="1.9.1",xk=48*1024*1024,fl=280,hl=6,gl=100,yl=3,vl=28,Ri=10,wl=/API参考|APIReference/i,Sn=200,bl=12,Sl=4,Oi=8,Pl=6,Gr=700,Ni=250,Li=400,El=1320,Il=120,Dl=450,Cl=250,Al=500,Tl=480,xl=80,kl=200,Ml=60,Rl=200,Ol=40,Nl=200,Ll=200,_l=40,_t=500,Hl=Object.fromEntries(ze.map((n,e)=>[at[n],e])),qe=Object.fromEntries(ze.map((n,e)=>[n,e]));import*as $l from"fs";import*as x from"path";import{fileURLToPath as Bl}from"url";import*as Yr from"path";import{homedir as jg}from"os";var Fg="deveco-cli";function Fl(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function $g(){let n=process.env.DEVECO_CLI_DATA_DIR;return n!==void 0&&Fl(n)!==""}function jl(){return Yr.join(jg(),".local","share",Fg)}function Jr(n){let e=Kr();return $g()?[`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 Kr(){let n=process.env.DEVECO_CLI_DATA_DIR;if(n===void 0||n==="")return jl();let e=Fl(n);return e?Yr.resolve(e):jl()}var Bg="docs";function Zr(){return x.join(Kr(),Bg)}function X(){return x.join(Zr(),".index")}function Wl(){return x.join(X(),"build.lock")}function _i(){return x.join(X(),"build-status.json")}function Xr(){return x.join(X(),"build-meta.json")}function Pn(){return x.join(X(),"search.db")}function Ht(){return x.join(X(),".tmp")}function Wg(){return x.join(Kr(),"logs")}function jt(){return x.join(Wg(),"doc-init.log")}function Ug(n,e){let t=e;for(;!t.endsWith(`${x.sep}dist`)&&t!==x.dirname(t);)t=x.dirname(t);return t}function Ul(n,e){return x.dirname(Ug(n,e))}function zg(){let n=Bl(import.meta.url),e=x.dirname(n);return n.includes(`${x.sep}dist${x.sep}`)?Ul(n,e):x.join(e,"..","..","..")}function qg(...n){let e=Bl(import.meta.url),t=x.dirname(e);return e.includes(`${x.sep}dist${x.sep}`)?[x.join(Ul(e,t),...n)]:[x.join(t,"..","..","..",...n)]}function zl(...n){for(let e of qg(...n))if($l.existsSync(e))return e;return null}function Ve(){return zl("docs.zip")}function Hi(){return zl("index.zip")}function ql(){return x.join(zg(),"index","data")}import*as ke from"fs";import*as ct from"path";var lt=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],Qr=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};function Vl(n){return n instanceof Qr}var ji=null;function Fi(n){ji=n}function $i(){if(ji)return ji;let n=X();if(lt.every(o=>ke.existsSync(ct.join(n,o))))return n;let t=ql();if(lt.every(o=>ke.existsSync(ct.join(t,o))))return t;throw new Qr("Lexicon files not found. Install the documentation index first (index.zip).")}function Gl(){$i()}function dt(n){let e=ct.join($i(),n);return ke.readFileSync(e,"utf-8")}function Yl(n,e){return ke.readFileSync(ct.join(e,n),"utf-8")}async function Jl(n,e=$i()){await ke.promises.mkdir(n,{recursive:!0});for(let t of lt){let r=ct.join(e,t),o=ct.join(n,t);await ke.promises.copyFile(r,o)}}import*as eo from"fs";import*as Kl from"path";import*as Zl from"yauzl";var En=null;function Vg(n){return new Promise((e,t)=>{Zl.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 Gg(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function Yg(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",o=>{let i=Gg(o);i.endsWith("/")||e.set(i,o),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function Jg(){En?.zipfile.close(),En=null}async function Kg(n){let e=Kl.resolve(n),t=await eo.promises.stat(e),r=En;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;Jg();let o=await Vg(e),i=await Yg(o);return En={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:o,entries:i,readChain:Promise.resolve()},En}function Zg(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 Xg(n,e){let t=n.readChain,r;n.readChain=new Promise(o=>{r=o}),await t;try{return await Zg(n.zipfile,e)}finally{r()}}function Qg(n){let e=n.replace(/\\/g,"/").replace(/\.md$/,"");return[`docs/${e}.md`,`${e}.md`,`docs/${e}`,e]}function ey(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function Xl(n){let e=Ve();if(!e)throw new Error("docs.zip not found");let t=await Kg(e),r=ey(t.entries,Qg(n));if(!r)throw new Error(`Document not found: ${n}`);return(await Xg(t,r)).toString("utf-8")}function Bi(){let n=Ve();return n!==null&&eo.existsSync(n)}import*as Y from"fs";import*as Ge from"path";import Ql from"adm-zip";var ed=["search.db","build-meta.json",...lt],ty=["corpus.json","corpus-offsets.json","orama.dpack"];async function ny(n){for(let e of ty)await Y.promises.rm(Ge.join(n,e),{force:!0})}async function ry(n){let e=await Y.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await Y.promises.rm(Ge.join(n,t.name),{recursive:!0,force:!0})}function oy(n){let t=new Ql(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 iy(n){let e=X();await Y.promises.mkdir(e,{recursive:!0});for(let t of ed){let r=Ge.join(e,t);await Y.promises.rm(r,{force:!0}),await Y.promises.rename(Ge.join(n,t),r)}await ny(e),await Y.promises.rm(Ht(),{recursive:!0,force:!0})}function Wi(){let n=Hi();return n!==null&&Y.existsSync(n)}async function td(n){let e=Hi();if(!e)throw new Error("index.zip not found");let t=oy(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=Ht();await Y.promises.rm(r,{recursive:!0,force:!0}),await Y.promises.mkdir(r,{recursive:!0});let o=new Ql(e);for(let s of ed){let a=o.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await Y.promises.writeFile(Ge.join(r,s),a.getData())}let i=JSON.parse(await Y.promises.readFile(Ge.join(r,"build-meta.json"),"utf-8"));if(!Y.existsSync(Ge.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await iy(r),await Y.promises.mkdir(Zr(),{recursive:!0}),await ry(Zr()),i}import{createHash as nd}from"crypto";import*as rd from"fs";async function to(n){return new Promise((e,t)=>{let r=nd("sha256"),o=rd.createReadStream(n);o.on("data",i=>r.update(i)),o.on("error",t),o.on("end",()=>e(r.digest("hex")))})}function od(n){return nd("sha256").update(n,"utf8").digest("hex")}var Ui=null;function sy(){let n=dt("harmonyos-synonyms.json");return JSON.parse(n)}function ay(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 cy(){let n=ay(sy()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function ly(){return Ui||(Ui=cy()),Ui}function zi(n,e){let t=ly(),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 id(n,e){let t=e?Yl(n,e):dt(n);return od(t)}function no(n){return id("harmonyos-synonyms.json",n)}function ro(n){return id("harmonyos-terms.txt",n)}var dy={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function oo(){try{let n=await pe.promises.readFile(_i(),"utf-8");return JSON.parse(n)}catch{return{...dy}}}async function qi(n){let e=_i();await pe.promises.mkdir(In.dirname(e),{recursive:!0}),await pe.promises.writeFile(e,JSON.stringify(n,null,2))}function sd(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 Ye(n){let t={...await oo(),...n,updatedAt:Date.now()};return await qi(t),t}async function Vi(){let n=Ve();return n?to(n):null}async function Gi(){try{let n=await pe.promises.readFile(Xr(),"utf-8");return JSON.parse(n)}catch{return null}}async function Yi(n=!1){if(n)return"no-index";let e=await Gi();if(!e||e.segmentCount===0)return"no-index";let t=await Vi();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==Vr?"engine-upgraded":e.termsHash!==ro()?"terms-changed":e.synonymsHash!==no()?"synonyms-changed":null}function Dn(){if(!Bi()||!pe.existsSync(Pn())||!pe.existsSync(Xr()))return!1;let n=In.dirname(Pn());if(!lt.every(e=>pe.existsSync(In.join(n,e))))return!1;try{let e=pe.readFileSync(Xr(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function Ji(n=!1){return n?!0:Bi()?Dn()?await Yi()!==null:!0:!1}async function ad(){let n=await oo();return["installing","indexing","persisting"].includes(n.state)}import*as J from"fs";import*as pu from"os";import*as ne from"path";var cd=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),Ki=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),ld=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"]),dd=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 uy=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,py=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,my=/[A-Z][a-zA-Z0-9]{2,}/g,fy=/@[A-Z][a-zA-Z0-9]*/g,hy=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,ud=6,gy=/^[a-z][a-z0-9]{2,}$/,yy=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,vy=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,wy=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,by=/^[A-Z][a-zA-Z0-9]+$/;function Sy(n){return`"${n.replace(/"/g,'""')}"`}function An(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(Sy).join(` ${e} `)}function Cn(n){return An(n,"OR")}function pd(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?Cn([...t,...r]):`(${Cn(t)}) AND (${Cn(r)})`}function Tn(n){return vy.test(n)}function md(n){return wy.test(n)&&n.length>=ud}function Py(n){return by.test(n)}function xn(n){return Tn(n)||md(n)||Py(n)}function Ey(n){let e=n.trim().toLowerCase();return dd.has(e)?!1:cd.has(e)}function Iy(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function io(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function Zi(n){return[...n.matchAll(uy)].map(e=>e[0])}function Xi(n,e=ud){let t=[];for(let r of n.matchAll(py))r[0].length>=e&&t.push(r[0]);return t}function Ft(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 me(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function Dy(n){let e=new Set;me(e,n);let t=io(n);return t&&me(e,t),Ft([...e])}function so(n){if(Tn(n))return Dy(n);let e=new Set;return me(e,n),Ft([...e])}function ao(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(yy);if(!t)return null;let r=t[1].toLowerCase(),o=t[2].toLowerCase();if(!gy.test(r)||ld.has(r)||!Ey(o))return null;let i=Iy(r,o);return{first:r,second:o,camelCase:i,lower:i.toLowerCase()}}function Qi(n){let e=ao(n.trim());return!e||e.second!=="manager"?null:e}function Cy(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function fd(n){let e=n.trim(),t=Qi(e);if(t&&Ki.has(t.first))return!0;if(md(e)){let r=Cy(e);return r!==null&&Ki.has(r)}return!1}function es(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 ts(n){let e=n.trim();if(xn(e))return so(e);let t=new Set;for(let r of Zi(n)){me(t,r);let o=io(r);o&&me(t,o)}for(let r of Xi(n))me(t,r);for(let r of n.matchAll(fy))t.add(r[0]);for(let r of n.matchAll(hy))t.add(r[0]);for(let r of n.matchAll(my))r[0].length>=4&&t.add(r[0]);return Ft([...t])}function hd(n){let e=n.trim();if(xn(e))return so(e);let t=new Set,r=ao(e);r&&me(t,r.camelCase);for(let o of ts(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 Ft([...t])}function gd(n){return xn(n)}var N={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 yd(n){return N.pureApiSymbol.test(n.trim())}function kn(n){let e=n.trim();return N.stageModelExact.test(e)||N.stageModelEnglishExact.test(e)}function vd(n){let e=[];return kn(n.trim())&&e.push("Stage\u6A21\u578B","Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0"),N.declarePermissionTokens.test(n)&&e.push("\u58F0\u660E\u6743\u9650"),N.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 wd(n){return kn(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var Ay=[{matches:n=>N.uiAbilityLifecycleBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:n=>kn(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!kn(n)&&N.stageModel.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:n=>N.entryAbilityPage.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:n=>N.declarePermissionBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:n=>N.stateDecoratorBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:n=>N.stateManagement.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:n=>N.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=>N.dialogPopupBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function Ty(n,e){for(let{catalog:t,multiplier:r}of e){let o=qe[t];n.set(o,(n.get(o)??1)*r)}}function bd(n,e){for(let t of Ay)t.matches(n)&&Ty(e,t.weights)}function Sd(n,e){if(e!==void 0)return!1;let t=n.trim();return Tn(t)||N.pureApiSymbol.test(t)||fd(t)}function Pd(n){let e=n.trim();if(Tn(e)||N.pureApiSymbol.test(e))return"harmonyos-references";if(kn(e)||N.uiAbilityLifecycleCatalog.test(e)||N.stateDecoratorCatalog.test(e)||N.stateManagement.test(e)||N.declarePermissionCatalog.test(e)||N.stageModelEntryPage.test(e)||N.routerRoute.test(e)||N.dialogPopupExact.test(e))return"harmonyos-guides"}var co=null,rs=null,os=null,Ed=!1,ns=null;function xy(){if(co)return co;let n=dt("harmonyos-stopwords.txt");return co=new Set(n.split(`
1287
+ `).map(e=>e.trim()).filter(Boolean)),co}function ky(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 Id(n){let e=xy(),t=[];for(let r of ky(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 My(){let n=await import("jieba-wasm");rs=n.cut,os=n.cut_for_search;let e=dt("harmonyos-terms.txt");n.with_dict(e)}async function Ry(){let{Jieba:n}=await import("@node-rs/jieba"),{dict:e}=await import("@node-rs/jieba/dict.js"),t=n.withDict(e),r=dt("harmonyos-terms.txt");t.loadDict(Buffer.from(r,"utf-8")),rs=t.cut.bind(t),os=t.cutForSearch.bind(t)}async function Je(){Ed||(ns||(ns=(D()?My():Ry()).then(()=>{Ed=!0})),await ns)}async function Oy(n){return await Je(),Id(os(n,!0))}async function Dd(n){return await Je(),Id(rs(n,!0))}async function lo(n,e){let t=n.trim();if(!t||e<=0)return"";let r=(await Oy(t)).join(" ");return r.length<=e?r:r.slice(0,e)}async function Ny(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 uo(n){let e=!!n.sectionTitle.trim(),t=n.titleTokens.trim(),r=e?Tl:El,o=e?kl:Dl,i=e?await Ny(n.apiSymbols,o):await lo(n.apiSymbols.join(" "),o),a=(await Promise.all([lo(t,e?xl:Il),Promise.resolve(i),lo(n.headingsText,e?Ml:Cl),lo(n.bodySample,e?Rl:Al)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}function Ly(n){return n.join(" ").replace(/\s+/g," ").trim().slice(0,Sn)}function is(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>=bl))break}return r}function _y(n){return n.length>=2&&n.length<=Sl}function Hy(n,e){let t=zi(n,Oi),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=is(o,i);return{rawQuery:n,expandedQuery:t,tokens:s,preferAnd:!1,ftsMatch:pd(o,i)}}function jy(n,e){let t=is(so(e),[]);return{rawQuery:n,expandedQuery:n,tokens:t,preferAnd:!1,ftsMatch:Cn(t)}}async function Cd(n){let e=Ly(n),t=e.trim(),r=wd(t);if(r)return{rawQuery:e,expandedQuery:r.expandedQuery,tokens:r.tokens,preferAnd:!1};let o=ao(t);if(o)return Hy(e,o);if(xn(t))return jy(e,t);let i=vd(e),s=[...ts(e),...i],c=gd(t)?e:zi(e,Oi),l=await Dd(c),u=is(s,l);return{rawQuery:e,expandedQuery:c,tokens:u,preferAnd:i.length===0&&_y(u)}}var Ad=["harmonyos-releases","harmonyos-roadmap"],Fy=new Set(Ad.map(n=>qe[n])),$y=Ad.map(n=>`${at[n]}/`);function By(n){return Fy.has(n)}function Wy(n){return $y.some(e=>n.startsWith(e))}function Td(n){let e=[],t=[];for(let r of n)By(r.catalog_id)?t.push(r):e.push(r);return[...e,...t]}function xd(n){let e=[],t=[];for(let r of n)Wy(r.documentId)?t.push(r):e.push(r);return[...e,...t]}var Uy=[{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 Mn(n,e,t){let r=qe[e];n.set(r,(n.get(r)??1)*t)}function zy(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)){Mn(e,"harmonyos-guides",1.45),Mn(e,"harmonyos-references",1.35);return}(o||i)&&Mn(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(t)&&Mn(e,"harmonyos-references",1.75)}function kd(n){let e=new Map,t=n.trim();if(!t)return e;let r=yd(t);zy(t,e),bd(t,e);for(let o of Uy)o.pattern.test(t)&&(o.skipForPureApiSymbol&&r||Mn(e,o.catalog,o.multiplier));return e}function Md(n){return Pd(n)}var qy=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function Rd(n,e){let t=-1;for(let r of qy){let o=n.lastIndexOf(r);o>t&&(t=o)}return t>=e?t:-1}function Od(n,e){let t=n.trim();if(t.length<=e)return{text:t,excerptTruncated:!1};let r=t.slice(0,e),o=Rd(r,e-20),i=o>=0?o:e;return{text:t.slice(0,i).trimEnd(),excerptTruncated:!0}}function Nd(n,e,t={}){let{maxLen:r=Ll,contextChars:o=_l,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(Me=>Me.trim()).filter(Boolean),c=0;for(let Me of a){let ut=s.toLowerCase().indexOf(Me.toLowerCase());if(ut>=0){c=ut;break}}let l=Math.max(0,c-o),u=Math.min(s.length,l+r),h=s.slice(l,u),v=Rd(h,r-25);v>=0&&(u=l+v);let I=s.slice(l,u).trim(),k=l>0?"...":"",ee=u<s.length||i?"...":"";return`${k}${I}${ee}`}var Vy=`
1289
1288
  SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
1290
1289
  d.catalog_id, bm25(segments_fts) AS bm25
1291
1290
  FROM segments_fts
@@ -1355,4 +1354,4 @@ CREATE INDEX segments_doc_id_idx ON segments(doc_id);
1355
1354
  Detail: ${n.message}`):n}try{await Je()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Ln(`${yw()}
1356
1355
 
1357
1356
  Detail: ${e}`)}try{await Rn()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Ln(vw(e))}}var fs=class extends Error{constructor(t,r){super(r);this.code=t;this.name="DocNotReadyError"}code};function Sw(n){return new Promise(e=>setTimeout(e,n))}async function Pw(n){let e=jt();await z.promises.mkdir(Bt.dirname(e),{recursive:!0}),await z.promises.appendFile(e,`${new Date().toISOString()} ${n}
1358
- `)}async function Ew(n){let e=Ve();if(!e)throw new Error("docs.zip not found");await z.promises.rm(n,{recursive:!0,force:!0}),await z.promises.mkdir(n,{recursive:!0}),new ww(e).extractAllTo(n,!0),await hu(n)}async function Iw(){let n=X(),e=Ht(),t=await z.promises.readdir(e);for(let r of t){let o=Bt.join(n,r);await z.promises.rm(o,{force:!0}),await z.promises.rename(Bt.join(e,r),o)}await z.promises.rm(e,{recursive:!0,force:!0}),await z.promises.rm(Bt.join(n,"orama.dpack"),{force:!0})}async function Dw(n,e){e?.start("Installing documentation index\u2026"),await Ye({state:"installing",phase:1,phaseLabel:"Installing index",message:"Installing documentation index\u2026"}),await td(n),e&&(e.text="Documentation index installed.")}async function Cw(n,e,t){let r=Ht(),o=await fu();await z.promises.mkdir(X(),{recursive:!0}),await z.promises.rm(r,{recursive:!0,force:!0}),t?.start("Building search index\u2026"),await Ye({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"});try{await Ew(o),await mu({docsDir:o,tmpDir:r,docsZipSha256:e,termsHash:ro(),synonymsHash:no(),builtBy:n.builtBy??"doc-init",onProgress:async i=>{t&&(t.text=i.message),await Ye({state:"indexing",current:i.current,total:i.total,message:i.message})}})}finally{await z.promises.rm(o,{recursive:!0,force:!0})}await Ye({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await Iw(),Wd()}async function yu(n){await Ye({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function Aw(n){let e=await Gi(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";n?.succeed(t),await Ye({state:"done",message:t,error:null})}async function Tw(n,e){let t=n instanceof Error?n.message:String(n);throw await Ye({state:"error",error:t}),await Pw(`ERROR: ${t}`),e?.fail(t),n}async function xw(){let n=X();await z.promises.mkdir(n,{recursive:!0});let e=Wl();return z.existsSync(e)||await z.promises.writeFile(e,"","utf-8"),e}async function kw(){let n=await xw();return bw.lock(n,{stale:1800*1e3})}async function Mw(){let n=Ve(),e=(n?await to(n):null)??await Vi();if(!e)throw new Error("docs.zip not found");return e}async function Rw(n,e){let t=await Mw(),r=n.force||await Ji(n.force),o=await Yi(n.force);if(!r&&!o&&Dn()){await Aw(e);return}if(Wi()&&!n.force){await Dw(t,e),await yu(e);return}await Cw(n,t,e),await yu(e)}var hs=class{static async run(e={}){let t=e.background??!1,o=e.quiet??t?void 0:wu({text:"Checking documentation\u2026",color:"cyan"}),i;try{i=await kw(),await qi(sd("Starting documentation setup\u2026")),await Rw(e,o)}catch(s){return Tw(s,o)}finally{i&&await i()}}};async function Ow(n){for(;;){let e=await oo();if(e.state==="done"&&Dn())return;if(e.state==="error")throw new fs("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 Sw(500)}}async function vu(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await hs.run({builtBy:"doc-init",force:e,quiet:!0})}async function Nw(){if(Dn())return;let n=wu({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await ad()){await Ow(n),n.succeed("Documentation ready.");return}if(await Ji()){await vu(n),n.succeed("Documentation ready.");return}await vu(n,!0),n.succeed("Documentation ready.")}catch(e){throw n.fail(e.message),e}}async function _n(){await Nw(),await gu()}var gs=class{async search(e,t,r=20){return await _n(),qd(e,t,r)}async readDocument(e){return await _n(),Xl(e)}},ys=new gs;function bu(...n){return e=>{if(!n.includes(e))throw new vs(`Allowed values: ${n.join(", ")}`);return e}}function Hw(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new vs("Must be a positive integer.");return e}var jw=bu("json","default"),Fw=bu("json","default"),Po=new Lw("docs").description("Search and read HarmonyOS documentation from local docs directory");Po.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",Bw,"all").option("--format <fmt>","Output format (default, json)",jw,"default").option("--limit <n>","Max number of results",Hw,20).action(async(n,e)=>{try{let t=$w(n),r=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=await ys.search(t,r,e.limit);e.format==="json"?console.log(JSON.stringify(o,null,2)):Ww(o)}catch(t){console.error(So(t.message)),process.exit(1)}});Po.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{try{let e=n.trim();e||(console.error(So("Document ID cannot be empty.")),process.exit(1));let t=await ys.readDocument(e);console.log(t)}catch(e){console.error(So(e.message)),process.exit(1)}});Po.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",Fw,"default").action(async n=>{try{if(await _n(),n.format==="json"){let e=ze.map(t=>({name:t,title:at[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of ze)console.log(` ${e.padEnd(20)} ${_w(at[e])}`)}catch(e){console.error(So(e.message)),process.exit(1)}});function $w(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>Sn)throw new Error(`Query exceeds ${Sn} characters.`);return e}function Bw(n){if(n==="all")return"all";if(!ze.includes(n))throw new vs(`Invalid catalog "${n}". Allowed: all, ${ze.join(", ")}`);return n}function Ww(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 Su=Po;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";Uw();Q.name("devecocli").description("HarmonyOS application development command line tool").version("0.1.0-TD.5");Q.addCommand(_s);Q.addCommand(Js);Q.addCommand(Qs);Q.addCommand(ua);D()||Q.addCommand(Ra);Q.addCommand(rc);Q.addCommand(cc);Q.addCommand(yc);Q.addCommand(Dc);Q.addCommand(ml);Q.addCommand(Su);var ws=process.argv.slice(2);ws.length>=2&&ws[ws.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var qw=new Set(["update"]);Q.hook("preAction",async(n,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==Q;)t=t.parent;qw.has(t.name())||await _.checkVersion()});Q.parseAsync(process.argv).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(zw(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
1357
+ `)}async function Ew(n){let e=Ve();if(!e)throw new Error("docs.zip not found");await z.promises.rm(n,{recursive:!0,force:!0}),await z.promises.mkdir(n,{recursive:!0}),new ww(e).extractAllTo(n,!0),await hu(n)}async function Iw(){let n=X(),e=Ht(),t=await z.promises.readdir(e);for(let r of t){let o=Bt.join(n,r);await z.promises.rm(o,{force:!0}),await z.promises.rename(Bt.join(e,r),o)}await z.promises.rm(e,{recursive:!0,force:!0}),await z.promises.rm(Bt.join(n,"orama.dpack"),{force:!0})}async function Dw(n,e){e?.start("Installing documentation index\u2026"),await Ye({state:"installing",phase:1,phaseLabel:"Installing index",message:"Installing documentation index\u2026"}),await td(n),e&&(e.text="Documentation index installed.")}async function Cw(n,e,t){let r=Ht(),o=await fu();await z.promises.mkdir(X(),{recursive:!0}),await z.promises.rm(r,{recursive:!0,force:!0}),t?.start("Building search index\u2026"),await Ye({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"});try{await Ew(o),await mu({docsDir:o,tmpDir:r,docsZipSha256:e,termsHash:ro(),synonymsHash:no(),builtBy:n.builtBy??"doc-init",onProgress:async i=>{t&&(t.text=i.message),await Ye({state:"indexing",current:i.current,total:i.total,message:i.message})}})}finally{await z.promises.rm(o,{recursive:!0,force:!0})}await Ye({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await Iw(),Wd()}async function yu(n){await Ye({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function Aw(n){let e=await Gi(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";n?.succeed(t),await Ye({state:"done",message:t,error:null})}async function Tw(n,e){let t=n instanceof Error?n.message:String(n);throw await Ye({state:"error",error:t}),await Pw(`ERROR: ${t}`),e?.fail(t),n}async function xw(){let n=X();await z.promises.mkdir(n,{recursive:!0});let e=Wl();return z.existsSync(e)||await z.promises.writeFile(e,"","utf-8"),e}async function kw(){let n=await xw();return bw.lock(n,{stale:1800*1e3})}async function Mw(){let n=Ve(),e=(n?await to(n):null)??await Vi();if(!e)throw new Error("docs.zip not found");return e}async function Rw(n,e){let t=await Mw(),r=n.force||await Ji(n.force),o=await Yi(n.force);if(!r&&!o&&Dn()){await Aw(e);return}if(Wi()&&!n.force){await Dw(t,e),await yu(e);return}await Cw(n,t,e),await yu(e)}var hs=class{static async run(e={}){let t=e.background??!1,o=e.quiet??t?void 0:wu({text:"Checking documentation\u2026",color:"cyan"}),i;try{i=await kw(),await qi(sd("Starting documentation setup\u2026")),await Rw(e,o)}catch(s){await Tw(s,o)}finally{i&&await i()}}};async function Ow(n){for(;;){let e=await oo();if(e.state==="done"&&Dn())return;if(e.state==="error")throw new fs("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 Sw(500)}}async function vu(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await hs.run({builtBy:"doc-init",force:e,quiet:!0})}async function Nw(){if(Dn())return;let n=wu({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await ad()){await Ow(n),n.succeed("Documentation ready.");return}if(await Ji()){await vu(n),n.succeed("Documentation ready.");return}await vu(n,!0),n.succeed("Documentation ready.")}catch(e){throw n.fail(e.message),e}}async function _n(){await Nw(),await gu()}var gs=class{async search(e,t,r=20){return await _n(),qd(e,t,r)}async readDocument(e){return await _n(),Xl(e)}},ys=new gs;function bu(...n){return e=>{if(!n.includes(e))throw new vs(`Allowed values: ${n.join(", ")}`);return e}}function Hw(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new vs("Must be a positive integer.");return e}var jw=bu("json","default"),Fw=bu("json","default"),Po=new Lw("docs").description("Search and read HarmonyOS documentation from local docs directory");Po.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",Bw,"all").option("--format <fmt>","Output format (default, json)",jw,"default").option("--limit <n>","Max number of results",Hw,20).action(async(n,e)=>{try{let t=$w(n),r=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=await ys.search(t,r,e.limit);e.format==="json"?console.log(JSON.stringify(o,null,2)):Ww(o)}catch(t){console.error(So(t.message)),process.exit(1)}});Po.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{try{let e=n.trim();e||(console.error(So("Document ID cannot be empty.")),process.exit(1));let t=await ys.readDocument(e);console.log(t)}catch(e){console.error(So(e.message)),process.exit(1)}});Po.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",Fw,"default").action(async n=>{try{if(await _n(),n.format==="json"){let e=ze.map(t=>({name:t,title:at[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of ze)console.log(` ${e.padEnd(20)} ${_w(at[e])}`)}catch(e){console.error(So(e.message)),process.exit(1)}});function $w(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>Sn)throw new Error(`Query exceeds ${Sn} characters.`);return e}function Bw(n){if(n==="all")return"all";if(!ze.includes(n))throw new vs(`Invalid catalog "${n}". Allowed: all, ${ze.join(", ")}`);return n}function Ww(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 Su=Po;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";Uw();Q.name("devecocli").description("HarmonyOS application development command line tool").version("0.1.0-TD.5.1");Q.addCommand(_s);Q.addCommand(Js);Q.addCommand(Qs);Q.addCommand(ua);D()||Q.addCommand(Ra);Q.addCommand(rc);Q.addCommand(cc);Q.addCommand(yc);Q.addCommand(Dc);Q.addCommand(ml);Q.addCommand(Su);var ws=process.argv.slice(2);ws.length>=2&&ws[ws.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var qw=new Set(["update"]);Q.hook("preAction",async(n,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==Q;)t=t.parent;qw.has(t.name())||await _.checkVersion()});Q.parseAsync(process.argv).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(zw(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
@@ -1,5 +1,5 @@
1
1
  import*as h from"fs";import*as H from"path";import ei from"adm-zip";import ni from"proper-lockfile";import ri from"ora";import*as b from"fs";import*as j from"path";var ht=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],G={"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 X="1.9.1",xi=48*1024*1024,te=280,ee=6,ne=100,re=3,oe=28,St=10,ie=/API参考|APIReference/i;var se=6,W=700,yt=250,xt=400,ae=1320,ce=120,ue=450,le=250,de=500,me=480,fe=80,pe=200,ge=60,he=200,Se=40,ye=200,xe=200,_e=40,B=500,Ee=Object.fromEntries(ht.map((t,e)=>[G[t],e])),w=Object.fromEntries(ht.map((t,e)=>[t,e]));import*as be from"fs";import*as m from"path";import{fileURLToPath as Te}from"url";import*as Q from"path";import{homedir as Zn}from"os";var Un="deveco-cli";function $n(t){let e=t.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function Ae(){return Q.join(Zn(),".local","share",Un)}function _t(){let t=process.env.DEVECO_CLI_DATA_DIR;if(t===void 0||t==="")return Ae();let e=$n(t);return e?Q.resolve(e):Ae()}var Gn="docs";function q(){return m.join(_t(),Gn)}function x(){return m.join(q(),".index")}function Ie(){return m.join(x(),"build.lock")}function Et(){return m.join(x(),"build-status.json")}function Y(){return m.join(x(),"build-meta.json")}function V(){return m.join(x(),"search.db")}function M(){return m.join(x(),".tmp")}function Xn(){return m.join(_t(),"logs")}function At(){return m.join(Xn(),"doc-init.log")}function Wn(t,e){let n=e;for(;!n.endsWith(`${m.sep}dist`)&&n!==m.dirname(n);)n=m.dirname(n);return n}function De(t,e){return m.dirname(Wn(t,e))}function Qn(){let t=Te(import.meta.url),e=m.dirname(t);return t.includes(`${m.sep}dist${m.sep}`)?De(t,e):m.join(e,"..","..","..")}function qn(...t){let e=Te(import.meta.url),n=m.dirname(e);return e.includes(`${m.sep}dist${m.sep}`)?[m.join(De(e,n),...t)]:[m.join(n,"..","..","..",...t)]}function we(...t){for(let e of qn(...t))if(be.existsSync(e))return e;return null}function O(){return we("docs.zip")}function bt(){return we("index.zip")}function Ce(){return m.join(Qn(),"index","data")}import*as D from"fs";import*as L from"path";var P=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],Tt=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};var It=null;function Dt(t){It=t}function Re(){if(It)return It;let t=x();if(P.every(o=>D.existsSync(L.join(t,o))))return t;let n=Ce();if(P.every(o=>D.existsSync(L.join(n,o))))return n;throw new Tt("Lexicon files not found. Install the documentation index first (index.zip).")}function k(t){let e=L.join(Re(),t);return D.readFileSync(e,"utf-8")}function Ne(t,e){return D.readFileSync(L.join(e,t),"utf-8")}async function Oe(t,e=Re()){await D.promises.mkdir(t,{recursive:!0});for(let n of P){let r=L.join(e,n),o=L.join(t,n);await D.promises.copyFile(r,o)}}import*as wt from"fs";import*as Yn from"yauzl";function Ct(){let t=O();return t!==null&&wt.existsSync(t)}import*as S from"fs";import*as C from"path";import Le from"adm-zip";var Pe=["search.db","build-meta.json",...P],Vn=["corpus.json","corpus-offsets.json","orama.dpack"];async function Kn(t){for(let e of Vn)await S.promises.rm(C.join(t,e),{force:!0})}async function Jn(t){let e=await S.promises.readdir(t,{withFileTypes:!0});for(let n of e)n.name!==".index"&&await S.promises.rm(C.join(t,n.name),{recursive:!0,force:!0})}function tr(t){let n=new Le(t).getEntry("build-meta.json");if(!n)throw new Error("index.zip is missing build-meta.json");return JSON.parse(n.getData().toString("utf-8"))}async function er(t){let e=x();await S.promises.mkdir(e,{recursive:!0});for(let n of Pe){let r=C.join(e,n);await S.promises.rm(r,{force:!0}),await S.promises.rename(C.join(t,n),r)}await Kn(e),await S.promises.rm(M(),{recursive:!0,force:!0})}function Rt(){let t=bt();return t!==null&&S.existsSync(t)}async function Be(t){let e=bt();if(!e)throw new Error("index.zip not found");let n=tr(e);if(n.docsZipSha256!==t)throw new Error("Bundled index.zip does not match docs.zip. Rebuild index.zip with npm run build:index.");if(n.segmentCount<=0)throw new Error("Bundled index.zip is empty");let r=M();await S.promises.rm(r,{recursive:!0,force:!0}),await S.promises.mkdir(r,{recursive:!0});let o=new Le(e);for(let s of Pe){let a=o.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await S.promises.writeFile(C.join(r,s),a.getData())}let i=JSON.parse(await S.promises.readFile(C.join(r,"build-meta.json"),"utf-8"));if(!S.existsSync(C.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await er(r),await S.promises.mkdir(q(),{recursive:!0}),await Jn(q()),i}import{createHash as Me}from"crypto";import*as ke from"fs";async function K(t){return new Promise((e,n)=>{let r=Me("sha256"),o=ke.createReadStream(t);o.on("data",i=>r.update(i)),o.on("error",n),o.on("end",()=>e(r.digest("hex")))})}function Fe(t){return Me("sha256").update(t,"utf8").digest("hex")}function ve(t,e){let n=e?Ne(t,e):k(t);return Fe(n)}function J(t){return ve("harmonyos-synonyms.json",t)}function tt(t){return ve("harmonyos-terms.txt",t)}var nr={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function ze(){try{let t=await b.promises.readFile(Et(),"utf-8");return JSON.parse(t)}catch{return{...nr}}}async function Nt(t){let e=Et();await b.promises.mkdir(j.dirname(e),{recursive:!0}),await b.promises.writeFile(e,JSON.stringify(t,null,2))}function He(t){let e=Date.now();return{state:"extracting",phase:1,phaseLabel:"Extracting documentation",current:0,total:0,message:t,startedAt:e,updatedAt:e,error:null}}async function R(t){let n={...await ze(),...t,updatedAt:Date.now()};return await Nt(n),n}async function Ot(){let t=O();return t?K(t):null}async function Lt(){try{let t=await b.promises.readFile(Y(),"utf-8");return JSON.parse(t)}catch{return null}}async function Pt(t=!1){if(t)return"no-index";let e=await Lt();if(!e||e.segmentCount===0)return"no-index";let n=await Ot();return n&&e.docsZipSha256!==n?"docs-changed":e.indexVersion!==X?"engine-upgraded":e.termsHash!==tt()?"terms-changed":e.synonymsHash!==J()?"synonyms-changed":null}function Bt(){if(!Ct()||!b.existsSync(V())||!b.existsSync(Y()))return!1;let t=j.dirname(V());if(!P.every(e=>b.existsSync(j.join(t,e))))return!1;try{let e=b.readFileSync(Y(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function je(t=!1){return t?!0:Ct()?Bt()?await Pt()!==null:!0:!1}import*as y from"fs";import*as kn from"os";import*as _ from"path";var Ze=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]);var Ue=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"]),$e=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 rr=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,or=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,ir=/[A-Z][a-zA-Z0-9]{2,}/g,sr=/@[A-Z][a-zA-Z0-9]*/g,ar=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,Ge=6,cr=/^[a-z][a-z0-9]{2,}$/,ur=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,lr=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,dr=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,mr=/^[A-Z][a-zA-Z0-9]+$/;function Mt(t){return lr.test(t)}function fr(t){return dr.test(t)&&t.length>=Ge}function pr(t){return mr.test(t)}function kt(t){return Mt(t)||fr(t)||pr(t)}function gr(t){let e=t.trim().toLowerCase();return $e.has(e)?!1:Ze.has(e)}function hr(t,e){let n=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${t.trim().toLowerCase()}${n}${r}`}function et(t){let n=t.replace(/^@ohos\./i,"").split(".").filter(Boolean);return n[n.length-1]?.trim()||void 0}function Ft(t){return[...t.matchAll(rr)].map(e=>e[0])}function vt(t,e=Ge){let n=[];for(let r of t.matchAll(or))r[0].length>=e&&n.push(r[0]);return n}function F(t){return t.filter(e=>{let n=e.toLowerCase();return!t.some(r=>{if(r===e)return!1;let o=r.toLowerCase();return o.length>n.length&&o.endsWith(n)&&n.length>=4})})}function T(t,e){let n=e.trim();if(!n)return;t.add(n);let r=n.toLowerCase();r!==n&&t.add(r)}function Sr(t){let e=new Set;T(e,t);let n=et(t);return n&&T(e,n),F([...e])}function zt(t){if(Mt(t))return Sr(t);let e=new Set;return T(e,t),F([...e])}function Ht(t){let e=t.trim();if(/[A-Z]/.test(e))return null;let n=e.match(ur);if(!n)return null;let r=n[1].toLowerCase(),o=n[2].toLowerCase();if(!cr.test(r)||Ue.has(r)||!gr(o))return null;let i=hr(r,o);return{first:r,second:o,camelCase:i,lower:i.toLowerCase()}}function Xe(t){let e=Ht(t.trim());return!e||e.second!=="manager"?null:e}function jt(t,e,n){let r=n.toLowerCase(),o=new RegExp(`@ohos\\.[^\\s(]*${n}`,"i");for(let i of[t,e])if(i&&(i.toLowerCase().includes(r)||o.test(i)))return!0;return!1}function We(t){let e=t.trim();if(kt(e))return zt(e);let n=new Set;for(let r of Ft(t)){T(n,r);let o=et(r);o&&T(n,o)}for(let r of vt(t))T(n,r);for(let r of t.matchAll(sr))n.add(r[0]);for(let r of t.matchAll(ar))n.add(r[0]);for(let r of t.matchAll(ir))r[0].length>=4&&n.add(r[0]);return F([...n])}function Qe(t){let e=t.trim();if(kt(e))return zt(e);let n=new Set,r=Ht(e);r&&T(n,r.camelCase);for(let o of We(e))n.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()&&n.add(i)}return F([...n])}var I={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 Ye(t){return I.pureApiSymbol.test(t.trim())}function qe(t){let e=t.trim();return I.stageModelExact.test(e)||I.stageModelEnglishExact.test(e)}var yr=[{matches:t=>I.uiAbilityLifecycleBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:t=>qe(t),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:t=>!qe(t)&&I.stageModel.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:t=>I.entryAbilityPage.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:t=>I.declarePermissionBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:t=>I.stateDecoratorBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:t=>I.stateManagement.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:t=>I.routerRoute.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:1.4},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]},{matches:t=>I.dialogPopupBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function xr(t,e){for(let{catalog:n,multiplier:r}of e){let o=w[n];t.set(o,(t.get(o)??1)*r)}}function Ve(t,e){for(let n of yr)n.matches(t)&&xr(e,n.weights)}import*as Ke from"os";function Zt(){return _r()==="openharmony"}function _r(){return Ke.platform()}var nt=null,tn=null,$t=null,Je=!1,Ut=null;function Er(){if(nt)return nt;let t=k("harmonyos-stopwords.txt");return nt=new Set(t.split(`
2
- `).map(e=>e.trim()).filter(Boolean)),nt}function Ar(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n]?.trim();if(!r)continue;let o=t[n+1]?.trim();if(r==="@"&&o&&/^[A-Z][a-zA-Z0-9]*$/.test(o)){e.push(`@${o}`),n+=1;continue}e.push(r)}return e}function br(t){let e=Er(),n=[];for(let r of Ar(t)){let o=r.trim();!o||e.has(o)||(n.push(o.toLowerCase()),/[A-Z]/.test(o)&&/[a-zA-Z]/.test(o)&&n.push(o))}return n}async function Tr(){let t=await import("jieba-wasm");tn=t.cut,$t=t.cut_for_search;let e=k("harmonyos-terms.txt");t.with_dict(e)}async function Ir(){let{Jieba:t}=await import("@node-rs/jieba"),e=k("harmonyos-terms.txt"),n=t.withDict(Buffer.from(e,"utf-8"));tn=n.cut.bind(n),$t=n.cutForSearch.bind(n)}async function v(){Je||(Ut||(Ut=(Zt()?Tr():Ir()).then(()=>{Je=!0})),await Ut)}async function Dr(t){return await v(),br($t(t,!0))}async function rt(t,e){let n=t.trim();if(!n||e<=0)return"";let r=(await Dr(n)).join(" ");return r.length<=e?r:r.slice(0,e)}async function wr(t,e){let n=[];for(let o of t){let i=o.trim();i&&(n.push(i.toLowerCase()),/[A-Z]/.test(i)&&n.push(i))}let r=[...new Set(n)].join(" ");return r.length<=e?r:r.slice(0,e)}async function ot(t){let e=!!t.sectionTitle.trim(),n=t.titleTokens.trim(),r=e?me:ae,o=e?pe:ue,i=e?await wr(t.apiSymbols,o):await rt(t.apiSymbols.join(" "),o),a=(await Promise.all([rt(n,e?fe:ce),Promise.resolve(i),rt(t.headingsText,e?ge:le),rt(t.bodySample,e?he:de)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}var en=["harmonyos-releases","harmonyos-roadmap"],Cr=new Set(en.map(t=>w[t])),js=en.map(t=>`${G[t]}/`);function Rr(t){return Cr.has(t)}function nn(t){let e=[],n=[];for(let r of t)Rr(r.catalog_id)?n.push(r):e.push(r);return[...e,...n]}var Nr=[{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 Z(t,e,n){let r=w[e];t.set(r,(t.get(r)??1)*n)}function Or(t,e){let n=t.trim(),r=/[\u4e00-\u9fff]/.test(n),o=/\b[A-Z][a-zA-Z0-9]{2,}\b/.test(n),i=/\b[a-z][a-zA-Z0-9]{3,}\b/.test(n);if(r&&(o||i)){Z(e,"harmonyos-guides",1.45),Z(e,"harmonyos-references",1.35);return}(o||i)&&Z(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(n)&&Z(e,"harmonyos-references",1.75)}function rn(t){let e=new Map,n=t.trim();if(!n)return e;let r=Ye(n);Or(n,e),Ve(n,e);for(let o of Nr)o.pattern.test(n)&&(o.skipForPureApiSymbol&&r||Z(e,o.catalog,o.multiplier));return e}function it(t){process.env.DEVECO_CLI_DEBUG&&console.log(`[DEBUG] ${t}`)}var Lr=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function on(t,e){let n=-1;for(let r of Lr){let o=t.lastIndexOf(r);o>n&&(n=o)}return n>=e?n:-1}function sn(t,e){let n=t.trim();if(n.length<=e)return{text:n,excerptTruncated:!1};let r=n.slice(0,e),o=on(r,e-20),i=o>=0?o:e;return{text:n.slice(0,i).trimEnd(),excerptTruncated:!0}}function an(t,e,n={}){let{maxLen:r=xe,contextChars:o=_e,excerptTruncated:i=!1}=n,s=t.replace(/\s+/g," ").trim();if(!s)return"";if(s.length<=r)return i?`${s}...`:s;let a=e.split(/\s+/).map(gt=>gt.trim()).filter(Boolean),c=0;for(let gt of a){let Jt=s.toLowerCase().indexOf(gt.toLowerCase());if(Jt>=0){c=Jt;break}}let f=Math.max(0,c-o),p=Math.min(s.length,f+r),u=s.slice(f,p),E=on(u,r-25);E>=0&&(p=f+E);let g=s.slice(f,p).trim(),A=f>0?"...":"",jn=p<s.length||i?"...":"";return`${A}${g}${jn}`}var Pr=`
2
+ `).map(e=>e.trim()).filter(Boolean)),nt}function Ar(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n]?.trim();if(!r)continue;let o=t[n+1]?.trim();if(r==="@"&&o&&/^[A-Z][a-zA-Z0-9]*$/.test(o)){e.push(`@${o}`),n+=1;continue}e.push(r)}return e}function br(t){let e=Er(),n=[];for(let r of Ar(t)){let o=r.trim();!o||e.has(o)||(n.push(o.toLowerCase()),/[A-Z]/.test(o)&&/[a-zA-Z]/.test(o)&&n.push(o))}return n}async function Tr(){let t=await import("jieba-wasm");tn=t.cut,$t=t.cut_for_search;let e=k("harmonyos-terms.txt");t.with_dict(e)}async function Ir(){let{Jieba:t}=await import("@node-rs/jieba"),{dict:e}=await import("@node-rs/jieba/dict.js"),n=t.withDict(e),r=k("harmonyos-terms.txt");n.loadDict(Buffer.from(r,"utf-8")),tn=n.cut.bind(n),$t=n.cutForSearch.bind(n)}async function v(){Je||(Ut||(Ut=(Zt()?Tr():Ir()).then(()=>{Je=!0})),await Ut)}async function Dr(t){return await v(),br($t(t,!0))}async function rt(t,e){let n=t.trim();if(!n||e<=0)return"";let r=(await Dr(n)).join(" ");return r.length<=e?r:r.slice(0,e)}async function wr(t,e){let n=[];for(let o of t){let i=o.trim();i&&(n.push(i.toLowerCase()),/[A-Z]/.test(i)&&n.push(i))}let r=[...new Set(n)].join(" ");return r.length<=e?r:r.slice(0,e)}async function ot(t){let e=!!t.sectionTitle.trim(),n=t.titleTokens.trim(),r=e?me:ae,o=e?pe:ue,i=e?await wr(t.apiSymbols,o):await rt(t.apiSymbols.join(" "),o),a=(await Promise.all([rt(n,e?fe:ce),Promise.resolve(i),rt(t.headingsText,e?ge:le),rt(t.bodySample,e?he:de)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}var en=["harmonyos-releases","harmonyos-roadmap"],Cr=new Set(en.map(t=>w[t])),js=en.map(t=>`${G[t]}/`);function Rr(t){return Cr.has(t)}function nn(t){let e=[],n=[];for(let r of t)Rr(r.catalog_id)?n.push(r):e.push(r);return[...e,...n]}var Nr=[{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 Z(t,e,n){let r=w[e];t.set(r,(t.get(r)??1)*n)}function Or(t,e){let n=t.trim(),r=/[\u4e00-\u9fff]/.test(n),o=/\b[A-Z][a-zA-Z0-9]{2,}\b/.test(n),i=/\b[a-z][a-zA-Z0-9]{3,}\b/.test(n);if(r&&(o||i)){Z(e,"harmonyos-guides",1.45),Z(e,"harmonyos-references",1.35);return}(o||i)&&Z(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(n)&&Z(e,"harmonyos-references",1.75)}function rn(t){let e=new Map,n=t.trim();if(!n)return e;let r=Ye(n);Or(n,e),Ve(n,e);for(let o of Nr)o.pattern.test(n)&&(o.skipForPureApiSymbol&&r||Z(e,o.catalog,o.multiplier));return e}function it(t){process.env.DEVECO_CLI_DEBUG&&console.log(`[DEBUG] ${t}`)}var Lr=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function on(t,e){let n=-1;for(let r of Lr){let o=t.lastIndexOf(r);o>n&&(n=o)}return n>=e?n:-1}function sn(t,e){let n=t.trim();if(n.length<=e)return{text:n,excerptTruncated:!1};let r=n.slice(0,e),o=on(r,e-20),i=o>=0?o:e;return{text:n.slice(0,i).trimEnd(),excerptTruncated:!0}}function an(t,e,n={}){let{maxLen:r=xe,contextChars:o=_e,excerptTruncated:i=!1}=n,s=t.replace(/\s+/g," ").trim();if(!s)return"";if(s.length<=r)return i?`${s}...`:s;let a=e.split(/\s+/).map(gt=>gt.trim()).filter(Boolean),c=0;for(let gt of a){let Jt=s.toLowerCase().indexOf(gt.toLowerCase());if(Jt>=0){c=Jt;break}}let f=Math.max(0,c-o),p=Math.min(s.length,f+r),u=s.slice(f,p),E=on(u,r-25);E>=0&&(p=f+E);let g=s.slice(f,p).trim(),A=f>0?"...":"",jn=p<s.length||i?"...":"";return`${A}${g}${jn}`}var Pr=`
3
3
  SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
4
4
  d.catalog_id, bm25(segments_fts) AS bm25
5
5
  FROM segments_fts
@@ -62,4 +62,4 @@ CREATE INDEX segments_doc_id_idx ON segments(doc_id);
62
62
  INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated)
63
63
  VALUES (?, ?, ?, ?, ?)
64
64
  `),a=n.length;for(let c=0;c<a;c+=B){let f=n.slice(c,c+B),p=await Promise.all(f.map(async E=>({source:E,searchText:await ot(E)})));o.transaction(E=>{for(let g of E){let A=to(o,i,g.source);s.run(A,g.source.sectionTitle,g.source.leadText,g.searchText,g.source.excerptTruncated?1:0)}})(p),await r?.(Math.min(c+f.length,a),a)}o.exec("ANALYZE"),o.exec("VACUUM"),o.close()}function no(t,e,n,r,o,i,s){let a=Kr(t,e);return at({all(c,...f){return a.prepare(c).all(...f)}},n,r,o,i,s)}async function ln(){let e=(await import("better-sqlite3")).default;return{kind:"better-sqlite3",resetCache:Vr,buildSearchIndex:(n,r,o)=>eo(e,n,r,o),searchIndex:(n,r,o,i,s,a,c)=>Promise.resolve(no(e,i,r,o,s,a,c))}}import{readFile as ro,stat as oo,writeFile as io}from"fs/promises";var Qt=null,N=null;async function qt(){return Qt||(Qt=(async()=>{let t=(await import("@sqlite.org/sqlite-wasm")).default;return t()})()),Qt}function so(t){return{all(e,...n){let r=t.prepare(e);n.length>0&&r.bind(n);let o=[];for(;r.step();)o.push(r.get({}));return r.finalize(),o}}}async function ao(t){let e=await oo(t);if(N&&N.dbPath===t&&N.mtimeMs===e.mtimeMs)return N.db;N?.db.close();let n=await qt(),r=n.capi,o=n.wasm,i=new Uint8Array(await ro(t)),s=o.allocFromTypedArray(i),a=new n.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),N={dbPath:t,mtimeMs:e.mtimeMs,db:a},a}function dn(){N?.db.close(),N=null}async function co(t,e,n,r){t.exec("BEGIN");for(let o of r){let i=n(o.source);e.bind([i,o.source.sectionTitle,o.source.leadText,o.searchText,o.source.excerptTruncated?1:0]),e.step(),e.reset()}t.exec("COMMIT")}function uo(t,e,n){return r=>{let o=e.get(r.documentId);if(o!==void 0)return o;let i=t.selectValue("SELECT id FROM documents WHERE document_id = ?",[r.documentId]);if(i!=null){let a=Number(i);return e.set(r.documentId,a),a}n.bind([r.documentId,r.catalogId,r.docTitle]),n.step(),n.reset();let s=Number(t.selectValue("SELECT last_insert_rowid()"));return e.set(r.documentId,s),s}}async function lo(t,e,n){await v();let r=await qt(),o=new r.oo1.DB(":memory:","c");o.exec(ct);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=uo(o,i,s),f=e.length;for(let u=0;u<f;u+=B){let E=e.slice(u,u+B),g=await Promise.all(E.map(async A=>({source:A,searchText:await ot(A)})));await co(o,a,c,g),await n?.(Math.min(u+E.length,f),f)}o.exec("ANALYZE");let p=r.capi.sqlite3_js_db_export(o);await io(t,p),o.close(),dn()}async function mo(t,e,n,r,o,i){let s=await ao(t);return at(so(s),e,n,r,o,i)}async function mn(){return await qt(),{kind:"sqlite-wasm",resetCache:dn,buildSearchIndex:lo,searchIndex:(t,e,n,r,o,i,s)=>mo(r,e,n,o,i,s)}}var ut=null,Yt=null;async function fo(){try{let e=await ln();return it("doc-index: using better-sqlite3 SQLite backend"),e}catch(e){it(`doc-index: better-sqlite3 unavailable (${e.message}); falling back to sqlite-wasm`)}let t=await mn();return it("doc-index: using @sqlite.org/sqlite-wasm SQLite backend"),t}async function Vt(){return ut||(ut=fo().then(t=>(Yt=t,t))),ut}function fn(){Yt?.resetCache(),ut=null,Yt=null}function pn(){fn()}async function gn(t,e,n){await(await Vt()).buildSearchIndex(t,e,n)}import{unified as bn}from"unified";import Tn from"remark-parse";import In from"remark-gfm";import{toString as dt}from"mdast-util-to-string";var po=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,go=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,ho=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,So=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,yo=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function lt(t){let e=t.trim(),n=e.match(So);return n?n[1]:e}function xo(t){let e=t.match(po);if(!e)return;let n=lt(e[1].trim());return{displayTitle:t,symbolName:n,searchExtras:[n,e[3]]}}function _o(t){let e=lt(t.replace(/\([^)]*\)$/,""));if(/^[A-Z][A-Za-z0-9]*$/.test(e))return{displayTitle:t,symbolName:e,searchExtras:[e]};if(/^[A-Z][A-Za-z0-9]*(\([^)]*\))?$/.test(t))return{displayTitle:t,symbolName:e,searchExtras:[e]}}function U(t){let e=t.trim();return e?xo(e)??(()=>{let n=e.match(go);if(n){let r=n[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let n=e.match(ho);if(!n)return;let r=n[1].trim(),o=n[2].trim();return{displayTitle:e,symbolName:o,searchExtras:[r,o]}})()??_o(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function Eo(t){if(t.length<2||t.length>36||yo.test(t))return!1;let e=[...t.replace(/\s/g,"")];return e.length===0?!1:e.filter(r=>new RegExp("\\p{Script=Han}","u").test(r)).length/e.length>=.4}function hn(t){for(let e of t){let n=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(Eo(n))return n}return""}function Sn(t,e,n){let r=[t,...n.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var Ao=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,$=/@[A-Z][a-zA-Z]+/g,bo=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,To=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,Io=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,Do=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),wo=new Set(["HAP","HSP","HAR","NAPI","CAPI","NDK","ArkTS","ArkUI","OHPM"]),Co=new Set(["JSON","Object","Array","Promise","console","Math","Date","String","Number","Boolean","Error","Function","Map","Set","RegExp"]);function Dn(t,e){let n=new Set,r=[t,...e];for(let o of r){for(let i of Ft(o)){T(n,i);let s=et(i);s&&T(n,s)}for(let i of vt(o))T(n,i);for(let i of o.matchAll(Ao)){let s=i[0];Ro(s)&&n.add(s)}for(let i of o.matchAll($))n.add(i[0])}return F([...n])}function Ro(t){let e=t.trim();if(!e||$.test(e))return!!e;if(e.includes(".")){let n=e.split(".")[0]??"";return Co.has(n)?!1:/^[A-Z]/.test(n)}return Do.has(e)?!1:wo.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 yn(t){let e=t.trim();return!!(!e||Io.test(e)||e.length>28&&!/[A-Z\u4e00-\u9fff]/.test(e)&&/^[a-z0-9_-]+$/.test(e))}function wn(t,e){let n=e.jsonTitle?.trim(),r=Po(t,"").trim(),o=e.fileName.trim();return n&&!yn(n)?n:r&&!yn(r)?r:n||r||o}function Cn(t){return bo.test(t.trim())}function Kt(t){let e=t.trim().replace(/\([^)]*\)$/,""),n=lt(e);return To.test(n)}function mt(t){let e=t.trim();return e?$.test(e)||Cn(e)||Kt(e)?!0:!!U(e).symbolName:!1}function No(t){let e=t.trim();return!(!e||Cn(e)||Kt(e))}function Oo(t){let e=new Set,n=[];for(let r of t){let o=r.trim();!No(o)||e.has(o)||(e.add(o),n.push(o))}return n}function xn(t){if(!t.includes("."))return 0;let e=t.split(".").pop()??"";return/^[a-z]/.test(e)?1:2}function Lo(t,e){let n=xn(t)-xn(e);return n!==0?n:t.localeCompare(e)}function Rn(t,e=[]){let n=[...new Set(e.map(i=>i.trim()).filter(Boolean))],r=new Set(n),o=[...new Set(t.map(i=>i.trim()).filter(Boolean))].filter(i=>!r.has(i));return o.sort(Lo),[...n,...o].slice(0,Se)}function ft(t){return t.replace(/\s+/g," ").trim()}function _n(t){return t.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function Po(t,e=""){let n=t.split(/\r?\n/),r=0;for(;r<n.length&&!n[r].trim();)r+=1;if(r>=n.length)return e;let o=_n(n[r].trim()),i=o.match(/^#+\s+(.+)$/);if(i)return _n(i[1].trim());if(r+1<n.length){let s=n[r+1].trim();if(/^=+$/.test(s)||/^-+$/.test(s))return o}return o||e}function Nn(t){let e=ft(t.join(" "));if(e.length<=W)return e;let n=e.slice(0,W);return e.length<=W+yt?n:`${n} ${e.slice(-yt)}`}function Bo(t){let e=Oo(t).join(" ");return e.length<=xt?e:e.slice(0,xt)}function On(t){let e=ft(t),{text:n,excerptTruncated:r}=sn(e,ye);return{leadText:n,excerptTruncated:r}}function Mo(t,e){let{leadText:n,excerptTruncated:r}=On(t);return{leadText:n,excerptTruncated:r||!!e.trim()}}function Ln(t,e){if(t.type==="code"){e.codeBlocks.push(t.value??"");return}if("children"in t&&Array.isArray(t.children)){for(let r of t.children)Ln(r,e);return}let n=ft(dt(t));n&&e.bodyParts.push(n)}function ko(t){let e=bn().use(Tn).use(In).parse(t),n=[],r=null,o=()=>{r&&((r.sectionTitle||r.bodyParts.length||r.codeBlocks.length)&&n.push(r),r=null)},i=()=>{r||(r={sectionTitle:"",bodyParts:[],codeBlocks:[]})};for(let s of e.children){if(s.type==="heading"){let a=s,c=dt(a).trim();if(a.depth>=4&&c&&mt(c)){o(),r={sectionTitle:c,bodyParts:[],codeBlocks:[]};continue}i(),c&&r.bodyParts.push(c);continue}i(),Ln(s,r)}return o(),n.length===0?[{sectionTitle:"",bodyParts:[],codeBlocks:[]}]:n}function Fo(t){return ie.test(t)}function vo(t){return t.filter(e=>e.sectionTitle&&mt(e.sectionTitle)).length}function zo(t){return{sectionTitle:t.map(e=>e.sectionTitle.trim()).join(" | "),bodyParts:t.flatMap(e=>e.bodyParts).slice(0,40),codeBlocks:t.flatMap(e=>e.codeBlocks).slice(0,8)}}function En(t){let e=t.trim();return!e||$.test(e)?$.test(e):/对象说明$|枚举说明$/.test(e)?!0:Kt(e)}function Ho(t){let e=t.filter(u=>!u.sectionTitle||!mt(u.sectionTitle)),n=t.filter(u=>u.sectionTitle&&mt(u.sectionTitle)),r=n.filter(u=>En(u.sectionTitle)),o=n.filter(u=>!En(u.sectionTitle)),i=Math.max(0,oe-r.length),s=o.slice(0,i),a=o.slice(i),c=a.filter(u=>An(u.sectionTitle)),f=a.filter(u=>!An(u.sectionTitle)),p=[];for(let u=0;u<f.length;u+=St)p.push(zo(f.slice(u,u+St)));return[...e,...r,...s,...c,...p]}function jo(t,e,n){let r=t.split(/\r?\n/).length,o=vo(e);return o===0?!1:Fo(n)?r>=ne&&o>=re:r>=te&&o>=ee}var Zo=/^\[h2\][A-Za-z]/;function An(t){return Zo.test(t.trim())}function Pn(t){if(!t.includes(" | ")){let n=U(t);return n.symbolName?[n.symbolName]:[]}let e=[];for(let n of t.split(" | ")){let r=U(n.trim()).symbolName;r&&e.push(r)}return e}function Uo(t,e,n,r){let o=Pn(t),i=Dn(n,r);return e.symbolName&&i.push(e.symbolName),Rn([...o,...i],o)}function $o(t,e){let n=Nn(t.bodyParts),r=t.sectionTitle.trim(),o=U(r),i=hn(t.bodyParts),s=Sn(r,i,o),a=Pn(r),c=r?a.length>0?`${e.docTitle} ${a.join(" ")}`:`${e.docTitle} ${o.symbolName??r}`:e.docTitle,f=[e.docTitle,s,...t.bodyParts].join(" "),{leadText:p,excerptTruncated:u}=Mo(n,r);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:e.docTitle,sectionTitle:r,titleTokens:c,headingsText:s,apiSymbols:Uo(r,o,f,t.codeBlocks),bodySample:n,leadText:p,excerptTruncated:u}}function Bn(t,e){for(let n of t){if(n.type==="heading"){let o=dt(n).trim();o&&e.headings.push(o);continue}if(n.type==="code"){e.codeBlocks.push(n.value??"");continue}if("children"in n&&Array.isArray(n.children)){Bn(n.children,e);continue}let r=ft(dt(n));r&&e.bodyParts.push(r)}}function Go(t){let e=bn().use(Tn).use(In).parse(t),n={headings:[],bodyParts:[],codeBlocks:[]};return Bn(e.children,n),n}function Xo(t,e){let n=Go(t),r=e.docTitle?.trim()||e.documentId,o=Nn(n.bodyParts),i=[r,...n.headings,o].join(" "),{leadText:s,excerptTruncated:a}=On(o);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:r,sectionTitle:"",titleTokens:r,headingsText:Bo(n.headings),apiSymbols:Rn(Dn(i,n.codeBlocks)),bodySample:o,leadText:s,excerptTruncated:a}}function Mn(t,e){let n=e.docTitle?.trim()||e.documentId,r=ko(t);return jo(t,r,e.documentId)?Ho(r).filter(o=>o.sectionTitle||o.bodyParts.length>0||o.codeBlocks.length>0).map(o=>$o(o,{...e,docTitle:n})):[Xo(t,{...e,docTitle:n})]}async function Wo(t){let e=[];async function n(r){let o=await y.promises.readdir(r,{withFileTypes:!0});for(let i of o){if(i.name.startsWith("."))continue;let s=_.join(r,i.name);i.isDirectory()?await n(s):i.isFile()&&i.name.endsWith(".md")&&e.push(s)}}return await n(t),e}function Qo(t,e){let n=_.relative(e,t).split(_.sep).join("/").split("/");if(n[0]==="docs"&&(n=n.slice(1)),n.length<2)return null;let r=n[0],o=Ee[r];if(o===void 0)return null;let i=n[n.length-1].replace(/\.md$/,"");return n[n.length-1]=i,{documentId:n.join("/"),catalogId:o,docTitle:i}}async function qo(t){let e=t.replace(/\.md$/,".json");try{let n=await y.promises.readFile(e,"utf-8");return JSON.parse(n).title?.trim()||void 0}catch{return}}async function Yo(t,e){let n=Qo(t,e);if(!n)return[];let r=await y.promises.readFile(t,"utf-8"),o=wn(r,{jsonTitle:await qo(t),fileName:n.docTitle});return Mn(r,{...n,docTitle:o})}async function Vo(t,e,n){let r=_.join(e,"search.db");return await gn(r,t,async(o,i)=>{await n?.({current:o,total:i,message:`Building search index\u2026 ${o.toLocaleString()} / ${i.toLocaleString()} segments`})}),t.length}async function Ko(t){let e=await Wo(t),n=[];for(let r of e){let o=await Yo(r,t);n.push(...o)}return n}function Jo(t,e){return{indexVersion:X,docsZipSha256:t.docsZipSha256,termsHash:t.termsHash,synonymsHash:t.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:t.builtBy}}async function Fn(t){t.lexiconDir&&Dt(t.lexiconDir);try{let e=await Ko(t.docsDir);await t.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await y.promises.mkdir(t.tmpDir,{recursive:!0});let n=await Vo(e,t.tmpDir,t.onProgress),r=Jo(t,n);return await y.promises.writeFile(_.join(t.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await Oe(t.tmpDir),r}finally{t.lexiconDir&&Dt(null)}}async function vn(){return y.promises.mkdtemp(_.join(kn.tmpdir(),"deveco-docs-"))}async function ti(t,e){try{await y.promises.rename(t,e)}catch(n){let r=n.code;if(r!=="EPERM"&&r!=="EXDEV")throw n;await y.promises.cp(t,e,{recursive:!0}),await y.promises.rm(t,{recursive:!0,force:!0})}}async function zn(t){let e=_.join(t,"docs");try{await y.promises.access(e)}catch{return}let n=new Set(["docs","docs.zip"]);for(let r of await y.promises.readdir(e,{withFileTypes:!0})){if(n.has(r.name))continue;let o=_.join(e,r.name),i=_.join(t,r.name);await y.promises.rm(i,{recursive:!0,force:!0}),await ti(o,i)}await y.promises.rm(_.join(e,"docs"),{recursive:!0,force:!0}),await y.promises.rm(_.join(e,"docs.zip"),{force:!0}),await y.promises.rm(e,{recursive:!0,force:!0})}async function oi(t){let e=At();await h.promises.mkdir(H.dirname(e),{recursive:!0}),await h.promises.appendFile(e,`${new Date().toISOString()} ${t}
65
- `)}async function ii(t){let e=O();if(!e)throw new Error("docs.zip not found");await h.promises.rm(t,{recursive:!0,force:!0}),await h.promises.mkdir(t,{recursive:!0}),new ei(e).extractAllTo(t,!0),await zn(t)}async function si(){let t=x(),e=M(),n=await h.promises.readdir(e);for(let r of n){let o=H.join(t,r);await h.promises.rm(o,{force:!0}),await h.promises.rename(H.join(e,r),o)}await h.promises.rm(e,{recursive:!0,force:!0}),await h.promises.rm(H.join(t,"orama.dpack"),{force:!0})}async function ai(t,e){e?.start("Installing documentation index\u2026"),await R({state:"installing",phase:1,phaseLabel:"Installing index",message:"Installing documentation index\u2026"}),await Be(t),e&&(e.text="Documentation index installed.")}async function ci(t,e,n){let r=M(),o=await vn();await h.promises.mkdir(x(),{recursive:!0}),await h.promises.rm(r,{recursive:!0,force:!0}),n?.start("Building search index\u2026"),await R({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"});try{await ii(o),await Fn({docsDir:o,tmpDir:r,docsZipSha256:e,termsHash:tt(),synonymsHash:J(),builtBy:t.builtBy??"doc-init",onProgress:async i=>{n&&(n.text=i.message),await R({state:"indexing",current:i.current,total:i.total,message:i.message})}})}finally{await h.promises.rm(o,{recursive:!0,force:!0})}await R({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await si(),pn()}async function Hn(t){await R({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),t?.succeed("Documentation ready.")}async function ui(t){let e=await Lt(),n=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";t?.succeed(n),await R({state:"done",message:n,error:null})}async function li(t,e){let n=t instanceof Error?t.message:String(t);throw await R({state:"error",error:n}),await oi(`ERROR: ${n}`),e?.fail(n),t}async function di(){let t=x();await h.promises.mkdir(t,{recursive:!0});let e=Ie();return h.existsSync(e)||await h.promises.writeFile(e,"","utf-8"),e}async function mi(){let t=await di();return ni.lock(t,{stale:1800*1e3})}async function fi(){let t=O(),e=(t?await K(t):null)??await Ot();if(!e)throw new Error("docs.zip not found");return e}async function pi(t,e){let n=await fi(),r=t.force||await je(t.force),o=await Pt(t.force);if(!r&&!o&&Bt()){await ui(e);return}if(Rt()&&!t.force){await ai(n,e),await Hn(e);return}await ci(t,n,e),await Hn(e)}var pt=class{static async run(e={}){let n=e.background??!1,o=e.quiet??n?void 0:ri({text:"Checking documentation\u2026",color:"cyan"}),i;try{i=await mi(),await Nt(He("Starting documentation setup\u2026")),await pi(e,o)}catch(s){return li(s,o)}finally{i&&await i()}}};var gi=process.env.DEVECO_CLI_POSTINSTALL?"postinstall":"doc-init";pt.run({background:!0,builtBy:gi}).catch(()=>{process.exit(1)});
65
+ `)}async function ii(t){let e=O();if(!e)throw new Error("docs.zip not found");await h.promises.rm(t,{recursive:!0,force:!0}),await h.promises.mkdir(t,{recursive:!0}),new ei(e).extractAllTo(t,!0),await zn(t)}async function si(){let t=x(),e=M(),n=await h.promises.readdir(e);for(let r of n){let o=H.join(t,r);await h.promises.rm(o,{force:!0}),await h.promises.rename(H.join(e,r),o)}await h.promises.rm(e,{recursive:!0,force:!0}),await h.promises.rm(H.join(t,"orama.dpack"),{force:!0})}async function ai(t,e){e?.start("Installing documentation index\u2026"),await R({state:"installing",phase:1,phaseLabel:"Installing index",message:"Installing documentation index\u2026"}),await Be(t),e&&(e.text="Documentation index installed.")}async function ci(t,e,n){let r=M(),o=await vn();await h.promises.mkdir(x(),{recursive:!0}),await h.promises.rm(r,{recursive:!0,force:!0}),n?.start("Building search index\u2026"),await R({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"});try{await ii(o),await Fn({docsDir:o,tmpDir:r,docsZipSha256:e,termsHash:tt(),synonymsHash:J(),builtBy:t.builtBy??"doc-init",onProgress:async i=>{n&&(n.text=i.message),await R({state:"indexing",current:i.current,total:i.total,message:i.message})}})}finally{await h.promises.rm(o,{recursive:!0,force:!0})}await R({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await si(),pn()}async function Hn(t){await R({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),t?.succeed("Documentation ready.")}async function ui(t){let e=await Lt(),n=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";t?.succeed(n),await R({state:"done",message:n,error:null})}async function li(t,e){let n=t instanceof Error?t.message:String(t);throw await R({state:"error",error:n}),await oi(`ERROR: ${n}`),e?.fail(n),t}async function di(){let t=x();await h.promises.mkdir(t,{recursive:!0});let e=Ie();return h.existsSync(e)||await h.promises.writeFile(e,"","utf-8"),e}async function mi(){let t=await di();return ni.lock(t,{stale:1800*1e3})}async function fi(){let t=O(),e=(t?await K(t):null)??await Ot();if(!e)throw new Error("docs.zip not found");return e}async function pi(t,e){let n=await fi(),r=t.force||await je(t.force),o=await Pt(t.force);if(!r&&!o&&Bt()){await ui(e);return}if(Rt()&&!t.force){await ai(n,e),await Hn(e);return}await ci(t,n,e),await Hn(e)}var pt=class{static async run(e={}){let n=e.background??!1,o=e.quiet??n?void 0:ri({text:"Checking documentation\u2026",color:"cyan"}),i;try{i=await mi(),await Nt(He("Starting documentation setup\u2026")),await pi(e,o)}catch(s){await li(s,o)}finally{i&&await i()}}};var gi=process.env.DEVECO_CLI_POSTINSTALL?"postinstall":"doc-init";pt.run({background:!0,builtBy:gi}).catch(()=>{process.exit(1)});
package/index.zip CHANGED
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deveco-test/hmos-deveco-cli",
3
- "version": "0.1.0-TD.5",
3
+ "version": "0.1.0-TD.5.1",
4
4
  "description": "HarmonyOS application development command line tool",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -45,11 +45,11 @@
45
45
  "@eslint/js": "^10.0.1",
46
46
  "@types/adm-zip": "^0.5.8",
47
47
  "@types/better-sqlite3": "^7.6.13",
48
- "@types/yauzl": "^2.10.3",
49
48
  "@types/fs-extra": "^11.0.4",
50
49
  "@types/global-agent": "^3.0.0",
51
50
  "@types/node": "^25.6.0",
52
51
  "@types/turndown": "^5.0.5",
52
+ "@types/yauzl": "^2.10.3",
53
53
  "eslint": "^10.2.1",
54
54
  "generate-license-file": "^4.2.1",
55
55
  "husky": "^9.1.7",
@@ -62,7 +62,6 @@
62
62
  },
63
63
  "dependencies": {
64
64
  "@modelcontextprotocol/sdk": "^1.29.0",
65
- "jieba-wasm": "^2.4.0",
66
65
  "@sqlite.org/sqlite-wasm": "^3.49.1-build4",
67
66
  "adm-zip": "^0.5.17",
68
67
  "axios": "1.17.0",
@@ -71,6 +70,7 @@
71
70
  "execa": "^9.6.1",
72
71
  "fs-extra": "^11.3.4",
73
72
  "global-agent": "^4.1.3",
73
+ "jieba-wasm": "^2.4.0",
74
74
  "json5": "^2.2.3",
75
75
  "mdast-util-to-string": "^4.0.0",
76
76
  "ora": "^8.2.0",
@@ -81,8 +81,8 @@
81
81
  "remark-parse": "^11.0.0",
82
82
  "smol-toml": "^1.6.1",
83
83
  "unified": "^11.0.5",
84
- "yauzl": "^3.2.0",
85
84
  "xdg-basedir": "^5.1.0",
85
+ "yauzl": "^3.2.0",
86
86
  "zod": "^4.4.3"
87
87
  },
88
88
  "optionalDependencies": {