@yinsen/deveco-cli-common 1.4.0-Test.911 → 1.4.0-Test.912
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/NOTICE +1 -1
- package/dist/cli.js +4 -4
- package/dist/internal/telemetry-upload-background.js +1 -1
- package/package.json +2 -2
- package/skills/index.json +1 -1
package/NOTICE
CHANGED
package/dist/cli.js
CHANGED
|
@@ -39,7 +39,7 @@ zYl5snR6SmrDfVmtsyz8aMqifx4gsVV2M5/owv8H3bUdOd5RbkKhzOS2Pmep0bbw
|
|
|
39
39
|
WRFUrWuQ+5ci2LLkZyIt9ffNR8W9gbmZOZZTrwSFRIT1Q433NOzCQNDjKwnekGAx
|
|
40
40
|
8o746tqqZxGCXgy2MaIIqvajhNw9Dr3NBQ8ziWyqaQBk2RrCWh6Q++Sd0b5L3RwH
|
|
41
41
|
rQ==
|
|
42
|
-
-----END CERTIFICATE-----`,yY=new hE.X509Certificate(hY),$N=[{cert:yY}];NN=new Set;xY=8e3,mE=class{constructor(e,t){this.callback=e;this.timeoutMs=t}settled=!1;timer;destroyers=[];onDestroy(e){this.destroyers.push(e)}start(){this.timer=setTimeout(()=>{this.settle(new Error(`[GRS] Connection deadline (${this.timeoutMs}ms) exceeded during CONNECT/TLS handshake`))},this.timeoutMs)}settle(e,t){if(!this.settled){if(this.settled=!0,this.timer&&clearTimeout(this.timer),e)for(let r of this.destroyers)try{r()}catch{}this.callback(e,t)}}},gE=class extends pY.Agent{connectTimeoutMs;constructor(e){super(e),this.connectTimeoutMs=e?.connectTimeoutMs??xY}createConnection(e,t){let r=e.host||e.servername||"",i=e.port||443,o=`https://${r}:${i}`,s=mY(o),a=new mE(t,this.connectTimeoutMs);if(a.start(),s){this.createConnectionViaProxy(e,s,r,i,a);return}return this.createDirectConnection(e,a,r)}createDirectConnection(e,t,r){let i=ON.connect({...e,rejectUnauthorized:!1});return t.onDestroy(()=>i.destroy()),this.attachTlsVerification(i,t,r),i}parseProxyOrSettle(e,t){try{return fE(e)}catch(r){return t.settle(new Error(`[GRS] ${r.message}`)),null}}createConnectionViaProxy(e,t,r,i,o){let s=this.parseProxyOrSettle(t,o);if(!s)return;let a=this.buildProxyHeaders(s,r,i);h(()=>`[GRS] Connecting via proxy ${s.host}:${s.port} to ${r}:${i}`);let c=dY.request({host:s.host,port:s.port,method:"CONNECT",path:`${r}:${i}`,headers:a});o.onDestroy(()=>c.destroy()),c.on("connect",(l,d)=>{if(l.statusCode!==200){d.destroy(),o.settle(new Error(`[GRS] Proxy CONNECT failed: ${l.statusCode} ${l.statusMessage||""}`));return}o.onDestroy(()=>d.destroy()),this.startTlsOverTunnel(e,d,o,r)}),c.on("error",l=>{o.settle(new Error(`[GRS] Proxy connection failed: ${l.message}`))}),c.end()}startTlsOverTunnel(e,t,r,i){h(()=>"[GRS] Proxy tunnel established, starting TLS handshake");let o=ON.connect({...e,socket:t,rejectUnauthorized:!1});r.onDestroy(()=>o.destroy()),this.attachTlsVerification(o,r,i)}buildProxyHeaders(e,t,r){let i={Host:`${t}:${r}`},o=e.auth;if(o&&(o.username||o.password)){let s=`${o.username}:${o.password}`;i["Proxy-Authorization"]=`Basic ${Buffer.from(s).toString("base64")}`}return i}attachTlsVerification(e,t,r){e.once("secureConnect",()=>{let i=PY(e,r);i?(e.destroy(i),t.settle(i)):t.settle(null,e)}),e.once("error",i=>{t.settle(i)})}},yE=new gE({keepAlive:!0})});var vE,So,bE=B(()=>{"use strict";u();vE=[{group:"com.huawei.devecostudio.region",key:"spaceintroduce"},{group:"com.huawei.devecostudio.region",key:"userinfo"},{group:"com.huawei.devecostudio.region",key:"agcsign"},{group:"com.huawei.devecostudio.region",key:"agcups"},{group:"com.huawei.devecostudio.region",key:"agreementservice"}],So=class extends Error{kind;constructor(e,t){super(t),this.name="GrsError",this.kind=e}}});async function zg(n){let e=[],t="";for(let o of AY){let s=await OY(o,n);if(s.outcome==="ok")return s.services;e.push(s.outcome),s.detail&&(t=s.detail)}if(e.some(o=>o==="incomplete"))throw new So("no-config",`GRS returned no valid configuration for country code ${n} (this region may not be supported)`);let r=process.env.HTTPS_PROXY||process.env.HTTP_PROXY,i=r?`Current proxy: ${Wg(r)}. Verify the proxy is running and allows CONNECT to grs.dbankcloud.com:443. If the proxy inspects TLS, set NODE_EXTRA_CA_CERTS to a PEM file with your corporate CA \u2014 untrusted GRS certificates are rejected.`:"No proxy configured (HTTP_PROXY/HTTPS_PROXY). If you are behind a corporate firewall, set HTTPS_PROXY=http://your-proxy:port.";throw new So("network",`GRS endpoints unreachable (grs.dbankcloud.com is globally reachable). ${i}${t?` Last endpoint error: ${t}`:""}`)}async function OY(n,e){let t=`${n}?issue_country=${encodeURIComponent(e)}&app_name=${IY}`;h(()=>`[GRS] POST ${t}`);try{let r=await ee.post(t,{headers:{"User-Agent":TY},httpsAgent:yE,timeout:DY}),i=ee.parseJson(r);return i.resultCode!==0?(h(()=>`[GRS] ${n} resultCode=${i.resultCode}, skipping`),{outcome:"incomplete",detail:`resultCode=${i.resultCode}`}):$Y(i.services)?(h(()=>`[GRS] hit ${n}, received ${Object.keys(i.services).length} service groups`),{outcome:"ok",services:i.services}):(h(()=>`[GRS] ${n} returned incomplete config (missing required service keys), skipping`),{outcome:"incomplete",detail:"missing required service keys"})}catch(r){let i=r instanceof Error?r.message:String(r);return h(()=>`[GRS] ${n} request failed: ${i}`),{outcome:"network",detail:i}}}function $Y(n){return vE.every(({group:e,key:t})=>typeof n[e]?.[t]=="string")}var AY,TY,IY,DY,SE=B(()=>{"use strict";u();Pn();P();dE();wE();bE();AY=["https://grs.dbankcloud.com/grs/2.0/router","https://grs.dbankcloud.cn/grs/2.0/router","https://grs.dbankcloud.asia/grs/2.0/router","https://grs.platform.dbankcloud.ru/grs/2.0/router"],TY="com.huawei.deveco.common-grs/0.1 (Windows;Linux;Mac) Deveco-grs/-1",IY="devecostudio",DY=8e3});function kE(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function Gg(n){let e=kE(n);if(!e)throw new p("InvalidArgument","Path must not be empty.","Path must not be empty.");return Ii(e)}var EE=B(()=>{"use strict";u();wo();zd()});import*as Zd from"fs";import*as qg from"path";import{homedir as NY}from"os";function MY(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":kE(n))||qg.join(NY(),".local","share",_Y);try{return Gg(t)}catch(r){throw new CE(r instanceof Error?r.message:String(r))}}function _(){if(LN!==void 0)return LN;let n=MY();try{if(Zd.existsSync(n))return Zd.realpathSync(n)}catch{}return n}function Jg(){return qg.join(_(),"workflow","workflows")}function FN(){return qg.join(_(),"workflow","engines")}var _Y,LN,CE,me=B(()=>{"use strict";u();EE();_Y="deveco-cli",CE=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}}});import RE from"fs";import LY from"path";function xE(n){return LY.join(_(),`grs_${n}.json`)}async function UN(n){try{let e=await RE.promises.readFile(xE(n),"utf8"),t=JSON.parse(e);return t.countryCode!==n||Date.now()-t.fetchedAt>jY?null:t}catch{return null}}async function WN(n,e){let t={services:e,fetchedAt:Date.now(),countryCode:n};try{await RE.promises.writeFile(xE(n),JSON.stringify(t),"utf8")}catch{}}async function AE(n){try{await RE.promises.unlink(xE(n))}catch{}}async function BN(n){if(n==="CN")return jN;let e=await UN(n);if(e)return e.services;let t=await zg(n);return await WN(n,t),t}var FY,jN,jY,HN,PE,te,Kg=B(()=>{"use strict";u();me();P();SE();wo();FY="com.huawei.devecostudio.region",jN={[FY]:{spaceintroduce:"https://cn.devecostudio.huawei.com",userinfo:"https://gopenuser-drcn.platform.dbankcloud.cn",agcsign:"https://connect-api.cloud.huawei.com",agcups:"https://connect-api.cloud.huawei.com",agreementservice:"https://terms-drcn.platform.dbankcloud.cn",agcdeveloper:"https://developer.huawei.com"}},jY=1440*60*1e3,HN=new Set(["CN","HK","MO"]),PE=class{countryCode="";services={};resolved=!1;isCN(){return this.countryCode==="CN"}isOnlineAllowed(){return HN.has(this.countryCode)}getService(e,t){let r=this.services[e]?.[t];if(!r)throw new p("RuntimeCondition",`GRS service ${e}.${t} not available`,"GRS service not available.");return r}setCountryCode(e){this.countryCode=e}async resolve(){if(!this.countryCode)throw new p("RuntimeCondition","Country code not set, cannot resolve GRS","Country code not set.");if(this.countryCode==="CN"){this.services=jN,this.resolved=!0,h(()=>"[GRS] CN uses hardcoded services, skipping GRS request");return}let e=await UN(this.countryCode);if(e){this.services=e.services,this.resolved=!0,h(()=>`[GRS] cache hit country=${this.countryCode}, skipping request`);return}h(()=>`[GRS] cache miss or expired, requesting GRS country=${this.countryCode}`);let t=await zg(this.countryCode);this.services=t,this.resolved=!0,await WN(this.countryCode,t)}},te=new PE});function WY(){return`CLI online services are not available in your region (detected: ${te.countryCode||"unknown"}).`}function Xt(){if(!te.isOnlineAllowed())throw new p("RuntimeCondition",WY(),"CLI online services are not available in your region.")}async function Di(){te.resolved||await te.resolve()}function ko(){return te.getService(Aa,"spaceintroduce")}async function TE(n){let t=(await BN(n))[Aa]?.spaceintroduce;if(!t)throw new p("RuntimeCondition",`GRS service ${Aa}.spaceintroduce not available`,"GRS service not available.");return t}function IE(){return`${te.getService(Aa,"agcups")}${HY}`}function Zn(){return te.getService(Aa,"agcsign")}function DE(){return`${te.getService(Aa,"agreementservice")}${UY}`}function OE(n){let e=VN[n];return e?GN(n,e):GN(zN,VN[zN])}function GN(n,e){return`${BY}/terms/scope/huawei/deveco-cli/privacy-statement.htm?code=${n}&language=${e}&branchid=0&contenttag=default`}function Yg(){return te.getService(Aa,"agcdeveloper")}var Aa,HY,UY,BY,VN,zN,$E=B(()=>{"use strict";u();Kg();wo();Aa="com.huawei.devecostudio.region",HY="/api/ups/user-permission-service/v1/user-team-list",UY="/agreementservice/user";BY="https://legal.cloud.huawei.com",VN={CN:"zh-CN",HK:"en-US",MO:"en-US"},zN="HK"});var ln=B(()=>{"use strict";u();SE();Kg();wE();bE();$E();Kg()});import qN from"crypto";import qe from"fs";import Xg from"os";import Rn from"path";function Qg(){return!Kt()&&te.isCN()}var ep,Zg=B(()=>{"use strict";u();_$();wo();H$();G$();Jt();Xd();wN();EN();ln();ep=class n{static MAX_BATCH=200;static MAX_PAYLOAD_BYTES=Math.floor(1.7*1024*1024);static TRACE_OS_VERSION="1.0";static COUNTRY_CODE="CN";static EVENT_PREFIX="devecocli_";uploader=new Ag;storageDir="";failedDir="";installId="";get disabled(){return!Qg()}traceFileKey=Buffer.alloc(0);sessionId=qN.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){v.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=Rn.join(e,"failed"),this.cliVersion="1.4.0-Test.911",this.nodeVersion=process.version,qe.mkdirSync(e,{recursive:!0}),qe.mkdirSync(this.failedDir,{recursive:!0});let t=Rn.dirname(e);this.installId=yN(t).replace(/-/g,""),this.traceFileKey=B$(t),kN(e),v.debug(`[telemetry] init: dir=${e}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(e){this.devecoStudioVersion=e,v.debug(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,v.debug(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,v.debug(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)return v.debug("[telemetry] track skipped: telemetry not initialized"),typeof t=="function"?t():void 0;if(!t){await this.record(e,0,!0,null);return}if(typeof t!="function"){let o=t;await this.record(e,o.duration_ms,o.success,o.error_code);return}let r=t,i=Date.now();try{let o=await r(),s=Date.now()-i;return await this.record(e,s,!0,null),o}catch(o){let s=Date.now()-i,a=this.resolveErrorCode(o);throw await this.record(e,s,!1,a),o}}resolveErrorCode(e){try{return U(e)}catch{return null}}async record(e,t,r,i){try{let o=this.buildTraceEvent(e,t,r,i),s=V$(JSON.stringify(o),this.traceFileKey);await qe.promises.appendFile(this.currentFile(),s+`
|
|
42
|
+
-----END CERTIFICATE-----`,yY=new hE.X509Certificate(hY),$N=[{cert:yY}];NN=new Set;xY=8e3,mE=class{constructor(e,t){this.callback=e;this.timeoutMs=t}settled=!1;timer;destroyers=[];onDestroy(e){this.destroyers.push(e)}start(){this.timer=setTimeout(()=>{this.settle(new Error(`[GRS] Connection deadline (${this.timeoutMs}ms) exceeded during CONNECT/TLS handshake`))},this.timeoutMs)}settle(e,t){if(!this.settled){if(this.settled=!0,this.timer&&clearTimeout(this.timer),e)for(let r of this.destroyers)try{r()}catch{}this.callback(e,t)}}},gE=class extends pY.Agent{connectTimeoutMs;constructor(e){super(e),this.connectTimeoutMs=e?.connectTimeoutMs??xY}createConnection(e,t){let r=e.host||e.servername||"",i=e.port||443,o=`https://${r}:${i}`,s=mY(o),a=new mE(t,this.connectTimeoutMs);if(a.start(),s){this.createConnectionViaProxy(e,s,r,i,a);return}return this.createDirectConnection(e,a,r)}createDirectConnection(e,t,r){let i=ON.connect({...e,rejectUnauthorized:!1});return t.onDestroy(()=>i.destroy()),this.attachTlsVerification(i,t,r),i}parseProxyOrSettle(e,t){try{return fE(e)}catch(r){return t.settle(new Error(`[GRS] ${r.message}`)),null}}createConnectionViaProxy(e,t,r,i,o){let s=this.parseProxyOrSettle(t,o);if(!s)return;let a=this.buildProxyHeaders(s,r,i);h(()=>`[GRS] Connecting via proxy ${s.host}:${s.port} to ${r}:${i}`);let c=dY.request({host:s.host,port:s.port,method:"CONNECT",path:`${r}:${i}`,headers:a});o.onDestroy(()=>c.destroy()),c.on("connect",(l,d)=>{if(l.statusCode!==200){d.destroy(),o.settle(new Error(`[GRS] Proxy CONNECT failed: ${l.statusCode} ${l.statusMessage||""}`));return}o.onDestroy(()=>d.destroy()),this.startTlsOverTunnel(e,d,o,r)}),c.on("error",l=>{o.settle(new Error(`[GRS] Proxy connection failed: ${l.message}`))}),c.end()}startTlsOverTunnel(e,t,r,i){h(()=>"[GRS] Proxy tunnel established, starting TLS handshake");let o=ON.connect({...e,socket:t,rejectUnauthorized:!1});r.onDestroy(()=>o.destroy()),this.attachTlsVerification(o,r,i)}buildProxyHeaders(e,t,r){let i={Host:`${t}:${r}`},o=e.auth;if(o&&(o.username||o.password)){let s=`${o.username}:${o.password}`;i["Proxy-Authorization"]=`Basic ${Buffer.from(s).toString("base64")}`}return i}attachTlsVerification(e,t,r){e.once("secureConnect",()=>{let i=PY(e,r);i?(e.destroy(i),t.settle(i)):t.settle(null,e)}),e.once("error",i=>{t.settle(i)})}},yE=new gE({keepAlive:!0})});var vE,So,bE=B(()=>{"use strict";u();vE=[{group:"com.huawei.devecostudio.region",key:"spaceintroduce"},{group:"com.huawei.devecostudio.region",key:"userinfo"},{group:"com.huawei.devecostudio.region",key:"agcsign"},{group:"com.huawei.devecostudio.region",key:"agcups"},{group:"com.huawei.devecostudio.region",key:"agreementservice"}],So=class extends Error{kind;constructor(e,t){super(t),this.name="GrsError",this.kind=e}}});async function zg(n){let e=[],t="";for(let o of AY){let s=await OY(o,n);if(s.outcome==="ok")return s.services;e.push(s.outcome),s.detail&&(t=s.detail)}if(e.some(o=>o==="incomplete"))throw new So("no-config",`GRS returned no valid configuration for country code ${n} (this region may not be supported)`);let r=process.env.HTTPS_PROXY||process.env.HTTP_PROXY,i=r?`Current proxy: ${Wg(r)}. Verify the proxy is running and allows CONNECT to grs.dbankcloud.com:443. If the proxy inspects TLS, set NODE_EXTRA_CA_CERTS to a PEM file with your corporate CA \u2014 untrusted GRS certificates are rejected.`:"No proxy configured (HTTP_PROXY/HTTPS_PROXY). If you are behind a corporate firewall, set HTTPS_PROXY=http://your-proxy:port.";throw new So("network",`GRS endpoints unreachable (grs.dbankcloud.com is globally reachable). ${i}${t?` Last endpoint error: ${t}`:""}`)}async function OY(n,e){let t=`${n}?issue_country=${encodeURIComponent(e)}&app_name=${IY}`;h(()=>`[GRS] POST ${t}`);try{let r=await ee.post(t,{headers:{"User-Agent":TY},httpsAgent:yE,timeout:DY}),i=ee.parseJson(r);return i.resultCode!==0?(h(()=>`[GRS] ${n} resultCode=${i.resultCode}, skipping`),{outcome:"incomplete",detail:`resultCode=${i.resultCode}`}):$Y(i.services)?(h(()=>`[GRS] hit ${n}, received ${Object.keys(i.services).length} service groups`),{outcome:"ok",services:i.services}):(h(()=>`[GRS] ${n} returned incomplete config (missing required service keys), skipping`),{outcome:"incomplete",detail:"missing required service keys"})}catch(r){let i=r instanceof Error?r.message:String(r);return h(()=>`[GRS] ${n} request failed: ${i}`),{outcome:"network",detail:i}}}function $Y(n){return vE.every(({group:e,key:t})=>typeof n[e]?.[t]=="string")}var AY,TY,IY,DY,SE=B(()=>{"use strict";u();Pn();P();dE();wE();bE();AY=["https://grs.dbankcloud.com/grs/2.0/router","https://grs.dbankcloud.cn/grs/2.0/router","https://grs.dbankcloud.asia/grs/2.0/router","https://grs.platform.dbankcloud.ru/grs/2.0/router"],TY="com.huawei.deveco.common-grs/0.1 (Windows;Linux;Mac) Deveco-grs/-1",IY="devecostudio",DY=8e3});function kE(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function Gg(n){let e=kE(n);if(!e)throw new p("InvalidArgument","Path must not be empty.","Path must not be empty.");return Ii(e)}var EE=B(()=>{"use strict";u();wo();zd()});import*as Zd from"fs";import*as qg from"path";import{homedir as NY}from"os";function MY(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":kE(n))||qg.join(NY(),".local","share",_Y);try{return Gg(t)}catch(r){throw new CE(r instanceof Error?r.message:String(r))}}function _(){if(LN!==void 0)return LN;let n=MY();try{if(Zd.existsSync(n))return Zd.realpathSync(n)}catch{}return n}function Jg(){return qg.join(_(),"workflow","workflows")}function FN(){return qg.join(_(),"workflow","engines")}var _Y,LN,CE,me=B(()=>{"use strict";u();EE();_Y="deveco-cli",CE=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}}});import RE from"fs";import LY from"path";function xE(n){return LY.join(_(),`grs_${n}.json`)}async function UN(n){try{let e=await RE.promises.readFile(xE(n),"utf8"),t=JSON.parse(e);return t.countryCode!==n||Date.now()-t.fetchedAt>jY?null:t}catch{return null}}async function WN(n,e){let t={services:e,fetchedAt:Date.now(),countryCode:n};try{await RE.promises.writeFile(xE(n),JSON.stringify(t),"utf8")}catch{}}async function AE(n){try{await RE.promises.unlink(xE(n))}catch{}}async function BN(n){if(n==="CN")return jN;let e=await UN(n);if(e)return e.services;let t=await zg(n);return await WN(n,t),t}var FY,jN,jY,HN,PE,te,Kg=B(()=>{"use strict";u();me();P();SE();wo();FY="com.huawei.devecostudio.region",jN={[FY]:{spaceintroduce:"https://cn.devecostudio.huawei.com",userinfo:"https://gopenuser-drcn.platform.dbankcloud.cn",agcsign:"https://connect-api.cloud.huawei.com",agcups:"https://connect-api.cloud.huawei.com",agreementservice:"https://terms-drcn.platform.dbankcloud.cn",agcdeveloper:"https://developer.huawei.com"}},jY=1440*60*1e3,HN=new Set(["CN","HK","MO"]),PE=class{countryCode="";services={};resolved=!1;isCN(){return this.countryCode==="CN"}isOnlineAllowed(){return HN.has(this.countryCode)}getService(e,t){let r=this.services[e]?.[t];if(!r)throw new p("RuntimeCondition",`GRS service ${e}.${t} not available`,"GRS service not available.");return r}setCountryCode(e){this.countryCode=e}async resolve(){if(!this.countryCode)throw new p("RuntimeCondition","Country code not set, cannot resolve GRS","Country code not set.");if(this.countryCode==="CN"){this.services=jN,this.resolved=!0,h(()=>"[GRS] CN uses hardcoded services, skipping GRS request");return}let e=await UN(this.countryCode);if(e){this.services=e.services,this.resolved=!0,h(()=>`[GRS] cache hit country=${this.countryCode}, skipping request`);return}h(()=>`[GRS] cache miss or expired, requesting GRS country=${this.countryCode}`);let t=await zg(this.countryCode);this.services=t,this.resolved=!0,await WN(this.countryCode,t)}},te=new PE});function WY(){return`CLI online services are not available in your region (detected: ${te.countryCode||"unknown"}).`}function Xt(){if(!te.isOnlineAllowed())throw new p("RuntimeCondition",WY(),"CLI online services are not available in your region.")}async function Di(){te.resolved||await te.resolve()}function ko(){return te.getService(Aa,"spaceintroduce")}async function TE(n){let t=(await BN(n))[Aa]?.spaceintroduce;if(!t)throw new p("RuntimeCondition",`GRS service ${Aa}.spaceintroduce not available`,"GRS service not available.");return t}function IE(){return`${te.getService(Aa,"agcups")}${HY}`}function Zn(){return te.getService(Aa,"agcsign")}function DE(){return`${te.getService(Aa,"agreementservice")}${UY}`}function OE(n){let e=VN[n];return e?GN(n,e):GN(zN,VN[zN])}function GN(n,e){return`${BY}/terms/scope/huawei/deveco-cli/privacy-statement.htm?code=${n}&language=${e}&branchid=0&contenttag=default`}function Yg(){return te.getService(Aa,"agcdeveloper")}var Aa,HY,UY,BY,VN,zN,$E=B(()=>{"use strict";u();Kg();wo();Aa="com.huawei.devecostudio.region",HY="/api/ups/user-permission-service/v1/user-team-list",UY="/agreementservice/user";BY="https://legal.cloud.huawei.com",VN={CN:"zh-CN",HK:"en-US",MO:"en-US"},zN="HK"});var ln=B(()=>{"use strict";u();SE();Kg();wE();bE();$E();Kg()});import qN from"crypto";import qe from"fs";import Xg from"os";import Rn from"path";function Qg(){return!Kt()&&te.isCN()}var ep,Zg=B(()=>{"use strict";u();_$();wo();H$();G$();Jt();Xd();wN();EN();ln();ep=class n{static MAX_BATCH=200;static MAX_PAYLOAD_BYTES=Math.floor(1.7*1024*1024);static TRACE_OS_VERSION="1.0";static COUNTRY_CODE="CN";static EVENT_PREFIX="devecocli_";uploader=new Ag;storageDir="";failedDir="";installId="";get disabled(){return!Qg()}traceFileKey=Buffer.alloc(0);sessionId=qN.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){v.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=Rn.join(e,"failed"),this.cliVersion="1.4.0-Test.912",this.nodeVersion=process.version,qe.mkdirSync(e,{recursive:!0}),qe.mkdirSync(this.failedDir,{recursive:!0});let t=Rn.dirname(e);this.installId=yN(t).replace(/-/g,""),this.traceFileKey=B$(t),kN(e),v.debug(`[telemetry] init: dir=${e}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(e){this.devecoStudioVersion=e,v.debug(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,v.debug(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,v.debug(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)return v.debug("[telemetry] track skipped: telemetry not initialized"),typeof t=="function"?t():void 0;if(!t){await this.record(e,0,!0,null);return}if(typeof t!="function"){let o=t;await this.record(e,o.duration_ms,o.success,o.error_code);return}let r=t,i=Date.now();try{let o=await r(),s=Date.now()-i;return await this.record(e,s,!0,null),o}catch(o){let s=Date.now()-i,a=this.resolveErrorCode(o);throw await this.record(e,s,!1,a),o}}resolveErrorCode(e){try{return U(e)}catch{return null}}async record(e,t,r,i){try{let o=this.buildTraceEvent(e,t,r,i),s=V$(JSON.stringify(o),this.traceFileKey);await qe.promises.appendFile(this.currentFile(),s+`
|
|
43
43
|
`,"utf8"),pN(this.storageDir)}catch{}}buildTraceEvent(e,t,r,i){let o=`${n.EVENT_PREFIX}${e.event}`,s=j$.toObject(e);return s&&typeof s=="object"&&delete s.event,{countryCode:n.COUNTRY_CODE,event:o,eventtime:String(Date.now()),properties:{uid:this.installId,trace_uuid:qN.randomUUID(),trace_os_version:n.TRACE_OS_VERSION,os_arch:this.resolveOsArch(),action:o,trace_os_name:this.resolveOsName(),version:`${this.cliVersion}_${this.resolveOsSuffix()}`,deveco_studio_version:this.formatVersion(this.devecoStudioVersion),command_line_version:this.formatVersion(this.cltVersion),source_type:this.sourceType,session_id:this.sessionId,node_version:this.nodeVersion,ram:this.resolveTotalRam(),duration_ms:t,success:r,error_code:i,event_detail:s}}}resolveOsArch(){let e=Xg.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=Xg.release().split(".");return(parseInt(e[e.length-1],10)||0)>=22e3?"Windows 11":"Windows 10"}case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}resolveOsSuffix(){switch(process.platform){case"win32":return"windows";case"darwin":return Xg.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(Xg.totalmem()/1024)}KB`}formatVersion(e){return e?`${e}_${this.resolveOsSuffix()}`:""}dateString(){let e=new Date,t=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0");return`${e.getFullYear()}-${t}-${r}`}currentFile(){return Rn.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){v.debug("[telemetry] scheduler not started (telemetry disabled)");return}v.debug(`[telemetry] scheduler started (flush every ${Jd/1e3}s, retry failed every ${Kd/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},Jd)},Jd),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},Kd)},Kd)}stopScheduler(){this.initialTimer&&(clearTimeout(this.initialTimer),this.initialTimer=null),this.intervalTimer&&(clearInterval(this.intervalTimer),this.intervalTimer=null),this.retryInitialTimer&&(clearTimeout(this.retryInitialTimer),this.retryInitialTimer=null),this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null),v.debug("[telemetry] scheduler stopped")}async flush(){return this.disabled?!0:this.runExclusive(()=>this.performFlush())}async performFlush(){if(!this.storageDir)return v.debug("[telemetry] flush skipped: telemetry not initialized"),!0;let e=await this.listPendingFiles(),t=!0;for(let r of e)await this.flushFile(r)||(t=!1);return fN(this.storageDir),t}async retryFailed(){return this.disabled?!0:this.runExclusive(()=>this.performRetryFailed())}async performRetryFailed(){if(!this.storageDir)return v.debug("[telemetry] retryFailed skipped: telemetry not initialized"),!0;await this.reclaimStalePending();let e=Date.now(),t;try{t=await qe.promises.readdir(this.failedDir)}catch{return!0}let r=t.filter(o=>o.startsWith("telemetry-")&&o.endsWith(".txt")).map(o=>Rn.join(this.failedDir,o)),i=!0;for(let o of r){let s=Rn.basename(o),a=cE(s);if(a!==null){if(e-a>oE){try{await qe.promises.unlink(o)}catch{}continue}await this.flushFile(o)||(i=!1)}}return i||v.warn("[telemetry] retry failed"),mN(this.storageDir),i}async reclaimStalePending(){let e=Date.now();for(let t of[this.storageDir,this.failedDir]){let r;try{r=await qe.promises.readdir(t)}catch{continue}for(let i of r)Yd(i)&&await this.reclaimOrphan(Rn.join(t,i),e)}}async reclaimOrphan(e,t){let r;try{let l=await qe.promises.stat(e);if(t-l.mtimeMs<sE)return;r=l.size}catch{return}let i=Rn.dirname(e),o=lE(Rn.basename(e));if(o===null)return;let s=await this.claimOrphan(e,i,o);if(s===null)return;let a=Rn.join(i,o),c=ul-await this.fileSize(a);if(r>c){try{await qe.promises.unlink(s)}catch{}v.warn(`[telemetry] dropped stale orphan pending: ${s} (${r} bytes > budget ${c})`);return}if(await this.mergeOrphanInto(s,a)){v.warn(`[telemetry] reclaimed orphan pending: ${s} (${r} bytes)`);return}v.warn(`[telemetry] merge failed, kept orphan pending for retry: ${s} (${r} bytes)`)}async claimOrphan(e,t,r){let i=Rn.join(t,`${r}.pending.reclaim-${process.pid}-${Date.now()}`);try{await qe.promises.rename(e,i)}catch{return null}return await this.touch(i),i}async mergeOrphanInto(e,t){try{await qe.promises.appendFile(t,await qe.promises.readFile(e))}catch(r){return v.warn(`[telemetry] merge orphan pending failed: ${e} -> ${t}: ${r instanceof Error?r.message:String(r)}`),!1}try{await qe.promises.unlink(e)}catch(r){v.warn(`[telemetry] merged but failed to remove orphan pending: ${e}: ${r instanceof Error?r.message:String(r)}`)}return!0}async fileSize(e){try{return(await qe.promises.stat(e)).size}catch{return 0}}async touch(e){let t=new Date;try{await qe.promises.utimes(e,t,t)}catch{}}runExclusive(e){let t=()=>e(),r=this.flushChain.then(t,t);return this.flushChain=r.then(()=>{},()=>{}),r}async listPendingFiles(){let e;try{e=await qe.promises.readdir(this.storageDir)}catch{return[]}return e.filter(t=>t.startsWith("telemetry-")&&t.endsWith(".txt")).map(t=>Rn.join(this.storageDir,t)).sort()}async flushFile(e){let t=await this.fileSize(e);if(t>ul){v.warn(`[telemetry] ${Rn.basename(e)} is ${t} bytes (> ${ul}), dropped without uploading`);try{await qe.promises.unlink(e)}catch{}return!0}let r=e+".pending";try{await qe.promises.rename(e,r)}catch{return!1}await this.touch(r);let i;try{i=await qe.promises.readFile(r,"utf8")}catch{return!1}let o=i.split(`
|
|
44
44
|
`).map(s=>s.trim()).filter(Boolean);if(o.length===0){try{await qe.promises.unlink(r)}catch{}return!0}return this.uploadInBatches(r,o)}collectDecryptBatch(e,t){let r=[],i=16,o=t;for(;o<e.length&&r.length<n.MAX_BATCH;){let s=z$(e[o],this.traceFileKey);if(s===null){o++;continue}let a=Buffer.byteLength(s,"utf8")+1;if(r.length>0&&i+a>n.MAX_PAYLOAD_BYTES)break;r.push(s),i+=a,o++}return{batch:r,next:o}}async uploadInBatches(e,t){let r=0;for(;r<t.length;){let i=r,{batch:o,next:s}=this.collectDecryptBatch(t,r);r=s;let a=this.buildPayloadItems(o);if(a.length===0)continue;let c=JSON.stringify(a),l=!1;try{l=await this.uploader.upload(c,this.installId)}catch{}if(!l){v.warn("[telemetry] upload failed");let d=t.slice(i).join(`
|
|
45
45
|
`)+`
|
|
@@ -70,7 +70,7 @@ ${o.stdout}`),this.parseCrashLogFilenames(o.stdout,r)}parseCrashLogFilenames(e,t
|
|
|
70
70
|
`).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>{try{return H.assertCrashFilename(r),!0}catch{return!1}}).filter(r=>t?r.toLowerCase().includes(t.toLowerCase()):!0)}async fetchCrashLogContent(e,t,r){h(`Fetching latest crash log file: ${r}`);let i=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];h(`Executing command: ${e} ${i.join(" ")}`);let o=await this.runHilogStreamingCollect(e,i,"a crash log streaming read"),s=Wa(o,"Failed to fetch crash log content");if(s)throw s;return o.exitCode!==0&&o.stderr&&console.error(`Warning: Failed to fetch crash logs: ${o.stderr}`),o.stdout+o.stderr}}});var GM={};xg(GM,{resolveDeviceSerial:()=>$});async function $(n,e){let r=await new Es(n).selectDevice(e);if(!r)throw new p("RuntimeCondition","No device selected. Use `devecocli device list` to see targets.","No device selected.");return r}var it=B(()=>{"use strict";u();ry();E()});u();import*as zk from"path";import{program as ke}from"commander";import{red as V_e}from"colorette";u();Je();import{Command as O3}from"commander";import{green as Gh,red as F_,yellow as NC}from"colorette";import L_ from"json5";import*as kp from"fs";import*as j_ from"path";u();import{join as l4}from"path";var tp="https://developer.huawei.com/consumer/cn/doc/doccenter-deveco-studio/ide-publish-app#section1079214271414",gr={CERT_LIST_PATH:"/api/cps/harmony-cert-manage/v1/cert/list",CERT_DELETE_PATH:"/api/cps/harmony-cert-manage/v1/cert/delete",CERT_ADD_PATH:"/api/cps/harmony-cert-manage/v1/cert/add",CERT_DOWNLOAD_URL_PATH:"/api/amis/app-manage/v1/objects/url/reapply",DEVICE_ADD_PATH:"/api/cps/device-manage/v1/device/add",DEVICE_LIST_PATH:"/api/cps/device-manage/v1/device/list",PROVISION_ADD_TEST_PATH:"/api/cps/provision-manage/v1/ide/test/provision/add",PROVISION_DELETE_PATH:"/api/cps/provision-manage/v1/provision/delete"},An={CERT_NAME_PREFIX:"auto_debug_",CERT_TYPE_DEBUG:"1",TEAM_ID_INVALID_CHARS:/[\\/.:]/g,CERT_PATTERN:/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/,TARGET_FRIENDLY_NAME:"debugKey",CERTIFICATE_PATTERN_GLOBAL:/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g,BUNDLE_NAME_REGEX:/^[a-zA-Z][a-zA-Z0-9._-]*$/,CERT_BEGIN_HEADER:"-----BEGIN CERTIFICATE-----",CERT_SAVE_DIR:l4(".ohos","config"),DOWNLOAD_CONNECT_TIMEOUT_MS:5e3},Lt={SUCCESS_MARKER:'"code":0',SQUARE_BRACKETS:"[]",OPENPROXY_BLOCKED_URL:"Openproxy_Blocked_URL_list",CERT_LIMIT_CODE:"205389872",USER_NOT_HARMONY_CODE:"205389904",DEVICE_EXCEEDS_LIMIT_CODE:"205389859",DEVICE_NAME_REPEAT_CODE:"205389857",PROVISION_EXCEEDS_LIMIT_CODE:"205389938",PROVISION_NAME_REPEAT_CODE:"205389830"},Gr={FORBIDDEN:403,UNAUTHORIZED:401},j={ERR_FORBIDDEN:"You do not have AppGallery Connect permissions for the current team. Request access from the team administrator or switch to a team where you have permissions.",ERR_UNAUTHORIZED:"Invalid AccessToken. Sign in and try again.",ERR_CERT_LIMIT_REACHED:"The number of certificates has reached the limit. Delete some certificates and try again.",ERR_CERT_NETWORK_ERROR:"Ensure the external network connection is available before downloading the certificate.",ERR_CERT_INVALIDATE:"The downloaded .cer file is invalid. Try again.",ERR_DOWNLOAD_CER:"Failed to download the certificate file. Check the following configurations: Network connection, HTTP Proxy, etc.",ERR_USER_NOT_HARMONY:"The user is not in harmony allow list, please grant the permission",ERR_READ_CSR:"Failed to read the .csr file, please try again later",ERROR_WHILE_ADD_DEVICE:"Failed to add the device, please try again.",DEVICE_LIMIT_REACHED:"The number of devices has reached the limit. Delete some unused devices and try again.",DEVICE_NAME_REPEAT:"Duplicate device name, please try again.",DEVICE_LIST_EMPTY:"No devices available.",ADD_PROFILE_FAIL:"Failed to add the profile, please try again.",NO_AGC_PERMISSION:"You do not have the AppGallery Connect permission with the current team. Apply for the permission form the team administrator, or switch to a team with which you already have the permission.",ERROR_WHILE_DOWNLOAD_PROFILE:"Failed to download the profile, please try again.",PROFILE_NAME_REPEAT:"The profile name already exists in the AGC.",ERROR_WHILE_PARSE_PROFILE:"Failed to parse the profile, please try again.",TEST_PROVISION_EXCEEDS_LIMIT:"Provision number exceeds limit.",CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT:"The certificate application file is inconsistent with the file in profile, please try again.",CERTIFICATE_HAS_EXPIRED:"The signature does not take effect or has expired. It may be the current system time is inaccurate, please calibrate the system time and sign again.",ERROR_SIGN_BUNDLE_NAME_VALIDATE:"The bundle name contains 7 to 128 characters, including only letters, digits, and underscores (_). It must be start with a letter and contain at least three segments separated by periods (.), each of the segments ending with a digit or letter."},at={REGION_CHINA_ONLY:"Testing commands are available only in mainland China.",TOOLCHAIN_INIT_FAILED:"Auto-sign failed: unable to initialize toolchain",LOGIN_REQUIRED:"Failed to automatically generate signatures.Run devecocli auth login to sign in.",TEAM_INFO_FAILED:"Failed to obtain user team information.Check the network connection, HTTP proxy, and other configurations.",REALNAME_REQUIRED:"Users without real-name verification are not supported.Complete real-name verification in AppGallery Connect.",SESSION_EXPIRED:"User session expired or token invalid. Please login again.",DEVICE_MISSING:"Unable to create the profile file due to missing devices.Connect a device through IP or USB, or manually add a device in AppGallery Connect first.If you are installing the HAP package on an emulator, you can skip the signing step.",DEVICE_DETECT_FAILED:"Unable to detect devices. Please check hdc status. If installing HAP on an emulator, signature step can be skipped.",PROJECT_DIR_MISSING:"Not in a valid project directory (project-level build-profile.json5 not found).",ATOMIC_SERVICE_UNSUPPORTED:"AtomicService projects are not yet supported. Please configure signing manually."};u();u();import aC from"fs/promises";import vr from"path";u();E();function Tn(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new p("InvalidArgument",`Unsafe skill name: ${JSON.stringify(n)}`,"Unsafe skill name.")}u();import sh from"fs";import Co from"path";import{homedir as l0}from"os";u();E();import Ft from"fs/promises";import In from"path";import{randomUUID as i0}from"crypto";import{setTimeout as u4}from"timers/promises";var d4=[20,40,80,160];async function et(n){try{return await Ft.lstat(n)}catch(e){if(e.code==="ENOENT")return;throw e}}async function We(n){let e=In.resolve(n),t=In.dirname(e);try{return In.join(await Ft.realpath(t),In.basename(e))}catch(r){if(r.code!=="ENOENT"||t===e)throw r;return In.join(await We(t),In.basename(e))}}async function UE(n,e){for(let t of d4)try{await Ft.rename(n,e);return}catch(r){let i=r.code;if(process.platform!=="win32"||i!=="EPERM"&&i!=="EBUSY")throw r;await u4(t)}await Ft.rename(n,e)}async function WE(n,e){let t=`${e}.backup-${i0()}`,r=await et(e);r&&await UE(e,t);try{await UE(n,e)}catch(i){if(r)try{await UE(t,e)}catch(o){throw new AggregateError([i,o],`Skill directory publication failed (${String(i)}). Backup restoration failed (${String(o)}). Backup retained at ${t}.`,{cause:o})}throw i}r&&await Ft.rm(t,{recursive:!0,force:!0})}async function BE(n,e){let t=()=>Ft.rm(n,{recursive:!0,force:!0}),r;try{r=await e()}catch(i){try{await t()}catch(o){throw new AggregateError([i,o],`${String(i)} Staging directory cleanup failed (${String(o)}).`,{cause:o})}throw i}return await t(),r}function ge(n,e){let t=r=>In.resolve(r).replace(/^\\\\\?\\/,"").replace(/[\\/]+$/,"");return process.platform==="win32"?t(n).toLowerCase()===t(e).toLowerCase():t(n)===t(e)}function pl(n,e){let t=(r,i)=>{let o=In.relative(r,i);return o===""||!o.startsWith(`..${In.sep}`)&&o!==".."&&!In.isAbsolute(o)};return t(n,e)||t(e,n)}async function o0(n){try{let e=JSON.parse(await Ft.readFile(In.resolve(n,"..","..","package.json"),"utf8"));return e.name?.includes("deveco-cli")?e.version:void 0}catch{return}}async function rh(n,e,t=!1){let r=await Ft.realpath(n);if(!(await Ft.stat(r)).isDirectory())throw new p("RuntimeCondition",`Skill source is not a directory: ${n}`,"Skill source is not a directory.");let i=await We(e),o=await et(i),s=await o0(r);if(ge(r,i))return qr(i,"same-source");let a=o?await Ft.realpath(i).catch(()=>i):i;if(o?.isSymbolicLink()&&ge(r,a))return qr(i,"correct-link",{detail:a,sourceVersion:s});if(!t&&o){let l=await p4(i,o);return qr(i,l.reason,{...l,sourceVersion:s})}if(pl(r,i)||o&&pl(r,a))throw new p("Internal",`Skill source and destination overlap: ${n}, ${e}`,"Skill source and destination overlap.");await Ft.mkdir(In.dirname(i),{recursive:!0});let c=`${i}.install-${i0()}`;return BE(c,async()=>{let l=await f4(r,c);return await WE(c,i),{success:!0,path:i,...l}})}function qr(n,e,t={}){return{success:!0,skipped:!0,path:n,reason:e,...t}}async function s0(n,e){if(!e&&await et(n))return qr(n,"already-exists")}async function p4(n,e){if(!e.isSymbolicLink())return{reason:"already-exists",detail:e.isDirectory()?"directory":"file"};let t=await Ft.realpath(n).catch(()=>null);return t===null?{reason:"broken-link",detail:await Ft.readlink(n).catch(()=>{})}:{reason:"linked-elsewhere",detail:t,localVersion:await o0(t)}}async function f4(n,e){try{let t=process.platform==="win32"?n:In.relative(In.dirname(e),n);return await Ft.symlink(t,e,process.platform==="win32"?"junction":"dir"),{mode:"symlink"}}catch(t){return await Ft.rm(e,{recursive:!0,force:!0}),await Ft.cp(n,e,{recursive:!0,dereference:!0,errorOnExist:!0,force:!1}),{mode:"copy",fallbackReason:t.code??String(t)}}}async function ih(n){let e=await We(n),t=await et(e);return t?(await Ft.rm(e,{recursive:!t.isSymbolicLink(),force:!0}),{success:!0,path:e}):qr(e,"not-installed")}zE();E();function Ta(n){return Co.resolve(n==="~"||n.startsWith("~/")?Co.join(l0(),n.slice(1)):n)}function ct(){return Object.keys(fl)}function hs(n){return n!=="deveco"}function np(n){return[...new Set((n??"").split(",").map(e=>e.trim()).filter(Boolean))]}function rp(n){return np(n).filter(e=>hs(e)&&Object.hasOwn(fl,e))}function tr(n){let e=Object.prototype.hasOwnProperty.call(fl,n)?fl[n]:void 0;if(!e)throw new p("Internal",`Invalid agent: ${n}, Valid options are: ${ct().filter(hs).join(", ")}`,"Invalid agent.");return e}function ah(n){return Ta(tr(n).globalSkillsDir)}function GE(n,e){return Co.join(n,tr(e).skillsDir)}function nr(n){return Co.join(n??l0(),oh)}function yr(n,e){return e?GE(e,n):ah(n)}function qE(n,e){let t=tr(n);if(!e){let r=t.legacyGlobalSkillsDirs?.[0];return r?Ta(r):ah(n)}return Co.join(e,u0(n))}function u0(n){let e=tr(n);return e.legacySkillsDirs?.[0]||e.skillsDir}function JE(n,e){let t=u0(n);if(t===oh)return!0;let r=t.split("/")[0];return r.startsWith(".")&&sh.existsSync(Co.join(e,r))}function KE(n,e){let t=yr(n,e);return ge(t,nr(e))}function d0(n,e){let t=tr(n),r=e?(t.legacySkillsDirs??[]).map(o=>Co.join(e,o)):(t.legacyGlobalSkillsDirs??[]).map(Ta),i=[yr(n,e)];return r.filter(o=>i.some(s=>ge(s,o))?!1:(i.push(o),!0))}function ch(n,e){let t=tr(e).skillsDir.split("/")[0];return t.startsWith(".")&&sh.existsSync(Co.join(n,t))}function Ia(n,e){let t=tr(n);if(t.detect)return t.detect.some(o=>sh.existsSync(Ta(o)));let r=ah(n);return![nr(),ah("universal")].some(o=>ge(o,r))&&sh.existsSync(Co.dirname(r))?!0:!!(e&&t.skillsDir!==oh&&ch(e,n))}u();import lh from"path";function p0(n){let e=[];n.agents.length&&e.push({agents:[...new Set(n.agents)]});let t=new Map;for(let{project:r,agent:i}of n.projectAgents){let o=t.get(r)??[];o.push(i),t.set(r,o)}for(let[r,i]of t)e.push({project:r,agents:[...new Set(i)]});return e}async function g4(n,e,t,r){let i=[];for(let o of d0(n,e.project)){let s=await We(lh.join(o,t));!r.some(a=>ge(a,s))&&await et(s)&&i.push(s)}return i}async function ip(n,e,t=!0){let r=await We(lh.join(nr(n.project),e)),i=[];for(let o of n.agents){let s=yr(o,n.project),a=await We(lh.join(s,e)),c=await g4(o,n,e,[r,a]),l=!!(n.project&&!t&&!KE(o,n.project)&&c.length===0&&!ch(n.project,o)),d=i.find(g=>ge(g.path,a));d?(d.legacy.push(...c.filter(g=>!d.legacy.some(y=>ge(y,g)))),d.skipped&&=l):i.push({path:a,legacy:c,skipped:l})}return i}async function f0(n,e,t=!0){let r=await ip(n,e,t);if(r.every(o=>o.skipped))return r;let i=await We(lh.join(nr(n.project),e));return r.some(o=>ge(o.path,i))||r.unshift({path:i,legacy:[],skipped:!1}),r}u();me();import up from"fs/promises";import wr from"path";import{randomUUID as R4}from"crypto";import{lock as x4}from"proper-lockfile";u();ml();Pn();import b4 from"adm-zip";import S4 from"crypto";import{timingSafeEqual as k4}from"crypto";import E4 from"fs";import ws from"path";u();Pn();ml();import*as A0 from"fs";import*as T0 from"path";E();var I0=["DevEco"];async function ph(){let n=await ee.get(hr.TAGS_API_URL),t=gh(n,"Tags API").data.skill.filter(r=>r.name==="HMOS");if(t.length===0)throw new p("RuntimeCondition","No HMOS tag found.","No HMOS tag found.");return t.map(r=>r.id)}async function w4(n){let e=[],t=hr.DEFAULT_PAGE_SIZE,r=hr.DEFAULT_MAX_PAGES,i=1;for(;i<=r;){let o=await ee.post(hr.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:i,pageSize:t,tagIds:[n]}}),s=gh(o,"Skills API");if(e.push(...s.data.list),s.data.list.length<t)break;i++}return e}async function fh(n){let e=new Map,t=n.map(i=>w4(i)),r=await Promise.all(t);for(let i of r)for(let o of i)e.has(o.id)||e.set(o.id,o);return Array.from(e.values()).filter(i=>i.tags?.every(o=>!I0.includes(o.name)))}async function v4(n,e){let t=await ee.post(hr.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:hr.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return gh(t,"Skills API").data.list}async function mh(n,e){let t=new Map,r=e.map(o=>v4(n,o)),i=await Promise.all(r);for(let o of i)for(let s of o)t.has(s.id)||t.set(s.id,s);return Array.from(t.values()).filter(o=>o.tags?.every(s=>!I0.includes(s.name)))}function ZE(n){Tn(n);let e=[];for(let t of ct()){let r=yr(t);if(!Ia(t))continue;let i=T0.join(r,n);A0.existsSync(i)&&e.push(tr(t).displayName)}return e.sort()}function gh(n,e){if(n.statusCode!==200)throw new p("Internal",`${e} Request failed: HTTP ${n.statusCode}`,"API request failed.");let t=ee.parseJson(n);if(t.code!==hr.SUCCESS_CODE)throw new p("Internal",`${e} Error returned: ${t.code} - ${t.message}`,"API error returned.");return t}async function D0(n){Tn(n);let e=`${hr.SKILL_API_BASE}/${n}/checksum`,t=await ee.get(e);return gh(t,"Checksum API").data}E();var O0=E4.promises;function $0(n,e){let t=ws.resolve(e),r=ws.resolve(n),i=ws.relative(r,t);if(i.startsWith("..")||ws.isAbsolute(i))throw new p("InvalidArgument",`Path traversal detected: ${e}.`,"Path traversal detected.")}function eC(n){return ws.isAbsolute(n)?n:ws.resolve(process.cwd(),n)}function C4(n){return S4.createHash("sha256").update(n).digest("hex")}async function P4(n,e){if(n.length!==e.size)throw new p("Internal","Skill zip integrity verification failed: Size mismatch","Skill zip integrity verification failed.");let r=C4(n),i=e.sha256.toLowerCase(),o=Buffer.from(r,"hex"),s=Buffer.from(i,"hex");if(o.length!==s.length||!k4(o,s))throw new p("Internal","Skill zip integrity verification failed: SHA256 mismatch","Skill zip integrity verification failed.")}async function tC(n){Tn(n);let e=`${hr.SKILL_API_BASE}/${n}/install?format=zip`,t=await ee.getBinary(e),r=await D0(n);return await P4(t,r),t}async function N0(n,e,t){Tn(t);let r=new b4(n),i=r.getEntries();try{await O0.stat(e)}catch{await O0.mkdir(e,{recursive:!0})}let o=ws.join(e,t);$0(e,o);for(let s of i){let a=ws.join(o,s.entryName);$0(o,a)}r.extractAllTo(o,!0)}E();function nC(n){return n?wr.join(n,".deveco-cli","skills"):wr.join(_(),"skills")}function A4(n,e){return Tn(n),wr.join(nC(e),"store",n)}async function rC(n,e){let t=e??_(),r=await up.realpath(t).catch(s=>{if(s.code==="ENOENT")return We(t);throw s}),i=wr.join(r,wr.relative(t,n)),o=await We(i);if(!ge(i,o))throw new p("Internal",`Skill storage parent redirects outside its managed location: ${i}`,"Skill storage parent redirects outside its managed location.");return o}async function hh(n,e){return rC(A4(n,e),e)}async function yh(n,e){return Tn(n),rC(wr.join(nC(e),"consumers",`${n}.json`),e)}async function dp(n,e,t){Tn(n);let r=e.customPath??nC(e.project),i=e.customPath?await We(wr.join(r,`.${n}.lock`)):await rC(wr.join(r,"locks",`${n}.lock`),e.project);await up.mkdir(wr.dirname(i),{recursive:!0});let o=await x4(r,{realpath:!1,lockfilePath:i,stale:3e4,update:1e4,retries:{retries:100,minTimeout:50,maxTimeout:200}});try{return await t()}finally{await o()}}async function _0(n){let e=await up.lstat(n);if(!e.isDirectory()||e.isSymbolicLink()||!(await up.stat(wr.join(n,"SKILL.md"))).isFile())throw new p("InvalidArgument",`Invalid Skill store: ${n}`,"Invalid Skill store.")}async function M0(n,e,t,r,i){let o=await hh(n,t),s=await et(o);if(!i&&!s&&(await Promise.all(r.map(c=>et(c.path)))).every(Boolean))return{results:r.map(c=>qr(c.path,"already-exists"))};for(let a of r)for(let c of[a.path,...a.legacy])if(pl(o,c))throw new p("Internal",`Skill store and destination overlap: ${o}, ${c}`,"Skill store and destination overlap.");if(!i&&s){try{await _0(o)}catch(a){throw new p("Internal",`Cannot reuse Skill store ${o}; use --force to replace: ${a.message}`,"Cannot reuse Skill store.",{cause:a})}return{source:o,results:[]}}return{source:o,results:[await F0(n,e,o)]}}async function L0(n,e,t,r){let i=await We(t);return await s0(i,r)??F0(n,e,i)}async function F0(n,e,t){await up.mkdir(wr.dirname(t),{recursive:!0});let r=`${t}.extract-${R4()}`;return BE(r,async()=>{await N0(e,r,n);let i=wr.join(r,n);return await _0(i),await WE(i,t),{success:!0,path:t,reason:"shared-entity-updated"}})}u();import{randomUUID as T4}from"crypto";import gl from"fs/promises";import I4 from"path";E();async function wh(n){let e=await et(n);if(!e)return!1;if(!e.isFile()||e.isSymbolicLink()||e.nlink!==1)throw new p("InvalidArgument",`Invalid Skill consumer record: ${n}`,"Invalid Skill consumer record.");return!0}function D4(n){if(!n||typeof n!="object"||Array.isArray(n))throw new p("InvalidArgument","Invalid Skill consumer record structure.","Invalid Skill consumer record structure.");let e=n,t=e.agents;if(e.schemaVersion!==1||Object.keys(e).some(i=>i!=="schemaVersion"&&i!=="agents")||!t||typeof t!="object"||Array.isArray(t))throw new p("InvalidArgument","Invalid Skill consumer record structure.","Invalid Skill consumer record structure.");let r=ct();for(let[i,o]of Object.entries(t))if(!r.includes(i)||typeof o!="boolean")throw new p("InvalidArgument",`Invalid Skill consumer: ${i}`,"Invalid Skill consumer.");return t}async function iC(n,e){let t=await yh(n,e);return await wh(t)?D4(JSON.parse(await gl.readFile(t,"utf8"))):{}}async function j0(n,e,t){let r=await yh(n,e);await wh(r),await gl.mkdir(I4.dirname(r),{recursive:!0});let i=`${r}.write-${T4()}`;try{await gl.writeFile(i,JSON.stringify({schemaVersion:1,agents:t},null,2)+`
|
|
71
71
|
`,{flag:"wx",mode:384}),await wh(r),await gl.rename(i,r)}finally{await gl.rm(i,{force:!0})}}async function H0(n,e){let t=await yh(n,e);await wh(t)&&await gl.unlink(t)}u();function oC(n){return n?`the bundled skill (deveco-cli ${n})`:"this skill's source"}var U0={"same-source":()=>({status:"destination is the skill source itself",action:"nothing to do"}),"correct-link":({detail:n,sourceVersion:e})=>({status:`already linked to ${e?`the bundled skill (deveco-cli ${e})`:"this skill"}${n?` \u2192 ${n}`:""}`,action:"nothing to do"}),"already-exists":({detail:n,sourceVersion:e})=>({status:`already exists as a ${n??"directory or file"} with unknown version, not a link to ${oC(e)}`,action:"use --force to replace it"}),"broken-link":({detail:n,sourceVersion:e})=>({status:`existing link is broken${n?` \u2014 its target ${n} no longer exists`:""}`,action:`use --force to replace it with ${oC(e)}`}),"linked-elsewhere":({detail:n,localVersion:e,sourceVersion:t})=>({status:e&&e===t?`links to ${n} (another deveco-cli ${e} installation), not this installation's bundled skill`:`links to ${n??"another location"}${e?` (deveco-cli ${e})`:""}, not ${oC(t)}`,action:"use --force to replace it"}),"agent-project-root-missing":()=>({status:"agent has no project directory in this project"}),"not-installed":()=>({status:"not installed",action:"nothing to remove"})};function W0(n){let e=U0[n.reason??""];if(!e)return n.reason;let{status:t,action:r}=e(n);return r?`${t}; ${r}`:t}function B0(n){return U0[n.reason??""]?.(n).status??n.reason}E();function pp(n,e){return{success:!1,path:n,error:e instanceof Error?e.message:String(e)}}async function sC(n,e,t){let r=[];for(let i of p0(e))try{r.push(...await dp(n,i,()=>t(i)))}catch(o){r.push(pp(vr.join(nr(i.project),n),o))}return r}async function z0(n){return aC.realpath(n).catch(e=>{if(e.code==="ENOENT"||e.code==="ELOOP")return n;throw e})}async function O4(n,e){let t=await aC.realpath(e);for(let r of n.legacy){let i=await et(r);if(i&&!i.isSymbolicLink()&&pl(t,r))throw new p("Internal",`Skill source and legacy destination overlap: ${e}, ${r}`,"Skill source and legacy destination overlap.");await ih(r)}}async function $4(n,e,t,r,i={}){let o=[],s=await We(vr.join(nr(e.project),n));for(let a of ct()){let c=yr(a,e.project);if(e.agents.includes(a))continue;let l=await We(vr.join(c,n)),d=ge(l,s),g=d?i[a]:void 0;if(g===!1)continue;let y=g===!0,k=Ia(a,e.project);if(d&&!y&&!k)continue;let D=await et(l);D&&(ge(l,t)&&(y||k)||r&&(y||ge(l,r)||D.isSymbolicLink()&&ge(await z0(l),r)))&&o.push(tr(a).displayName)}return[...new Set(o)]}function N4(n,e,t=console.log){let r=`still used by ${e.join(", ")}`;return t(`Skill ${vr.basename(n)} in ${vr.dirname(n)} is kept: ${r}.`),qr(n,r)}function _4(n,e,t=console.log){return t(`Skill ${n} not found for the selected agents.`),qr(e,"not-installed")}async function V0(n,e,t,r,i={},o={}){try{if(!await et(n))return;let s=await $4(e,t,n,r,o);return s.length?N4(n,s,i.log):await ih(n)}catch(s){return pp(n,s)}}var rr=class{async installBundledSkill(e,t,r,i=!1){return Tn(e),await aC.access(vr.join(t,"SKILL.md")),r.customPath?this.installCustom(e,t,r.customPath,i):sC(e,r,o=>this.installScope(e,t,o,r.explicitAgents,i))}async installArchiveSkill(e,t,r,i=!1,o={}){return Tn(e),r.customPath?this.installCustom(e,t,r.customPath,i,o):sC(e,r,s=>this.installScope(e,t,s,r.explicitAgents,i,o))}async installCustom(e,t,r,i,o={}){let s=vr.join(r,e);try{return await dp(e,{customPath:r},async()=>(await this.validateEntries([s],o),[typeof t=="string"?await rh(t,s,i):await L0(e,t,s,i)]))}catch(a){return[pp(s,a)]}}async installScope(e,t,r,i=!0,o=!1,s={}){let a=await f0(r,e,i),c=a.filter(d=>!d.skipped),l=a.filter(d=>d.skipped).map(d=>qr(d.path,"agent-project-root-missing"));if(!c.length)return l;try{let d=await iC(e,r.project);await this.validateScopeEntries(e,r,c,s);let g=[...l,...await this.installActive(e,t,r,c,o)];return await this.recordSharedConsumers(e,r,g,d,!0),g}catch(d){return[...l,...c.map(g=>pp(g.path,d))]}}async installActive(e,t,r,i,o){let s=typeof t=="string"?{source:t,results:[]}:await M0(e,t,r.project,i,o);return[...s.results,...s.source?await this.installSkillEntries(s.source,i,o):[]]}async recordSharedConsumers(e,t,r,i,o){let s=await We(vr.join(nr(t.project),e)),a=!1;for(let c of t.agents){let l=await We(vr.join(yr(c,t.project),e));!r.some(g=>g.path&&ge(g.path,l)&&g.success)||i[c]===o||!ge(l,s)&&!Object.hasOwn(i,c)||(i[c]=o,a=!0)}a&&await j0(e,t.project,i)}async validateEntries(e,t,r){if(!t.validateExisting)return;let i=await Promise.all(e.map(We));for(let o of new Set(i))await et(o)&&await t.validateExisting(o,r)}async validateScopeEntries(e,t,r,i){if(!i.validateExisting)return;let o=await hh(e,t.project),s=await We(vr.join(nr(t.project),e)),a=r.filter(c=>!c.skipped).flatMap(c=>[c.path,...c.legacy]);await this.validateEntries([...a,s,o],i,o)}async installSkillEntries(e,t,r){let i=[];for(let o of t)try{i.push(await rh(e,o.path,r)),r&&await O4(o,e)}catch(s){i.push(pp(o.path,s))}return i}async migrateBundledSkill(e,t,r){await dp(e,r,()=>this.migrateBundledScope(e,t,r))}async migrateBundledScope(e,t,r){let i,o=[],s=[];for(let a of r.agents)try{for(let c of await ip({...r,agents:[a]},e))await this.migrateBundledDestination(t,c,o,s)}catch(c){i=c,console.error(`Skill migration failed for ${a}: ${c.message}`)}if(s.length>0&&console.warn(`Skill migration skipped: ${e} has ${s.length} existing ${s.length===1?"entry":"entries"} (run devecocli init --force to replace):
|
|
72
72
|
${s.map(a=>`${a.path} (${B0(a)})`).join(`
|
|
73
|
-
`)}`),i)throw i}async migrateBundledDestination(e,t,r,i){let o=await et(t.path);if(!((!o||!o.isDirectory()&&!o.isSymbolicLink())&&!t.legacy.length)&&!r.some(s=>ge(s,t.path))){let s=await rh(e,t.path);s.skipped&&s.reason!=="correct-link"&&s.reason!=="same-source"&&i.push(s),r.push(t.path)}}async removeSkill(e,t,r={}){if(Tn(e),t.customPath){let i=vr.join(t.customPath,e);return dp(e,t,async()=>(await this.validateEntries([i],r),[await ih(i)]))}return sC(e,t,async i=>{let o=await iC(e,i.project);if(r.validateExisting){let s=await ip(i,e,t.explicitAgents);await this.validateScopeEntries(e,i,s,r)}return this.removeScope(e,i,t.explicitAgents,r,o)})}async removeScope(e,t,r=!0,i={},o={}){let s=await We(vr.join(nr(t.project),e)),a=await hh(e,t.project),c=await this.removeAgentEntries(e,t,s,a,r,i,o);for(let l of[s,a]){if(!c.every(g=>g.success))break;let d=await V0(l,e,t,await z0(l),i,o);d&&c.push(d)}return c.length||c.push(_4(e,s,i.log)),await this.completeConsumerRemoval(e,t,s,a,c,o),c}async completeConsumerRemoval(e,t,r,i,o,s){if(!await et(r)&&!await et(i)){await H0(e,t.project);return}await this.recordSharedConsumers(e,t,o,s,!1)}async removeAgentEntries(e,t,r,i,o,s,a){let c=new Set;for(let d of await ip(t,e,o))if(!d.skipped)for(let g of[d.path,...d.legacy])!ge(g,r)&&!ge(g,i)&&c.add(g);let l=[];for(let d of c){let g=await V0(d,e,t,void 0,s,a);g&&l.push(g)}return l}};u();import U4 from"p-limit";u();E();import vh from"fs";import Oa from"path";import{fileURLToPath as M4}from"url";function cC(){let n=Oa.dirname(M4(import.meta.url));for(;;){if(vh.existsSync(Oa.join(n,"skills","deveco-cli","SKILL.md")))return Oa.join(n,"skills");let e=Oa.dirname(n);if(e===n)break;n=e}throw new p("RuntimeCondition","skills/deveco-cli directory not found in deveco-cli package. Reinstall deveco-cli.","BundledSkillsAnchorMissing")}function hl(){cC()}function L4(n){return n.sort((e,t)=>e==="deveco-cli"?-1:t==="deveco-cli"?1:e.localeCompare(t))}function F4(n){let e=vh.readdirSync(n,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).map(t=>t.name).filter(t=>vh.existsSync(Oa.join(n,t,"SKILL.md")));return L4(e).map(t=>({name:t,dir:Oa.join(n,t)}))}function br(){return F4(cC())}function yl(n){try{return br().some(e=>e.name===n)}catch{return!1}}function j4(n){try{let e=JSON.parse(n);return Array.isArray(e.skills)?e.skills.filter(t=>typeof t=="object"&&t!==null).filter(t=>typeof t.name=="string").map(t=>({name:t.name,...typeof t.description=="string"?{description:t.description}:{}})):[]}catch{return[]}}function lC(){try{let n=Oa.join(cC(),"index.json");return j4(vh.readFileSync(n,"utf8"))}catch{return[]}}function uC(){let n=new Map(lC().map(e=>[e.name,e]));return br().map(({name:e})=>({name:e,description:n.get(e)?.description}))}function H4(n,e){let t=new Set(e);return n.filter(r=>!t.has(r.name)).map(r=>r.name)}function G0(n){return`Warning: bundled skill "${n}" is listed in the package index but missing from disk. The package may be corrupted \u2014 reinstall deveco-cli.`}function q0(){try{let n=lC();if(n.length===0)return[];let e=br().map(t=>t.name);return H4(n,e)}catch{return[]}}function $a(n=q0()){for(let e of n)console.warn(G0(e))}E();async function J0(n,e){try{let t=await ph();return await n(t)}catch(t){return e?.(t instanceof Error?t.message:"network error"),[]}}function K0(n){return n.map(e=>({...e,bundled:yl(e.enName)}))}function Y0(n,e){let t=new Set(n.map(r=>r.enName));return[...n,...e.filter(r=>!t.has(r.enName))]}var Na=class{constructor(e=[]){this.providers=e}catalog(){return this.mergeCatalog(this.providers.map(e=>e.catalog()))}search(e){return this.mergeCatalog(this.providers.flatMap(t=>t.search(e)))}async listCatalog(e){let t=K0(this.catalog()),r=await J0(fh,e);return Y0(t,r)}async findCatalog(e,t){let r=K0(this.search(e)),i=await J0(o=>mh(e,o),t);return Y0(r,i)}mergeCatalog(e){let t=new Map;for(let r of e)t.has(r.name)||t.set(r.name,{enName:r.name,description:r.description??""});return[...t.values()]}async resolveNames(e){if(e.skill&&this.provider(e.skill))return[e.skill];let t=await ph();if(e.all)return(await fh(t)).map(o=>o.enName);let i=(await mh(e.skill,t)).find(o=>o.enName===e.skill);if(!i)throw new p("InvalidArgument",`Skill "${e.skill}" not found`,"Skill not found.");return[i.enName]}async installSkills(e,t,r,i){let o=U4(5),s=e.map(l=>o(()=>this.prepareArchive(l))),a=[],c=0;for(let[l,d]of e.entries()){let g={name:d,index:l,total:e.length};i({...g,phase:"installing"});let y=await s[l];if(!y.success){i({...g,phase:"download-failed",error:y.error}),a.push({success:!1});continue}c+=y.buffer?.length??0,i({...g,phase:"ready"});let k=this.provider(d);a.push(...k?await k.installForTargets(d,t,r):await new rr().installArchiveSkill(d,y.buffer,t,r))}return{results:a,diskBytes:c}}removeSkill(e,t,r=!1){let i=this.provider(e);return i?i.uninstallForTargets(e,t,r):new rr().removeSkill(e,t)}provider(e){return this.providers.find(t=>t.handles(e))}async prepareArchive(e){try{return{success:!0,buffer:this.provider(e)?void 0:await tC(e)}}catch(t){return{success:!1,error:t instanceof Error?t.message:"unknown error"}}}};u();E();var bh=class{constructor(e){this.skill=e}handles(e){return e===this.skill.name}catalog(){return{name:this.skill.name,aliases:[],description:this.skill.description}}search(e){let t=e.trim().toLowerCase(),r=`${this.skill.name} ${this.skill.description??""}`.toLowerCase();return!t||r.includes(t)?[this.catalog()]:[]}installForTargets(){return Promise.reject(new p("InvalidArgument",`Skill "${this.skill.name}" is bundled with deveco-cli. Bundled skills are installed by devecocli init and update with the CLI package.`,"Skill is bundled with deveco-cli."))}uninstallForTargets(){return Promise.reject(new p("InvalidArgument",`Skill "${this.skill.name}" is bundled with deveco-cli and cannot be removed. Bundled skills are managed by the CLI package and update with npm update.`,"Skill is bundled with deveco-cli and cannot be removed."))}};function dC(){try{return uC().map(n=>new bh(n))}catch{return[]}}u();import pC from"fs/promises";import W4 from"path";function B4(n){return`'${process.platform==="win32"?n.replace(/'/g,"''"):n.replace(/'/g,"'\\''")}'`}async function V4(n,e,t){try{if(!(await et(n))?.isSymbolicLink())return;let i=await pC.realpath(n);return ge(i,e)?void 0:{path:n,reason:`points to ${i}`,repairAgent:t}}catch(r){let i=r.code,o=i==="ENOENT"||i==="ELOOP"||i==="ENOTDIR";return{path:n,reason:o?"broken link":`cannot check: ${r.message}`,repairAgent:o?t:void 0}}}var fC=class{checked=new Set;async warnInvalidBundledLinks(e){try{let t=await pC.realpath(e),r=process.platform==="win32"?t.toLowerCase():t;if(this.checked.has(r))return;this.checked.add(r);let i=await this.checkKnownEntries(t,br());this.reportIssues(t,i)}catch(t){console.warn(`Cannot check project Skill links for ${e}: ${t.message}`)}}async checkKnownEntries(e,t){let r=new Map([[nr(e),"universal"]]);for(let o of ct().filter(hs)){let s=GE(e,o);r.has(s)||r.set(s,o)}let i=[];for(let o of t){let s=await pC.realpath(o.dir),a=[];for(let[c,l]of r){let d=await this.checkDirectoryEntry(W4.join(c,o.name),s,l,a);d&&i.push(d)}}return i}async checkDirectoryEntry(e,t,r,i){try{let o=await We(e);return i.some(s=>ge(s,o))?void 0:(i.push(o),await V4(o,t,r))}catch(o){return{path:e,reason:`cannot check: ${o.message}`}}}reportIssues(e,t){let r=new Set;for(let i of t)console.warn(`Project Skill link: ${i.path} (${i.reason}).`),i.repairAgent&&r.add(i.repairAgent);r.size&&(console.warn(`Run: devecocli init --agent ${[...r].join(",")} --project ${B4(e)} -f`),console.warn("Existing copies and local edits in the selected installation scope will be replaced."))}},On=new fC;u();import wC from"fs";import n_ from"path";import{cyan as o8}from"colorette";me();u();u();P();me();_a();import{spawn as e8}from"child_process";import*as t_ from"fs";import*as kh from"path";import{yellow as t8,cyan as n8}from"colorette";import r8 from"proper-lockfile";u();var X0={name:"@yinsen/deveco-cli-common",version:"1.4.0-Test.911",description:"HarmonyOS application development command line tool",supportedDocsApi:1,license:"MIT",type:"module",files:["dist","templates","src/resources","!src/resources/**/*.test.ts","NOTICE","skills"],scripts:{prebuild:"node ../../scripts/sync-cli-docs.mjs",build:"npm run build -w design2arkts-engine && tsup",dev:"tsx watch src/cli.ts",start:"tsx src/cli.ts","prebundle:skills":"node ../../scripts/sync-cli-docs.mjs","bundle:skills":"tsx scripts/bundle-skills.ts","precheck:skills":"node ../../scripts/sync-cli-docs.mjs","check:skills":"tsx scripts/bundle-skills.ts --check","check:pack":"node ../../scripts/check-pack.mjs",test:"vitest run",lint:'eslint "src/**/*.ts"',"lint:fix":"eslint src --fix",format:"prettier --write src",prepack:"node ../../scripts/sync-cli-docs.mjs",prepublishOnly:"npm run lint && npm run build && npm run check:skills && npm run check:pack"},engines:{node:">=22"},os:["darwin","linux","win32"],cpu:["x64","arm64"],keywords:["harmonyos","deveco","cli"],dependencies:{"@agentclientprotocol/sdk":"^2.4.0","@ai-sdk/anthropic":"^4.0.99","@ai-sdk/openai":"^4.0.111","@ai-sdk/openai-compatible":"^3.0.87","@modelcontextprotocol/sdk":"^1.29.0","@xmldom/xmldom":"^0.8.15","adm-zip":"0.6.1",ai:"^7.0.166",axios:"1.20.0",colorette:"^2.0.20",commander:"^13.1.0",execa:"^9.6.1","fs-extra":"^11.3.4","global-agent":"^4.1.3","hypium-driver":"6.1.210",json5:"^2.2.3",mp4box:"^2.4.1","node-forge":"^1.4.0",ora:"^9.4.0","p-limit":"^5.0.0","proper-lockfile":"^4.1.2","proxy-from-env":"^2.1.0",semver:"^7.8.5","smol-toml":"^1.6.1","socket.io-client":"^4.7.5","ui-verification-mcp":"0.0.21",ws:"^8.21.1",xpath:"^0.0.35",yaml:"^2.9.1",zod:"^4.4.3","@yinsen/deveco-cli-knowledgebase":"1.4.0-Test.910"},devDependencies:{"@types/adm-zip":"^0.5.8","@types/fs-extra":"^11.0.4","@types/global-agent":"^3.0.0","@types/node-forge":"^1.3.14","@types/proper-lockfile":"^4.1.4","@types/semver":"^7.7.1","@types/ws":"^8.18.2","design2arkts-engine":"0.1.0"}};E();function fp(){return process.env.DEVECO_CLI_WRAPPER_NAME?process.env.DEVECO_CLI_WRAPPER_NAME:"@yinsen/deveco-cli-common"}function $n(){return process.env.DEVECO_CLI_WRAPPER_VERSION?process.env.DEVECO_CLI_WRAPPER_VERSION:"1.4.0-Test.911"}function vs(){return"test-v2"}function mC(){return"@yinsen/deveco-cli-common"}function Sr(){return Number.isFinite(1),1}var Ro=(()=>{let n=Object.keys(X0.dependencies).find(e=>e.endsWith("/deveco-cli-knowledgebase"));if(!n)throw new p("Internal","CLI package.json must declare a deveco-cli-knowledgebase dependency.","CLI package.json must declare a deveco-cli-knowledgebase dependency.");return n})();function vl(){let n=process.env.DEVECO_CLI_DISABLE_UPDATE;return n==="check"||n==="all"?n:"off"}u();P();import*as mp from"fs";import*as gp from"path";var q4={lastCheckedTimestamp:null,latestVersion:null,blockedVersions:[],checkError:null,latestDocsVersion:null,latestDocsApiVersion:null,latestCompatibleDocsVersion:null,checkedAgainstDocsApi:null},gC=new Map,bs=class n{static CHECK_WINDOW_HOUR=21;static ONE_DAY_MS=1440*60*1e3;cacheFilePath;lockFilePath;constructor(e){this.cacheFilePath=gp.join(e,"cache.json"),this.lockFilePath=gp.join(e,"check.lock")}async writeSuccess(e,t=[],r,i,o){let s=this.read();await this.write({lastCheckedTimestamp:Date.now(),latestVersion:e,blockedVersions:t,checkError:null,checkedAgainstVersion:r,checkedAgainstTag:i,latestDocsVersion:o?o.latestDocsVersion:s.latestDocsVersion??null,latestDocsApiVersion:o?o.latestDocsApiVersion:s.latestDocsApiVersion??null,latestCompatibleDocsVersion:o?o.latestCompatibleDocsVersion:s.latestCompatibleDocsVersion??null,checkedAgainstDocsApi:o?o.checkedAgainstDocsApi:s.checkedAgainstDocsApi??null})}async writeError(e){let t=this.read();await this.write({...t,lastCheckedTimestamp:Date.now(),checkError:e})}getLatestVersion(){return this.read().latestVersion}getBlockedVersions(){return[...this.read().blockedVersions]}getCheckedAgainstVersion(){return this.read().checkedAgainstVersion}getCheckedAgainstTag(){return this.read().checkedAgainstTag}getLatestDocsVersion(){return this.read().latestDocsVersion??null}getLatestDocsApiVersion(){return this.read().latestDocsApiVersion??null}getLatestCompatibleDocsVersion(){return this.read().latestCompatibleDocsVersion??null}getCheckedAgainstDocsApi(){return this.read().checkedAgainstDocsApi??null}isCheckNeeded(){let{lastCheckedTimestamp:e}=this.read();if(!e||e>Date.now())return!0;let t=new Date().setHours(n.CHECK_WINDOW_HOUR,0,0,0),r=t>Date.now()?t-n.ONE_DAY_MS:t;return e<r}getLockPath(){return this.lockFilePath}read(){let e=gC.get(this.cacheFilePath);if(e)return e;try{let t=mp.readFileSync(this.cacheFilePath,"utf-8"),r=JSON.parse(t);return gC.set(this.cacheFilePath,r),r}catch{return{...q4}}}async write(e){h(()=>`Writing update cache: lastChecked=${e.lastCheckedTimestamp}, latest=${e.latestVersion}, blocked=[${e.blockedVersions.join(",")}], error=${e.checkError}`),await mp.promises.mkdir(gp.dirname(this.cacheFilePath),{recursive:!0}),await mp.promises.writeFile(this.cacheFilePath,JSON.stringify(e,null,2),"utf-8"),gC.set(this.cacheFilePath,e)}};u();me();P();import{createRequire as J4}from"module";import{dirname as K4,join as bl}from"path";import{pathToFileURL as Y4}from"url";import{readFile as Q0,access as hC}from"fs/promises";import*as Z0 from"semver";E();var X4=J4(import.meta.url);async function Q4(){try{let n=X4.resolve(`${Ro}/package.json`),e=JSON.parse(await Q0(n,"utf8"));return{version:e.version,apiVersion:e.apiVersion??0,dir:K4(n)}}catch{return null}}async function e_(){let n=_(),e=bl(n,"doc-data","current.json"),t;try{t=JSON.parse(await Q0(e,"utf8"))}catch{return null}let r=bl(n,"doc-data",t.version);try{return await hC(bl(r,"dist","engine","index.js")),await hC(bl(r,"docs.zip")),await hC(bl(r,"index.zip")),{version:t.version,apiVersion:t.apiVersion,dir:r}}catch{return null}}async function Z4(){return[await e_(),await Q4()].filter(e=>e!==null).sort((e,t)=>Z0.rcompare(e.version,t.version))}async function Sl(){let n=Sr(),e=await e_();return e&&e.apiVersion<=n?e.version:null}async function Sh(){let n=Sr(),e=await Z4(),t=!1;for(let r of e){if(r.apiVersion>n){h(`docs: skip candidate v${r.version} (apiVersion ${r.apiVersion} > ${n})`);continue}t=!0;try{let i=bl(r.dir,"dist","engine","index.js");return await import(Y4(i).href)}catch(i){h(`docs: candidate v${r.version} load failed: ${i instanceof Error?i.message:String(i)}`)}}throw e.length>0&&!t?new p("RuntimeCondition","Documentation package version is incompatible, please upgrade CLI","Incompatible docs package."):new p("RuntimeCondition","No available documentation package, please run `devecocli docs update` or reinstall CLI","Docs package missing.")}u();_a();function Ma(n,e){return e===null||Li(n,e)>0}var hp=class{constructor(e){this.actionCommand=e}cache=new bs(kh.join(_(),"update"));async checkAndNotify(){if(!this.shouldSkip())try{let e=$n(),t=vs(),r=this.cache.getCheckedAgainstVersion(),i=this.cache.getCheckedAgainstTag(),o=i!=null&&i!==t,s=r!=null&&r!==e,a=[],c=o?null:this.cache.getLatestVersion();c&&Li(c,e)>0&&a.push(t8(`New cli version ${c} available, run \`devecocli update\` to update`));let l=await this.buildDocsMessage();if(l.message&&a.push(l.message),a.length>0){console.error();for(let d of a)console.error(d)}(o||s||l.stale||this.cache.isCheckNeeded())&&await this.spawnBackgroundCheck()}catch(e){h(`Update check failed: ${e instanceof Error?e.message:String(e)}`)}}async buildDocsMessage(){let e=Sr(),t=this.cache.getCheckedAgainstDocsApi();if(t!=null&&t!==e)return{message:null,stale:!0};let r=this.cache.getLatestCompatibleDocsVersion();if(!r)return{message:null,stale:!1};let i=await Sl();return Ma(r,i)?{message:n8(`New docs version ${r} available, run \`devecocli docs update\` to upgrade`),stale:!1}:{message:null,stale:!1}}shouldSkip(){let e=this.actionCommand;for(;e;){if(e.name()==="update")return!0;e=e.parent}return!1}async spawnBackgroundCheck(){if(!process.argv[1]?.endsWith(".ts"))try{await i8(this.cache.getLockPath(),()=>{let e=[process.argv[1],"update","_check"];h(`Executing: ${process.execPath} ${e.join(" ")}`),e8(process.execPath,e,{detached:!0,windowsHide:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1"}}).unref()})}catch{h("Update check lock held by another process, skipping")}}};async function i8(n,e){await t_.promises.mkdir(kh.dirname(n),{recursive:!0});let t=await r8.lock(n,{stale:6e4,retries:0,realpath:!1});try{await e()}finally{await t()}}E();var yC=wC.promises;async function Eh(n){let e=np(n);for(let t of e)tr(t);return e}async function Ch(n){return ct().filter(e=>Ia(e,n))}async function s8(){let n=new rr,e=ct().filter(hs),t=[];for(let{name:r,dir:i}of br())try{await n.migrateBundledSkill(r,i,{agents:e})}catch(o){t.push({name:r,error:o})}if(t.length>0){let r=t.map(({name:i,error:o})=>`${i}: ${o instanceof Error?o.message:String(o)}`).join("; ");throw new p("Internal",`Bundled skill migration failed \u2014 ${r}`,"Bundled skill migration failed.")}}async function r_(){try{let n=n_.join(_(),"skills","migration-version"),e=await yC.readFile(n,"utf8").catch(r=>{if(r.code==="ENOENT")return"";throw r}),t=$n();if(e.trim()===t)return;await s8(),await yC.mkdir(n_.dirname(n),{recursive:!0}),await yC.writeFile(n,t,"utf8")}catch(n){console.warn(`Bundled skill migration failed (will retry on the next command): ${n instanceof Error?n.message:String(n)}`)}}function kl(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(o8("Finished:"));for(let i of n){if(!i.path)continue;let o=W0(i),s=i.fallbackReason?" (link failed: "+i.fallbackReason+")":o??i.error?" ("+(o??i.error)+")":"",a=i.success?i.skipped?"skipped":i.mode??(i.reason==="shared-entity-updated"?"updated":"removed"):"failed";console.log(" "+a+": "+i.path+s)}console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function Jr(n,e,t){if(!wC.existsSync(n)){if(t)return;throw new p("InvalidArgument",`${e} "${n}" not found`,"Directory not found.")}if(!wC.statSync(n).isDirectory())throw new p("InvalidArgument",`"${n}" is not a directory`,"Path is not a directory.")}function El(n,e,t){if(n&&(e||t))throw new p("InvalidArgument","Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?eC(n):void 0,resolvedProject:e?eC(e):void 0}}async function Ph(n,e,t="No agents found. Install an AI agent (cursor, opencode, etc.) or use `--path` for a custom location."){let r=n.agent?await Eh(n.agent):await Ch(e);if(!r.length)throw new p("RuntimeCondition",t,"NoAgentsFound");return r.map(i=>({agent:i,directory:yr(i,e),explicit:!!n.agent}))}async function yp(n,e,t){if(e)return{agents:[],projectAgents:[],customPath:e};let r=await Ph(n,t),i=r.some(o=>o.explicit);return t?{agents:[],explicitAgents:i,projectAgents:r.map(({agent:o})=>({project:t,agent:o}))}:{agents:r.map(({agent:o})=>o),projectAgents:[],explicitAgents:i}}async function vC(n,e,t){let r=await yp(n,e,t);if(r.customPath)return r;let i=r.agents.filter(hs),o=r.projectAgents.filter(({agent:s})=>hs(s));return i.length||o.length?{...r,agents:i,projectAgents:o}:void 0}u();cp();E();import a8 from"fs";import Rh from"path";import{cyan as c8}from"colorette";import*as xh from"smol-toml";var Cl=a8.promises;async function l8(n){try{let e=await Cl.readFile(n,"utf8");return e.trim()===""?{}:JSON.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new p("Internal",`Failed to read configuration file ${n}: ${e.message}`,"Failed to read configuration file.",{cause:e})}}async function u8(n){try{let e=await Cl.readFile(n,"utf8");return e.trim()===""?{}:xh.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new p("Internal",`Failed to read TOML config file ${n}: ${e.message}`,"Failed to read TOML config file.",{cause:e})}}async function d8(n,e){let t=Rh.dirname(n);await Cl.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await Cl.writeFile(n,r,"utf8")}async function p8(n,e){let t=Rh.dirname(n);await Cl.mkdir(t,{recursive:!0});let r=xh.stringify(e);await Cl.writeFile(n,r,"utf8")}function f8(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function m8(n,e,t,r,i){(!n[e]||typeof n[e]!="object")&&(n[e]={});let o=n[e];return t in o&&!i?!1:(o[t]=r,!0)}async function g8(n,e){return n.format==="codex"?u8(e):l8(e)}async function h8(n,e,t){return n.format==="codex"?p8(e,t):d8(e,t)}function i_(n={}){return{force:n.force??!1,withHomegraph:n.withHomegraph??!1}}function y8(n,e,t,r,i){let o=[],s=[],a=!1,c=(l,d)=>{if(f8(n,e.mcpServersKey,l)&&!r){s.push(l);return}m8(n,e.mcpServersKey,l,d,r),o.push(l),a=!0};return c(XE,QE(e,t)),i&&c(C0,x0(e,t)),{changed:a,configured:o,skipped:s}}async function o_(n,e,t,r,i,o){try{let s=await g8(e,t),{changed:a,configured:c,skipped:l}=y8(s,e,r,o.force,o.withHomegraph);return a?(await h8(e,t,s),console.log(`MCP server(s) ${c.join(", ")} configured in ${t}.`),{success:!0,configPath:t,agentName:n,installType:i}):(console.log(`MCP already configured in ${t} (${l.join(", ")}).`),{success:!0,skipped:!0,configPath:t,agentName:n,installType:i})}catch(s){return{success:!1,error:`Failed to configure MCP for ${e.displayName}: ${s.message}`}}}async function bC(n,e={}){let t=i_(e),r=Po[n];return r?r.supportsGlobal?o_(n,r,r.globalConfigPath,void 0,"global",t):{success:!1,error:`${r.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`}:{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Po).join(", ")}`}}async function Ah(n,e,t={}){let r=i_(t),i=Po[n];if(!i)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Po).join(", ")}`};let o=Rh.isAbsolute(i.projectConfigPath)?i.projectConfigPath:Rh.join(e,i.projectConfigPath);return o_(n,i,o,e,"project",r)}function SC(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(c8("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`);for(let i of n)!i.success&&i.error&&console.error(` - ${i.agentName??"unknown"}: ${i.error}`);r>0&&(process.exitCode=1)}u();cp();import w8 from"fs";import v8 from"path";import{homedir as b8}from"os";E();async function kC(n,e){let t=[],r=n.agent?np(n.agent):Object.keys(dh);for(let i of r){if(!Object.prototype.hasOwnProperty.call(dh,i))throw new p("InvalidArgument",`Invalid MCP agent: ${i}`,"Invalid MCP agent.");(n.agent||w8.existsSync(v8.join(b8(),dh[i])))&&t.push(i)}if(!t.length)throw new p("Internal","No agents supporting MCP configuration found; use --skill","No agents supporting MCP configuration found.");return e?{agents:[],projectAgents:t.map(i=>({project:e,agent:i}))}:{agents:t,projectAgents:[]}}u();wp();u();P();Oi();import{execa as G8}from"execa";import*as h_ from"net";import*as Rl from"path";import*as $h from"fs";import*as Nh from"os";u();import*as Oh from"path";function Pl(n){let e=Oh.dirname(n.javaPath);return{...process.env,PATH:`${e}${Oh.delimiter}${process.env.PATH||""}`,DEVECO_SDK_HOME:n.sdkPath}}E();var _h="module",ir=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let i=Pl(e),o=Nh.platform()==="darwin"&&e.javaPath==="/usr/bin/java";e.sourceType==="clt"&&e.javaPath&&!o&&(i.JAVA_HOME=Rl.dirname(Rl.dirname(e.javaPath))),this.env=i}async sync(e,t){let r=["--sync","-p",`product=${e}`,"-p",`buildMode=${t}`];return this.runHvigor(r)}async buildProduct(e,t,r=!1){let i=["assembleApp","-p",`product=${e}`,"-p",`buildMode=${t}`];return r&&i.push("-p","debugLine=true"),this.runHvigor(i)}async buildModules(e,t,r,i,o=!1){let s=[...Array.from(i),"--mode","module","-p",`module=${r.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`];return o&&s.push("-p","debugLine=true"),this.runHvigor(s)}async clean(e,t){let r=["clean","--mode",e??_h];return t&&t.length>0&&r.push("-p",`module=${t.join(",")}`),this.runHvigor(r)}async stopDaemon(){return this.runHvigor(["--stop-daemon"])}async ensureDaemonRunning(){if(this.findProjectDaemon()){h("[HvigorAdapter] Daemon already running.");return}h("[HvigorAdapter] No daemon running, starting via --sync --daemon (no hap build)."),await this.runHvigor(["--sync","--daemon"])}isDaemonRunning(e){return this.findProjectDaemon(e)!==null}async isDaemonAlive(e){let t=this.findProjectDaemon(e);return t?this.isPortListening(t.port):!1}isPortListening(e){return new Promise(t=>{let r=new h_.Socket;r.setTimeout(2e3),r.once("connect",()=>{r.destroy(),t(!0)}),r.once("error",()=>t(!1)),r.once("timeout",()=>{r.destroy(),t(!1)}),r.connect(e,"127.0.0.1")})}findProjectDaemon(e){let t=this.getDaemonRegistryPath();if(!$h.existsSync(t))return null;try{let r=$h.readFileSync(t,"utf-8"),i=JSON.parse(r),o=e??this.projectRoot,s=Object.values(i).filter(a=>a.cwdPath===o&&(a.state==="idle"||a.state==="half_busy"||a.state==="busy")&&this.isProcessAlive(a.pid));return s.length>0?s[s.length-1]:null}catch{return null}}getDaemonRegistryPath(){let e=process.env.HVIGOR_USER_HOME||Rl.join(Nh.homedir(),".hvigor");return Rl.join(e,"daemon","cache","daemon-sec.json")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}async compileNative(e,t){let r=["--mode","module"];return t&&r.push("-p",`module=${t}`),r.push("-p",`product=${e}`,"compileNative"),this.runHvigor(r)}async runHvigor(e){let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];h(`Executing: ${t} ${r.join(" ")}`);let i=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit",o=this.silent&&process.env.DEVECO_CLI_DEBUG?process.stderr:i,s=G8(t,r,{cwd:this.projectRoot,env:this.env,stdout:o,stderr:i,windowsHide:!0}),a=Kt()?void 0:dl(s.pid,2e3,!0),c="";try{await s}finally{if(a){let l=await a.stop();l>0&&(c=Qt(l),h(`Hvigor peak memory: ${c}`))}}return c}};u();P();Oi();E();import{execa as q8}from"execa";var xl=class{toolProvider;projectRoot;peakMemoryMb="";constructor(e,t){this.toolProvider=e,this.projectRoot=t}async install(){let e=this.toolProvider.nodePath,t=[this.toolProvider.ohpmJsPath,"install"];h(`Executing: ${e} ${t.join(" ")}`);let r=q8(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"}),i=Kt()?void 0:dl(r.pid,2e3,!1);try{await r}finally{if(i){let o=await i.stop();o>0&&(this.peakMemoryMb=Qt(o))}}}};u();import{mkdir as J8}from"fs/promises";import{dirname as K8,resolve as Y8}from"path";import{execa as X8}from"execa";import{lock as xC,check as hBe}from"proper-lockfile";function AC(n){return Y8(n,".hvigor",".build-lock")}function Q8(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function y_(n){let e=K8(AC(n));if(await J8(e,{recursive:!0}),process.platform==="win32")try{await X8("attrib",["+h",e])}catch{}}async function Z8(n,e){let t=new AbortController,r=Q8(e);await y_(n);let i={lockfilePath:AC(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await xC(n,{...i,retries:0}),signal:t.signal}}catch(s){if(s&&typeof s=="object"&&"code"in s&&s.code!=="ELOCKED")throw s}return r(),{release:await xC(n,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function To(n,e,t){let{release:r,signal:i}=await Z8(n,t);try{return await e(i)}finally{await r()}}async function Mh(n,e){let t=new AbortController;await y_(n);let r={lockfilePath:AC(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},i;try{i=await xC(n,{...r,retries:0})}catch(o){if(o&&typeof o=="object"&&"code"in o&&o.code==="ELOCKED")return{acquired:!1};throw o}try{return{acquired:!0,result:await e(t.signal)}}finally{await i()}}u();P();import Fa from"fs";import*as he from"path";import{execa as n3}from"execa";u();P();import w_ from"fs";import*as v_ from"path";import e3 from"json5";function t3(n,e){try{let r=e3.parse(w_.readFileSync(n,"utf-8")).modules?.find(i=>i.name===e);return r?.srcPath?r.srcPath.replace(/^\.\//,""):null}catch(t){return h(`[apply] resolveModuleSrcPath fallback (module=${e}): ${t.message}`),null}}function _n(n,e){let t=v_.join(n,"build-profile.json5");return w_.existsSync(t)?t3(t,e)??e:e}u();P();Je();import Be from"fs";import*as Te from"path";import TC from"json5";var b_="default",kr=class n{static writeChangedFileLists(e,t,r,i){let o=t||b_,s=n.loadBuildProfile(e);if(!s)return{writtenModules:[],skippedFiles:r};let a=s.modules,c=n.filterRunnableModules(e,a);if(c.length===0)return{writtenModules:[],skippedFiles:r};let l=n.buildReverseDependencyMap(e,a),d=n.createCollectors(c),g=n.collectChanges(r,e,a,l,d);return{writtenModules:n.flushCollectors(e,o,c,d,i),skippedFiles:g}}static initEmptyChangedFileLists(e,t,r){let i=t||b_,o=n.loadBuildProfile(e);if(!o)return[];let s=o.modules,a=[];for(let c of s){let l=n.getModuleType(e,c.srcPath);if(l!=="entry"&&l!=="shared")continue;let d=!r||c.name===r;n.initEmptyForModule(e,i,c.srcPath,d),a.push(c.name)}return a}static filterRunnableModules(e,t){return t.filter(r=>{let i=n.getModuleType(e,r.srcPath);return i==="entry"||i==="shared"})}static createCollectors(e){let t=new Map;for(let r of e)t.set(r.name,{hotReloadEntries:[],patchEtsFiles:[],patchRawFiles:[],patchResFiles:[],nativeFiles:[]});return t}static collectChanges(e,t,r,i,o){let s=[];for(let a of e){let c=Te.normalize(a),l=n.classifyFile(c,t,r);if(l.fileClass==="unknown"){s.push(c);continue}let d=n.findModuleByFilePath(c,t,r);if(!d){s.push(c);continue}let g=n.resolveTargetModules(d,t,r,i);if(g.length===0){s.push(c);continue}n.dispatchToCollectors(g,o,c,l,d.srcPath,t)}return s}static resolveTargetModules(e,t,r,i){let o=n.getModuleType(t,e.srcPath);return o==="entry"||o==="shared"?[e.name]:Array.from(n.findTopLevelConsumers(e.name,i,t,r))}static dispatchToCollectors(e,t,r,i,o,s){for(let a of e){let c=t.get(a);c&&n.addFileToCollector(c,r,i.fileClass,o,s)}}static flushCollectors(e,t,r,i,o){let s=[];for(let a of r){let c=i.get(a.name);if(!c||!n.hasAnyChange(c))continue;(!o||a.name===o)&&c.hotReloadEntries.length>0&&n.writeApplyFile(e,a.srcPath,t,c.hotReloadEntries),n.writePatchFile(e,a.srcPath,t,c.patchEtsFiles,c.patchRawFiles,c.patchResFiles),s.push(a.name)}return s}static hasAnyChange(e){return e.hotReloadEntries.length>0||e.patchEtsFiles.length>0||e.patchRawFiles.length>0||e.patchResFiles.length>0||e.nativeFiles.length>0}static initEmptyForModule(e,t,r,i){let o=n.patchChangedFileListPath(Te.join(e,r),t);if(Be.existsSync(o)||(Be.mkdirSync(Te.dirname(o),{recursive:!0}),Be.writeFileSync(o,JSON.stringify({resources:{resFile:[],rawFile:[]},modifiedFiles:[]}),"utf-8")),!i)return;let s=Te.join(e,r,"build",t,"intermediates","hotReload"),a=Te.join(s,"changedFileList.json");Be.existsSync(a)||(Be.mkdirSync(s,{recursive:!0}),Be.writeFileSync(a,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=Te.join(e,"build-profile.json5");if(!Be.existsSync(t))return null;try{let r=Be.readFileSync(t,"utf-8");return TC.parse(r)}catch{return null}}static classifyFile(e,t,r){let i=Te.extname(e).toLowerCase(),o=n.owningSrcPath(e,t,r);if(i===".ets"||i===".ts")return{fileClass:"ets_ts",moduleSrcPath:o};if(i===".cpp"||i===".cc"||i===".c"||i===".h"||i===".hpp")return{fileClass:"native",moduleSrcPath:o};let s=e.replace(/\\/g,"/");return s.includes("/resources/rawfile/")?{fileClass:"raw_file",moduleSrcPath:o}:s.includes("/resources/resfile/")?{fileClass:"res_file",moduleSrcPath:o}:{fileClass:"unknown",moduleSrcPath:""}}static owningSrcPath(e,t,r){return n.findModuleByFilePath(e,t,r)?.srcPath??""}static findModuleByFilePath(e,t,r){return V.findModuleNodeByFilePath(e,t,r)}static getModuleType(e,t){let r=Te.join(e,t,"src","main","module.json5");if(!Be.existsSync(r))return"entry";try{let i=Be.readFileSync(r,"utf-8");return TC.parse(i)?.module?.type||"entry"}catch{return"entry"}}static patchDir(e,t){return Te.join(e,"build",t,"intermediates","patch",t)}static patchChangedFileListPath(e,t){return Te.join(n.patchDir(e,t),"changedFileList.json")}static hasArkTSChanges(e,t,r){let i=Te.join(e,t.replace(/^\.\//,""));try{let o=JSON.parse(Be.readFileSync(n.patchChangedFileListPath(i,r),"utf-8"));return Array.isArray(o.modifiedFiles)&&o.modifiedFiles.length>0}catch{return!0}}static buildReverseDependencyMap(e,t){let r=new Map;for(let i of t){let o=n.readLocalDependencies(e,i.srcPath);for(let s of o){let a=r.get(s)||[];a.includes(i.name)||a.push(i.name),r.set(s,a)}}return r}static readLocalDependencies(e,t){let r=Te.join(e,t,"oh-package.json5");if(!Be.existsSync(r))return[];try{let i=Be.readFileSync(r,"utf-8"),o=TC.parse(i);return n.resolveDepModuleNames(e,t,o.dependencies||{})}catch{return[]}}static resolveDepModuleNames(e,t,r){let i=n.loadBuildProfile(e);if(!i)return[];let o=i.modules,s=[];for(let a of Object.values(r)){if(typeof a!="string")continue;let c=V.resolveLocalDepToModuleName(e,t,a,o);c&&s.push(c)}return s}static findTopLevelConsumers(e,t,r,i){let o=new Set,s=new Set,a=[e];for(;a.length>0;){let c=a.shift();s.has(c)||(s.add(c),n.processDependents(c,t,r,i,o,a))}return o}static processDependents(e,t,r,i,o,s){let a=t.get(e)||[];for(let c of a){let l=i.find(g=>g.name===c);if(!l)continue;let d=n.getModuleType(r,l.srcPath);(d==="entry"||d==="shared")&&o.add(c),d==="har"&&s.push(c)}}static addFileToCollector(e,t,r,i,o){let s=Te.join(o,i,"src","main","resources");r==="ets_ts"?(e.hotReloadEntries.push({filePath:t,belongProjectPath:o}),e.patchEtsFiles.push(t)):r==="raw_file"?e.patchRawFiles.push({filePath:t,resourcePath:s}):r==="res_file"?e.patchResFiles.push({filePath:t,resourcePath:s}):r==="native"&&e.nativeFiles.push(t)}static writeApplyFile(e,t,r,i){let o=t.replace(/^\.\//,""),s=Te.join(e,o,"build",r,"intermediates","hotReload","changedFileList.json"),a=n.readExistingApply(s),c=n.mergeApplyEntries(a,i),l=Te.dirname(s);Be.existsSync(l)||Be.mkdirSync(l,{recursive:!0}),Be.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),h(`[ChangedFileListWriter] Written hotReload: ${s} (${c.length} entries)`)}static readExistingApply(e){if(!Be.existsSync(e))return[];try{let t=Be.readFileSync(e,"utf-8");return JSON.parse(t)?.modifiedFilesV2||[]}catch{return[]}}static writePatchFile(e,t,r,i,o,s){let a=t.replace(/^\.\//,""),c=n.patchChangedFileListPath(Te.join(e,a),r),l=n.readExistingPatch(c),d=Te.join(e,a,"src","main","ets"),g=i.map(Le=>n.resolveRelativePathForPatch(Le,d)),y=n.mergeStrings(l.modifiedFiles,g),k=n.mergePatchResources(l.rawFile,o),D=n.mergePatchResources(l.resFile,s),Z=Te.dirname(c);Be.existsSync(Z)||Be.mkdirSync(Z,{recursive:!0}),Be.writeFileSync(c,JSON.stringify({resources:{resFile:D,rawFile:k},modifiedFiles:y}),"utf-8"),h(`[ChangedFileListWriter] Written patch: ${c}`)}static readExistingPatch(e){if(!Be.existsSync(e))return{modifiedFiles:[],rawFile:[],resFile:[]};try{let t=Be.readFileSync(e,"utf-8"),r=JSON.parse(t);return{modifiedFiles:r?.modifiedFiles||[],rawFile:r?.resources?.rawFile||[],resFile:r?.resources?.resFile||[]}}catch{return{modifiedFiles:[],rawFile:[],resFile:[]}}}static resolveRelativePathForPatch(e,t){return Te.relative(Te.normalize(t),Te.normalize(e)).replace(/\\/g,"/")}static mergeApplyEntries(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o.filePath)||(r.add(o.filePath),i.push(o));return i}static mergeStrings(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o)||(r.add(o),i.push(o));return i}static mergePatchResources(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o.filePath)||(r.add(o.filePath),i.push(o));return i}};u();function Lh(n,e,t,r,i=[]){return[n,"--mode","module","-p",`module=${t.join(",")}@${r}`,"-p",`product=${r}`,...i.flatMap(o=>["-p",o]),e]}E();var Fi=class n{static generate(e,t,r,i){let o=_n(e,t),s=he.join(e,o),a=he.join(s,"build","config"),c=n.buildConfig(e,s,r,i);Fa.mkdirSync(a,{recursive:!0}),Fa.writeFileSync(he.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),h(`[BuildConfigManager] buildConfig.json written to ${a}`),Fa.mkdirSync(he.dirname(n.symbolTablePath(s,r)),{recursive:!0})}static remove(e,t){let r=_n(e,t),i=he.join(e,r,"build","config","buildConfig.json");Fa.existsSync(i)&&(Fa.unlinkSync(i),h(`[BuildConfigManager] buildConfig.json removed: ${i}`))}static removeAll(e){for(let t of e.profile.modules)n.remove(e.rootDir,t.name)}static async withBuildConfig(e,t,r,i,o,s,a=!1){for(let c of t)n.generate(e,c,r,i);try{return await n.ensureSymbolTable(e,t,r,i,s,a),await o()}finally{for(let c of t)n.remove(e,c)}}static async ensureSymbolTable(e,t,r,i,o,s=!1){let a=[];for(let c of t){let l=_n(e,c);if(!kr.hasArkTSChanges(e,l,r))continue;let d=he.join(e,l);Fa.existsSync(n.symbolTablePath(d,r))||a.push(c)}a.length!==0&&(o?.(a),await n.bootstrapSymbolTable(e,a,r,i,s))}static async bootstrapSymbolTable(e,t,r,i,o=!1){let s=[],a=[];for(let l of t){let d=_n(e,l);kr.getModuleType(e,d)==="shared"?a.push(l):s.push(l)}let c=[{modules:s,task:"assembleHap"},{modules:a,task:"assembleHsp"}];for(let{modules:l,task:d}of c)l.length!==0&&await n.runBootstrapBuild(e,l,r,i,d,o);for(let l of t){let d=he.join(e,_n(e,l)),g=n.symbolTablePath(d,r);if(!Fa.existsSync(g))throw new p("Internal",`Symbol table still missing after bootstrap: ${g}`,"Symbol table still missing after bootstrap.")}h("[BuildConfigManager] Symbol table bootstrap completed")}static async runBootstrapBuild(e,t,r,i,o,s){let a=Pl(i),c=["buildMode=debug"];s&&c.push("debugLine=true");let l=Lh(i.hvigorJsPath,o,t,r,c);h(`[BuildConfigManager] Bootstrap (${o}): ${i.nodePath} ${l.join(" ")}`);let d=n3(i.nodePath,l,{cwd:e,env:a,stdout:"pipe",stderr:"pipe",reject:!1});d.stdout?.pipe(process.stdout),d.stderr?.pipe(process.stderr);let g=await d;if(g.signal)throw new p("Internal",`Symbol table bootstrap (${o}) was terminated by signal ${g.signal}`,"Symbol table bootstrap terminated by signal.");let y=(g.exitCode??-1)|0;if(y!==0){let D=(g.stderr||g.stdout||"").toString().trim().split(/\r?\n/).slice(-15).join(`
|
|
73
|
+
`)}`),i)throw i}async migrateBundledDestination(e,t,r,i){let o=await et(t.path);if(!((!o||!o.isDirectory()&&!o.isSymbolicLink())&&!t.legacy.length)&&!r.some(s=>ge(s,t.path))){let s=await rh(e,t.path);s.skipped&&s.reason!=="correct-link"&&s.reason!=="same-source"&&i.push(s),r.push(t.path)}}async removeSkill(e,t,r={}){if(Tn(e),t.customPath){let i=vr.join(t.customPath,e);return dp(e,t,async()=>(await this.validateEntries([i],r),[await ih(i)]))}return sC(e,t,async i=>{let o=await iC(e,i.project);if(r.validateExisting){let s=await ip(i,e,t.explicitAgents);await this.validateScopeEntries(e,i,s,r)}return this.removeScope(e,i,t.explicitAgents,r,o)})}async removeScope(e,t,r=!0,i={},o={}){let s=await We(vr.join(nr(t.project),e)),a=await hh(e,t.project),c=await this.removeAgentEntries(e,t,s,a,r,i,o);for(let l of[s,a]){if(!c.every(g=>g.success))break;let d=await V0(l,e,t,await z0(l),i,o);d&&c.push(d)}return c.length||c.push(_4(e,s,i.log)),await this.completeConsumerRemoval(e,t,s,a,c,o),c}async completeConsumerRemoval(e,t,r,i,o,s){if(!await et(r)&&!await et(i)){await H0(e,t.project);return}await this.recordSharedConsumers(e,t,o,s,!1)}async removeAgentEntries(e,t,r,i,o,s,a){let c=new Set;for(let d of await ip(t,e,o))if(!d.skipped)for(let g of[d.path,...d.legacy])!ge(g,r)&&!ge(g,i)&&c.add(g);let l=[];for(let d of c){let g=await V0(d,e,t,void 0,s,a);g&&l.push(g)}return l}};u();import U4 from"p-limit";u();E();import vh from"fs";import Oa from"path";import{fileURLToPath as M4}from"url";function cC(){let n=Oa.dirname(M4(import.meta.url));for(;;){if(vh.existsSync(Oa.join(n,"skills","deveco-cli","SKILL.md")))return Oa.join(n,"skills");let e=Oa.dirname(n);if(e===n)break;n=e}throw new p("RuntimeCondition","skills/deveco-cli directory not found in deveco-cli package. Reinstall deveco-cli.","BundledSkillsAnchorMissing")}function hl(){cC()}function L4(n){return n.sort((e,t)=>e==="deveco-cli"?-1:t==="deveco-cli"?1:e.localeCompare(t))}function F4(n){let e=vh.readdirSync(n,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).map(t=>t.name).filter(t=>vh.existsSync(Oa.join(n,t,"SKILL.md")));return L4(e).map(t=>({name:t,dir:Oa.join(n,t)}))}function br(){return F4(cC())}function yl(n){try{return br().some(e=>e.name===n)}catch{return!1}}function j4(n){try{let e=JSON.parse(n);return Array.isArray(e.skills)?e.skills.filter(t=>typeof t=="object"&&t!==null).filter(t=>typeof t.name=="string").map(t=>({name:t.name,...typeof t.description=="string"?{description:t.description}:{}})):[]}catch{return[]}}function lC(){try{let n=Oa.join(cC(),"index.json");return j4(vh.readFileSync(n,"utf8"))}catch{return[]}}function uC(){let n=new Map(lC().map(e=>[e.name,e]));return br().map(({name:e})=>({name:e,description:n.get(e)?.description}))}function H4(n,e){let t=new Set(e);return n.filter(r=>!t.has(r.name)).map(r=>r.name)}function G0(n){return`Warning: bundled skill "${n}" is listed in the package index but missing from disk. The package may be corrupted \u2014 reinstall deveco-cli.`}function q0(){try{let n=lC();if(n.length===0)return[];let e=br().map(t=>t.name);return H4(n,e)}catch{return[]}}function $a(n=q0()){for(let e of n)console.warn(G0(e))}E();async function J0(n,e){try{let t=await ph();return await n(t)}catch(t){return e?.(t instanceof Error?t.message:"network error"),[]}}function K0(n){return n.map(e=>({...e,bundled:yl(e.enName)}))}function Y0(n,e){let t=new Set(n.map(r=>r.enName));return[...n,...e.filter(r=>!t.has(r.enName))]}var Na=class{constructor(e=[]){this.providers=e}catalog(){return this.mergeCatalog(this.providers.map(e=>e.catalog()))}search(e){return this.mergeCatalog(this.providers.flatMap(t=>t.search(e)))}async listCatalog(e){let t=K0(this.catalog()),r=await J0(fh,e);return Y0(t,r)}async findCatalog(e,t){let r=K0(this.search(e)),i=await J0(o=>mh(e,o),t);return Y0(r,i)}mergeCatalog(e){let t=new Map;for(let r of e)t.has(r.name)||t.set(r.name,{enName:r.name,description:r.description??""});return[...t.values()]}async resolveNames(e){if(e.skill&&this.provider(e.skill))return[e.skill];let t=await ph();if(e.all)return(await fh(t)).map(o=>o.enName);let i=(await mh(e.skill,t)).find(o=>o.enName===e.skill);if(!i)throw new p("InvalidArgument",`Skill "${e.skill}" not found`,"Skill not found.");return[i.enName]}async installSkills(e,t,r,i){let o=U4(5),s=e.map(l=>o(()=>this.prepareArchive(l))),a=[],c=0;for(let[l,d]of e.entries()){let g={name:d,index:l,total:e.length};i({...g,phase:"installing"});let y=await s[l];if(!y.success){i({...g,phase:"download-failed",error:y.error}),a.push({success:!1});continue}c+=y.buffer?.length??0,i({...g,phase:"ready"});let k=this.provider(d);a.push(...k?await k.installForTargets(d,t,r):await new rr().installArchiveSkill(d,y.buffer,t,r))}return{results:a,diskBytes:c}}removeSkill(e,t,r=!1){let i=this.provider(e);return i?i.uninstallForTargets(e,t,r):new rr().removeSkill(e,t)}provider(e){return this.providers.find(t=>t.handles(e))}async prepareArchive(e){try{return{success:!0,buffer:this.provider(e)?void 0:await tC(e)}}catch(t){return{success:!1,error:t instanceof Error?t.message:"unknown error"}}}};u();E();var bh=class{constructor(e){this.skill=e}handles(e){return e===this.skill.name}catalog(){return{name:this.skill.name,aliases:[],description:this.skill.description}}search(e){let t=e.trim().toLowerCase(),r=`${this.skill.name} ${this.skill.description??""}`.toLowerCase();return!t||r.includes(t)?[this.catalog()]:[]}installForTargets(){return Promise.reject(new p("InvalidArgument",`Skill "${this.skill.name}" is bundled with deveco-cli. Bundled skills are installed by devecocli init and update with the CLI package.`,"Skill is bundled with deveco-cli."))}uninstallForTargets(){return Promise.reject(new p("InvalidArgument",`Skill "${this.skill.name}" is bundled with deveco-cli and cannot be removed. Bundled skills are managed by the CLI package and update with npm update.`,"Skill is bundled with deveco-cli and cannot be removed."))}};function dC(){try{return uC().map(n=>new bh(n))}catch{return[]}}u();import pC from"fs/promises";import W4 from"path";function B4(n){return`'${process.platform==="win32"?n.replace(/'/g,"''"):n.replace(/'/g,"'\\''")}'`}async function V4(n,e,t){try{if(!(await et(n))?.isSymbolicLink())return;let i=await pC.realpath(n);return ge(i,e)?void 0:{path:n,reason:`points to ${i}`,repairAgent:t}}catch(r){let i=r.code,o=i==="ENOENT"||i==="ELOOP"||i==="ENOTDIR";return{path:n,reason:o?"broken link":`cannot check: ${r.message}`,repairAgent:o?t:void 0}}}var fC=class{checked=new Set;async warnInvalidBundledLinks(e){try{let t=await pC.realpath(e),r=process.platform==="win32"?t.toLowerCase():t;if(this.checked.has(r))return;this.checked.add(r);let i=await this.checkKnownEntries(t,br());this.reportIssues(t,i)}catch(t){console.warn(`Cannot check project Skill links for ${e}: ${t.message}`)}}async checkKnownEntries(e,t){let r=new Map([[nr(e),"universal"]]);for(let o of ct().filter(hs)){let s=GE(e,o);r.has(s)||r.set(s,o)}let i=[];for(let o of t){let s=await pC.realpath(o.dir),a=[];for(let[c,l]of r){let d=await this.checkDirectoryEntry(W4.join(c,o.name),s,l,a);d&&i.push(d)}}return i}async checkDirectoryEntry(e,t,r,i){try{let o=await We(e);return i.some(s=>ge(s,o))?void 0:(i.push(o),await V4(o,t,r))}catch(o){return{path:e,reason:`cannot check: ${o.message}`}}}reportIssues(e,t){let r=new Set;for(let i of t)console.warn(`Project Skill link: ${i.path} (${i.reason}).`),i.repairAgent&&r.add(i.repairAgent);r.size&&(console.warn(`Run: devecocli init --agent ${[...r].join(",")} --project ${B4(e)} -f`),console.warn("Existing copies and local edits in the selected installation scope will be replaced."))}},On=new fC;u();import wC from"fs";import n_ from"path";import{cyan as o8}from"colorette";me();u();u();P();me();_a();import{spawn as e8}from"child_process";import*as t_ from"fs";import*as kh from"path";import{yellow as t8,cyan as n8}from"colorette";import r8 from"proper-lockfile";u();var X0={name:"@yinsen/deveco-cli-common",version:"1.4.0-Test.912",description:"HarmonyOS application development command line tool",supportedDocsApi:1,license:"MIT",type:"module",files:["dist","templates","src/resources","!src/resources/**/*.test.ts","NOTICE","skills"],scripts:{prebuild:"node ../../scripts/sync-cli-docs.mjs",build:"npm run build -w design2arkts-engine && tsup",dev:"tsx watch src/cli.ts",start:"tsx src/cli.ts","prebundle:skills":"node ../../scripts/sync-cli-docs.mjs","bundle:skills":"tsx scripts/bundle-skills.ts","precheck:skills":"node ../../scripts/sync-cli-docs.mjs","check:skills":"tsx scripts/bundle-skills.ts --check","check:pack":"node ../../scripts/check-pack.mjs",test:"vitest run",lint:'eslint "src/**/*.ts"',"lint:fix":"eslint src --fix",format:"prettier --write src",prepack:"node ../../scripts/sync-cli-docs.mjs",prepublishOnly:"npm run lint && npm run build && npm run check:skills && npm run check:pack"},engines:{node:">=22"},os:["darwin","linux","win32"],cpu:["x64","arm64"],keywords:["harmonyos","deveco","cli"],dependencies:{"@agentclientprotocol/sdk":"^2.4.0","@ai-sdk/anthropic":"^4.0.99","@ai-sdk/openai":"^4.0.111","@ai-sdk/openai-compatible":"^3.0.87","@modelcontextprotocol/sdk":"^1.29.0","@xmldom/xmldom":"^0.8.15","adm-zip":"0.6.1",ai:"^7.0.166",axios:"1.20.0",colorette:"^2.0.20",commander:"^13.1.0",execa:"^9.6.1","fs-extra":"^11.3.4","global-agent":"^4.1.3","hypium-driver":"6.1.210",json5:"^2.2.3",mp4box:"^2.4.1","node-forge":"^1.4.0",ora:"^9.4.0","p-limit":"^5.0.0","proper-lockfile":"^4.1.2","proxy-from-env":"^2.1.0",semver:"^7.8.5","smol-toml":"^1.6.1","socket.io-client":"^4.7.5","ui-verification-mcp":"0.0.21",ws:"^8.21.1",xpath:"^0.0.35",yaml:"^2.9.1",zod:"^4.4.3","@yinsen/deveco-cli-knowledgebase":"1.4.0-Test.912"},devDependencies:{"@types/adm-zip":"^0.5.8","@types/fs-extra":"^11.0.4","@types/global-agent":"^3.0.0","@types/node-forge":"^1.3.14","@types/proper-lockfile":"^4.1.4","@types/semver":"^7.7.1","@types/ws":"^8.18.2","design2arkts-engine":"0.1.0"}};E();function fp(){return process.env.DEVECO_CLI_WRAPPER_NAME?process.env.DEVECO_CLI_WRAPPER_NAME:"@yinsen/deveco-cli-common"}function $n(){return process.env.DEVECO_CLI_WRAPPER_VERSION?process.env.DEVECO_CLI_WRAPPER_VERSION:"1.4.0-Test.912"}function vs(){return"test-v2"}function mC(){return"@yinsen/deveco-cli-common"}function Sr(){return Number.isFinite(1),1}var Ro=(()=>{let n=Object.keys(X0.dependencies).find(e=>e.endsWith("/deveco-cli-knowledgebase"));if(!n)throw new p("Internal","CLI package.json must declare a deveco-cli-knowledgebase dependency.","CLI package.json must declare a deveco-cli-knowledgebase dependency.");return n})();function vl(){let n=process.env.DEVECO_CLI_DISABLE_UPDATE;return n==="check"||n==="all"?n:"off"}u();P();import*as mp from"fs";import*as gp from"path";var q4={lastCheckedTimestamp:null,latestVersion:null,blockedVersions:[],checkError:null,latestDocsVersion:null,latestDocsApiVersion:null,latestCompatibleDocsVersion:null,checkedAgainstDocsApi:null},gC=new Map,bs=class n{static CHECK_WINDOW_HOUR=21;static ONE_DAY_MS=1440*60*1e3;cacheFilePath;lockFilePath;constructor(e){this.cacheFilePath=gp.join(e,"cache.json"),this.lockFilePath=gp.join(e,"check.lock")}async writeSuccess(e,t=[],r,i,o){let s=this.read();await this.write({lastCheckedTimestamp:Date.now(),latestVersion:e,blockedVersions:t,checkError:null,checkedAgainstVersion:r,checkedAgainstTag:i,latestDocsVersion:o?o.latestDocsVersion:s.latestDocsVersion??null,latestDocsApiVersion:o?o.latestDocsApiVersion:s.latestDocsApiVersion??null,latestCompatibleDocsVersion:o?o.latestCompatibleDocsVersion:s.latestCompatibleDocsVersion??null,checkedAgainstDocsApi:o?o.checkedAgainstDocsApi:s.checkedAgainstDocsApi??null})}async writeError(e){let t=this.read();await this.write({...t,lastCheckedTimestamp:Date.now(),checkError:e})}getLatestVersion(){return this.read().latestVersion}getBlockedVersions(){return[...this.read().blockedVersions]}getCheckedAgainstVersion(){return this.read().checkedAgainstVersion}getCheckedAgainstTag(){return this.read().checkedAgainstTag}getLatestDocsVersion(){return this.read().latestDocsVersion??null}getLatestDocsApiVersion(){return this.read().latestDocsApiVersion??null}getLatestCompatibleDocsVersion(){return this.read().latestCompatibleDocsVersion??null}getCheckedAgainstDocsApi(){return this.read().checkedAgainstDocsApi??null}isCheckNeeded(){let{lastCheckedTimestamp:e}=this.read();if(!e||e>Date.now())return!0;let t=new Date().setHours(n.CHECK_WINDOW_HOUR,0,0,0),r=t>Date.now()?t-n.ONE_DAY_MS:t;return e<r}getLockPath(){return this.lockFilePath}read(){let e=gC.get(this.cacheFilePath);if(e)return e;try{let t=mp.readFileSync(this.cacheFilePath,"utf-8"),r=JSON.parse(t);return gC.set(this.cacheFilePath,r),r}catch{return{...q4}}}async write(e){h(()=>`Writing update cache: lastChecked=${e.lastCheckedTimestamp}, latest=${e.latestVersion}, blocked=[${e.blockedVersions.join(",")}], error=${e.checkError}`),await mp.promises.mkdir(gp.dirname(this.cacheFilePath),{recursive:!0}),await mp.promises.writeFile(this.cacheFilePath,JSON.stringify(e,null,2),"utf-8"),gC.set(this.cacheFilePath,e)}};u();me();P();import{createRequire as J4}from"module";import{dirname as K4,join as bl}from"path";import{pathToFileURL as Y4}from"url";import{readFile as Q0,access as hC}from"fs/promises";import*as Z0 from"semver";E();var X4=J4(import.meta.url);async function Q4(){try{let n=X4.resolve(`${Ro}/package.json`),e=JSON.parse(await Q0(n,"utf8"));return{version:e.version,apiVersion:e.apiVersion??0,dir:K4(n)}}catch{return null}}async function e_(){let n=_(),e=bl(n,"doc-data","current.json"),t;try{t=JSON.parse(await Q0(e,"utf8"))}catch{return null}let r=bl(n,"doc-data",t.version);try{return await hC(bl(r,"dist","engine","index.js")),await hC(bl(r,"docs.zip")),await hC(bl(r,"index.zip")),{version:t.version,apiVersion:t.apiVersion,dir:r}}catch{return null}}async function Z4(){return[await e_(),await Q4()].filter(e=>e!==null).sort((e,t)=>Z0.rcompare(e.version,t.version))}async function Sl(){let n=Sr(),e=await e_();return e&&e.apiVersion<=n?e.version:null}async function Sh(){let n=Sr(),e=await Z4(),t=!1;for(let r of e){if(r.apiVersion>n){h(`docs: skip candidate v${r.version} (apiVersion ${r.apiVersion} > ${n})`);continue}t=!0;try{let i=bl(r.dir,"dist","engine","index.js");return await import(Y4(i).href)}catch(i){h(`docs: candidate v${r.version} load failed: ${i instanceof Error?i.message:String(i)}`)}}throw e.length>0&&!t?new p("RuntimeCondition","Documentation package version is incompatible, please upgrade CLI","Incompatible docs package."):new p("RuntimeCondition","No available documentation package, please run `devecocli docs update` or reinstall CLI","Docs package missing.")}u();_a();function Ma(n,e){return e===null||Li(n,e)>0}var hp=class{constructor(e){this.actionCommand=e}cache=new bs(kh.join(_(),"update"));async checkAndNotify(){if(!this.shouldSkip())try{let e=$n(),t=vs(),r=this.cache.getCheckedAgainstVersion(),i=this.cache.getCheckedAgainstTag(),o=i!=null&&i!==t,s=r!=null&&r!==e,a=[],c=o?null:this.cache.getLatestVersion();c&&Li(c,e)>0&&a.push(t8(`New cli version ${c} available, run \`devecocli update\` to update`));let l=await this.buildDocsMessage();if(l.message&&a.push(l.message),a.length>0){console.error();for(let d of a)console.error(d)}(o||s||l.stale||this.cache.isCheckNeeded())&&await this.spawnBackgroundCheck()}catch(e){h(`Update check failed: ${e instanceof Error?e.message:String(e)}`)}}async buildDocsMessage(){let e=Sr(),t=this.cache.getCheckedAgainstDocsApi();if(t!=null&&t!==e)return{message:null,stale:!0};let r=this.cache.getLatestCompatibleDocsVersion();if(!r)return{message:null,stale:!1};let i=await Sl();return Ma(r,i)?{message:n8(`New docs version ${r} available, run \`devecocli docs update\` to upgrade`),stale:!1}:{message:null,stale:!1}}shouldSkip(){let e=this.actionCommand;for(;e;){if(e.name()==="update")return!0;e=e.parent}return!1}async spawnBackgroundCheck(){if(!process.argv[1]?.endsWith(".ts"))try{await i8(this.cache.getLockPath(),()=>{let e=[process.argv[1],"update","_check"];h(`Executing: ${process.execPath} ${e.join(" ")}`),e8(process.execPath,e,{detached:!0,windowsHide:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1"}}).unref()})}catch{h("Update check lock held by another process, skipping")}}};async function i8(n,e){await t_.promises.mkdir(kh.dirname(n),{recursive:!0});let t=await r8.lock(n,{stale:6e4,retries:0,realpath:!1});try{await e()}finally{await t()}}E();var yC=wC.promises;async function Eh(n){let e=np(n);for(let t of e)tr(t);return e}async function Ch(n){return ct().filter(e=>Ia(e,n))}async function s8(){let n=new rr,e=ct().filter(hs),t=[];for(let{name:r,dir:i}of br())try{await n.migrateBundledSkill(r,i,{agents:e})}catch(o){t.push({name:r,error:o})}if(t.length>0){let r=t.map(({name:i,error:o})=>`${i}: ${o instanceof Error?o.message:String(o)}`).join("; ");throw new p("Internal",`Bundled skill migration failed \u2014 ${r}`,"Bundled skill migration failed.")}}async function r_(){try{let n=n_.join(_(),"skills","migration-version"),e=await yC.readFile(n,"utf8").catch(r=>{if(r.code==="ENOENT")return"";throw r}),t=$n();if(e.trim()===t)return;await s8(),await yC.mkdir(n_.dirname(n),{recursive:!0}),await yC.writeFile(n,t,"utf8")}catch(n){console.warn(`Bundled skill migration failed (will retry on the next command): ${n instanceof Error?n.message:String(n)}`)}}function kl(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(o8("Finished:"));for(let i of n){if(!i.path)continue;let o=W0(i),s=i.fallbackReason?" (link failed: "+i.fallbackReason+")":o??i.error?" ("+(o??i.error)+")":"",a=i.success?i.skipped?"skipped":i.mode??(i.reason==="shared-entity-updated"?"updated":"removed"):"failed";console.log(" "+a+": "+i.path+s)}console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function Jr(n,e,t){if(!wC.existsSync(n)){if(t)return;throw new p("InvalidArgument",`${e} "${n}" not found`,"Directory not found.")}if(!wC.statSync(n).isDirectory())throw new p("InvalidArgument",`"${n}" is not a directory`,"Path is not a directory.")}function El(n,e,t){if(n&&(e||t))throw new p("InvalidArgument","Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?eC(n):void 0,resolvedProject:e?eC(e):void 0}}async function Ph(n,e,t="No agents found. Install an AI agent (cursor, opencode, etc.) or use `--path` for a custom location."){let r=n.agent?await Eh(n.agent):await Ch(e);if(!r.length)throw new p("RuntimeCondition",t,"NoAgentsFound");return r.map(i=>({agent:i,directory:yr(i,e),explicit:!!n.agent}))}async function yp(n,e,t){if(e)return{agents:[],projectAgents:[],customPath:e};let r=await Ph(n,t),i=r.some(o=>o.explicit);return t?{agents:[],explicitAgents:i,projectAgents:r.map(({agent:o})=>({project:t,agent:o}))}:{agents:r.map(({agent:o})=>o),projectAgents:[],explicitAgents:i}}async function vC(n,e,t){let r=await yp(n,e,t);if(r.customPath)return r;let i=r.agents.filter(hs),o=r.projectAgents.filter(({agent:s})=>hs(s));return i.length||o.length?{...r,agents:i,projectAgents:o}:void 0}u();cp();E();import a8 from"fs";import Rh from"path";import{cyan as c8}from"colorette";import*as xh from"smol-toml";var Cl=a8.promises;async function l8(n){try{let e=await Cl.readFile(n,"utf8");return e.trim()===""?{}:JSON.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new p("Internal",`Failed to read configuration file ${n}: ${e.message}`,"Failed to read configuration file.",{cause:e})}}async function u8(n){try{let e=await Cl.readFile(n,"utf8");return e.trim()===""?{}:xh.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new p("Internal",`Failed to read TOML config file ${n}: ${e.message}`,"Failed to read TOML config file.",{cause:e})}}async function d8(n,e){let t=Rh.dirname(n);await Cl.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await Cl.writeFile(n,r,"utf8")}async function p8(n,e){let t=Rh.dirname(n);await Cl.mkdir(t,{recursive:!0});let r=xh.stringify(e);await Cl.writeFile(n,r,"utf8")}function f8(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function m8(n,e,t,r,i){(!n[e]||typeof n[e]!="object")&&(n[e]={});let o=n[e];return t in o&&!i?!1:(o[t]=r,!0)}async function g8(n,e){return n.format==="codex"?u8(e):l8(e)}async function h8(n,e,t){return n.format==="codex"?p8(e,t):d8(e,t)}function i_(n={}){return{force:n.force??!1,withHomegraph:n.withHomegraph??!1}}function y8(n,e,t,r,i){let o=[],s=[],a=!1,c=(l,d)=>{if(f8(n,e.mcpServersKey,l)&&!r){s.push(l);return}m8(n,e.mcpServersKey,l,d,r),o.push(l),a=!0};return c(XE,QE(e,t)),i&&c(C0,x0(e,t)),{changed:a,configured:o,skipped:s}}async function o_(n,e,t,r,i,o){try{let s=await g8(e,t),{changed:a,configured:c,skipped:l}=y8(s,e,r,o.force,o.withHomegraph);return a?(await h8(e,t,s),console.log(`MCP server(s) ${c.join(", ")} configured in ${t}.`),{success:!0,configPath:t,agentName:n,installType:i}):(console.log(`MCP already configured in ${t} (${l.join(", ")}).`),{success:!0,skipped:!0,configPath:t,agentName:n,installType:i})}catch(s){return{success:!1,error:`Failed to configure MCP for ${e.displayName}: ${s.message}`}}}async function bC(n,e={}){let t=i_(e),r=Po[n];return r?r.supportsGlobal?o_(n,r,r.globalConfigPath,void 0,"global",t):{success:!1,error:`${r.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`}:{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Po).join(", ")}`}}async function Ah(n,e,t={}){let r=i_(t),i=Po[n];if(!i)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Po).join(", ")}`};let o=Rh.isAbsolute(i.projectConfigPath)?i.projectConfigPath:Rh.join(e,i.projectConfigPath);return o_(n,i,o,e,"project",r)}function SC(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(c8("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`);for(let i of n)!i.success&&i.error&&console.error(` - ${i.agentName??"unknown"}: ${i.error}`);r>0&&(process.exitCode=1)}u();cp();import w8 from"fs";import v8 from"path";import{homedir as b8}from"os";E();async function kC(n,e){let t=[],r=n.agent?np(n.agent):Object.keys(dh);for(let i of r){if(!Object.prototype.hasOwnProperty.call(dh,i))throw new p("InvalidArgument",`Invalid MCP agent: ${i}`,"Invalid MCP agent.");(n.agent||w8.existsSync(v8.join(b8(),dh[i])))&&t.push(i)}if(!t.length)throw new p("Internal","No agents supporting MCP configuration found; use --skill","No agents supporting MCP configuration found.");return e?{agents:[],projectAgents:t.map(i=>({project:e,agent:i}))}:{agents:t,projectAgents:[]}}u();wp();u();P();Oi();import{execa as G8}from"execa";import*as h_ from"net";import*as Rl from"path";import*as $h from"fs";import*as Nh from"os";u();import*as Oh from"path";function Pl(n){let e=Oh.dirname(n.javaPath);return{...process.env,PATH:`${e}${Oh.delimiter}${process.env.PATH||""}`,DEVECO_SDK_HOME:n.sdkPath}}E();var _h="module",ir=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let i=Pl(e),o=Nh.platform()==="darwin"&&e.javaPath==="/usr/bin/java";e.sourceType==="clt"&&e.javaPath&&!o&&(i.JAVA_HOME=Rl.dirname(Rl.dirname(e.javaPath))),this.env=i}async sync(e,t){let r=["--sync","-p",`product=${e}`,"-p",`buildMode=${t}`];return this.runHvigor(r)}async buildProduct(e,t,r=!1){let i=["assembleApp","-p",`product=${e}`,"-p",`buildMode=${t}`];return r&&i.push("-p","debugLine=true"),this.runHvigor(i)}async buildModules(e,t,r,i,o=!1){let s=[...Array.from(i),"--mode","module","-p",`module=${r.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`];return o&&s.push("-p","debugLine=true"),this.runHvigor(s)}async clean(e,t){let r=["clean","--mode",e??_h];return t&&t.length>0&&r.push("-p",`module=${t.join(",")}`),this.runHvigor(r)}async stopDaemon(){return this.runHvigor(["--stop-daemon"])}async ensureDaemonRunning(){if(this.findProjectDaemon()){h("[HvigorAdapter] Daemon already running.");return}h("[HvigorAdapter] No daemon running, starting via --sync --daemon (no hap build)."),await this.runHvigor(["--sync","--daemon"])}isDaemonRunning(e){return this.findProjectDaemon(e)!==null}async isDaemonAlive(e){let t=this.findProjectDaemon(e);return t?this.isPortListening(t.port):!1}isPortListening(e){return new Promise(t=>{let r=new h_.Socket;r.setTimeout(2e3),r.once("connect",()=>{r.destroy(),t(!0)}),r.once("error",()=>t(!1)),r.once("timeout",()=>{r.destroy(),t(!1)}),r.connect(e,"127.0.0.1")})}findProjectDaemon(e){let t=this.getDaemonRegistryPath();if(!$h.existsSync(t))return null;try{let r=$h.readFileSync(t,"utf-8"),i=JSON.parse(r),o=e??this.projectRoot,s=Object.values(i).filter(a=>a.cwdPath===o&&(a.state==="idle"||a.state==="half_busy"||a.state==="busy")&&this.isProcessAlive(a.pid));return s.length>0?s[s.length-1]:null}catch{return null}}getDaemonRegistryPath(){let e=process.env.HVIGOR_USER_HOME||Rl.join(Nh.homedir(),".hvigor");return Rl.join(e,"daemon","cache","daemon-sec.json")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}async compileNative(e,t){let r=["--mode","module"];return t&&r.push("-p",`module=${t}`),r.push("-p",`product=${e}`,"compileNative"),this.runHvigor(r)}async runHvigor(e){let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];h(`Executing: ${t} ${r.join(" ")}`);let i=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit",o=this.silent&&process.env.DEVECO_CLI_DEBUG?process.stderr:i,s=G8(t,r,{cwd:this.projectRoot,env:this.env,stdout:o,stderr:i,windowsHide:!0}),a=Kt()?void 0:dl(s.pid,2e3,!0),c="";try{await s}finally{if(a){let l=await a.stop();l>0&&(c=Qt(l),h(`Hvigor peak memory: ${c}`))}}return c}};u();P();Oi();E();import{execa as q8}from"execa";var xl=class{toolProvider;projectRoot;peakMemoryMb="";constructor(e,t){this.toolProvider=e,this.projectRoot=t}async install(){let e=this.toolProvider.nodePath,t=[this.toolProvider.ohpmJsPath,"install"];h(`Executing: ${e} ${t.join(" ")}`);let r=q8(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"}),i=Kt()?void 0:dl(r.pid,2e3,!1);try{await r}finally{if(i){let o=await i.stop();o>0&&(this.peakMemoryMb=Qt(o))}}}};u();import{mkdir as J8}from"fs/promises";import{dirname as K8,resolve as Y8}from"path";import{execa as X8}from"execa";import{lock as xC,check as hBe}from"proper-lockfile";function AC(n){return Y8(n,".hvigor",".build-lock")}function Q8(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function y_(n){let e=K8(AC(n));if(await J8(e,{recursive:!0}),process.platform==="win32")try{await X8("attrib",["+h",e])}catch{}}async function Z8(n,e){let t=new AbortController,r=Q8(e);await y_(n);let i={lockfilePath:AC(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await xC(n,{...i,retries:0}),signal:t.signal}}catch(s){if(s&&typeof s=="object"&&"code"in s&&s.code!=="ELOCKED")throw s}return r(),{release:await xC(n,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function To(n,e,t){let{release:r,signal:i}=await Z8(n,t);try{return await e(i)}finally{await r()}}async function Mh(n,e){let t=new AbortController;await y_(n);let r={lockfilePath:AC(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},i;try{i=await xC(n,{...r,retries:0})}catch(o){if(o&&typeof o=="object"&&"code"in o&&o.code==="ELOCKED")return{acquired:!1};throw o}try{return{acquired:!0,result:await e(t.signal)}}finally{await i()}}u();P();import Fa from"fs";import*as he from"path";import{execa as n3}from"execa";u();P();import w_ from"fs";import*as v_ from"path";import e3 from"json5";function t3(n,e){try{let r=e3.parse(w_.readFileSync(n,"utf-8")).modules?.find(i=>i.name===e);return r?.srcPath?r.srcPath.replace(/^\.\//,""):null}catch(t){return h(`[apply] resolveModuleSrcPath fallback (module=${e}): ${t.message}`),null}}function _n(n,e){let t=v_.join(n,"build-profile.json5");return w_.existsSync(t)?t3(t,e)??e:e}u();P();Je();import Be from"fs";import*as Te from"path";import TC from"json5";var b_="default",kr=class n{static writeChangedFileLists(e,t,r,i){let o=t||b_,s=n.loadBuildProfile(e);if(!s)return{writtenModules:[],skippedFiles:r};let a=s.modules,c=n.filterRunnableModules(e,a);if(c.length===0)return{writtenModules:[],skippedFiles:r};let l=n.buildReverseDependencyMap(e,a),d=n.createCollectors(c),g=n.collectChanges(r,e,a,l,d);return{writtenModules:n.flushCollectors(e,o,c,d,i),skippedFiles:g}}static initEmptyChangedFileLists(e,t,r){let i=t||b_,o=n.loadBuildProfile(e);if(!o)return[];let s=o.modules,a=[];for(let c of s){let l=n.getModuleType(e,c.srcPath);if(l!=="entry"&&l!=="shared")continue;let d=!r||c.name===r;n.initEmptyForModule(e,i,c.srcPath,d),a.push(c.name)}return a}static filterRunnableModules(e,t){return t.filter(r=>{let i=n.getModuleType(e,r.srcPath);return i==="entry"||i==="shared"})}static createCollectors(e){let t=new Map;for(let r of e)t.set(r.name,{hotReloadEntries:[],patchEtsFiles:[],patchRawFiles:[],patchResFiles:[],nativeFiles:[]});return t}static collectChanges(e,t,r,i,o){let s=[];for(let a of e){let c=Te.normalize(a),l=n.classifyFile(c,t,r);if(l.fileClass==="unknown"){s.push(c);continue}let d=n.findModuleByFilePath(c,t,r);if(!d){s.push(c);continue}let g=n.resolveTargetModules(d,t,r,i);if(g.length===0){s.push(c);continue}n.dispatchToCollectors(g,o,c,l,d.srcPath,t)}return s}static resolveTargetModules(e,t,r,i){let o=n.getModuleType(t,e.srcPath);return o==="entry"||o==="shared"?[e.name]:Array.from(n.findTopLevelConsumers(e.name,i,t,r))}static dispatchToCollectors(e,t,r,i,o,s){for(let a of e){let c=t.get(a);c&&n.addFileToCollector(c,r,i.fileClass,o,s)}}static flushCollectors(e,t,r,i,o){let s=[];for(let a of r){let c=i.get(a.name);if(!c||!n.hasAnyChange(c))continue;(!o||a.name===o)&&c.hotReloadEntries.length>0&&n.writeApplyFile(e,a.srcPath,t,c.hotReloadEntries),n.writePatchFile(e,a.srcPath,t,c.patchEtsFiles,c.patchRawFiles,c.patchResFiles),s.push(a.name)}return s}static hasAnyChange(e){return e.hotReloadEntries.length>0||e.patchEtsFiles.length>0||e.patchRawFiles.length>0||e.patchResFiles.length>0||e.nativeFiles.length>0}static initEmptyForModule(e,t,r,i){let o=n.patchChangedFileListPath(Te.join(e,r),t);if(Be.existsSync(o)||(Be.mkdirSync(Te.dirname(o),{recursive:!0}),Be.writeFileSync(o,JSON.stringify({resources:{resFile:[],rawFile:[]},modifiedFiles:[]}),"utf-8")),!i)return;let s=Te.join(e,r,"build",t,"intermediates","hotReload"),a=Te.join(s,"changedFileList.json");Be.existsSync(a)||(Be.mkdirSync(s,{recursive:!0}),Be.writeFileSync(a,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=Te.join(e,"build-profile.json5");if(!Be.existsSync(t))return null;try{let r=Be.readFileSync(t,"utf-8");return TC.parse(r)}catch{return null}}static classifyFile(e,t,r){let i=Te.extname(e).toLowerCase(),o=n.owningSrcPath(e,t,r);if(i===".ets"||i===".ts")return{fileClass:"ets_ts",moduleSrcPath:o};if(i===".cpp"||i===".cc"||i===".c"||i===".h"||i===".hpp")return{fileClass:"native",moduleSrcPath:o};let s=e.replace(/\\/g,"/");return s.includes("/resources/rawfile/")?{fileClass:"raw_file",moduleSrcPath:o}:s.includes("/resources/resfile/")?{fileClass:"res_file",moduleSrcPath:o}:{fileClass:"unknown",moduleSrcPath:""}}static owningSrcPath(e,t,r){return n.findModuleByFilePath(e,t,r)?.srcPath??""}static findModuleByFilePath(e,t,r){return V.findModuleNodeByFilePath(e,t,r)}static getModuleType(e,t){let r=Te.join(e,t,"src","main","module.json5");if(!Be.existsSync(r))return"entry";try{let i=Be.readFileSync(r,"utf-8");return TC.parse(i)?.module?.type||"entry"}catch{return"entry"}}static patchDir(e,t){return Te.join(e,"build",t,"intermediates","patch",t)}static patchChangedFileListPath(e,t){return Te.join(n.patchDir(e,t),"changedFileList.json")}static hasArkTSChanges(e,t,r){let i=Te.join(e,t.replace(/^\.\//,""));try{let o=JSON.parse(Be.readFileSync(n.patchChangedFileListPath(i,r),"utf-8"));return Array.isArray(o.modifiedFiles)&&o.modifiedFiles.length>0}catch{return!0}}static buildReverseDependencyMap(e,t){let r=new Map;for(let i of t){let o=n.readLocalDependencies(e,i.srcPath);for(let s of o){let a=r.get(s)||[];a.includes(i.name)||a.push(i.name),r.set(s,a)}}return r}static readLocalDependencies(e,t){let r=Te.join(e,t,"oh-package.json5");if(!Be.existsSync(r))return[];try{let i=Be.readFileSync(r,"utf-8"),o=TC.parse(i);return n.resolveDepModuleNames(e,t,o.dependencies||{})}catch{return[]}}static resolveDepModuleNames(e,t,r){let i=n.loadBuildProfile(e);if(!i)return[];let o=i.modules,s=[];for(let a of Object.values(r)){if(typeof a!="string")continue;let c=V.resolveLocalDepToModuleName(e,t,a,o);c&&s.push(c)}return s}static findTopLevelConsumers(e,t,r,i){let o=new Set,s=new Set,a=[e];for(;a.length>0;){let c=a.shift();s.has(c)||(s.add(c),n.processDependents(c,t,r,i,o,a))}return o}static processDependents(e,t,r,i,o,s){let a=t.get(e)||[];for(let c of a){let l=i.find(g=>g.name===c);if(!l)continue;let d=n.getModuleType(r,l.srcPath);(d==="entry"||d==="shared")&&o.add(c),d==="har"&&s.push(c)}}static addFileToCollector(e,t,r,i,o){let s=Te.join(o,i,"src","main","resources");r==="ets_ts"?(e.hotReloadEntries.push({filePath:t,belongProjectPath:o}),e.patchEtsFiles.push(t)):r==="raw_file"?e.patchRawFiles.push({filePath:t,resourcePath:s}):r==="res_file"?e.patchResFiles.push({filePath:t,resourcePath:s}):r==="native"&&e.nativeFiles.push(t)}static writeApplyFile(e,t,r,i){let o=t.replace(/^\.\//,""),s=Te.join(e,o,"build",r,"intermediates","hotReload","changedFileList.json"),a=n.readExistingApply(s),c=n.mergeApplyEntries(a,i),l=Te.dirname(s);Be.existsSync(l)||Be.mkdirSync(l,{recursive:!0}),Be.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),h(`[ChangedFileListWriter] Written hotReload: ${s} (${c.length} entries)`)}static readExistingApply(e){if(!Be.existsSync(e))return[];try{let t=Be.readFileSync(e,"utf-8");return JSON.parse(t)?.modifiedFilesV2||[]}catch{return[]}}static writePatchFile(e,t,r,i,o,s){let a=t.replace(/^\.\//,""),c=n.patchChangedFileListPath(Te.join(e,a),r),l=n.readExistingPatch(c),d=Te.join(e,a,"src","main","ets"),g=i.map(Le=>n.resolveRelativePathForPatch(Le,d)),y=n.mergeStrings(l.modifiedFiles,g),k=n.mergePatchResources(l.rawFile,o),D=n.mergePatchResources(l.resFile,s),Z=Te.dirname(c);Be.existsSync(Z)||Be.mkdirSync(Z,{recursive:!0}),Be.writeFileSync(c,JSON.stringify({resources:{resFile:D,rawFile:k},modifiedFiles:y}),"utf-8"),h(`[ChangedFileListWriter] Written patch: ${c}`)}static readExistingPatch(e){if(!Be.existsSync(e))return{modifiedFiles:[],rawFile:[],resFile:[]};try{let t=Be.readFileSync(e,"utf-8"),r=JSON.parse(t);return{modifiedFiles:r?.modifiedFiles||[],rawFile:r?.resources?.rawFile||[],resFile:r?.resources?.resFile||[]}}catch{return{modifiedFiles:[],rawFile:[],resFile:[]}}}static resolveRelativePathForPatch(e,t){return Te.relative(Te.normalize(t),Te.normalize(e)).replace(/\\/g,"/")}static mergeApplyEntries(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o.filePath)||(r.add(o.filePath),i.push(o));return i}static mergeStrings(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o)||(r.add(o),i.push(o));return i}static mergePatchResources(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o.filePath)||(r.add(o.filePath),i.push(o));return i}};u();function Lh(n,e,t,r,i=[]){return[n,"--mode","module","-p",`module=${t.join(",")}@${r}`,"-p",`product=${r}`,...i.flatMap(o=>["-p",o]),e]}E();var Fi=class n{static generate(e,t,r,i){let o=_n(e,t),s=he.join(e,o),a=he.join(s,"build","config"),c=n.buildConfig(e,s,r,i);Fa.mkdirSync(a,{recursive:!0}),Fa.writeFileSync(he.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),h(`[BuildConfigManager] buildConfig.json written to ${a}`),Fa.mkdirSync(he.dirname(n.symbolTablePath(s,r)),{recursive:!0})}static remove(e,t){let r=_n(e,t),i=he.join(e,r,"build","config","buildConfig.json");Fa.existsSync(i)&&(Fa.unlinkSync(i),h(`[BuildConfigManager] buildConfig.json removed: ${i}`))}static removeAll(e){for(let t of e.profile.modules)n.remove(e.rootDir,t.name)}static async withBuildConfig(e,t,r,i,o,s,a=!1){for(let c of t)n.generate(e,c,r,i);try{return await n.ensureSymbolTable(e,t,r,i,s,a),await o()}finally{for(let c of t)n.remove(e,c)}}static async ensureSymbolTable(e,t,r,i,o,s=!1){let a=[];for(let c of t){let l=_n(e,c);if(!kr.hasArkTSChanges(e,l,r))continue;let d=he.join(e,l);Fa.existsSync(n.symbolTablePath(d,r))||a.push(c)}a.length!==0&&(o?.(a),await n.bootstrapSymbolTable(e,a,r,i,s))}static async bootstrapSymbolTable(e,t,r,i,o=!1){let s=[],a=[];for(let l of t){let d=_n(e,l);kr.getModuleType(e,d)==="shared"?a.push(l):s.push(l)}let c=[{modules:s,task:"assembleHap"},{modules:a,task:"assembleHsp"}];for(let{modules:l,task:d}of c)l.length!==0&&await n.runBootstrapBuild(e,l,r,i,d,o);for(let l of t){let d=he.join(e,_n(e,l)),g=n.symbolTablePath(d,r);if(!Fa.existsSync(g))throw new p("Internal",`Symbol table still missing after bootstrap: ${g}`,"Symbol table still missing after bootstrap.")}h("[BuildConfigManager] Symbol table bootstrap completed")}static async runBootstrapBuild(e,t,r,i,o,s){let a=Pl(i),c=["buildMode=debug"];s&&c.push("debugLine=true");let l=Lh(i.hvigorJsPath,o,t,r,c);h(`[BuildConfigManager] Bootstrap (${o}): ${i.nodePath} ${l.join(" ")}`);let d=n3(i.nodePath,l,{cwd:e,env:a,stdout:"pipe",stderr:"pipe",reject:!1});d.stdout?.pipe(process.stdout),d.stderr?.pipe(process.stderr);let g=await d;if(g.signal)throw new p("Internal",`Symbol table bootstrap (${o}) was terminated by signal ${g.signal}`,"Symbol table bootstrap terminated by signal.");let y=(g.exitCode??-1)|0;if(y!==0){let D=(g.stderr||g.stdout||"").toString().trim().split(/\r?\n/).slice(-15).join(`
|
|
74
74
|
`),Z=g.exitCode===void 0?"unknown":String(y);throw new p("Internal",`Symbol table bootstrap (${o}) failed with exit code ${Z}`+(D?`:
|
|
75
75
|
${D}`:""),"Symbol table bootstrap failed with exit code.")}}static symbolTablePath(e,t){return he.join(e,"build",t,"intermediates","loader_out",t,"ets","symbolMap.map")}static buildConfig(e,t,r,i){let o=he.dirname(i.nodePath)+he.sep,s=he.join(t,"build",r),a=he.join(s,"intermediates"),c=he.join(a,"loader_out",r),l=he.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:o,projectProfilePath:he.join(e,"build-profile.json5"),localPropertiesPath:he.join(e,"local.properties"),appResource:he.join(l,"ResourceTable.txt"),cachePath:he.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:he.join(a,"loader",r,"loader.json"),aceModuleJsonPath:he.join(l,"module.json"),aceSoPath:he.join(c,"nativeDependencies.txt"),aceModuleRoot:he.join(t,"src","main","ets"),aceModuleBuild:he.join(c,"ets"),aceProfilePath:he.join(l,"resources","base","profile"),aceSuperVisualPath:he.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"false",mode:"hotReload",oldMapFilePath:he.join(c,"ets"),changedFileList:kr.patchChangedFileListPath(t,r),patchAbcPath:he.join(kr.patchDir(t,r),"ets"),removeChangedFileListInSdk:"true"}}}};u();P();ml();import*as Io from"fs";import*as ji from"path";import r3 from"json5";var i3=1e3;function Al(n,e,t){let r=o3(n,e,t);return r.required?(h(`[ProjectCheck] ${t} check: ${r.reason}`),r):null}function Fh(n){h(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=ji.join(n,Pt.SYNC_OUTPUT_PATH);if(!Io.existsSync(e)){let a={required:!0,reason:`sync baseline file not found: ${e}`};return h(`[ProjectCheck] ${a.reason}`),a}let t=Io.statSync(e).mtimeMs,r=ji.join(n,Pt.LOCK_JSON5_PATH);if(!Io.existsSync(r)){let a={required:!0,reason:`oh_modules lock not found: ${r}`};return h(`[ProjectCheck] ${a.reason}`),a}let i=s3(n);if(i===null)return{required:!0,reason:"failed to parse build-profile.json5"};let o=Al(ji.join(n,Pt.OH_PACKAGE_JSON5),t,"root");if(o||(o=Al(ji.join(n,Pt.BUILD_PROFILE_JSON5),t,"build-profile"),o)||(o=Al(ji.join(n,Pt.HVIGOR_CONFIG),t,"hvigor-config"),o)||(o=Al(ji.join(n,Pt.HVIGOR_CONFIG),t,"hvigor-config"),o))return o;for(let a of i)if(o=Al(ji.join(n,a.srcPath,Pt.OH_PACKAGE_JSON5),t,a.name),o||(o=Al(ji.join(n,a.srcPath,Pt.BUILD_PROFILE_JSON5),t,a.name),o))return o;let s=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return h(`[ProjectCheck] ${s}`),{required:!1,reason:s}}function o3(n,e,t){if(!Io.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=Io.statSync(n).mtimeMs;return r-e>i3?{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 s3(n){let e=ji.join(n,Pt.BUILD_PROFILE_JSON5);try{let t=Io.readFileSync(e,"utf-8");if(!t.trim())return null;let r=r3.parse(t);if(typeof r!="object"||r===null)return null;let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):null}catch{return null}}u();import*as Ie from"fs";import*as Ee from"path";u();u();Jt();import*as S_ from"util";var IC="";function Hh(n){if(!n||n==="auto"||n==="stdout"||n==="none"){IC="";return}IC=n}function k_(){return IC||(cN()??"")}function jh(n,...e){if(e.length===0)return n;try{return S_.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var w={info(n,...e){v.info(`[lsp] ${jh(n,...e)}`)},warn(n,...e){v.warn(`[lsp] ${jh(n,...e)}`)},error(n,...e){v.error(`[lsp] ${jh(n,...e)}`)},debug(n,...e){v.debug(`[lsp] ${jh(n,...e)}`)}};u();import*as vp from"fs";import*as bp from"os";import*as Il from"path";import a3 from"json5";u();var R={INITIALIZE:"initialize",INITIALIZED:"initialized",SHUTDOWN:"shutdown",EXIT:"exit",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",DID_CLOSE:"textDocument/didClose",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",DECLARATION:"textDocument/declaration",REFERENCES:"textDocument/references",IMPLEMENTATION:"textDocument/implementation",COMPLETION:"textDocument/completion",COMPLETION_ITEM_RESOLVE:"completionItem/resolve",SIGNATURE_HELP:"textDocument/signatureHelp",CODE_ACTION:"textDocument/codeAction",PREPARE_RENAME:"textDocument/prepareRename",RENAME:"textDocument/rename",DOCUMENT_HIGHLIGHT:"textDocument/documentHighlight",DOCUMENT_LINK:"textDocument/documentLink",INLAY_HINT:"textDocument/inlayHint",DOCUMENT_SYMBOL:"textDocument/documentSymbol",WORKSPACE_SYMBOL:"workspace/symbol",DIAGNOSTIC:"textDocument/diagnostic",WORKSPACE_DIAGNOSTIC:"workspace/diagnostic",PREPARE_CALL_HIERARCHY:"textDocument/prepareCallHierarchy",INCOMING_CALLS:"callHierarchy/incomingCalls",OUTGOING_CALLS:"callHierarchy/outgoingCalls",PREPARE_TYPE_HIERARCHY:"textDocument/prepareTypeHierarchy",SUPERTYPES:"typeHierarchy/supertypes",SUBTYPES:"typeHierarchy/subtypes",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",DID_CREATE_FILES:"workspace/didCreateFiles",DID_DELETE_FILES:"workspace/didDeleteFiles",PROGRESS:"$/progress",WINDOW_SHOW_MESSAGE:"window/showMessage",WINDOW_LOG_MESSAGE:"window/logMessage",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing",ARKTS_ERROR:"arkts/error",CPP_INITIALIZED:"cpp/initialized",CPP_INITIALIZATION_FAILED:"cpp/initializationFailed",CPP_INDEXING_PROGRESS:"cpp/indexingProgress",CPP_SYNC_PROJECT:"cpp/syncProject",CPP_SYNC_COMPLETED:"cpp/syncCompleted",CPP_REINITIALIZING:"cpp/reinitializing",CPP_ERROR:"cpp/error",BROADCAST:"lsp/broadcast"},ie="2.0",Tl={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate"};var E_=8192,DC=100,C_=.03,P_=.7,Mn=900*1e3;function or(n){if(!vp.existsSync(n))return null;try{let e=vp.readFileSync(n,"utf-8");return e.trim()?a3.parse(e):null}catch{return null}}function Uh(n,e){let t=Math.floor(bp.totalmem()/1048576),r=Math.floor(t*P_),i,o;e!==void 0&&Number.isFinite(e)&&e>0?(i=e,o=`override(${e})`):(i=E_,n>DC&&(i+=(n-DC)*C_*1024),o=`formula(moduleCount=${n})`);let s=r>0&&i>r;s&&(i=r);let a=Math.round(i);return w.info(`[computeLspServerMaxSize] source=${o}, physicalTotal=${t}MB, physicalCap(70%)=${r}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function Kr(n){if(n.startsWith("file:"))return n;try{let e=Il.resolve(n),t=new URL(`file://${e}`).toString();if(bp.platform()==="win32"){let r=t.match(/^file:\/\/\/([A-Za-z]):/);if(r){let i=r[1].toUpperCase(),o=t.substring(`file:///${r[1]}:`.length);t=`file:///${i}%3A${o}`}}return t}catch{return n}}function Dl(n){return n&&n.replace(/\\/g,"/")}function tt(n){let e=Il.normalize(n).replace(/\\/g,"/");if(bp.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function ja(n){return n||process.execPath||"node"}function Sp(n){let e=tt(n.lspLogPath),t=["--expose-gc",`--max-old-space-size=${n.serverMaxSize}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${e}`,n.serverPath,n.transportFlag??"--stdio",`--logger-path=${e}`,"--logger-level=TRACE"];return n.projectPath&&t.push(`--projectPath=${tt(n.projectPath)}`),n.sdkPath&&t.push(`--sdkPath=${tt(n.sdkPath)}`),t}function R_(n){return Il.join(n,"build-profile.json5")}var Do=class{constructor(e){this.projectRoot=e}getAllModuleInfo(){let e=R_(this.projectRoot);try{let t=or(e);if(typeof t!="object"||t===null)return[];let r=t.modules;return Array.isArray(r)?r.filter(i=>{if(typeof i!="object"||i===null)return!1;let o=i;return typeof o.name=="string"&&typeof o.srcPath=="string"}):[]}catch(t){return w.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};u();import{spawn as c3}from"child_process";import*as Bh from"fs";var l3=600*1e3;function u3(n,e,t){let r=t.split(/\s+/).filter(i=>i.length>0);return[n,[e,...r]]}function d3(n,e){let t=[],r=[],i="",o="";return n.stdout?.on("data",s=>{let a=s.toString();t.push(a),i=x_(i+a,e)}),n.stderr?.on("data",s=>{let a=s.toString();r.push(a),o=x_(o+a,c=>{w.info("[hvigor:err] %s",c),e?.(c)})}),{stdout:t,stderr:r,flush:()=>{i&&e?.(i),o&&(w.info("[hvigor:err] %s",o),e?.(o))}}}function x_(n,e){let t=n.split(/\r?\n/),r=t.pop()??"";for(let i of t)i&&e?.(i);return r}function Wh(n){return n.join("")}function p3(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
|
|
76
76
|
Output so far:
|
|
@@ -1444,7 +1444,7 @@ ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this
|
|
|
1444
1444
|
`):"No valid C/C++ files"}],isError:!0};for(let c of i){await mfe(pfe);try{let l=await this.checkFile(c);r.push(ffe(c,l))}catch(l){t.push(`${c} => wait for diagnostics failed: ${l.message}`)}}let o=t.length>0,s=[];t.length>0&&s.push(t.join(`
|
|
1445
1445
|
`)),r.length>0&&s.push(r.join(`
|
|
1446
1446
|
`));let a=s.join(`
|
|
1447
|
-
`).trim();return!o&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:o}}async checkFile(e){let t=zr(e),r=await Js.promises.readFile(e,"utf8"),i=_g(e),o=this.manager.registerDiagnosticCallback(t);this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:t,text:r,languageId:i,version:r.length}}});try{return await o}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:t}}})}}collectValidFiles(e,t){let r=Rc.resolve(this.manager.projectRoot),i=[];for(let o of e){let s=Rc.resolve(Rc.isAbsolute(o)?o:Rc.join(r,o));if(!Js.existsSync(s)){t.push(`File does not exist: ${o}`);continue}if(!Js.statSync(s).isFile()){t.push(`Not a regular file: ${o}`);continue}if(!Pa(s)){t.push(`Not a supported C/C++ file: ${o}`);continue}try{i.push(Js.realpathSync(s))}catch{i.push(s)}}return i}};function ffe(n,e){if(Array.isArray(e))return e.length===0?`${n} => no diagnostics`:`${n} => Diagnostic: ${JSON.stringify(e)}`;if(e&&typeof e=="object"&&typeof e.errorMessage=="string"){let t=e.errorMessage;return`${n} diagnostic failed, error_message: ${t}`}return`${n} => diagnostic failed, result: ${JSON.stringify(e)}`}function mfe(n){return new Promise(e=>setTimeout(e,n))}u();fr();Jt();import*as Ju from"fs";import*as ob from"path";var qu=class n{manager;static FEATURE_METHOD_MAP={hover:R.HOVER,definition:R.DEFINITION,declaration:R.DECLARATION,references:R.REFERENCES,implementation:R.IMPLEMENTATION};constructor(e){this.manager=e}async handleLspFeature(e,t){if(!this.manager.ready)return zu();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${t.file}`}],isError:!0};let i=n.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};v.info(`[ClangdLspTool] handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(r,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){return ib(e,o)}}async handleWorkspaceSymbolRaw(e){if(!this.manager.ready)return null;try{let t=await this.manager.sendFeatureRequest(R.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return v.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return zu();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e}`}],isError:!0};v.info(`[ClangdLspTool] handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(R.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){return ib("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return zu();if(e.direction==="outgoing")return{content:[{type:"text",text:"callHierarchy outgoing is not supported by clangd (incoming only)"}],isError:!0};let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e.file}`}],isError:!0};v.info(`[ClangdLspTool] handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,o=>this.fetchCallHierarchyResult(o,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return ib("callHierarchy",r)}}async fetchCallHierarchyResult(e,t){let r=await this.manager.sendFeatureRequest(R.PREPARE_CALL_HIERARCHY,{textDocument:{uri:e},position:{line:t.line,character:t.character}}),i=this.normalizeCallHierarchyItems(r);if(i.length===0)return{items:[],calls:[]};let o=await this.collectIncomingCalls(i);return{items:i,calls:o}}normalizeCallHierarchyItems(e){return Array.isArray(e)?e:e?[e]:[]}async collectIncomingCalls(e){let t=[];for(let r of e)t.push(...await this.fetchIncomingCalls(r));return t}async fetchIncomingCalls(e){let t=await this.manager.sendFeatureRequest(R.INCOMING_CALLS,{item:e});return Array.isArray(t)?t:t?[t]:[]}async withOpenFile(e,t){let r=zr(e),i=await Ju.promises.readFile(e,"utf8"),o=_g(e);v.info(`[ClangdLspTool] withOpenFile didOpen uri=${r} langId=${o} len=${i.length}`),this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:r,text:i,languageId:o,version:i.length}}});try{return await t(r)}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:r}}})}}resolveSingleFile(e){let t=ob.isAbsolute(e)?e:ob.join(this.manager.projectRoot,e);return!Ju.existsSync(t)||!Ju.statSync(t).isFile()||!Pa(t)?null:t}};fr();u();Je();import gfe from"fs";import*as cW from"path";function hfe(n){try{return gfe.statSync(cW.join(n,"AppScope","app.json5")).mtimeMs}catch{return-1}}function yfe(n){try{return V.discover(n).rootDir}catch{return null}}var sb=class{rootFor="";root=null;appJson5MtimeMs=-2;value;resolve(e){this.rootFor!==e&&(this.rootFor=e,this.root=yfe(e),this.appJson5MtimeMs=-2);let t=this.root;if(t===null)return;let r=hfe(t);return r!==this.appJson5MtimeMs&&(this.appJson5MtimeMs=r,this.value=V.tryResolveBundleName(t)),this.value}};Jt();u();u();import{spawn as wfe}from"child_process";import*as cb from"fs";import*as lW from"path";var vfe=30*1e3,bfe=30*1e3,ab=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new Vs;diagnosticWaiters=new Map;lastStartErrorMessage=null;onMessage=()=>{};disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}get clangdPid(){return this.clangdProcess?.pid??null}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}async start(e){let t=!1;try{w.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),w.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),w.info(`[ClangdLspProxy] compileCommandsDir: ${this.config.compileCommandsDir}`),this.ensureLogDir(),this.clangdProcess=this.spawnClangd();let r={serverPath:"",logPath:this.config.logPath,indexingDataLocation:this.config.logPath,cwd:this.config.workspaceRoot};this.client=new Bs(r),this.client.on("message",o=>this.handleRawMessage(o)),this.client.on("error",o=>this.handleError(o)),this.client.attachProcess(this.clangdProcess,{stderrAsError:!1});let i=this.buildInitializeParams();await this.sendLspRequest(R.INITIALIZE,i,Mn),w.info("[ClangdLspProxy] initialize response received"),this.sendNotification(R.INITIALIZED,{}),t=!0}catch(r){this.lastStartErrorMessage=r instanceof Error?r.message:String(r),w.error(`[ClangdLspProxy] initialization failed: ${this.lastStartErrorMessage}`),await this.dispose()}e?.(t)}async hover(e){return this.sendLspRequest(R.HOVER,e)}async definition(e){return this.sendLspRequest(R.DEFINITION,e)}async declaration(e){return this.sendLspRequest(R.DECLARATION,e)}async references(e){return this.sendLspRequest(R.REFERENCES,e)}async implementation(e){return this.sendLspRequest(R.IMPLEMENTATION,e)}async documentSymbol(e){return this.sendLspRequest(R.DOCUMENT_SYMBOL,e)}async workspaceSymbol(e){return this.sendLspRequest(R.WORKSPACE_SYMBOL,e)}async prepareCallHierarchy(e){return this.sendLspRequest(R.PREPARE_CALL_HIERARCHY,e)}async incomingCalls(e){return this.sendLspRequest(R.INCOMING_CALLS,e)}async sendFeatureRequest(e,t){return this.sendLspRequest(e,t)}sendDidOpen(e){this.sendNotification(R.DID_OPEN,e)}sendDidChange(e){this.sendNotification(R.DID_CHANGE,e)}sendDidClose(e){this.sendNotification(R.DID_CLOSE,e)}sendNotification(e,t){if(!this.client){w.warn("[ClangdLspProxy] sendNotification before ready, dropped");return}this.client.sendNotification(e,t)}registerDiagnosticCallback(e){let t=this.normalizeClangdUri(e);if(this.diagnosticWaiters.has(t)){w.warn(`[ClangdLspProxy] overwrite existing diagnostic waiter for ${t}`);let r=this.diagnosticWaiters.get(t);clearTimeout(r.timer),this.diagnosticWaiters.delete(t)}return new Promise((r,i)=>{let o=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&i(new Error(`Wait for clangd diagnostics timeout, uri: ${t}`))},bfe);this.diagnosticWaiters.set(t,{resolve:r,reject:i,timer:o})})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){this.requestCallbacks.rejectAll(new Error("ClangdLspProxy disposing"));for(let[,e]of this.diagnosticWaiters)clearTimeout(e.timer),e.reject(new Error("ClangdLspProxy disposing"));if(this.diagnosticWaiters.clear(),this.client&&this.clangdProcess)try{await this.sendLspRequest(R.SHUTDOWN,null,3e3).catch(e=>{w.warn(`[ClangdLspProxy] shutdown request failed: ${e}`)}),this.sendNotification(R.EXIT,null),await this.client.waitForExitOrTimeout(300)}catch(e){w.warn(`[ClangdLspProxy] dispose error: ${e}`)}if(this.clangdProcess){try{this.clangdProcess.exitCode===null&&this.clangdProcess.signalCode===null&&this.clangdProcess.kill()}catch{}this.clangdProcess=null}this.client=null}spawnClangd(){let e=[`--compile-commands-dir=${tt(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];w.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=wfe(this.config.clangdPath,e,{cwd:this.config.workspaceRoot,stdio:["pipe","pipe","pipe"],windowsHide:!0});if(!t.stdin||!t.stdout||!t.stderr)throw new Error("Failed to spawn clangd: stdio not available");return t}buildInitializeParams(){let e=Dl(this.config.workspaceRoot),t=Kr(e),r=lW.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.4.0-Test.911"},rootPath:e,rootUri:t,workspaceFolders:[{uri:t,name:r}],capabilities:this.buildClientCapabilities(),initializationOptions:null}}buildClientCapabilities(){return{textDocument:{synchronization:{didOpen:!0,didChange:!0,didClose:!0,willSave:!1,save:!1},publishDiagnostics:{relatedInformation:!0,versionSupport:!1,tagSupport:{valueSet:[1,2]}},hover:{contentFormat:["markdown","plaintext"]},completion:{contextSupport:!1,completionItemKind:{valueSet:[]}},signatureHelp:{signatureInformation:{documentationFormat:["markdown","plaintext"]}},references:{},declaration:{linkSupport:!0},definition:{linkSupport:!0},implementation:{linkSupport:!0},documentSymbol:{hierarchicalDocumentSymbolSupport:!0,symbolKind:{valueSet:[]}},callHierarchy:{dynamicRegistration:!1}},workspace:{symbol:{symbolKind:{valueSet:[]}},configuration:!1,didChangeWatchedFiles:{dynamicRegistration:!1}}}}sendLspRequest(e,t,r=vfe){if(!this.client)return Promise.reject(new Error("[ClangdLspProxy] client not ready"));let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,r);return this.client.sendRequest(e,t,i),o}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let i=r instanceof Error?r.message:String(r);w.error(`[ClangdLspProxy] JSON parse error: ${i}, raw: ${e.slice(0,200)}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotification(t):w.warn(`[ClangdLspProxy] unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t==null||typeof t!="string"&&typeof t!="number")return;let r=t;if(e.error!==void 0&&e.error!==null){let i=e.error;w.warn(`[ClangdLspProxy] LSP error id=${r}: code=${i.code??-1} message=${i.message??"unknown"}`),this.requestCallbacks.rejectPending(r,new Error(`LSP error ${i.code??-1}: ${i.message??"unknown"}`))}else this.requestCallbacks.resolvePending(r,e.result)}handleNotification(e){let t=e.method;if(t)switch(t){case R.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case R.PROGRESS:this.onMessage({jsonrpc:ie,method:R.PROGRESS,params:e.params});break;case R.WINDOW_SHOW_MESSAGE:w.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case R.WINDOW_LOG_MESSAGE:w.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:ie,method:t,params:e.params})}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=this.normalizeClangdUri(e.uri),r=this.diagnosticWaiters.get(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.diagnosticWaiters.get(s),r&&this.diagnosticWaiters.delete(s)}else r&&this.diagnosticWaiters.delete(t);if(!r)return;clearTimeout(r.timer);let i=Array.isArray(e.diagnostics)?e.diagnostics:[],o=i.length;w.info(`[ClangdLspProxy] diagnostics received uri=${t} count=${o}`),r.resolve(i)}handleError(e){for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear(),this.requestCallbacks.rejectAll(e),this.onMessage({jsonrpc:ie,method:R.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{cb.existsSync(this.config.logPath)||cb.mkdirSync(this.config.logPath,{recursive:!0})}catch{}}normalizeClangdUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=decodeURIComponent(t.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(r)&&(r=r.slice(1)),Kr(r)}}catch{}return e}};fr();import*as lb from"path";import*as XA from"fs";var em=class n{config;proxy=null;isInitialized=!1;onMessage=()=>{};disposeOnce=null;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;resolvedRoot="";constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}get ready(){return this.isInitialized&&this.proxy!==null}get clangdPid(){return this.proxy?.clangdPid??null}get projectRoot(){return this.resolvedRoot}async start(){if(!this.isInitialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doStart();try{await this.initPromise}catch(e){throw this.initPromise=null,e}}}sendNotification(e){if(!this.proxy){w.warn("[ClangdLspManager] sendNotification before LSP ready, dropped");return}this.dispatchNotification(e)}async sendFeatureRequest(e,t){if(!this.proxy)throw new Error("[ClangdLspManager] LSP not ready");return this.proxy.sendFeatureRequest(e,t)}registerDiagnosticCallback(e){return this.proxy?this.proxy.registerDiagnosticCallback(e):Promise.reject(new Error("[ClangdLspManager] LSP not ready"))}static async handleSyncCppProject(e,t,r,i,o){if(w.info("[ClangdLspManager] Received cpp/syncProject"),!e||!t)return w.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};if(ks(e).length===0)return w.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let a=o?.skipCompileNative===!0,c=await Mh(e,a?(async()=>(w.info("[ClangdLspManager] compileNative skipped (C++ project up-to-date)"),{status:"success"})):(async()=>{let l=Date.now(),d=await n.executeCompileNative(e,t,r,i),g=Date.now()-l;return d.status!=="success"?d:{...d,cppSyncDurationMs:g}}));return c.acquired?c.result:(w.info("[ClangdLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}static async executeCompileNative(e,t,r,i){try{return await O_(e,t,r,i),w.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(o){let s=o instanceof Error?o.message:String(o);return w.error(`[ClangdLspManager] compileNative failed: ${s}`),{status:"failed",reason:s}}}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}doStart(){return new Promise((e,t)=>{this.initResolve=e,this.initReject=t,this.armInitTimer(Mn);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=vo(this.config.workspaceRoot);this.resolvedRoot=e?Mt(e):Mt(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();Hh(t);let r=this.config.clangdPath;if(!r){let s="clangd not found (install DevEco Studio / CLT)";w.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let i=this.config.compileCommandsDir??lb.dirname(Ca(this.resolvedRoot));try{XA.mkdirSync(i,{recursive:!0})}catch(s){w.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${s}`)}w.info(`[ClangdLspManager] clangdPath: ${r}`),w.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),w.info(`[ClangdLspManager] compileCommandsDir: ${i}`);let o=new ab({clangdPath:r,workspaceRoot:this.resolvedRoot,compileCommandsDir:i,logPath:t});o.setOnMessage(s=>this.handleLspMessage(s)),this.proxy=o,o.start(s=>this.handleProxyInitialized(s)).catch(s=>{let a=s instanceof Error?s:new Error(String(s));this.handleProxyInitialized(!1,a.message)})}handleProxyInitialized=(e,t)=>{if(this.clearInitTimer(),e){this.isInitialized=!0,w.info("[ClangdLspManager] clangd initialized");let r=this.initResolve;this.clearInitHandlers(),r?.()}else{let r=t??this.proxy?.consumeStartErrorMessage()??"unknown error";w.error(`[ClangdLspManager] clangd initialization failed: ${r}`),this.isInitialized=!1,this.proxy=null;let i=this.initReject;this.clearInitHandlers(),i?.(new Error(`C++ LSP initialize failed: ${r}`))}};handleLspMessage(e){this.onMessage(e)}dispatchNotification(e){if(!this.proxy)return;let t=e,r=t.method;if(!r){w.warn("[ClangdLspManager] dispatchNotification: missing method");return}let i=t.params;switch(r){case R.DID_OPEN:this.proxy.sendDidOpen(i);break;case R.DID_CHANGE:this.proxy.sendDidChange(i);break;case R.DID_CLOSE:this.proxy.sendDidClose(i);break;default:this.proxy.sendNotification(r,i)}}armInitTimer(e){this.clearInitTimer(),this.initDeadlineTimer=setTimeout(()=>{this.failInit(new Error("C++ LSP initialize timeout"))},e)}clearInitTimer(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null)}clearInitHandlers(){this.clearInitTimer(),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async performDispose(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("ClangdLspManager disposing")),this.proxy){try{await this.proxy.dispose()}catch(t){w.warn(`[ClangdLspManager] proxy dispose error: ${t}`)}this.proxy=null}this.isInitialized=!1,this.initPromise=null}getLogPath(){let e=`${Date.now()}${process.hrtime.bigint()%1000000n}`;return tE(t=>{let r=lb.join(t,"CppCheck","lsp-log",e);return XA.mkdirSync(r,{recursive:!0}),Mt(r)})??"auto"}};u();function uW(n){let e=Fh(n);return w.info(`[SyncGuard] ${e.reason}`),e}var pW=(s=>(s[s.IDLE_CPP=0]="IDLE_CPP",s[s.DISCOVERING_CPP=1]="DISCOVERING_CPP",s[s.SYNCING_CPP=2]="SYNCING_CPP",s[s.INITIALIZING_CPP=3]="INITIALIZING_CPP",s[s.READY_CPP=4]="READY_CPP",s[s.ERROR_CPP=5]="ERROR_CPP",s))(pW||{}),io=3,QA=600*1e3,ZA=100,ub=["ohpm","hvigor","dep-parse","lsp-init"],dW={ohpm:"ohpm install",hvigor:"hvigor sync","dep-parse":"dependency parse","lsp-init":"LSP init"},tm=15;function Efe(n){let{subAction:e,mcpMemory:t,lspMemory:r}=n,i={event:b.McpToolCall,subAction:e,mcpMemory:t,lspMemory:r,...n.bundleName!==void 0?{bundleName:n.bundleName}:{}};return e==="init_cpp"?{...i,cppSyncDurationMs:n.cppSyncDurationMs??0}:{...i,ohpmDurationMs:n.ohpmDurationMs??0,syncDurationMs:n.syncDurationMs??0}}var db=class{server;toolRouter;config={};arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";sdkPath="";arktsLangServerPath=null;nodePath="";ohpmJsPath="";hvigorJsPath="";clangdPath=null;initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;arktsInitProgress=null;arktsPipelineStartedAt=0;standardProtocolAvailable=!1;socketAvailable=!1;cppProjectState=0;cppInitPromise=null;cppNeedsReinit=!1;cppInitRetryCount=0;cppSyncSkippedDueToLock=!1;cppSyncSkipStartedAt=0;cppHasNoCppCode=!1;cppEnabled;cppCustomCompileCommandsDir=null;cppCustomDirResolvedFor="";bundleNameResolver=new sb;constructor(e={}){this.config=e,Ra(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),v.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",v.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,v.info(`Constructor: using configured path as startPath: '${t}'`));let i=vo(t);v.info(`Constructor: findHarmonyProject('${t}') => ${i??"null"}`),this.config.projectPath=i??void 0,this.sdkPath=this.config.sdkPath??"",this.arktsLangServerPath=this.config.arktsLangServerPath??null,this.nodePath=this.config.nodePath??"",this.ohpmJsPath=this.config.ohpmJsPath??"",this.hvigorJsPath=this.config.hvigorJsPath??"",this.clangdPath=this.config.clangdPath??null,this.cppEnabled=this.config.cppEnabled??!0,v.info(`Constructor: sdkPath='${this.sdkPath}', arktsLangServerPath='${this.arktsLangServerPath??"(null)"}', cppEnabled=${this.cppEnabled}, cppCompileCommandsPath='${this.config.cppCompileCommandsPath??"(none)"}'`),this.server=new Sfe({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=GA(e.telemetry,()=>this.arktsCheckTool?.aceServerPid??null,()=>this.config.projectPath??"",()=>this.sdkPath??"",()=>this.resolveProjectBundleName()),this.standardProtocolAvailable=this.detectStandardProtocolAvailable()}registerTools(){this.registerCheckTool(),this.registerLspFeatureTools(),this.socketAvailable||this.registerRestartTool()}registerRestartTool(){this.toolRouter.add({name:"restart",description:"Restart the MCP server in-place: re-sync the project and re-initialize the LSP, without dropping the client connection. Use to recover from a stuck/ERROR state after fixing the root cause, instead of exiting and reopening the agent. Use target to restart one side only (arkts/cpp) or both (all, default). Only callable when the project state is ready/idle/error; during discovery/sync/init (large-project init can take minutes) it returns an error\u2014wait for ready and retry tools instead. Caution: if initialization fails again after a restart, the cause is likely a persistent project/SDK configuration issue\u2014do not call restart repeatedly; ask the user to fix the project first.",inputSchema:$t.object({target:$t.enum(["arkts","cpp","all"]).default("all").describe('Which backend to restart: "arkts" (ArkTS ace-server), "cpp" (C++ clangd), or "all" (both, default).')})},async e=>this.handleRestartCall(e))}registerCheckTool(){this.toolRouter.add({name:"check",description:"Perform static syntax analysis on HarmonyOS project source files and return structured diagnostics. Supported languages: ArkTS and C/C++.",inputSchema:$t.object({files:$t.array($t.string()).min(1).describe("List of source file paths to check, relative to the project root (absolute paths within the project are also accepted). Supports ArkTS and C/C++ files in the same call.")})},async e=>this.handleCheckCall(e))}registerLspFeatureTools(){if(!this.standardProtocolAvailable){v.info("Skip registering LSP feature tools (hover/definition/declaration/references/implementation, workspaceSymbol, documentSymbol, callHierarchy): standard LSP protocol unavailable (standardIndex/index.js not found). These tools require a DevEco Studio version that ships the standard LSP server entry.");return}let e=$t.object({file:$t.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets (ArkTS) and C/C++ extensions."),line:$t.number().describe("Line number (0-based)"),character:$t.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:r,feature:i}of this.getPositionFeatures())this.toolRouter.add({name:t,description:r,inputSchema:e},async o=>this.handleLspFeatureCall(i,o));this.registerSymbolTools(),this.registerCallHierarchyTool()}getPositionFeatures(){return[{name:"hover",description:"Get hover information (type info, documentation) at a specific position in an ArkTS (.ets) or C/C++ file.",feature:"hover"},{name:"definition",description:"Find where the symbol at the given position is defined. Returns file path, line, and character.",feature:"definition"},{name:"declaration",description:"Find the declaration of the symbol at the given position. In ArkTS, this may differ from definition.",feature:"declaration"},{name:"references",description:"Find all references to the symbol at the given position across the HarmonyOS project.",feature:"references"},{name:"implementation",description:"Find implementations of the symbol at the given position (e.g., interface implementations).",feature:"implementation"}]}registerSymbolTools(){this.toolRouter.add({name:"workspaceSymbol",description:"Search for symbols by name across the entire HarmonyOS project.",inputSchema:$t.object({query:$t.string().describe("Symbol name (or partial) to search for")})},async e=>this.handleWorkspaceSymbolCall(e)),this.toolRouter.add({name:"documentSymbol",description:"Get the symbol tree (functions, classes, variables with ranges) of an ArkTS (.ets) or C/C++ file. Useful for file overview, structured code breakdown, and large file slicing.",inputSchema:$t.object({file:$t.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets and C/C++ extensions.")})},async e=>this.handleDocumentSymbolCall(e))}registerCallHierarchyTool(){this.toolRouter.add({name:"callHierarchy",description:'Query call hierarchy for a function at the given position. Use direction "incoming" to find callers, "outgoing" to find callees. ArkTS supports both directions; C/C++ (clangd) supports incoming only.',inputSchema:$t.object({file:$t.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets and C/C++ extensions."),line:$t.number().describe("Line number (0-based)"),character:$t.number().describe("Character offset in the line (0-based)"),direction:$t.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.arktsLangServerPath;if(!e)return v.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=Ng(e);return v.info(`ArktsCheck protocol: ${t?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${t})`),t}catch(e){return v.warn(`Failed to detect standard LSP protocol availability: ${e}`),!1}}async detectSocketAvailable(){try{let e=this.arktsLangServerPath;if(!e){this.socketAvailable=!1;return}this.socketAvailable=await tN(e,ja(this.nodePath)),v.info(`Socket transport: ${this.socketAvailable?"enabled":"disabled (stdio mode)"} (--list-protocols probe)`)}catch{this.socketAvailable=!1}}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(d=>typeof d=="string"):[];if(t.length===0)return v.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};if(t.length>ZA)return v.warn(`check tool called with ${t.length} files (max: ${ZA})`),{content:[{type:"text",text:`Too many files: ${t.length}. Maximum allowed is ${ZA}.`}],isError:!0};let{etsFiles:r,cppFiles:i,unsupported:o}=Cfe(t);o.length>0&&v.warn(`Unsupported file types in check request: ${o.join(", ")}`);let s=o.map(d=>`Unsupported file type: ${d} (only .ets and C/C++ source/header files are supported)`),a=[];r.length>0&&this.mergeCheckResult(await this.callArktsCheck(r),s,a),i.length>0&&this.mergeCheckResult(await this.callCppCheck(i),s,a);let c=s.length>0;return{content:[{type:"text",text:[a.join(`
|
|
1447
|
+
`).trim();return!o&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:o}}async checkFile(e){let t=zr(e),r=await Js.promises.readFile(e,"utf8"),i=_g(e),o=this.manager.registerDiagnosticCallback(t);this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:t,text:r,languageId:i,version:r.length}}});try{return await o}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:t}}})}}collectValidFiles(e,t){let r=Rc.resolve(this.manager.projectRoot),i=[];for(let o of e){let s=Rc.resolve(Rc.isAbsolute(o)?o:Rc.join(r,o));if(!Js.existsSync(s)){t.push(`File does not exist: ${o}`);continue}if(!Js.statSync(s).isFile()){t.push(`Not a regular file: ${o}`);continue}if(!Pa(s)){t.push(`Not a supported C/C++ file: ${o}`);continue}try{i.push(Js.realpathSync(s))}catch{i.push(s)}}return i}};function ffe(n,e){if(Array.isArray(e))return e.length===0?`${n} => no diagnostics`:`${n} => Diagnostic: ${JSON.stringify(e)}`;if(e&&typeof e=="object"&&typeof e.errorMessage=="string"){let t=e.errorMessage;return`${n} diagnostic failed, error_message: ${t}`}return`${n} => diagnostic failed, result: ${JSON.stringify(e)}`}function mfe(n){return new Promise(e=>setTimeout(e,n))}u();fr();Jt();import*as Ju from"fs";import*as ob from"path";var qu=class n{manager;static FEATURE_METHOD_MAP={hover:R.HOVER,definition:R.DEFINITION,declaration:R.DECLARATION,references:R.REFERENCES,implementation:R.IMPLEMENTATION};constructor(e){this.manager=e}async handleLspFeature(e,t){if(!this.manager.ready)return zu();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${t.file}`}],isError:!0};let i=n.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};v.info(`[ClangdLspTool] handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(r,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){return ib(e,o)}}async handleWorkspaceSymbolRaw(e){if(!this.manager.ready)return null;try{let t=await this.manager.sendFeatureRequest(R.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return v.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return zu();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e}`}],isError:!0};v.info(`[ClangdLspTool] handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(R.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){return ib("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return zu();if(e.direction==="outgoing")return{content:[{type:"text",text:"callHierarchy outgoing is not supported by clangd (incoming only)"}],isError:!0};let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e.file}`}],isError:!0};v.info(`[ClangdLspTool] handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,o=>this.fetchCallHierarchyResult(o,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return ib("callHierarchy",r)}}async fetchCallHierarchyResult(e,t){let r=await this.manager.sendFeatureRequest(R.PREPARE_CALL_HIERARCHY,{textDocument:{uri:e},position:{line:t.line,character:t.character}}),i=this.normalizeCallHierarchyItems(r);if(i.length===0)return{items:[],calls:[]};let o=await this.collectIncomingCalls(i);return{items:i,calls:o}}normalizeCallHierarchyItems(e){return Array.isArray(e)?e:e?[e]:[]}async collectIncomingCalls(e){let t=[];for(let r of e)t.push(...await this.fetchIncomingCalls(r));return t}async fetchIncomingCalls(e){let t=await this.manager.sendFeatureRequest(R.INCOMING_CALLS,{item:e});return Array.isArray(t)?t:t?[t]:[]}async withOpenFile(e,t){let r=zr(e),i=await Ju.promises.readFile(e,"utf8"),o=_g(e);v.info(`[ClangdLspTool] withOpenFile didOpen uri=${r} langId=${o} len=${i.length}`),this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:r,text:i,languageId:o,version:i.length}}});try{return await t(r)}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:r}}})}}resolveSingleFile(e){let t=ob.isAbsolute(e)?e:ob.join(this.manager.projectRoot,e);return!Ju.existsSync(t)||!Ju.statSync(t).isFile()||!Pa(t)?null:t}};fr();u();Je();import gfe from"fs";import*as cW from"path";function hfe(n){try{return gfe.statSync(cW.join(n,"AppScope","app.json5")).mtimeMs}catch{return-1}}function yfe(n){try{return V.discover(n).rootDir}catch{return null}}var sb=class{rootFor="";root=null;appJson5MtimeMs=-2;value;resolve(e){this.rootFor!==e&&(this.rootFor=e,this.root=yfe(e),this.appJson5MtimeMs=-2);let t=this.root;if(t===null)return;let r=hfe(t);return r!==this.appJson5MtimeMs&&(this.appJson5MtimeMs=r,this.value=V.tryResolveBundleName(t)),this.value}};Jt();u();u();import{spawn as wfe}from"child_process";import*as cb from"fs";import*as lW from"path";var vfe=30*1e3,bfe=30*1e3,ab=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new Vs;diagnosticWaiters=new Map;lastStartErrorMessage=null;onMessage=()=>{};disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}get clangdPid(){return this.clangdProcess?.pid??null}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}async start(e){let t=!1;try{w.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),w.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),w.info(`[ClangdLspProxy] compileCommandsDir: ${this.config.compileCommandsDir}`),this.ensureLogDir(),this.clangdProcess=this.spawnClangd();let r={serverPath:"",logPath:this.config.logPath,indexingDataLocation:this.config.logPath,cwd:this.config.workspaceRoot};this.client=new Bs(r),this.client.on("message",o=>this.handleRawMessage(o)),this.client.on("error",o=>this.handleError(o)),this.client.attachProcess(this.clangdProcess,{stderrAsError:!1});let i=this.buildInitializeParams();await this.sendLspRequest(R.INITIALIZE,i,Mn),w.info("[ClangdLspProxy] initialize response received"),this.sendNotification(R.INITIALIZED,{}),t=!0}catch(r){this.lastStartErrorMessage=r instanceof Error?r.message:String(r),w.error(`[ClangdLspProxy] initialization failed: ${this.lastStartErrorMessage}`),await this.dispose()}e?.(t)}async hover(e){return this.sendLspRequest(R.HOVER,e)}async definition(e){return this.sendLspRequest(R.DEFINITION,e)}async declaration(e){return this.sendLspRequest(R.DECLARATION,e)}async references(e){return this.sendLspRequest(R.REFERENCES,e)}async implementation(e){return this.sendLspRequest(R.IMPLEMENTATION,e)}async documentSymbol(e){return this.sendLspRequest(R.DOCUMENT_SYMBOL,e)}async workspaceSymbol(e){return this.sendLspRequest(R.WORKSPACE_SYMBOL,e)}async prepareCallHierarchy(e){return this.sendLspRequest(R.PREPARE_CALL_HIERARCHY,e)}async incomingCalls(e){return this.sendLspRequest(R.INCOMING_CALLS,e)}async sendFeatureRequest(e,t){return this.sendLspRequest(e,t)}sendDidOpen(e){this.sendNotification(R.DID_OPEN,e)}sendDidChange(e){this.sendNotification(R.DID_CHANGE,e)}sendDidClose(e){this.sendNotification(R.DID_CLOSE,e)}sendNotification(e,t){if(!this.client){w.warn("[ClangdLspProxy] sendNotification before ready, dropped");return}this.client.sendNotification(e,t)}registerDiagnosticCallback(e){let t=this.normalizeClangdUri(e);if(this.diagnosticWaiters.has(t)){w.warn(`[ClangdLspProxy] overwrite existing diagnostic waiter for ${t}`);let r=this.diagnosticWaiters.get(t);clearTimeout(r.timer),this.diagnosticWaiters.delete(t)}return new Promise((r,i)=>{let o=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&i(new Error(`Wait for clangd diagnostics timeout, uri: ${t}`))},bfe);this.diagnosticWaiters.set(t,{resolve:r,reject:i,timer:o})})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){this.requestCallbacks.rejectAll(new Error("ClangdLspProxy disposing"));for(let[,e]of this.diagnosticWaiters)clearTimeout(e.timer),e.reject(new Error("ClangdLspProxy disposing"));if(this.diagnosticWaiters.clear(),this.client&&this.clangdProcess)try{await this.sendLspRequest(R.SHUTDOWN,null,3e3).catch(e=>{w.warn(`[ClangdLspProxy] shutdown request failed: ${e}`)}),this.sendNotification(R.EXIT,null),await this.client.waitForExitOrTimeout(300)}catch(e){w.warn(`[ClangdLspProxy] dispose error: ${e}`)}if(this.clangdProcess){try{this.clangdProcess.exitCode===null&&this.clangdProcess.signalCode===null&&this.clangdProcess.kill()}catch{}this.clangdProcess=null}this.client=null}spawnClangd(){let e=[`--compile-commands-dir=${tt(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];w.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=wfe(this.config.clangdPath,e,{cwd:this.config.workspaceRoot,stdio:["pipe","pipe","pipe"],windowsHide:!0});if(!t.stdin||!t.stdout||!t.stderr)throw new Error("Failed to spawn clangd: stdio not available");return t}buildInitializeParams(){let e=Dl(this.config.workspaceRoot),t=Kr(e),r=lW.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.4.0-Test.912"},rootPath:e,rootUri:t,workspaceFolders:[{uri:t,name:r}],capabilities:this.buildClientCapabilities(),initializationOptions:null}}buildClientCapabilities(){return{textDocument:{synchronization:{didOpen:!0,didChange:!0,didClose:!0,willSave:!1,save:!1},publishDiagnostics:{relatedInformation:!0,versionSupport:!1,tagSupport:{valueSet:[1,2]}},hover:{contentFormat:["markdown","plaintext"]},completion:{contextSupport:!1,completionItemKind:{valueSet:[]}},signatureHelp:{signatureInformation:{documentationFormat:["markdown","plaintext"]}},references:{},declaration:{linkSupport:!0},definition:{linkSupport:!0},implementation:{linkSupport:!0},documentSymbol:{hierarchicalDocumentSymbolSupport:!0,symbolKind:{valueSet:[]}},callHierarchy:{dynamicRegistration:!1}},workspace:{symbol:{symbolKind:{valueSet:[]}},configuration:!1,didChangeWatchedFiles:{dynamicRegistration:!1}}}}sendLspRequest(e,t,r=vfe){if(!this.client)return Promise.reject(new Error("[ClangdLspProxy] client not ready"));let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,r);return this.client.sendRequest(e,t,i),o}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let i=r instanceof Error?r.message:String(r);w.error(`[ClangdLspProxy] JSON parse error: ${i}, raw: ${e.slice(0,200)}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotification(t):w.warn(`[ClangdLspProxy] unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t==null||typeof t!="string"&&typeof t!="number")return;let r=t;if(e.error!==void 0&&e.error!==null){let i=e.error;w.warn(`[ClangdLspProxy] LSP error id=${r}: code=${i.code??-1} message=${i.message??"unknown"}`),this.requestCallbacks.rejectPending(r,new Error(`LSP error ${i.code??-1}: ${i.message??"unknown"}`))}else this.requestCallbacks.resolvePending(r,e.result)}handleNotification(e){let t=e.method;if(t)switch(t){case R.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case R.PROGRESS:this.onMessage({jsonrpc:ie,method:R.PROGRESS,params:e.params});break;case R.WINDOW_SHOW_MESSAGE:w.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case R.WINDOW_LOG_MESSAGE:w.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:ie,method:t,params:e.params})}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=this.normalizeClangdUri(e.uri),r=this.diagnosticWaiters.get(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.diagnosticWaiters.get(s),r&&this.diagnosticWaiters.delete(s)}else r&&this.diagnosticWaiters.delete(t);if(!r)return;clearTimeout(r.timer);let i=Array.isArray(e.diagnostics)?e.diagnostics:[],o=i.length;w.info(`[ClangdLspProxy] diagnostics received uri=${t} count=${o}`),r.resolve(i)}handleError(e){for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear(),this.requestCallbacks.rejectAll(e),this.onMessage({jsonrpc:ie,method:R.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{cb.existsSync(this.config.logPath)||cb.mkdirSync(this.config.logPath,{recursive:!0})}catch{}}normalizeClangdUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=decodeURIComponent(t.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(r)&&(r=r.slice(1)),Kr(r)}}catch{}return e}};fr();import*as lb from"path";import*as XA from"fs";var em=class n{config;proxy=null;isInitialized=!1;onMessage=()=>{};disposeOnce=null;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;resolvedRoot="";constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}get ready(){return this.isInitialized&&this.proxy!==null}get clangdPid(){return this.proxy?.clangdPid??null}get projectRoot(){return this.resolvedRoot}async start(){if(!this.isInitialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doStart();try{await this.initPromise}catch(e){throw this.initPromise=null,e}}}sendNotification(e){if(!this.proxy){w.warn("[ClangdLspManager] sendNotification before LSP ready, dropped");return}this.dispatchNotification(e)}async sendFeatureRequest(e,t){if(!this.proxy)throw new Error("[ClangdLspManager] LSP not ready");return this.proxy.sendFeatureRequest(e,t)}registerDiagnosticCallback(e){return this.proxy?this.proxy.registerDiagnosticCallback(e):Promise.reject(new Error("[ClangdLspManager] LSP not ready"))}static async handleSyncCppProject(e,t,r,i,o){if(w.info("[ClangdLspManager] Received cpp/syncProject"),!e||!t)return w.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};if(ks(e).length===0)return w.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let a=o?.skipCompileNative===!0,c=await Mh(e,a?(async()=>(w.info("[ClangdLspManager] compileNative skipped (C++ project up-to-date)"),{status:"success"})):(async()=>{let l=Date.now(),d=await n.executeCompileNative(e,t,r,i),g=Date.now()-l;return d.status!=="success"?d:{...d,cppSyncDurationMs:g}}));return c.acquired?c.result:(w.info("[ClangdLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}static async executeCompileNative(e,t,r,i){try{return await O_(e,t,r,i),w.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(o){let s=o instanceof Error?o.message:String(o);return w.error(`[ClangdLspManager] compileNative failed: ${s}`),{status:"failed",reason:s}}}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}doStart(){return new Promise((e,t)=>{this.initResolve=e,this.initReject=t,this.armInitTimer(Mn);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=vo(this.config.workspaceRoot);this.resolvedRoot=e?Mt(e):Mt(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();Hh(t);let r=this.config.clangdPath;if(!r){let s="clangd not found (install DevEco Studio / CLT)";w.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let i=this.config.compileCommandsDir??lb.dirname(Ca(this.resolvedRoot));try{XA.mkdirSync(i,{recursive:!0})}catch(s){w.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${s}`)}w.info(`[ClangdLspManager] clangdPath: ${r}`),w.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),w.info(`[ClangdLspManager] compileCommandsDir: ${i}`);let o=new ab({clangdPath:r,workspaceRoot:this.resolvedRoot,compileCommandsDir:i,logPath:t});o.setOnMessage(s=>this.handleLspMessage(s)),this.proxy=o,o.start(s=>this.handleProxyInitialized(s)).catch(s=>{let a=s instanceof Error?s:new Error(String(s));this.handleProxyInitialized(!1,a.message)})}handleProxyInitialized=(e,t)=>{if(this.clearInitTimer(),e){this.isInitialized=!0,w.info("[ClangdLspManager] clangd initialized");let r=this.initResolve;this.clearInitHandlers(),r?.()}else{let r=t??this.proxy?.consumeStartErrorMessage()??"unknown error";w.error(`[ClangdLspManager] clangd initialization failed: ${r}`),this.isInitialized=!1,this.proxy=null;let i=this.initReject;this.clearInitHandlers(),i?.(new Error(`C++ LSP initialize failed: ${r}`))}};handleLspMessage(e){this.onMessage(e)}dispatchNotification(e){if(!this.proxy)return;let t=e,r=t.method;if(!r){w.warn("[ClangdLspManager] dispatchNotification: missing method");return}let i=t.params;switch(r){case R.DID_OPEN:this.proxy.sendDidOpen(i);break;case R.DID_CHANGE:this.proxy.sendDidChange(i);break;case R.DID_CLOSE:this.proxy.sendDidClose(i);break;default:this.proxy.sendNotification(r,i)}}armInitTimer(e){this.clearInitTimer(),this.initDeadlineTimer=setTimeout(()=>{this.failInit(new Error("C++ LSP initialize timeout"))},e)}clearInitTimer(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null)}clearInitHandlers(){this.clearInitTimer(),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async performDispose(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("ClangdLspManager disposing")),this.proxy){try{await this.proxy.dispose()}catch(t){w.warn(`[ClangdLspManager] proxy dispose error: ${t}`)}this.proxy=null}this.isInitialized=!1,this.initPromise=null}getLogPath(){let e=`${Date.now()}${process.hrtime.bigint()%1000000n}`;return tE(t=>{let r=lb.join(t,"CppCheck","lsp-log",e);return XA.mkdirSync(r,{recursive:!0}),Mt(r)})??"auto"}};u();function uW(n){let e=Fh(n);return w.info(`[SyncGuard] ${e.reason}`),e}var pW=(s=>(s[s.IDLE_CPP=0]="IDLE_CPP",s[s.DISCOVERING_CPP=1]="DISCOVERING_CPP",s[s.SYNCING_CPP=2]="SYNCING_CPP",s[s.INITIALIZING_CPP=3]="INITIALIZING_CPP",s[s.READY_CPP=4]="READY_CPP",s[s.ERROR_CPP=5]="ERROR_CPP",s))(pW||{}),io=3,QA=600*1e3,ZA=100,ub=["ohpm","hvigor","dep-parse","lsp-init"],dW={ohpm:"ohpm install",hvigor:"hvigor sync","dep-parse":"dependency parse","lsp-init":"LSP init"},tm=15;function Efe(n){let{subAction:e,mcpMemory:t,lspMemory:r}=n,i={event:b.McpToolCall,subAction:e,mcpMemory:t,lspMemory:r,...n.bundleName!==void 0?{bundleName:n.bundleName}:{}};return e==="init_cpp"?{...i,cppSyncDurationMs:n.cppSyncDurationMs??0}:{...i,ohpmDurationMs:n.ohpmDurationMs??0,syncDurationMs:n.syncDurationMs??0}}var db=class{server;toolRouter;config={};arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";sdkPath="";arktsLangServerPath=null;nodePath="";ohpmJsPath="";hvigorJsPath="";clangdPath=null;initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;arktsInitProgress=null;arktsPipelineStartedAt=0;standardProtocolAvailable=!1;socketAvailable=!1;cppProjectState=0;cppInitPromise=null;cppNeedsReinit=!1;cppInitRetryCount=0;cppSyncSkippedDueToLock=!1;cppSyncSkipStartedAt=0;cppHasNoCppCode=!1;cppEnabled;cppCustomCompileCommandsDir=null;cppCustomDirResolvedFor="";bundleNameResolver=new sb;constructor(e={}){this.config=e,Ra(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),v.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",v.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,v.info(`Constructor: using configured path as startPath: '${t}'`));let i=vo(t);v.info(`Constructor: findHarmonyProject('${t}') => ${i??"null"}`),this.config.projectPath=i??void 0,this.sdkPath=this.config.sdkPath??"",this.arktsLangServerPath=this.config.arktsLangServerPath??null,this.nodePath=this.config.nodePath??"",this.ohpmJsPath=this.config.ohpmJsPath??"",this.hvigorJsPath=this.config.hvigorJsPath??"",this.clangdPath=this.config.clangdPath??null,this.cppEnabled=this.config.cppEnabled??!0,v.info(`Constructor: sdkPath='${this.sdkPath}', arktsLangServerPath='${this.arktsLangServerPath??"(null)"}', cppEnabled=${this.cppEnabled}, cppCompileCommandsPath='${this.config.cppCompileCommandsPath??"(none)"}'`),this.server=new Sfe({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=GA(e.telemetry,()=>this.arktsCheckTool?.aceServerPid??null,()=>this.config.projectPath??"",()=>this.sdkPath??"",()=>this.resolveProjectBundleName()),this.standardProtocolAvailable=this.detectStandardProtocolAvailable()}registerTools(){this.registerCheckTool(),this.registerLspFeatureTools(),this.socketAvailable||this.registerRestartTool()}registerRestartTool(){this.toolRouter.add({name:"restart",description:"Restart the MCP server in-place: re-sync the project and re-initialize the LSP, without dropping the client connection. Use to recover from a stuck/ERROR state after fixing the root cause, instead of exiting and reopening the agent. Use target to restart one side only (arkts/cpp) or both (all, default). Only callable when the project state is ready/idle/error; during discovery/sync/init (large-project init can take minutes) it returns an error\u2014wait for ready and retry tools instead. Caution: if initialization fails again after a restart, the cause is likely a persistent project/SDK configuration issue\u2014do not call restart repeatedly; ask the user to fix the project first.",inputSchema:$t.object({target:$t.enum(["arkts","cpp","all"]).default("all").describe('Which backend to restart: "arkts" (ArkTS ace-server), "cpp" (C++ clangd), or "all" (both, default).')})},async e=>this.handleRestartCall(e))}registerCheckTool(){this.toolRouter.add({name:"check",description:"Perform static syntax analysis on HarmonyOS project source files and return structured diagnostics. Supported languages: ArkTS and C/C++.",inputSchema:$t.object({files:$t.array($t.string()).min(1).describe("List of source file paths to check, relative to the project root (absolute paths within the project are also accepted). Supports ArkTS and C/C++ files in the same call.")})},async e=>this.handleCheckCall(e))}registerLspFeatureTools(){if(!this.standardProtocolAvailable){v.info("Skip registering LSP feature tools (hover/definition/declaration/references/implementation, workspaceSymbol, documentSymbol, callHierarchy): standard LSP protocol unavailable (standardIndex/index.js not found). These tools require a DevEco Studio version that ships the standard LSP server entry.");return}let e=$t.object({file:$t.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets (ArkTS) and C/C++ extensions."),line:$t.number().describe("Line number (0-based)"),character:$t.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:r,feature:i}of this.getPositionFeatures())this.toolRouter.add({name:t,description:r,inputSchema:e},async o=>this.handleLspFeatureCall(i,o));this.registerSymbolTools(),this.registerCallHierarchyTool()}getPositionFeatures(){return[{name:"hover",description:"Get hover information (type info, documentation) at a specific position in an ArkTS (.ets) or C/C++ file.",feature:"hover"},{name:"definition",description:"Find where the symbol at the given position is defined. Returns file path, line, and character.",feature:"definition"},{name:"declaration",description:"Find the declaration of the symbol at the given position. In ArkTS, this may differ from definition.",feature:"declaration"},{name:"references",description:"Find all references to the symbol at the given position across the HarmonyOS project.",feature:"references"},{name:"implementation",description:"Find implementations of the symbol at the given position (e.g., interface implementations).",feature:"implementation"}]}registerSymbolTools(){this.toolRouter.add({name:"workspaceSymbol",description:"Search for symbols by name across the entire HarmonyOS project.",inputSchema:$t.object({query:$t.string().describe("Symbol name (or partial) to search for")})},async e=>this.handleWorkspaceSymbolCall(e)),this.toolRouter.add({name:"documentSymbol",description:"Get the symbol tree (functions, classes, variables with ranges) of an ArkTS (.ets) or C/C++ file. Useful for file overview, structured code breakdown, and large file slicing.",inputSchema:$t.object({file:$t.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets and C/C++ extensions.")})},async e=>this.handleDocumentSymbolCall(e))}registerCallHierarchyTool(){this.toolRouter.add({name:"callHierarchy",description:'Query call hierarchy for a function at the given position. Use direction "incoming" to find callers, "outgoing" to find callees. ArkTS supports both directions; C/C++ (clangd) supports incoming only.',inputSchema:$t.object({file:$t.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets and C/C++ extensions."),line:$t.number().describe("Line number (0-based)"),character:$t.number().describe("Character offset in the line (0-based)"),direction:$t.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.arktsLangServerPath;if(!e)return v.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=Ng(e);return v.info(`ArktsCheck protocol: ${t?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${t})`),t}catch(e){return v.warn(`Failed to detect standard LSP protocol availability: ${e}`),!1}}async detectSocketAvailable(){try{let e=this.arktsLangServerPath;if(!e){this.socketAvailable=!1;return}this.socketAvailable=await tN(e,ja(this.nodePath)),v.info(`Socket transport: ${this.socketAvailable?"enabled":"disabled (stdio mode)"} (--list-protocols probe)`)}catch{this.socketAvailable=!1}}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(d=>typeof d=="string"):[];if(t.length===0)return v.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};if(t.length>ZA)return v.warn(`check tool called with ${t.length} files (max: ${ZA})`),{content:[{type:"text",text:`Too many files: ${t.length}. Maximum allowed is ${ZA}.`}],isError:!0};let{etsFiles:r,cppFiles:i,unsupported:o}=Cfe(t);o.length>0&&v.warn(`Unsupported file types in check request: ${o.join(", ")}`);let s=o.map(d=>`Unsupported file type: ${d} (only .ets and C/C++ source/header files are supported)`),a=[];r.length>0&&this.mergeCheckResult(await this.callArktsCheck(r),s,a),i.length>0&&this.mergeCheckResult(await this.callCppCheck(i),s,a);let c=s.length>0;return{content:[{type:"text",text:[a.join(`
|
|
1448
1448
|
`),s.join(`
|
|
1449
1449
|
`)].filter(d=>d.trim().length>0).join(`
|
|
1450
1450
|
`).trim()||"No diagnostics collected"}],isError:c}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:return v.warn(`ArkTS check rejected: project is DISCOVERING, files: ${e.join(", ")}`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 2:return v.warn(`ArkTS check rejected: project is SYNCING, files: ${e.join(", ")}`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 3:return v.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 5:return this.handleErrorCheck();case 4:return this.arktsCheckTool.handleCall({files:e});default:return v.error(`ArkTS check: unknown project state ${this.projectState}, files: ${e.join(", ")}`),{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],isError:!0}}}async handleLspFeatureCall(e,t){let r=t.file,i=t.line,o=t.character;return typeof r!="string"||typeof i!="number"||typeof o!="number"?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}:this.routeLspRequest(r,e,async()=>{if(r.endsWith(".ets"))return this.arktsCheckTool.handleLspFeature(e,{file:r,line:i,character:o});let s=e;return this.cppLspTool.handleLspFeature(s,{file:r,line:i,character:o})})}async handleWorkspaceSymbolCall(e){let t=e.query;return typeof t!="string"||t.trim().length===0?{content:[{type:"text",text:"Missing or invalid parameter: query (non-empty string required)."}],isError:!0}:this.routeWorkspaceSymbolRequest(t)}async routeWorkspaceSymbolRequest(e){let t=this.projectState===4&&this.arktsCheckTool!==null,r=this.cppProjectState===4&&!this.cppHasNoCppCode&&this.cppLspTool!==null;if(!t&&!r){let a=this.describeArktsState(),c=this.describeCppState();return v.info(`workspaceSymbol rejected: ArkTS ${a}; C++ ${c}`),{content:[{type:"text",text:`workspaceSymbol: ArkTS ${a}; C++ ${c}`}],isError:!0}}let i=[],o=new Set;if(t)try{this.mergeSymbolItems(await this.arktsCheckTool.handleWorkspaceSymbolRaw(e),o,i)}catch(a){v.warn(`workspaceSymbol ArkTS query failed: ${a.message}`)}if(r)try{this.mergeSymbolItems(await this.cppLspTool.handleWorkspaceSymbolRaw(e),o,i)}catch(a){v.warn(`workspaceSymbol C++ query failed: ${a.message}`)}return{content:[{type:"text",text:i.length===0?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(i,null,2)}`}]}}symbolDedupKey(e){let t=e,r=t?.location?.uri??"",i=t?.location?.range?.start?.line??0,o=t?.location?.range?.start?.character??0;return`${r}:${i}:${o}`}mergeSymbolItems(e,t,r){if(e)for(let i of e){let o=this.symbolDedupKey(i);t.has(o)||(t.add(o),r.push(i))}}describeArktsState(){switch(this.projectState){case 0:return"idle";case 1:return"discovering";case 2:return`syncing (retry ${tm}s)`;case 3:return`initializing (retry ${tm}s)`;case 5:return`error (${this.initRetryCount}/${io})`;case 4:return"ready";default:return"unknown"}}describeCppState(){switch(this.cppProjectState){case 0:return"idle";case 1:return"discovering";case 2:return"syncing (retry 25s)";case 3:return"initializing (retry 10s)";case 5:return`error (${this.cppInitRetryCount}/${io})`;case 4:return this.cppHasNoCppCode?"ready (no C++ code)":"ready";default:return"unknown"}}async handleDocumentSymbolCall(e){let t=e.file;return typeof t!="string"?{content:[{type:"text",text:"Missing or invalid parameter: file (string required)."}],isError:!0}:this.routeLspRequest(t,"documentSymbol",async()=>t.endsWith(".ets")?this.arktsCheckTool.handleDocumentSymbol(t):this.cppLspTool.handleDocumentSymbol(t))}async handleCallHierarchyCall(e){let t=e.file,r=e.line,i=e.character,o=e.direction;return typeof t!="string"||typeof r!="number"||typeof i!="number"?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}:o!=="incoming"&&o!=="outgoing"?{content:[{type:"text",text:'Parameter direction must be "incoming" or "outgoing".'}],isError:!0}:this.routeLspRequest(t,`callHierarchy(${o})`,async()=>t.endsWith(".ets")?this.arktsCheckTool.handleCallHierarchy({file:t,line:r,character:i,direction:o}):this.cppLspTool.handleCallHierarchy({file:t,line:r,character:i,direction:o}))}async routeArktsRequest(e,t){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:return v.warn(`ArkTS ${e} rejected: project is DISCOVERING`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 2:return v.warn(`ArkTS ${e} rejected: project is SYNCING`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 3:return v.warn(`ArkTS ${e} rejected: LSP is initializing`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 5:return this.handleErrorCheck();case 4:return t();default:return v.warn(`ArkTS ${e} rejected: unknown project state ${this.projectState}`),{content:[{type:"text",text:"Unknown project state, please retry"}],isError:!0}}}async handleIdleCheck(){if(this.ensureProjectReady(),this.config.projectPath){let e,t;return this.syncSkippedDueToLock?(e=`Another build process is running, sync deferred (waiting ${this.syncSkipStartedAt>0?Math.round((Date.now()-this.syncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,t="lock contention",this.syncSkippedDueToLock=!1):this.configChangedTriggeredResync?(e=this.arktsInitProgress?this.buildInitRetryMessage():`Config file changed, resyncing project.${this.buildRetrySuffix()}`,t="config changed",this.configChangedTriggeredResync=!1):(e=this.arktsInitProgress?this.buildInitRetryMessage():`ArkTS project detected, syncing.${this.buildRetrySuffix()}`,t="initial"),v.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(v.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:`Initializing.${this.buildRetrySuffix()}`}],isError:!0}):(v.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>=io?(v.error(`Init retry limit reached (${this.initRetryCount}/${io}), will not auto-retry`),{content:[{type:"text",text:`Project initialization failed repeatedly (auto-retry exhausted: ${this.initRetryCount}/${io}). Ask the user to investigate and confirm \`ohpm install\` + \`hvigor\` sync succeed manually. Do NOT call the \`restart\` tool repeatedly \u2014 call it at most once after the user fixes the root cause; if it fails again, stop retrying and escalate to the user.`}],isError:!0}):(v.info(`Error check: auto-retrying (${this.initRetryCount}/${io})`),this.arktsInitProgress=null,this.ensureProjectReady(),{content:[{type:"text",text:`Project initialization failed, auto-retrying.${this.buildRetrySuffix()}`}],isError:!0})}buildRetrySuffix(){return` Retry in ${tm}s. Expected total: 30s\u201310min (depends on project size).`}buildInitRetryMessage(){let e=this.arktsInitProgress;if(!e)return`ArkTS init in progress.${this.buildRetrySuffix()}`;let t=ub.indexOf(e.phase)+1,r=Math.round((Date.now()-e.startedAt)/1e3),i=this.arktsPipelineStartedAt?Math.round((Date.now()-this.arktsPipelineStartedAt)/1e3):r,o=e.percent!==null?` (${e.percent}%)`:"";return[`ArkTS init [${t}/4] ${dW[e.phase]}: ${e.detail}${o} [${r}s, total ${i}s]`,this.buildPipelineLine(e.phase),`Retry in ${tm}s. Expected total: 30s\u201310min (depends on project size).`].join(`
|
|
@@ -1888,4 +1888,4 @@ Available engines: ${t.join(", ")}`:"";if(!n)throw new Error(`\u2717 Engine not
|
|
|
1888
1888
|
\u{1F4A1} devecocli workflow create my-demo`);let e=Se(),t=En(kd(e),n);if(Vk(t))throw new Error(`\u2717 Workflow "${n}" already exists at ${t}.
|
|
1889
1889
|
\u{1F4A1} devecocli workflow validate ${n} (check the existing one)`);let r=KK(n);D$(En(t,"reference"),{recursive:!0}),D$(En(t,"scripts"),{recursive:!0}),D$(En(t,"agents"),{recursive:!0}),Bk(En(t,"workflow.yaml"),r.workflowYaml,"utf-8"),Bk(En(t,"reference","architecture-notes.md"),r.architectureNotes,"utf-8"),Bk(En(t,"scripts","check-style.cjs"),r.checkStyleScript,"utf-8"),Bk(En(t,"agents","README.md"),r.agentsReadme,"utf-8"),j_e(t,r.agentNames),console.log(Ai(`\u2713 Created workflow '${n}' at .deveco-cli/workflows/${n}/`)),await Wk(n),console.log(`\u{1F4A1} devecocli workflow validate ${n}`),console.log(`\u{1F4A1} devecocli workflow run ${n} --engine deveco --model deveco/glm-5`)}an.command("create <name>",{hidden:!0}).description("Scaffold a demo workflow (agent + script + human_gate showcase) at .deveco-cli/workflows/<name>/").action(async n=>{let e={event:b.CommandExecuted,args:["workflow","create","<name>"]};await Et(e,()=>H_e(n))});ka.command("get [section]").description("Show configuration: agents | channels | engine | concurrency \u2014 or everything when no section is given").action(async n=>{let e={event:b.CommandExecuted,args:["workflow","config","get"]};await Et(e,()=>C$(n))});ka.command("set").description("Set a concurrency value (--key maxApiConcurrency|maxScriptConcurrency --value <n>, global)").requiredOption("--key <key>",`Config key (${wa.join(" | ")})`).requiredOption("--value <value>","Positive integer").action(async n=>{let e={event:b.CommandExecuted,args:["workflow","config","set"]};await Et(e,async()=>{A$(n.key,n.value)})});ka.command("set-agent <workflow>").description("Set workflow-scoped agent engine/model (atomic pair). Omit --agent for the workflow default; --agent a,b for specific agents. Never edits agent YAML.").option("--agent <names>","Agent name(s), comma-separated (e.g. arkts-reviewer,documentation-writer)").option("--all","Unsupported \u2014 omit --agent for the workflow default (passing it errors)").requiredOption("--engine <type>","Engine type (available engines: workflow list --health) \u2014 paired with --model").requiredOption("--model <model>","Model name (e.g. glm-5.2, gpt-4o, or provider/model) \u2014 paired with --engine").action(async(n,e)=>{let t={event:b.CommandExecuted,args:["workflow","config","set-agent"]};await Et(t,()=>jk(n,e.agent,e.engine,e.model,e.all===!0))});ka.command("unset-agent <workflow>").description("Remove workflow-scoped agent config: --agent a,b clears those entries; no --agent clears the workflow config").option("--agent <names>","Agent name(s), comma-separated").action(async(n,e)=>{let t={event:b.CommandExecuted,args:["workflow","config","unset-agent"]};await Et(t,async()=>{Hk(n,e.agent)})});ka.command("set-channel").description("Set an engine default channel (global): --engine <type> --channel <sdk|cli|acp>. An engine accepts only the channels it declares.").requiredOption("--engine <type>","Engine type (available engines: workflow list --health)").requiredOption("--channel <channel>","Default channel for the engine (sdk | cli | acp)").action(async n=>{let e={event:b.CommandExecuted,args:["workflow","config","set-channel"]};await Et(e,async()=>{Fk(n.engine,n.channel)})});ka.command("unset-channel").description("Remove an engine channel override (global) \u2014 the engine falls back to its declared default channel").requiredOption("--engine <type>","Engine type (available engines: workflow list --health)").action(async n=>{let e={event:b.CommandExecuted,args:["workflow","config","unset-channel"]};await Et(e,async()=>{R$(n.engine)})});ka.command("init").description("Interactive configuration wizard: pick the default engine and a model from its live list").action(async()=>{let n={event:b.CommandExecuted,args:["workflow","config","init"]};await Et(n,()=>Lk())});ka.command("set-engine").description("Set the default engine type (global) \u2014 used when `run` omits --engine").requiredOption("--engine <type>","Engine type (available engines: workflow list --health)").action(async n=>{let e={event:b.CommandExecuted,args:["workflow","config","set-engine"]};await Et(e,async()=>{Rg(n.engine)})});async function U_e(n,e){let t=En(e,St),r=await st.load(n,t),i=r?.getState().params,o=i?.engine_type,s=i?.engine_channel,a=i?.run_model,c=o&&a?{engine:o,model:a}:void 0;try{let l=await ng(e,o,c,s);return{runner:qO(l)}}catch(l){let d=l.message,g=d.includes("Engine not specified")?`${d} (This checkpoint has no stored engine type. Re-run with: workflow run <workflow> --engine <type>)`:d;if(r)try{await r.update({status:"failed",error:`Worker boot failed: ${g}`,finishedAt:new Date().toISOString()}),Xn(n)}catch{}throw l instanceof Error&&g===d?l:new Error(g,{cause:l})}}an.command("_internal-run <runId>",{hidden:!0}).description("Internal: run orchestrator in detached mode").requiredOption("--project-root <path>","Project root directory").action(async(n,e)=>{let t=e.projectRoot,{runner:r}=await U_e(n,t);await r.runInternal(n,t)});var Z5=an;me();u();function e6(n,e,t){if(n.length<2||n[n.length-1]!=="help")return!1;let[r]=n.filter(a=>!a.startsWith("-"));if(r===e)return!1;let i=n[n.length-2];if(!i.startsWith("-")||i==="--"||i.includes("="))return!0;let o=W_e(t,n),s=o?B_e(o,i):void 0;return!o||!s?!1:!s.required&&!s.optional}function W_e(n,e){let t=n,r=!1;for(let i of e){if(i.startsWith("-"))break;let o=t.commands.find(s=>s.name()===i||s.aliases().includes(i));if(!o)return;t=o,r=!0}return r?t:void 0}function B_e(n,e){let t=e.startsWith("--");return n.options.find(r=>t?r.long===e:r.short===e)}E();Jt();ln();{let n=gP();if(n)te.setCountryCode(n);else{let e=fP();e&&(te.setCountryCode(e.code),Vl(e.code))}}gn()&&(te.setCountryCode("CN"),Vl("CN"));if(!Kt()&&te.isCN())try{A.init(zk.join(_(),"TraceLogData",te.countryCode)),A.startScheduler()}catch(n){v.error(`[telemetry] init failed: ${n instanceof Error?n.message:String(n)}`)}ke.name("devecocli").description(`HarmonyOS application development command line tool${te.countryCode?`
|
|
1890
1890
|
|
|
1891
|
-
Privacy: ${OE(te.countryCode)}`:""}`).version("1.4.0-Test.
|
|
1891
|
+
Privacy: ${OE(te.countryCode)}`:""}`).version("1.4.0-Test.912");var t6=ke.options.find(n=>n.long==="--version");t6&&(t6.flags="-V, -v, --version");ke.addCommand(B_);ke.addCommand(jM);ke.addCommand(zM);ke.addCommand(VF);ke.addCommand(gj);ke.addCommand(Lj);ke.addCommand(Uj(new Na([new Us,...dC()])));ke.addCommand(iH);ke.addCommand(hU);ke.addCommand(_U);ke.addCommand(FU);ke.addCommand(hW);ke.addCommand(SW);ke.addCommand(tB);ke.addCommand(jB);ke.addCommand(C2);ke.addCommand(P2);ke.addCommand(pV);ke.addCommand(YV);ke.addCommand(Z5);ke.addCommand(dz);ke.addCommand(gz);async function z_e(){if(!Kt())try{let n=await T.new();A.setSourceType(n.sourceType);let e=n.readVersion();e&&(n.sourceType==="clt"?A.setCltVersion(e):A.setStudioVersion(e))}catch(n){v.error(`[telemetry] toolchain info failed: ${n instanceof Error?n.message:String(n)}`)}}var G_e=z_e();for(let n=2;n<process.argv.length;n++){let e=process.argv[n];if(e==="-v"){process.argv[n]="-V";break}if(!e.startsWith("-"))break}var q_e=process.argv.slice(2);e6(q_e,xm,ke)&&(process.argv=[...process.argv.slice(0,-1),"--help"]);function J_e(n){let e=n;for(;e.parent&&e.parent!==ke;)e=e.parent;return e}var K_e=new Set(["update","auth","serve","testing","design2arkts","plugin","workflow"]);ke.hook("preAction",async(n,e)=>{await r_().catch(()=>{});let t=J_e(e),r=vl();if(t.name()==="update"||t.name()==="docs"&&e.name()==="update")return;let i=new bs(zk.join(_(),"update")),o=$n();if(r==="off"&&i.getBlockedVersions().includes(o))throw new Error(`devecocli ${o} has been disabled, run \`devecocli update\` to upgrade`);if(t.name()==="design2arkts"&&e.name()==="stage-complete"&&await G_e,!process.env.DEVECO_CLI_SKIP_VERSION_CHECK&&!K_e.has(t.name())){if(t.name()==="profiler"){await T.checkProfilerVersion();return}await T.checkVersion()}});ke.hook("postAction",async(n,e)=>{if(process.exitCode||vl()!=="off")return;await new hp(e).checkAndNotify()});var Y_e=PI(process.argv),X_e=Y_e??KI(process.argv);ke.parseAsync(X_e).finally(()=>{A.stopScheduler();try{jE(zk.join(_(),"TraceLogData",te.countryCode))}catch(n){v.error(`[telemetry] background upload spawn check failed: ${n instanceof Error?n.message:String(n)}`)}}).catch(n=>{let t=Ud(n)?.message??(n instanceof Error?n.message:String(n??"Unknown error"));console.error(V_e(`Error: ${t}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
|
|
@@ -36,7 +36,7 @@ zYl5snR6SmrDfVmtsyz8aMqifx4gsVV2M5/owv8H3bUdOd5RbkKhzOS2Pmep0bbw
|
|
|
36
36
|
WRFUrWuQ+5ci2LLkZyIt9ffNR8W9gbmZOZZTrwSFRIT1Q433NOzCQNDjKwnekGAx
|
|
37
37
|
8o746tqqZxGCXgy2MaIIqvajhNw9Dr3NBQ8ziWyqaQBk2RrCWh6Q++Sd0b5L3RwH
|
|
38
38
|
rQ==
|
|
39
|
-
-----END CERTIFICATE-----`,xr=new Ee.X509Certificate(Ar),pt=[{cert:xr}];function wr(r){let e=[],t=r.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let n of t)try{e.push({cert:new Ee.X509Certificate(n)})}catch{}return e}var dt=new Set,J;function Rr(){let r=process.env.NODE_EXTRA_CA_CERTS;if(J&&J.envValue===r)return J.anchors;let e=r?Pr(r):[],t=e.length?[...pt,...e]:pt;return J={envValue:r,anchors:t},t}function Pr(r){try{let e=wr(Er.readFileSync(r,"utf8"));return e.length===0&&mt(r,"no parseable certificate found"),e}catch(e){return mt(r,e instanceof Error?e.message:String(e)),[]}}function mt(r,e){dt.has(r)||(dt.add(r),console.warn(br(`[devecocli] GRS TLS: failed to load NODE_EXTRA_CA_CERTS (${Cr.basename(r)}): ${e} \u2014 falling back to the built-in CA only.`)))}function Dr(r){let e=[],t=new Set,n=r;for(;n&&n.raw;){let o=n.fingerprint256||n.fingerprint||"";if(!o||t.has(o))break;t.add(o);try{e.push(new Ee.X509Certificate(n.raw))}catch{break}let i=n.issuerCertificate??null;if(i===r)break;n=i}return e}function Lr(r,e,t){if(r.length===0)return new Error("[GRS TLS] Server did not provide a certificate");if(!Ir(r,t))return p(()=>"[GRS TLS] No trusted anchor (built-in intermediate CA or NODE_EXTRA_CA_CERTS) matched the presented chain"),new Error("[GRS TLS] Server certificate chain is not trusted by the built-in CA or NODE_EXTRA_CA_CERTS");let n=_r(r[0],e);if(n)return n;p(()=>"[GRS TLS] Verification passed: certificate chain anchored on a trusted CA")}function Ir(r,e){for(let n of e){let o=r.findIndex(i=>i.fingerprint256===n.cert.fingerprint256);if(o>=0&&ft(r,o))return!0}let t=r[r.length-1];for(let n of e)if(n.cert.subject===t.issuer)try{if(t.verify(n.cert.publicKey)&&ft(r,r.length-1))return!0}catch{}return!1}function ft(r,e){try{for(let t=e;t>0;t--)if(!r[t-1].verify(r[t].publicKey))return!1;return!0}catch{return!1}}function _r(r,e){let t=Date.now();if(new Date(r.validFrom).getTime()>t||new Date(r.validTo).getTime()<t)return new Error("[GRS TLS] Server certificate is expired or not yet valid");if(!kr(r,e))return new Error(`[GRS TLS] Server certificate does not match host ${e}`)}function Nr(r,e){let t=r.getPeerCertificate(!0);if(!t||!t.raw)return new Error("[GRS TLS] Server did not provide a certificate");let n=Dr(t);return n.length===0?new Error("[GRS TLS] Server certificate could not be parsed"):Lr(n,e,Rr())}function kr(r,e){let t=r.subjectAltName??"",n=e.toLowerCase();for(let o of t.split(",")){let i=o.trim();if(!i.startsWith("DNS:"))continue;let s=i.slice(4).toLowerCase();if(s===n)return!0;if(s.startsWith("*.")){let a=s.slice(1),c=n.slice(0,-a.length);if(n.endsWith(a)&&c.length>0&&!c.includes("."))return!0}}return!1}var Or=8e3,he=class{constructor(e,t){this.callback=e;this.timeoutMs=t}settled=!1;timer;destroyers=[];onDestroy(e){this.destroyers.push(e)}start(){this.timer=setTimeout(()=>{this.settle(new Error(`[GRS] Connection deadline (${this.timeoutMs}ms) exceeded during CONNECT/TLS handshake`))},this.timeoutMs)}settle(e,t){if(!this.settled){if(this.settled=!0,this.timer&&clearTimeout(this.timer),e)for(let n of this.destroyers)try{n()}catch{}this.callback(e,t)}}},ye=class extends vr.Agent{connectTimeoutMs;constructor(e){super(e),this.connectTimeoutMs=e?.connectTimeoutMs??Or}createConnection(e,t){let n=e.host||e.servername||"",o=e.port||443,i=`https://${n}:${o}`,s=Tr(i),a=new he(t,this.connectTimeoutMs);if(a.start(),s){this.createConnectionViaProxy(e,s,n,o,a);return}return this.createDirectConnection(e,a,n)}createDirectConnection(e,t,n){let o=lt.connect({...e,rejectUnauthorized:!1});return t.onDestroy(()=>o.destroy()),this.attachTlsVerification(o,t,n),o}parseProxyOrSettle(e,t){try{return fe(e)}catch(n){return t.settle(new Error(`[GRS] ${n.message}`)),null}}createConnectionViaProxy(e,t,n,o,i){let s=this.parseProxyOrSettle(t,i);if(!s)return;let a=this.buildProxyHeaders(s,n,o);p(()=>`[GRS] Connecting via proxy ${s.host}:${s.port} to ${n}:${o}`);let c=Sr.request({host:s.host,port:s.port,method:"CONNECT",path:`${n}:${o}`,headers:a});i.onDestroy(()=>c.destroy()),c.on("connect",(g,S)=>{if(g.statusCode!==200){S.destroy(),i.settle(new Error(`[GRS] Proxy CONNECT failed: ${g.statusCode} ${g.statusMessage||""}`));return}i.onDestroy(()=>S.destroy()),this.startTlsOverTunnel(e,S,i,n)}),c.on("error",g=>{i.settle(new Error(`[GRS] Proxy connection failed: ${g.message}`))}),c.end()}startTlsOverTunnel(e,t,n,o){p(()=>"[GRS] Proxy tunnel established, starting TLS handshake");let i=lt.connect({...e,socket:t,rejectUnauthorized:!1});n.onDestroy(()=>i.destroy()),this.attachTlsVerification(i,n,o)}buildProxyHeaders(e,t,n){let o={Host:`${t}:${n}`},i=e.auth;if(i&&(i.username||i.password)){let s=`${i.username}:${i.password}`;o["Proxy-Authorization"]=`Basic ${Buffer.from(s).toString("base64")}`}return o}attachTlsVerification(e,t,n){e.once("secureConnect",()=>{let o=Nr(e,n);o?(e.destroy(o),t.settle(o)):t.settle(null,e)}),e.once("error",o=>{t.settle(o)})}},Se=new ye({keepAlive:!0});var ve=[{group:"com.huawei.devecostudio.region",key:"spaceintroduce"},{group:"com.huawei.devecostudio.region",key:"userinfo"},{group:"com.huawei.devecostudio.region",key:"agcsign"},{group:"com.huawei.devecostudio.region",key:"agcups"},{group:"com.huawei.devecostudio.region",key:"agreementservice"}],D=class extends Error{kind;constructor(e,t){super(t),this.name="GrsError",this.kind=e}};var Mr=["https://grs.dbankcloud.com/grs/2.0/router","https://grs.dbankcloud.cn/grs/2.0/router","https://grs.dbankcloud.asia/grs/2.0/router","https://grs.platform.dbankcloud.ru/grs/2.0/router"],Fr="com.huawei.deveco.common-grs/0.1 (Windows;Linux;Mac) Deveco-grs/-1",Br="devecostudio",$r=8e3;async function Ce(r){let e=[],t="";for(let i of Mr){let s=await Ur(i,r);if(s.outcome==="ok")return s.services;e.push(s.outcome),s.detail&&(t=s.detail)}if(e.some(i=>i==="incomplete"))throw new D("no-config",`GRS returned no valid configuration for country code ${r} (this region may not be supported)`);let n=process.env.HTTPS_PROXY||process.env.HTTP_PROXY,o=n?`Current proxy: ${X(n)}. Verify the proxy is running and allows CONNECT to grs.dbankcloud.com:443. If the proxy inspects TLS, set NODE_EXTRA_CA_CERTS to a PEM file with your corporate CA \u2014 untrusted GRS certificates are rejected.`:"No proxy configured (HTTP_PROXY/HTTPS_PROXY). If you are behind a corporate firewall, set HTTPS_PROXY=http://your-proxy:port.";throw new D("network",`GRS endpoints unreachable (grs.dbankcloud.com is globally reachable). ${o}${t?` Last endpoint error: ${t}`:""}`)}async function Ur(r,e){let t=`${r}?issue_country=${encodeURIComponent(e)}&app_name=${Br}`;p(()=>`[GRS] POST ${t}`);try{let n=await ge.post(t,{headers:{"User-Agent":Fr},httpsAgent:Se,timeout:$r}),o=ge.parseJson(n);return o.resultCode!==0?(p(()=>`[GRS] ${r} resultCode=${o.resultCode}, skipping`),{outcome:"incomplete",detail:`resultCode=${o.resultCode}`}):Gr(o.services)?(p(()=>`[GRS] hit ${r}, received ${Object.keys(o.services).length} service groups`),{outcome:"ok",services:o.services}):(p(()=>`[GRS] ${r} returned incomplete config (missing required service keys), skipping`),{outcome:"incomplete",detail:"missing required service keys"})}catch(n){let o=n instanceof Error?n.message:String(n);return p(()=>`[GRS] ${r} request failed: ${o}`),{outcome:"network",detail:o}}}function Gr(r){return ve.every(({group:e,key:t})=>typeof r[e]?.[t]=="string")}import gt from"fs";import Hr from"path";var jr="com.huawei.devecostudio.region",Vr={[jr]:{spaceintroduce:"https://cn.devecostudio.huawei.com",userinfo:"https://gopenuser-drcn.platform.dbankcloud.cn",agcsign:"https://connect-api.cloud.huawei.com",agcups:"https://connect-api.cloud.huawei.com",agreementservice:"https://terms-drcn.platform.dbankcloud.cn",agcdeveloper:"https://developer.huawei.com"}},zr=1440*60*1e3,ht=new Set(["CN","HK","MO"]),Te=class{countryCode="";services={};resolved=!1;isCN(){return this.countryCode==="CN"}isOnlineAllowed(){return ht.has(this.countryCode)}getService(e,t){let n=this.services[e]?.[t];if(!n)throw new h("RuntimeCondition",`GRS service ${e}.${t} not available`,"GRS service not available.");return n}setCountryCode(e){this.countryCode=e}async resolve(){if(!this.countryCode)throw new h("RuntimeCondition","Country code not set, cannot resolve GRS","Country code not set.");if(this.countryCode==="CN"){this.services=Vr,this.resolved=!0,p(()=>"[GRS] CN uses hardcoded services, skipping GRS request");return}let e=await Wr(this.countryCode);if(e){this.services=e.services,this.resolved=!0,p(()=>`[GRS] cache hit country=${this.countryCode}, skipping request`);return}p(()=>`[GRS] cache miss or expired, requesting GRS country=${this.countryCode}`);let t=await Ce(this.countryCode);this.services=t,this.resolved=!0,await qr(this.countryCode,t)}},C=new Te;function yt(r){return Hr.join(R(),`grs_${r}.json`)}async function Wr(r){try{let e=await gt.promises.readFile(yt(r),"utf8"),t=JSON.parse(e);return t.countryCode!==r||Date.now()-t.fetchedAt>zr?null:t}catch{return null}}async function qr(r,e){let t={services:e,fetchedAt:Date.now(),countryCode:r};try{await gt.promises.writeFile(yt(r),JSON.stringify(t),"utf8")}catch{}}function St(){return!W()&&C.isCN()}var M=class r{static MAX_BATCH=200;static MAX_PAYLOAD_BYTES=Math.floor(1.7*1024*1024);static TRACE_OS_VERSION="1.0";static COUNTRY_CODE="CN";static EVENT_PREFIX="devecocli_";uploader=new $;storageDir="";failedDir="";installId="";get disabled(){return!St()}traceFileKey=Buffer.alloc(0);sessionId=Et.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){d.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=E.join(e,"failed"),this.cliVersion="1.4.0-Test.911",this.nodeVersion=process.version,f.mkdirSync(e,{recursive:!0}),f.mkdirSync(this.failedDir,{recursive:!0});let t=E.dirname(e);this.installId=Je(t).replace(/-/g,""),this.traceFileKey=Me(t),tt(e),d.debug(`[telemetry] init: dir=${e}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(e){this.devecoStudioVersion=e,d.debug(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,d.debug(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,d.debug(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)return d.debug("[telemetry] track skipped: telemetry not initialized"),typeof t=="function"?t():void 0;if(!t){await this.record(e,0,!0,null);return}if(typeof t!="function"){let i=t;await this.record(e,i.duration_ms,i.success,i.error_code);return}let n=t,o=Date.now();try{let i=await n(),s=Date.now()-o;return await this.record(e,s,!0,null),i}catch(i){let s=Date.now()-o,a=this.resolveErrorCode(i);throw await this.record(e,s,!1,a),i}}resolveErrorCode(e){try{return te(e)}catch{return null}}async record(e,t,n,o){try{let i=this.buildTraceEvent(e,t,n,o),s=Fe(JSON.stringify(i),this.traceFileKey);await f.promises.appendFile(this.currentFile(),s+`
|
|
39
|
+
-----END CERTIFICATE-----`,xr=new Ee.X509Certificate(Ar),pt=[{cert:xr}];function wr(r){let e=[],t=r.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let n of t)try{e.push({cert:new Ee.X509Certificate(n)})}catch{}return e}var dt=new Set,J;function Rr(){let r=process.env.NODE_EXTRA_CA_CERTS;if(J&&J.envValue===r)return J.anchors;let e=r?Pr(r):[],t=e.length?[...pt,...e]:pt;return J={envValue:r,anchors:t},t}function Pr(r){try{let e=wr(Er.readFileSync(r,"utf8"));return e.length===0&&mt(r,"no parseable certificate found"),e}catch(e){return mt(r,e instanceof Error?e.message:String(e)),[]}}function mt(r,e){dt.has(r)||(dt.add(r),console.warn(br(`[devecocli] GRS TLS: failed to load NODE_EXTRA_CA_CERTS (${Cr.basename(r)}): ${e} \u2014 falling back to the built-in CA only.`)))}function Dr(r){let e=[],t=new Set,n=r;for(;n&&n.raw;){let o=n.fingerprint256||n.fingerprint||"";if(!o||t.has(o))break;t.add(o);try{e.push(new Ee.X509Certificate(n.raw))}catch{break}let i=n.issuerCertificate??null;if(i===r)break;n=i}return e}function Lr(r,e,t){if(r.length===0)return new Error("[GRS TLS] Server did not provide a certificate");if(!Ir(r,t))return p(()=>"[GRS TLS] No trusted anchor (built-in intermediate CA or NODE_EXTRA_CA_CERTS) matched the presented chain"),new Error("[GRS TLS] Server certificate chain is not trusted by the built-in CA or NODE_EXTRA_CA_CERTS");let n=_r(r[0],e);if(n)return n;p(()=>"[GRS TLS] Verification passed: certificate chain anchored on a trusted CA")}function Ir(r,e){for(let n of e){let o=r.findIndex(i=>i.fingerprint256===n.cert.fingerprint256);if(o>=0&&ft(r,o))return!0}let t=r[r.length-1];for(let n of e)if(n.cert.subject===t.issuer)try{if(t.verify(n.cert.publicKey)&&ft(r,r.length-1))return!0}catch{}return!1}function ft(r,e){try{for(let t=e;t>0;t--)if(!r[t-1].verify(r[t].publicKey))return!1;return!0}catch{return!1}}function _r(r,e){let t=Date.now();if(new Date(r.validFrom).getTime()>t||new Date(r.validTo).getTime()<t)return new Error("[GRS TLS] Server certificate is expired or not yet valid");if(!kr(r,e))return new Error(`[GRS TLS] Server certificate does not match host ${e}`)}function Nr(r,e){let t=r.getPeerCertificate(!0);if(!t||!t.raw)return new Error("[GRS TLS] Server did not provide a certificate");let n=Dr(t);return n.length===0?new Error("[GRS TLS] Server certificate could not be parsed"):Lr(n,e,Rr())}function kr(r,e){let t=r.subjectAltName??"",n=e.toLowerCase();for(let o of t.split(",")){let i=o.trim();if(!i.startsWith("DNS:"))continue;let s=i.slice(4).toLowerCase();if(s===n)return!0;if(s.startsWith("*.")){let a=s.slice(1),c=n.slice(0,-a.length);if(n.endsWith(a)&&c.length>0&&!c.includes("."))return!0}}return!1}var Or=8e3,he=class{constructor(e,t){this.callback=e;this.timeoutMs=t}settled=!1;timer;destroyers=[];onDestroy(e){this.destroyers.push(e)}start(){this.timer=setTimeout(()=>{this.settle(new Error(`[GRS] Connection deadline (${this.timeoutMs}ms) exceeded during CONNECT/TLS handshake`))},this.timeoutMs)}settle(e,t){if(!this.settled){if(this.settled=!0,this.timer&&clearTimeout(this.timer),e)for(let n of this.destroyers)try{n()}catch{}this.callback(e,t)}}},ye=class extends vr.Agent{connectTimeoutMs;constructor(e){super(e),this.connectTimeoutMs=e?.connectTimeoutMs??Or}createConnection(e,t){let n=e.host||e.servername||"",o=e.port||443,i=`https://${n}:${o}`,s=Tr(i),a=new he(t,this.connectTimeoutMs);if(a.start(),s){this.createConnectionViaProxy(e,s,n,o,a);return}return this.createDirectConnection(e,a,n)}createDirectConnection(e,t,n){let o=lt.connect({...e,rejectUnauthorized:!1});return t.onDestroy(()=>o.destroy()),this.attachTlsVerification(o,t,n),o}parseProxyOrSettle(e,t){try{return fe(e)}catch(n){return t.settle(new Error(`[GRS] ${n.message}`)),null}}createConnectionViaProxy(e,t,n,o,i){let s=this.parseProxyOrSettle(t,i);if(!s)return;let a=this.buildProxyHeaders(s,n,o);p(()=>`[GRS] Connecting via proxy ${s.host}:${s.port} to ${n}:${o}`);let c=Sr.request({host:s.host,port:s.port,method:"CONNECT",path:`${n}:${o}`,headers:a});i.onDestroy(()=>c.destroy()),c.on("connect",(g,S)=>{if(g.statusCode!==200){S.destroy(),i.settle(new Error(`[GRS] Proxy CONNECT failed: ${g.statusCode} ${g.statusMessage||""}`));return}i.onDestroy(()=>S.destroy()),this.startTlsOverTunnel(e,S,i,n)}),c.on("error",g=>{i.settle(new Error(`[GRS] Proxy connection failed: ${g.message}`))}),c.end()}startTlsOverTunnel(e,t,n,o){p(()=>"[GRS] Proxy tunnel established, starting TLS handshake");let i=lt.connect({...e,socket:t,rejectUnauthorized:!1});n.onDestroy(()=>i.destroy()),this.attachTlsVerification(i,n,o)}buildProxyHeaders(e,t,n){let o={Host:`${t}:${n}`},i=e.auth;if(i&&(i.username||i.password)){let s=`${i.username}:${i.password}`;o["Proxy-Authorization"]=`Basic ${Buffer.from(s).toString("base64")}`}return o}attachTlsVerification(e,t,n){e.once("secureConnect",()=>{let o=Nr(e,n);o?(e.destroy(o),t.settle(o)):t.settle(null,e)}),e.once("error",o=>{t.settle(o)})}},Se=new ye({keepAlive:!0});var ve=[{group:"com.huawei.devecostudio.region",key:"spaceintroduce"},{group:"com.huawei.devecostudio.region",key:"userinfo"},{group:"com.huawei.devecostudio.region",key:"agcsign"},{group:"com.huawei.devecostudio.region",key:"agcups"},{group:"com.huawei.devecostudio.region",key:"agreementservice"}],D=class extends Error{kind;constructor(e,t){super(t),this.name="GrsError",this.kind=e}};var Mr=["https://grs.dbankcloud.com/grs/2.0/router","https://grs.dbankcloud.cn/grs/2.0/router","https://grs.dbankcloud.asia/grs/2.0/router","https://grs.platform.dbankcloud.ru/grs/2.0/router"],Fr="com.huawei.deveco.common-grs/0.1 (Windows;Linux;Mac) Deveco-grs/-1",Br="devecostudio",$r=8e3;async function Ce(r){let e=[],t="";for(let i of Mr){let s=await Ur(i,r);if(s.outcome==="ok")return s.services;e.push(s.outcome),s.detail&&(t=s.detail)}if(e.some(i=>i==="incomplete"))throw new D("no-config",`GRS returned no valid configuration for country code ${r} (this region may not be supported)`);let n=process.env.HTTPS_PROXY||process.env.HTTP_PROXY,o=n?`Current proxy: ${X(n)}. Verify the proxy is running and allows CONNECT to grs.dbankcloud.com:443. If the proxy inspects TLS, set NODE_EXTRA_CA_CERTS to a PEM file with your corporate CA \u2014 untrusted GRS certificates are rejected.`:"No proxy configured (HTTP_PROXY/HTTPS_PROXY). If you are behind a corporate firewall, set HTTPS_PROXY=http://your-proxy:port.";throw new D("network",`GRS endpoints unreachable (grs.dbankcloud.com is globally reachable). ${o}${t?` Last endpoint error: ${t}`:""}`)}async function Ur(r,e){let t=`${r}?issue_country=${encodeURIComponent(e)}&app_name=${Br}`;p(()=>`[GRS] POST ${t}`);try{let n=await ge.post(t,{headers:{"User-Agent":Fr},httpsAgent:Se,timeout:$r}),o=ge.parseJson(n);return o.resultCode!==0?(p(()=>`[GRS] ${r} resultCode=${o.resultCode}, skipping`),{outcome:"incomplete",detail:`resultCode=${o.resultCode}`}):Gr(o.services)?(p(()=>`[GRS] hit ${r}, received ${Object.keys(o.services).length} service groups`),{outcome:"ok",services:o.services}):(p(()=>`[GRS] ${r} returned incomplete config (missing required service keys), skipping`),{outcome:"incomplete",detail:"missing required service keys"})}catch(n){let o=n instanceof Error?n.message:String(n);return p(()=>`[GRS] ${r} request failed: ${o}`),{outcome:"network",detail:o}}}function Gr(r){return ve.every(({group:e,key:t})=>typeof r[e]?.[t]=="string")}import gt from"fs";import Hr from"path";var jr="com.huawei.devecostudio.region",Vr={[jr]:{spaceintroduce:"https://cn.devecostudio.huawei.com",userinfo:"https://gopenuser-drcn.platform.dbankcloud.cn",agcsign:"https://connect-api.cloud.huawei.com",agcups:"https://connect-api.cloud.huawei.com",agreementservice:"https://terms-drcn.platform.dbankcloud.cn",agcdeveloper:"https://developer.huawei.com"}},zr=1440*60*1e3,ht=new Set(["CN","HK","MO"]),Te=class{countryCode="";services={};resolved=!1;isCN(){return this.countryCode==="CN"}isOnlineAllowed(){return ht.has(this.countryCode)}getService(e,t){let n=this.services[e]?.[t];if(!n)throw new h("RuntimeCondition",`GRS service ${e}.${t} not available`,"GRS service not available.");return n}setCountryCode(e){this.countryCode=e}async resolve(){if(!this.countryCode)throw new h("RuntimeCondition","Country code not set, cannot resolve GRS","Country code not set.");if(this.countryCode==="CN"){this.services=Vr,this.resolved=!0,p(()=>"[GRS] CN uses hardcoded services, skipping GRS request");return}let e=await Wr(this.countryCode);if(e){this.services=e.services,this.resolved=!0,p(()=>`[GRS] cache hit country=${this.countryCode}, skipping request`);return}p(()=>`[GRS] cache miss or expired, requesting GRS country=${this.countryCode}`);let t=await Ce(this.countryCode);this.services=t,this.resolved=!0,await qr(this.countryCode,t)}},C=new Te;function yt(r){return Hr.join(R(),`grs_${r}.json`)}async function Wr(r){try{let e=await gt.promises.readFile(yt(r),"utf8"),t=JSON.parse(e);return t.countryCode!==r||Date.now()-t.fetchedAt>zr?null:t}catch{return null}}async function qr(r,e){let t={services:e,fetchedAt:Date.now(),countryCode:r};try{await gt.promises.writeFile(yt(r),JSON.stringify(t),"utf8")}catch{}}function St(){return!W()&&C.isCN()}var M=class r{static MAX_BATCH=200;static MAX_PAYLOAD_BYTES=Math.floor(1.7*1024*1024);static TRACE_OS_VERSION="1.0";static COUNTRY_CODE="CN";static EVENT_PREFIX="devecocli_";uploader=new $;storageDir="";failedDir="";installId="";get disabled(){return!St()}traceFileKey=Buffer.alloc(0);sessionId=Et.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){d.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=E.join(e,"failed"),this.cliVersion="1.4.0-Test.912",this.nodeVersion=process.version,f.mkdirSync(e,{recursive:!0}),f.mkdirSync(this.failedDir,{recursive:!0});let t=E.dirname(e);this.installId=Je(t).replace(/-/g,""),this.traceFileKey=Me(t),tt(e),d.debug(`[telemetry] init: dir=${e}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(e){this.devecoStudioVersion=e,d.debug(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,d.debug(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,d.debug(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)return d.debug("[telemetry] track skipped: telemetry not initialized"),typeof t=="function"?t():void 0;if(!t){await this.record(e,0,!0,null);return}if(typeof t!="function"){let i=t;await this.record(e,i.duration_ms,i.success,i.error_code);return}let n=t,o=Date.now();try{let i=await n(),s=Date.now()-o;return await this.record(e,s,!0,null),i}catch(i){let s=Date.now()-o,a=this.resolveErrorCode(i);throw await this.record(e,s,!1,a),i}}resolveErrorCode(e){try{return te(e)}catch{return null}}async record(e,t,n,o){try{let i=this.buildTraceEvent(e,t,n,o),s=Fe(JSON.stringify(i),this.traceFileKey);await f.promises.appendFile(this.currentFile(),s+`
|
|
40
40
|
`,"utf8"),We(this.storageDir)}catch{}}buildTraceEvent(e,t,n,o){let i=`${r.EVENT_PREFIX}${e.event}`,s=Ne.toObject(e);return s&&typeof s=="object"&&delete s.event,{countryCode:r.COUNTRY_CODE,event:i,eventtime:String(Date.now()),properties:{uid:this.installId,trace_uuid:Et.randomUUID(),trace_os_version:r.TRACE_OS_VERSION,os_arch:this.resolveOsArch(),action:i,trace_os_name:this.resolveOsName(),version:`${this.cliVersion}_${this.resolveOsSuffix()}`,deveco_studio_version:this.formatVersion(this.devecoStudioVersion),command_line_version:this.formatVersion(this.cltVersion),source_type:this.sourceType,session_id:this.sessionId,node_version:this.nodeVersion,ram:this.resolveTotalRam(),duration_ms:t,success:n,error_code:o,event_detail:s}}}resolveOsArch(){let e=Z.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=Z.release().split(".");return(parseInt(e[e.length-1],10)||0)>=22e3?"Windows 11":"Windows 10"}case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}resolveOsSuffix(){switch(process.platform){case"win32":return"windows";case"darwin":return Z.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(Z.totalmem()/1024)}KB`}formatVersion(e){return e?`${e}_${this.resolveOsSuffix()}`:""}dateString(){let e=new Date,t=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0");return`${e.getFullYear()}-${t}-${n}`}currentFile(){return E.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){d.debug("[telemetry] scheduler not started (telemetry disabled)");return}d.debug(`[telemetry] scheduler started (flush every ${V/1e3}s, retry failed every ${z/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},V)},V),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},z)},z)}stopScheduler(){this.initialTimer&&(clearTimeout(this.initialTimer),this.initialTimer=null),this.intervalTimer&&(clearInterval(this.intervalTimer),this.intervalTimer=null),this.retryInitialTimer&&(clearTimeout(this.retryInitialTimer),this.retryInitialTimer=null),this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null),d.debug("[telemetry] scheduler stopped")}async flush(){return this.disabled?!0:this.runExclusive(()=>this.performFlush())}async performFlush(){if(!this.storageDir)return d.debug("[telemetry] flush skipped: telemetry not initialized"),!0;let e=await this.listPendingFiles(),t=!0;for(let n of e)await this.flushFile(n)||(t=!1);return qe(this.storageDir),t}async retryFailed(){return this.disabled?!0:this.runExclusive(()=>this.performRetryFailed())}async performRetryFailed(){if(!this.storageDir)return d.debug("[telemetry] retryFailed skipped: telemetry not initialized"),!0;await this.reclaimStalePending();let e=Date.now(),t;try{t=await f.promises.readdir(this.failedDir)}catch{return!0}let n=t.filter(i=>i.startsWith("telemetry-")&&i.endsWith(".txt")).map(i=>E.join(this.failedDir,i)),o=!0;for(let i of n){let s=E.basename(i),a=Xe(s);if(a!==null){if(e-a>je){try{await f.promises.unlink(i)}catch{}continue}await this.flushFile(i)||(o=!1)}}return o||d.warn("[telemetry] retry failed"),Ke(this.storageDir),o}async reclaimStalePending(){let e=Date.now();for(let t of[this.storageDir,this.failedDir]){let n;try{n=await f.promises.readdir(t)}catch{continue}for(let o of n)q(o)&&await this.reclaimOrphan(E.join(t,o),e)}}async reclaimOrphan(e,t){let n;try{let g=await f.promises.stat(e);if(t-g.mtimeMs<Ve)return;n=g.size}catch{return}let o=E.dirname(e),i=le(E.basename(e));if(i===null)return;let s=await this.claimOrphan(e,o,i);if(s===null)return;let a=E.join(o,i),c=P-await this.fileSize(a);if(n>c){try{await f.promises.unlink(s)}catch{}d.warn(`[telemetry] dropped stale orphan pending: ${s} (${n} bytes > budget ${c})`);return}if(await this.mergeOrphanInto(s,a)){d.warn(`[telemetry] reclaimed orphan pending: ${s} (${n} bytes)`);return}d.warn(`[telemetry] merge failed, kept orphan pending for retry: ${s} (${n} bytes)`)}async claimOrphan(e,t,n){let o=E.join(t,`${n}.pending.reclaim-${process.pid}-${Date.now()}`);try{await f.promises.rename(e,o)}catch{return null}return await this.touch(o),o}async mergeOrphanInto(e,t){try{await f.promises.appendFile(t,await f.promises.readFile(e))}catch(n){return d.warn(`[telemetry] merge orphan pending failed: ${e} -> ${t}: ${n instanceof Error?n.message:String(n)}`),!1}try{await f.promises.unlink(e)}catch(n){d.warn(`[telemetry] merged but failed to remove orphan pending: ${e}: ${n instanceof Error?n.message:String(n)}`)}return!0}async fileSize(e){try{return(await f.promises.stat(e)).size}catch{return 0}}async touch(e){let t=new Date;try{await f.promises.utimes(e,t,t)}catch{}}runExclusive(e){let t=()=>e(),n=this.flushChain.then(t,t);return this.flushChain=n.then(()=>{},()=>{}),n}async listPendingFiles(){let e;try{e=await f.promises.readdir(this.storageDir)}catch{return[]}return e.filter(t=>t.startsWith("telemetry-")&&t.endsWith(".txt")).map(t=>E.join(this.storageDir,t)).sort()}async flushFile(e){let t=await this.fileSize(e);if(t>P){d.warn(`[telemetry] ${E.basename(e)} is ${t} bytes (> ${P}), dropped without uploading`);try{await f.promises.unlink(e)}catch{}return!0}let n=e+".pending";try{await f.promises.rename(e,n)}catch{return!1}await this.touch(n);let o;try{o=await f.promises.readFile(n,"utf8")}catch{return!1}let i=o.split(`
|
|
41
41
|
`).map(s=>s.trim()).filter(Boolean);if(i.length===0){try{await f.promises.unlink(n)}catch{}return!0}return this.uploadInBatches(n,i)}collectDecryptBatch(e,t){let n=[],o=16,i=t;for(;i<e.length&&n.length<r.MAX_BATCH;){let s=Be(e[i],this.traceFileKey);if(s===null){i++;continue}let a=Buffer.byteLength(s,"utf8")+1;if(n.length>0&&o+a>r.MAX_PAYLOAD_BYTES)break;n.push(s),o+=a,i++}return{batch:n,next:i}}async uploadInBatches(e,t){let n=0;for(;n<t.length;){let o=n,{batch:i,next:s}=this.collectDecryptBatch(t,n);n=s;let a=this.buildPayloadItems(i);if(a.length===0)continue;let c=JSON.stringify(a),g=!1;try{g=await this.uploader.upload(c,this.installId)}catch{}if(!g){d.warn("[telemetry] upload failed");let S=t.slice(o).join(`
|
|
42
42
|
`)+`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yinsen/deveco-cli-common",
|
|
3
|
-
"version": "1.4.0-Test.
|
|
3
|
+
"version": "1.4.0-Test.912",
|
|
4
4
|
"description": "HarmonyOS application development command line tool",
|
|
5
5
|
"supportedDocsApi": 1,
|
|
6
6
|
"license": "MIT",
|
|
@@ -78,7 +78,7 @@
|
|
|
78
78
|
"xpath": "^0.0.35",
|
|
79
79
|
"yaml": "^2.9.1",
|
|
80
80
|
"zod": "^4.4.3",
|
|
81
|
-
"@yinsen/deveco-cli-knowledgebase": "1.4.0-Test.
|
|
81
|
+
"@yinsen/deveco-cli-knowledgebase": "1.4.0-Test.912"
|
|
82
82
|
},
|
|
83
83
|
"devDependencies": {
|
|
84
84
|
"@types/adm-zip": "^0.5.8",
|
package/skills/index.json
CHANGED