@deveco-test/deveco-cli 1.3.5-Test.1 → 1.3.5-Test.2
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/LICENSE +21 -21
- package/README.md +1751 -1684
- package/THIRD-PARTY-LICENSES +45 -0
- package/dist/cli.js +129 -125
- package/dist/internal/telemetry-upload-background.js +3 -3
- package/package.json +58 -57
- package/{SKILL.md → skills/deveco-cli/SKILL.md} +256 -236
- package/src/resources/aclPermission/aclPermissionsInfo.json +310 -310
- package/src/resources/arkts-check.cjs +3642 -3642
- package/templates/application/AppScope/app.json5 +10 -10
- package/templates/application/AppScope/resources/base/element/string.json +8 -8
- package/templates/application/AppScope/resources/base/media/layered_image.json +6 -6
- package/templates/application/build-profile.json5 +41 -41
- package/templates/application/code-linter.json5 +31 -31
- package/templates/application/entry/build-profile.json5 +32 -32
- package/templates/application/entry/gitignore.txt +5 -5
- package/templates/application/entry/hvigorfile.ts +7 -7
- package/templates/application/entry/obfuscation-rules.txt +19 -19
- package/templates/application/entry/oh-package.json5 +10 -10
- package/templates/application/entry/src/main/ets/entryability/EntryAbility.ets +62 -62
- package/templates/application/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets +30 -30
- package/templates/application/entry/src/main/ets/pages/Index.ets +37 -37
- package/templates/application/entry/src/main/module.json5 +49 -49
- package/templates/application/entry/src/main/resources/base/element/color.json +7 -7
- package/templates/application/entry/src/main/resources/base/element/float.json +8 -8
- package/templates/application/entry/src/main/resources/base/element/string.json +15 -15
- package/templates/application/entry/src/main/resources/base/media/layered_image.json +6 -6
- package/templates/application/entry/src/main/resources/base/profile/backup_config.json +2 -2
- package/templates/application/entry/src/main/resources/base/profile/main_pages.json +5 -5
- package/templates/application/entry/src/main/resources/dark/element/color.json +7 -7
- package/templates/application/gitignore.txt +12 -12
- package/templates/application/hvigor/hvigor-config.json5 +23 -23
- package/templates/application/hvigorfile.ts +7 -7
- package/templates/application/oh-package.json5 +10 -10
package/dist/cli.js
CHANGED
|
@@ -1,102 +1,103 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var qw=Object.defineProperty;var zw=(n,e)=>{for(var t in e)qw(n,t,{get:e[t],enumerable:!0})};import*as Oc from"path";import{program as ae}from"commander";import{red as dO}from"colorette";var Ci={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},Uo={USER_AGENT:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",ACCEPT_LANGUAGE:"zh-CN"};var Ce={APP_ID:"1009",CONFIG_DIR_NAME:".config",APP_NAME:"deveco-cli",TOKEN_FILE_NAME:"token.enc",KEY_FILE_NAME:"token.dek",API_VERSION:"1.0.0",AUTH_SOURCE_DEVECO_CODE:"deveco-code"},Z={LOGIN_URL:"https://devecostudio.huawei.com",CN_LOGIN_URL:"https://cn.devecostudio.huawei.com",AUTH_APPLY_PATH:"console/DevEcoIDE/apply",TEMP_TOKEN_CHECK_PATH:"authrouter/auth/api/temptoken/check",JWT_TOKEN_CHECK_PATH:"authrouter/auth/api/jwToken/check",LOGIN_SUCCESS_PATH:"console/DevEcoCLI/loginSuccess",LOGIN_FAILED_PATH:"console/DevEcoCLI/loginFailed",LOGOUT_PATH:"authrouter/auth/api/logout",AGC_TEAM_LIST_URL:"https://connect-api.cloud.huawei.com/api/ups/user-permission-service/v1/user-team-list"},Wr={ALGORITHM:"aes-256-gcm",KEY_LENGTH:32,IV_LENGTH:12,KEK_VERSIONS:["kek-v1","kek-v2","kek-v3"]},ki={TMS_URL:"https://terms-drcn.platform.dbankcloud.cn/agreementservice/user",PRIVACY_ID:"20000257",PRIVACY_URL:"https://legal.cloud.huawei.com/terms/scope/huawei/deveco-cli/privacy-statement.htm?code=CN&language=zh-CN&branchid=0&contenttag=default"},Ii={baseUrl:Z.LOGIN_URL,authUrl:Z.AUTH_APPLY_PATH,tempTokenCheckUrl:Z.TEMP_TOKEN_CHECK_PATH,jwtTokenCheckUrl:Z.JWT_TOKEN_CHECK_PATH,successRedirectUrl:Z.LOGIN_SUCCESS_PATH,failedRedirectUrl:Z.LOGIN_FAILED_PATH,logoutUrl:Z.LOGOUT_PATH,agcTeamListUrl:Z.AGC_TEAM_LIST_URL,appId:Ce.APP_ID,timeout:Ci.LOGIN_TIMEOUT_MS,countryCode:"CN"};import{Command as qb}from"commander";import{green as ml,red as lm,yellow as fl}from"colorette";import Q from"fs";import*as $ from"path";import Lt from"json5";import*as $c from"fs";import*as ke from"path";function p(n){if(process.env.DEVECO_CLI_DEBUG){let e=typeof n=="function"?n():n;console.log(`[DEBUG] ${e}`)}}var E=class n{static ASCII_CONTROL_MAX=31;static ASCII_DELETE=127;static parsePositiveInteger(e,t="value"){let r=e.trim();if(!/^\d+$/.test(r))throw new Error(`${t} must be a positive integer`);let i=Number.parseInt(r,10);if(!Number.isInteger(i)||i<=0)throw new Error(`${t} must be a positive integer`);return i}static getLastLines(e,t){return!t||t<=0?e:e.split(/\r?\n/).slice(-t).join(`
|
|
3
3
|
`)}static parseDurationToSeconds(e,t="value"){let i=e.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)([sm])?$/);if(!i)throw new Error(`${t} must be like 30s, 5m or 2.5m (only s/m supported).`);let o=i[1];if((i[2]??"s")==="s")return n.parsePositiveInteger(o,t);if(!/^\d+(?:\.\d)?$/.test(o))throw new Error(`${t} supports a maximum of 1 decimal place for minutes (e.g. 2.5m).`);let a=Number.parseFloat(o);if(!Number.isFinite(a)||a<=0)throw new Error(`${t} must be a positive duration.`);return Math.round(a*60)}static filterLogsByRelativeWindow(e,t,r,i=new Date){if(!t&&!r)return e;let[o,s]=n.resolveTimeBounds(t,r,i),a=e.split(/\r?\n/),c=[],l=!1;for(let d of a){let g=n.extractTimestampFromLogLine(d,i);g&&(l=n.isWithinBounds(g,o,s)),l&&c.push(d)}return c.join(`
|
|
4
|
-
`)}static resolveTimeBounds(e,t,r){let i=e?new Date(r.getTime()-e*1e3):null,o=t?new Date(r.getTime()-t*1e3):null;return i&&o?i<o?[i,o]:[o,i]:i?[i,r]:o?[null,o]:[null,null]}static isWithinBounds(e,t,r){let i=e.getTime(),o=t?Math.floor(t.getTime()/1e3)*1e3:null,s=r?Math.floor(r.getTime()/1e3)*1e3+999:null;return!(o!==null&&i<o||s!==null&&i>s)}static extractTimestampFromLogLine(e,t){let r=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!r)return null;let i=t.getFullYear(),o=Number.parseInt(r[1],10)-1,s=Number.parseInt(r[2],10),a=Number.parseInt(r[3],10),c=Number.parseInt(r[4],10),l=Number.parseInt(r[5],10),d=r[6]??"0",g=Number.parseInt(d.padEnd(3,"0").slice(0,3),10),y=new Date(i,o,s,a,c,l,g);return y.getTime()>t.getTime()+1440*60*1e3&&y.setFullYear(i-1),y}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static assertBundleNameStrict(e){if(e.length<7||e.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${e.length}`);if(e.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example").');let t=e.split(".");if(t.length<3)throw new Error("Bundle name must contain at least 3 dot-separated segments.");let r=/^[a-zA-Z0-9_]+$/;for(let i=0;i<t.length;i++){let o=t[i];if(!r.test(o))throw new Error(`Segment "${o}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(i===0){if(!/^[a-zA-Z]/.test(o))throw new Error(`First segment "${o}" must start with a letter (a-z, A-Z).`)}else if(!/^[a-zA-Z0-9]/.test(o))throw new Error(`Segment "${o}" must start with a letter or digit.`);if(!/[a-zA-Z0-9]$/.test(o))throw new Error(`Segment "${o}" must end with a letter or digit.`)}}static assertModuleName(e){this.assertSafeName(e,"module name")}static assertAbilityName(e){this.assertSafeName(e,"ability name")}static assertSafeName(e,t){if(!/^[A-Za-z0-9_.]+$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogToken(e,t){if(!/^[A-Za-z0-9_.:\\-]{1,64}$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogKeyword(e){if(e.length===0||e.length>128)throw new Error(`Invalid keyword: ${JSON.stringify(e)}`);if([...e].some(r=>{let i=r.charCodeAt(0);return i<=n.ASCII_CONTROL_MAX||i===n.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let r=`'${e.replace(/'/g,"'\\''")}'`;return p(`quotePosixShellArg: ${e} -> ${r}`),r}static assertCrashFilename(e){if(!/^\w+-[\w.]+-\d+-\d+$/.test(e))throw new Error(`Invalid crash log filename: ${JSON.stringify(e)}`)}static assertHilogLevel(e){if(!/^[DIWEF]$/.test(e))throw new Error(`Invalid log level: ${e}`)}static resolvePathWithinRoot(e,t){if(Ce.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=Ce.resolve(Ce.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=Ce.normalize(e),i=Ce.relative(r,t);if(i.split(Ce.sep)[0]===".."||Ce.isAbsolute(i))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||Ce.isAbsolute(e)}static isPathContained(e,t){let r=Ce.resolve(t,e),i=Ce.relative(t,r);return n.isPathEscaping(i)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){let r=n.isPathContained(e,t);if(!r.contained)return r;let i;try{i=wc.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let o=Ce.resolve(i,e),s;try{s=wc.realpathSync(o)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${o}`}}return n.isPathContained(s,i)}};import tp from"crypto";import ee from"fs";import Nc from"os";import Ye from"path";import fw from"https";var Cu={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var xo=class n{static ENDPOINT=Cu.devecoApiTraceUpload;static SENDER="deveco-cli";async upload(e,t){let r={"Content-Type":"application/json",sender:n.SENDER,deviceid:t.replace(/-/g,""),"Content-Length":String(Buffer.byteLength(e,"utf8"))};try{let{body:i}=await this.httpPost(n.ENDPOINT,r,Buffer.from(e,"utf8"),6e4);return n.isSuccess(i)}catch{return!1}}static isSuccess(e){try{let t=JSON.parse(e),r=t?.code??t?.errorCode;return String(r)==="200"}catch{return!1}}async httpPost(e,t,r,i){let o=new URL(e);return new Promise((s,a)=>{let c=fw.request({protocol:o.protocol,hostname:o.hostname,port:o.port||(o.protocol==="https:"?443:80),path:o.pathname+o.search,method:"POST",headers:t,timeout:i},l=>{let d=[];l.on("data",g=>d.push(g)),l.on("end",()=>{s({code:l.statusCode??0,body:Buffer.concat(d).toString("utf8")})})});c.on("timeout",()=>{c.destroy(new Error("request timeout"))}),c.on("error",a),c.write(r),c.end()})}};var ku={identity:n=>n,camelCase:n=>n,snakeCase:n=>n.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()},Sc=class{constructor(e={}){this.config=e}serialize(e){let t=this.transform(e);return this.config.pretty?JSON.stringify(t,null,2):JSON.stringify(t)}toObject(e){return this.transform(e)}transform(e){if(e==null)return e;if(Array.isArray(e))return e.map(o=>this.transform(o));if(typeof e!="object")return e;let t=this.config.namingStrategy??ku.identity,r=this.config.fieldNames??{},i={};for(let[o,s]of Object.entries(e)){let a=r[o]??t(o);i[a]=this.transform(s)}return i}},Iu=new Sc({namingStrategy:ku.snakeCase,fieldNames:{}});import yi from"crypto";import Lo from"fs";import hw from"path";var No="aes-256-gcm",gw=12,yw="deveco-cli-trace-file",vw="trace-file-secret",Du=32;function Au(n){try{let e=Lo.readFileSync(n,"utf8").trim();return e&&Buffer.from(e,"base64").length===Du?e:null}catch{return null}}function Ru(n){let e=hw.join(n,vw),t=Au(e);if(t)return bc(t);let r=yi.randomBytes(Du).toString("base64");try{Lo.mkdirSync(n,{recursive:!0});try{Lo.writeFileSync(e,r,{flag:"wx"})}catch{let i=Au(e);if(i)return bc(i);Lo.writeFileSync(e,r)}}catch{}return bc(r)}function bc(n){return yi.createHash("sha256").update(yw).update(n).digest()}function Tu(n,e){let t=yi.randomBytes(gw),r=yi.createCipheriv(No,e,t),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o={version:1,algorithm:No,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:r.getAuthTag().toString("base64")};return JSON.stringify(o)}function xu(n,e){let t;try{t=JSON.parse(n)}catch{return null}if(!ww(t))return n;try{let r=yi.createDecipheriv(No,e,Buffer.from(t.iv,"base64"));return r.setAuthTag(Buffer.from(t.authTag,"base64")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"base64")),r.final()]).toString("utf8")}catch{return null}}function ww(n){if(!n||typeof n!="object")return!1;let e=n;return e.version===1&&e.algorithm===No&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}import*as j from"fs";import*as Ho from"path";import K from"fs";import{spawn as Sw}from"child_process";import*as Mo from"os";import*as O from"path";import bw from"json5";var Ec="Huawei";var _u=3;function Oo(n){if(!K.existsSync(n)||!K.statSync(n).isDirectory())return!1;let e=K.existsSync(O.join(n,"build-profile.json5")),t=K.existsSync(O.join(n,"hvigorfile.js"))||K.existsSync(O.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=K.readFileSync(O.join(n,"build-profile.json5"),"utf-8");return bw.parse(r).app!==void 0}catch{return!1}}function Pc(n,e,t){if(e>=t)return null;let r=Ew(n),i=Pw(r);if(i)return i;for(let o of r){let s=Pc(o,e+1,t);if(s)return s}return null}function Ew(n){try{let e=K.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(O.join(n,r.name));return t}catch{return[]}}function Pw(n){for(let e of n)if(Oo(e))return e;return null}function jt(n){if(!n||n.trim()==="")return null;let e=O.resolve(n),t;try{t=K.realpathSync(e)}catch{t=e}if(!K.existsSync(t))return null;if(Oo(t))return t;let r=t;for(let i=1;i<=3;i++){let o=O.dirname(r);if(o===r)break;if(Oo(o))return o;r=o}if(K.statSync(t).isDirectory()){let i=Pc(t,0,_u);if(i)return i}return null}function _o(n){if(!n||n.trim()==="")return null;let e=O.resolve(n),t;try{t=K.realpathSync(e)}catch{t=e}return!K.existsSync(t)||!K.statSync(t).isDirectory()?null:Oo(t)?t:Pc(t,0,_u)}var Lu="DevEco Studio";function Fu(){if(process.platform==="win32"){let n=[O.join("C:\\Program Files",Ec,Lu),O.join("C:\\Program Files (x86)",Ec,Lu)];return Nu(n)}if(process.platform==="darwin"){let n=["/Applications/DevEco Studio.app",O.join(process.env.HOME??"","Applications","DevEco Studio.app")];return Nu(n)}return null}function Nu(n){for(let e of n)if(K.existsSync(e))return e;return null}function wn(n,e){let t=e?O.join("standardIndex","index.js"):"index.js";return K.existsSync(O.join(n,"ace-server"))?O.join(n,"ace-server","out",t):O.join(n,"out",t)}function Fo(n){return K.existsSync(wn(n,!0))}var Cw=5e3,kw=64*1024,Mu=new Map;function $u(n,e){let t=Iw(n),r=Mu.get(t);if(r)return r;let i=Aw(n,e).catch(()=>!1);return Mu.set(t,i),i}function Iw(n){let e=O.resolve(n).replace(/\\/g,"/");return process.platform==="win32"?e.toLowerCase():e}function Ou(n){try{let e=JSON.parse(n.trim());return Array.isArray(e.protocols)?e.protocols.includes("--socket"):null}catch{return null}}function Aw(n,e){let t=wn(n,!0);if(!K.existsSync(t))return Promise.resolve(!1);let r=e||process.execPath||"node",i=[t,"--list-protocols"];return h.debug(`Executing: ${r} ${i.join(" ")}`),new Promise(o=>{let s=Sw(r,i,{stdio:["ignore","pipe","ignore"],windowsHide:!0}),a="",c=!1,l=g=>{c||(c=!0,clearTimeout(d),s.exitCode===null&&s.signalCode===null&&s.kill(),o(g))},d=setTimeout(()=>l(!1),Cw);s.stdout?.on("data",g=>{a=(a+g.toString("utf8")).slice(-kw);let y=Ou(a);y!==null&&l(y)}),s.on("error",()=>l(!1)),s.on("close",()=>l(Ou(a)??!1))})}var Dw=[".idea",".deveco","cxx","compile_commands.json"];function Br(n){return O.join(n,...Dw)}function ju(n){return new Promise(e=>setTimeout(e,n))}var Rw=new Set(["c","cc","cpp","cxx","h","hh","hpp","hxx"]);function Wr(n){let e=O.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&Rw.has(e)}function $o(n){return O.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function we(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function Tw(n){return we(n)}function gt(n){let e=Tw(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function sr(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??O.join(Mo.homedir(),"AppData","Local");return O.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?O.join(Mo.homedir(),"Library","Logs","devecocli-mcp-server"):O.join(Mo.homedir(),".local","share","devecocli-mcp-server","logs")}function Hu(n,e){let t=xw(e),r=Lw(t,n);if(r!==null)return r;let i=Date.now(),s=`${n.replace(/:/g,"\\:")}=${i}`,a=Nw(t,n,s);return Mw(e,a),i}function xw(n){let e;try{e=K.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function Lw(n,e){for(let t of n){let r=t.indexOf("=");if(r<=0||t.slice(0,r).replace(/\\:/g,":")!==e)continue;let o=parseInt(t.slice(r+1),10);return Number.isFinite(o)&&o>0?o:null}return null}function Nw(n,e,t){let r=!1,i=n.map(o=>{if(r)return o;let s=o.indexOf("=");return s<=0?o:o.slice(0,s).replace(/\\:/g,":")===e?(r=!0,t):o});return r||i.push(t),i}function Mw(n,e){try{K.mkdirSync(O.dirname(n),{recursive:!0})}catch{}try{K.writeFileSync(n,e.join(`
|
|
4
|
+
`)}static resolveTimeBounds(e,t,r){let i=e?new Date(r.getTime()-e*1e3):null,o=t?new Date(r.getTime()-t*1e3):null;return i&&o?i<o?[i,o]:[o,i]:i?[i,r]:o?[null,o]:[null,null]}static isWithinBounds(e,t,r){let i=e.getTime(),o=t?Math.floor(t.getTime()/1e3)*1e3:null,s=r?Math.floor(r.getTime()/1e3)*1e3+999:null;return!(o!==null&&i<o||s!==null&&i>s)}static extractTimestampFromLogLine(e,t){let r=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!r)return null;let i=t.getFullYear(),o=Number.parseInt(r[1],10)-1,s=Number.parseInt(r[2],10),a=Number.parseInt(r[3],10),c=Number.parseInt(r[4],10),l=Number.parseInt(r[5],10),d=r[6]??"0",g=Number.parseInt(d.padEnd(3,"0").slice(0,3),10),y=new Date(i,o,s,a,c,l,g);return y.getTime()>t.getTime()+1440*60*1e3&&y.setFullYear(i-1),y}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static assertBundleNameStrict(e){if(e.length<7||e.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${e.length}`);if(e.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example").');let t=e.split(".");if(t.length<3)throw new Error("Bundle name must contain at least 3 dot-separated segments.");let r=/^[a-zA-Z0-9_]+$/;for(let i=0;i<t.length;i++){let o=t[i];if(!r.test(o))throw new Error(`Segment "${o}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(i===0){if(!/^[a-zA-Z]/.test(o))throw new Error(`First segment "${o}" must start with a letter (a-z, A-Z).`)}else if(!/^[a-zA-Z0-9]/.test(o))throw new Error(`Segment "${o}" must start with a letter or digit.`);if(!/[a-zA-Z0-9]$/.test(o))throw new Error(`Segment "${o}" must end with a letter or digit.`)}}static assertModuleName(e){this.assertSafeName(e,"module name")}static assertAbilityName(e){this.assertSafeName(e,"ability name")}static assertSafeName(e,t){if(!/^[A-Za-z0-9_.]+$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogToken(e,t){if(!/^[A-Za-z0-9_.:\\-]{1,64}$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogKeyword(e){if(e.length===0||e.length>128)throw new Error(`Invalid keyword: ${JSON.stringify(e)}`);if([...e].some(r=>{let i=r.charCodeAt(0);return i<=n.ASCII_CONTROL_MAX||i===n.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let r=`'${e.replace(/'/g,"'\\''")}'`;return p(`quotePosixShellArg: ${e} -> ${r}`),r}static assertCrashFilename(e){if(!/^\w+-[\w.]+-\d+-\d+$/.test(e))throw new Error(`Invalid crash log filename: ${JSON.stringify(e)}`)}static assertHilogLevel(e){if(!/^[DIWEF]$/.test(e))throw new Error(`Invalid log level: ${e}`)}static resolvePathWithinRoot(e,t){if(ke.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=ke.resolve(ke.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=ke.normalize(e),i=ke.relative(r,t);if(i.split(ke.sep)[0]===".."||ke.isAbsolute(i))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||ke.isAbsolute(e)}static isPathContained(e,t){let r=ke.resolve(t,e),i=ke.relative(t,r);return n.isPathEscaping(i)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){let r=n.isPathContained(e,t);if(!r.contained)return r;let i;try{i=$c.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let o=ke.resolve(i,e),s;try{s=$c.realpathSync(o)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${o}`}}return n.isPathContained(s,i)}};import Dp from"crypto";import ee from"fs";import es from"os";import Ze from"path";import Yw from"https";var Ku={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var Bo=class n{static ENDPOINT=Ku.devecoApiTraceUpload;static SENDER="deveco-cli";async upload(e,t){let r={"Content-Type":"application/json",sender:n.SENDER,deviceid:t.replace(/-/g,""),"Content-Length":String(Buffer.byteLength(e,"utf8"))};try{let{body:i}=await this.httpPost(n.ENDPOINT,r,Buffer.from(e,"utf8"),6e4);return n.isSuccess(i)}catch{return!1}}static isSuccess(e){try{let t=JSON.parse(e),r=t?.code??t?.errorCode;return String(r)==="200"}catch{return!1}}async httpPost(e,t,r,i){let o=new URL(e);return new Promise((s,a)=>{let c=Yw.request({protocol:o.protocol,hostname:o.hostname,port:o.port||(o.protocol==="https:"?443:80),path:o.pathname+o.search,method:"POST",headers:t,timeout:i},l=>{let d=[];l.on("data",g=>d.push(g)),l.on("end",()=>{s({code:l.statusCode??0,body:Buffer.concat(d).toString("utf8")})})});c.on("timeout",()=>{c.destroy(new Error("request timeout"))}),c.on("error",a),c.write(r),c.end()})}};var Xu={identity:n=>n,camelCase:n=>n,snakeCase:n=>n.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()},jc=class{constructor(e={}){this.config=e}serialize(e){let t=this.transform(e);return this.config.pretty?JSON.stringify(t,null,2):JSON.stringify(t)}toObject(e){return this.transform(e)}transform(e){if(e==null)return e;if(Array.isArray(e))return e.map(o=>this.transform(o));if(typeof e!="object")return e;let t=this.config.namingStrategy??Xu.identity,r=this.config.fieldNames??{},i={};for(let[o,s]of Object.entries(e)){let a=r[o]??t(o);i[a]=this.transform(s)}return i}},Zu=new jc({namingStrategy:Xu.snakeCase,fieldNames:{}});import Di from"crypto";import Wo from"fs";import Kw from"path";var Vo="aes-256-gcm",Xw=12,Zw="deveco-cli-trace-file",Qw="trace-file-secret",ep=32;function Qu(n){try{let e=Wo.readFileSync(n,"utf8").trim();return e&&Buffer.from(e,"base64").length===ep?e:null}catch{return null}}function tp(n){let e=Kw.join(n,Qw),t=Qu(e);if(t)return Hc(t);let r=Di.randomBytes(ep).toString("base64");try{Wo.mkdirSync(n,{recursive:!0});try{Wo.writeFileSync(e,r,{flag:"wx"})}catch{let i=Qu(e);if(i)return Hc(i);Wo.writeFileSync(e,r)}}catch{}return Hc(r)}function Hc(n){return Di.createHash("sha256").update(Zw).update(n).digest()}function rp(n,e){let t=Di.randomBytes(Xw),r=Di.createCipheriv(Vo,e,t),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o={version:1,algorithm:Vo,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:r.getAuthTag().toString("base64")};return JSON.stringify(o)}function np(n,e){let t;try{t=JSON.parse(n)}catch{return null}if(!eS(t))return n;try{let r=Di.createDecipheriv(Vo,e,Buffer.from(t.iv,"base64"));return r.setAuthTag(Buffer.from(t.authTag,"base64")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"base64")),r.final()]).toString("utf8")}catch{return null}}function eS(n){if(!n||typeof n!="object")return!1;let e=n;return e.version===1&&e.algorithm===Vo&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}import*as H from"fs";import*as Xo from"path";import K from"fs";import{spawn as tS}from"child_process";import*as Go from"os";import*as O from"path";import rS from"json5";var Uc="Huawei";var cp=3;function qo(n){if(!K.existsSync(n)||!K.statSync(n).isDirectory())return!1;let e=K.existsSync(O.join(n,"build-profile.json5")),t=K.existsSync(O.join(n,"hvigorfile.js"))||K.existsSync(O.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=K.readFileSync(O.join(n,"build-profile.json5"),"utf-8");return rS.parse(r).app!==void 0}catch{return!1}}function Bc(n,e,t){if(e>=t)return null;let r=nS(n),i=iS(r);if(i)return i;for(let o of r){let s=Bc(o,e+1,t);if(s)return s}return null}function nS(n){try{let e=K.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(O.join(n,r.name));return t}catch{return[]}}function iS(n){for(let e of n)if(qo(e))return e;return null}function Wt(n){if(!n||n.trim()==="")return null;let e=O.resolve(n),t;try{t=K.realpathSync(e)}catch{t=e}if(!K.existsSync(t))return null;if(qo(t))return t;let r=t;for(let i=1;i<=3;i++){let o=O.dirname(r);if(o===r)break;if(qo(o))return o;r=o}if(K.statSync(t).isDirectory()){let i=Bc(t,0,cp);if(i)return i}return null}function zo(n){if(!n||n.trim()==="")return null;let e=O.resolve(n),t;try{t=K.realpathSync(e)}catch{t=e}return!K.existsSync(t)||!K.statSync(t).isDirectory()?null:qo(t)?t:Bc(t,0,cp)}var ip="DevEco Studio";function lp(){if(process.platform==="win32"){let n=[O.join("C:\\Program Files",Uc,ip),O.join("C:\\Program Files (x86)",Uc,ip)];return op(n)}if(process.platform==="darwin"){let n=["/Applications/DevEco Studio.app",O.join(process.env.HOME??"","Applications","DevEco Studio.app")];return op(n)}return null}function op(n){for(let e of n)if(K.existsSync(e))return e;return null}function En(n,e){let t=e?O.join("standardIndex","index.js"):"index.js";return K.existsSync(O.join(n,"ace-server"))?O.join(n,"ace-server","out",t):O.join(n,"out",t)}function Jo(n){return K.existsSync(En(n,!0))}var oS=5e3,sS=64*1024,sp=new Map;function dp(n,e){let t=aS(n),r=sp.get(t);if(r)return r;let i=cS(n,e).catch(()=>!1);return sp.set(t,i),i}function aS(n){let e=O.resolve(n).replace(/\\/g,"/");return process.platform==="win32"?e.toLowerCase():e}function ap(n){try{let e=JSON.parse(n.trim());return Array.isArray(e.protocols)?e.protocols.includes("--socket"):null}catch{return null}}function cS(n,e){let t=En(n,!0);if(!K.existsSync(t))return Promise.resolve(!1);let r=e||process.execPath||"node",i=[t,"--list-protocols"];return h.debug(`Executing: ${r} ${i.join(" ")}`),new Promise(o=>{let s=tS(r,i,{stdio:["ignore","pipe","ignore"],windowsHide:!0}),a="",c=!1,l=g=>{c||(c=!0,clearTimeout(d),s.exitCode===null&&s.signalCode===null&&s.kill(),o(g))},d=setTimeout(()=>l(!1),oS);s.stdout?.on("data",g=>{a=(a+g.toString("utf8")).slice(-sS);let y=ap(a);y!==null&&l(y)}),s.on("error",()=>l(!1)),s.on("close",()=>l(ap(a)??!1))})}var lS=[".idea",".deveco","cxx","compile_commands.json"];function Vr(n){return O.join(n,...lS)}function up(n){return new Promise(e=>setTimeout(e,n))}var dS=new Set(["c","cc","cpp","cxx","h","hh","hpp","hxx"]);function Gr(n){let e=O.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&dS.has(e)}function Yo(n){return O.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function we(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function uS(n){return we(n)}function vt(n){let e=uS(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function lr(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??O.join(Go.homedir(),"AppData","Local");return O.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?O.join(Go.homedir(),"Library","Logs","devecocli-mcp-server"):O.join(Go.homedir(),".local","share","devecocli-mcp-server","logs")}function pp(n,e){let t=pS(e),r=mS(t,n);if(r!==null)return r;let i=Date.now(),s=`${n.replace(/:/g,"\\:")}=${i}`,a=fS(t,n,s);return hS(e,a),i}function pS(n){let e;try{e=K.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function mS(n,e){for(let t of n){let r=t.indexOf("=");if(r<=0||t.slice(0,r).replace(/\\:/g,":")!==e)continue;let o=parseInt(t.slice(r+1),10);return Number.isFinite(o)&&o>0?o:null}return null}function fS(n,e,t){let r=!1,i=n.map(o=>{if(r)return o;let s=o.indexOf("=");return s<=0?o:o.slice(0,s).replace(/\\:/g,":")===e?(r=!0,t):o});return r||i.push(t),i}function hS(n,e){try{K.mkdirSync(O.dirname(n),{recursive:!0})}catch{}try{K.writeFileSync(n,e.join(`
|
|
5
5
|
`)+`
|
|
6
|
-
`,"utf8")}catch{}}function
|
|
7
|
-
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);
|
|
8
|
-
`,"utf8"),
|
|
9
|
-
`).map(s=>s.trim()).filter(Boolean);if(o.length===0){try{await ee.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=
|
|
6
|
+
`,"utf8")}catch{}}function Wc(n,e,t="[Cleanup]"){try{let r=O.dirname(n);if(!K.existsSync(r))return;let i=Date.now();for(let o of K.readdirSync(r,{withFileTypes:!0}))o.isDirectory()&&gS(O.join(r,o.name),i,e,t)}catch{}}function gS(n,e,t,r){try{let{mtimeMs:i}=K.statSync(n);if(e-i<=t)return;K.rmSync(n,{recursive:!0,force:!0});let o=Math.floor((e-i)/1e3);console.error(`${r} Removed expired dir (age ${Math.floor(o/86400)}d ${Math.floor(o%86400/3600)}h): ${n}`)}catch(i){console.error(`${r} Failed to remove expired dir ${n}: ${i}`)}}var mp="mcp-server.log",yS="mcp-server",vS={maxSize:10*1024*1024,maxFiles:4},Vc=class n{fd=null;logDir=null;currentLogFile=null;mode;rotationOptions;currentFileSize=0;currentDate="";isRotating=!1;minLevel;static LEVEL_ORDER={debug:0,info:1,warn:2,error:3};constructor(e,t){this.rotationOptions={...vS,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=lr(),this.currentLogFile=Xo.join(this.logDir,mp),H.existsSync(this.logDir)||H.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${i}`}getRotatedFileName(e,t){return Xo.join(this.logDir,`${yS}-${e}.log.${t}`)}fileExists(e){try{return H.accessSync(e,H.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=H.readdirSync(this.logDir),t=[];for(let i of e)if(i===mp||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=Xo.join(this.logDir,i),s=H.statSync(o);t.push({name:i,mtime:s.mtime,path:o})}t.sort((i,o)=>o.mtime.getTime()-i.mtime.getTime());let r=1+this.rotationOptions.maxFiles;for(let i=r;i<t.length;i++)try{H.unlinkSync(t[i].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let e=this.getCurrentDateString(),t=this.getRotatedFileName(e,this.rotationOptions.maxFiles);this.fileExists(t)&&H.unlinkSync(t);for(let i=this.rotationOptions.maxFiles-1;i>=1;i--){let o=this.getRotatedFileName(e,i),s=this.getRotatedFileName(e,i+1);this.fileExists(o)&&H.renameSync(o,s)}let r=this.getRotatedFileName(e,1);H.renameSync(this.currentLogFile,r),this.cleanupOrphanLogFiles(),this.openLogFile()}catch{this.openLogFile()}finally{this.isRotating=!1}}}openLogFile(){if(this.currentLogFile){this.currentDate=this.getCurrentDateString();try{if(this.fileExists(this.currentLogFile)){let e=H.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=H.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{H.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...r){if(this.mode==="silent"||n.LEVEL_ORDER[e]<n.LEVEL_ORDER[this.minLevel])return;let i=r.map(c=>c instanceof Error?`${c.name}: ${c.message}`:typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),o=i?`${t} ${i}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] [pid=${process.pid}] ${o}
|
|
7
|
+
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);H.writeSync(this.fd,c),this.checkRotation(c.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(a)}debug(e,...t){this.write("debug",e,...t)}info(e,...t){this.write("info",e,...t)}warn(e,...t){this.write("warn",e,...t)}error(e,...t){this.write("error",e,...t)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{H.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},ct=null;function qr(n=!1){ct&&ct.dispose(),ct=new Vc(n)}function fp(){ct&&(ct.dispose(),ct=null)}function hp(){ct&&ct.flush()}function gp(){return ct?.getLogFilePath()??null}function yp(){return ct?.getLogDirectory()??null}function Ko(){return ct||qr(!1),ct}var h={debug:(n,...e)=>Ko().debug(n,...e),info:(n,...e)=>Ko().info(n,...e),warn:(n,...e)=>Ko().warn(n,...e),error:(n,...e)=>Ko().error(n,...e)};import Ai from"fs";import Gc from"path";var Ri=300*1e3,Ti=3600*1e3,qc=10080*60*1e3,Pn=8*1024*1024,zc=3600*1e3,vp=".pending",wS=/\.reclaim-\d+-\d+$/;function je(){let n=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return n==="1"||n==="true"}var SS="upload-state.json";function Sp(n){return Gc.join(n,SS)}function bS(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function Zo(n){try{let e=Ai.readFileSync(Sp(n),"utf8"),t=JSON.parse(e);return{firstEventAt:typeof t.firstEventAt=="number"?t.firstEventAt:null,lastUploadAt:typeof t.lastUploadAt=="number"?t.lastUploadAt:null,lastRetryAt:typeof t.lastRetryAt=="number"?t.lastRetryAt:null}}catch{return bS()}}function Jc(n,e){try{Ai.writeFileSync(Sp(n),JSON.stringify(e),"utf8")}catch{}}function bp(n){let e=Zo(n);e.firstEventAt===null&&(e.firstEventAt=Date.now(),Jc(n,e))}function Ep(n){let e=Zo(n);e.lastUploadAt=Date.now(),e.firstEventAt=null,Jc(n,e)}function Pp(n){let e=Zo(n);e.lastRetryAt=Date.now(),Jc(n,e)}function Yc(n){let e=n.match(/^telemetry-(\d{4})-(\d{2})-(\d{2})\.txt$/);if(!e)return null;let t=Date.parse(`${e[1]}-${e[2]}-${e[3]}T00:00:00`);return Number.isFinite(t)?t:null}function Kc(n){if(!n.startsWith("telemetry-"))return null;let e=wS.exec(n),t=e?n.slice(0,e.index):n;if(!t.endsWith(vp))return null;let r=t.slice(0,-vp.length);return r.endsWith(".txt")?r:null}function Xc(n){return Kc(n)!==null}function ES(n,e=Date.now()){try{return e-Ai.statSync(n).mtimeMs>=zc}catch{return!1}}function wp(n,e=Date.now()){let t;try{t=Ai.readdirSync(n)}catch{return!1}return t.some(r=>Xc(r)&&ES(Gc.join(n,r),e))}function PS(n,e=Date.now()){if(wp(n,e))return!0;let t=Gc.join(n,"failed");if(wp(t,e))return!0;let r;try{r=Ai.readdirSync(t)}catch{return!1}for(let i of r){if(!i.startsWith("telemetry-")||!i.endsWith(".txt"))continue;let o=Yc(i);if(o!==null&&e-o<=qc)return!0}return!1}function Cp(n,e=Date.now()){let t=Zo(n);return!!(t.firstEventAt!==null&&e-t.firstEventAt>=Ri||PS(n,e)&&(t.lastRetryAt===null||e-t.lastRetryAt>=Ti))}import CS from"crypto";import Qo from"fs";import kS from"path";var IS="install-id";function DS(n){return kS.join(n,IS)}function kp(n){try{let e=Qo.readFileSync(n,"utf8").trim();return AS(e)?e:null}catch{return null}}function AS(n){return/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(n)}function Ip(n){let e=DS(n),t=kp(e);if(t)return t;let r=CS.randomUUID();try{Qo.mkdirSync(n,{recursive:!0});try{Qo.writeFileSync(e,r,{flag:"wx"})}catch{let i=kp(e);if(i)return i;Qo.writeFileSync(e,r)}}catch{}return r}var xi=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 Bo;storageDir="";failedDir="";installId="";disabled=je();traceFileKey=Buffer.alloc(0);sessionId=Dp.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){h.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=Ze.join(e,"failed"),this.cliVersion="1.3.5-Test.2",this.nodeVersion=process.version,this.installId=Ip(e).replace(/-/g,""),this.traceFileKey=tp(e),ee.mkdirSync(e,{recursive:!0}),ee.mkdirSync(this.failedDir,{recursive:!0}),h.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,h.debug(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,h.debug(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,h.debug(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");if(!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.toErrorCode(o);throw await this.record(e,s,!1,a),o}}async record(e,t,r,i){let o=this.buildTraceEvent(e,t,r,i);try{let s=rp(JSON.stringify(o),this.traceFileKey);await ee.promises.appendFile(this.currentFile(),s+`
|
|
8
|
+
`,"utf8"),bp(this.storageDir)}catch{}}buildTraceEvent(e,t,r,i){let o=`${n.EVENT_PREFIX}${e.event}`,s=Zu.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:Dp.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}}}toErrorCode(e){return e instanceof Error?e.code??e.name:"UnknownError"}resolveOsArch(){let e=es.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=es.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 es.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(es.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 Ze.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){h.debug("[telemetry] scheduler not started (telemetry disabled)");return}h.debug(`[telemetry] scheduler started (flush every ${Ri/1e3}s, retry failed every ${Ti/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},Ri)},Ri),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},Ti)},Ti)}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),h.debug("[telemetry] scheduler stopped")}async flush(){return this.disabled?!0:this.runExclusive(()=>this.performFlush())}async performFlush(){if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");let e=await this.listPendingFiles(),t=!0;for(let r of e)await this.flushFile(r)||(t=!1);return Ep(this.storageDir),t}async retryFailed(){return this.disabled?!0:this.runExclusive(()=>this.performRetryFailed())}async performRetryFailed(){if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");await this.reclaimStalePending();let e=Date.now(),t;try{t=await ee.promises.readdir(this.failedDir)}catch{return!0}let r=t.filter(o=>o.startsWith("telemetry-")&&o.endsWith(".txt")).map(o=>Ze.join(this.failedDir,o)),i=!0;for(let o of r){let s=Ze.basename(o),a=Yc(s);if(a!==null){if(e-a>qc){try{await ee.promises.unlink(o)}catch{}continue}await this.flushFile(o)||(i=!1)}}return i||h.warn("[telemetry] retry failed"),Pp(this.storageDir),i}async reclaimStalePending(){let e=Date.now();for(let t of[this.storageDir,this.failedDir]){let r;try{r=await ee.promises.readdir(t)}catch{continue}for(let i of r)Xc(i)&&await this.reclaimOrphan(Ze.join(t,i),e)}}async reclaimOrphan(e,t){let r;try{let l=await ee.promises.stat(e);if(t-l.mtimeMs<zc)return;r=l.size}catch{return}let i=Ze.dirname(e),o=Kc(Ze.basename(e));if(o===null)return;let s=await this.claimOrphan(e,i,o);if(s===null)return;let a=Ze.join(i,o),c=Pn-await this.fileSize(a);if(r>c){try{await ee.promises.unlink(s)}catch{}h.warn(`[telemetry] dropped stale orphan pending: ${s} (${r} bytes > budget ${c})`);return}if(await this.mergeOrphanInto(s,a)){h.warn(`[telemetry] reclaimed orphan pending: ${s} (${r} bytes)`);return}h.warn(`[telemetry] merge failed, kept orphan pending for retry: ${s} (${r} bytes)`)}async claimOrphan(e,t,r){let i=Ze.join(t,`${r}.pending.reclaim-${process.pid}-${Date.now()}`);try{await ee.promises.rename(e,i)}catch{return null}return await this.touch(i),i}async mergeOrphanInto(e,t){try{await ee.promises.appendFile(t,await ee.promises.readFile(e))}catch(r){return h.warn(`[telemetry] merge orphan pending failed: ${e} -> ${t}: ${r instanceof Error?r.message:String(r)}`),!1}try{await ee.promises.unlink(e)}catch(r){h.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 ee.promises.stat(e)).size}catch{return 0}}async touch(e){let t=new Date;try{await ee.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 ee.promises.readdir(this.storageDir)}catch{return[]}return e.filter(t=>t.startsWith("telemetry-")&&t.endsWith(".txt")).map(t=>Ze.join(this.storageDir,t)).sort()}async flushFile(e){let t=await this.fileSize(e);if(t>Pn){h.warn(`[telemetry] ${Ze.basename(e)} is ${t} bytes (> ${Pn}), dropped without uploading`);try{await ee.promises.unlink(e)}catch{}return!0}let r=e+".pending";try{await ee.promises.rename(e,r)}catch{return!1}await this.touch(r);let i;try{i=await ee.promises.readFile(r,"utf8")}catch{return!1}let o=i.split(`
|
|
9
|
+
`).map(s=>s.trim()).filter(Boolean);if(o.length===0){try{await ee.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=np(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){h.warn("[telemetry] upload failed");let d=t.slice(i).join(`
|
|
10
10
|
`)+`
|
|
11
|
-
`;return await this.moveToFailed(e,d),!1}}try{await ee.promises.unlink(e)}catch{}return!0}buildPayloadItems(e){let t=[];for(let r of e)try{let i=JSON.parse(r);t.push({action:i.event,detail:JSON.stringify(i.properties),timestamp:Number(i.eventtime)||Date.now()})}catch{}return t}async moveToFailed(e,t){let r=
|
|
12
|
-
`).filter(Boolean),s=
|
|
11
|
+
`;return await this.moveToFailed(e,d),!1}}try{await ee.promises.unlink(e)}catch{}return!0}buildPayloadItems(e){let t=[];for(let r of e)try{let i=JSON.parse(r);t.push({action:i.event,detail:JSON.stringify(i.properties),timestamp:Number(i.eventtime)||Date.now()})}catch{}return t}async moveToFailed(e,t){let r=Ze.basename(e,".pending"),i=Ze.join(this.failedDir,r),o=t.split(`
|
|
12
|
+
`).filter(Boolean),s=Pn-await this.fileSize(i),a=this.takeNewestWithinBudget(o,s);a.length<o.length&&h.warn(`[telemetry] failed file capped at ${Pn} bytes, dropped ${o.length-a.length} older events`);try{a.length>0&&await ee.promises.appendFile(i,a.join(`
|
|
13
13
|
`)+`
|
|
14
|
-
`,"utf8")}catch{return}try{await ee.promises.unlink(e)}catch{}}takeNewestWithinBudget(e,t){if(t<=0)return[];let r=[],i=0;for(let o=e.length-1;o>=0;o--){let s=Buffer.byteLength(e[o],"utf8")+1;if(i+s>t)break;i+=s,r.push(e[o])}return r.reverse(),r}};var k=new bi;import{spawn as Jw}from"child_process";import{existsSync as Yw}from"fs";import{dirname as Kw,join as Xw}from"path";import{fileURLToPath as Zw}from"url";function Qw(){let n=Kw(Zw(import.meta.url)),e=Xw(n,"internal","telemetry-upload-background.js");return Yw(e)?e:null}function Mc(n){if(At()||!Zu(n))return;let e=Qw();if(!e){h.warn("[telemetry] background upload script not found, skipping spawn");return}try{Jw(process.execPath,[e],{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1",DEVECO_CLI_TELEMETRY_UPLOAD:"1"}}).unref()}catch(t){h.warn("[telemetry] failed to spawn background upload:",t)}}var S=class extends Error{traceMessage;constructor(e,t,r){super(e,r),this.name="TraceError",this.traceMessage=t??e}};function B(n){if(n instanceof S)return n.traceMessage;if(n instanceof Error){let e=n.code;return typeof e=="string"&&e!==""?e:n.name}return"UnknownError"}var b={CommandExecuted:"Command_executed",McpToolCall:"serve_mcp",SkillOperation:"skills",Init:"mcp_config_operation",SkillConfigOperation:"skill_config_operation",DocOperation:"docs",ServeLsp:"serve_lsp",CheckCommand:"check"};var xe={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json",LOCK_JSON5_PATH:"oh_modules/.ohpm/lock.json5"};var q=class n{rootDir;profile;constructor(e,t){this.rootDir=e,this.profile=t}static discover(e){let t=e;for(;;){let r=n.tryLoadProjectProfile(t);if(r)return new n(t,r);let i=$.dirname(t);if(i===t)break;t=i}throw new Error("Not in a valid project directory (project-level build-profile.json5 not found).")}static tryLoadProjectProfile(e){let t=$.join(e,"build-profile.json5");if(!Q.existsSync(t))return null;try{let r=Q.readFileSync(t,"utf-8"),i=Dt.parse(r);return i.app?i:null}catch(r){return console.error(`Error parsing ${t}:`,r),null}}getRunnableModuleNames(){return this.profile.modules.map(e=>e.name).filter(e=>this.getModuleType(e)!=="har").join(", ")}getModuleType(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)throw new S(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let r=E.resolvePathWithinRoot(this.rootDir,t.srcPath),i=$.join(r,"src","main","module.json5");if(!Q.existsSync(i))return"entry";try{let o=Q.readFileSync(i,"utf-8");return Dt.parse(o)?.module?.type||"entry"}catch(o){return console.warn(`Warning: Failed to parse ${i}:`,o),"entry"}}findOwningModule(e){let t=$.normalize(e);for(let r of this.profile.modules){let i=$.normalize($.join(this.rootDir,r.srcPath)),o=i+$.sep;if(t.startsWith(o)||t===i)return r.name}return null}getModuleProfile(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)throw new S(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let r=E.resolvePathWithinRoot(this.rootDir,t.srcPath),i=$.join(r,"build-profile.json5");if(!Q.existsSync(i))throw new S(`Build profile for module '${e}' not found at ${i}.`,"Build profile for module not found at ${profilePath}.");try{let o=Q.readFileSync(i,"utf-8");return Dt.parse(o)}catch(o){throw new Error(`Failed to parse module build profile at ${i}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}}getBundleName(e){if(e){let r=this.profile.app.products?.find(i=>i.name===e);if(r?.bundleName)return r.bundleName}let t=$.join(this.rootDir,"AppScope","app.json5");if(Q.existsSync(t))try{let r=Q.readFileSync(t,"utf-8"),i=Dt.parse(r);if(i?.app?.bundleName)return i.app.bundleName}catch(r){console.warn(`Warning: Failed to parse ${t}:`,r)}throw new Error("Could not find bundleName in AppScope/app.json5.")}isAtomicService(){let e=$.join(this.rootDir,"AppScope","app.json5");if(!Q.existsSync(e))return!1;try{let t=Q.readFileSync(e,"utf-8");return Dt.parse(t)?.app?.bundleType==="atomicService"}catch{return!1}}getMainAbility(e,t){if(t)return t;let r=this.profile.modules.find(s=>s.name===e);if(!r)return"EntryAbility";let i=E.resolvePathWithinRoot(this.rootDir,r.srcPath),o=$.join(i,"src","main","module.json5");if(!Q.existsSync(o))return"EntryAbility";try{let s=Q.readFileSync(o,"utf-8"),c=Dt.parse(s)?.module?.abilities||[];if(c.length===0)return"EntryAbility";let l=c.find(d=>d.name==="EntryAbility");return l?l.name:c[0].name}catch(s){return console.warn(`Warning: Failed to parse ${o}:`,s),"EntryAbility"}}validateProduct(e){if(!/^[\da-zA-Z_-]+$/.test(e))throw new S(`Invalid product name '${e}'. Product names must only contain letters, digits, underscores, and hyphens.`,"Invalid product name.");if(!this.profile.app.products?.some(r=>r.name===e)){let r=this.profile.app.products?.map(i=>i.name).join(", ")||"none";throw new S(`Product '${e}' not found in project configuration. Available products: ${r}`,"Productnot found in project configuration.")}}getModuleDependencies(e){let t=this.profile.modules.find(i=>i.name===e);if(!t)return[];let r=this.readLockFinalLocalModuleDeps(e);return r!==null?r:this.readOhPackageLocalModuleDeps(t)}readLockFinalLocalModuleDeps(e){let t=$.join(this.rootDir,xe.LOCK_JSON5_PATH);if(!Q.existsSync(t))return null;let r;try{r=Dt.parse(Q.readFileSync(t,"utf-8"))}catch(d){return p(`Failed to parse lock.json5: ${d instanceof Error?d.message:String(d)}`),null}let i=r,o=i?.modules;if(!o||typeof o!="object")return null;let s=Object.values(o).find(d=>typeof d=="object"&&d!==null&&d.name===e);if(!s)return null;let a=this.buildOverrideMap(i.overrides),c=[],l=new Set;for(let d of["dependencies","dynamicDependencies"]){let g=s[d];!g||typeof g!="object"||this.collectLocalDeps(g,a,y=>this.resolveLockDepByVersion(y),c,l)}return c}resolveLockDepByVersion(e){if(typeof e!="object"||e===null)return null;let t=e.version;return typeof t=="string"?this.resolveLocalDepToModule(t):null}resolveDepModule(e,t,r){if(t?.has(e)){let i=t.get(e);if(i){let o=this.resolveLocalDepToModule(i);if(o)return o}}return r()}buildOverrideMap(e){if(!e||typeof e!="object")return null;let t=new Map;for(let[r,i]of Object.entries(e))typeof i=="string"&&t.set(r,i);return t.size>0?t:null}resolveLocalDepToModule(e){let t=n.stripLocalDep(e);if(!t)return null;let r=$.resolve(this.rootDir,t),i;try{i=E.ensurePathWithinRoot(this.rootDir,r)}catch{return null}let o=this.profile.modules.find(s=>$.resolve(this.rootDir,s.srcPath)===i);return o?o.name:null}static stripLocalDep(e){return!e.startsWith("file:")&&!e.startsWith(".")&&!e.startsWith("..")?null:e.startsWith("file:")?e.substring(5):e}readOhPackageLocalModuleDeps(e){let t=$.join(E.resolvePathWithinRoot(this.rootDir,e.srcPath),xe.OH_PACKAGE_JSON5);if(!Q.existsSync(t))return[];let r=this.readRootOverrideMap(),i=[],o=new Set;try{let s=Dt.parse(Q.readFileSync(t,"utf-8"));for(let a of["dependencies","dynamicDependencies"]){let c=s?.[a];!c||typeof c!="object"||this.collectLocalDeps(c,r,l=>this.resolveOhPackageDepByValue(l,e),i,o)}}catch(s){p(`Failed to get module dependencies: ${s instanceof Error?s.message:String(s)}`)}return i}readRootOverrideMap(){let e=$.join(this.rootDir,xe.OH_PACKAGE_JSON5);if(!Q.existsSync(e))return null;try{let t=Dt.parse(Q.readFileSync(e,"utf-8"));return this.buildOverrideMap(t?.overrides)}catch{return null}}resolveOhPackageDepByValue(e,t){return typeof e=="string"?this.resolveLocalDepModuleName(e,t):null}collectLocalDeps(e,t,r,i,o){for(let[s,a]of Object.entries(e)){let c=this.resolveDepModule(s,t,()=>r(a));c&&!o.has(c)&&(o.add(c),i.push(c))}}resolveLocalDepModuleName(e,t){let r=n.stripLocalDep(e);if(!r)return null;let i=$.join(t.srcPath,r),o=E.resolvePathWithinRoot(this.rootDir,i),s=this.profile.modules.find(a=>$.resolve(this.rootDir,a.srcPath)===o);return s?s.name:null}collectNonHarDependentModuleList(e){let t=[],r=[],i=new Set;for(r.push(e),i.add(e);r.length>0;){let o=r.shift();this.getModuleType(o)!=="har"&&t.push(o);let a=this.getModuleDependencies(o);for(let c of a)i.has(c)||(r.push(c),i.add(c))}return t}resolveModuleMetadata(e,t,r){this.validateProduct(r);let i=this.profile.modules.find(l=>l.name===e);if(!i){let l=this.getRunnableModuleNames();throw new S(`Module '${e}' not found. Available modules: ${l}`,"Module not found.")}let o=this.getModuleType(e)==="shared",s=o?"hspName":"hapName",a=this.buildOutputPath(i.srcPath,r,["intermediates",o?"hsp_metadata":"hap_metadata",t,"output_metadata.json"]);if(!Q.existsSync(a))throw new S(`Build metadata not found for module '${e}' at ${a}. Build the project first.`,"Build metadata not found for module. Build the project first.");let c=this.parseOutputMetadata(a,s);return{moduleNode:i,isShared:o,metadataPath:a,metadata:c}}findArtifactPath(e,t,r,i="default"){let{moduleNode:o,isShared:s,metadata:a}=this.resolveModuleMetadata(e,t,i),{packageName:c,isSigned:l}=a,d=c;if(!l){let I=this.getSignedHapName(c,o.srcPath,i,t);I&&(d=I)}let g=s?"-signed.hsp":"-signed.hap";if(!r&&!d.endsWith(g))throw new S(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`,"Target device is a real device, but the artifact is not signed.");let y=this.buildOutputPath(o.srcPath,i,["outputs",t,d]);if(!Q.existsSync(y))throw new S(`Generated package file not found in ${y}.`,"Generated package file not found.");return y}findRemoteHspPaths(e,t,r="default"){let{moduleNode:i,metadata:o}=this.resolveModuleMetadata(e,t,r),s=[],a=new Set;for(let{hspPath:c}of o.dependRemoteHsps){if(a.has(c))continue;a.add(c);let l=$.isAbsolute(c)?c:this.buildOutputPath(i.srcPath,r,["outputs",t,c]);if(!Q.existsSync(l))throw new S(`Remote HSP dependency not found: ${l}`,"Remote HSP dependency not found.");s.push(l)}return s}getSignedHapName(e,t,r,i){let o=null;if(e.endsWith("-unsigned.hap")?o=e.replace("-unsigned.hap","-signed.hap"):e.endsWith("-unsigned.hsp")&&(o=e.replace("-unsigned.hsp","-signed.hsp")),!o)return null;let s=this.buildOutputPath(t,r,["outputs",i,o]);return Q.existsSync(s)?o:null}buildOutputPath(e,t,r){let i=E.resolvePathWithinRoot(this.rootDir,e),o=$.resolve(i,"build",t,...r);return E.ensurePathWithinRoot(this.rootDir,o)}collectRemoteHsps(e){return e.flatMap(t=>{let r=t.dependRemoteHsps;return Array.isArray(r)?r.filter(i=>!!(i.hspName&&i.hspPath)).map(i=>({hspName:i.hspName,hspPath:i.hspPath})):[]})}parseOutputMetadata(e,t){let r;try{let c=Q.readFileSync(e,"utf-8");r=Dt.parse(c)}catch(c){throw new Error(`Failed to parse output metadata at ${e}: ${c instanceof Error?c.message:String(c)}`,{cause:c})}let i,o=!1,s=Array.isArray(r)?r:[r];for(let c of s)i||(i=c[t]),o||(o=c.isSigned===!0);if(!i)throw new S(`Could not find ${t} in output_metadata.json at ${e}`,"Could not find metadataKey in output_metadata.json at metadataPath.");this.validatePackageName(i);let a=this.collectRemoteHsps(s);return{packageName:i,isSigned:o,dependRemoteHsps:a}}validatePackageName(e){let t=$.basename(e);if(t!==e)throw new S(`Invalid traversal name: '${e}'. It must contain path characters.`,"Invalid traversal name.");if(!t.endsWith(".hap")&&!t.endsWith(".hsp"))throw new S(`Invalid package name '${t}'.It must be a .hap or .hsp file.`,"Invalid package name.")}};import{spawnSync as mp}from"child_process";import ke from"fs";import*as je from"os";import*as D from"path";import Vo from"fs";import*as Go from"os";import*as Ei from"path";import nS from"regedit";import{execFileSync as tS}from"child_process";import np from"fs";import*as ip from"os";import*as Oc from"path";import{compare as eS}from"semver";function rp(n,e){return eS(n,e)}function bn(n,e){let t=Math.max(n.split(".").length,e.split(".").length);for(let r=0;r<t;r++){let i=Number(n.split(".")[r]??0)-Number(e.split(".")[r]??0);if(i)return i}return 0}function Wo(n,e){let t=Oc.join(n,"Contents","Info.plist");if(!np.existsSync(t)){p(`[ToolProvider] Info.plist not found at: ${t}`);return}for(let[r,i]of[["/usr/libexec/PlistBuddy",["-c",`Print :${e}`,t]],["plutil",["-extract",e,"raw","-o","-",t]]])try{let o=tS(r,i,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(o&&!o.includes("Does Not Exist"))return o}catch{}}function rS(n){let e=Wo(n,"CFBundleShortVersionString");if(!e)return Wo(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[Wo(n,"CFBundleVersion"),Wo(n,"CFBundleGetInfoString")?.match(/DS-[\d.]+/)?.[0]];for(let i of r){let o=i?.split(".").at(-1)?.replace(new RegExp(`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`),"");if(o&&/^\d+$/.test(o))return`${e}.${o}`}return e}function ar(n){if(ip.platform()==="darwin")return rS(n);let e=Oc.join(n,"product-info.json");try{let t=JSON.parse(np.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}var iS="DevEco Studio",oS=["Contents","Resources","product-info.json"],sS="name";function aS(n){return n.filter(e=>{try{return Vo.statSync(e).isDirectory()}catch{return!1}})}function cS(n){let e=Ei.join(n,...oS);if(Vo.existsSync(e))try{let r=JSON.parse(Vo.readFileSync(e,"utf8"))[sS];return typeof r=="string"&&r.trim()?r.trim():void 0}catch{return}}function lS(n){return cS(n)===iS}function dS(){let n=[];for(let e of[Ei.join(Go.homedir(),"Applications"),"/Applications"])try{n.push(...Vo.readdirSync(e).filter(t=>t.endsWith(".app")).map(t=>Ei.join(e,t)).filter(lS))}catch{}return n}function op(n){return new Promise((e,t)=>nS.list(n,(r,i)=>r?t(r):e(i)))}async function sp(n,e,t){let i=((await op([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(i.length===0)return[];let o=await op(i);return i.flatMap(s=>{let a=o[s]?.values?.[t]?.value;return a?[a]:[]})}async function uS(){let n=[Ei.join("C:","Program Files","Huawei","DevEco Studio")];for(let e of["HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall","HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"])try{n.push(...await sp(e,t=>t.normalize("NFKC").trim().toLowerCase().startsWith("deveco studio"),"InstallLocation"))}catch{}for(let e of["HKLM\\SOFTWARE\\Huawei\\DevEco Studio","HKLM\\SOFTWARE\\WOW6432Node\\Huawei\\DevEco Studio"])try{n.push(...await sp(e,()=>!0,""))}catch{}return n}async function ap(){let n=Go.platform();if(n==="linux")throw new Error("DevEco Studio is not available on Linux. Set DEVECO_CLI_CLT_PATH to a Command Line Tools installation.");let e=n==="darwin"?dS():await uS(),t=aS(e).flatMap(r=>{let i=ar(r);return i?(p(`[ToolProvider] ${r} => version ${i}`),[{root:r,version:i}]):(p(`[ToolProvider] Skipping ${r}: could not read version`),[])});if(!t.length)throw new Error("DevEco Studio installation not found in default locations. Set DEVECO_CLI_STUDIO_PATH to a DevEco Studio installation, or set DEVECO_CLI_CLT_PATH to a Command Line Tools installation.");return t.reduce((r,i)=>bn(i.version,r.version)>0?i:r)}import*as cp from"fs";import*as Fe from"path";function _c(n,e){let t=Fe.relative(e,n);return t===""||!Fe.isAbsolute(t)&&!t.startsWith(`..${Fe.sep}`)&&t!==".."}function cr(n){let e=Fe.resolve(n),t=[],r=e;for(;;)try{let i=cp.realpathSync(r);return t.length===0?i:Fe.join(i,...t.reverse())}catch(i){if(i.code!=="ENOENT")throw i;let o=Fe.dirname(r);if(o===r)return e;t.push(Fe.basename(r)),r=o}}function lp(n,e){let t=cr(e),r=cr(n);return _c(r,t)?r:null}function Fc(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function qo(n){let e=Fc(n);if(!e)throw new Error("Path must not be empty.");return cr(e)}var $c="https://matrix.openharmony.cn",st={TAGS_API_URL:`${$c}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${$c}/api/registry/skill/skills`,SKILL_API_BASE:`${$c}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,DEFAULT_MAX_PAGES:100,SUCCESS_CODE:"20000"},yt={"trae-cn":{path:".trae-cn/skills",displayName:"trae-cn"},opencode:{path:".config/opencode/skills",displayName:"opencode"},pi:{path:".pi/agent/skills",displayName:"pi"},deveco:{path:".config/deveco/skills",displayName:"deveco"},cursor:{path:".cursor/skills",displayName:"cursor"},codebuddy:{path:".codebuddy/skills",displayName:"codebuddy"},qoder:{path:".qoder/skills",displayName:"qoder"},"claude-code":{path:".claude/skills",projectPath:".claude/skills",displayName:"claude-code"},codex:{path:".codex/skills",displayName:"codex"},atomcode:{path:".atomcode/skills",displayName:"atomcode"},dsh:{path:".dsh/skills",projectPath:".dsh/skills",displayName:"deepseek harness"}};import{homedir as Rt}from"os";import $e from"path";var Tt="deveco-mcp";var lr={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:$e.join(Rt(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},pi:{name:"pi",displayName:"Pi Coding Agent",supportsGlobal:!0,globalConfigPath:$e.join(Rt(),".pi","agent","mcp.json"),projectConfigPath:".pi/mcp.json",mcpServersKey:"mcpServers",format:"standard"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:$e.join(process.platform==="win32"?$e.join(process.env.APPDATA??$e.join(Rt(),"AppData","Roaming"),"Trae CN","User"):$e.join(Rt(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:$e.join(Rt(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:$e.join(Rt(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:$e.join(process.platform==="win32"?$e.join(process.env.APPDATA??$e.join(Rt(),"AppData","Roaming"),"Qoder","SharedClientCache"):$e.join(Rt(),"Library","Application Support","Qoder","SharedClientCache"),"mcp.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"standard"},"claude-code":{name:"claude-code",displayName:"Claude Code",supportsGlobal:!0,globalConfigPath:$e.join(Rt(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:$e.join(Rt(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function up(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function dp(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function pp(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function zo(n,e){return n.format==="opencode"?up(e):n.format==="claude-code"||n.format==="codex"?dp(e):pp(e)}var jc="https://developer.huawei.com/consumer/cn/download/";var pS=/^#\s*Version:\s*(\S+)/,mS="26.0.0.810";function fS(n){try{let e=JSON.parse(ke.readFileSync(n,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch(e){p(`[ToolProvider] Failed to parse API level from ${n}: ${e instanceof Error?e.message:String(e)}`);return}}function hS(n){let e=D.join(n,"default","openharmony");return[D.join(n,"default","sdk-pkg.json"),...["toolchains","native","previewer"].map(t=>D.join(e,t,"oh-uni-package.json"))]}var C=class n{constructor(e,t,r,i,o,s,a,c,l,d){this._sourceType=e;this._toolchainRoot=t;this._devecoStudioPath=r;this._nodePath=i;this._ohpmJsPath=o;this._hvigorJsPath=s;this._javaPath=a;this._sdkPath=c;this._hdcPath=l;this._emulatorPath=d}static installSourcePromise;get sourceType(){return this._sourceType}get toolchainRoot(){return this._toolchainRoot}get devecoStudioPath(){return this._devecoStudioPath}get nodePath(){return this._nodePath}get ohpmJsPath(){return this._ohpmJsPath}get hvigorJsPath(){return this._hvigorJsPath}get codelinterPath(){return n.resolveCodelinterPath(this._toolchainRoot,this._sourceType)}get arktsLangServerPath(){let e=n.buildToolPaths(this._toolchainRoot,this._sourceType).arktsLangServerCandidates;for(let t of e)if(ke.existsSync(t.marker))return t.root;return null}get clangdPath(){let e=n.buildToolPaths(this._toolchainRoot,this._sourceType).clangdPath;return ke.existsSync(e)?e:null}get javaPath(){return this._javaPath??""}get sdkPath(){return this._sdkPath}get hdcPath(){return this._hdcPath}get emulatorPath(){return this._emulatorPath}get emulatorLauncherPath(){return this.emulatorPath}assertJava(){if(this._sourceType==="clt"&&(this._javaPath=n.resolveCltJava(!0)),!this._javaPath)throw new Error("Java runtime is required to run hvigor. Set JAVA_HOME or add Java to PATH.")}assertStudio(){if(this._sourceType==="clt")throw new Error("This operation requires DevEco Studio. Set DEVECO_CLI_STUDIO_PATH to a DevEco Studio installation.")}assertLsp(){this.assertStudio()}static compareVersion(e,t){return bn(e,t)}static async checkVersion(){let e=await n.resolveInstallSource();(e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)).assertVersion()}static async new(){let e=await n.resolveInstallSource();return e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)}static fromCLT(e){let t=n.buildToolPaths(e,"clt");return n.assertBuiltPathsInsideRoot(e,t,!1),new n("clt",e,void 0,t.nodePath,t.ohpmJsPath,t.hvigorJsPath,n.resolveCltJava(!1),t.sdkPath,t.hdcPath,t.emulatorPath)}static fromIDE(e,t="studio"){let r=n.buildToolPaths(e,"studio");return n.assertBuiltPathsInsideRoot(e,r,!0),new n(t,e,e,r.nodePath,r.ohpmJsPath,r.hvigorJsPath,r.javaPath,r.sdkPath,r.hdcPath,r.emulatorPath)}assertVersion(){if(this._sourceType==="clt"){this.assertCltVersion();return}this.assertIdeVersion()}readVersion(){return this._sourceType==="clt"?n.readCltVersion(this._toolchainRoot):ar(this._toolchainRoot)}assertCltVersion(e="26.0.0"){if(this._sourceType!=="clt")throw new Error("This operation requires Command Line Tools.");n.assertMinimumVersion(n.readCltVersion(this._toolchainRoot),"Command Line Tools","version.txt",e,this._toolchainRoot)}assertIdeVersion(e="6.0.0"){this.assertStudio(),n.assertMinimumVersion(ar(this._toolchainRoot),"DevEco Studio","product-info.json / Info.plist",e,this._toolchainRoot)}require(e){if(this._sourceType==="clt"){this.requireClt(e.clt);return}this.requireIde(e.studio)}requireClt(e){if(e===!1)throw new Error("This operation is not supported in Command Line Tools mode.");typeof e=="string"&&this.assertCltVersion(e)}requireIde(e){if(e===!1)throw new Error("This operation is not supported in DevEco Studio mode.");typeof e=="string"&&this.assertIdeVersion(e)}static assertMinimumVersion(e,t,r,i,o){if(!e)throw new S(`Failed to determine ${t} version from ${r} at ${o}`,`Failed to determine ${t} version from ${r}`);if(!/^\d+(?:\.\d+){1,3}$/.test(e))throw new S(`Invalid ${t} version "${e}" from ${r} at ${o}`,`Invalid ${t} version "${e}" from ${r}`);if(bn(e,i)<0)throw new Error(`The detected ${t} version is ${e}, which is below the minimum required version ${i}. Upgrade before using deveco-cli:
|
|
15
|
-
${
|
|
14
|
+
`,"utf8")}catch{return}try{await ee.promises.unlink(e)}catch{}}takeNewestWithinBudget(e,t){if(t<=0)return[];let r=[],i=0;for(let o=e.length-1;o>=0;o--){let s=Buffer.byteLength(e[o],"utf8")+1;if(i+s>t)break;i+=s,r.push(e[o])}return r.reverse(),r}};var k=new xi;import{spawn as RS}from"child_process";import{existsSync as TS}from"fs";import{dirname as xS,join as LS}from"path";import{fileURLToPath as NS}from"url";function MS(){let n=xS(NS(import.meta.url)),e=LS(n,"internal","telemetry-upload-background.js");return TS(e)?e:null}function Zc(n){if(je()||!Cp(n))return;let e=MS();if(!e){h.warn("[telemetry] background upload script not found, skipping spawn");return}try{RS(process.execPath,[e],{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1",DEVECO_CLI_TELEMETRY_UPLOAD:"1"}}).unref()}catch(t){h.warn("[telemetry] failed to spawn background upload:",t)}}var S=class extends Error{traceMessage;constructor(e,t,r){super(e,r),this.name="TraceError",this.traceMessage=t??e}};function B(n){if(n instanceof S)return n.traceMessage;if(n instanceof Error){let e=n.code;return typeof e=="string"&&e!==""?e:n.name}return"UnknownError"}var b={CommandExecuted:"Command_executed",McpToolCall:"serve_mcp",SkillOperation:"skills",Init:"mcp_config_operation",SkillConfigOperation:"skill_config_operation",DocOperation:"docs",ServeLsp:"serve_lsp",CheckCommand:"check"};var Le={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json",LOCK_JSON5_PATH:"oh_modules/.ohpm/lock.json5"};var q=class n{rootDir;profile;constructor(e,t){this.rootDir=e,this.profile=t}static discover(e){let t=e;for(;;){let r=n.tryLoadProjectProfile(t);if(r)return new n(t,r);let i=$.dirname(t);if(i===t)break;t=i}throw new Error("Not in a valid project directory (project-level build-profile.json5 not found).")}static tryLoadProjectProfile(e){let t=$.join(e,"build-profile.json5");if(!Q.existsSync(t))return null;try{let r=Q.readFileSync(t,"utf-8"),i=Lt.parse(r);return i.app?i:null}catch(r){return console.error(`Error parsing ${t}:`,r),null}}getRunnableModuleNames(){return this.profile.modules.map(e=>e.name).filter(e=>this.getModuleType(e)!=="har").join(", ")}getModuleType(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)throw new S(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let r=E.resolvePathWithinRoot(this.rootDir,t.srcPath),i=$.join(r,"src","main","module.json5");if(!Q.existsSync(i))return"entry";try{let o=Q.readFileSync(i,"utf-8");return Lt.parse(o)?.module?.type||"entry"}catch(o){return console.warn(`Warning: Failed to parse ${i}:`,o),"entry"}}findOwningModule(e){let t=$.normalize(e);for(let r of this.profile.modules){let i=$.normalize($.join(this.rootDir,r.srcPath)),o=i+$.sep;if(t.startsWith(o)||t===i)return r.name}return null}getModuleProfile(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)throw new S(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let r=E.resolvePathWithinRoot(this.rootDir,t.srcPath),i=$.join(r,"build-profile.json5");if(!Q.existsSync(i))throw new S(`Build profile for module '${e}' not found at ${i}.`,"Build profile for module not found at ${profilePath}.");try{let o=Q.readFileSync(i,"utf-8");return Lt.parse(o)}catch(o){throw new Error(`Failed to parse module build profile at ${i}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}}getBundleName(e){if(e){let r=this.profile.app.products?.find(i=>i.name===e);if(r?.bundleName)return r.bundleName}let t=$.join(this.rootDir,"AppScope","app.json5");if(Q.existsSync(t))try{let r=Q.readFileSync(t,"utf-8"),i=Lt.parse(r);if(i?.app?.bundleName)return i.app.bundleName}catch(r){console.warn(`Warning: Failed to parse ${t}:`,r)}throw new Error("Could not find bundleName in AppScope/app.json5.")}isAtomicService(){let e=$.join(this.rootDir,"AppScope","app.json5");if(!Q.existsSync(e))return!1;try{let t=Q.readFileSync(e,"utf-8");return Lt.parse(t)?.app?.bundleType==="atomicService"}catch{return!1}}getMainAbility(e,t){if(t)return t;let r=this.profile.modules.find(s=>s.name===e);if(!r)return"EntryAbility";let i=E.resolvePathWithinRoot(this.rootDir,r.srcPath),o=$.join(i,"src","main","module.json5");if(!Q.existsSync(o))return"EntryAbility";try{let s=Q.readFileSync(o,"utf-8"),c=Lt.parse(s)?.module?.abilities||[];if(c.length===0)return"EntryAbility";let l=c.find(d=>d.name==="EntryAbility");return l?l.name:c[0].name}catch(s){return console.warn(`Warning: Failed to parse ${o}:`,s),"EntryAbility"}}validateProduct(e){if(!/^[\da-zA-Z_-]+$/.test(e))throw new S(`Invalid product name '${e}'. Product names must only contain letters, digits, underscores, and hyphens.`,"Invalid product name.");if(!this.profile.app.products?.some(r=>r.name===e)){let r=this.profile.app.products?.map(i=>i.name).join(", ")||"none";throw new S(`Product '${e}' not found in project configuration. Available products: ${r}`,"Productnot found in project configuration.")}}getModuleDependencies(e){let t=this.profile.modules.find(i=>i.name===e);if(!t)return[];let r=this.readLockFinalLocalModuleDeps(e);return r!==null?r:this.readOhPackageLocalModuleDeps(t)}readLockFinalLocalModuleDeps(e){let t=$.join(this.rootDir,Le.LOCK_JSON5_PATH);if(!Q.existsSync(t))return null;let r;try{r=Lt.parse(Q.readFileSync(t,"utf-8"))}catch(d){return p(`Failed to parse lock.json5: ${d instanceof Error?d.message:String(d)}`),null}let i=r,o=i?.modules;if(!o||typeof o!="object")return null;let s=Object.values(o).find(d=>typeof d=="object"&&d!==null&&d.name===e);if(!s)return null;let a=this.buildOverrideMap(i.overrides),c=[],l=new Set;for(let d of["dependencies","dynamicDependencies"]){let g=s[d];!g||typeof g!="object"||this.collectLocalDeps(g,a,y=>this.resolveLockDepByVersion(y),c,l)}return c}resolveLockDepByVersion(e){if(typeof e!="object"||e===null)return null;let t=e.version;return typeof t=="string"?this.resolveLocalDepToModule(t):null}resolveDepModule(e,t,r){if(t?.has(e)){let i=t.get(e);if(i){let o=this.resolveLocalDepToModule(i);if(o)return o}}return r()}buildOverrideMap(e){if(!e||typeof e!="object")return null;let t=new Map;for(let[r,i]of Object.entries(e))typeof i=="string"&&t.set(r,i);return t.size>0?t:null}resolveLocalDepToModule(e){let t=n.stripLocalDep(e);if(!t)return null;let r=$.resolve(this.rootDir,t),i;try{i=E.ensurePathWithinRoot(this.rootDir,r)}catch{return null}let o=this.profile.modules.find(s=>$.resolve(this.rootDir,s.srcPath)===i);return o?o.name:null}static stripLocalDep(e){return!e.startsWith("file:")&&!e.startsWith(".")&&!e.startsWith("..")?null:e.startsWith("file:")?e.substring(5):e}readOhPackageLocalModuleDeps(e){let t=$.join(E.resolvePathWithinRoot(this.rootDir,e.srcPath),Le.OH_PACKAGE_JSON5);if(!Q.existsSync(t))return[];let r=this.readRootOverrideMap(),i=[],o=new Set;try{let s=Lt.parse(Q.readFileSync(t,"utf-8"));for(let a of["dependencies","dynamicDependencies"]){let c=s?.[a];!c||typeof c!="object"||this.collectLocalDeps(c,r,l=>this.resolveOhPackageDepByValue(l,e),i,o)}}catch(s){p(`Failed to get module dependencies: ${s instanceof Error?s.message:String(s)}`)}return i}readRootOverrideMap(){let e=$.join(this.rootDir,Le.OH_PACKAGE_JSON5);if(!Q.existsSync(e))return null;try{let t=Lt.parse(Q.readFileSync(e,"utf-8"));return this.buildOverrideMap(t?.overrides)}catch{return null}}resolveOhPackageDepByValue(e,t){return typeof e=="string"?this.resolveLocalDepModuleName(e,t):null}collectLocalDeps(e,t,r,i,o){for(let[s,a]of Object.entries(e)){let c=this.resolveDepModule(s,t,()=>r(a));c&&!o.has(c)&&(o.add(c),i.push(c))}}resolveLocalDepModuleName(e,t){let r=n.stripLocalDep(e);if(!r)return null;let i=$.join(t.srcPath,r),o=E.resolvePathWithinRoot(this.rootDir,i),s=this.profile.modules.find(a=>$.resolve(this.rootDir,a.srcPath)===o);return s?s.name:null}collectNonHarDependentModuleList(e){let t=[],r=[],i=new Set;for(r.push(e),i.add(e);r.length>0;){let o=r.shift();this.getModuleType(o)!=="har"&&t.push(o);let a=this.getModuleDependencies(o);for(let c of a)i.has(c)||(r.push(c),i.add(c))}return t}resolveModuleMetadata(e,t,r){this.validateProduct(r);let i=this.profile.modules.find(l=>l.name===e);if(!i){let l=this.getRunnableModuleNames();throw new S(`Module '${e}' not found. Available modules: ${l}`,"Module not found.")}let o=this.getModuleType(e)==="shared",s=o?"hspName":"hapName",a=this.buildOutputPath(i.srcPath,r,["intermediates",o?"hsp_metadata":"hap_metadata",t,"output_metadata.json"]);if(!Q.existsSync(a))throw new S(`Build metadata not found for module '${e}' at ${a}. Build the project first.`,"Build metadata not found for module. Build the project first.");let c=this.parseOutputMetadata(a,s);return{moduleNode:i,isShared:o,metadataPath:a,metadata:c}}findArtifactPath(e,t,r,i="default"){let{moduleNode:o,isShared:s,metadata:a}=this.resolveModuleMetadata(e,t,i),{packageName:c,isSigned:l}=a,d=c;if(!l){let I=this.getSignedHapName(c,o.srcPath,i,t);I&&(d=I)}let g=s?"-signed.hsp":"-signed.hap";if(!r&&!d.endsWith(g))throw new S(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`,"Target device is a real device, but the artifact is not signed.");let y=this.buildOutputPath(o.srcPath,i,["outputs",t,d]);if(!Q.existsSync(y))throw new S(`Generated package file not found in ${y}.`,"Generated package file not found.");return y}findRemoteHspPaths(e,t,r="default"){let{moduleNode:i,metadata:o}=this.resolveModuleMetadata(e,t,r),s=[],a=new Set;for(let{hspPath:c}of o.dependRemoteHsps){if(a.has(c))continue;a.add(c);let l=$.isAbsolute(c)?c:this.buildOutputPath(i.srcPath,r,["outputs",t,c]);if(!Q.existsSync(l))throw new S(`Remote HSP dependency not found: ${l}`,"Remote HSP dependency not found.");s.push(l)}return s}getSignedHapName(e,t,r,i){let o=null;if(e.endsWith("-unsigned.hap")?o=e.replace("-unsigned.hap","-signed.hap"):e.endsWith("-unsigned.hsp")&&(o=e.replace("-unsigned.hsp","-signed.hsp")),!o)return null;let s=this.buildOutputPath(t,r,["outputs",i,o]);return Q.existsSync(s)?o:null}buildOutputPath(e,t,r){let i=E.resolvePathWithinRoot(this.rootDir,e),o=$.resolve(i,"build",t,...r);return E.ensurePathWithinRoot(this.rootDir,o)}collectRemoteHsps(e){return e.flatMap(t=>{let r=t.dependRemoteHsps;return Array.isArray(r)?r.filter(i=>!!(i.hspName&&i.hspPath)).map(i=>({hspName:i.hspName,hspPath:i.hspPath})):[]})}parseOutputMetadata(e,t){let r;try{let c=Q.readFileSync(e,"utf-8");r=Lt.parse(c)}catch(c){throw new Error(`Failed to parse output metadata at ${e}: ${c instanceof Error?c.message:String(c)}`,{cause:c})}let i,o=!1,s=Array.isArray(r)?r:[r];for(let c of s)i||(i=c[t]),o||(o=c.isSigned===!0);if(!i)throw new S(`Could not find ${t} in output_metadata.json at ${e}`,"Could not find metadataKey in output_metadata.json at metadataPath.");this.validatePackageName(i);let a=this.collectRemoteHsps(s);return{packageName:i,isSigned:o,dependRemoteHsps:a}}validatePackageName(e){let t=$.basename(e);if(t!==e)throw new S(`Invalid traversal name: '${e}'. It must contain path characters.`,"Invalid traversal name.");if(!t.endsWith(".hap")&&!t.endsWith(".hsp"))throw new S(`Invalid package name '${t}'.It must be a .hap or .hsp file.`,"Invalid package name.")}};import{spawnSync as $p}from"child_process";import Ie from"fs";import*as Be from"os";import*as A from"path";import rs from"fs";import*as ns from"os";import*as Li from"path";import $S from"regedit";import{execFileSync as _S}from"child_process";import Ap from"fs";import*as Rp from"os";import*as Qc from"path";import{compare as OS}from"semver";function dr(n,e){return OS(n,e)}function Cn(n,e){let t=Math.max(n.split(".").length,e.split(".").length);for(let r=0;r<t;r++){let i=Number(n.split(".")[r]??0)-Number(e.split(".")[r]??0);if(i)return i}return 0}function ts(n,e){let t=Qc.join(n,"Contents","Info.plist");if(!Ap.existsSync(t)){p(`[ToolProvider] Info.plist not found at: ${t}`);return}for(let[r,i]of[["/usr/libexec/PlistBuddy",["-c",`Print :${e}`,t]],["plutil",["-extract",e,"raw","-o","-",t]]])try{let o=_S(r,i,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(o&&!o.includes("Does Not Exist"))return o}catch{}}function FS(n){let e=ts(n,"CFBundleShortVersionString");if(!e)return ts(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[ts(n,"CFBundleVersion"),ts(n,"CFBundleGetInfoString")?.match(/DS-[\d.]+/)?.[0]];for(let i of r){let o=i?.split(".").at(-1)?.replace(new RegExp(`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`),"");if(o&&/^\d+$/.test(o))return`${e}.${o}`}return e}function ur(n){if(Rp.platform()==="darwin")return FS(n);let e=Qc.join(n,"product-info.json");try{let t=JSON.parse(Ap.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}var jS="DevEco Studio",HS=["Contents","Resources","product-info.json"],US="name";function BS(n){return n.filter(e=>{try{return rs.statSync(e).isDirectory()}catch{return!1}})}function WS(n){let e=Li.join(n,...HS);if(rs.existsSync(e))try{let r=JSON.parse(rs.readFileSync(e,"utf8"))[US];return typeof r=="string"&&r.trim()?r.trim():void 0}catch{return}}function VS(n){return WS(n)===jS}function GS(){let n=[];for(let e of[Li.join(ns.homedir(),"Applications"),"/Applications"])try{n.push(...rs.readdirSync(e).filter(t=>t.endsWith(".app")).map(t=>Li.join(e,t)).filter(VS))}catch{}return n}function Tp(n){return new Promise((e,t)=>$S.list(n,(r,i)=>r?t(r):e(i)))}async function xp(n,e,t){let i=((await Tp([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(i.length===0)return[];let o=await Tp(i);return i.flatMap(s=>{let a=o[s]?.values?.[t]?.value;return a?[a]:[]})}async function qS(){let n=[Li.join("C:","Program Files","Huawei","DevEco Studio")];for(let e of["HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall","HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"])try{n.push(...await xp(e,t=>t.normalize("NFKC").trim().toLowerCase().startsWith("deveco studio"),"InstallLocation"))}catch{}for(let e of["HKLM\\SOFTWARE\\Huawei\\DevEco Studio","HKLM\\SOFTWARE\\WOW6432Node\\Huawei\\DevEco Studio"])try{n.push(...await xp(e,()=>!0,""))}catch{}return n}async function Lp(){let n=ns.platform();if(n==="linux")throw new Error("DevEco Studio is not available on Linux. Set DEVECO_CLI_CLT_PATH to a Command Line Tools installation.");let e=n==="darwin"?GS():await qS(),t=BS(e).flatMap(r=>{let i=ur(r);return i?(p(`[ToolProvider] ${r} => version ${i}`),[{root:r,version:i}]):(p(`[ToolProvider] Skipping ${r}: could not read version`),[])});if(!t.length)throw new Error("DevEco Studio installation not found in default locations. Set DEVECO_CLI_STUDIO_PATH to a DevEco Studio installation, or set DEVECO_CLI_CLT_PATH to a Command Line Tools installation.");return t.reduce((r,i)=>Cn(i.version,r.version)>0?i:r)}import*as Np from"fs";import*as He from"path";function el(n,e){let t=He.relative(e,n);return t===""||!He.isAbsolute(t)&&!t.startsWith(`..${He.sep}`)&&t!==".."}function pr(n){let e=He.resolve(n),t=[],r=e;for(;;)try{let i=Np.realpathSync(r);return t.length===0?i:He.join(i,...t.reverse())}catch(i){if(i.code!=="ENOENT")throw i;let o=He.dirname(r);if(o===r)return e;t.push(He.basename(r)),r=o}}function Mp(n,e){let t=pr(e),r=pr(n);return el(r,t)?r:null}function tl(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function is(n){let e=tl(n);if(!e)throw new Error("Path must not be empty.");return pr(e)}var rl="https://matrix.openharmony.cn",lt={TAGS_API_URL:`${rl}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${rl}/api/registry/skill/skills`,SKILL_API_BASE:`${rl}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,DEFAULT_MAX_PAGES:100,SUCCESS_CODE:"20000"},wt={"trae-cn":{path:".trae-cn/skills",displayName:"trae-cn"},opencode:{path:".config/opencode/skills",displayName:"opencode"},pi:{path:".pi/agent/skills",displayName:"pi"},deveco:{path:".config/deveco/skills",displayName:"deveco"},cursor:{path:".cursor/skills",displayName:"cursor"},codebuddy:{path:".codebuddy/skills",displayName:"codebuddy"},qoder:{path:".qoder/skills",displayName:"qoder"},"claude-code":{path:".claude/skills",projectPath:".claude/skills",displayName:"claude-code"},codex:{path:".codex/skills",displayName:"codex"},atomcode:{path:".atomcode/skills",displayName:"atomcode"},dsh:{path:".dsh/skills",projectPath:".dsh/skills",displayName:"deepseek harness"}};import{homedir as Nt}from"os";import Ue from"path";var Mt="deveco-mcp";var mr={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:Ue.join(Nt(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},pi:{name:"pi",displayName:"Pi Coding Agent",supportsGlobal:!0,globalConfigPath:Ue.join(Nt(),".pi","agent","mcp.json"),projectConfigPath:".pi/mcp.json",mcpServersKey:"mcpServers",format:"standard"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:Ue.join(process.platform==="win32"?Ue.join(process.env.APPDATA??Ue.join(Nt(),"AppData","Roaming"),"Trae CN","User"):Ue.join(Nt(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:Ue.join(Nt(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:Ue.join(Nt(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:Ue.join(process.platform==="win32"?Ue.join(process.env.APPDATA??Ue.join(Nt(),"AppData","Roaming"),"Qoder","SharedClientCache"):Ue.join(Nt(),"Library","Application Support","Qoder","SharedClientCache"),"mcp.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"standard"},"claude-code":{name:"claude-code",displayName:"Claude Code",supportsGlobal:!0,globalConfigPath:Ue.join(Nt(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:Ue.join(Nt(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function _p(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function Op(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function Fp(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function os(n,e){return n.format==="opencode"?_p(e):n.format==="claude-code"||n.format==="codex"?Op(e):Fp(e)}var nl="https://developer.huawei.com/consumer/cn/download/";var zS=/^#\s*Version:\s*(\S+)/,JS="26.0.0.810";function YS(n){try{let e=JSON.parse(Ie.readFileSync(n,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch(e){p(`[ToolProvider] Failed to parse API level from ${n}: ${e instanceof Error?e.message:String(e)}`);return}}function KS(n){let e=A.join(n,"default","openharmony");return[A.join(n,"default","sdk-pkg.json"),...["toolchains","native","previewer"].map(t=>A.join(e,t,"oh-uni-package.json"))]}var C=class n{constructor(e,t,r,i,o,s,a,c,l,d){this._sourceType=e;this._toolchainRoot=t;this._devecoStudioPath=r;this._nodePath=i;this._ohpmJsPath=o;this._hvigorJsPath=s;this._javaPath=a;this._sdkPath=c;this._hdcPath=l;this._emulatorPath=d}static installSourcePromise;get sourceType(){return this._sourceType}get toolchainRoot(){return this._toolchainRoot}get devecoStudioPath(){return this._devecoStudioPath}get nodePath(){return this._nodePath}get ohpmJsPath(){return this._ohpmJsPath}get hvigorJsPath(){return this._hvigorJsPath}get codelinterPath(){return n.resolveCodelinterPath(this._toolchainRoot,this._sourceType)}get arktsLangServerPath(){let e=n.buildToolPaths(this._toolchainRoot,this._sourceType).arktsLangServerCandidates;for(let t of e)if(Ie.existsSync(t.marker))return t.root;return null}get clangdPath(){let e=n.buildToolPaths(this._toolchainRoot,this._sourceType).clangdPath;return Ie.existsSync(e)?e:null}get javaPath(){return this._javaPath??""}get sdkPath(){return this._sdkPath}get hdcPath(){return this._hdcPath}get emulatorPath(){return this._emulatorPath}get emulatorLauncherPath(){return this.emulatorPath}assertJava(){if(this._sourceType==="clt"&&(this._javaPath=n.resolveCltJava(!0)),!this._javaPath)throw new Error("Java runtime is required to run hvigor. Set JAVA_HOME or add Java to PATH.")}assertStudio(){if(this._sourceType==="clt")throw new Error("This operation requires DevEco Studio. Set DEVECO_CLI_STUDIO_PATH to a DevEco Studio installation.")}assertLsp(){this.assertStudio()}static compareVersion(e,t){return Cn(e,t)}static async checkVersion(){let e=await n.resolveInstallSource();(e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)).assertVersion()}static async new(){let e=await n.resolveInstallSource();return e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)}static fromCLT(e){let t=n.buildToolPaths(e,"clt");return n.assertBuiltPathsInsideRoot(e,t,!1),new n("clt",e,void 0,t.nodePath,t.ohpmJsPath,t.hvigorJsPath,n.resolveCltJava(!1),t.sdkPath,t.hdcPath,t.emulatorPath)}static fromIDE(e,t="studio"){let r=n.buildToolPaths(e,"studio");return n.assertBuiltPathsInsideRoot(e,r,!0),new n(t,e,e,r.nodePath,r.ohpmJsPath,r.hvigorJsPath,r.javaPath,r.sdkPath,r.hdcPath,r.emulatorPath)}assertVersion(){if(this._sourceType==="clt"){this.assertCltVersion();return}this.assertIdeVersion()}readVersion(){return this._sourceType==="clt"?n.readCltVersion(this._toolchainRoot):ur(this._toolchainRoot)}assertCltVersion(e="26.0.0"){if(this._sourceType!=="clt")throw new Error("This operation requires Command Line Tools.");n.assertMinimumVersion(n.readCltVersion(this._toolchainRoot),"Command Line Tools","version.txt",e,this._toolchainRoot)}assertIdeVersion(e="6.0.0"){this.assertStudio(),n.assertMinimumVersion(ur(this._toolchainRoot),"DevEco Studio","product-info.json / Info.plist",e,this._toolchainRoot)}require(e){if(this._sourceType==="clt"){this.requireClt(e.clt);return}this.requireIde(e.studio)}requireClt(e){if(e===!1)throw new Error("This operation is not supported in Command Line Tools mode.");typeof e=="string"&&this.assertCltVersion(e)}requireIde(e){if(e===!1)throw new Error("This operation is not supported in DevEco Studio mode.");typeof e=="string"&&this.assertIdeVersion(e)}static assertMinimumVersion(e,t,r,i,o){if(!e)throw new S(`Failed to determine ${t} version from ${r} at ${o}`,`Failed to determine ${t} version from ${r}`);if(!/^\d+(?:\.\d+){1,3}$/.test(e))throw new S(`Invalid ${t} version "${e}" from ${r} at ${o}`,`Invalid ${t} version "${e}" from ${r}`);if(Cn(e,i)<0)throw new Error(`The detected ${t} version is ${e}, which is below the minimum required version ${i}. Upgrade before using deveco-cli:
|
|
15
|
+
${nl}`)}static resolveCodelinterPath(e,t){let r=n.buildToolPaths(e,t).codelinterCandidates,i=r.find(n.isFile);if(!i){let a=t==="studio"?"Code Linter not found in DevEco Studio.":"Code Linter not found in DevEco Command Line Tools.";throw new S(`${a}
|
|
16
16
|
Searched paths:
|
|
17
17
|
${r.join(`
|
|
18
|
-
`)}`,a)}let o=
|
|
19
|
-
`);for(let l of c){let d=l.trim();d&&/^\d+$/.test(d)&&a.push(Number(d))}e(a)})})}async function yp(n){let e=0,t=await He(n);t&&(e+=Number(t)*1024);let r=await vS(n);for(let i of r)e+=await yp(i);return e}function te(n){return`${(n/1024/1024).toFixed(2)}MB`}async function fp(n,e){if(!n)return process.memoryUsage().rss;if(e)return yp(n);let t=await He(n);return t?Number(t)*1024:0}function En(n,e=500,t=!1){let r=0,i=!1,o=setInterval(async()=>{if(i)return;let s=await fp(n,t);s>r&&(r=s)},e);return{stop:async()=>{i=!0,clearInterval(o);let s=await fp(n,t);return Math.max(r,s)}}}function wS(n){let e=n.trim().match(/^(\d+)$/);return e?e[1]:null}function SS(n){let e=n.match(/"([^"]+?)\s*K"/i);return e&&e[1].replace(/\D/g,"")||null}var Ke=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let i=dr.dirname(e.javaPath),o=`${i}${dr.delimiter}${process.env.PATH||""}`,s={...process.env,PATH:o,DEVECO_SDK_HOME:e.sdkPath},a=Yo.platform()==="darwin"&&e.javaPath==="/usr/bin/java";e.sourceType==="clt"&&e.javaPath&&!a&&(s.JAVA_HOME=dr.dirname(i)),this.env=s}async sync(e,t){let r=["--sync","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(r)}async buildProduct(e,t){let r=["assembleApp","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(r)}async buildModules(e,t,r,i){let o=[...Array.from(i),"--mode","module","-p",`module=${r.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(o)}async clean(){let e=["clean","--analyze=normal","--parallel","--no-daemon"];return this.runHvigor(e)}async stopDaemon(){return this.runHvigor(["--stop-daemon"])}async ensureDaemonRunning(){if(this.findProjectDaemon()){p("[HvigorAdapter] Daemon already running.");return}p("[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 vp.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(!Jo.existsSync(t))return null;try{let r=Jo.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||dr.join(Yo.homedir(),".hvigor");return dr.join(e,"daemon","cache","daemon-sec.json")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}async compileNative(e,t){let r=["--mode","module"];return t&&r.push("-p",`module=${t}`),r.push("-p",`product=${e}`,"compileNative","--analyze=normal"),this.runHvigor(r)}async runHvigor(e){let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];p(`Executing: ${t} ${r.join(" ")}`);let i=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit",o=bS(t,r,{cwd:this.projectRoot,env:this.env,stdout:i,stderr:i}),s=En(o.pid,500,!0),a="";try{await o}finally{let c=await s.stop();c>0&&(a=te(c),p(`Hvigor peak memory: ${a}`))}return a}};import{execa as ES}from"execa";var Pn=class{toolProvider;projectRoot;peakMemoryMb="";constructor(e,t){this.toolProvider=e,this.projectRoot=t}async installAll(){let e=this.toolProvider.nodePath,t=[this.toolProvider.ohpmJsPath,"install","--all"];p(`Executing: ${e} ${t.join(" ")}`);let r=ES(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"}),i=En(r.pid);try{await r}finally{let o=await i.stop();o>0&&(this.peakMemoryMb=te(o))}}};import{mkdir as PS}from"fs/promises";import{dirname as CS,resolve as kS}from"path";import{execa as IS}from"execa";import{lock as Uc,check as q_}from"proper-lockfile";function Bc(n){return kS(n,".hvigor",".build-lock")}function AS(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function wp(n){let e=CS(Bc(n));if(await PS(e,{recursive:!0}),process.platform==="win32")try{await IS("attrib",["+h",e])}catch{}}async function DS(n,e){let t=new AbortController,r=AS(e);await wp(n);let i={lockfilePath:Bc(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await Uc(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 Uc(n,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function Gr(n,e,t){let{release:r,signal:i}=await DS(n,t);try{return await e(i)}finally{await r()}}async function Ko(n,e){let t=new AbortController;await wp(n);let r={lockfilePath:Bc(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},i;try{i=await Uc(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()}}import*as ur from"fs";import*as qr from"path";import RS from"json5";var TS=1e3;function Zo(n){p(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=qr.join(n,xe.SYNC_OUTPUT_PATH);if(!ur.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return p(`[ProjectCheck] ${l.reason}`),l}let t=ur.statSync(e).mtimeMs;p(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=xS(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return p(`[ProjectCheck] ${l.reason}`),l}let i=qr.join(n,xe.OH_PACKAGE_JSON5),o=Xo(i,t,"root");if(o.required)return p(`[ProjectCheck] Root check: ${o.reason}`),o;let s=qr.join(n,xe.BUILD_PROFILE_JSON5),a=Xo(s,t,"build-profile");if(a.required)return p(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let d=qr.join(n,l.srcPath,xe.OH_PACKAGE_JSON5),g=Xo(d,t,l.name);if(g.required)return p(`[ProjectCheck] Module '${l.name}' check: ${g.reason}`),g;let y=qr.join(n,l.srcPath,xe.BUILD_PROFILE_JSON5),I=Xo(y,t,l.name);if(I.required)return p(`[ProjectCheck] Module '${l.name}' build-profile check: ${I.reason}`),I}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return p(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function Xo(n,e,t){if(!ur.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=ur.statSync(n).mtimeMs;return r-e>TS?{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 xS(n){let e=qr.join(n,xe.BUILD_PROFILE_JSON5);try{let t=ur.readFileSync(e,"utf-8");if(!t.trim())return null;let r=RS.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}}import*as W from"fs";import*as z from"path";import*as Sp from"util";var Wc="";function es(n){if(!n||n==="auto"||n==="stdout"||n==="none"){Wc="";return}Wc=n}function bp(){return Wc||(Gu()??"")}function Qo(n,...e){if(e.length===0)return n;try{return Sp.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var u={info(n,...e){h.info(`[lsp] ${Qo(n,...e)}`)},warn(n,...e){h.warn(`[lsp] ${Qo(n,...e)}`)},error(n,...e){h.error(`[lsp] ${Qo(n,...e)}`)},debug(n,...e){h.debug(`[lsp] ${Qo(n,...e)}`)}};import*as Pi from"fs";import*as Ci from"os";import*as Cn from"path";import LS from"json5";var v={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"},x="2.0",ts={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish"};var Ep=8192,Vc=100,Pp=.03,Cp=.7,Xe=900*1e3;function Ze(n){if(!Pi.existsSync(n))return null;try{let e=Pi.readFileSync(n,"utf-8");return e.trim()?LS.parse(e):null}catch{return null}}function rs(n,e){let t=Math.floor(Ci.totalmem()/1048576),r=Math.floor(t*Cp),i,o;e!==void 0&&Number.isFinite(e)&&e>0?(i=e,o=`override(${e})`):(i=Ep,n>Vc&&(i+=(n-Vc)*Pp*1024),o=`formula(moduleCount=${n})`);let s=r>0&&i>r;s&&(i=r);let a=Math.round(i);return u.info(`[computeLspServerMaxSize] source=${o}, physicalTotal=${t}MB, physicalCap(70%)=${r}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function vt(n){if(n.startsWith("file:"))return n;try{let e=Cn.resolve(n),t=new URL(`file://${e}`).toString();if(Ci.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 kn(n){return n&&n.replace(/\\/g,"/")}function de(n){let e=Cn.normalize(n).replace(/\\/g,"/");if(Ci.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function zr(n){return n||process.execPath||"node"}function ki(n){let e=de(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=${de(n.projectPath)}`),n.sdkPath&&t.push(`--sdkPath=${de(n.sdkPath)}`),t}function kp(n){return Cn.join(n,"build-profile.json5")}var Ht=class{constructor(e){this.projectRoot=e}getAllModuleInfo(){let e=kp(this.projectRoot);try{let t=Ze(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 u.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};import{spawn as NS}from"child_process";import*as is from"fs";var MS=600*1e3;function OS(n,e,t){let r=t.split(/\s+/).filter(i=>i.length>0);return[n,[e,...r]]}function _S(n){let e=[],t=[];return n.stdout?.on("data",r=>{e.push(r.toString())}),n.stderr?.on("data",r=>{let i=r.toString();t.push(i),i.split(/\r?\n/).filter(Boolean).forEach(o=>u.info("[hvigor:err] %s",o))}),{stdout:e,stderr:t}}function ns(n){return n.join("")}function FS(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
|
|
18
|
+
`)}`,a)}let o=pr(e),s=pr(i);return n.assertInsideRoot(s,o,"codelinter"),s}static isValidRoot(e,t){if(!n.isDirectory(e))return!1;if(t==="clt")return Ie.existsSync(A.join(e,"version.txt"));let r=Be.platform()==="darwin"?A.join(e,"Contents"):e,i=Be.platform()==="darwin"?A.join(r,"Info.plist"):A.join(r,"product-info.json");if(!Ie.existsSync(i))return!1;let o=n.buildToolPaths(e,"studio");return[o.nodePath,o.ohpmJsPath,o.hvigorJsPath].every(Ie.existsSync)}static buildToolPaths(e,t){return t==="clt"?n.buildCltToolPaths(e):n.buildStudioToolPaths(e)}static buildCltToolPaths(e){let t=Be.platform()==="win32",r=t?".exe":"",i=A.join(e,"sdk");return{nodePath:t?A.join(e,"tool","node","node.exe"):A.join(e,"tool","node","bin","node"),ohpmJsPath:A.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:A.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:i,hdcPath:A.join(i,"default","openharmony","toolchains",`hdc${r}`),emulatorPath:A.join(e,"emulator",t?"Emulator.exe":"Emulator"),clangdPath:n.clangdPathFor(i),arktsLangServerCandidates:[{root:A.join(e,"arkts-lsp","lib"),marker:A.join(e,"arkts-lsp","lib","out","index.js")}],codelinterCandidates:n.codelinterCandidatesFor(e,"clt")}}static buildStudioToolPaths(e){let t=Be.platform()==="darwin",r=Be.platform()==="win32",i=t?A.join(e,"Contents"):e,o=A.join(i,"tools"),s=A.join(i,"sdk"),a=r?".exe":"";return{nodePath:r?A.join(o,"node","node.exe"):A.join(o,"node","bin","node"),ohpmJsPath:A.join(o,"ohpm","bin","pm-cli.js"),hvigorJsPath:A.join(o,"hvigor","bin","hvigorw.js"),javaPath:r?A.join(e,"jbr","bin","java.exe"):t?A.join(i,"jbr","Contents","Home","bin","java"):A.join(i,"jbr","bin","java"),sdkPath:s,hdcPath:A.join(s,"default","openharmony","toolchains",`hdc${a}`),emulatorPath:A.join(o,"emulator",r?"Emulator.exe":"Emulator"),clangdPath:n.clangdPathFor(s),arktsLangServerCandidates:n.studioArktsLangServerCandidates(e),codelinterCandidates:n.codelinterCandidatesFor(e,"studio")}}static codelinterCandidatesFor(e,t){if(t==="clt")return[A.join(e,"codelinter","index.js"),A.join(e,"codelinter","run","index.js"),A.join(e,"tool","codelinter","bin","codelinter.js"),A.join(e,"tool","codelinter","codelinter.js")];let r=Be.platform()==="darwin"?["Contents"]:[];return[A.join(e,...r,"plugins","codelinter","run","index.js"),A.join(e,...r,"plugins","codelinter","index.js"),A.join(e,...r,"tools","codelinter","bin","codelinter.js"),A.join(e,...r,"tools","codelinter","codelinter.js")]}static studioArktsLangServerCandidates(e){if(Be.platform()==="linux")return[];let t=Be.platform()==="darwin"?["Contents"]:[],r=A.join(e,...t,"plugins","openharmony");return[{root:r,marker:A.join(r,"ace-server","out","index.js")}]}static clangdPathFor(e){return A.join(e,"default","openharmony","native","llvm","bin",Be.platform()==="win32"?"clangd.exe":"clangd")}static isFile(e){try{return Ie.statSync(e).isFile()}catch{return!1}}static isDirectory(e){try{return Ie.existsSync(e)&&Ie.statSync(e).isDirectory()}catch{return!1}}static resolveInstallSource(){return n.installSourcePromise||(n.installSourcePromise=n.resolveInstallSourceUncached()),n.installSourcePromise}static async resolveInstallSourceUncached(){let e=[["DEVECO_CLI_STUDIO_PATH","studio","studio"],["DEVECO_CLI_CLT_PATH","clt","clt"],["DEVECO_HOME","studio","studio"],["DEVECO_PATH","studio","studio"]];for(let[r,i,o]of e){let s=process.env[r]?.trim();if(s){let a=n.resolveExplicitRoot(s,i,r);return p(`[ToolProvider] Using ${r} \u2192 ${a}`),{sourceType:o,toolchainRoot:a}}}let t=await Lp();return p(`[ToolProvider] Using auto \u2192 ${t.root} (${t.version})`),{sourceType:"studio",toolchainRoot:t.root}}static resolveExplicitRoot(e,t,r){let i;try{i=is(e)}catch(o){throw new Error(`Invalid ${r}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}return t==="studio"&&Be.platform()==="darwin"&&(i=n.normalizeMacStudioRoot(i)),n.isValidRoot(i,t)?i:n.throwInvalidSource(i,t,r,e)}static assertBuiltPathsInsideRoot(e,t,r){let i=pr(e),o=[["node",t.nodePath],["ohpm",t.ohpmJsPath],["hvigor",t.hvigorJsPath],["sdk",t.sdkPath],["hdc",t.hdcPath],["emulator",t.emulatorPath]];r&&t.javaPath&&o.push(["java",t.javaPath]);for(let[s,a]of o)n.assertInsideRoot(a,i,s)}static assertInsideRoot(e,t,r){if(Mp(e,t)===null)throw new Error(`Unsafe toolchain path: ${r} resolves outside the toolchain root`)}static throwInvalidSource(e,t,r,i){throw t==="clt"&&n.isValidRoot(e,"studio")?new Error(`${r} must point to Command Line Tools, not a DevEco Studio installation; use DEVECO_CLI_STUDIO_PATH instead`):t==="studio"&&n.isValidRoot(e,"clt")?new Error(`${r} must point to a DevEco Studio installation, not Command Line Tools; use DEVECO_CLI_CLT_PATH instead`):new Error(`Invalid ${r}: ${i}`)}static normalizeMacStudioRoot(e){let t=`${A.sep}Contents`,r=A.normalize(e);return r.endsWith(t)?r.slice(0,-t.length):r}static readCltVersion(e){try{return Ie.readFileSync(A.join(e,"version.txt"),"utf-8").split(/\r?\n/).map(t=>t.match(zS)?.[1]?.trim()).find(Boolean)}catch{return}}static resolveCltJava(e){let t=process.env.JAVA_HOME?.trim(),i=[t&&(n.javaIn(A.join(t,"bin"))??n.javaIn(t)),...n.locateJavaFromPath()].filter(o=>!!o);if(!e)return i[0]?Ie.realpathSync(i[0]):"";for(let o of i)if(n.isUsableJava(o))return Ie.realpathSync(o);throw new Error("No Java runtime found in CLT mode. Set JAVA_HOME to a JDK/JBR installation directory (or point JAVA_HOME at the JDK bin directory), or add the JDK bin directory to PATH.")}static locateJavaFromPath(){let e=Be.platform()==="win32",t=e?"where.exe":"which",r=e?["java"]:["-a","java"];p(`Executing: ${t} ${r.join(" ")}`);let i=$p(t,r,{encoding:"utf8",stdio:"pipe",timeout:2e3,windowsHide:!0});return i.error||i.status!==0?[]:i.stdout.split(/\r?\n/).map(o=>o.trim()).filter(Boolean)}static javaIn(e){return(Be.platform()==="win32"?["java.exe","java.cmd"]:["java"]).map(r=>A.join(e,r)).find(Ie.existsSync)}static isUsableJava(e){let t=["-version"];p(`Executing: ${e} ${t.join(" ")}`);let r=$p(e,t,{encoding:"utf8",stdio:"pipe",timeout:2e3,windowsHide:!0});return!r.error&&r.status===0}getMaxApiLevel(){for(let e of KS(this.sdkPath)){let t=YS(e);if(t!==void 0)return t}return 23}getSdkPlatformVersion(){let e=A.join(this.sdkPath,"default","sdk-pkg.json"),t;try{t=JSON.parse(Ie.readFileSync(e,"utf8"))}catch(o){throw new Error(`Failed to read SDK metadata: ${e}`,{cause:o})}let r=t.data?.platformVersion,i=typeof r=="string"?r.trim():"";if(!i)throw new Error(`Missing data.platformVersion in SDK metadata: ${e}`);return i}detectApiLevel(){return this.getMaxApiLevel()}_apiscanPaths;getApiscanPaths(){if(this._apiscanPaths)return this._apiscanPaths;let e=Be.platform();if(e!=="darwin"&&e!=="win32")throw new Error(`Unsupported platform: ${e}. compat only supports macOS and Windows.`);if(!this._devecoStudioPath)throw new Error("DevEco Studio is required for compatibility checking. Set DEVECO_CLI_STUDIO_PATH or install DevEco Studio.");let t=e==="darwin"?"Contents":"",r=A.join(this._devecoStudioPath,t,"plugins","harmony","arkanalyzer-apiscan"),i=A.join(r,"resources","apiChange"),o=A.join(r,"api-change-scan.js");if(!Ie.existsSync(i)||!Ie.existsSync(o)){let s=ur(this._toolchainRoot)??"unknown";throw new Error(`A required component is missing. The detected DevEco Studio version is ${s}. The minimum required version is ${JS}. Upgrade before using 'check compat' at ${nl}`)}return this._apiscanPaths={apiChangeDir:i,scriptPath:o},this._apiscanPaths}};import{execa as db}from"execa";import*as Gp from"net";import*as fr from"path";import*as cs from"fs";import*as ls from"os";import{execFile as sl,spawn as jp}from"child_process";import{existsSync as XS,readdirSync as ZS,readFileSync as QS}from"fs";var as="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",il,ol="---MEMORY-SAMPLE-DELIMITER---";function Up(){return il===void 0&&(il=XS(as)),il}function Qe(n){return new Promise(e=>{let t=process.platform==="win32",r=t?"tasklist":"ps",i=t?["/fi",`PID eq ${n}`,"/fo","csv","/nh"]:["-o","rss=","-p",String(n)];p(`Executing: ${r} ${i.join(" ")}`),sl(r,i,{timeout:5e3,windowsHide:!0},(o,s)=>{if(o){e(null);return}e(t?lb(s):cb(s))})})}async function eb(){return process.platform==="linux"?ss():process.platform==="darwin"?tb():process.platform==="win32"?rb():[]}function ss(){let n=[],e;try{e=ZS("/proc")}catch{return n}for(let t of e){if(!/^\d+$/.test(t))continue;let r=Number(t);try{let i=QS(`/proc/${r}/status`,"utf8"),o=i.match(/VmRSS:\s+(\d+)\s+kB/),s=i.match(/^PPid:\s+(\d+)/m);if(!o||!s)continue;n.push({pid:r,ppid:Number(s[1]),rssBytes:Number(o[1])*1024})}catch{}}return n}function tb(){return new Promise(n=>{sl("ps",["-ax","-o","pid=,ppid=,rss="],{timeout:5e3,windowsHide:!0},(e,t)=>{if(e){n([]);return}n(Bp(t))})})}function Bp(n){let e=[];for(let t of n.trim().split(`
|
|
19
|
+
`)){let r=t.trim().split(/\s+/);if(r.length<3)continue;let i=Number(r[0]),o=Number(r[1]),s=Number(r[2]);isNaN(i)||isNaN(o)||isNaN(s)||e.push({pid:i,ppid:o,rssBytes:s*1024})}return e}function rb(){return new Promise(n=>{if(!Up()){n([]);return}sl(as,["-NoProfile","-Command",'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId),$($_.ParentProcessId),$($_.WorkingSetSize)" }'],{timeout:5e3,windowsHide:!0},(t,r)=>{if(t){n([]);return}n(Wp(r))})})}function Wp(n){let e=[];for(let t of n.trim().split(`
|
|
20
|
+
`)){let r=t.trim();if(!r)continue;let i=r.split(",");if(i.length<3)continue;let o=Number(i[0]),s=Number(i[1]),a=Number(i[2]);isNaN(o)||isNaN(s)||isNaN(a)||e.push({pid:o,ppid:s,rssBytes:a})}return e}function Vp(n,e){let t=new Map,r=new Map;for(let a of n){t.set(a.pid,a.rssBytes);let c=r.get(a.ppid);c?c.push(a.pid):r.set(a.ppid,[a.pid])}let i=0,o=new Set,s=[e];for(;s.length>0;){let a=s.shift();if(o.has(a))continue;o.add(a),i+=t.get(a)??0;let c=r.get(a);c&&s.push(...c)}return i}async function nb(n){let e=await eb();return Vp(e,n)}function ib(n){if(process.platform==="darwin"){let e=(n/1e3).toFixed(1),t=`while true; do ps -ax -o pid=,ppid=,rss=; echo '${ol}'; sleep ${e}; done`;return p(`Executing: sh -c ${t}`),jp("sh",["-c",t],{stdio:["ignore","pipe","ignore"],windowsHide:!0})}if(process.platform==="win32"&&Up()){let e=`while ($true) { Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId),$($_.ParentProcessId),$($_.WorkingSetSize)" }; Write-Output '${ol}'; Start-Sleep -Milliseconds ${n} }`;return p(`Executing: ${as} -NoProfile -Command ${e}`),jp(as,["-NoProfile","-Command",e],{stdio:["ignore","pipe","ignore"],windowsHide:!0})}return null}function te(n){return`${(n/1024/1024).toFixed(2)}MB`}async function Hp(n,e){if(!n)return process.memoryUsage().rss;if(e)return nb(n);let t=await Qe(n);return t?Number(t)*1024:0}function kn(n,e=500,t=!1){let r=0,i=!1,o=a=>{if(i||!n)return;let c=t?Vp(a,n):a.find(l=>l.pid===n)?.rssBytes??0;c>r&&(r=c)};if(!n)return sb(e);if(process.platform==="linux")return ab(e,o,()=>r);let s=ib(e);return s?(ob(s,o),{stop:async()=>{i=!0;try{s.kill()}catch{}let a=await Hp(n,t);return Math.max(r,a)}}):{stop:async()=>{i=!0;let a=await Hp(n,t);return Math.max(r,a)}}}function ob(n,e){let t=process.platform==="darwin"?Bp:Wp,r="";n.stdout?.on("data",i=>{r+=i.toString();let o=r.split(ol);r=o.pop()??"";for(let s of o)e(t(s))}),n.on("error",()=>{})}function sb(n){let e=process.memoryUsage().rss,t=setInterval(()=>{let r=process.memoryUsage().rss;r>e&&(e=r)},n);return{stop:async()=>(clearInterval(t),Math.max(e,process.memoryUsage().rss))}}function ab(n,e,t){e(ss());let r=setInterval(()=>e(ss()),n);return{stop:async()=>(clearInterval(r),e(ss()),t())}}function cb(n){let e=n.trim().match(/^(\d+)$/);return e?e[1]:null}function lb(n){let e=n.match(/"([^"]+?)\s*K"/i);return e&&e[1].replace(/\D/g,"")||null}var et=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let i=fr.dirname(e.javaPath),o=`${i}${fr.delimiter}${process.env.PATH||""}`,s={...process.env,PATH:o,DEVECO_SDK_HOME:e.sdkPath},a=ls.platform()==="darwin"&&e.javaPath==="/usr/bin/java";e.sourceType==="clt"&&e.javaPath&&!a&&(s.JAVA_HOME=fr.dirname(i)),this.env=s}async sync(e,t){let r=["--sync","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(r)}async buildProduct(e,t){let r=["assembleApp","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(r)}async buildModules(e,t,r,i){let o=[...Array.from(i),"--mode","module","-p",`module=${r.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(o)}async clean(){let e=["clean","--analyze=normal","--parallel","--no-daemon"];return this.runHvigor(e)}async stopDaemon(){return this.runHvigor(["--stop-daemon"])}async ensureDaemonRunning(){if(this.findProjectDaemon()){p("[HvigorAdapter] Daemon already running.");return}p("[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 Gp.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(!cs.existsSync(t))return null;try{let r=cs.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||fr.join(ls.homedir(),".hvigor");return fr.join(e,"daemon","cache","daemon-sec.json")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}async compileNative(e,t){let r=["--mode","module"];return t&&r.push("-p",`module=${t}`),r.push("-p",`product=${e}`,"compileNative","--analyze=normal"),this.runHvigor(r)}async runHvigor(e){let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];p(`Executing: ${t} ${r.join(" ")}`);let i=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit",o=db(t,r,{cwd:this.projectRoot,env:this.env,stdout:i,stderr:i}),s=je()?void 0:kn(o.pid,500,!0),a="";try{await o}finally{if(s){let c=await s.stop();c>0&&(a=te(c),p(`Hvigor peak memory: ${a}`))}}return a}};import{execa as ub}from"execa";var In=class{toolProvider;projectRoot;peakMemoryMb="";constructor(e,t){this.toolProvider=e,this.projectRoot=t}async installAll(){let e=this.toolProvider.nodePath,t=[this.toolProvider.ohpmJsPath,"install","--all"];p(`Executing: ${e} ${t.join(" ")}`);let r=ub(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"}),i=je()?void 0:kn(r.pid,500,!1);try{await r}finally{if(i){let o=await i.stop();o>0&&(this.peakMemoryMb=te(o))}}}};import{mkdir as pb}from"fs/promises";import{dirname as mb,resolve as fb}from"path";import{execa as hb}from"execa";import{lock as al,check as dF}from"proper-lockfile";function cl(n){return fb(n,".hvigor",".build-lock")}function gb(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function qp(n){let e=mb(cl(n));if(await pb(e,{recursive:!0}),process.platform==="win32")try{await hb("attrib",["+h",e])}catch{}}async function yb(n,e){let t=new AbortController,r=gb(e);await qp(n);let i={lockfilePath:cl(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await al(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 al(n,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function zr(n,e,t){let{release:r,signal:i}=await yb(n,t);try{return await e(i)}finally{await r()}}async function ds(n,e){let t=new AbortController;await qp(n);let r={lockfilePath:cl(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},i;try{i=await al(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()}}import*as hr from"fs";import*as Jr from"path";import vb from"json5";var wb=1e3;function ps(n){p(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=Jr.join(n,Le.SYNC_OUTPUT_PATH);if(!hr.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return p(`[ProjectCheck] ${l.reason}`),l}let t=hr.statSync(e).mtimeMs;p(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=Sb(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return p(`[ProjectCheck] ${l.reason}`),l}let i=Jr.join(n,Le.OH_PACKAGE_JSON5),o=us(i,t,"root");if(o.required)return p(`[ProjectCheck] Root check: ${o.reason}`),o;let s=Jr.join(n,Le.BUILD_PROFILE_JSON5),a=us(s,t,"build-profile");if(a.required)return p(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let d=Jr.join(n,l.srcPath,Le.OH_PACKAGE_JSON5),g=us(d,t,l.name);if(g.required)return p(`[ProjectCheck] Module '${l.name}' check: ${g.reason}`),g;let y=Jr.join(n,l.srcPath,Le.BUILD_PROFILE_JSON5),I=us(y,t,l.name);if(I.required)return p(`[ProjectCheck] Module '${l.name}' build-profile check: ${I.reason}`),I}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return p(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function us(n,e,t){if(!hr.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=hr.statSync(n).mtimeMs;return r-e>wb?{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 Sb(n){let e=Jr.join(n,Le.BUILD_PROFILE_JSON5);try{let t=hr.readFileSync(e,"utf-8");if(!t.trim())return null;let r=vb.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}}import*as W from"fs";import*as z from"path";import*as zp from"util";var ll="";function fs(n){if(!n||n==="auto"||n==="stdout"||n==="none"){ll="";return}ll=n}function Jp(){return ll||(yp()??"")}function ms(n,...e){if(e.length===0)return n;try{return zp.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var u={info(n,...e){h.info(`[lsp] ${ms(n,...e)}`)},warn(n,...e){h.warn(`[lsp] ${ms(n,...e)}`)},error(n,...e){h.error(`[lsp] ${ms(n,...e)}`)},debug(n,...e){h.debug(`[lsp] ${ms(n,...e)}`)}};import*as Ni from"fs";import*as Mi from"os";import*as An from"path";import bb from"json5";var v={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"},x="2.0",Dn={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate"};var Yp=8192,dl=100,Kp=.03,Xp=.7,We=900*1e3;function tt(n){if(!Ni.existsSync(n))return null;try{let e=Ni.readFileSync(n,"utf-8");return e.trim()?bb.parse(e):null}catch{return null}}function hs(n,e){let t=Math.floor(Mi.totalmem()/1048576),r=Math.floor(t*Xp),i,o;e!==void 0&&Number.isFinite(e)&&e>0?(i=e,o=`override(${e})`):(i=Yp,n>dl&&(i+=(n-dl)*Kp*1024),o=`formula(moduleCount=${n})`);let s=r>0&&i>r;s&&(i=r);let a=Math.round(i);return u.info(`[computeLspServerMaxSize] source=${o}, physicalTotal=${t}MB, physicalCap(70%)=${r}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function St(n){if(n.startsWith("file:"))return n;try{let e=An.resolve(n),t=new URL(`file://${e}`).toString();if(Mi.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 Rn(n){return n&&n.replace(/\\/g,"/")}function le(n){let e=An.normalize(n).replace(/\\/g,"/");if(Mi.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function Yr(n){return n||process.execPath||"node"}function Oi(n){let e=le(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=${le(n.projectPath)}`),n.sdkPath&&t.push(`--sdkPath=${le(n.sdkPath)}`),t}function Zp(n){return An.join(n,"build-profile.json5")}var Vt=class{constructor(e){this.projectRoot=e}getAllModuleInfo(){let e=Zp(this.projectRoot);try{let t=tt(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 u.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};import{spawn as Eb}from"child_process";import*as ys from"fs";var Pb=600*1e3;function Cb(n,e,t){let r=t.split(/\s+/).filter(i=>i.length>0);return[n,[e,...r]]}function kb(n,e){let t=[],r=[],i="",o="";return n.stdout?.on("data",s=>{let a=s.toString();t.push(a),i=Qp(i+a,e)}),n.stderr?.on("data",s=>{let a=s.toString();r.push(a),o=Qp(o+a,c=>{u.info("[hvigor:err] %s",c),e?.(c)})}),{stdout:t,stderr:r,flush:()=>{i&&e?.(i),o&&(u.info("[hvigor:err] %s",o),e?.(o))}}}function Qp(n,e){let t=n.split(/\r?\n/),r=t.pop()??"";for(let i of t)i&&e?.(i);return r}function gs(n){return n.join("")}function Ib(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
|
|
20
21
|
Output so far:
|
|
21
|
-
`+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function
|
|
22
|
-
`).trim();
|
|
22
|
+
`+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function Db(n,e,t,r){return new Promise(i=>{let o=Eb(n[0],n[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:s,stderr:a,flush:c}=kb(o,r),l=setTimeout(()=>{o.kill(),c();let d=[gs(s),gs(a)].filter(Boolean).join(`
|
|
23
|
+
`).trim();i({success:!1,output:`Build process timeout after 10 minutes.
|
|
23
24
|
Output so far:
|
|
24
|
-
`+
|
|
25
|
-
`).trim()||"";
|
|
26
|
-
[ohpm install] Running...`);try{await n.installAll()}catch(l){
|
|
27
|
-
[hvigor sync] Running...`);try{a=await e.sync(t,r)}catch(l){
|
|
25
|
+
`+d,exitCode:-1})},Pb);o.on("close",(d,g)=>{clearTimeout(l),c();let y=[gs(s),gs(a)].filter(Boolean).join(`
|
|
26
|
+
`).trim()||"";i(Ib(d,g,y))}),o.on("error",d=>{clearTimeout(l),i({success:!1,output:`Build execution exception: ${d.message}`,exitCode:-1})})})}async function ul(n,e,t,r,i,o){let s={...process.env,DEVECO_SDK_HOME:r},a=Cb(e,t,i);return await Db(a,n,s,o)}function Ab(n,e,t){return{node_path:e,hvigor_path:t,sdk_path:n}}function Rb(n){return!n.node_path||!ys.existsSync(n.node_path)?`Node path not found or invalid: ${n.node_path}`:!n.hvigor_path||!ys.existsSync(n.hvigor_path)?`Hvigor path not found or invalid: ${n.hvigor_path}`:!n.sdk_path||!ys.existsSync(n.sdk_path)?`SDK path not found or invalid: ${n.sdk_path}`:null}var Tb="--sync -p product=default --analyze=normal --parallel --incremental --no-daemon";async function em(n,e,t,r,i){try{let o=Ab(e,t,r),s=Rb(o);if(s!=null)return u.info(`Config validation failed: ${s}`),!1;let a=await ul(n,o.node_path,o.hvigor_path,e,Tb,i);return u.info(`[hvigor] sync finished: success=${a.success}, exitCode=${a.exitCode}`),a.success}catch(o){return u.info(`syncProject failed: ${JSON.stringify(o)}`),!1}}function xb(n){let e=z.extname(n).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh"].includes(e)}function Lb(n,e){let t=z.join(n,e.name);return e.isDirectory()?e.name===".cxx"||rm(t):xb(t)}function rm(n){if(!W.existsSync(n))return!1;try{return W.readdirSync(n,{withFileTypes:!0}).some(t=>Lb(n,t))}catch{}return!1}function gr(n){try{let t=new Vt(n).getAllModuleInfo(),r=[];for(let i of t){let o=z.resolve(n,i.srcPath);rm(o)&&r.push(i)}return r}catch(e){throw h.error(`[CppCompile] findCppModules threw: ${e instanceof Error?e.message:String(e)}`),e}}function Nb(n){let e=[],r=new Vt(n).getAllModuleInfo();for(let i of r){let o=z.resolve(n,i.srcPath),s=z.join(o,".cxx");W.existsSync(s)&&nm(s,e)}return e}function nm(n,e){try{let t=W.readdirSync(n,{withFileTypes:!0});for(let r of t){let i=z.join(n,r.name);r.isDirectory()?nm(i,e):r.name==="compile_commands.json"&&e.push(i)}}catch{}}function Mb(n){let e=[];for(let t of n)try{let r=W.readFileSync(t,"utf8"),i=JSON.parse(r);e.push(...i)}catch{}return e}function Ob(n,e){let t=z.join(n,..._b.slice(0,-1));W.mkdirSync(t,{recursive:!0});let r=z.join(t,"compile_commands.json");W.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function pl(n){let e=Nb(n);if(e.length>0){let t=Mb(e);Ob(n,t),h.info(`[CppCompile] compile_commands.json generated, ${t.length} compile commands`)}else h.warn("[CppCompile] No compile_commands.json files found")}var _b=[".idea",".deveco","cxx","compile_commands.json"];async function Fb(n,e,t,r,i){if(!r){h.warn(`[CppCompile] hvigorw.js path not injected (sdk '${e}')`);return}h.info(`[CppCompile] sdkPath: ${e}, hvigorPath: ${r}`);for(let o of i){let s=o.name;try{E.assertModuleName(s)}catch{h.warn(`[CppCompile] Skipping module with invalid name: ${s}`);continue}let a=["--mode","module","-p",`module=${o.name}`,"-p","product=default","compileNative","--analyze=normal","--parallel","--incremental","--no-daemon"].join(" ");h.info(`[CppCompile] Running compileNative for module: ${o.name}`);let c=await ul(n,t,r,e,a);c.success?h.info(`[CppCompile] compileNative ${o.name} succeeded`):h.warn(`[CppCompile] compileNative ${o.name} failed: ${c.output}`)}}async function im(n,e,t,r){let i=gr(n);if(i.length===0){h.info("[CppCompile] No C++ modules found, skipping initialization");return}h.info(`[CppCompile] Found ${i.length} C++ module(s): ${i.map(o=>o.name).join(", ")}`),await Fb(n,e,t,r,i),pl(n),Vb(n,i)}function vs(n){let e=n?.trim()??"";if(!e)return null;let t=z.resolve(e);try{if(!W.existsSync(t)||!W.statSync(t).isFile())return h.warn(`[CppCompile] Custom compile_commands.json not found: ${t}, falling back to default sync`),null;let r=JSON.parse(W.readFileSync(t,"utf8"));if(!Array.isArray(r))return h.warn(`[CppCompile] Custom compile_commands.json is not a JSON array: ${t}, falling back to default sync`),null}catch(r){return h.warn(`[CppCompile] Failed to read custom compile_commands.json (${t}): ${r}, falling back to default sync`),null}return z.dirname(t)}var $b=1e3,jb=["src","main","cpp","CMakeLists.txt"],Hb=new Set([".cxx","build","node_modules",".preview",".hvigor",".idea"]),Ub=new Set(["c","cpp","cxx","cc"]),Bb="cpp-source-manifest.json";function Wb(n){let e=z.extname(n).replace(/^\./,"").toLowerCase();return Ub.has(e)}function tm(n,e){return W.existsSync(n)?W.statSync(n).mtimeMs-e>$b:!1}function om(n){return z.join(z.dirname(Vr(n)),Bb)}function sm(n,e,t){let r;try{r=W.readdirSync(n,{withFileTypes:!0})}catch{return}for(let i of r){let o=z.join(n,i.name);if(i.isDirectory()){if(Hb.has(i.name))continue;sm(o,e,t)}else Wb(i.name)&&t.push(z.relative(e,o).replace(/\\/g,"/"))}}function am(n,e){let t=[];for(let r of e){let i=z.resolve(n,r.srcPath);sm(i,n,t)}return t.sort()}function Vb(n,e){let t=am(n,e),r={files:t,updatedAt:Date.now()},i=om(n);try{W.mkdirSync(z.dirname(i),{recursive:!0}),W.writeFileSync(i,JSON.stringify(r,null,2),"utf8"),h.info(`[CppCompile] C++ source manifest written, ${t.length} files`)}catch(o){h.warn(`[CppCompile] Failed to write C++ source manifest: ${o}`)}}function Gb(n,e){let t=om(n);if(!W.existsSync(t))return{required:!0,reason:"C++ source manifest not found, needs initialization"};let r;try{let o=JSON.parse(W.readFileSync(t,"utf8"));r=Array.isArray(o.files)?o.files:[]}catch{return{required:!0,reason:"C++ source manifest corrupted, needs initialization"}}let i=am(n,e);return i.length!==r.length||i.some((o,s)=>o!==r[s])?{required:!0,reason:`C++ source file set changed (recorded=${r.length}, actual=${i.length})`}:null}function cm(n){let e=Vr(n);if(!W.existsSync(e))return{required:!0,reason:"C++ baseline (compile_commands.json) not found, needs initialization"};let t=W.statSync(e).mtimeMs,r=gr(n);if(r.length===0)return{required:!1,reason:"no C++ modules, skip compileNative"};for(let o of r){let s=z.resolve(n,o.srcPath);if(tm(z.join(s,"build-profile.json5"),t))return{required:!0,reason:`module '${o.name}': build-profile.json5 newer than baseline`};let a=z.join(s,...jb);if(tm(a,t))return{required:!0,reason:`module '${o.name}': CMakeLists.txt newer than baseline`}}let i=Gb(n,r);return i||{required:!1,reason:`C++ project up-to-date (baseline: ${new Date(t).toISOString()})`}}function zb(n,e){if(e.product&&n.validateProduct(e.product),e.buildMode){let t=["debug","release"],r=(n.profile.app.buildModeSet?.map(o=>o.name)??[]).filter(o=>!t.includes(o)),i=[...t,...r];if(!i.includes(e.buildMode))throw new Error(`Build mode '${e.buildMode}' not found. Available modes: ${i.join(", ")}`)}}function Jb(n,e){let t=n.profile.modules.map(i=>i.name),r=new Set(t);for(let i of e){let o=i.split("@",1)[0];if(!r.has(o))throw new Error(`Module '${o}' not found in project-level build-profile.json5. Available modules: ${t.join(", ")||"none"}`)}}function Yb(n,e){let t;if(e.modules&&e.modules.length>0)t=e.modules,Jb(n,t);else{let i=n.profile.modules,o=i.filter(s=>n.getModuleType(s.name)==="entry");if(i.length===1)t=[i[0].name];else if(o.length===1)t=[o[0].name];else throw o.length>1?new S(`Multiple entry modules found (${o.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`,"Multiple entry modules found."):new S(`No entry module found and multiple modules available (${i.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`,"No entry module found and multiple modules available.")}let r=new Set;for(let i of t){let o=i.indexOf("@"),s=o!==-1?i.substring(0,o):i,a=o!==-1?i.substring(o+1):"default";r.add(`${s}@${a}`)}return Array.from(r)}function hl(n,e){let t=new Set;for(let r of e){let i=r.indexOf("@"),o=i!==-1?r.substring(0,i):r,s=n.getModuleType(o);s==="shared"?t.add("assembleHsp"):s==="har"?t.add("assembleHar"):t.add("assembleHap")}return t}function _i(n,e){let t=e,r=`${n} failed`;console.error(lm(r));let i=t.stdout||t.message;throw i&&console.error(i),t.stderr&&console.error(t.stderr),new Error(r,{cause:e})}async function gl(n,e,t,r,i,o){let s=ps(o);console.log(`
|
|
27
|
+
[ohpm install] Running...`);try{await n.installAll()}catch(l){_i("ohpm install",l)}let a="";if(s.required){console.log(`
|
|
28
|
+
[hvigor sync] Running...`);try{a=await e.sync(t,r)}catch(l){_i("hvigor sync",l)}}else console.log(`
|
|
28
29
|
[hvigor sync] Skipped (configurations unchanged)`);console.log(`
|
|
29
|
-
[hvigor build] Running...`);let c="";try{i.type==="product"?c=await e.buildProduct(t,r):c=await e.buildModules(t,r,i.modulesToBuild,i.moduleTasks)}catch(l){
|
|
30
|
-
Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(
|
|
31
|
-
Failed to merge compile_commands.json: ${e.message}`))}}async function
|
|
32
|
-
`+
|
|
33
|
-
[1/2] Running hvigor clean...`);try{await r.clean()}catch(i){
|
|
34
|
-
[2/2] Running hvigor --stop-daemon...`);try{await r.stopDaemon()}catch(i){
|
|
35
|
-
`+
|
|
30
|
+
[hvigor build] Running...`);let c="";try{i.type==="product"?c=await e.buildProduct(t,r):c=await e.buildModules(t,r,i.modulesToBuild,i.moduleTasks)}catch(l){_i("hvigor build",l)}return Kb(o),{ohpmMemoryMb:n.peakMemoryMb,syncMemoryMb:a,buildMemoryMb:c}}function Kb(n){try{if(gr(n).length===0)return;pl(n),console.log(ml(`
|
|
31
|
+
Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(fl(`
|
|
32
|
+
Failed to merge compile_commands.json: ${e.message}`))}}async function dm(n,e){let t=Date.now(),r=!0,i=null;try{await e()}catch(o){r=!1,i=B(o),console.error(lm(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await k.track(n,o)}}function Xb(n){let e={event:b.CommandExecuted,args:["build",...n.product?["--product"]:[],...n.modules?["--modules"]:[],...n.buildMode?["--build-mode"]:[]]};return n.buildMode&&(e.build_mode=n.buildMode),n.modules&&(e.module_count=n.modules.length),e}function Zb(){return{event:b.CommandExecuted,args:["build","clean"]}}async function Qb(n){let e=process.cwd(),t=q.discover(e);console.warn(fl("Ensure the project source is trustworthy before proceeding."));let r=await C.new();r.assertJava(),zb(t,n);let i=n.product||"default",o=n.buildMode||"debug",s;if(n.product&&!n.modules)s={type:"product"};else{let d=Yb(t,n),g=hl(t,d);s={type:"modules",modulesToBuild:d,moduleTasks:g}}let a=new In(r,t.rootDir),c=new et(r,t.rootDir),l=await zr(t.rootDir,async()=>gl(a,c,i,o,s,t.rootDir),()=>{console.log("Another build is already running for this project. Waiting for completion...")});return console.log(`
|
|
33
|
+
`+ml("Build completed successfully")),{bundleName:t.getBundleName(),ohpmMemoryMb:l.ohpmMemoryMb,syncMemoryMb:l.syncMemoryMb,buildMemoryMb:l.buildMemoryMb}}async function eE(){let n=process.cwd(),e=q.discover(n);console.warn(fl("Ensure the project source is trusted before proceeding."));let t=await C.new();t.assertJava();let r=new et(t,e.rootDir);return await zr(e.rootDir,async()=>{console.log(`
|
|
34
|
+
[1/2] Running hvigor clean...`);try{await r.clean()}catch(i){_i("hvigor clean",i)}console.log(`
|
|
35
|
+
[2/2] Running hvigor --stop-daemon...`);try{await r.stopDaemon()}catch(i){_i("hvigor --stop-daemon",i)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
|
|
36
|
+
`+ml("Clean completed successfully.")),e.getBundleName()}var um=new qb("build").description("Build HarmonyOS project").option("--product <product>","Product name defined in build-profile.json5 (default: default)").option("--modules <modules...>","Modules to build (format: module or module@target)").option("--build-mode <mode>","Build mode (buildModeSet in build-profile.json5; e.g. debug, release; default: debug)").action(async n=>{let e=Xb(n);await dm(e,async()=>{let t=await Qb(n);e.bundle_name=t.bundleName,t.ohpmMemoryMb&&(e.ohpm_install_memory=t.ohpmMemoryMb),t.syncMemoryMb&&(e.hvigor_sync_memory=t.syncMemoryMb),t.buildMemoryMb&&(e.hvigor_build_memory=t.buildMemoryMb)})});um.command("clean").description("Clean HarmonyOS project build outputs").action(async()=>{let n=Zb();await dm(n,async()=>{n.bundle_name=await eE()})});var pm=um;import{Command as tC}from"commander";import{green as Yi,red as rC,yellow as Bs}from"colorette";import*as Ki from"path";import{randomUUID as fE}from"crypto";import{execa as Sm}from"execa";import{execa as mE}from"execa";import{execFile as tE,spawn as rE}from"child_process";import{promisify as nE}from"util";var iE=nE(tE);function mm(n,e,t){let i=n.replace(/\r\n/g,`
|
|
36
37
|
`).split(`
|
|
37
|
-
`),o=i.pop()??"",s=i.map(a=>a.endsWith("\r")?a.slice(0,-1):a).filter(a=>a.length>0);return s.length>0&&t.onData(s,e),o}function
|
|
38
|
-
`)){let i=r.trim();if(!i||i.startsWith("[Empty]"))continue;let o=i.split(/\s+/),s=o[0];if(!s||s.startsWith("[Empty]"))continue;let a=o.length>=2?o[1]:"device";if(a.toLowerCase()==="unauthorized"){p(`[DeviceManager] Skipping unauthorized device: ${s}`);continue}t.push({serial:s,status:a})}return t}extractDisplayName(e){let t=e.get("ohos.qemu.hvd.name");if(t)return t;let r=e.get("const.product.name");if(r&&r!=="emulator")return r;let i=e.get("const.product.model");if(i&&i!=="emulator"){let s=e.get("const.product.brand");return this.stripBrandPrefix(i,s)}let o=e.get("const.build.product");if(o&&o!=="emulator")return o}async getDeviceName(e){let t=await
|
|
38
|
+
`),o=i.pop()??"",s=i.map(a=>a.endsWith("\r")?a.slice(0,-1):a).filter(a=>a.length>0);return s.length>0&&t.onData(s,e),o}function fm(n,e,t){let r=n.endsWith("\r")?n.slice(0,-1):n;r.length>0&&t.onData([r],e)}function oE(n,e){return{stdout:n.stdoutChunks.join(""),stderr:n.stderrChunks.join(""),exitCode:e??-1}}function sE(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function aE(n,e,t,r,i){n.stdout?.on("data",o=>{let s=o.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=mm(e.stdoutLineBuffer+s,"stdout",t)}),n.stderr?.on("data",o=>{let s=o.toString();e.stderrChunks.push(s),e.stderrLineBuffer=mm(e.stderrLineBuffer+s,"stderr",t)}),n.on("error",o=>{e.settled||(e.settled=!0,t.onError(o),i(o))}),n.on("close",o=>{if(e.settled)return;e.settled=!0,fm(e.stdoutLineBuffer,"stdout",t),fm(e.stderrLineBuffer,"stderr",t),t.onClose(o);let s=oE(e,o);r(s)})}async function Fi(n,e=[],t={}){try{let{stdout:r,stderr:i}=await iE(n,e,t);return{stdout:typeof r=="string"?r.trim():"",stderr:typeof i=="string"?i.trim():"",exitCode:0}}catch(r){let i=r;return{stdout:i.stdout?.trim()||"",stderr:i.stderr?.trim()??i.message,exitCode:typeof i.code=="number"?i.code:1}}}async function hm(n,e,t){return await new Promise((r,i)=>{let o=rE(n,e,{stdio:["inherit","pipe","pipe"]}),s=sE();aE(o,s,t,r,i)})}function gm(n){let e=n.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var cE=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],lE=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function bt(n){return n?cE.some(e=>e.test(n))?"transient":lE.some(e=>e.test(n))?"fatal":"ok":"ok"}var dE=/(?:^|\s)(\d{2,})(?:\s|$)/;function ym(n){let e=n.stdout.trim(),t=n.stderr.trim();return bt(e)!=="ok"||bt(t)!=="ok"?"query-failed":n.exitCode===0?e&&dE.test(e)?"alive":"dead":n.exitCode===1&&!e&&!t?"dead":"query-failed"}var yl=[800,1500,2500];function uE(n){return new Promise(e=>setTimeout(e,n))}async function re(n,e){let t=1+yl.length,r={stdout:"",stderr:"",exitCode:-1};for(let i=0;i<t;i++){if(r=await Fi(n,e),r.exitCode===0||bt(r.stderr)!=="transient"||i>=t-1)return r;p(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${yl[i]}ms`),await uE(yl[i])}return r}var vm=/^[\w.-]+$/;async function ws(n,e,t){if(!vm.test(t)){p(`Skipping invalid param key: ${JSON.stringify(t)}`);return}let r=["-t",e,"shell","param","get",t];p(`Executing: ${n} ${r.join(" ")}`);let i=await re(n,r);if(i.exitCode!==0)return;let o=i.stdout.trim();if(!(!o||bt(o)!=="ok"))return gm(o)}var vl="__DEVECO_PARAM_DELIM__";function pE(n,e){let t=new Map,r=n.split(vl);for(let i=0;i<e.length;i++){let o=(r[i]??"").trim();if(!o||bt(o)!=="ok")continue;let s=gm(o);s&&t.set(e[i],s)}return t}async function Tn(n,e,t){let r=t.filter(a=>vm.test(a)?!0:(p(`Skipping invalid param key: ${JSON.stringify(a)}`),!1));if(r.length===0)return new Map;if(r.length===1){let a=new Map,c=await ws(n,e,r[0]);return c&&a.set(r[0],c),a}let i=r.map(a=>`param get ${a}`).join(`; echo ${vl}; `)+`; echo ${vl}`,o=await re(n,["-t",e,"shell",i]);if(o.exitCode===0){let a=pE(o.stdout,r);if(a.size>0)return a}p(`Batched param fetch failed (exit=${o.exitCode}), falling back to individual calls for ${e}`);let s=new Map;for(let a of r){let c=await ws(n,e,a);c&&s.set(a,c)}return s}function Ot(n){return n.startsWith("127.0.0.1:")}var wm=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],ne=class n{hdcPath;constructor(e){this.hdcPath=e}static from(e){return new n(e.hdcPath)}static withHdcPath(e){return new n(e)}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}stripBrandPrefix(e,t){let r=e.trim(),i=t?.trim();if(!r||!i)return r;let o=new RegExp(`^${this.escapeRegExp(i)}(\\s+|[-_]+)?`,"i");return r.replace(o,"").trim()||r}async executeHdc(e){return p(`Executing: ${this.hdcPath} ${e.join(" ")}`),mE(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let r of e.split(`
|
|
39
|
+
`)){let i=r.trim();if(!i||i.startsWith("[Empty]"))continue;let o=i.split(/\s+/),s=o[0];if(!s||s.startsWith("[Empty]"))continue;let a=o.length>=2?o[1]:"device";if(a.toLowerCase()==="unauthorized"){p(`[DeviceManager] Skipping unauthorized device: ${s}`);continue}t.push({serial:s,status:a})}return t}extractDisplayName(e){let t=e.get("ohos.qemu.hvd.name");if(t)return t;let r=e.get("const.product.name");if(r&&r!=="emulator")return r;let i=e.get("const.product.model");if(i&&i!=="emulator"){let s=e.get("const.product.brand");return this.stripBrandPrefix(i,s)}let o=e.get("const.build.product");if(o&&o!=="emulator")return o}async getDeviceName(e){let t=await Tn(this.hdcPath,e,[...wm]);return this.extractDisplayName(t)??e}async getDeviceInfo(e,t){if(e.length===0)return null;if(t){let r=e.find(s=>s.serial===t);if(r)return r;let i=t.toLowerCase(),o=[];for(let s of e){let a=await this.getDeviceName(s.serial);a.toLowerCase()===i&&o.push({device:s,name:a})}if(o.length===1)return o[0].device;throw o.length>1?new S(`Multiple devices match "${t}". Use a serial instead:
|
|
39
40
|
`+o.map(s=>` - ${s.name} (${s.device.serial})`).join(`
|
|
40
|
-
`),"Multiple devices match."):new S(`Device "${t}" not found. Use \`devecocli device list\` to see available targets.`,"Device not found.")}return e[0]}async getDeviceDetail(e){let t={serial:e,status:"device"};try{let r=await In(this.hdcPath,e,["const.product.devicetype","const.ohos.apiversion","const.ohos.releasetype"]);t.deviceType=r.get("const.product.devicetype");let i=r.get("const.ohos.apiversion"),o=r.get("const.ohos.releasetype");i&&(t.osVersion=o?`API ${i} (${o})`:`API ${i}`)}catch{}return t}async listDevicesWithName(){let e=await this.listDevices();return Promise.all(e.map(async t=>({serial:t.serial,name:await this.getDeviceName(t.serial)})))}async getConnectedEntries(){let e=await this.listDevices();return Promise.all(e.map(t=>this.buildConnectedEntry(t.serial)))}async buildConnectedEntry(e){let t=xt(e),r,i;try{let o=await In(this.hdcPath,e,[...Gp]);r=this.extractDisplayName(o),i=o.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:i}}};var Qe=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=ne.from(e)}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;p(`Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await qp(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}async listTargets(){return(await this.deviceManager.listDevicesWithName()).map(t=>({name:t.name,id:t.serial}))}async uninstallApp(e,t){E.assertBundleNameStrict(t);let r=await this.runHdc(["-t",e,"shell","bm","uninstall","-n",t],!1);if(r.includes("uninstall bundle successfully"))return!0;if(r.includes("uninstall missing installed bundle"))return!1;throw new Error(`Uninstall failed: ${r}`)}async installApp(e,t){if(t.length===0)return;let i=`/data/local/tmp/${kb()}`;try{await this.runHdc(["-t",e,"shell","mkdir",i]);for(let s of t){let a=await this.runHdc(["-t",e,"file","send",s,i+"/"]);if(!a.startsWith("FileTransfer finish"))throw new Error(a)}let o=await this.runHdc(["-t",e,"shell","bm","install","-p",i]);if(!o.includes("install bundle successfully."))throw new Error(o);console.log("App installed successfully")}finally{await this.runHdc(["-t",e,"shell","rm","-rf",i],!1)}}async launchApp(e,t,r){E.assertBundleNameStrict(t),E.assertAbilityName(r);let i=["-t",e,"shell","aa","start","-a",r,"-b",t];return await this.runHdc(i)}async pidofBundle(e,t){E.assertBundleNameStrict(t);let r=["-t",e,"shell","pidof",t],i=this.toolProvider.hdcPath;p(`Executing: ${i} ${r.join(" ")}`);let o=await re(i,r),s=Wp(o);if(s==="query-failed"){let a=[o.stdout,o.stderr].map(c=>c.trim()).filter(Boolean).join(" ");throw new Error(`pidof query failed for '${t}': ${a||`exit ${o.exitCode}`}`)}return s==="alive"}async forceStopApp(e,t){E.assertBundleNameStrict(t);let r=["-t",e,"shell","aa","force-stop",t];return await this.runHdc(r,!1)}async transferFile(e,t,r,i){let o=["-t",e,"file",t,r,i],s=await this.runHdc(o,!1);if(!s.includes("FileTransfer finish"))throw new Error(`File ${t} failed: ${s.trim()||"hdc returned no output"}`);return s.trim()}async runSqlite3(e,t,r=[]){let i=["-t",e,"shell","sqlite3",t,...r];await qp(this.toolProvider.hdcPath,i,{stdio:"inherit",env:{...process.env}})}};import Qc from"fs";import*as Jr from"path";function Di(n,e){if(!Qc.existsSync(n))throw new Error(`Apply file list not found: ${n}`);let r=Qc.readFileSync(n,"utf-8").split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0&&!a.startsWith("#"));if(r.length===0)throw new Error("Apply file list is empty (no valid entries)");let i=Jr.resolve(e),o=new Set,s=[];for(let a of r){let c=Jr.resolve(i,a),l=Jr.isAbsolute(a)?Jr.relative(i,a):a;if(l.startsWith(".."))throw new Error(`File path is outside the project directory: ${a}`);let d=E.isPathContainedWithSymlink(l,i);if(!d.contained){if(!Qc.existsSync(c))throw new Error(`File not found: ${a}`);let g=d.reason?`; ${d.reason}`:"";throw new Error(`File path is outside the project directory: ${a}${g}`)}o.has(c)||(o.add(c),s.push(c))}return s}import el from"fs";import Ri from"path";import{execa as Db}from"execa";import zp from"fs";import*as Jp from"path";import Ib from"json5";function Ab(n,e){try{let r=Ib.parse(zp.readFileSync(n,"utf-8")).modules?.find(i=>i.name===e);return r?.srcPath?r.srcPath.replace(/^\.\//,""):null}catch(t){return p(`[apply] resolveModuleSrcPath fallback (module=${e}): ${t.message}`),null}}function Lt(n,e){let t=Jp.join(n,"build-profile.json5");return zp.existsSync(t)?Ab(t,e)??e:e}async function Yp(n,e,t,r){let i=Ri.dirname(n.javaPath),o={...process.env,PATH:`${i}${Ri.delimiter}${process.env.PATH||""}`,DEVECO_SDK_HOME:n.sdkPath},s=[n.hvigorJsPath,"--mode","module","-p",`module=${t.join(",")}@${r}`,"-p",`product=${r}`,"-p","debuggable=true","assembleDevHqf","--analyze=normal","--parallel","--incremental","--no-daemon"];p(`[buildSignedHqf] ${n.nodePath} ${s.join(" ")}`);let a=await Db(n.nodePath,s,{cwd:e,env:o,stdout:"inherit",stderr:"inherit",reject:!1}),c=(a.exitCode??0)|0;if(c===-1)throw new Error("hvigor hot compile produced invalid abc (exit code -1)");if(c!==0)throw new Error(`hvigor assembleDevHqf failed with exit code ${a.exitCode}`);return t.map(l=>Tb(e,l,r))}function Kp(n,e,t){let r=Lt(n,e);return Ri.join(n,r,"build",t,"outputs")}function Rb(n,e,t){return Ri.join(Kp(n,e,t),`${e}-${t}-signed.hqf`)}function Tb(n,e,t){let r=Kp(n,e,t),i=Rb(n,e,t);if(el.existsSync(i))return i;let o=tl(r,"-signed.hqf")??tl(r,".hqf");if(!o)throw new Error(`Signed hqf not found at ${i} (and no *.hqf under ${r})`);return p(`[buildSignedHqf] signed hqf not at exact path, using fallback: ${o}`),o}function tl(n,e){if(!el.existsSync(n))return null;for(let t of el.readdirSync(n,{withFileTypes:!0})){let r=Ri.join(n,t.name);if(t.isDirectory()){let i=tl(r,e);if(i)return i}else if(t.isFile()&&t.name.endsWith(e))return r}return null}import ie from"fs";import*as M from"path";import rl from"json5";var Xp="default",An=class n{static writeChangedFileLists(e,t,r,i){let o=t||Xp,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||Xp,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=M.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=M.join(e,r,"build",t,"intermediates","patch","default"),s=M.join(o,"changedFileList.json");if(ie.existsSync(s)||(ie.mkdirSync(o,{recursive:!0}),ie.writeFileSync(s,JSON.stringify({resources:{resFile:[],rawFile:[]},modifiedFiles:[]}),"utf-8")),!i)return;let a=M.join(e,r,"build",t,"intermediates","hotReload"),c=M.join(a,"changedFileList.json");ie.existsSync(c)||(ie.mkdirSync(a,{recursive:!0}),ie.writeFileSync(c,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=M.join(e,"build-profile.json5");if(!ie.existsSync(t))return null;try{let r=ie.readFileSync(t,"utf-8");return rl.parse(r)}catch{return null}}static classifyFile(e,t,r){let i=M.extname(e).toLowerCase();if(i===".ets"||i===".ts")return{fileClass:"ets_ts",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""};if(i===".cpp"||i===".cc"||i===".c"||i===".h"||i===".hpp")return{fileClass:"native",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""};let o=e.replace(/\\/g,"/");return o.includes("/resources/rawfile/")?{fileClass:"raw_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:o.includes("/resources/resfile/")?{fileClass:"res_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:{fileClass:"unknown",moduleSrcPath:""}}static findModuleByFilePath(e,t,r){let i=M.normalize(e);for(let o of r){let s=M.normalize(M.join(t,o.srcPath)),a=s+M.sep;if(i.startsWith(a)||i===s)return o}return null}static getModuleType(e,t){let r=M.join(e,t,"src","main","module.json5");if(!ie.existsSync(r))return"entry";try{let i=ie.readFileSync(r,"utf-8");return rl.parse(i)?.module?.type||"entry"}catch{return"entry"}}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=M.join(e,t,"oh-package.json5");if(!ie.existsSync(r))return[];try{let i=ie.readFileSync(r,"utf-8"),o=rl.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=n.tryResolveDepModule(e,t,a,o);c&&s.push(c)}return s}static tryResolveDepModule(e,t,r,i){let o=r;if(!(o.startsWith("file:")||o.startsWith(".")||o.startsWith("..")))return null;o.startsWith("file:")&&(o=o.substring(5));let a=M.resolve(e,t,o);return i.find(l=>M.resolve(e,l.srcPath)===a)?.name??null}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=M.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=M.join(e,o,"build",r,"intermediates","hotReload","changedFileList.json"),a=n.readExistingApply(s),c=n.mergeApplyEntries(a,i),l=M.dirname(s);ie.existsSync(l)||ie.mkdirSync(l,{recursive:!0}),ie.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),p(`[ChangedFileListWriter] Written hotReload: ${s} (${c.length} entries)`)}static readExistingApply(e){if(!ie.existsSync(e))return[];try{let t=ie.readFileSync(e,"utf-8");return JSON.parse(t)?.modifiedFilesV2||[]}catch{return[]}}static writePatchFile(e,t,r,i,o,s){let a=t.replace(/^\.\//,""),c=M.join(e,a,"build",r,"intermediates","patch","default","changedFileList.json"),l=n.readExistingPatch(c),d=M.join(e,a,"src","main","ets"),g=i.map(Te=>n.resolveRelativePathForPatch(Te,d)),y=n.mergeStrings(l.modifiedFiles,g),I=n.mergePatchResources(l.rawFile,o),le=n.mergePatchResources(l.resFile,s),G=M.dirname(c);ie.existsSync(G)||ie.mkdirSync(G,{recursive:!0}),ie.writeFileSync(c,JSON.stringify({resources:{resFile:le,rawFile:I},modifiedFiles:y}),"utf-8"),p(`[ChangedFileListWriter] Written patch: ${c}`)}static readExistingPatch(e){if(!ie.existsSync(e))return{modifiedFiles:[],rawFile:[],resFile:[]};try{let t=ie.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 M.relative(M.normalize(t),M.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}};import xb from"fs";import{randomUUID as Lb}from"crypto";import{execa as Nb}from"execa";var Dn=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,r){for(let a of t)if(!xb.existsSync(a)){let c=`Signed hqf file not found: ${a}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}E.assertBundleName(r);let o=`/data/local/tmp/${Lb()}`,s=[];try{for(let a=0;a<t.length;a++){let c=`${o}/${r}_${a}.hqf`;s.push(c),await this.pushHqf(e,t[a],o,c)}return await this.executeQuickfix(e,s)}catch(a){let c=`hqf install error: ${a.message}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}finally{await this.runHdc(["-t",e,"shell","rm","-rf",o],!1)}}async pushHqf(e,t,r,i){console.log(`[Apply] Pushing hqf to device ${e}: ${t}`),await this.runHdc(["-t",e,"shell","mkdir","-p",r]);let o=await this.runHdc(["-t",e,"file","send",t,i]);if(!o.startsWith("FileTransfer finish"))throw new Error(`Failed to send hqf: ${o}`)}async executeQuickfix(e,t){console.log(`[Apply] Installing ${t.length} hqf patch(es) via quickfix...`);let r=["-t",e,"shell","bm","quickfix","-a","-f",...t,"-d"];await this.getApiVersion(e)>17&&r.push("-o");let o=await this.runHdc(r,!1);if(p(`[InstallHqf] quickfix output: ${o}`),/succe(?:ed|ss)/i.test(o))return console.log("[Apply] hqf installed successfully."),{success:!0,message:"hqf quickfix installed successfully."};let s=`hqf quickfix install failed. Device response: ${o||"(empty)"}. Please try reinstalling the application.`;return console.error(`[Apply] ${s}`),{success:!1,message:s}}async getApiVersion(e){try{let t=await this.runHdc(["-t",e,"shell","param","get","const.ohos.apiversion"],!1),r=parseInt(t.trim(),10);if(!isNaN(r))return console.log(`[InstallHqf] device API version: ${r}`),r}catch{}return 0}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;p(`[InstallHqf] Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await Nb(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}};var Mb="6.1.1",as=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}async execute(e){await Gr(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion(Mb);let t=Di(e.applyFile,this.projectRoot);console.log(`[Apply] Parsed ${t.length} changed file(s)`);let r=this.writeChangeFileList(e,t);await this.stopApp(e);let i=await this.buildHqf(e,r);await this.installHqf(e,i),await this.launchApp(e),console.log("[Apply] Apply complete")}writeChangeFileList(e,t){let r=An.writeChangedFileLists(this.projectRoot,e.productName,t);if(r.writtenModules.length===0)throw new Error("No changed files belong to a runnable module");return console.log(`[Apply] changeFileList written for: ${r.writtenModules.join(", ")}`),r.writtenModules}async buildHqf(e,t){return p(`[Apply] hvigor assembleDevHqf --no-daemon (modules=${t.join(",")})`),await Yp(this.toolProvider,this.projectRoot,t,e.productName)}async installHqf(e,t){console.log(`[Apply] Installing ${t.length} hqf(s) to ${e.targetDeviceId}`);let i=await new Dn(this.toolProvider).install(e.targetDeviceId,t,e.bundleName);if(!i.success)throw new Error(`hqf install failed: ${i.message}`);console.log("[Apply] hqf installed")}async stopApp(e){let t=new Qe(this.toolProvider);try{await t.forceStopApp(e.targetDeviceId,e.bundleName),console.log("[Apply] app stopped")}catch(r){console.warn(`[Apply] stop app failed: ${r.message}`)}}async launchApp(e){let t=new Qe(this.toolProvider);try{await t.launchApp(e.targetDeviceId,e.bundleName,e.abilityName),console.log("[Apply] app launched")}catch(r){throw new Error(`[Apply] launch app failed: ${r.message}`,{cause:r})}}};import nl from"fs";import*as H from"path";var cs=class n{static generate(e,t,r,i){let o=Lt(e,t),s=H.join(e,o),a=H.join(s,"build","config"),c=n.buildConfig(e,s,r,i);nl.mkdirSync(a,{recursive:!0}),nl.writeFileSync(H.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),p(`[BuildConfigManager] buildConfig.json written to ${a}`);let l=H.join(s,"build",r,"intermediates","loader_out",r,"ets");nl.mkdirSync(l,{recursive:!0})}static buildConfig(e,t,r,i){let o=H.dirname(i.nodePath)+H.sep,s=H.join(t,"build",r),a=H.join(s,"intermediates"),c=H.join(a,"loader_out",r),l=H.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:o,projectProfilePath:H.join(e,"build-profile.json5"),localPropertiesPath:H.join(e,"local.properties"),appResource:H.join(l,"ResourceTable.txt"),cachePath:H.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:H.join(a,"loader",r,"loader.json"),aceModuleJsonPath:H.join(l,"module.json"),aceSoPath:H.join(c,"nativeDependencies.txt"),aceModuleRoot:H.join(t,"src","main","ets"),aceModuleBuild:H.join(c,"ets"),aceProfilePath:H.join(l,"resources","base","profile"),aceSuperVisualPath:H.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"false",mode:"hotReload",oldMapFilePath:H.join(c,"ets"),changedFileList:H.join(a,"patch",r,"changedFileList.json"),patchAbcPath:H.join(a,"patch",r,"ets"),removeChangedFileListInSdk:"true"}}}};import Zp from"fs";import*as V from"path";var ls=class n{static generate(e,t,r,i){let o=Lt(e,t),s=V.join(e,o),a=V.join(s,"build","config"),c=n.buildConfig(e,s,r,i);Zp.mkdirSync(a,{recursive:!0}),Zp.writeFileSync(V.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),p(`[HotReloadBuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,i){let o=V.dirname(i.nodePath)+V.sep,s=V.join(t,"build",r),a=V.join(s,"intermediates"),c=V.join(a,"loader_out",r),l=V.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:o,projectProfilePath:V.join(e,"build-profile.json5"),localPropertiesPath:V.join(e,"local.properties"),appResource:V.join(l,"ResourceTable.txt"),cachePath:V.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:V.join(a,"loader",r,"loader.json"),aceModuleJsonPath:V.join(l,"module.json"),aceSoPath:V.join(c,"nativeDependencies.txt"),aceModuleRoot:V.join(t,"src","main","ets"),aceModuleBuild:V.join(c,"ets"),aceProfilePath:V.join(l,"resources","base","profile"),aceSuperVisualPath:V.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:V.join(c,"ets"),changedFileList:V.join(a,"hotReload","changedFileList.json"),patchAbcPath:V.join(a,"hotReload","patchAbcPath","ets"),removeChangedFileListInSdk:"true"}}}};import Qp from"crypto";import at from"fs";import ct from"path";import em from"os";import{io as Ob}from"socket.io-client";var _b=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Rn=class n{projectRoot;toolProvider;cachedSocket=null;cachedDaemonPort=0;constructor(e,t){this.projectRoot=e,this.toolProvider=t}async sendHotCompile(e){await this.waitForDaemonReady();let t=this.findProjectDaemon();if(!t?.sessionId)throw new Error("No running hvigor daemon with sessionId found. Run `devecocli run --hotreload` first.");return this.sendViaSocket(t,e)}async startWatchSession(e){await this.waitForDaemonReady(),console.log(`[DaemonClient] Compiling, build with: ${JSON.stringify(e)}`);let t=this.findProjectDaemon();if(!t?.sessionId)throw new Error("No running hvigor daemon with sessionId found. Build the hap first.");let r=await this.getOrCreateSocket(t),i=this.watchLogPath;at.mkdirSync(ct.dirname(i),{recursive:!0}),at.writeFileSync(i,"");let o=this.createWatchLogBuffer(i);r.on("WatchLog",o.onWatchLog),r.on("WatchResult",o.onWatchResult),await this.awaitInitialBuild(r,e)}createWatchLogBuffer(e){let r=[];return{onWatchLog:s=>{let a=n.extractText(s);a.trim()&&(r.push(a.endsWith(`
|
|
41
|
+
`),"Multiple devices match."):new S(`Device "${t}" not found. Use \`devecocli device list\` to see available targets.`,"Device not found.")}return e[0]}async getDeviceDetail(e){let t={serial:e,status:"device"};try{let r=await Tn(this.hdcPath,e,["const.product.devicetype","const.ohos.apiversion","const.ohos.releasetype"]);t.deviceType=r.get("const.product.devicetype");let i=r.get("const.ohos.apiversion"),o=r.get("const.ohos.releasetype");i&&(t.osVersion=o?`API ${i} (${o})`:`API ${i}`)}catch{}return t}async listDevicesWithName(){let e=await this.listDevices();return Promise.all(e.map(async t=>({serial:t.serial,name:await this.getDeviceName(t.serial)})))}async getConnectedEntries(){let e=await this.listDevices();return Promise.all(e.map(t=>this.buildConnectedEntry(t.serial)))}async buildConnectedEntry(e){let t=Ot(e),r,i;try{let o=await Tn(this.hdcPath,e,[...wm]);r=this.extractDisplayName(o),i=o.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:i}}};var rt=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=ne.from(e)}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;p(`Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await Sm(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}async listTargets(){return(await this.deviceManager.listDevicesWithName()).map(t=>({name:t.name,id:t.serial}))}async uninstallApp(e,t){E.assertBundleNameStrict(t);let r=await this.runHdc(["-t",e,"shell","bm","uninstall","-n",t],!1);if(r.includes("uninstall bundle successfully"))return!0;if(r.includes("uninstall missing installed bundle"))return!1;throw new Error(`Uninstall failed: ${r}`)}async installApp(e,t){if(t.length===0)return;let i=`/data/local/tmp/${fE()}`;try{await this.runHdc(["-t",e,"shell","mkdir",i]);for(let s of t){let a=await this.runHdc(["-t",e,"file","send",s,i+"/"]);if(!a.startsWith("FileTransfer finish"))throw new Error(a)}let o=await this.runHdc(["-t",e,"shell","bm","install","-p",i]);if(!o.includes("install bundle successfully."))throw new Error(o);console.log("App installed successfully")}finally{await this.runHdc(["-t",e,"shell","rm","-rf",i],!1)}}async launchApp(e,t,r){E.assertBundleNameStrict(t),E.assertAbilityName(r);let i=["-t",e,"shell","aa","start","-a",r,"-b",t];return await this.runHdc(i)}async pidofBundle(e,t){E.assertBundleNameStrict(t);let r=["-t",e,"shell","pidof",t],i=this.toolProvider.hdcPath;p(`Executing: ${i} ${r.join(" ")}`);let o=await re(i,r),s=ym(o);if(s==="query-failed"){let a=[o.stdout,o.stderr].map(c=>c.trim()).filter(Boolean).join(" ");throw new Error(`pidof query failed for '${t}': ${a||`exit ${o.exitCode}`}`)}return s==="alive"}async forceStopApp(e,t){E.assertBundleNameStrict(t);let r=["-t",e,"shell","aa","force-stop",t];return await this.runHdc(r,!1)}async transferFile(e,t,r,i){let o=["-t",e,"file",t,r,i],s=await this.runHdc(o,!1);if(!s.includes("FileTransfer finish"))throw new Error(`File ${t} failed: ${s.trim()||"hdc returned no output"}`);return s.trim()}async runSqlite3(e,t,r=[]){let i=["-t",e,"shell","sqlite3",t,...r];await Sm(this.toolProvider.hdcPath,i,{stdio:"inherit",env:{...process.env}})}};import wl from"fs";import*as Kr from"path";function $i(n,e){if(!wl.existsSync(n))throw new Error(`Apply file list not found: ${n}`);let r=wl.readFileSync(n,"utf-8").split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0&&!a.startsWith("#"));if(r.length===0)throw new Error("Apply file list is empty (no valid entries)");let i=Kr.resolve(e),o=new Set,s=[];for(let a of r){let c=Kr.resolve(i,a),l=Kr.isAbsolute(a)?Kr.relative(i,a):a;if(l.startsWith(".."))throw new Error(`File path is outside the project directory: ${a}`);let d=E.isPathContainedWithSymlink(l,i);if(!d.contained){if(!wl.existsSync(c))throw new Error(`File not found: ${a}`);let g=d.reason?`; ${d.reason}`:"";throw new Error(`File path is outside the project directory: ${a}${g}`)}o.has(c)||(o.add(c),s.push(c))}return s}import Sl from"fs";import ji from"path";import{execa as yE}from"execa";import bm from"fs";import*as Em from"path";import hE from"json5";function gE(n,e){try{let r=hE.parse(bm.readFileSync(n,"utf-8")).modules?.find(i=>i.name===e);return r?.srcPath?r.srcPath.replace(/^\.\//,""):null}catch(t){return p(`[apply] resolveModuleSrcPath fallback (module=${e}): ${t.message}`),null}}function _t(n,e){let t=Em.join(n,"build-profile.json5");return bm.existsSync(t)?gE(t,e)??e:e}async function Pm(n,e,t,r){let i=ji.dirname(n.javaPath),o={...process.env,PATH:`${i}${ji.delimiter}${process.env.PATH||""}`,DEVECO_SDK_HOME:n.sdkPath},s=[n.hvigorJsPath,"--mode","module","-p",`module=${t.join(",")}@${r}`,"-p",`product=${r}`,"-p","debuggable=true","assembleDevHqf","--analyze=normal","--parallel","--incremental","--no-daemon"];p(`[buildSignedHqf] ${n.nodePath} ${s.join(" ")}`);let a=await yE(n.nodePath,s,{cwd:e,env:o,stdout:"inherit",stderr:"inherit",reject:!1}),c=(a.exitCode??0)|0;if(c===-1)throw new Error("hvigor hot compile produced invalid abc (exit code -1)");if(c!==0)throw new Error(`hvigor assembleDevHqf failed with exit code ${a.exitCode}`);return t.map(l=>wE(e,l,r))}function Cm(n,e,t){let r=_t(n,e);return ji.join(n,r,"build",t,"outputs")}function vE(n,e,t){return ji.join(Cm(n,e,t),`${e}-${t}-signed.hqf`)}function wE(n,e,t){let r=Cm(n,e,t),i=vE(n,e,t);if(Sl.existsSync(i))return i;let o=bl(r,"-signed.hqf")??bl(r,".hqf");if(!o)throw new Error(`Signed hqf not found at ${i} (and no *.hqf under ${r})`);return p(`[buildSignedHqf] signed hqf not at exact path, using fallback: ${o}`),o}function bl(n,e){if(!Sl.existsSync(n))return null;for(let t of Sl.readdirSync(n,{withFileTypes:!0})){let r=ji.join(n,t.name);if(t.isDirectory()){let i=bl(r,e);if(i)return i}else if(t.isFile()&&t.name.endsWith(e))return r}return null}import ie from"fs";import*as M from"path";import El from"json5";var km="default",xn=class n{static writeChangedFileLists(e,t,r,i){let o=t||km,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||km,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=M.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=M.join(e,r,"build",t,"intermediates","patch","default"),s=M.join(o,"changedFileList.json");if(ie.existsSync(s)||(ie.mkdirSync(o,{recursive:!0}),ie.writeFileSync(s,JSON.stringify({resources:{resFile:[],rawFile:[]},modifiedFiles:[]}),"utf-8")),!i)return;let a=M.join(e,r,"build",t,"intermediates","hotReload"),c=M.join(a,"changedFileList.json");ie.existsSync(c)||(ie.mkdirSync(a,{recursive:!0}),ie.writeFileSync(c,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=M.join(e,"build-profile.json5");if(!ie.existsSync(t))return null;try{let r=ie.readFileSync(t,"utf-8");return El.parse(r)}catch{return null}}static classifyFile(e,t,r){let i=M.extname(e).toLowerCase();if(i===".ets"||i===".ts")return{fileClass:"ets_ts",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""};if(i===".cpp"||i===".cc"||i===".c"||i===".h"||i===".hpp")return{fileClass:"native",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""};let o=e.replace(/\\/g,"/");return o.includes("/resources/rawfile/")?{fileClass:"raw_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:o.includes("/resources/resfile/")?{fileClass:"res_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:{fileClass:"unknown",moduleSrcPath:""}}static findModuleByFilePath(e,t,r){let i=M.normalize(e);for(let o of r){let s=M.normalize(M.join(t,o.srcPath)),a=s+M.sep;if(i.startsWith(a)||i===s)return o}return null}static getModuleType(e,t){let r=M.join(e,t,"src","main","module.json5");if(!ie.existsSync(r))return"entry";try{let i=ie.readFileSync(r,"utf-8");return El.parse(i)?.module?.type||"entry"}catch{return"entry"}}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=M.join(e,t,"oh-package.json5");if(!ie.existsSync(r))return[];try{let i=ie.readFileSync(r,"utf-8"),o=El.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=n.tryResolveDepModule(e,t,a,o);c&&s.push(c)}return s}static tryResolveDepModule(e,t,r,i){let o=r;if(!(o.startsWith("file:")||o.startsWith(".")||o.startsWith("..")))return null;o.startsWith("file:")&&(o=o.substring(5));let a=M.resolve(e,t,o);return i.find(l=>M.resolve(e,l.srcPath)===a)?.name??null}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=M.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=M.join(e,o,"build",r,"intermediates","hotReload","changedFileList.json"),a=n.readExistingApply(s),c=n.mergeApplyEntries(a,i),l=M.dirname(s);ie.existsSync(l)||ie.mkdirSync(l,{recursive:!0}),ie.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),p(`[ChangedFileListWriter] Written hotReload: ${s} (${c.length} entries)`)}static readExistingApply(e){if(!ie.existsSync(e))return[];try{let t=ie.readFileSync(e,"utf-8");return JSON.parse(t)?.modifiedFilesV2||[]}catch{return[]}}static writePatchFile(e,t,r,i,o,s){let a=t.replace(/^\.\//,""),c=M.join(e,a,"build",r,"intermediates","patch","default","changedFileList.json"),l=n.readExistingPatch(c),d=M.join(e,a,"src","main","ets"),g=i.map(xe=>n.resolveRelativePathForPatch(xe,d)),y=n.mergeStrings(l.modifiedFiles,g),I=n.mergePatchResources(l.rawFile,o),ce=n.mergePatchResources(l.resFile,s),G=M.dirname(c);ie.existsSync(G)||ie.mkdirSync(G,{recursive:!0}),ie.writeFileSync(c,JSON.stringify({resources:{resFile:ce,rawFile:I},modifiedFiles:y}),"utf-8"),p(`[ChangedFileListWriter] Written patch: ${c}`)}static readExistingPatch(e){if(!ie.existsSync(e))return{modifiedFiles:[],rawFile:[],resFile:[]};try{let t=ie.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 M.relative(M.normalize(t),M.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}};import SE from"fs";import{randomUUID as bE}from"crypto";import{execa as EE}from"execa";var Ln=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,r){for(let a of t)if(!SE.existsSync(a)){let c=`Signed hqf file not found: ${a}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}E.assertBundleName(r);let o=`/data/local/tmp/${bE()}`,s=[];try{for(let a=0;a<t.length;a++){let c=`${o}/${r}_${a}.hqf`;s.push(c),await this.pushHqf(e,t[a],o,c)}return await this.executeQuickfix(e,s)}catch(a){let c=`hqf install error: ${a.message}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}finally{await this.runHdc(["-t",e,"shell","rm","-rf",o],!1)}}async pushHqf(e,t,r,i){console.log(`[Apply] Pushing hqf to device ${e}: ${t}`),await this.runHdc(["-t",e,"shell","mkdir","-p",r]);let o=await this.runHdc(["-t",e,"file","send",t,i]);if(!o.startsWith("FileTransfer finish"))throw new Error(`Failed to send hqf: ${o}`)}async executeQuickfix(e,t){console.log(`[Apply] Installing ${t.length} hqf patch(es) via quickfix...`);let r=["-t",e,"shell","bm","quickfix","-a","-f",...t,"-d"];await this.getApiVersion(e)>17&&r.push("-o");let o=await this.runHdc(r,!1);if(p(`[InstallHqf] quickfix output: ${o}`),/succe(?:ed|ss)/i.test(o))return console.log("[Apply] hqf installed successfully."),{success:!0,message:"hqf quickfix installed successfully."};let s=`hqf quickfix install failed. Device response: ${o||"(empty)"}. Please try reinstalling the application.`;return console.error(`[Apply] ${s}`),{success:!1,message:s}}async getApiVersion(e){try{let t=await this.runHdc(["-t",e,"shell","param","get","const.ohos.apiversion"],!1),r=parseInt(t.trim(),10);if(!isNaN(r))return console.log(`[InstallHqf] device API version: ${r}`),r}catch{}return 0}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;p(`[InstallHqf] Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await EE(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}};var PE="6.1.1",Ss=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}async execute(e){await zr(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion(PE);let t=$i(e.applyFile,this.projectRoot);console.log(`[Apply] Parsed ${t.length} changed file(s)`);let r=this.writeChangeFileList(e,t);await this.stopApp(e);let i=await this.buildHqf(e,r);await this.installHqf(e,i),await this.launchApp(e),console.log("[Apply] Apply complete")}writeChangeFileList(e,t){let r=xn.writeChangedFileLists(this.projectRoot,e.productName,t);if(r.writtenModules.length===0)throw new Error("No changed files belong to a runnable module");return console.log(`[Apply] changeFileList written for: ${r.writtenModules.join(", ")}`),r.writtenModules}async buildHqf(e,t){return p(`[Apply] hvigor assembleDevHqf --no-daemon (modules=${t.join(",")})`),await Pm(this.toolProvider,this.projectRoot,t,e.productName)}async installHqf(e,t){console.log(`[Apply] Installing ${t.length} hqf(s) to ${e.targetDeviceId}`);let i=await new Ln(this.toolProvider).install(e.targetDeviceId,t,e.bundleName);if(!i.success)throw new Error(`hqf install failed: ${i.message}`);console.log("[Apply] hqf installed")}async stopApp(e){let t=new rt(this.toolProvider);try{await t.forceStopApp(e.targetDeviceId,e.bundleName),console.log("[Apply] app stopped")}catch(r){console.warn(`[Apply] stop app failed: ${r.message}`)}}async launchApp(e){let t=new rt(this.toolProvider);try{await t.launchApp(e.targetDeviceId,e.bundleName,e.abilityName),console.log("[Apply] app launched")}catch(r){throw new Error(`[Apply] launch app failed: ${r.message}`,{cause:r})}}};import Pl from"fs";import*as U from"path";var bs=class n{static generate(e,t,r,i){let o=_t(e,t),s=U.join(e,o),a=U.join(s,"build","config"),c=n.buildConfig(e,s,r,i);Pl.mkdirSync(a,{recursive:!0}),Pl.writeFileSync(U.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),p(`[BuildConfigManager] buildConfig.json written to ${a}`);let l=U.join(s,"build",r,"intermediates","loader_out",r,"ets");Pl.mkdirSync(l,{recursive:!0})}static buildConfig(e,t,r,i){let o=U.dirname(i.nodePath)+U.sep,s=U.join(t,"build",r),a=U.join(s,"intermediates"),c=U.join(a,"loader_out",r),l=U.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:o,projectProfilePath:U.join(e,"build-profile.json5"),localPropertiesPath:U.join(e,"local.properties"),appResource:U.join(l,"ResourceTable.txt"),cachePath:U.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:U.join(a,"loader",r,"loader.json"),aceModuleJsonPath:U.join(l,"module.json"),aceSoPath:U.join(c,"nativeDependencies.txt"),aceModuleRoot:U.join(t,"src","main","ets"),aceModuleBuild:U.join(c,"ets"),aceProfilePath:U.join(l,"resources","base","profile"),aceSuperVisualPath:U.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"false",mode:"hotReload",oldMapFilePath:U.join(c,"ets"),changedFileList:U.join(a,"patch",r,"changedFileList.json"),patchAbcPath:U.join(a,"patch",r,"ets"),removeChangedFileListInSdk:"true"}}}};import Im from"fs";import*as V from"path";var Es=class n{static generate(e,t,r,i){let o=_t(e,t),s=V.join(e,o),a=V.join(s,"build","config"),c=n.buildConfig(e,s,r,i);Im.mkdirSync(a,{recursive:!0}),Im.writeFileSync(V.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),p(`[HotReloadBuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,i){let o=V.dirname(i.nodePath)+V.sep,s=V.join(t,"build",r),a=V.join(s,"intermediates"),c=V.join(a,"loader_out",r),l=V.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:o,projectProfilePath:V.join(e,"build-profile.json5"),localPropertiesPath:V.join(e,"local.properties"),appResource:V.join(l,"ResourceTable.txt"),cachePath:V.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:V.join(a,"loader",r,"loader.json"),aceModuleJsonPath:V.join(l,"module.json"),aceSoPath:V.join(c,"nativeDependencies.txt"),aceModuleRoot:V.join(t,"src","main","ets"),aceModuleBuild:V.join(c,"ets"),aceProfilePath:V.join(l,"resources","base","profile"),aceSuperVisualPath:V.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:V.join(c,"ets"),changedFileList:V.join(a,"hotReload","changedFileList.json"),patchAbcPath:V.join(a,"hotReload","patchAbcPath","ets"),removeChangedFileListInSdk:"true"}}}};import Dm from"crypto";import dt from"fs";import ut from"path";import Am from"os";import{io as CE}from"socket.io-client";var kE=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Nn=class n{projectRoot;toolProvider;cachedSocket=null;cachedDaemonPort=0;constructor(e,t){this.projectRoot=e,this.toolProvider=t}async sendHotCompile(e){await this.waitForDaemonReady();let t=this.findProjectDaemon();if(!t?.sessionId)throw new Error("No running hvigor daemon with sessionId found. Run `devecocli run --hotreload` first.");return this.sendViaSocket(t,e)}async startWatchSession(e){await this.waitForDaemonReady(),console.log(`[DaemonClient] Compiling, build with: ${JSON.stringify(e)}`);let t=this.findProjectDaemon();if(!t?.sessionId)throw new Error("No running hvigor daemon with sessionId found. Build the hap first.");let r=await this.getOrCreateSocket(t),i=this.watchLogPath;dt.mkdirSync(ut.dirname(i),{recursive:!0}),dt.writeFileSync(i,"");let o=this.createWatchLogBuffer(i);r.on("WatchLog",o.onWatchLog),r.on("WatchResult",o.onWatchResult),await this.awaitInitialBuild(r,e)}createWatchLogBuffer(e){let r=[];return{onWatchLog:s=>{let a=n.extractText(s);a.trim()&&(r.push(a.endsWith(`
|
|
41
42
|
`)?a:a+`
|
|
42
|
-
`),r.length>100&&r.shift())},onWatchResult:s=>{let a=n.extractText(s);if(!a.trim())return;let c=`[WatchResult] ${a}`;console.log(c),
|
|
43
|
-
`].join("")),r.length=0}}}awaitInitialBuild(e,t){return new Promise((r,i)=>{let o=!1,s=this.createOutputHandler(),a=l=>{!l?.status||o||(l.status==="finish"?(o=!0,e.off("disconnect",c),e.off("Output",s),e.off("BuildStatus",a),r()):(l.status==="reject"||l.status==="close")&&(o=!0,e.off("disconnect",c),e.off("Output",s),e.off("BuildStatus",a),this.invalidateSocket(),i(new Error(l.reason||`Watch-session build ${l.status}`))))},c=l=>{o||(o=!0,i(new Error(`Socket disconnected: ${l}`)))};e.on("disconnect",c),e.on("Output",s),e.on("BuildStatus",a),e.emit("CommonBuild",this.buildStartOptions(t)),console.log("[DaemonClient] Compiling, waiting for build to finish...")})}getWatchLogPath(){return this.watchLogPath}get watchLogPath(){return
|
|
43
|
+
`),r.length>100&&r.shift())},onWatchResult:s=>{let a=n.extractText(s);if(!a.trim())return;let c=`[WatchResult] ${a}`;console.log(c),dt.writeFileSync(e,[...r,c+`
|
|
44
|
+
`].join("")),r.length=0}}}awaitInitialBuild(e,t){return new Promise((r,i)=>{let o=!1,s=this.createOutputHandler(),a=l=>{!l?.status||o||(l.status==="finish"?(o=!0,e.off("disconnect",c),e.off("Output",s),e.off("BuildStatus",a),r()):(l.status==="reject"||l.status==="close")&&(o=!0,e.off("disconnect",c),e.off("Output",s),e.off("BuildStatus",a),this.invalidateSocket(),i(new Error(l.reason||`Watch-session build ${l.status}`))))},c=l=>{o||(o=!0,i(new Error(`Socket disconnected: ${l}`)))};e.on("disconnect",c),e.on("Output",s),e.on("BuildStatus",a),e.emit("CommonBuild",this.buildStartOptions(t)),console.log("[DaemonClient] Compiling, waiting for build to finish...")})}getWatchLogPath(){return this.watchLogPath}get watchLogPath(){return ut.join(this.projectRoot,".hvigor","hotreload-watch.log")}buildStartOptions(e){let t={_:["assembleHap"],daemon:!0,watch:!0,hotReloadBuild:!0,mode:"module",prop:[`module=${e.moduleSpecs.join(",")}`,`product=${e.productName}`,"debuggable=true","hotReload=true","requiredDeviceType=phone"],parallel:!0,incremental:!0,analyze:"normal",env:{DEVECO_SDK_HOME:this.toolProvider.sdkPath}};return console.log("[DaemonClient] buildStartOptions:",JSON.stringify(t,null,2)),t}disconnect(){this.invalidateSocket()}onSocketDisconnect(e){this.cachedSocket&&this.cachedSocket.on("disconnect",e)}async getOrCreateSocket(e){if(this.cachedSocket&&this.cachedDaemonPort===e.port){if(this.cachedSocket.connected)return this.cachedSocket;this.invalidateSocket()}let t=this.decryptSessionId(e.sessionId);console.log(`[DaemonClient] Socket.IO connect: ws://127.0.0.1:${e.port} (${e.state})`);let r=CE(`ws://127.0.0.1:${e.port}`,{transports:["websocket"],path:`/${t}`});return await new Promise((i,o)=>{let s=setTimeout(()=>{o(new Error("Socket connect timeout (10s)"))},1e4);r.once("connect",()=>{clearTimeout(s),i()}),r.once("connect_error",a=>{clearTimeout(s),o(new Error(`Socket connect error: ${a.message}`))})}),this.cachedSocket=r,this.cachedDaemonPort=e.port,r}invalidateSocket(){this.cachedSocket&&(this.cachedSocket.removeAllListeners(),this.cachedSocket.disconnect(),this.cachedSocket=null,this.cachedDaemonPort=0)}async sendViaSocket(e,t){let r=await this.getOrCreateSocket(e);return new Promise((i,o)=>{let s=!1,a=Date.now(),c=this.createHotCompileHandlers(r,()=>s,d=>s=d,o),l=d=>{!d?.status||s||(d.status==="finish"?(s=!0,c.detach(),r.off("BuildStatus",l),console.log(`[Timing] abc compile: ${Date.now()-a}ms`),i(d.exitCode??0)):(d.status==="reject"||d.status==="close")&&(s=!0,c.detach(),r.off("BuildStatus",l),this.invalidateSocket(),o(new Error(`Hot compile ${d.status}: ${d.reason||"see WatchLog/Output above for compile errors"}`))))};r.on("disconnect",c.onDisconnect),r.on("Output",c.onOutput),r.on("BuildStatus",l),r.on("WatchLog",c.onWatchLog),r.on("WatchResult",c.onWatchResult),r.on("WatchCompileResult",c.onWatchCompileResult),r.on("WatchCompileData",c.onWatchCompileData),r.emit("CommonBuild",this.buildCompileOptions(t)),console.log("[DaemonClient] Compiling, waiting for hot compile to finish...")})}static extractText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="object"){let t=e;if(typeof t.text=="string")return t.text;if(typeof t.msg=="string")return t.msg;if(typeof t.message=="string")return t.message}return JSON.stringify(e)}createHotCompileHandlers(e,t,r,i){let o=y=>{t()||(r(!0),g(),this.invalidateSocket(),i(new Error(`Socket disconnected: ${y}`)))},s=this.createOutputHandler(),{onWatchLog:a,onWatchResult:c,onWatchCompileResult:l,onWatchCompileData:d}=this.getDataHandler(),g=()=>{e.off("disconnect",o),e.off("Output",s),e.off("WatchLog",a),e.off("WatchResult",c),e.off("WatchCompileResult",l),e.off("WatchCompileData",d)};return{onDisconnect:o,onOutput:s,onWatchLog:a,onWatchResult:c,onWatchCompileResult:l,onWatchCompileData:d,detach:g}}getDataHandler(){let e=n.extractText;return{onWatchLog:s=>{let a=e(s);a.trim()&&process.stdout.write(a+(a.endsWith(`
|
|
44
45
|
`)?"":`
|
|
45
|
-
`))},onWatchResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchResult] ${a}`)},onWatchCompileResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileResult] ${a}`)},onWatchCompileData:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileData] ${a}`)}}}createOutputHandler(){return e=>{let t=typeof e.text=="string"?e.text:Buffer.from(e.text).toString(e.encoding??"utf-8");t.trim()&&(e.type==="stderr"?process.stderr.write(t):process.stdout.write(t))}}buildCompileOptions(e){let t={_:["assembleDevHqf"],daemon:!0,hotCompile:!0,mode:"module",prop:[`module=${e.moduleSpecs.join(",")}`,`product=${e.productName}`,"debuggable=true","hotReload=true","requiredDeviceType=phone"],parallel:!0,incremental:!0,analyze:"normal",env:{DEVECO_SDK_HOME:this.toolProvider.sdkPath}};return console.log("[DaemonClient] buildCompileOptions:",JSON.stringify(t,null,2)),t}async waitForDaemonReady(){let r=Date.now();for(;Date.now()-r<3e4;){let i=this.findProjectDaemon();if(i&&(i.state==="half_busy"||i.state==="idle"))return;await new Promise(o=>setTimeout(o,1e3))}throw new Error("No running hvigor daemon found. Run `devecocli run --hotreload` first.")}findProjectDaemon(){let e=this.getRegistryPath();if(!at.existsSync(e))return null;try{let t=at.readFileSync(e,"utf-8"),r=JSON.parse(t),i=Object.values(r).filter(o=>o.cwdPath===this.projectRoot&&(o.state==="idle"||o.state==="half_busy"||o.state==="busy")&&this.isProcessAlive(o.pid));return i.length>0?i[i.length-1]:null}catch{return null}}decryptSessionId(e){let t=this.getMetaDir(),r=ct.join(t,"fd"),i=ct.join(t,"ac"),o=ct.join(t,"ce"),s=this.readComponents(r),a=this.xorBuffers([s[0],s[1],s[2],Buffer.from(_b)]),c=this.readSingleFile(i),l=Qp.pbkdf2Sync(Buffer.from(a).toString(),c,1e4,16,"sha256"),d=this.readSingleFile(o),g=this.aesGcmDecrypt(l,d),y=Buffer.from(e,"hex");return this.aesGcmDecrypt(g,y).toString("utf-8")}aesGcmDecrypt(e,t){let r=0,i=t.readUInt32BE(r);r+=4;let o=t.subarray(r,r+12);r+=12;let s=i-16,a=t.subarray(r,r+s);r+=s;let c=t.subarray(r,r+16),l=Qp.createDecipheriv("aes-128-gcm",e,o);return l.setAuthTag(c),Buffer.concat([l.update(a),l.final()])}readComponents(e){let t=at.readdirSync(e).map(r=>ct.join(e,r)).filter(r=>at.statSync(r).isDirectory()).sort();if(t.length<3)throw new Error(`Expected 3 subdirectories in ${e}, found ${t.length}`);return t.slice(0,3).map(r=>{let i=at.readdirSync(r);if(i.length===0)throw new Error(`No file in ${r}`);return at.readFileSync(ct.join(r,i[0]))})}readSingleFile(e){let t=at.readdirSync(e).map(r=>ct.join(e,r)).filter(r=>at.statSync(r).isFile());if(t.length===0)throw new Error(`No file in ${e}`);return at.readFileSync(t[0])}xorBuffers(e){let t=Buffer.alloc(e[0].length);t.set(e[0]);for(let r=1;r<e.length;r++){let i=Buffer.isBuffer(e[r])?e[r]:Buffer.from(e[r]);for(let o=0;o<t.length;o++)t[o]^=i[o]}return t}getRegistryPath(){let e=process.env.HVIGOR_USER_HOME||ct.join(em.homedir(),".hvigor");return ct.join(e,"daemon","cache","daemon-sec.json")}getMetaDir(){let e=process.env.HVIGOR_USER_HOME||ct.join(em.homedir(),".hvigor");return ct.join(e,"meta")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}};import nm from"fs";import*as Ut from"path";import{green as ms,yellow as il}from"colorette";import Yr from"fs";import*as Kr from"path";import Fb from"json5";var $b=2e6,jb=1e6,Hb="hotreload",ds=class n{static generateOrUpdate(e,t,r){let i=n.readAppConfig(e),o=Kr.resolve(e,t),s=Kr.join(o,"patch.json"),a;return Yr.existsSync(s)?(p(`[PatchManager] patch.json found at ${s}, incrementing patchVersionCode`),a=n.readExistingPatch(s),a.app.patchVersionCode+=1):(p(`[PatchManager] patch.json not found, generating new one at ${s}`),a={app:{bundleName:i.bundleName,patchVersionCode:$b,versionCode:i.versionCode},module:{name:r,type:Hb}}),n.writePatchJson(s,a),a}static readAppConfig(e){let t=Kr.join(e,"AppScope","app.json5");if(!Yr.existsSync(t))throw new Error(`AppScope/app.json5 not found at ${t}. Unable to read bundleName and versionCode.`);let r=Yr.readFileSync(t,"utf-8"),i=Fb.parse(r),o=i?.app?.bundleName;if(!o)throw new Error("bundleName is missing in AppScope/app.json5");let s=i?.app?.versionCode??jb;return{bundleName:o,versionCode:s}}static readExistingPatch(e){let t=Yr.readFileSync(e,"utf-8"),r=JSON.parse(t);if(!r?.app?.patchVersionCode)throw new Error(`Invalid patch.json at ${e}: missing app.patchVersionCode`);return r}static writePatchJson(e,t){let r=Kr.dirname(e);Yr.existsSync(r)||Yr.mkdirSync(r,{recursive:!0});let i=JSON.stringify(t,null,2);Yr.writeFileSync(e,i,"utf-8"),p(`[PatchManager] patch.json written to ${e}`),p(`[PatchManager] Content: ${i}`)}};import Se from"fs";import*as J from"path";import tm from"crypto";import Ub from"json5";import{execa as rm}from"execa";var us=class n{static COMPONENT=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]);static DIRS=["fd","ac","ce"];static decryptPwd(e,t,r){if(t.length<32||t.length%2!==0)throw new Error(`Invalid encrypted password for ${r}`);p(`[DecipherUtil] Decrypting ${r}, encrypted length: ${t.length}`);let i=J.resolve(e,"material"),o=n.getKey(i,r),s=new Int8Array(Buffer.from(t,"hex"));return p(`[DecipherUtil] Data length: ${s.length}, key length: ${o.length}`),n.decrypt(o,s).toString("utf-8")}static getKey(e,t){let r=J.resolve(e,n.DIRS[0]),i=n.readFd(r,t),o=n.readDirBytes(J.resolve(e,n.DIRS[1]),t),s=n.getRootKey(i,o,t),a=n.readDirBytes(J.resolve(e,n.DIRS[2]),t);return new Int8Array(n.decrypt(s,a))}static getRootKey(e,t,r){if(!e.every(a=>a.length===16))throw new Error(`Signing material data error for ${r}`);let i=[...e,n.COMPONENT],o=n.xor(i[0],i[1],r);for(let a=2;a<i.length;a++)o=n.xor(o,i[a],r);let s=tm.pbkdf2Sync(Buffer.from(o).toString(),Buffer.from(t),1e4,16,"sha256");return new Int8Array(s)}static xor(e,t,r){if(e.byteLength!==t.byteLength)throw new Error(`Signing material data error for ${r}`);let i=new Int8Array(e.byteLength);for(let o=0;o<e.byteLength;o++)i[o]=e[o]^t[o];return i}static decrypt(e,t){let r=(255&t[0])<<24|(255&t[1])<<16|(255&t[2])<<8|255&t[3],i=t.length-4-r,o=t.slice(4,4+i),s=t.slice(t.length-16),a=tm.createDecipheriv("aes-128-gcm",Buffer.from(e),Buffer.from(o));a.setAuthTag(Buffer.from(s));let c=a.update(Buffer.from(t.subarray(4+i,t.length-16))),l=a.final();return Buffer.concat([c,l])}static readFd(e,t){let r=Se.readdirSync(e).filter(o=>o!==".DS_Store");if(r.length!==3)throw new Error(`fd directory must have 3 entries for ${t}`);let i=[];for(let o of r){let s=J.join(e,o);i.push(n.readDirBytes(s,t))}return i}static readDirBytes(e,t){if(Se.statSync(e).isDirectory()){let i=Se.readdirSync(e).filter(o=>o!==".DS_Store");if(i.length!==1)throw new Error(`Expected exactly 1 file in ${e} for ${t}`);return new Int8Array(Se.readFileSync(J.join(e,i[0])))}return new Int8Array(Se.readFileSync(e))}},ps=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let i=`${J.dirname(e.javaPath)}${J.delimiter}${process.env.PATH||""}`;this.env={...process.env,PATH:i,DEVECO_SDK_HOME:e.sdkPath}}async generateAndSign(e,t,r,i,o=!1){let s=this.checkAbcExists(t);if(!s.exists)return{signedHqfPaths:[],message:s.message};let a=this.resolveHqfPaths(e,i);return await this.generateHqf(r,s.abcPath,a.unsignedHqfPath)?o?{success:!0,signedHqfPaths:[a.unsignedHqfPath],unsignedHqfPath:a.unsignedHqfPath,message:"Unsigned hqf generated (signing skipped for emulator)."}:this.signHqfDirect(a.unsignedHqfPath,a.signedHqfPath):{signedHqfPaths:[],unsignedHqfPath:a.unsignedHqfPath,message:"Failed to generate unsigned hqf."}}checkAbcExists(e){let t=J.join(e,"ets","modules.abc");if(Se.existsSync(t))return{exists:!0,abcPath:t,message:"abc file exists."};let r=this.findFirstAbc(e);return r?{exists:!0,abcPath:r,message:"abc file exists."}:{exists:!1,abcPath:"",message:`abc file not found in ${e}.`}}findFirstAbc(e){if(!Se.existsSync(e))return null;let t=Se.readdirSync(e,{withFileTypes:!0});for(let r of t){let i=J.join(e,r.name);if(r.isDirectory()){let o=this.findFirstAbc(i);if(o)return o}else if(r.isFile()&&r.name.endsWith(".abc"))return i}return null}resolveHqfPaths(e,t){let r=Lt(this.projectRoot,e),i=J.join(this.projectRoot,r,"build",t,"outputs","default");return Se.existsSync(i)||Se.mkdirSync(i,{recursive:!0}),{unsignedHqfPath:J.join(i,`${e}-default-unsigned.hqf`),signedHqfPath:J.join(i,`${e}-default-signed.hqf`)}}async generateHqf(e,t,r){let i=this.resolvePackingTool();if(!i)return console.error("[HotReload] app_packing_tool.jar not found in SDK."),!1;let o=J.dirname(t),s=this.toolProvider.javaPath,a=["-jar",i,"--mode","hqf","--json-path",e,"--ets-path",o,"--out-path",r,"--force","true"];p(`[GenSignHqf] Packing: ${s} ${a.join(" ")}`);try{let c=Date.now(),l=await rm(s,a,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] pack (JVM#1): ${Date.now()-c}ms`),l.stdout&&console.log(l.stdout),l.stderr&&console.error(l.stderr),l.exitCode!==0?(console.error(`[HotReload] app_packing_tool failed with exit code ${l.exitCode}`),!1):Se.existsSync(r)?(console.log(`[HotReload] Unsigned hqf generated: ${r}`),!0):(console.error(`[HotReload] hqf not generated at ${r}`),!1)}catch(c){return console.error(`[HotReload] Packing hqf failed: ${c.message}`),!1}}async signHqfDirect(e,t){let r=this.resolveSignConfig();if(!r)return this.signFailResult(e,"Signing prerequisites not met.");let i=this.buildSignArgs(r,e,t),o=this.toolProvider.javaPath,s=i.map((a,c)=>c>0&&["-keyPwd","-keystorePwd"].includes(i[c-1])?"******":a);p(`[GenSignHqf] Signing: ${o} ${s.join(" ")}`);try{let a=Date.now(),c=await rm(o,i,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] sign (JVM#2): ${Date.now()-a}ms`),c.stdout&&console.log(c.stdout),c.stderr&&console.error(c.stderr),c.exitCode!==0?this.signFailResult(e,`hqf signing failed with exit code ${c.exitCode}`):Se.existsSync(t)?(console.log(`[HotReload] Signed hqf generated: ${t}`),{success:!0,signedHqfPaths:[t],unsignedHqfPath:e,message:"hqf generated and signed successfully."}):this.signFailResult(e,`Signed hqf not generated at ${t}`)}catch(a){return this.signFailResult(e,`hqf signing failed: ${a.message}`)}}resolveSignConfig(){let e=this.resolveSignTool();if(!e)return null;let t=this.readSigningConfig("default");if(!t?.storeFile||!t?.certpath||!t?.profile)return null;let r=this.resolveMaterialDir();if(!r)return null;try{let i=us.decryptPwd(r,t.storePassword,"storePassword"),o=us.decryptPwd(r,t.keyPassword,"keyPassword");return{signToolPath:e,storePwd:i,keyPwd:o,signingConfig:t}}catch{return null}}buildSignArgs(e,t,r){return["-jar",e.signToolPath,"sign-app","-mode","localSign","-keyAlias",e.signingConfig.keyAlias||"debugKey","-keyPwd",e.keyPwd,"-keystoreFile",e.signingConfig.storeFile,"-keystorePwd",e.storePwd,"-appCertFile",e.signingConfig.certpath,"-profileFile",e.signingConfig.profile,"-inFile",t,"-outFile",r,"-signAlg",e.signingConfig.signAlg||"SHA256withECDSA"]}resolveMaterialDir(){let e=this.readSigningConfig("default");if(!e?.storeFile)return null;let t=J.resolve(e.storeFile,".."),r=J.join(t,"material");return Se.existsSync(r)?t:null}readSigningConfig(e){let t=J.join(this.projectRoot,"build-profile.json5");if(!Se.existsSync(t))return null;try{let r=Se.readFileSync(t,"utf-8"),i=Ub.parse(r),s=i.app?.products?.find(a=>a.name===e)?.signingConfig;return s?i.app?.signingConfigs?.find(a=>a.name===s)?.material??null:null}catch{return null}}resolveSignTool(){let e=this.toolProvider.sdkPath,t=[J.join(e,"default","openharmony","toolchains","lib","hap-sign-tool.jar"),J.join(e,"toolchains","lib","hap-sign-tool.jar")];for(let r of t)if(Se.existsSync(r))return r;return null}signFailResult(e,t){return console.error(`[HotReload] ${t}`),{success:!1,signedHqfPaths:[],unsignedHqfPath:e,message:t}}resolvePackingTool(){let e=this.toolProvider.sdkPath,t=[J.join(e,"default","openharmony","toolchains","lib","app_packing_tool.jar"),J.join(e,"toolchains","lib","app_packing_tool.jar")];for(let r of t)if(Se.existsSync(r))return r;return null}};async function im(n){let e=Date.now(),t=Lt(n.projectPath,n.moduleName),r=Bb(n);console.log(il("[HotReload] Ensure the project source is trusted before proceeding."));let i=Wb(n),o=Di(r,n.projectPath);console.log(`[HotReload] Parsed ${o.length} changed file(s) from ${n.applyFileName}`),Vb(n,o),Gb(n,t),await qb(n,i);let s=Ut.join(n.projectPath,t,"patch.json"),a=await Jb(n,t,s);return await Yb(n,a),console.log(ms("[HotReload] hot reload applied successfully (app not restarted).")),console.log(`[Timing] TOTAL executeHotReloadApply: ${Date.now()-e}ms`),{success:!0,message:"Hot reload applied successfully."}}function Bb(n){if(Ut.basename(n.applyFileName)!==n.applyFileName)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${n.applyFileName}`);return Ut.join(n.projectPath,".hvigor",n.applyFileName)}function Wb(n){let{projectPath:e,toolProvider:t}=n,r=new Rn(e,t);if(!r.findProjectDaemon())throw new Error("No running hvigor daemon found. Run `devecocli run --hotreload` first to start the daemon.");return r}function Vb(n,e){let t=An.writeChangedFileLists(n.projectPath,n.productName,e,n.moduleName);if(t.writtenModules.length===0)throw new Error("No changed files belong to a runnable module");console.log(ms(`[HotReload] changedFileList written for: ${t.writtenModules.join(", ")}`)),t.skippedFiles.length>0&&console.warn(il(`[HotReload] skipped ${t.skippedFiles.length} file(s)`))}function Gb(n,e){let t=ds.generateOrUpdate(n.projectPath,e,n.moduleName);console.log(ms(`[HotReload] patch.json ready (patchVersionCode=${t.app.patchVersionCode})`))}async function qb(n,e){let t=Date.now(),r=e.getWatchLogPath();try{console.log("[HotReload] Daemon hot compile (socket short connection)...");let i=await e.sendHotCompile({moduleSpecs:n.moduleSpecs,productName:n.productName});if(i!==0){let o=zb(r);throw new Error(`Daemon hot compile exited with code ${i}`+(o?`
|
|
46
|
+
`))},onWatchResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchResult] ${a}`)},onWatchCompileResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileResult] ${a}`)},onWatchCompileData:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileData] ${a}`)}}}createOutputHandler(){return e=>{let t=typeof e.text=="string"?e.text:Buffer.from(e.text).toString(e.encoding??"utf-8");t.trim()&&(e.type==="stderr"?process.stderr.write(t):process.stdout.write(t))}}buildCompileOptions(e){let t={_:["assembleDevHqf"],daemon:!0,hotCompile:!0,mode:"module",prop:[`module=${e.moduleSpecs.join(",")}`,`product=${e.productName}`,"debuggable=true","hotReload=true","requiredDeviceType=phone"],parallel:!0,incremental:!0,analyze:"normal",env:{DEVECO_SDK_HOME:this.toolProvider.sdkPath}};return console.log("[DaemonClient] buildCompileOptions:",JSON.stringify(t,null,2)),t}async waitForDaemonReady(){let r=Date.now();for(;Date.now()-r<3e4;){let i=this.findProjectDaemon();if(i&&(i.state==="half_busy"||i.state==="idle"))return;await new Promise(o=>setTimeout(o,1e3))}throw new Error("No running hvigor daemon found. Run `devecocli run --hotreload` first.")}findProjectDaemon(){let e=this.getRegistryPath();if(!dt.existsSync(e))return null;try{let t=dt.readFileSync(e,"utf-8"),r=JSON.parse(t),i=Object.values(r).filter(o=>o.cwdPath===this.projectRoot&&(o.state==="idle"||o.state==="half_busy"||o.state==="busy")&&this.isProcessAlive(o.pid));return i.length>0?i[i.length-1]:null}catch{return null}}decryptSessionId(e){let t=this.getMetaDir(),r=ut.join(t,"fd"),i=ut.join(t,"ac"),o=ut.join(t,"ce"),s=this.readComponents(r),a=this.xorBuffers([s[0],s[1],s[2],Buffer.from(kE)]),c=this.readSingleFile(i),l=Dm.pbkdf2Sync(Buffer.from(a).toString(),c,1e4,16,"sha256"),d=this.readSingleFile(o),g=this.aesGcmDecrypt(l,d),y=Buffer.from(e,"hex");return this.aesGcmDecrypt(g,y).toString("utf-8")}aesGcmDecrypt(e,t){let r=0,i=t.readUInt32BE(r);r+=4;let o=t.subarray(r,r+12);r+=12;let s=i-16,a=t.subarray(r,r+s);r+=s;let c=t.subarray(r,r+16),l=Dm.createDecipheriv("aes-128-gcm",e,o);return l.setAuthTag(c),Buffer.concat([l.update(a),l.final()])}readComponents(e){let t=dt.readdirSync(e).map(r=>ut.join(e,r)).filter(r=>dt.statSync(r).isDirectory()).sort();if(t.length<3)throw new Error(`Expected 3 subdirectories in ${e}, found ${t.length}`);return t.slice(0,3).map(r=>{let i=dt.readdirSync(r);if(i.length===0)throw new Error(`No file in ${r}`);return dt.readFileSync(ut.join(r,i[0]))})}readSingleFile(e){let t=dt.readdirSync(e).map(r=>ut.join(e,r)).filter(r=>dt.statSync(r).isFile());if(t.length===0)throw new Error(`No file in ${e}`);return dt.readFileSync(t[0])}xorBuffers(e){let t=Buffer.alloc(e[0].length);t.set(e[0]);for(let r=1;r<e.length;r++){let i=Buffer.isBuffer(e[r])?e[r]:Buffer.from(e[r]);for(let o=0;o<t.length;o++)t[o]^=i[o]}return t}getRegistryPath(){let e=process.env.HVIGOR_USER_HOME||ut.join(Am.homedir(),".hvigor");return ut.join(e,"daemon","cache","daemon-sec.json")}getMetaDir(){let e=process.env.HVIGOR_USER_HOME||ut.join(Am.homedir(),".hvigor");return ut.join(e,"meta")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}};import xm from"fs";import*as Gt from"path";import{green as Is,yellow as Cl}from"colorette";import Xr from"fs";import*as Zr from"path";import IE from"json5";var DE=2e6,AE=1e6,RE="hotreload",Ps=class n{static generateOrUpdate(e,t,r){let i=n.readAppConfig(e),o=Zr.resolve(e,t),s=Zr.join(o,"patch.json"),a;return Xr.existsSync(s)?(p(`[PatchManager] patch.json found at ${s}, incrementing patchVersionCode`),a=n.readExistingPatch(s),a.app.patchVersionCode+=1):(p(`[PatchManager] patch.json not found, generating new one at ${s}`),a={app:{bundleName:i.bundleName,patchVersionCode:DE,versionCode:i.versionCode},module:{name:r,type:RE}}),n.writePatchJson(s,a),a}static readAppConfig(e){let t=Zr.join(e,"AppScope","app.json5");if(!Xr.existsSync(t))throw new Error(`AppScope/app.json5 not found at ${t}. Unable to read bundleName and versionCode.`);let r=Xr.readFileSync(t,"utf-8"),i=IE.parse(r),o=i?.app?.bundleName;if(!o)throw new Error("bundleName is missing in AppScope/app.json5");let s=i?.app?.versionCode??AE;return{bundleName:o,versionCode:s}}static readExistingPatch(e){let t=Xr.readFileSync(e,"utf-8"),r=JSON.parse(t);if(!r?.app?.patchVersionCode)throw new Error(`Invalid patch.json at ${e}: missing app.patchVersionCode`);return r}static writePatchJson(e,t){let r=Zr.dirname(e);Xr.existsSync(r)||Xr.mkdirSync(r,{recursive:!0});let i=JSON.stringify(t,null,2);Xr.writeFileSync(e,i,"utf-8"),p(`[PatchManager] patch.json written to ${e}`),p(`[PatchManager] Content: ${i}`)}};import Se from"fs";import*as J from"path";import Rm from"crypto";import TE from"json5";import{execa as Tm}from"execa";var Cs=class n{static COMPONENT=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]);static DIRS=["fd","ac","ce"];static decryptPwd(e,t,r){if(t.length<32||t.length%2!==0)throw new Error(`Invalid encrypted password for ${r}`);p(`[DecipherUtil] Decrypting ${r}, encrypted length: ${t.length}`);let i=J.resolve(e,"material"),o=n.getKey(i,r),s=new Int8Array(Buffer.from(t,"hex"));return p(`[DecipherUtil] Data length: ${s.length}, key length: ${o.length}`),n.decrypt(o,s).toString("utf-8")}static getKey(e,t){let r=J.resolve(e,n.DIRS[0]),i=n.readFd(r,t),o=n.readDirBytes(J.resolve(e,n.DIRS[1]),t),s=n.getRootKey(i,o,t),a=n.readDirBytes(J.resolve(e,n.DIRS[2]),t);return new Int8Array(n.decrypt(s,a))}static getRootKey(e,t,r){if(!e.every(a=>a.length===16))throw new Error(`Signing material data error for ${r}`);let i=[...e,n.COMPONENT],o=n.xor(i[0],i[1],r);for(let a=2;a<i.length;a++)o=n.xor(o,i[a],r);let s=Rm.pbkdf2Sync(Buffer.from(o).toString(),Buffer.from(t),1e4,16,"sha256");return new Int8Array(s)}static xor(e,t,r){if(e.byteLength!==t.byteLength)throw new Error(`Signing material data error for ${r}`);let i=new Int8Array(e.byteLength);for(let o=0;o<e.byteLength;o++)i[o]=e[o]^t[o];return i}static decrypt(e,t){let r=(255&t[0])<<24|(255&t[1])<<16|(255&t[2])<<8|255&t[3],i=t.length-4-r,o=t.slice(4,4+i),s=t.slice(t.length-16),a=Rm.createDecipheriv("aes-128-gcm",Buffer.from(e),Buffer.from(o));a.setAuthTag(Buffer.from(s));let c=a.update(Buffer.from(t.subarray(4+i,t.length-16))),l=a.final();return Buffer.concat([c,l])}static readFd(e,t){let r=Se.readdirSync(e).filter(o=>o!==".DS_Store");if(r.length!==3)throw new Error(`fd directory must have 3 entries for ${t}`);let i=[];for(let o of r){let s=J.join(e,o);i.push(n.readDirBytes(s,t))}return i}static readDirBytes(e,t){if(Se.statSync(e).isDirectory()){let i=Se.readdirSync(e).filter(o=>o!==".DS_Store");if(i.length!==1)throw new Error(`Expected exactly 1 file in ${e} for ${t}`);return new Int8Array(Se.readFileSync(J.join(e,i[0])))}return new Int8Array(Se.readFileSync(e))}},ks=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let i=`${J.dirname(e.javaPath)}${J.delimiter}${process.env.PATH||""}`;this.env={...process.env,PATH:i,DEVECO_SDK_HOME:e.sdkPath}}async generateAndSign(e,t,r,i,o=!1){let s=this.checkAbcExists(t);if(!s.exists)return{signedHqfPaths:[],message:s.message};let a=this.resolveHqfPaths(e,i);return await this.generateHqf(r,s.abcPath,a.unsignedHqfPath)?o?{success:!0,signedHqfPaths:[a.unsignedHqfPath],unsignedHqfPath:a.unsignedHqfPath,message:"Unsigned hqf generated (signing skipped for emulator)."}:this.signHqfDirect(a.unsignedHqfPath,a.signedHqfPath):{signedHqfPaths:[],unsignedHqfPath:a.unsignedHqfPath,message:"Failed to generate unsigned hqf."}}checkAbcExists(e){let t=J.join(e,"ets","modules.abc");if(Se.existsSync(t))return{exists:!0,abcPath:t,message:"abc file exists."};let r=this.findFirstAbc(e);return r?{exists:!0,abcPath:r,message:"abc file exists."}:{exists:!1,abcPath:"",message:`abc file not found in ${e}.`}}findFirstAbc(e){if(!Se.existsSync(e))return null;let t=Se.readdirSync(e,{withFileTypes:!0});for(let r of t){let i=J.join(e,r.name);if(r.isDirectory()){let o=this.findFirstAbc(i);if(o)return o}else if(r.isFile()&&r.name.endsWith(".abc"))return i}return null}resolveHqfPaths(e,t){let r=_t(this.projectRoot,e),i=J.join(this.projectRoot,r,"build",t,"outputs","default");return Se.existsSync(i)||Se.mkdirSync(i,{recursive:!0}),{unsignedHqfPath:J.join(i,`${e}-default-unsigned.hqf`),signedHqfPath:J.join(i,`${e}-default-signed.hqf`)}}async generateHqf(e,t,r){let i=this.resolvePackingTool();if(!i)return console.error("[HotReload] app_packing_tool.jar not found in SDK."),!1;let o=J.dirname(t),s=this.toolProvider.javaPath,a=["-jar",i,"--mode","hqf","--json-path",e,"--ets-path",o,"--out-path",r,"--force","true"];p(`[GenSignHqf] Packing: ${s} ${a.join(" ")}`);try{let c=Date.now(),l=await Tm(s,a,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] pack (JVM#1): ${Date.now()-c}ms`),l.stdout&&console.log(l.stdout),l.stderr&&console.error(l.stderr),l.exitCode!==0?(console.error(`[HotReload] app_packing_tool failed with exit code ${l.exitCode}`),!1):Se.existsSync(r)?(console.log(`[HotReload] Unsigned hqf generated: ${r}`),!0):(console.error(`[HotReload] hqf not generated at ${r}`),!1)}catch(c){return console.error(`[HotReload] Packing hqf failed: ${c.message}`),!1}}async signHqfDirect(e,t){let r=this.resolveSignConfig();if(!r)return this.signFailResult(e,"Signing prerequisites not met.");let i=this.buildSignArgs(r,e,t),o=this.toolProvider.javaPath,s=i.map((a,c)=>c>0&&["-keyPwd","-keystorePwd"].includes(i[c-1])?"******":a);p(`[GenSignHqf] Signing: ${o} ${s.join(" ")}`);try{let a=Date.now(),c=await Tm(o,i,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] sign (JVM#2): ${Date.now()-a}ms`),c.stdout&&console.log(c.stdout),c.stderr&&console.error(c.stderr),c.exitCode!==0?this.signFailResult(e,`hqf signing failed with exit code ${c.exitCode}`):Se.existsSync(t)?(console.log(`[HotReload] Signed hqf generated: ${t}`),{success:!0,signedHqfPaths:[t],unsignedHqfPath:e,message:"hqf generated and signed successfully."}):this.signFailResult(e,`Signed hqf not generated at ${t}`)}catch(a){return this.signFailResult(e,`hqf signing failed: ${a.message}`)}}resolveSignConfig(){let e=this.resolveSignTool();if(!e)return null;let t=this.readSigningConfig("default");if(!t?.storeFile||!t?.certpath||!t?.profile)return null;let r=this.resolveMaterialDir();if(!r)return null;try{let i=Cs.decryptPwd(r,t.storePassword,"storePassword"),o=Cs.decryptPwd(r,t.keyPassword,"keyPassword");return{signToolPath:e,storePwd:i,keyPwd:o,signingConfig:t}}catch{return null}}buildSignArgs(e,t,r){return["-jar",e.signToolPath,"sign-app","-mode","localSign","-keyAlias",e.signingConfig.keyAlias||"debugKey","-keyPwd",e.keyPwd,"-keystoreFile",e.signingConfig.storeFile,"-keystorePwd",e.storePwd,"-appCertFile",e.signingConfig.certpath,"-profileFile",e.signingConfig.profile,"-inFile",t,"-outFile",r,"-signAlg",e.signingConfig.signAlg||"SHA256withECDSA"]}resolveMaterialDir(){let e=this.readSigningConfig("default");if(!e?.storeFile)return null;let t=J.resolve(e.storeFile,".."),r=J.join(t,"material");return Se.existsSync(r)?t:null}readSigningConfig(e){let t=J.join(this.projectRoot,"build-profile.json5");if(!Se.existsSync(t))return null;try{let r=Se.readFileSync(t,"utf-8"),i=TE.parse(r),s=i.app?.products?.find(a=>a.name===e)?.signingConfig;return s?i.app?.signingConfigs?.find(a=>a.name===s)?.material??null:null}catch{return null}}resolveSignTool(){let e=this.toolProvider.sdkPath,t=[J.join(e,"default","openharmony","toolchains","lib","hap-sign-tool.jar"),J.join(e,"toolchains","lib","hap-sign-tool.jar")];for(let r of t)if(Se.existsSync(r))return r;return null}signFailResult(e,t){return console.error(`[HotReload] ${t}`),{success:!1,signedHqfPaths:[],unsignedHqfPath:e,message:t}}resolvePackingTool(){let e=this.toolProvider.sdkPath,t=[J.join(e,"default","openharmony","toolchains","lib","app_packing_tool.jar"),J.join(e,"toolchains","lib","app_packing_tool.jar")];for(let r of t)if(Se.existsSync(r))return r;return null}};async function Lm(n){let e=Date.now(),t=_t(n.projectPath,n.moduleName),r=xE(n);console.log(Cl("[HotReload] Ensure the project source is trusted before proceeding."));let i=LE(n),o=$i(r,n.projectPath);console.log(`[HotReload] Parsed ${o.length} changed file(s) from ${n.applyFileName}`),NE(n,o),ME(n,t),await OE(n,i);let s=Gt.join(n.projectPath,t,"patch.json"),a=await FE(n,t,s);return await $E(n,a),console.log(Is("[HotReload] hot reload applied successfully (app not restarted).")),console.log(`[Timing] TOTAL executeHotReloadApply: ${Date.now()-e}ms`),{success:!0,message:"Hot reload applied successfully."}}function xE(n){if(Gt.basename(n.applyFileName)!==n.applyFileName)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${n.applyFileName}`);return Gt.join(n.projectPath,".hvigor",n.applyFileName)}function LE(n){let{projectPath:e,toolProvider:t}=n,r=new Nn(e,t);if(!r.findProjectDaemon())throw new Error("No running hvigor daemon found. Run `devecocli run --hotreload` first to start the daemon.");return r}function NE(n,e){let t=xn.writeChangedFileLists(n.projectPath,n.productName,e,n.moduleName);if(t.writtenModules.length===0)throw new Error("No changed files belong to a runnable module");console.log(Is(`[HotReload] changedFileList written for: ${t.writtenModules.join(", ")}`)),t.skippedFiles.length>0&&console.warn(Cl(`[HotReload] skipped ${t.skippedFiles.length} file(s)`))}function ME(n,e){let t=Ps.generateOrUpdate(n.projectPath,e,n.moduleName);console.log(Is(`[HotReload] patch.json ready (patchVersionCode=${t.app.patchVersionCode})`))}async function OE(n,e){let t=Date.now(),r=e.getWatchLogPath();try{console.log("[HotReload] Daemon hot compile (socket short connection)...");let i=await e.sendHotCompile({moduleSpecs:n.moduleSpecs,productName:n.productName});if(i!==0){let o=_E(r);throw new Error(`Daemon hot compile exited with code ${i}`+(o?`
|
|
46
47
|
--- compile output (from watch session) ---
|
|
47
|
-
${o}`:""))}}finally{e.disconnect()}console.log(`[Timing] daemon hot compile: ${Date.now()-t}ms`)}function
|
|
48
|
-
`):""}catch{return""}}async function
|
|
49
|
-
`)}toTraceError(e,t){return new S(this.formatFailure(e,t),e.status)}};import
|
|
50
|
-
`)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let i=t[0];return p(
|
|
48
|
+
${o}`:""))}}finally{e.disconnect()}console.log(`[Timing] daemon hot compile: ${Date.now()-t}ms`)}function _E(n){try{return xm.existsSync(n)?xm.readFileSync(n,"utf8").split(/\r?\n/).filter(t=>t.trim()).slice(-40).join(`
|
|
49
|
+
`):""}catch{return""}}async function FE(n,e,t){let r=Gt.join(n.projectPath,e,"build",n.productName,"intermediates"),i=[Gt.join(r,"hotReload","patchAbcPath"),Gt.join(r,"patch","default")],o=Date.now(),s=new ks(n.toolProvider,n.projectPath),a=n.targetDeviceId.includes("127.0.0.1")||n.targetDeviceId.includes("localhost"),c=null;for(let l of i){let d=await s.generateAndSign(n.moduleName,l,t,n.productName,a);if(d.success&&d.signedHqfPaths.length>0){c=d;break}c=d}if(console.log(`[Timing] gen+sign hqf: ${Date.now()-o}ms`),!c?.success||c.signedHqfPaths.length===0)throw new Error(`hqf generation/signing failed (no abc found in any candidate). Last: ${c?.message??"unknown"}`);return c.signedHqfPaths}async function $E(n,e){let t=Date.now(),i=await new Ln(n.toolProvider).install(n.targetDeviceId,e,n.bundleName);if(console.log(`[Timing] quickfix install: ${Date.now()-t}ms`),!i.success)throw new Error(`hqf install failed: ${i.message}`)}function kl(n,e){if(!n||n.length===0)throw new Error(`Hot reload requires --module <name> (a single target module; har deps are fine). Got: '${e??""}' (no --module passed).`)}function Nm(n,e,t){let r=Gt.join(n.rootDir,".hvigor",t),i;try{i=$i(r,n.rootDir)}catch{return}let o=new Set;for(let s of i){let a=n.findOwningModule(s);if(!a||a===e)continue;let c=n.getModuleType(a);(c==="feature"||c==="shared")&&o.add(`${a} (${c})`)}o.size>0&&console.warn(Cl(`[HotReload] Changed files belong to feature/hsp dependency module(s): ${[...o].join(", ")}. These are NOT hot-reloadable \u2014 run \`devecocli run\` (full redeploy) for them. Only the target module (+ har deps) will be hot-reloaded this time.`))}function Mm(n,e,t,r,i){let o=new Set,s=n.collectNonHarDependentModuleList(e);for(let a of s)o.add(n.findArtifactPath(a,t,r,i));return o.add(n.findArtifactPath(e,t,r,i)),[...o]}async function Om(n,e){await new et(n,e.rootDir).stopDaemon(),console.log(Is("Hvigor daemon stopped."))}var Ds=class{formatPass(e){return e.evidence.processCheckSkipped?"Smoke: PASS (process check unavailable, smoke skipped)":e.evidence.phashBlank===null?"Smoke: PASS (screenshot unavailable, blank check skipped)":"Smoke: PASS"}formatFailure(e,t){let{status:r,reason:i,evidence:o}=e,s=[`Smoke: ${r}`,`${i} (bundle=${t.bundleName}, device=${t.targetDeviceId}).`];return r==="FAIL_CRASH"&&o.crashLogPath&&s.push(`crash_log: ${o.crashLogPath}`),r==="FAIL_BLANK"&&o.screenshotPath&&s.push(`screenshot: ${o.screenshotPath}`),s.join(`
|
|
50
|
+
`)}toTraceError(e,t){return new S(this.formatFailure(e,t),e.status)}};import $s from"fs";import QP from"path";import{yellow as Ji}from"colorette";import{cyan as As}from"colorette";function Qr(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=bt(t);return r==="transient"?new Error(`${e}: Device communication channel unavailable. Retry in a few seconds.`):r==="fatal"?new Error(`${e}: ${t.trim()}`):null}var Il=[800,1500,2500];function HE(n){return new Promise(e=>setTimeout(e,n))}var yr=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=ne.from(e)}createFollowLineHandler(){return(e,t)=>{if(t==="stderr"){for(let r of e)console.error(r);return}for(let r of e)console.log(r)}}findDeviceByArg(e,t){return e.find(r=>r.serial===t||r.name===t)}formatConnectedDeviceList(e){return e.map(t=>` - ${t.name} (${t.serial})`).join(`
|
|
51
|
+
`)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let i=t[0];return p(As(`Using device serial: ${i}`)),i}if(e&&t.includes(e))return p(As(`Using device serial: ${e}`)),e;let r=await this.loadConnectedDevicesByName();if(e){let i=this.findDeviceByArg(r,e);if(i)return p(As(`Using device: ${i.name} (${i.serial})`)),i.serial;let o=this.formatConnectedDeviceList(r);throw new S(`Device '${e}' not found.
|
|
51
52
|
Available devices:
|
|
52
|
-
${o}`,"Device not found.")}if(r.length===1){let i=r[0];return p(
|
|
53
|
+
${o}`,"Device not found.")}if(r.length===1){let i=r[0];return p(As(`Using device: ${i.name} (${i.serial})`)),i.serial}throw new S("Multiple devices found. Specify a target device using `--device <name>` or `--device <serial>`.\nAvailable devices:\n"+this.formatConnectedDeviceList(r),"Multiple devices found.")}async getConnectedDeviceSerials(){let e=await this.deviceManager.listDevices();if(e.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");return e.map(t=>t.serial)}async getConnectedDevices(){let e=await this.deviceManager.listDevicesWithName();if(e.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");return e}async getPidForBundle(e,t,r){p(`Retrieving PID for bundle ${r}`),E.assertBundleNameStrict(r);let i=await re(e,["-t",t,"shell","pidof",r]),o=Qr(i,"Failed to look up PID");if(o)throw o;if(i.exitCode===0&&i.stdout.trim()){let s=i.stdout.trim(),a=s.split(/\s+/)[0]||s;return p(`Found PID for ${r}: ${a}`),a}return p(`No PID found for bundle: ${r}`),null}async resizeHilogBuffer(e,t,r){if(p(`Setting hilog buffer size to: ${r}`),!/^\d+[KMG]?$/.test(r))throw new Error(`Invalid hilog buffer size: ${JSON.stringify(r)}. Expected format: <number>[K|M|G], e.g. "4M", "16M"`);let i=await re(e,["-t",t,"shell","hilog","-G",r]),o=Qr(i,"Failed to resize hilog buffer");if(o)throw o;i.exitCode!==0&&console.error(`Failed to resize hilog buffer: ${i.stderr||i.stdout}`)}buildHilogCommand(e,t,r,i){let o=this.buildHilogShellCommand(r,i);return[e,["-t",t,"shell",o]]}buildHilogShellCommand(e,t){let r=["hilog"];return e.isFollow||r.push("-x"),e.tag&&(E.assertHilogToken(e.tag,"tag"),r.push("-T",e.tag)),e.level&&(E.assertHilogLevel(e.level),r.push("-L",e.level)),e.domain&&(E.assertHilogToken(e.domain,"domain"),r.push("-D",e.domain)),t&&r.push("-P",t),e.keyword&&(E.assertHilogKeyword(e.keyword),r.push("-e",E.quotePosixShellArg(e.keyword))),r.join(" ")}async followHilog(e,t,r,i,o){let a=await hm(e,t,{onData:r,onError:i,onClose:o});return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}async runHilogWithSpawnRetry(e,t,r,i,o){let s=1+Il.length,a={stdout:"",stderr:"",exitCode:-1};for(let c=0;c<s;c++){if(a=await this.followHilog(e,t,r,i,o),a.exitCode===0||bt(a.stderr)!=="transient"||c>=s-1)return a;p(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${Il[c]}ms`),await HE(Il[c])}return a}async runHilogStreamingCollect(e,t,r){return this.runHilogWithSpawnRetry(e,t,()=>{},i=>{p(`Callback triggered when an error occurs during ${r}: ${i.message}`)},()=>{})}async printTailSnapshotIfNeeded(e,t,r,i){if(!r.tail&&!r.fromSeconds&&!r.toSeconds)return;let o={...r,isFollow:!1},[s,a]=this.buildHilogCommand(e,t,o,i);p(`Ready to run hilog snapshot command: ${s} ${a.join(" ")}`);let c=await this.runHilogStreamingCollect(s,a,"a hilog snapshot streaming read"),l=Qr(c,"Failed to get hilog");if(l)throw l;if(c.exitCode!==0&&c.stderr)throw new Error(`Failed to get hilog: ${c.stderr}`);let d=E.filterLogsByRelativeWindow(c.stdout||c.stderr,r.fromSeconds,r.toSeconds);d=E.getLastLines(d,r.tail),d.trim()&&console.log(d)}async getHilogOnce(e,t,r,i){let[o,s]=this.buildHilogCommand(e,t,r,i);p(`Ready to run hilog command: ${o} ${s.join(" ")}`);let a=await this.runHilogStreamingCollect(o,s,"a single hilog streaming read"),c=Qr(a,"Failed to get hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to get hilog: ${a.stderr}`);let l=a.stdout||a.stderr,d=E.filterLogsByRelativeWindow(l,r.fromSeconds,r.toSeconds);return d=E.getLastLines(d,r.tail),d}async runHilogFollow(e,t,r,i){try{await this.printTailSnapshotIfNeeded(e,t,r,i)}catch(l){console.error(`Warning: Failed to fetch log snapshot, continuing with live stream: ${l.message}`)}let[o,s]=this.buildHilogCommand(e,t,r,i);p(`Ready to run hilog command which contain \`follow\` and \`tail\`: ${o} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(o,s,this.createFollowLineHandler(),l=>{p(`Spawn error during hilog follow: ${l.message}`)},()=>{}),c=Qr(a,"Failed to follow hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to follow hilog: ${a.stderr}`);return""}async getHilog(e,t){let r=this.toolProvider.hdcPath,i=t.bundleName?await this.getPidForBundle(r,e,t.bundleName):void 0;if(t.bundleName&&!i)throw new S(`No running process found for bundle '${t.bundleName}'. Ensure the app is launched on the device before fetching logs.`,"No running process found for bundle.");return t.logSize&&await this.resizeHilogBuffer(r,e,t.logSize),t.isFollow?await this.runHilogFollow(r,e,t,i||""):await this.getHilogOnce(r,e,t,i||"")}async getLatestCrashLog(e,t){p(`Fetching crash logs from device: ${e}`);let r=this.toolProvider.hdcPath,i=await this.listCrashLogs(r,e,t);if(i.length===0)return;let s=[...i].sort((c,l)=>{let d=c.split("-").pop()||"";return(l.split("-").pop()||"").localeCompare(d)})[0],a=await this.fetchCrashLogContent(r,e,s);return`--- Latest Crash Log File: ${s} ---${a}`}async getCrashLog(e,t){let r=await this.getLatestCrashLog(e,t);return r!==void 0?r:t?`No crash logs found for bundle '${t}'.`:"No crash logs found."}async listCrashLogs(e,t,r){let i=["-t",t,"shell","hidumper","-s","1201","-a","-p Faultlogger"];p(`Running command: ${e} ${i.join(" ")}`);let o=await this.runHilogStreamingCollect(e,i,"a crash log list streaming read"),s=Qr(o,"Failed to list crash logs");if(s)throw s;if(o.exitCode!==0)throw new Error(`Failed to list crash logs: ${o.stderr||o.stdout}`);return p(`Crash logs list output:
|
|
53
54
|
${o.stdout}`),this.parseCrashLogFilenames(o.stdout,r)}parseCrashLogFilenames(e,t){return e.split(`
|
|
54
|
-
`).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>{try{return E.assertCrashFilename(r),!0}catch{return!1}}).filter(r=>t?r.toLowerCase().includes(t.toLowerCase()):!0)}async fetchCrashLogContent(e,t,r){p(`Fetching latest crash log file: ${r}`);let i=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];p(`Executing command: ${e} ${i.join(" ")}`);let o=await this.runHilogStreamingCollect(e,i,"a crash log streaming read"),s=
|
|
55
|
-
`),t=e.findIndex(s=>s.trimStart().startsWith("WindowName"));if(t===-1)return[];let r=[];for(let s=t+1;s<e.length;s++){let a=e[s].trim();if(!a||/^-+$/.test(a)||a.startsWith("Focus window")||a.startsWith("total window"))break;let c=a.split(/\s+/);if(c.length<5)continue;let l=c[0],d=Number(c[1]),g=Number(c[2]),y=Number(c[3]),I=Number(c[4]);Number.isFinite(y)&&Number.isFinite(d)&&Number.isFinite(g)&&r.push({id:y,name:l,pid:g,displayId:d,type:I})}let i=e.find(s=>s.trim().startsWith("Focus window")),o=i?Number(i.replace(/.*:\s*/,"").trim()):NaN;return r.map(s=>({...s,focused:s.id===o}))}function
|
|
56
|
-
`).trim()}function
|
|
55
|
+
`).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>{try{return E.assertCrashFilename(r),!0}catch{return!1}}).filter(r=>t?r.toLowerCase().includes(t.toLowerCase()):!0)}async fetchCrashLogContent(e,t,r){p(`Fetching latest crash log file: ${r}`);let i=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];p(`Executing command: ${e} ${i.join(" ")}`);let o=await this.runHilogStreamingCollect(e,i,"a crash log streaming read"),s=Qr(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}};import{readFileSync as BE,unlinkSync as WE}from"fs";import{tmpdir as VE}from"os";import{join as GE}from"path";var qt=class{constructor(e,t){this.hdcPath=e;this.serial=t}async listWindows(e){let t=await this.fetchDump(),r=UE(t);return e?.all||(r=r.filter(i=>i.type===1)),r}async fetchDump(){let e=["-t",this.serial,"shell","hidumper","-s","WindowManagerService","-a","-a"];p(`Executing: ${this.hdcPath} ${e.join(" ")}`);let t=await re(this.hdcPath,e);if(t.exitCode!==0)throw new Error(`Failed to query windows: ${(t.stderr||t.stdout).trim()}`);return t.stdout}};function UE(n){let e=n.split(`
|
|
56
|
+
`),t=e.findIndex(s=>s.trimStart().startsWith("WindowName"));if(t===-1)return[];let r=[];for(let s=t+1;s<e.length;s++){let a=e[s].trim();if(!a||/^-+$/.test(a)||a.startsWith("Focus window")||a.startsWith("total window"))break;let c=a.split(/\s+/);if(c.length<5)continue;let l=c[0],d=Number(c[1]),g=Number(c[2]),y=Number(c[3]),I=Number(c[4]);Number.isFinite(y)&&Number.isFinite(d)&&Number.isFinite(g)&&r.push({id:y,name:l,pid:g,displayId:d,type:I})}let i=e.find(s=>s.trim().startsWith("Focus window")),o=i?Number(i.replace(/.*:\s*/,"").trim()):NaN;return r.map(s=>({...s,focused:s.id===o}))}function _m(n){if(!(!n||n==="HitTestMode.Default"))return n.startsWith("HitTestMode.")?n.slice(12):n}function Hi(n){if(!(n==null||n==="")){if(typeof n=="boolean")return n;if(n==="true")return!0;if(n==="false")return!1}}function Fm(n){if(typeof n!="string")return;let e=n.match(/-?\d+/g);if(!(!e||e.length<4))return[Number(e[0]),Number(e[1]),Number(e[2]),Number(e[3])]}function $m(n){return n.originalText||void 0}function Mn(n,e){let t=[],r=[...n].reverse();for(;r.length>0;){let i=r.pop();i.id===e&&t.push(i);for(let o=i.children.length-1;o>=0;o--)r.push(i.children[o])}return t}function jm(n,e){let t=[],r=[{current:n,parent:null,depth:0}];for(;r.length>0;){let{current:i,parent:o,depth:s}=r.pop(),a=o===null,c=!i.id&&!i.text&&!i.clickable&&!i.longClickable&&!i.scrollable&&!i.checkable,l=a||!c,d=o;if(l){let y={...i,children:[]};if(a?t.push(y):o.children.push(y),d=y,e>0&&s+1>=e)continue}if(process.env.DEVECO_CLI_DEBUG){let y=i.type?i.id?`${i.type}#${i.id}`:i.type:"#";p(`collapse ${y} depth=${s} -> ${a?"root":c?"collapsed":"emitted"}`)}let g=l?s+1:s;for(let y=i.children.length-1;y>=0;y--)r.push({current:i.children[y],parent:d,depth:g})}return t}function qE(n){let e=BE(n,"utf-8").trim();if(!e)throw new Error("Empty dumpLayout response from device");return JSON.parse(e)}function zE(n){return n.attributes??{}}function Rs(n,e,t){let r=zE(n),i={id:r.id||void 0,type:r.type||void 0,text:$m(r),bounds:Fm(r.bounds),clickable:Hi(r.clickable)||void 0,longClickable:Hi(r.longClickable)||void 0,scrollable:Hi(r.scrollable)||void 0,checkable:Hi(r.checkable)||void 0,hitTestBehavior:_m(r.hitTestBehavior),children:[]};return e>0&&t+1>=e||n.children&&(i.children=n.children.map(o=>Rs(o,e,t+1))),i}function JE(n,e){if(e){let r=n.find(i=>String(i.id)===e);if(!r){let i=n.map(o=>`${o.id} (${o.name})`).join(", ");throw new S(`Window '${e}' not found. Available windows: ${i||"none"}`,"Window not found.")}return r}let t=n.find(r=>r.focused);if(t)return t;throw new Error("No window id specified and could not detect focused window")}var en=class{hdcPath;constructor(e){this.hdcPath=e}buildRemoteDumpPath(){return`/data/local/tmp/deveco_cli_dump_${Date.now()}_${process.pid}.json`}async fetchRawDump(e,t,r){let i=this.buildRemoteDumpPath(),o=["-t",e,"shell","uitest","dumpLayout","-p",i];r!==void 0&&o.push("-d",String(r)),t&&o.push("-w",t),p(`Executing: ${this.hdcPath} ${o.join(" ")}`);let s=await re(this.hdcPath,o);if(s.exitCode!==0)throw new Error(`Failed to dump layout: ${(s.stderr||s.stdout).trim()}`);return this.recvAndParseDump(e,i)}async recvAndParseDump(e,t){let r=GE(VE(),`deveco_cli_dump_${Date.now()}_${process.pid}.json`);try{return await this.recvDumpFile(e,t,r),qE(r)}finally{await this.cleanupDumpArtifacts(e,r,t)}}async recvDumpFile(e,t,r){let i=["-t",e,"file","recv",t,r];p(`Executing: ${this.hdcPath} ${i.join(" ")}`);let o=await re(this.hdcPath,i);if(o.exitCode!==0)throw new Error(`Failed to recv dump file: ${(o.stderr||o.stdout).trim()}`)}async cleanupDumpArtifacts(e,t,r){try{p(`Removing local dump file: ${t}`),WE(t)}catch(o){p(`Failed to clean local dump file ${t}: ${o.message}`)}let i=["-t",e,"shell","rm","-f",r];p(`Executing: ${this.hdcPath} ${i.join(" ")}`),await re(this.hdcPath,i).catch(o=>{p(`Failed to clean remote dump file ${r}: ${o.message}`)})}async dumpRawNodes(e,t,r){let o=await new qt(this.hdcPath,e).listWindows({all:!0});if(r){let a=[...new Set(o.map(l=>l.displayId))],c=[];for(let l of a)c.push(await this.fetchRawDump(e,void 0,l));return c}let s=JE(o,t);return[await this.fetchRawDump(e,String(s.id),s.displayId)]}async dumpFullTree(e,t,r,i){return(await this.dumpRawNodes(e,r,i)).map(s=>Rs(s,t,0))}async dumpFullTreeByDisplays(e,t,r){let i=[];for(let o of r){let s=await this.fetchRawDump(e,void 0,o);i.push({displayId:o,tree:Rs(s,t,0)})}return i}async dumpCollapsedTree(e,t,r,i){return(await this.dumpRawNodes(e,r,i)).flatMap(s=>jm(Rs(s,0,0),t))}};import Ve from"fs";import De from"path";import{randomUUID as YE}from"crypto";function Hm(n,e){let t=["-t",n.serial,"shell","snapshot_display"];return n.display!==void 0&&t.push("-i",n.display),t.push("-f",n.remotePath),e&&t.push("-t",e),t}function Um(n,e){return[n,e].filter(Boolean).join(`
|
|
57
|
+
`).trim()}function Bm(n){return n.replace(/(Tips:\s*supported\s+displayIds)\s*:?[ \t]*(?:\r?\n[ \t]*)?(\d+(?:(?:[ \t]*,[ \t]*|[ \t]+|\r?\n[ \t]*)\d+)*)/gi,(e,t,r)=>`${t}: ${r.match(/\d+/g)?.join(", ")??r}`)}function Wm(n){let e=String.raw`invalid|not found|not exist|does not exist|out of range|unsupported`;return new RegExp(String.raw`display(?:\s*id)?.*(?:${e})`,"is").test(n)||new RegExp(String.raw`(?:${e}).*display(?:\s*id)?`,"is").test(n)}function Vm(n){let e=n.trim();if(!e||/No such file|not found|cannot access/i.test(e))return;let t=e.split(/\s+/),r=Number(t[4]);return Number.isFinite(r)?r:void 0}function KE(){return String(Date.now())}function Dl(n){let e;try{e=Ve.statSync(n)}catch(t){let r=t.code;throw r==="ENOENT"?new Error(`Screenshot directory does not exist: ${n}`,{cause:t}):r==="EACCES"||r==="EPERM"?new Error(`Screenshot directory is not writable: ${n}`,{cause:t}):new Error(`Invalid screenshot path: ${t.message}${r?` (${r})`:""}`,{cause:t})}if(!e.isDirectory())throw new Error(`Screenshot parent path is not a directory: ${n}`);try{Ve.accessSync(n,Ve.constants.W_OK|Ve.constants.X_OK)}catch(t){throw new Error(`Screenshot directory is not writable: ${n}`,{cause:t})}}function Al(n,e){try{throw Ve.lstatSync(n),new Error(`Screenshot file already exists: ${n}`)}catch(t){let r=t.code;if(r==="ENOENT")return;throw r==="EACCES"||r==="EPERM"?new Error(`Screenshot directory is not writable: ${e}`,{cause:t}):t instanceof Error&&!r?t:new Error(`Invalid screenshot path: ${t.message}${r?` (${r})`:""}`,{cause:t})}}function Gm(n){if(!Ve.existsSync(n))throw new Error(`Screenshot file was not created: ${n}`);let e=Ve.statSync(n);if(!e.isFile()||e.size===0)throw new Error(`Screenshot file is empty: ${n}`);let t=Ve.readFileSync(n).subarray(0,8),r=Buffer.from([137,80,78,71,13,10,26,10]);if(!t.equals(r))throw new Error(`Screenshot file is not a valid PNG: ${n}`)}function qm(n){try{return Gm(n),!0}catch{return!1}}function zm(n){let e=[];for(let t of Ve.readdirSync(n,{withFileTypes:!0})){let r=De.join(n,t.name);if(t.isDirectory()){e.push(...zm(r));continue}t.isFile()&&qm(r)&&e.push(r)}return e}function XE(n,e){let t=De.join(n,De.basename(e));if(qm(t))return t;let r=zm(n);if(r.length===1)return r[0];if(r.length>1)throw new Error(`Multiple screenshot files were received in ${n}.`)}function ZE(n,e){try{Ve.copyFileSync(n,e,Ve.constants.COPYFILE_EXCL)}catch(t){throw t.code==="EEXIST"?new Error(`Screenshot file already exists: ${e}`,{cause:t}):t}Gm(e)}var tn=class{constructor(e){this.toolProvider=e}resolveDestinationPath(e){if(!e?.trim())throw new Error("--path is required.");let t=e.trim(),r=De.resolve(t);try{if(Ve.statSync(r).isDirectory()){Dl(r);let o=De.join(r,`screenshot-${KE()}.png`);return Al(o,r),o}}catch(o){if(o.code!=="ENOENT")throw o}if(De.extname(r).toLowerCase()!==".png")throw new Error(`Screenshot path must be an existing directory or a PNG file: ${r}`);let i=De.dirname(r);return Dl(i),Al(r,i),r}async captureToPath(e,t,r){let i=De.dirname(De.resolve(t));Dl(i),Al(De.resolve(t),i);let o=`/data/local/tmp/devecocli-${YE()}.png`;await this.capture({hdcPath:this.toolProvider.hdcPath,serial:e,localPath:De.resolve(t),remotePath:o,display:r})}async capture(e){try{await this.createRemoteScreenshot(e),await this.receiveScreenshotFile(e)}finally{await this.removeRemoteScreenshot(e)}}async getRemoteScreenshotSize(e){let t=["-t",e.serial,"shell","ls","-l",e.remotePath];p(`Executing: ${e.hdcPath} ${t.join(" ")}`);let r=await re(e.hdcPath,t);return r.exitCode===0?Vm(r.stdout):void 0}async tryCreateRemoteScreenshot(e,t){let r=Hm(e,t);p(`Executing: ${e.hdcPath} ${r.join(" ")}`);let i=await re(e.hdcPath,r),o=await this.getRemoteScreenshotSize(e);return{created:o!==void 0&&o>0,output:Bm(Um(i.stdout,i.stderr))}}async createRemoteScreenshot(e){let t="";for(let r of[void 0,"png"]){let i=await this.tryCreateRemoteScreenshot(e,r);if(i.created)return;if(e.display!==void 0&&Wm(i.output))throw new Error(`Screenshot was not created on device: ${e.remotePath}.
|
|
57
58
|
snapshot_display output:
|
|
58
59
|
${i.output}`);i.output&&(t=i.output)}throw new Error(t?`Screenshot was not created on device: ${e.remotePath}.
|
|
59
60
|
snapshot_display output:
|
|
60
|
-
${t}`:`Screenshot was not created on device: ${e.remotePath}.`)}async tryReceiveScreenshot(e,t,r){let i=["-t",e.serial,"file","recv",e.remotePath,r];p(`Executing: ${e.hdcPath} ${i.join(" ")}`);let o=await re(e.hdcPath,i);return o.exitCode!==0&&p(`hdc file recv failed: ${o.stderr||o.stdout||`exit code ${o.exitCode}`}`),cE(t,e.remotePath)}async receiveScreenshotFile(e){let t=Ue.mkdtempSync(Ie.join(Ie.dirname(e.localPath),".devecocli-screenshot-"));try{let r=await this.tryReceiveScreenshot(e,t,Ie.join(t,Ie.basename(e.remotePath)))??await this.tryReceiveScreenshot(e,t,t)??await this.tryReceiveScreenshot(e,t,Ie.join(t,"screenshot.png"));if(!r)throw new Error(`Screenshot file was not created in ${t}.`);lE(r,e.localPath)}finally{Ue.rmSync(t,{recursive:!0,force:!0})}}async removeRemoteScreenshot(e){let t=["-t",e.serial,"shell","rm","-f",e.remotePath];p(`Executing: ${e.hdcPath} ${t.join(" ")}`),await re(e.hdcPath,t)}};import Qm from"path";import{randomBytes as GE}from"crypto";import*as xi from"fs";import*as bm from"path";import{homedir as dE}from"os";var uE="deveco-cli",Sm,ll=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function pE(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":Fc(n))||bm.join(dE(),".local","share",uE);try{return qo(t)}catch(r){throw new ll(r instanceof Error?r.message:String(r))}}function he(){if(Sm!==void 0)return Sm;let n=pE();try{if(xi.existsSync(n))return xi.realpathSync(n)}catch{}return n}async function et(n,e){let r=await new mr(n).selectDevice(e);if(!r)throw new Error("No device selected. Use `devecocli device list` to see targets.");return r}var Li="com.huawei.hmos.screenrecorder",en="com.huawei.hmos.screenrecorder.ServiceExtAbility",Em="/data/local/tmp",w=class extends Error{constructor(t,r=t,i){super(r,i);this.code=t;this.name="ScreenRecordError"}};var dl=/^\s*uri \[([^\]]*)\]\s*$/,mE=/^\s*uri \[/,fE=/AbilityRecord ID\s*[:#]\s*(\d+)/,hE=/start time \[(\d+)\]/,gE=/bundle name \[([^\]]*)\]/,yE=/main name \[([^\]]*)\]/,vE=/\[(?:Fail|E\d{5,})\]|^\s*(?:error|Error)(?::|\s)/m,wE=en.slice(en.lastIndexOf(".")+1);function SE(n){let e=[],t;for(let r of n.split(/\r?\n/))dl.test(r)?(t=[r],e.push(t)):t&&t.push(r);return e}function bE(n){let e={};for(let t of n){let r=dl.exec(t);if(r){e.uri=r[1].trim();continue}let i=fE.exec(t);if(i&&(e.id=Number(i[1]),!Number.isSafeInteger(e.id)))throw new w("DUMP_PARSE_FAILED",`Unparseable AbilityRecord ID in aa dump output: ${i[1]}`);let o=hE.exec(t);if(o){e.startedAtMs=Number(o[1]);continue}let s=gE.exec(t);if(s){e.bundleName=s[1].trim();continue}let a=yE.exec(t);a&&(e.mainName=a[1].trim())}return e}function Pm(n){let e=n.mainName;if((!n.bundleName||!e)&&n.uri){let t=n.uri.split("/").filter(Boolean);t.length>=3&&(n.bundleName??=t[0],e??=t[t.length-1])}return{bundleName:n.bundleName,abilityName:e}}function EE(n){let{bundleName:e,abilityName:t}=Pm(n);return e!==Li||!t?!1:t===en||t===wE}function PE(n){if(vE.test(n))throw new w("DUMP_PARSE_FAILED",`Unexpected aa dump output: ${n.trim().split(/\r?\n/)[0]??""}`);if(!n.includes("ExtensionRecords")&&!n.includes("AbilityRecord ID"))throw new w("DUMP_PARSE_FAILED","aa dump output has no recognizable extension-record structure");for(let t of n.split(/\r?\n/))if(mE.test(t)&&!dl.test(t))throw new w("DUMP_PARSE_FAILED","aa dump output has an unterminated uri line; output may be truncated");let e=SE(n);if(e.length===0&&n.replace(/ExtensionRecords:\s*/,"").trim()!=="")throw new w("DUMP_PARSE_FAILED","aa dump output has no complete ability records; output may be truncated");return e}function Cm(n){if(!n.trim())throw new w("DUMP_PARSE_FAILED","aa dump output is empty; the device state is unknown");let e=new Map;for(let t of PE(n)){let r=bE(t);if(!EE(r))continue;if(r.id===void 0)throw new w("DUMP_PARSE_FAILED","Recorder ability block is missing its AbilityRecord ID");let{bundleName:i,abilityName:o}=Pm(r);e.set(r.id,{abilityRecordId:r.id,bundleName:i??Li,abilityName:o??en,startedAtMs:r.startedAtMs})}return[...e.values()]}function ul(n,e){if(n.length>1)throw new w("AMBIGUOUS_DEVICE_STATE",`Multiple screen recorder ability records: ${n.map(r=>r.abilityRecordId).join(", ")}`);let t=n[0];return t?{status:e?.abilityRecordId===t.abilityRecordId?"recording":"busy",activeId:t.abilityRecordId,session:e}:{status:"idle",session:e}}function tn(n,e){return!n||!e?n===e:n.fileName===e.fileName&&n.abilityRecordId===e.abilityRecordId&&n.startTime===e.startTime&&n.localPath===e.localPath}function km(n){return n.status==="recording"?{plan:"error",error:new w("CLI_RECORDING_ACTIVE","A CLI recording session is already running; run stop first")}:n.status==="busy"?{plan:"error",error:new w("EXTERNAL_RECORDING","A recording not started by this CLI is in progress; run stop --force first")}:n.session?{plan:"discard-first",session:n.session}:{plan:"start-new"}}function Im(n){return n.status==="idle"&&!n.session?{plan:"start-new"}:{plan:"error",error:new w("STATE_CHANGED","Device state changed while discarding the interrupted registration; not starting")}}function Am(n,e){return n.status==="busy"?e?{plan:"force-stop-external",activeId:n.activeId}:{plan:"error",error:new w("EXTERNAL_RECORDING","Recording was not started by this CLI. Stop it on the device or run stop --force.")}:n.session?{plan:"finalize-session",session:n.session}:{plan:"error",error:new w("NO_CLI_SESSION","No CLI recording session on this device")}}function Dm(n,e,t){return tn(n,e)?{plan:"proceed"}:t==="interactive"?{plan:"completed-elsewhere"}:{plan:"error",error:new w("SESSION_CHANGED","The recording session changed; leaving the current one untouched")}}function Rm(n){return n.status==="busy"?{plan:"error",error:new w("EXTERNAL_RECORDING","A recording not started by this CLI is in progress; not toggling")}:n.status==="recording"?{plan:"stop-recording"}:{plan:"retrieve"}}function Tm(n,e){if(n.length===0)return{outcome:"gone"};if(n.length>1)return{outcome:"error",error:new w("STATE_CHANGED","Multiple recorder records while confirming stop; not toggling again")};let t=n[0].abilityRecordId;return t!==e?{outcome:"error",error:new w("STATE_CHANGED",`A different recording (ID ${t}) appeared while stopping; leaving it alone`)}:{outcome:"still-recording",activeId:t}}function xm(n){return n.length===1?{outcome:"confirmed",record:n[0]}:n.length>1?{outcome:"error",error:new w("AMBIGUOUS_DEVICE_STATE","Multiple recorder records after start; refusing to pick one")}:{outcome:"pending"}}function Lm(n,e){if(n.length===0)return{plan:"already-stopped"};if(n.length>1)return{plan:"error",error:new w("AMBIGUOUS_DEVICE_STATE","Multiple recorder records; refusing to force-stop")};let t=n[0];return e!==void 0&&t.abilityRecordId!==e?{plan:"error",error:new w("STATE_CHANGED","The recording changed while stopping; leaving it alone")}:{plan:"stop",currentId:t.abilityRecordId,startedAtMs:t.startedAtMs}}function Nm(n){return n.status==="idle"&&n.session?{status:"idle",note:"interrupted session found; retrievable via ui screenrecord stop"}:{status:n.status}}function Mm(n,e){return!tn(n.session,e)||n.status!=="recording"}function pl(n,e){return n.startTime+e}function Om(n,e,t){return t+Math.max(0,e-n)}import fr from"fs";import Um from"path";import{randomBytes as AE}from"crypto";import{lock as DE}from"proper-lockfile";import Ni from"path";var CE=/^[A-Za-z0-9][A-Za-z0-9.-]*\.mp4$/;function xn(n){return Buffer.from(n,"utf8").toString("hex")}function rn(n,e){return String(n).padStart(e,"0")}function _m(n){return`${rn(n.getFullYear(),4)}${rn(n.getMonth()+1,2)}${rn(n.getDate(),2)}-${rn(n.getHours(),2)}${rn(n.getMinutes(),2)}${rn(n.getSeconds(),2)}${rn(n.getMilliseconds(),3)}`}function kE(n){return n.replace(/[<>:"/\\|?*\u0000-\u001f]/g,"-").replace(/\s+/g," ").trim().replace(/[. ]+$/,"").replace(/^[. ]+/,"")||"device"}function Fm(n,e){if(!/^[a-z0-9]{4}$/.test(e))throw new w("INVALID_RECORDING_PATH",`Internal: bad random suffix ${JSON.stringify(e)}`);return`devecocli-${_m(n)}-${e}.mp4`}function $m(n,e,t){return`${kE(n)}-${_m(e)}-${t}.mp4`}function jm(n,e){if(!CE.test(n))throw new w("INVALID_RECORDING_PATH",`Unsafe device file name: ${JSON.stringify(n)}`);return`${Em}/devecocli-${e}-${n}`}var IE=20;function Hm(n){let e=Ni.dirname(n),t=Ni.extname(n),r=Ni.basename(n,t),i=[n];i.push(Ni.join(e,`${r}-recovered${t}`));for(let o=2;o<IE;o++)i.push(Ni.join(e,`${r}-recovered-${o}${t}`));return i}var RE=5*6e4,TE=5*6e4,xE=1e4,LE=6e4,ml=200;function NE(n){if(!Number.isInteger(n)||n<=0)return"unknown";try{return process.kill(n,0),"alive"}catch(e){let t=e.code;return t==="ESRCH"?"dead":t==="EPERM"?"alive":"unknown"}}function Bm(n){return new Promise(e=>setTimeout(e,n))}function ME(){return AE(8).toString("hex")}async function Wm(n){let e;try{e=await fr.promises.readFile(n,"utf8")}catch{return}try{let t=JSON.parse(e);return typeof t.token=="string"?t.token:void 0}catch{return}}var ys=class{constructor(e,t={}){this.recordDir=e;this.releaseGuardWaitMs=t.releaseGuardWaitMs??xE}releaseGuardWaitMs;lockPath(e){return Um.join(this.recordDir,`${xn(e)}.lock`)}guardPath(e){return Um.join(this.recordDir,`${xn(e)}.guard`)}async withDeviceLock(e,t,r=LE){let i=await this.acquire(e,r),o;try{o=await t(i)}catch(s){try{await this.releaseOwned(e,i)}catch(a){p(`lock release failed after action error: ${a.message}`)}throw s}return await this.releaseOwned(e,i),o}async withGuard(e,t,r=0){let i=Date.now()+r;for(;;){let o;try{o=await DE(this.guardPath(e),{realpath:!1,stale:RE,update:1e3,retries:0})}catch(s){if(s.code!=="ELOCKED"||Date.now()>=i)throw s;await Bm(Math.min(ml,i-Date.now()));continue}try{return await t()}finally{await o()}}}async acquire(e,t){await fr.promises.mkdir(this.recordDir,{recursive:!0});let r=ME(),i=this.lockPath(e),o=Date.now()+t;for(;;){let s=!1;try{await this.withGuard(e,async()=>{s=await this.tryCreateOrReclaim(i,r)})}catch(a){if(a.code!=="ELOCKED")throw a}if(s)return this.buildLease(i,r);if(Date.now()+ml>o)throw new w("LOCK_BUSY",`Timed out waiting ${t}ms for the device lock (${e})`);await Bm(ml)}}async tryCreateOrReclaim(e,t){let r;try{r=await fr.promises.open(e,"wx")}catch(i){if(i.code!=="EEXIST")throw i;return await this.reclaimIfDead(e),!1}try{let i={pid:process.pid,createdAt:Date.now(),token:t};await r.writeFile(JSON.stringify(i)),await r.sync()}finally{await r.close()}return!0}async reclaimIfDead(e){let t,r;try{t=await fr.promises.readFile(e,"utf8"),r=await fr.promises.stat(e)}catch(o){if(o.code==="ENOENT")return;throw o}let i;try{let o=JSON.parse(t);typeof o.pid=="number"&&typeof o.createdAt=="number"&&typeof o.token=="string"&&(i=o)}catch{}if(i){NE(i.pid)==="dead"&&await fr.promises.unlink(e);return}Date.now()-r.mtimeMs>TE&&await fr.promises.unlink(e)}buildLease(e,t){let r=new AbortController;return{token:t,signal:r.signal,assertOwned:async()=>{if(await Wm(e)!==t)throw r.abort(),new w("LOCK_LOST","Lost the device lock; aborting this operation")}}}async releaseOwned(e,t){let r=this.lockPath(e);try{await this.withGuard(e,async()=>{await Wm(r)===t.token&&await fr.promises.unlink(r)},this.releaseGuardWaitMs)}catch(i){throw new w("LOCK_RELEASE_FAILED",`Could not release the device lock (${e}): ${i.message}. The lock stays in place; it is reclaimed by the dead-PID or corrupt-age rule once this process exits.`,{cause:i})}}};import{execa as OE}from"execa";var fl=15e3,Vm=10*6e4,_E=3,Gm=400;function FE(n){return new Promise(e=>setTimeout(e,n))}function $E(n){return async(e,t)=>{p(`Executing: ${n} ${e.join(" ")}`);let r=await OE(n,e,{reject:!1,timeout:t.timeoutMs??fl,cancelSignal:t.signal,stdout:"pipe",stderr:"pipe"});return{stdout:typeof r.stdout=="string"?r.stdout:"",stderr:typeof r.stderr=="string"?r.stderr:"",exitCode:r.exitCode??-1}}}var vs=class n{runner;constructor(e){this.runner=$E(e)}async runReadOnly(e,t){let r={stdout:"",stderr:"",exitCode:-1},i=t!==void 0?Date.now()+t:void 0;for(let o=0;o<_E;o++){let s=i!==void 0?i-Date.now():void 0;r=await this.runner(e,s===void 0?{}:{timeoutMs:Math.max(1,s)});let a=`${r.stdout}
|
|
61
|
-
${r.stderr}`;if(r.exitCode===0||
|
|
62
|
-
${e.stderr}`.trim();if(e.exitCode!==0||
|
|
63
|
-
`)[0]??""}`)}async observeOnce(e,t){let r=await this.runReadOnly(["-t",e,"shell","aa","dump","-e"],t);return n.assertUsable(r,"DUMP_PARSE_FAILED"),
|
|
64
|
-
`)[0]??""}`);return Math.round(i*1e3)}async toggleOnce(e,t,r,i){await r.assertOwned();let o=["-t",e,"shell","aa","start","-b",
|
|
65
|
-
`)[0]??""}`);let s=[...i.stdout.matchAll(/"(file:\/\/[^"]+)"/g)].map(c=>c[1]),a=Number(o[1]);if(a!==0){if(a>1||s.length>1)throw new w("MEDIA_AMBIGUOUS",`mediatool returned ${a} entries for ${t}`);if(s.length!==1)throw new w("MEDIA_QUERY_FAILED",`mediatool reported 1 entry but no URI for ${t}`);return s[0]}}async exportToStaging(e,t,r){let i=await this.runner(["-t",e,"shell","mediatool","recv",t,r],{timeoutMs:
|
|
66
|
-
`)[0]??""}`)}async receiveFile(e,t,r,i){let o=await this.runner(["-t",e,"file","recv",t,r],{timeoutMs:
|
|
67
|
-
`)[0]??""}`)}async removeStaging(e,t){return(await this.runReadOnly(["-t",e,"shell","rm","-f",t],fl)).exitCode===0}};import Wt from"fs";import Nt from"path";import{createFile as jE}from"mp4box";var zm=".devecocli-record-";function Ln(n,e){return new w("INVALID_RECORDING_PATH",e instanceof Error?`${n}: ${e.message}`:n,e instanceof Error?{cause:e}:void 0)}async function hl(n){try{return{stat:await Wt.promises.stat(n)}}catch(e){let t=e.code;return t==="ENOENT"?null:{code:t??"UNKNOWN"}}}async function qm(n){let e=await hl(n);if(!e)throw Ln(`Directory does not exist: ${n}`);if("code"in e)throw Ln(`Directory is not accessible: ${n}`);if(!e.stat.isDirectory())throw Ln(`Path is not a directory: ${n}`);try{await Wt.promises.access(n,Wt.constants.W_OK)}catch(t){throw Ln(`Directory is not writable: ${n}`,t)}}async function gl(n){if(await hl(n))throw new w("DESTINATION_EXISTS",`Destination already exists: ${n}`)}async function yl(n,e,t,r){if(!n?.trim())throw Ln("--path is required.");let i=Nt.resolve(n.trim()),o=await hl(i);if(o&&"stat"in o&&o.stat.isDirectory()){await qm(i);let a=Nt.join(i,$m(e,t,r));return await gl(a),a}if(o)throw new w("DESTINATION_EXISTS",`Destination already exists: ${i}`);if(Nt.extname(i).toLowerCase()!==".mp4")throw Ln(`Destination must be an existing directory or a new .mp4 file: ${i}`);let s=Nt.dirname(i);return await qm(s),i}async function Jm(n){return Wt.promises.mkdtemp(Nt.join(Nt.dirname(n),zm))}var HE=4*1024*1024;async function UE(n){let e=await Wt.promises.open(n,"r");try{let{size:t}=await e.stat(),r=jE(),i=0;for(let s=0;s<t;){let a=Math.min(HE,t-s),c=Buffer.alloc(a),{bytesRead:l}=await e.read(c,0,a,s);if(l<=0)break;let d=c.buffer.slice(c.byteOffset,c.byteOffset+l);d.fileStart=s,i=r.appendBuffer(d,s+l>=t),s+=l}r.flush();let o=r.getBox("moov");return{size:t,complete:i===t,hasMovieHeader:o?.mvhd!==void 0,videoTrackCount:o?.mvhd!==void 0?r.getInfo().videoTracks.length:0}}finally{await e.close()}}async function Ym(n){let e;try{e=await UE(n)}catch(t){throw new w("SAVE_FAILED",`Cannot inspect received file: ${t.message}`,{cause:t})}if(e.size===0)throw new w("MEDIA_NOT_READY","Received file is empty");if(!e.complete||!e.hasMovieHeader)throw new w("MEDIA_NOT_READY","Received file is not a complete MP4");if(e.videoTrackCount<1)throw new w("MEDIA_NOT_READY","Received file has no video track");return e.size}async function BE(n){let e=await Wt.promises.open(n,"r+");try{await e.sync()}finally{await e.close()}}async function WE(n){try{let e=await Wt.promises.open(Nt.dirname(n),"r");try{await e.sync()}finally{await e.close()}}catch{}}async function Km(n,e){await BE(n);for(let t of Hm(e))try{return await Wt.promises.link(n,t),await WE(t),t}catch(r){if(r.code==="EEXIST")continue;throw new w("SAVE_FAILED",`Cannot publish recording to ${t}: ${r.message}`,{cause:r})}throw new w("DESTINATION_UNAVAILABLE",`All recovery names are taken near ${e}`)}async function Xm(n,e){let t=Nt.dirname(e),r=Nt.basename(n);Nt.dirname(n)!==t||!r.startsWith(zm)||await Wt.promises.rm(n,{recursive:!0,force:!0}).catch(()=>{})}import Vt from"fs";import ws from"path";import{randomBytes as VE}from"crypto";function Zm(n,e){let t=n,r=i=>new w("SESSION_CORRUPT",`Invalid recording session ${i} in ${e}`);if(!t||typeof t!="object")throw r("object");if(typeof t.fileName!="string"||t.fileName.length===0||t.fileName!==ws.basename(t.fileName)||t.fileName.includes(".."))throw r("fileName");if(typeof t.abilityRecordId!="number"||!Number.isSafeInteger(t.abilityRecordId)||t.abilityRecordId<=0)throw r("abilityRecordId");if(typeof t.startTime!="number"||!Number.isFinite(t.startTime))throw r("startTime");if(typeof t.localPath!="string"||t.localPath.length===0||!ws.isAbsolute(t.localPath))throw r("localPath");return{fileName:t.fileName,abilityRecordId:t.abilityRecordId,startTime:t.startTime,localPath:t.localPath}}var Ss=class{constructor(e){this.recordDir=e}sessionPath(e){return ws.join(this.recordDir,`${xn(e)}.json`)}async read(e){let t=this.sessionPath(e),r;try{r=await Vt.promises.readFile(t,"utf8")}catch(o){if(o.code==="ENOENT")return;throw new w("SESSION_CORRUPT",`Cannot read recording session: ${o.message}`,{cause:o})}let i;try{i=JSON.parse(r)}catch(o){throw new w("SESSION_CORRUPT",`Recording session file is not valid JSON: ${t}`,{cause:o})}return Zm(i,t)}async createAtomic(e,t,r){await Vt.promises.mkdir(this.recordDir,{recursive:!0});let i=this.sessionPath(e),o=ws.join(this.recordDir,`${xn(e)}.${VE(6).toString("hex")}.tmp`),s=JSON.stringify(Zm(t,"input")),a;try{a=await Vt.promises.open(o,"wx")}catch(c){throw new w("SESSION_PUBLISH_FAILED",`Cannot create session temp file: ${c.message}`,{cause:c})}try{await a.writeFile(s),await a.sync()}catch(c){throw await a.close().catch(()=>{}),await Vt.promises.unlink(o).catch(()=>{}),new w("SESSION_PUBLISH_FAILED",`Cannot write session temp file: ${c.message}`,{cause:c})}await a.close();try{if(await r.assertOwned(),await this.exists(i))throw new w("SESSION_CHANGED",`A recording session was created concurrently for ${e}`);await Vt.promises.link(o,i),await this.syncDir()}finally{await Vt.promises.unlink(o).catch(()=>{})}}async deleteIfSame(e,t,r){await r.assertOwned();let i=await this.read(e);if(i){if(!tn(i,t))throw new w("SESSION_CHANGED","The recording session changed hands; leaving the new record untouched");await Vt.promises.unlink(this.sessionPath(e)),await this.syncDir()}}async exists(e){try{return await Vt.promises.lstat(e),!0}catch{return!1}}async syncDir(){try{let e=await Vt.promises.open(this.recordDir,"r");try{await e.sync()}finally{await e.close()}}catch{}}};var qE={startConfirmMs:1e4,stopConfirmMs:15e3,stopReadyMs:3e3,observeIntervalMs:250,foregroundPollMs:1e3,mediaReadyMs:3e4,mediaBackoffMs:[250,500,1e3,2e3],mediaRecvAttempts:3,lockWaitMs:6e4,interactiveLockWaitMs:10*6e4,foregroundFailureBudget:3},ef=4e3;function Mi(n){return new Promise(e=>setTimeout(e,n))}function bs(){return GE(2).toString("hex")}var tf=["SIGINT","SIGTERM","SIGHUP"];function zE(n){let e=()=>{n.requested||(n.requested=!0,n.wake())};for(let t of tf)process.on(t,e);return()=>{for(let t of tf)process.off(t,e)}}var hr=class{constructor(e,t={}){this.toolProvider=e;let r=Qm.join(he(),"record");this.deps={store:t.store??new Ss(r),lock:t.lock??new ys(r),device:t.device??new vs(e.hdcPath),timing:{...qE,...t.timing}}}deps;async startDetached(e,t){let r=await this.resolveTarget(e),i=await yl(t,r.name,new Date,bs());return this.startSession(r,i)}async recordInteractively(e,t,r){let i=new Set,o={requested:!1,wake:()=>{for(let a of i)a()}},s=zE(o);try{let a=await this.resolveTarget(e),c=await yl(t,a.name,new Date,bs()),l=await this.startSession(a,c);return r.onStarted(),await this.waitForInteractiveCompletion(l,o,i)}finally{s()}}async waitForInteractiveCompletion(e,t,r){let i,o=()=>(i??=this.deps.lock.withDeviceLock(e.serial,a=>this.finalizeLocked(e.serial,e.session,"interactive",a),this.deps.timing.interactiveLockWaitMs),i),s=0;for(;;){if(t.requested)return await o();let a;try{a=await this.readSnapshot(e.serial),s=0}catch(c){if(s+=1,s>=this.deps.timing.foregroundFailureBudget)throw c;await this.waitPoll(t,r);continue}if(Mm(a,e.session))return await o();await this.waitPoll(t,r)}}async stopRecording(e,t){let r=await this.resolveTarget(e);return this.deps.lock.withDeviceLock(r.serial,async i=>{let o=await this.readSnapshot(r.serial),s=Am(o,t);if(s.plan==="force-stop-external")return await this.stopExternal(r.serial,s.activeId,i),{kind:"external-stopped"};if(s.plan==="error")throw s.error;return this.finalizeLocked(r.serial,s.session,"stop-or-recover",i)},this.deps.timing.lockWaitMs)}async getRecordingStatus(e){let t=await this.resolveTarget(e);for(let r=0;r<3;r++){let i=await this.deps.store.read(t.serial),o=await this.deps.device.observeOnce(t.serial),s=await this.deps.store.read(t.serial);if(!tn(i,s))continue;let a=ul(o,s);return Nm(a)}throw new w("STATE_CHANGING","The recording session keeps changing; try again")}async resolveTarget(e){let t=await et(this.toolProvider,e),i=(await ne.from(this.toolProvider).getConnectedEntries()).find(o=>o.serial===t);if(i?.isEmulator)throw new w("EMULATOR_NOT_SUPPORTED","Screen recording is only supported on physical devices");return{serial:t,name:i?.name??t}}async readSnapshot(e){let t=await this.deps.store.read(e),r=await this.deps.device.observeOnce(e);return ul(r,t)}async startSession(e,t){return this.deps.lock.withDeviceLock(e.serial,r=>this.startSessionLocked(e,t,r),this.deps.timing.lockWaitMs)}async startSessionLocked(e,t,r){let i=await this.readSnapshot(e.serial),o=km(i);if(o.plan==="error")throw o.error;if(o.plan==="discard-first"){await this.deps.store.deleteIfSame(e.serial,o.session,r);let s=await this.readSnapshot(e.serial),a=Im(s);if(a.plan==="error")throw a.error}return this.toggleAndRegister(e,t,r)}async toggleAndRegister(e,t,r){await gl(t);let i=Fm(new Date,bs()),o=Date.now(),s=Date.now()+this.deps.timing.startConfirmMs;await r.assertOwned(),await this.deps.device.toggleOnce(e.serial,i,r,Math.max(1,s-Date.now()));let a=await this.waitForStarted(e.serial,s),c={fileName:i,abilityRecordId:a.abilityRecordId,startTime:o,localPath:t};return await this.registerSession(e.serial,c,r),{serial:e.serial,session:c}}async registerSession(e,t,r){try{await this.deps.store.createAtomic(e,t,r)}catch(i){throw await this.abortUnregistered(e,t,r),new w(i.code??"SESSION_PUBLISH_FAILED",`Recording started on device (file ${t.fileName}) but could not be registered: ${i.message}. Check the device gallery.`,{cause:i})}}async withinDeadline(e,t,r){try{return await r(Math.max(1,e-Date.now()))}catch(i){throw Date.now()>=e?t:i}}async waitForStarted(e,t){for(;;){let r=t-Date.now();if(r<=0)throw new w("START_CONFIRM_TIMEOUT","Device screen may be locked");let i=await this.withinDeadline(t,new w("START_CONFIRM_TIMEOUT","Device screen may be locked"),s=>this.deps.device.observeOnce(e,s)),o=xm(i);if(o.outcome==="error")throw o.error;if(o.outcome==="confirmed"){if(Date.now()>t)throw new w("START_CONFIRM_TIMEOUT","Device screen may be locked");return o.record}await Mi(Math.min(this.deps.timing.observeIntervalMs,r))}}async observeActiveId(e,t,r){let i=await this.deps.device.observeOnce(e,r),o=Tm(i,t);if(o.outcome==="error")throw o.error;return o.outcome==="gone"?void 0:o.activeId}async waitForStopped(e,t,r){for(;;){let i=r-Date.now();if(i<=0)throw new w("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent");if(await this.withinDeadline(r,new w("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent"),s=>this.observeActiveId(e,t,s))===void 0)return;await Mi(Math.min(this.deps.timing.observeIntervalMs,i))}}async awaitStopReady(e,t,r,i){for(;;){let o=i-Date.now();if(o<=0)throw new w("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent");if(await this.withinDeadline(i,new w("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent"),a=>this.observeActiveId(e,t,a))===void 0)return"vanished";if(Date.now()>=r){if(Date.now()>i)throw new w("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent");return"ready"}await Mi(Math.min(this.deps.timing.observeIntervalMs,r-Date.now(),o))}}async abortUnregistered(e,t,r){try{let i=Date.now()+this.deps.timing.stopConfirmMs,o=pl(t,this.deps.timing.stopReadyMs);await this.awaitStopReady(e,t.abilityRecordId,o,i)==="ready"&&await this.deps.device.toggleOnce(e,void 0,r,Math.max(1,i-Date.now()))}catch(i){p(`abortUnregistered: best-effort stop failed: ${i.message}`)}}async finalizeLocked(e,t,r,i){let o=await this.deps.store.read(e),s=Dm(o,t,r);if(s.plan==="completed-elsewhere")return{kind:"completed-elsewhere"};if(s.plan==="error")throw s.error;let a=await this.readSnapshot(e),c=Rm(a);if(c.plan==="error")throw c.error;if(c.plan==="stop-recording"){let l=Date.now()+this.deps.timing.stopConfirmMs;return this.stopLiveRecording(e,t,i,l)}return this.retrieveAndPublish(e,t,i)}async stopLiveRecording(e,t,r,i){let o=pl(t,this.deps.timing.stopReadyMs);return await this.awaitStopReady(e,t.abilityRecordId,o,i)==="vanished"?this.retrieveAndPublish(e,t,r):(await r.assertOwned(),await this.deps.device.toggleOnce(e,void 0,r,Math.max(1,i-Date.now())),await this.waitForStopped(e,t.abilityRecordId,i),this.retrieveAndPublish(e,t,r))}async stopExternal(e,t,r){let i=await this.deps.device.observeOnce(e),o=Lm(i,t);if(o.plan==="already-stopped")return;if(o.plan==="error")throw o.error;let s=Date.now()+this.deps.timing.stopConfirmMs;o.startedAtMs!==void 0&&!await this.awaitForeignStopReady(e,o.currentId,o.startedAtMs,s)||(await r.assertOwned(),await this.deps.device.toggleOnce(e,void 0,r,Math.max(1,s-Date.now())),await this.waitForStopped(e,o.currentId,s))}async awaitForeignStopReady(e,t,r,i){let o=await this.withinDeadline(i,new w("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent"),c=>this.deps.device.readUptimeMs(e,c)),s=Om(o-r,this.deps.timing.stopReadyMs,Date.now());return await this.awaitStopReady(e,t,s,i)==="ready"}async retrieveAndPublish(e,t,r){let i=[],o=await this.waitForMediaUri(e,t.fileName),s=await Jm(t.localPath);try{let a=await this.receiveUntilValid(e,o,t,s,r,i);await r.assertOwned();let c=await Km(a,t.localPath);return await this.deleteSessionAfterSave(e,t,r,c),{kind:"saved",localPath:c,warnings:i}}finally{await Xm(s,t.localPath)}}async waitForMediaUri(e,t){let r=Date.now()+this.deps.timing.mediaReadyMs,i=0;for(;;){let o=r-Date.now();if(o<=0)throw new w("MEDIA_NOT_READY",`Timed out waiting for ${t} in the media library; session kept for a later stop`);let s=await this.withinDeadline(r,new w("MEDIA_NOT_READY",`Timed out waiting for ${t} in the media library; session kept for a later stop`),c=>this.deps.device.queryMediaUri(e,t,c));if(s&&Date.now()<=r)return s;let a=Math.min(this.deps.timing.mediaBackoffMs[Math.min(i,this.deps.timing.mediaBackoffMs.length-1)]??ef,ef,o);i+=1,await Mi(a)}}async receiveUntilValid(e,t,r,i,o,s){for(let a=0;a<this.deps.timing.mediaRecvAttempts;a++){await o.assertOwned();let c=jm(r.fileName,bs()),l=await this.receiveOnce(e,t,c,i,r.fileName,o,s);try{return await Ym(l),l}catch(d){if(d.code!=="MEDIA_NOT_READY")throw d;p(`Received file incomplete (attempt ${a+1}); retrying export`),await Mi(this.deps.timing.mediaBackoffMs[0]??250)}}throw new w("MEDIA_NOT_READY",`Received file for ${r.fileName} is incomplete after ${this.deps.timing.mediaRecvAttempts} attempts; session kept`)}async receiveOnce(e,t,r,i,o,s,a){let c=Qm.join(i,o);try{await this.deps.device.exportToStaging(e,t,r),await this.deps.device.receiveFile(e,r,c,s.signal)}finally{await this.deps.device.removeStaging(e,r)||a.push(`Failed to remove device staging file: ${r}`)}return c}async deleteSessionAfterSave(e,t,r,i){try{await this.deps.store.deleteIfSame(e,t,r)}catch(o){throw new w(o.code??"SESSION_DELETE_FAILED",`Recording saved to ${i}, but the session record could not be removed: ${o.message}. A later stop may create a recovered copy.`,{cause:o})}}async waitPoll(e,t){await new Promise(r=>{let i=setTimeout(()=>{t.delete(o),r()},this.deps.timing.foregroundPollMs),o=()=>{t.delete(o),clearTimeout(i),r()};t.add(o)})}};var Es={left:"0",right:"1",up:"2",down:"3"};function Le(n,e){let t=Number(n);if(!Number.isInteger(t)||t<=0)throw new Error(`${e} must be a positive integer`)}function vl(n,e){n!==void 0&&Le(n,e)}function rf(n,e){if(n===void 0!=(e===void 0))throw new Error("x and y must be provided together")}function Ps(n,e){if(n!==void 0&&n.length===0)throw new Error(`${e} must not be empty`)}function Oi(n){if(n===void 0)return;let e=Number(n);if(!Number.isInteger(e)||e<200||e>4e4)throw new Error("--speed must be an integer between 200 and 40000");return n}function nf(n){if(n!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(n))throw new Error("--window must consist of letters, digits, - or _")}function of(n,e,t,r=!0){if(t&&!e)throw new Error("--window must be used with --id");if(n&&e)throw new Error("Coordinates and --id are mutually exclusive");if(r&&!n&&!e)throw new Error("Either provide x y coordinates or use --id")}function Nn(n,e,t,r,i=!0){rf(n,e),Ps(t,"--id"),vl(n,"x"),vl(e,"y"),nf(r),of(n!==void 0,!!t,!!r,i)}async function Mt(n){let e=await C.new(),t=await et(e,n);return{hdcPath:e.hdcPath,deviceId:t}}async function Mn(n,e,t,r,i,o){if(t!==void 0&&r!==void 0)return{x:t,y:r};if(i===void 0)throw new Error("Either provide x y coordinates or use --id");let a=await new Bt(n,e).listWindows({all:!0}),c=new Zr(n);return JE(c,e,a,i,o)}async function JE(n,e,t,r,i){if(i!==void 0){let o=t.find(a=>String(a.id)===i);if(o&&o.displayId!==0)throw new S(`Window "${i}" is on display ${o.displayId}. The current command only supports operations on the primary display.`,"The current command only supports operations on the primary display.");let s=await n.dumpFullTree(e,0,i,!1);return KE(s,r)}return YE(n,e,t,r)}async function YE(n,e,t,r){let i=[...new Set(t.map(a=>a.displayId))],o=await n.dumpFullTreeByDisplays(e,0,i),s=[];for(let{displayId:a,tree:c}of o)for(let l of Tn([c],r))s.push({node:l,displayId:a});if(s.length===0)throw new S(`Node "${r}" not found.`,"Node not found.");if(s.length>1)throw new S(`Multiple nodes found with id "${r}".`,"Multiple nodes found");if(s[0].displayId!==0)throw new S(`Node "${r}" is on display ${s[0].displayId}. The current command only supports operations on the primary display.`,"The current command only supports operations on the primary display.");return sf(s[0].node,r)}function KE(n,e){let t=Tn(n,e);if(t.length===0)throw new S(`Node "${e}" not found.`,"Node not found.");if(t.length>1)throw new S(`Multiple nodes found with id "${e}".`,"Multiple nodes found");return sf(t[0],e)}function sf(n,e){let t=n.bounds;if(!t)throw new S(`Node "${e}" has no bounds.`,"Node has no bounds.");let[r,i,o,s]=t;return{x:Math.ceil((r+o)/2),y:Math.ceil((i+s)/2)}}async function lt(n,e,t){let r=["-t",e,"shell",...t];p(`Executing: ${n} ${r.join(" ")}`);let i=await re(n,r);if(i.exitCode!==0)throw new Error(i.stderr||i.stdout||`uitest exited with code ${i.exitCode}`);let o=i.stdout.toLowerCase();if(["illegal","fail","error","incorrect","please confirm that the coordinate values are correct"].some(a=>o.includes(a))&&!o.includes("no error"))throw new Error(i.stdout.trim()||"uitest command failed")}import{deflateSync as XE,inflateSync as ZE}from"zlib";import QE from"fs";var af=8,cf=32,eP=.06,tP=.04,wl=10,Cs=class n{whiteBits=null;blackBits=null;analyzeRgb(e,t,r){if(e<8||t<8||r.length<e*t*3)return null;let i=this.cropChrome(e,t,r),o=this.hashBits(i.width,i.height,i.rgb),s=Math.min(this.hammingDistance(o,this.solidRefBits(255)),this.hammingDistance(o,this.solidRefBits(0)));return{phash:this.bitsToHex(o),hamming:s,isBlank:s<=wl}}analyzeFile(e){let t;try{t=QE.readFileSync(e)}catch{return null}let r=this.decodePngRgb(t);return r?this.analyzeRgb(r.width,r.height,r.rgb):null}static encodePngRgb(e,t,r){let i=n.pngCrcTable(),o=[Buffer.from(`\x89PNG\r
|
|
61
|
+
${t}`:`Screenshot was not created on device: ${e.remotePath}.`)}async tryReceiveScreenshot(e,t,r){let i=["-t",e.serial,"file","recv",e.remotePath,r];p(`Executing: ${e.hdcPath} ${i.join(" ")}`);let o=await re(e.hdcPath,i);return o.exitCode!==0&&p(`hdc file recv failed: ${o.stderr||o.stdout||`exit code ${o.exitCode}`}`),XE(t,e.remotePath)}async receiveScreenshotFile(e){let t=Ve.mkdtempSync(De.join(De.dirname(e.localPath),".devecocli-screenshot-"));try{let r=await this.tryReceiveScreenshot(e,t,De.join(t,De.basename(e.remotePath)))??await this.tryReceiveScreenshot(e,t,t)??await this.tryReceiveScreenshot(e,t,De.join(t,"screenshot.png"));if(!r)throw new Error(`Screenshot file was not created in ${t}.`);ZE(r,e.localPath)}finally{Ve.rmSync(t,{recursive:!0,force:!0})}}async removeRemoteScreenshot(e){let t=["-t",e.serial,"shell","rm","-f",e.remotePath];p(`Executing: ${e.hdcPath} ${t.join(" ")}`),await re(e.hdcPath,t)}};import Af from"path";import{randomBytes as MP}from"crypto";import*as Ui from"fs";import*as Ym from"path";import{homedir as QE}from"os";var eP="deveco-cli",Jm,Rl=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function tP(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":tl(n))||Ym.join(QE(),".local","share",eP);try{return is(t)}catch(r){throw new Rl(r instanceof Error?r.message:String(r))}}function de(){if(Jm!==void 0)return Jm;let n=tP();try{if(Ui.existsSync(n))return Ui.realpathSync(n)}catch{}return n}async function nt(n,e){let r=await new yr(n).selectDevice(e);if(!r)throw new Error("No device selected. Use `devecocli device list` to see targets.");return r}var Bi="com.huawei.hmos.screenrecorder",rn="com.huawei.hmos.screenrecorder.ServiceExtAbility",Km="/data/local/tmp",w=class extends Error{constructor(t,r=t,i){super(r,i);this.code=t;this.name="ScreenRecordError"}};var Tl=/^\s*uri \[([^\]]*)\]\s*$/,rP=/^\s*uri \[/,nP=/AbilityRecord ID\s*[:#]\s*(\d+)/,iP=/start time \[(\d+)\]/,oP=/bundle name \[([^\]]*)\]/,sP=/main name \[([^\]]*)\]/,aP=/\[(?:Fail|E\d{5,})\]|^\s*(?:error|Error)(?::|\s)/m,cP=rn.slice(rn.lastIndexOf(".")+1);function lP(n){let e=[],t;for(let r of n.split(/\r?\n/))Tl.test(r)?(t=[r],e.push(t)):t&&t.push(r);return e}function dP(n){let e={};for(let t of n){let r=Tl.exec(t);if(r){e.uri=r[1].trim();continue}let i=nP.exec(t);if(i&&(e.id=Number(i[1]),!Number.isSafeInteger(e.id)))throw new w("DUMP_PARSE_FAILED",`Unparseable AbilityRecord ID in aa dump output: ${i[1]}`);let o=iP.exec(t);if(o){e.startedAtMs=Number(o[1]);continue}let s=oP.exec(t);if(s){e.bundleName=s[1].trim();continue}let a=sP.exec(t);a&&(e.mainName=a[1].trim())}return e}function Xm(n){let e=n.mainName;if((!n.bundleName||!e)&&n.uri){let t=n.uri.split("/").filter(Boolean);t.length>=3&&(n.bundleName??=t[0],e??=t[t.length-1])}return{bundleName:n.bundleName,abilityName:e}}function uP(n){let{bundleName:e,abilityName:t}=Xm(n);return e!==Bi||!t?!1:t===rn||t===cP}function pP(n){if(aP.test(n))throw new w("DUMP_PARSE_FAILED",`Unexpected aa dump output: ${n.trim().split(/\r?\n/)[0]??""}`);if(!n.includes("ExtensionRecords")&&!n.includes("AbilityRecord ID"))throw new w("DUMP_PARSE_FAILED","aa dump output has no recognizable extension-record structure");for(let t of n.split(/\r?\n/))if(rP.test(t)&&!Tl.test(t))throw new w("DUMP_PARSE_FAILED","aa dump output has an unterminated uri line; output may be truncated");let e=lP(n);if(e.length===0&&n.replace(/ExtensionRecords:\s*/,"").trim()!=="")throw new w("DUMP_PARSE_FAILED","aa dump output has no complete ability records; output may be truncated");return e}function Zm(n){if(!n.trim())throw new w("DUMP_PARSE_FAILED","aa dump output is empty; the device state is unknown");let e=new Map;for(let t of pP(n)){let r=dP(t);if(!uP(r))continue;if(r.id===void 0)throw new w("DUMP_PARSE_FAILED","Recorder ability block is missing its AbilityRecord ID");let{bundleName:i,abilityName:o}=Xm(r);e.set(r.id,{abilityRecordId:r.id,bundleName:i??Bi,abilityName:o??rn,startedAtMs:r.startedAtMs})}return[...e.values()]}function xl(n,e){if(n.length>1)throw new w("AMBIGUOUS_DEVICE_STATE",`Multiple screen recorder ability records: ${n.map(r=>r.abilityRecordId).join(", ")}`);let t=n[0];return t?{status:e?.abilityRecordId===t.abilityRecordId?"recording":"busy",activeId:t.abilityRecordId,session:e}:{status:"idle",session:e}}function nn(n,e){return!n||!e?n===e:n.fileName===e.fileName&&n.abilityRecordId===e.abilityRecordId&&n.startTime===e.startTime&&n.localPath===e.localPath}function Qm(n){return n.status==="recording"?{plan:"error",error:new w("CLI_RECORDING_ACTIVE","A CLI recording session is already running; run stop first")}:n.status==="busy"?{plan:"error",error:new w("EXTERNAL_RECORDING","A recording not started by this CLI is in progress; run stop --force first")}:n.session?{plan:"discard-first",session:n.session}:{plan:"start-new"}}function ef(n){return n.status==="idle"&&!n.session?{plan:"start-new"}:{plan:"error",error:new w("STATE_CHANGED","Device state changed while discarding the interrupted registration; not starting")}}function tf(n,e){return n.status==="busy"?e?{plan:"force-stop-external",activeId:n.activeId}:{plan:"error",error:new w("EXTERNAL_RECORDING","Recording was not started by this CLI. Stop it on the device or run stop --force.")}:n.session?{plan:"finalize-session",session:n.session}:{plan:"error",error:new w("NO_CLI_SESSION","No CLI recording session on this device")}}function rf(n,e,t){return nn(n,e)?{plan:"proceed"}:t==="interactive"?{plan:"completed-elsewhere"}:{plan:"error",error:new w("SESSION_CHANGED","The recording session changed; leaving the current one untouched")}}function nf(n){return n.status==="busy"?{plan:"error",error:new w("EXTERNAL_RECORDING","A recording not started by this CLI is in progress; not toggling")}:n.status==="recording"?{plan:"stop-recording"}:{plan:"retrieve"}}function of(n,e){if(n.length===0)return{outcome:"gone"};if(n.length>1)return{outcome:"error",error:new w("STATE_CHANGED","Multiple recorder records while confirming stop; not toggling again")};let t=n[0].abilityRecordId;return t!==e?{outcome:"error",error:new w("STATE_CHANGED",`A different recording (ID ${t}) appeared while stopping; leaving it alone`)}:{outcome:"still-recording",activeId:t}}function sf(n){return n.length===1?{outcome:"confirmed",record:n[0]}:n.length>1?{outcome:"error",error:new w("AMBIGUOUS_DEVICE_STATE","Multiple recorder records after start; refusing to pick one")}:{outcome:"pending"}}function af(n,e){if(n.length===0)return{plan:"already-stopped"};if(n.length>1)return{plan:"error",error:new w("AMBIGUOUS_DEVICE_STATE","Multiple recorder records; refusing to force-stop")};let t=n[0];return e!==void 0&&t.abilityRecordId!==e?{plan:"error",error:new w("STATE_CHANGED","The recording changed while stopping; leaving it alone")}:{plan:"stop",currentId:t.abilityRecordId,startedAtMs:t.startedAtMs}}function cf(n){return n.status==="idle"&&n.session?{status:"idle",note:"interrupted session found; retrievable via ui screenrecord stop"}:{status:n.status}}function lf(n,e){return!nn(n.session,e)||n.status!=="recording"}function Ll(n,e){return n.startTime+e}function df(n,e,t){return t+Math.max(0,e-n)}import vr from"fs";import gf from"path";import{randomBytes as gP}from"crypto";import{lock as yP}from"proper-lockfile";import Wi from"path";var mP=/^[A-Za-z0-9][A-Za-z0-9.-]*\.mp4$/;function On(n){return Buffer.from(n,"utf8").toString("hex")}function on(n,e){return String(n).padStart(e,"0")}function uf(n){return`${on(n.getFullYear(),4)}${on(n.getMonth()+1,2)}${on(n.getDate(),2)}-${on(n.getHours(),2)}${on(n.getMinutes(),2)}${on(n.getSeconds(),2)}${on(n.getMilliseconds(),3)}`}function fP(n){return n.replace(/[<>:"/\\|?*\u0000-\u001f]/g,"-").replace(/\s+/g," ").trim().replace(/[. ]+$/,"").replace(/^[. ]+/,"")||"device"}function pf(n,e){if(!/^[a-z0-9]{4}$/.test(e))throw new w("INVALID_RECORDING_PATH",`Internal: bad random suffix ${JSON.stringify(e)}`);return`devecocli-${uf(n)}-${e}.mp4`}function mf(n,e,t){return`${fP(n)}-${uf(e)}-${t}.mp4`}function ff(n,e){if(!mP.test(n))throw new w("INVALID_RECORDING_PATH",`Unsafe device file name: ${JSON.stringify(n)}`);return`${Km}/devecocli-${e}-${n}`}var hP=20;function hf(n){let e=Wi.dirname(n),t=Wi.extname(n),r=Wi.basename(n,t),i=[n];i.push(Wi.join(e,`${r}-recovered${t}`));for(let o=2;o<hP;o++)i.push(Wi.join(e,`${r}-recovered-${o}${t}`));return i}var vP=5*6e4,wP=5*6e4,SP=1e4,bP=6e4,Nl=200;function EP(n){if(!Number.isInteger(n)||n<=0)return"unknown";try{return process.kill(n,0),"alive"}catch(e){let t=e.code;return t==="ESRCH"?"dead":t==="EPERM"?"alive":"unknown"}}function yf(n){return new Promise(e=>setTimeout(e,n))}function PP(){return gP(8).toString("hex")}async function vf(n){let e;try{e=await vr.promises.readFile(n,"utf8")}catch{return}try{let t=JSON.parse(e);return typeof t.token=="string"?t.token:void 0}catch{return}}var Ts=class{constructor(e,t={}){this.recordDir=e;this.releaseGuardWaitMs=t.releaseGuardWaitMs??SP}releaseGuardWaitMs;lockPath(e){return gf.join(this.recordDir,`${On(e)}.lock`)}guardPath(e){return gf.join(this.recordDir,`${On(e)}.guard`)}async withDeviceLock(e,t,r=bP){let i=await this.acquire(e,r),o;try{o=await t(i)}catch(s){try{await this.releaseOwned(e,i)}catch(a){p(`lock release failed after action error: ${a.message}`)}throw s}return await this.releaseOwned(e,i),o}async withGuard(e,t,r=0){let i=Date.now()+r;for(;;){let o;try{o=await yP(this.guardPath(e),{realpath:!1,stale:vP,update:1e3,retries:0})}catch(s){if(s.code!=="ELOCKED"||Date.now()>=i)throw s;await yf(Math.min(Nl,i-Date.now()));continue}try{return await t()}finally{await o()}}}async acquire(e,t){await vr.promises.mkdir(this.recordDir,{recursive:!0});let r=PP(),i=this.lockPath(e),o=Date.now()+t;for(;;){let s=!1;try{await this.withGuard(e,async()=>{s=await this.tryCreateOrReclaim(i,r)})}catch(a){if(a.code!=="ELOCKED")throw a}if(s)return this.buildLease(i,r);if(Date.now()+Nl>o)throw new w("LOCK_BUSY",`Timed out waiting ${t}ms for the device lock (${e})`);await yf(Nl)}}async tryCreateOrReclaim(e,t){let r;try{r=await vr.promises.open(e,"wx")}catch(i){if(i.code!=="EEXIST")throw i;return await this.reclaimIfDead(e),!1}try{let i={pid:process.pid,createdAt:Date.now(),token:t};await r.writeFile(JSON.stringify(i)),await r.sync()}finally{await r.close()}return!0}async reclaimIfDead(e){let t,r;try{t=await vr.promises.readFile(e,"utf8"),r=await vr.promises.stat(e)}catch(o){if(o.code==="ENOENT")return;throw o}let i;try{let o=JSON.parse(t);typeof o.pid=="number"&&typeof o.createdAt=="number"&&typeof o.token=="string"&&(i=o)}catch{}if(i){EP(i.pid)==="dead"&&await vr.promises.unlink(e);return}Date.now()-r.mtimeMs>wP&&await vr.promises.unlink(e)}buildLease(e,t){let r=new AbortController;return{token:t,signal:r.signal,assertOwned:async()=>{if(await vf(e)!==t)throw r.abort(),new w("LOCK_LOST","Lost the device lock; aborting this operation")}}}async releaseOwned(e,t){let r=this.lockPath(e);try{await this.withGuard(e,async()=>{await vf(r)===t.token&&await vr.promises.unlink(r)},this.releaseGuardWaitMs)}catch(i){throw new w("LOCK_RELEASE_FAILED",`Could not release the device lock (${e}): ${i.message}. The lock stays in place; it is reclaimed by the dead-PID or corrupt-age rule once this process exits.`,{cause:i})}}};import{execa as CP}from"execa";var Ml=15e3,wf=10*6e4,kP=3,Sf=400;function IP(n){return new Promise(e=>setTimeout(e,n))}function DP(n){return async(e,t)=>{p(`Executing: ${n} ${e.join(" ")}`);let r=await CP(n,e,{reject:!1,timeout:t.timeoutMs??Ml,cancelSignal:t.signal,stdout:"pipe",stderr:"pipe"});return{stdout:typeof r.stdout=="string"?r.stdout:"",stderr:typeof r.stderr=="string"?r.stderr:"",exitCode:r.exitCode??-1}}}var xs=class n{runner;constructor(e){this.runner=DP(e)}async runReadOnly(e,t){let r={stdout:"",stderr:"",exitCode:-1},i=t!==void 0?Date.now()+t:void 0;for(let o=0;o<kP;o++){let s=i!==void 0?i-Date.now():void 0;r=await this.runner(e,s===void 0?{}:{timeoutMs:Math.max(1,s)});let a=`${r.stdout}
|
|
62
|
+
${r.stderr}`;if(r.exitCode===0||bt(a)!=="transient")return r;if(i!==void 0&&Date.now()+Sf>i)break;await IP(Sf)}return r}static assertUsable(e,t){let r=`${e.stdout}
|
|
63
|
+
${e.stderr}`.trim();if(e.exitCode!==0||bt(r)!=="ok")throw new w(t,`hdc command failed (exit ${e.exitCode}): ${r.split(`
|
|
64
|
+
`)[0]??""}`)}async observeOnce(e,t){let r=await this.runReadOnly(["-t",e,"shell","aa","dump","-e"],t);return n.assertUsable(r,"DUMP_PARSE_FAILED"),Zm(r.stdout)}async readUptimeMs(e,t){let r=await this.runReadOnly(["-t",e,"shell","cat","/proc/uptime"],t);n.assertUsable(r,"DUMP_PARSE_FAILED");let i=Number(/^([\d.]+)/.exec(r.stdout.trim())?.[1]);if(!Number.isFinite(i)||i<=0)throw new w("DUMP_PARSE_FAILED",`Unparseable /proc/uptime output: ${r.stdout.trim().split(`
|
|
65
|
+
`)[0]??""}`);return Math.round(i*1e3)}async toggleOnce(e,t,r,i){await r.assertOwned();let o=["-t",e,"shell","aa","start","-b",Bi,"-a",rn];t!==void 0&&o.push("--ps","CustomizedFileName",t);try{let s=await this.runner(o,{timeoutMs:i??Ml,signal:r.signal});return s.exitCode!==0?(p(`aa start exited ${s.exitCode}: ${s.stderr||s.stdout}`),{transport:"uncertain",stdout:s.stdout,stderr:s.stderr}):{transport:"returned",stdout:s.stdout,stderr:s.stderr}}catch(s){return p(`aa start transport failure: ${s.message}`),{transport:"uncertain",stderr:s.message}}}async queryMediaUri(e,t,r){let i=await this.runReadOnly(["-t",e,"shell","mediatool","query",t,"-u"],r);n.assertUsable(i,"MEDIA_QUERY_FAILED");let o=/find\s+(\d+)\s+result/i.exec(i.stdout);if(!o)throw new w("MEDIA_QUERY_FAILED",`Unparseable mediatool query output: ${i.stdout.trim().split(`
|
|
66
|
+
`)[0]??""}`);let s=[...i.stdout.matchAll(/"(file:\/\/[^"]+)"/g)].map(c=>c[1]),a=Number(o[1]);if(a!==0){if(a>1||s.length>1)throw new w("MEDIA_AMBIGUOUS",`mediatool returned ${a} entries for ${t}`);if(s.length!==1)throw new w("MEDIA_QUERY_FAILED",`mediatool reported 1 entry but no URI for ${t}`);return s[0]}}async exportToStaging(e,t,r){let i=await this.runner(["-t",e,"shell","mediatool","recv",t,r],{timeoutMs:wf});if(n.assertUsable(i,"SAVE_FAILED"),!i.stdout.includes(r))throw new w("SAVE_FAILED",`mediatool recv did not confirm ${r}: ${i.stdout.trim().split(`
|
|
67
|
+
`)[0]??""}`)}async receiveFile(e,t,r,i){let o=await this.runner(["-t",e,"file","recv",t,r],{timeoutMs:wf,signal:i});if(o.exitCode!==0)throw new w("SAVE_FAILED",`hdc file recv failed (exit ${o.exitCode}): ${(o.stderr||o.stdout).split(`
|
|
68
|
+
`)[0]??""}`)}async removeStaging(e,t){return(await this.runReadOnly(["-t",e,"shell","rm","-f",t],Ml)).exitCode===0}};import zt from"fs";import Ft from"path";import{createFile as AP}from"mp4box";var Ef=".devecocli-record-";function _n(n,e){return new w("INVALID_RECORDING_PATH",e instanceof Error?`${n}: ${e.message}`:n,e instanceof Error?{cause:e}:void 0)}async function Ol(n){try{return{stat:await zt.promises.stat(n)}}catch(e){let t=e.code;return t==="ENOENT"?null:{code:t??"UNKNOWN"}}}async function bf(n){let e=await Ol(n);if(!e)throw _n(`Directory does not exist: ${n}`);if("code"in e)throw _n(`Directory is not accessible: ${n}`);if(!e.stat.isDirectory())throw _n(`Path is not a directory: ${n}`);try{await zt.promises.access(n,zt.constants.W_OK)}catch(t){throw _n(`Directory is not writable: ${n}`,t)}}async function _l(n){if(await Ol(n))throw new w("DESTINATION_EXISTS",`Destination already exists: ${n}`)}async function Fl(n,e,t,r){if(!n?.trim())throw _n("--path is required.");let i=Ft.resolve(n.trim()),o=await Ol(i);if(o&&"stat"in o&&o.stat.isDirectory()){await bf(i);let a=Ft.join(i,mf(e,t,r));return await _l(a),a}if(o)throw new w("DESTINATION_EXISTS",`Destination already exists: ${i}`);if(Ft.extname(i).toLowerCase()!==".mp4")throw _n(`Destination must be an existing directory or a new .mp4 file: ${i}`);let s=Ft.dirname(i);return await bf(s),i}async function Pf(n){return zt.promises.mkdtemp(Ft.join(Ft.dirname(n),Ef))}var RP=4*1024*1024;async function TP(n){let e=await zt.promises.open(n,"r");try{let{size:t}=await e.stat(),r=AP(),i=0;for(let s=0;s<t;){let a=Math.min(RP,t-s),c=Buffer.alloc(a),{bytesRead:l}=await e.read(c,0,a,s);if(l<=0)break;let d=c.buffer.slice(c.byteOffset,c.byteOffset+l);d.fileStart=s,i=r.appendBuffer(d,s+l>=t),s+=l}r.flush();let o=r.getBox("moov");return{size:t,complete:i===t,hasMovieHeader:o?.mvhd!==void 0,videoTrackCount:o?.mvhd!==void 0?r.getInfo().videoTracks.length:0}}finally{await e.close()}}async function Cf(n){let e;try{e=await TP(n)}catch(t){throw new w("SAVE_FAILED",`Cannot inspect received file: ${t.message}`,{cause:t})}if(e.size===0)throw new w("MEDIA_NOT_READY","Received file is empty");if(!e.complete||!e.hasMovieHeader)throw new w("MEDIA_NOT_READY","Received file is not a complete MP4");if(e.videoTrackCount<1)throw new w("MEDIA_NOT_READY","Received file has no video track");return e.size}async function xP(n){let e=await zt.promises.open(n,"r+");try{await e.sync()}finally{await e.close()}}async function LP(n){try{let e=await zt.promises.open(Ft.dirname(n),"r");try{await e.sync()}finally{await e.close()}}catch{}}async function kf(n,e){await xP(n);for(let t of hf(e))try{return await zt.promises.link(n,t),await LP(t),t}catch(r){if(r.code==="EEXIST")continue;throw new w("SAVE_FAILED",`Cannot publish recording to ${t}: ${r.message}`,{cause:r})}throw new w("DESTINATION_UNAVAILABLE",`All recovery names are taken near ${e}`)}async function If(n,e){let t=Ft.dirname(e),r=Ft.basename(n);Ft.dirname(n)!==t||!r.startsWith(Ef)||await zt.promises.rm(n,{recursive:!0,force:!0}).catch(()=>{})}import Jt from"fs";import Ls from"path";import{randomBytes as NP}from"crypto";function Df(n,e){let t=n,r=i=>new w("SESSION_CORRUPT",`Invalid recording session ${i} in ${e}`);if(!t||typeof t!="object")throw r("object");if(typeof t.fileName!="string"||t.fileName.length===0||t.fileName!==Ls.basename(t.fileName)||t.fileName.includes(".."))throw r("fileName");if(typeof t.abilityRecordId!="number"||!Number.isSafeInteger(t.abilityRecordId)||t.abilityRecordId<=0)throw r("abilityRecordId");if(typeof t.startTime!="number"||!Number.isFinite(t.startTime))throw r("startTime");if(typeof t.localPath!="string"||t.localPath.length===0||!Ls.isAbsolute(t.localPath))throw r("localPath");return{fileName:t.fileName,abilityRecordId:t.abilityRecordId,startTime:t.startTime,localPath:t.localPath}}var Ns=class{constructor(e){this.recordDir=e}sessionPath(e){return Ls.join(this.recordDir,`${On(e)}.json`)}async read(e){let t=this.sessionPath(e),r;try{r=await Jt.promises.readFile(t,"utf8")}catch(o){if(o.code==="ENOENT")return;throw new w("SESSION_CORRUPT",`Cannot read recording session: ${o.message}`,{cause:o})}let i;try{i=JSON.parse(r)}catch(o){throw new w("SESSION_CORRUPT",`Recording session file is not valid JSON: ${t}`,{cause:o})}return Df(i,t)}async createAtomic(e,t,r){await Jt.promises.mkdir(this.recordDir,{recursive:!0});let i=this.sessionPath(e),o=Ls.join(this.recordDir,`${On(e)}.${NP(6).toString("hex")}.tmp`),s=JSON.stringify(Df(t,"input")),a;try{a=await Jt.promises.open(o,"wx")}catch(c){throw new w("SESSION_PUBLISH_FAILED",`Cannot create session temp file: ${c.message}`,{cause:c})}try{await a.writeFile(s),await a.sync()}catch(c){throw await a.close().catch(()=>{}),await Jt.promises.unlink(o).catch(()=>{}),new w("SESSION_PUBLISH_FAILED",`Cannot write session temp file: ${c.message}`,{cause:c})}await a.close();try{if(await r.assertOwned(),await this.exists(i))throw new w("SESSION_CHANGED",`A recording session was created concurrently for ${e}`);await Jt.promises.link(o,i),await this.syncDir()}finally{await Jt.promises.unlink(o).catch(()=>{})}}async deleteIfSame(e,t,r){await r.assertOwned();let i=await this.read(e);if(i){if(!nn(i,t))throw new w("SESSION_CHANGED","The recording session changed hands; leaving the new record untouched");await Jt.promises.unlink(this.sessionPath(e)),await this.syncDir()}}async exists(e){try{return await Jt.promises.lstat(e),!0}catch{return!1}}async syncDir(){try{let e=await Jt.promises.open(this.recordDir,"r");try{await e.sync()}finally{await e.close()}}catch{}}};var OP={startConfirmMs:1e4,stopConfirmMs:15e3,stopReadyMs:3e3,observeIntervalMs:250,foregroundPollMs:1e3,mediaReadyMs:3e4,mediaBackoffMs:[250,500,1e3,2e3],mediaRecvAttempts:3,lockWaitMs:6e4,interactiveLockWaitMs:10*6e4,foregroundFailureBudget:3},Rf=4e3;function Vi(n){return new Promise(e=>setTimeout(e,n))}function Ms(){return MP(2).toString("hex")}var Tf=["SIGINT","SIGTERM","SIGHUP"];function _P(n){let e=()=>{n.requested||(n.requested=!0,n.wake())};for(let t of Tf)process.on(t,e);return()=>{for(let t of Tf)process.off(t,e)}}var wr=class{constructor(e,t={}){this.toolProvider=e;let r=Af.join(de(),"record");this.deps={store:t.store??new Ns(r),lock:t.lock??new Ts(r),device:t.device??new xs(e.hdcPath),timing:{...OP,...t.timing}}}deps;async startDetached(e,t){let r=await this.resolveTarget(e),i=await Fl(t,r.name,new Date,Ms());return this.startSession(r,i)}async recordInteractively(e,t,r){let i=new Set,o={requested:!1,wake:()=>{for(let a of i)a()}},s=_P(o);try{let a=await this.resolveTarget(e),c=await Fl(t,a.name,new Date,Ms()),l=await this.startSession(a,c);return r.onStarted(),await this.waitForInteractiveCompletion(l,o,i)}finally{s()}}async waitForInteractiveCompletion(e,t,r){let i,o=()=>(i??=this.deps.lock.withDeviceLock(e.serial,a=>this.finalizeLocked(e.serial,e.session,"interactive",a),this.deps.timing.interactiveLockWaitMs),i),s=0;for(;;){if(t.requested)return await o();let a;try{a=await this.readSnapshot(e.serial),s=0}catch(c){if(s+=1,s>=this.deps.timing.foregroundFailureBudget)throw c;await this.waitPoll(t,r);continue}if(lf(a,e.session))return await o();await this.waitPoll(t,r)}}async stopRecording(e,t){let r=await this.resolveTarget(e);return this.deps.lock.withDeviceLock(r.serial,async i=>{let o=await this.readSnapshot(r.serial),s=tf(o,t);if(s.plan==="force-stop-external")return await this.stopExternal(r.serial,s.activeId,i),{kind:"external-stopped"};if(s.plan==="error")throw s.error;return this.finalizeLocked(r.serial,s.session,"stop-or-recover",i)},this.deps.timing.lockWaitMs)}async getRecordingStatus(e){let t=await this.resolveTarget(e);for(let r=0;r<3;r++){let i=await this.deps.store.read(t.serial),o=await this.deps.device.observeOnce(t.serial),s=await this.deps.store.read(t.serial);if(!nn(i,s))continue;let a=xl(o,s);return cf(a)}throw new w("STATE_CHANGING","The recording session keeps changing; try again")}async resolveTarget(e){let t=await nt(this.toolProvider,e),i=(await ne.from(this.toolProvider).getConnectedEntries()).find(o=>o.serial===t);if(i?.isEmulator)throw new w("EMULATOR_NOT_SUPPORTED","Screen recording is only supported on physical devices");return{serial:t,name:i?.name??t}}async readSnapshot(e){let t=await this.deps.store.read(e),r=await this.deps.device.observeOnce(e);return xl(r,t)}async startSession(e,t){return this.deps.lock.withDeviceLock(e.serial,r=>this.startSessionLocked(e,t,r),this.deps.timing.lockWaitMs)}async startSessionLocked(e,t,r){let i=await this.readSnapshot(e.serial),o=Qm(i);if(o.plan==="error")throw o.error;if(o.plan==="discard-first"){await this.deps.store.deleteIfSame(e.serial,o.session,r);let s=await this.readSnapshot(e.serial),a=ef(s);if(a.plan==="error")throw a.error}return this.toggleAndRegister(e,t,r)}async toggleAndRegister(e,t,r){await _l(t);let i=pf(new Date,Ms()),o=Date.now(),s=Date.now()+this.deps.timing.startConfirmMs;await r.assertOwned(),await this.deps.device.toggleOnce(e.serial,i,r,Math.max(1,s-Date.now()));let a=await this.waitForStarted(e.serial,s),c={fileName:i,abilityRecordId:a.abilityRecordId,startTime:o,localPath:t};return await this.registerSession(e.serial,c,r),{serial:e.serial,session:c}}async registerSession(e,t,r){try{await this.deps.store.createAtomic(e,t,r)}catch(i){throw await this.abortUnregistered(e,t,r),new w(i.code??"SESSION_PUBLISH_FAILED",`Recording started on device (file ${t.fileName}) but could not be registered: ${i.message}. Check the device gallery.`,{cause:i})}}async withinDeadline(e,t,r){try{return await r(Math.max(1,e-Date.now()))}catch(i){throw Date.now()>=e?t:i}}async waitForStarted(e,t){for(;;){let r=t-Date.now();if(r<=0)throw new w("START_CONFIRM_TIMEOUT","Device screen may be locked");let i=await this.withinDeadline(t,new w("START_CONFIRM_TIMEOUT","Device screen may be locked"),s=>this.deps.device.observeOnce(e,s)),o=sf(i);if(o.outcome==="error")throw o.error;if(o.outcome==="confirmed"){if(Date.now()>t)throw new w("START_CONFIRM_TIMEOUT","Device screen may be locked");return o.record}await Vi(Math.min(this.deps.timing.observeIntervalMs,r))}}async observeActiveId(e,t,r){let i=await this.deps.device.observeOnce(e,r),o=of(i,t);if(o.outcome==="error")throw o.error;return o.outcome==="gone"?void 0:o.activeId}async waitForStopped(e,t,r){for(;;){let i=r-Date.now();if(i<=0)throw new w("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent");if(await this.withinDeadline(r,new w("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent"),s=>this.observeActiveId(e,t,s))===void 0)return;await Vi(Math.min(this.deps.timing.observeIntervalMs,i))}}async awaitStopReady(e,t,r,i){for(;;){let o=i-Date.now();if(o<=0)throw new w("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent");if(await this.withinDeadline(i,new w("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent"),a=>this.observeActiveId(e,t,a))===void 0)return"vanished";if(Date.now()>=r){if(Date.now()>i)throw new w("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent");return"ready"}await Vi(Math.min(this.deps.timing.observeIntervalMs,r-Date.now(),o))}}async abortUnregistered(e,t,r){try{let i=Date.now()+this.deps.timing.stopConfirmMs,o=Ll(t,this.deps.timing.stopReadyMs);await this.awaitStopReady(e,t.abilityRecordId,o,i)==="ready"&&await this.deps.device.toggleOnce(e,void 0,r,Math.max(1,i-Date.now()))}catch(i){p(`abortUnregistered: best-effort stop failed: ${i.message}`)}}async finalizeLocked(e,t,r,i){let o=await this.deps.store.read(e),s=rf(o,t,r);if(s.plan==="completed-elsewhere")return{kind:"completed-elsewhere"};if(s.plan==="error")throw s.error;let a=await this.readSnapshot(e),c=nf(a);if(c.plan==="error")throw c.error;if(c.plan==="stop-recording"){let l=Date.now()+this.deps.timing.stopConfirmMs;return this.stopLiveRecording(e,t,i,l)}return this.retrieveAndPublish(e,t,i)}async stopLiveRecording(e,t,r,i){let o=Ll(t,this.deps.timing.stopReadyMs);return await this.awaitStopReady(e,t.abilityRecordId,o,i)==="vanished"?this.retrieveAndPublish(e,t,r):(await r.assertOwned(),await this.deps.device.toggleOnce(e,void 0,r,Math.max(1,i-Date.now())),await this.waitForStopped(e,t.abilityRecordId,i),this.retrieveAndPublish(e,t,r))}async stopExternal(e,t,r){let i=await this.deps.device.observeOnce(e),o=af(i,t);if(o.plan==="already-stopped")return;if(o.plan==="error")throw o.error;let s=Date.now()+this.deps.timing.stopConfirmMs;o.startedAtMs!==void 0&&!await this.awaitForeignStopReady(e,o.currentId,o.startedAtMs,s)||(await r.assertOwned(),await this.deps.device.toggleOnce(e,void 0,r,Math.max(1,s-Date.now())),await this.waitForStopped(e,o.currentId,s))}async awaitForeignStopReady(e,t,r,i){let o=await this.withinDeadline(i,new w("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent"),c=>this.deps.device.readUptimeMs(e,c)),s=df(o-r,this.deps.timing.stopReadyMs,Date.now());return await this.awaitStopReady(e,t,s,i)==="ready"}async retrieveAndPublish(e,t,r){let i=[],o=await this.waitForMediaUri(e,t.fileName),s=await Pf(t.localPath);try{let a=await this.receiveUntilValid(e,o,t,s,r,i);await r.assertOwned();let c=await kf(a,t.localPath);return await this.deleteSessionAfterSave(e,t,r,c),{kind:"saved",localPath:c,warnings:i}}finally{await If(s,t.localPath)}}async waitForMediaUri(e,t){let r=Date.now()+this.deps.timing.mediaReadyMs,i=0;for(;;){let o=r-Date.now();if(o<=0)throw new w("MEDIA_NOT_READY",`Timed out waiting for ${t} in the media library; session kept for a later stop`);let s=await this.withinDeadline(r,new w("MEDIA_NOT_READY",`Timed out waiting for ${t} in the media library; session kept for a later stop`),c=>this.deps.device.queryMediaUri(e,t,c));if(s&&Date.now()<=r)return s;let a=Math.min(this.deps.timing.mediaBackoffMs[Math.min(i,this.deps.timing.mediaBackoffMs.length-1)]??Rf,Rf,o);i+=1,await Vi(a)}}async receiveUntilValid(e,t,r,i,o,s){for(let a=0;a<this.deps.timing.mediaRecvAttempts;a++){await o.assertOwned();let c=ff(r.fileName,Ms()),l=await this.receiveOnce(e,t,c,i,r.fileName,o,s);try{return await Cf(l),l}catch(d){if(d.code!=="MEDIA_NOT_READY")throw d;p(`Received file incomplete (attempt ${a+1}); retrying export`),await Vi(this.deps.timing.mediaBackoffMs[0]??250)}}throw new w("MEDIA_NOT_READY",`Received file for ${r.fileName} is incomplete after ${this.deps.timing.mediaRecvAttempts} attempts; session kept`)}async receiveOnce(e,t,r,i,o,s,a){let c=Af.join(i,o);try{await this.deps.device.exportToStaging(e,t,r),await this.deps.device.receiveFile(e,r,c,s.signal)}finally{await this.deps.device.removeStaging(e,r)||a.push(`Failed to remove device staging file: ${r}`)}return c}async deleteSessionAfterSave(e,t,r,i){try{await this.deps.store.deleteIfSame(e,t,r)}catch(o){throw new w(o.code??"SESSION_DELETE_FAILED",`Recording saved to ${i}, but the session record could not be removed: ${o.message}. A later stop may create a recovered copy.`,{cause:o})}}async waitPoll(e,t){await new Promise(r=>{let i=setTimeout(()=>{t.delete(o),r()},this.deps.timing.foregroundPollMs),o=()=>{t.delete(o),clearTimeout(i),r()};t.add(o)})}};var Os={left:"0",right:"1",up:"2",down:"3"};function Ne(n,e){let t=Number(n);if(!Number.isInteger(t)||t<=0)throw new Error(`${e} must be a positive integer`)}function $l(n,e){n!==void 0&&Ne(n,e)}function xf(n,e){if(n===void 0!=(e===void 0))throw new Error("x and y must be provided together")}function _s(n,e){if(n!==void 0&&n.length===0)throw new Error(`${e} must not be empty`)}function Gi(n){if(n===void 0)return;let e=Number(n);if(!Number.isInteger(e)||e<200||e>4e4)throw new Error("--speed must be an integer between 200 and 40000");return n}function Lf(n){if(n!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(n))throw new Error("--window must consist of letters, digits, - or _")}function Nf(n,e,t,r=!0){if(t&&!e)throw new Error("--window must be used with --id");if(n&&e)throw new Error("Coordinates and --id are mutually exclusive");if(r&&!n&&!e)throw new Error("Either provide x y coordinates or use --id")}function Fn(n,e,t,r,i=!0){xf(n,e),_s(t,"--id"),$l(n,"x"),$l(e,"y"),Lf(r),Nf(n!==void 0,!!t,!!r,i)}async function $t(n){let e=await C.new(),t=await nt(e,n);return{hdcPath:e.hdcPath,deviceId:t}}async function $n(n,e,t,r,i,o){if(t!==void 0&&r!==void 0)return{x:t,y:r};if(i===void 0)throw new Error("Either provide x y coordinates or use --id");let a=await new qt(n,e).listWindows({all:!0}),c=new en(n);return FP(c,e,a,i,o)}async function FP(n,e,t,r,i){if(i!==void 0){let o=t.find(a=>String(a.id)===i);if(o&&o.displayId!==0)throw new S(`Window "${i}" is on display ${o.displayId}. The current command only supports operations on the primary display.`,"The current command only supports operations on the primary display.");let s=await n.dumpFullTree(e,0,i,!1);return jP(s,r)}return $P(n,e,t,r)}async function $P(n,e,t,r){let i=[...new Set(t.map(a=>a.displayId))],o=await n.dumpFullTreeByDisplays(e,0,i),s=[];for(let{displayId:a,tree:c}of o)for(let l of Mn([c],r))s.push({node:l,displayId:a});if(s.length===0)throw new S(`Node "${r}" not found.`,"Node not found.");if(s.length>1)throw new S(`Multiple nodes found with id "${r}".`,"Multiple nodes found");if(s[0].displayId!==0)throw new S(`Node "${r}" is on display ${s[0].displayId}. The current command only supports operations on the primary display.`,"The current command only supports operations on the primary display.");return Mf(s[0].node,r)}function jP(n,e){let t=Mn(n,e);if(t.length===0)throw new S(`Node "${e}" not found.`,"Node not found.");if(t.length>1)throw new S(`Multiple nodes found with id "${e}".`,"Multiple nodes found");return Mf(t[0],e)}function Mf(n,e){let t=n.bounds;if(!t)throw new S(`Node "${e}" has no bounds.`,"Node has no bounds.");let[r,i,o,s]=t;return{x:Math.ceil((r+o)/2),y:Math.ceil((i+s)/2)}}async function pt(n,e,t){let r=["-t",e,"shell",...t];p(`Executing: ${n} ${r.join(" ")}`);let i=await re(n,r);if(i.exitCode!==0)throw new Error(i.stderr||i.stdout||`uitest exited with code ${i.exitCode}`);let o=i.stdout.toLowerCase();if(["illegal","fail","error","incorrect","please confirm that the coordinate values are correct"].some(a=>o.includes(a))&&!o.includes("no error"))throw new Error(i.stdout.trim()||"uitest command failed")}import{deflateSync as HP,inflateSync as UP}from"zlib";import BP from"fs";var Of=8,_f=32,WP=.06,VP=.04,jl=10,Fs=class n{whiteBits=null;blackBits=null;analyzeRgb(e,t,r){if(e<8||t<8||r.length<e*t*3)return null;let i=this.cropChrome(e,t,r),o=this.hashBits(i.width,i.height,i.rgb),s=Math.min(this.hammingDistance(o,this.solidRefBits(255)),this.hammingDistance(o,this.solidRefBits(0)));return{phash:this.bitsToHex(o),hamming:s,isBlank:s<=jl}}analyzeFile(e){let t;try{t=BP.readFileSync(e)}catch{return null}let r=this.decodePngRgb(t);return r?this.analyzeRgb(r.width,r.height,r.rgb):null}static encodePngRgb(e,t,r){let i=n.pngCrcTable(),o=[Buffer.from(`\x89PNG\r
|
|
68
69
|
|
|
69
|
-
`,"binary")],s=Buffer.alloc(13);s.writeUInt32BE(e,0),s.writeUInt32BE(t,4),s[8]=8,s[9]=2,o.push(n.pngChunk("IHDR",s,i));let a=Buffer.alloc((e*3+1)*t);for(let c=0;c<t;c++)a[c*(e*3+1)]=0,Buffer.from(r.buffer,r.byteOffset+c*e*3,e*3).copy(a,c*(e*3+1)+1);return o.push(n.pngChunk("IDAT",
|
|
70
|
+
`,"binary")],s=Buffer.alloc(13);s.writeUInt32BE(e,0),s.writeUInt32BE(t,4),s[8]=8,s[9]=2,o.push(n.pngChunk("IHDR",s,i));let a=Buffer.alloc((e*3+1)*t);for(let c=0;c<t;c++)a[c*(e*3+1)]=0,Buffer.from(r.buffer,r.byteOffset+c*e*3,e*3).copy(a,c*(e*3+1)+1);return o.push(n.pngChunk("IDAT",HP(a),i)),o.push(n.pngChunk("IEND",Buffer.alloc(0),i)),Buffer.concat(o)}cropChrome(e,t,r){let i=Math.floor(t*WP),o=Math.floor(t*(1-VP));if(o<=i+8)return{width:e,height:t,rgb:r};let s=o-i,a=new Uint8Array(e*s*3);for(let c=0;c<s;c++){let l=(i+c)*e*3;a.set(r.subarray(l,l+e*3),c*e*3)}return{width:e,height:s,rgb:a}}hashBits(e,t,r){let i=this.toGray(e,t,r),o=this.resizeGray(i,_f,_f),s=this.dct2(o),a=[];for(let d=0;d<Of;d++)a.push(s[d].slice(0,Of));let c=this.stabilizeDct(a),l=this.median(c);return c.map(d=>d>l)}solidRefBits(e){return e===255?this.whiteBits??=this.solidBits(255,255,255):this.blackBits??=this.solidBits(0,0,0)}solidBits(e,t,r){let o=new Uint8Array(12288);for(let s=0;s<4096;s++)o[s*3]=e,o[s*3+1]=t,o[s*3+2]=r;return this.hashBits(64,64,o)}hammingDistance(e,t){let r=Math.min(e.length,t.length),i=Math.abs(e.length-t.length);for(let o=0;o<r;o++)e[o]!==t[o]&&i++;return i}bitsToHex(e){let t=0n;for(let i of e)t=t<<1n|(i?1n:0n);let r=Math.max(1,Math.ceil(e.length/4));return t.toString(16).padStart(r,"0")}toGray(e,t,r){let i=[];for(let o=0;o<t;o++){let s=[];for(let a=0;a<e;a++){let c=(o*e+a)*3;s.push(.299*r[c]+.587*r[c+1]+.114*r[c+2])}i.push(s)}return i}resizeGray(e,t,r){let i=e.length,o=e[0]?.length??0;if(o===t&&i===r)return e;let s=[];for(let a=0;a<r;a++){let c=(a+.5)*i/r-.5,l=Math.max(0,Math.min(i-1,Math.floor(c))),d=Math.max(0,Math.min(i-1,l+1)),g=c-l,y=[];for(let I=0;I<t;I++){let ce=(I+.5)*o/t-.5,G=Math.max(0,Math.min(o-1,Math.floor(ce))),xe=Math.max(0,Math.min(o-1,G+1)),at=ce-G,xt=e[l][G],Yu=e[l][xe],_c=e[d][G],Fc=e[d][xe];y.push(xt*(1-at)*(1-g)+Yu*at*(1-g)+_c*(1-at)*g+Fc*at*g)}s.push(y)}return s}stabilizeDct(e){let t=e.flat(),r=Math.abs(t[0]??0),i=Math.max(.001,r*1e-8);return t.map(o=>Math.abs(o)<i?0:o)}median(e){if(e.length===0)return 0;let t=[...e].sort((i,o)=>i-o),r=Math.floor(t.length/2);return t.length%2?t[r]:.5*(t[r-1]+t[r])}dct2(e){let t=e.length,r=a=>{let c=new Array(t).fill(0);for(let l=0;l<t;l++){let d=0;for(let g=0;g<t;g++)d+=a[g]*Math.cos(Math.PI*(g+.5)*l/t);c[l]=d}return c},i=e.map(r),o=[];for(let a=0;a<t;a++)o.push(r(i.map(c=>c[a])));let s=[];for(let a=0;a<t;a++){let c=[];for(let l=0;l<t;l++)c.push(o[l][a]);s.push(c)}return s}decodePngRgb(e){let t=this.parsePngChunks(e);if(!t)return null;let r;try{r=UP(Buffer.concat(t.idat))}catch{return null}let i=this.pngScanlinesToRgb(r,t.width,t.height,t.colorType);return{width:t.width,height:t.height,rgb:i}}parsePngChunks(e){if(e.length<8||e.subarray(0,8).toString("binary")!==`\x89PNG\r
|
|
70
71
|
|
|
71
|
-
`)return null;let t=8,r=0,i=0,o=0,s=0,a=[];for(;t+8<=e.length;){let c=e.readUInt32BE(t),l=e.subarray(t+4,t+8).toString("ascii"),d=e.subarray(t+8,t+8+c);if(t+=12+c,l==="IHDR")r=d.readUInt32BE(0),i=d.readUInt32BE(4),o=d[8],s=d[9];else if(l==="IDAT")a.push(d);else if(l==="IEND")break}return!r||!i||o!==8||s!==2&&s!==6?null:{width:r,height:i,colorType:s,idat:a}}pngScanlinesToRgb(e,t,r,i){let o=i===6?4:3,s=t*o,a=new Uint8Array(t*r*3),c=0,l=new Uint8Array(s),d=new Uint8Array(s);for(let g=0;g<r;g++){let y=e[c++];d.set(e.subarray(c,c+s)),c+=s,this.applyPngFilter(y,d,l,o);for(let I=0;I<t;I++){let
|
|
72
|
-
`),"Multiple devices found.")}let r=await n.getDeviceInfo(t,e);if(!r)throw new Error("No active devices found.");if(!e){let i=await n.getDeviceName(r.serial);console.log(`Auto-selected device: ${i} (${r.serial})`)}return r.serial}function
|
|
72
|
+
`)return null;let t=8,r=0,i=0,o=0,s=0,a=[];for(;t+8<=e.length;){let c=e.readUInt32BE(t),l=e.subarray(t+4,t+8).toString("ascii"),d=e.subarray(t+8,t+8+c);if(t+=12+c,l==="IHDR")r=d.readUInt32BE(0),i=d.readUInt32BE(4),o=d[8],s=d[9];else if(l==="IDAT")a.push(d);else if(l==="IEND")break}return!r||!i||o!==8||s!==2&&s!==6?null:{width:r,height:i,colorType:s,idat:a}}pngScanlinesToRgb(e,t,r,i){let o=i===6?4:3,s=t*o,a=new Uint8Array(t*r*3),c=0,l=new Uint8Array(s),d=new Uint8Array(s);for(let g=0;g<r;g++){let y=e[c++];d.set(e.subarray(c,c+s)),c+=s,this.applyPngFilter(y,d,l,o);for(let I=0;I<t;I++){let ce=(g*t+I)*3,G=I*o;a[ce]=d[G],a[ce+1]=d[G+1],a[ce+2]=d[G+2]}l.set(d)}return a}applyPngFilter(e,t,r,i){for(let o=0;o<t.length;o++){let s=o>=i?t[o-i]:0,a=r[o],c=o>=i?r[o-i]:0;e===1?t[o]=t[o]+s&255:e===2?t[o]=t[o]+a&255:e===3?t[o]=t[o]+Math.floor((s+a)/2)&255:e===4&&(t[o]=t[o]+this.paeth(s,a,c)&255)}}paeth(e,t,r){let i=e+t-r,o=Math.abs(i-e),s=Math.abs(i-t),a=Math.abs(i-r);return o<=s&&o<=a?e:s<=a?t:r}static pngChunk(e,t,r){let i=Buffer.concat([Buffer.from(e,"ascii"),t]),o=Buffer.alloc(12+t.length);return o.writeUInt32BE(t.length,0),i.copy(o,4),o.writeUInt32BE(n.pngCrc(i,r),8+t.length),o}static pngCrcTable(){let e=new Uint32Array(256);for(let t=0;t<256;t++){let r=t;for(let i=0;i<8;i++)r=r&1?3988292384^r>>>1:r>>>1;e[t]=r>>>0}return e}static pngCrc(e,t){let r=4294967295;for(let i=0;i<e.length;i++)r=t[(r^e[i])&255]^r>>>8;return(r^4294967295)>>>0}};import Yt from"fs";import Et from"path";import{randomUUID as KP}from"crypto";var GP=/^smoke-screenshot-\d+\.png$/,qP=/^smoke-crash-\d+\.log$/,zP=/^run-\d+-\d+-[0-9a-f]{4}$/;function Ff(n){return`smoke-screenshot-${n}.png`}function $f(n){return`smoke-crash-${n}.log`}function jf(n){return GP.test(n)||qP.test(n)}var qi="RUNNING",Hl="ENDED",JP=1440*60*1e3,YP=1440*60*1e3;function Hf(n,e,t){return`run-${n}-${e}-${t}`}function Uf(n){return zP.test(n)}function Bf(n){try{let e=JSON.parse(n);if(typeof e.pid!="number"||typeof e.startedAt!="number"||!Number.isFinite(e.pid)||!Number.isFinite(e.startedAt))return null;let t={pid:e.pid,startedAt:e.startedAt};return typeof e.endedAt=="number"&&Number.isFinite(e.endedAt)&&(t.endedAt=e.endedAt),t}catch{}return null}function Wf(n,e,t){return n===null?!0:n==="ended"?e?.endedAt===void 0?!0:t.now-e.endedAt>=JP:!e||!Number.isInteger(e.pid)||e.pid<=0||t.now-e.startedAt>=YP?!0:!t.isPidAlive(e.pid)}var XP="smoke";function ZP(n){try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}var zi=class{constructor(e,t=ZP){this.baseDir=e;this.isPidAlive=t;this.runsRoot=Et.join(e,XP)}runsRoot;static resolveBaseDir(e,t){return t??Et.join(e,".hvigor")}createRun(){let e=Et.join(this.runsRoot,Hf(Date.now(),process.pid,KP().slice(0,4)));Yt.mkdirSync(e,{recursive:!0});let t={pid:process.pid,startedAt:Date.now()};return Yt.writeFileSync(Et.join(e,qi),JSON.stringify(t),"utf8"),e}prune(e,t=Date.now()){this.pruneLegacyFlatArtifacts(),this.pruneEndedRuns(e,t)}finalize(e){try{let t=this.readMarker(e,qi),r={pid:t?.pid??process.pid,startedAt:t?.startedAt??Date.now(),endedAt:Date.now()};Yt.writeFileSync(Et.join(e,Hl),JSON.stringify(r),"utf8"),Yt.rmSync(Et.join(e,qi),{force:!0})}catch(t){p(`Smoke: finalize run failed (${e}): ${t.message}`)}}discard(e){try{Yt.rmSync(e,{recursive:!0,force:!0})}catch(t){p(`Smoke: discard run failed (${e}): ${t.message}`)}}pruneLegacyFlatArtifacts(){let e;try{e=Yt.readdirSync(this.baseDir,{withFileTypes:!0})}catch{return}for(let t of e)!t.isFile()||!jf(t.name)||this.removeQuietly(Et.join(this.baseDir,t.name))}pruneEndedRuns(e,t){let r;try{r=Yt.readdirSync(this.runsRoot,{withFileTypes:!0})}catch{return}for(let i of r){if(!i.isDirectory()||!Uf(i.name))continue;let o=Et.join(this.runsRoot,i.name);if(Et.resolve(o)===Et.resolve(e))continue;let s=this.readMarkerState(o);Wf(s.kind,s.marker,{now:t,isPidAlive:this.isPidAlive})&&this.removeQuietly(o)}}readMarkerState(e){let t=this.readMarker(e,Hl);if(t!==void 0)return{kind:"ended",marker:t};let r=this.readMarker(e,qi);return r!==void 0?{kind:"running",marker:r}:{kind:null,marker:null}}readMarker(e,t){try{return Bf(Yt.readFileSync(Et.join(e,t),"utf8"))}catch(r){return r.code==="ENOENT"?void 0:null}}removeQuietly(e){try{Yt.rmSync(e,{recursive:!0,force:!0})}catch(t){p(`Smoke: prune artifact failed (${e}): ${t.message}`)}}};var Vf=3e3;function eC(){let n=process.env.DEVECO_CLI_SMOKE_WAIT_MS;if(n===void 0||n==="")return Vf;let e=Number(n);return Number.isFinite(e)&&e>=0?Math.floor(e):Vf}var js=class{constructor(e,t,r){this.hdc=t;this.projectRoot=r;this.hilog=new yr(e),this.screenshots=new tn(e)}phash=new Fs;hilog;screenshots;runDir;runStore;async collect(e){this.openRun(e);let t=eC();t>0&&await new Promise(i=>setTimeout(i,t));let r;try{r=await this.hdc.pidofBundle(e.targetDeviceId,e.bundleName)}catch(i){return console.warn(Ji(`Smoke: process check failed (${i.message}); smoke skipped.`)),{processAlive:!0,phashBlank:null,processCheckSkipped:!0}}return r?this.collectScreenshotEvidence(e):{processAlive:!1,phashBlank:null,crashLogPath:await this.writeCrashLogFile(e)}}openRun(e){let t=new zi(zi.resolveBaseDir(this.projectRoot,e.screenshotDir)),r=t.createRun();t.prune(r),this.runStore=t,this.runDir=r}artifactPath(e){return QP.join(this.runDir??"",e)}discardEvidence(e){for(let t of[e.screenshotPath,e.crashLogPath])if(t)try{$s.rmSync(t,{force:!0})}catch(r){p(`Smoke: discard artifact failed (${t}): ${r.message}`)}this.runStore&&this.runDir&&this.runStore.discard(this.runDir)}finalizeRun(){this.runStore&&this.runDir&&this.runStore.finalize(this.runDir)}async collectScreenshotEvidence(e){let t=this.artifactPath(Ff(Date.now()));try{await this.screenshots.captureToPath(e.targetDeviceId,t)}catch(i){return this.skipBlank(`screenshot failed (${i.message})`)}if(!$s.existsSync(t)||$s.statSync(t).size<=32)return this.skipBlank("screenshot file missing or empty");let r=this.phash.analyzeFile(t);return r?{processAlive:!0,phashBlank:r.isBlank,phash:r.phash,phashHamming:r.hamming,screenshotPath:t}:this.skipBlank("failed to analyze screenshot",t)}skipBlank(e,t){return console.warn(Ji(`Smoke: ${e}; blank check skipped.`)),{processAlive:!0,phashBlank:null,screenshotPath:t,screenshotSkipped:!0}}async writeCrashLogFile(e){let t;try{t=await this.hilog.getLatestCrashLog(e.targetDeviceId,e.bundleName)}catch(r){console.warn(Ji(`Smoke: crash log query failed (${r.message}).`));return}if(!t?.trim()){console.warn(Ji("Smoke: no crash log found on device."));return}try{let r=this.artifactPath($f(Date.now()));return $s.writeFileSync(r,t,"utf8"),r}catch(r){console.warn(Ji(`Smoke: failed to save crash log (${r.message}).`));return}}};var Hs=class{judge(e){if(!e.processAlive)return this.verdict("FAIL_CRASH","Application process died after launch (possible crash).",e);if(e.phashBlank===!0)return this.verdict("FAIL_BLANK",`Blank/solid screen after launch (hamming ${e.phashHamming} \u2264 ${jl}, hash=${e.phash||"-"}).`,e);let t=e.phashBlank===null?"Process alive; screenshot unavailable, blank check skipped.":"Process alive; screenshot is not a solid blank screen.";return this.verdict("PASS",t,e)}verdict(e,t,r){return{status:e,reason:t,evidence:r,passed:e==="PASS"}}};var Us=class{inspector;judge=new Hs;formatter=new Ds;constructor(e,t,r){let i=r??new rt(e);this.inspector=new js(e,i,t)}async execute(e){let t=await this.inspector.collect(e),r=this.judge.judge(t);if(r.passed){this.inspector.discardEvidence(t),console.log(this.formatter.formatPass(r));return}throw this.inspector.finalizeRun(),this.formatter.toTraceError(r,e)}};async function Ul(n){await new Us(n.toolProvider,n.projectRoot,n.hdcAdapter).execute(n)}function Bl(n){let e=n.indexOf("@"),t=e!==-1?n.substring(0,e):n,r=e!==-1?n.substring(e+1):"default";return{moduleName:t,targetName:r}}async function Ws(n,e){let t=await n.listDevices();if(t.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");if(!e&&t.length>1){let i=await n.listDevicesWithName();throw new S("Multiple devices found. Specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+i.map(o=>` - ${o.name} (${o.serial})`).join(`
|
|
73
|
+
`),"Multiple devices found.")}let r=await n.getDeviceInfo(t,e);if(!r)throw new Error("No active devices found.");if(!e){let i=await n.getDeviceName(r.serial);console.log(`Auto-selected device: ${i} (${r.serial})`)}return r.serial}function Wl(n,e){if(e&&e.length>0)return e;let t=n.profile.modules.filter(r=>{let i=n.getModuleType(r.name);return i==="entry"||i==="feature"||i==="shared"});if(t.length===1){let r=t[0].name;return console.log(`Auto-selected module: ${r}`),[r]}throw new S(`Specify module(s) using --module <name> [<name>...].
|
|
73
74
|
Available runnable modules:
|
|
74
75
|
`+t.map(r=>` - ${r.name}`).join(`
|
|
75
|
-
`),"Specify module error.")}function
|
|
76
|
-
Installing artifacts to device ${e}...`),await n.installApp(e,r),i){console.log(`Launching ${t}/${i}...`);let s=await n.launchApp(e,t,i);console.log(
|
|
76
|
+
`),"Specify module error.")}function Gf(n,e,t){if(t)return t;let r=e.find(({moduleName:o})=>n.getModuleType(o)==="entry");if(r)return n.getMainAbility(r.moduleName);let i=e.find(({moduleName:o})=>n.getModuleType(o)==="feature");if(i)return n.getMainAbility(i.moduleName)}async function qf(n,e,t,r,i,o){if(o&&(console.log(`Uninstalling ${t}...`),await n.uninstallApp(e,t)||console.log(`App ${t} not installed; skipping uninstallation.`)),console.log(`
|
|
77
|
+
Installing artifacts to device ${e}...`),await n.installApp(e,r),i){console.log(`Launching ${t}/${i}...`);let s=await n.launchApp(e,t,i);console.log(Yi(`
|
|
77
78
|
Application '${t}': ${s}`))}else console.log(`
|
|
78
|
-
Application '${t}' installed successfully (no ability to launch).`)}function
|
|
79
|
-
`+ji("Build completed successfully.")),y}async function yP(n,e){let t=q.discover(process.cwd());console.warn(Rs("Ensure the project source is trusted before proceeding."));let r=await C.new();if(n.skipBuild||r.assertJava(),e.bundle_name=t.getBundleName(),n.hotreloadApply){await SP(n,t,r);return}if(n.hotreload){await wP(n,t,r);return}if(n.apply){await EP(n,t,r);return}return wf(n,t,r)}async function vP(n,e,t){n.onSocketDisconnect(()=>{console.log("Daemon disconnected (likely via --hotreload stop). Exiting watch session."),process.exit(0)});let r=new Ke(e,t.rootDir),i=setInterval(async()=>{await r.isDaemonAlive()||(clearInterval(i),console.log("Daemon stopped (via --hotreload stop). Exiting watch session."),process.exit(0))},3e3);await new Promise(()=>{})}async function wP(n,e,t){if(n.hotreload==="stop"){await am(t,e);return}let i=Pl(e,n.module).map(El),{moduleName:o,targetName:s}=i[0];ol(n.module,o);let a=new Qe(t),c=ne.from(t),l=await Ts(c,n.device),d=l.includes("127.0.0.1")||l.includes("localhost"),g=n.product||"default";e.validateProduct(g);let y=e.getBundleName(g),I=yf(e,i,n.ability);ls.generate(e.rootDir,o,g,t);let le=new Ke(t,e.rootDir);console.log(ji("Ensuring hvigor daemon is running (via --sync --daemon, no hap build)...")),await le.ensureDaemonRunning();let G=[`${o}@${g}`];for(let It of e.collectNonHarDependentModuleList(o))G.includes(`${It}@${g}`)||G.push(`${It}@${g}`);console.log(ji("Building hap + starting watch session (socket -> CommonBuild assembleHap --hot-reload-build --watch, kept open)..."));let Te=new Rn(e.rootDir,t);await Te.startWatchSession({moduleSpecs:G,productName:g});let it=sm(e,o,s,d,g);await vf(a,l,y,it,I,!!n.uninstall),console.log(ji("Hot-reload watch session active (socket persistent). Edit code, write .hvigor/<file>, then `devecocli run --hotreload-apply <file>` in another terminal. Ctrl+C here to stop.")),await vP(Te,t,e)}async function SP(n,e,t){let r=n.hotreloadApply;if(!r)throw new Error("hotreload-apply requires --hotreload-apply <fileName> (under .hvigor/)");if(Hi.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let i=Pl(e,n.module),{moduleName:o}=El(i[0]);ol(n.module,o);let s=ne.from(t),a=await Ts(s,n.device),c=n.product||"default";e.validateProduct(c);let l=e.getBundleName(c);om(e,o,r);let d=[`${o}@${c}`],g=await im({applyFileName:r,projectPath:e.rootDir,moduleName:o,productName:c,bundleName:l,toolProvider:t,targetDeviceId:a,moduleSpecs:d});if(!g.success)throw new Error(g.message)}function bP(n,e,t,r){let i=new Set;for(let{moduleName:o,targetName:s}of e)for(let a of n.collectNonHarDependentModuleList(o)){i.add(n.findArtifactPath(a,s,t,r));for(let c of n.findRemoteHspPaths(a,s,r))i.add(c)}return[...i]}async function wf(n,e,t){let i=Pl(e,n.module).map(El);for(let{moduleName:G}of i){let Te=e.getModuleType(G);if(Te!=="entry"&&Te!=="feature"&&Te!=="shared")throw new S(`Module '${G}' '${Te}' is not runnable. Specify an entry or feature module.`,"Module is not runnable.")}let o=new Qe(t),s=ne.from(t),a=await Ts(s,n.device),c=a.includes("127.0.0.1")||a.includes("localhost"),l=n.product||"default";e.validateProduct(l);let d=n.buildMode||"debug",g;n.skipBuild||(g=await gP(e,t,i,l,d));let y=bP(e,i,c,l),I=e.getBundleName(l),le=yf(e,i,n.ability);return await vf(o,a,I,y,le,!!n.uninstall),le&&await bl({toolProvider:t,projectRoot:e.rootDir,hdcAdapter:o,targetDeviceId:a,bundleName:I}),g}async function EP(n,e,t){let r=n.apply;if(!r)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(Hi.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let i=Hi.join(e.rootDir,".hvigor",r),o=ne.from(t),s=await Ts(o,n.device),a=n.product||"default";e.validateProduct(a);let c=e.getBundleName(a),l=e.profile.modules.find(y=>e.getModuleType(y.name)==="entry")?.name,d=l?e.getMainAbility(l,n.ability):n.ability||"EntryAbility",g=new as(t,e.rootDir);try{await g.execute({applyFile:i,productName:a,targetDeviceId:s,bundleName:c,abilityName:d})}catch(y){console.warn(Rs(`[Apply] failed: ${y.message}`)),console.warn(Rs('[Apply] Falling back to full "devecocli run"...')),await wf(n,e,t);return}console.log(Rs('[Apply] Done. If changes did not take effect, check <module>/build/config/buildConfig.json for content, or run "devecocli run" for a full build.')),await bl({toolProvider:t,projectRoot:e.rootDir,targetDeviceId:s,bundleName:c})}var Sf=hP;import{Command as BP}from"commander";import*as Rf from"path";import{green as If,red as Af,cyan as Il}from"colorette";import{execa as Dl}from"execa";import{spawn as CP}from"child_process";import*as bf from"fs";import*as xs from"path";import{yellow as kP}from"colorette";import IP from"proper-lockfile";function Ui(){return"@deveco-test/deveco-cli"}function gr(){return"1.3.5-Test.1"}function On(){return"daily"}function _n(){let n=process.env.DEVECO_CLI_DISABLE_UPDATE;return n==="check"||n==="all"?n:"off"}import*as Bi from"fs";import*as Wi from"path";var PP={lastCheckedTimestamp:null,latestVersion:null,blockedVersions:[],checkError:null},Cl=new Map,yr=class n{static CHECK_WINDOW_HOUR=21;static ONE_DAY_MS=1440*60*1e3;cacheFilePath;lockFilePath;constructor(e){this.cacheFilePath=Wi.join(e,"cache.json"),this.lockFilePath=Wi.join(e,"check.lock")}async writeSuccess(e,t=[],r,i){await this.write({lastCheckedTimestamp:Date.now(),latestVersion:e,blockedVersions:t,checkError:null,checkedAgainstVersion:r,checkedAgainstTag:i})}async writeError(e){let t=this.read();await this.write({...t,lastCheckedTimestamp:Date.now(),checkError:e})}getLatestVersion(){return this.read().latestVersion}getBlockedVersions(){return[...this.read().blockedVersions]}getCheckedAgainstVersion(){return this.read().checkedAgainstVersion}getCheckedAgainstTag(){return this.read().checkedAgainstTag}isCheckNeeded(){let{lastCheckedTimestamp:e}=this.read();if(!e||e>Date.now())return!0;let t=new Date().setHours(n.CHECK_WINDOW_HOUR,0,0,0),r=t>Date.now()?t-n.ONE_DAY_MS:t;return e<r}getLockPath(){return this.lockFilePath}read(){let e=Cl.get(this.cacheFilePath);if(e)return e;try{let t=Bi.readFileSync(this.cacheFilePath,"utf-8"),r=JSON.parse(t);return Cl.set(this.cacheFilePath,r),r}catch{return{...PP}}}async write(e){p(()=>`Writing update cache: lastChecked=${e.lastCheckedTimestamp}, latest=${e.latestVersion}, blocked=[${e.blockedVersions.join(",")}], error=${e.checkError}`),await Bi.promises.mkdir(Wi.dirname(this.cacheFilePath),{recursive:!0}),await Bi.promises.writeFile(this.cacheFilePath,JSON.stringify(e,null,2),"utf-8"),Cl.set(this.cacheFilePath,e)}};var Vi=class{constructor(e){this.actionCommand=e}cache=new yr(xs.join(he(),"update"));async checkAndNotify(){if(!this.shouldSkip())try{let e=gr(),t=On(),r=this.cache.getCheckedAgainstVersion(),i=this.cache.getCheckedAgainstTag(),o=i!=null&&i!==t,s=r!=null&&r!==e,a=o?null:this.cache.getLatestVersion();a&&rp(a,e)>0&&(console.log(),console.log(kP(`New version ${a} available, run \`devecocli update\` to upgrade`))),(o||s||this.cache.isCheckNeeded())&&await this.spawnBackgroundCheck()}catch(e){p(`Update check failed: ${e instanceof Error?e.message:String(e)}`)}}shouldSkip(){let e=this.actionCommand;for(;e;){if(e.name()==="update")return!0;e=e.parent}return!1}async spawnBackgroundCheck(){if(!process.argv[1]?.endsWith(".ts"))try{await AP(this.cache.getLockPath(),()=>{let e=[process.argv[1],"update","_check"];p(`Executing: ${process.execPath} ${e.join(" ")}`),CP(process.execPath,e,{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1"}}).unref()})}catch{p("Update check lock held by another process, skipping")}}};async function AP(n,e){await bf.promises.mkdir(xs.dirname(n),{recursive:!0});let t=await IP.lock(n,{stale:6e4,retries:0,realpath:!1});try{await e()}finally{await t()}}import*as Ls from"fs";import*as Fn from"path";import{execa as DP}from"execa";import{yellow as RP}from"colorette";function TP(n){return n?n.endsWith(".ts"):!0}function xP(n,e){let t=Fn.join(n,"package.json");try{return JSON.parse(Ls.readFileSync(t,"utf8")).name===e}catch{return!1}}function LP(n,e){let t;try{t=Fn.dirname(Ls.realpathSync(n))}catch{return null}for(let r=0;r<20&&t&&t!==Fn.dirname(t);r++){if(xP(t,e))return t;t=Fn.dirname(t)}return null}async function NP(){try{p("Executing: npm root -g");let{stdout:n}=await DP("npm",["root","-g"]);return n.trim()||null}catch(n){return p(`[install-check] npm root -g failed: ${n instanceof Error?n.message:String(n)}`),null}}function MP(n,e){return _c(n,e)}async function kl(n){if(process.env.DEVECO_CLI_SKIP_INSTALL_CHECK)return;let e=process.argv[1];if(TP(e))return;let t=await NP();if(!t)return;let r=LP(e,n);if(!r){p("[install-check] running package root not found, skipping");return}MP(r,t)||(console.log(),console.log(RP(`Warning: devecocli is running from
|
|
79
|
+
Application '${t}' installed successfully (no ability to launch).`)}function nC(n){let e={event:b.CommandExecuted,args:["run",...n.module?["--module"]:[],...n.device?["--device"]:[],...n.product?["--product"]:[],...n.buildMode?["--build-mode"]:[],...n.ability?["--ability"]:[],...n.uninstall?["--uninstall"]:[],...n.skipBuild?["--skip-build"]:[],...n.apply?["--apply"]:[],...n.hotreload?["--hotreload"]:[],...n.hotreloadApply?["--hotreload-apply"]:[]]};return n.buildMode&&(e.build_mode=n.buildMode),n.module&&(e.module_count=n.module.length),e}var iC=new tC("run").description("Build and run the project on a connected device").option("--module <modules...>","Module(s) to run (format: module or module@target)").option("--device <device>","Target device name or serial").option("--product <product>","Product name (default: default)").option("--build-mode <mode>","Build mode (options: debug, release; default: debug)").option("--ability <ability>","Ability name to launch").option("--uninstall","Uninstall existing app before installation").option("--skip-build","Skip build step and deploy existing artifacts").option("--apply <fileName>","Quick-apply changed files via quickfix (incremental hqf) and restart. <fileName> under project .hvigor/").option("--hotreload [action]",'Start hot-reload mode (build+deploy with daemon, then exit). Use "stop" to shut down the hvigor daemon.').option("--hotreload-apply <fileName>","Hot-reload changed files (.hvigor/<fileName> list) via daemon hot compile + signed hqf + quickfix, without restarting the app.").action(async n=>{let e=nC(n),t=Date.now(),r=!0,i=null;try{let o=await sC(n,e);o&&(o.ohpmMemoryMb&&(e.ohpm_install_memory=o.ohpmMemoryMb),o.syncMemoryMb&&(e.hvigor_sync_memory=o.syncMemoryMb),o.buildMemoryMb&&(e.hvigor_build_memory=o.buildMemoryMb))}catch(o){r=!1,i=B(o),console.error(rC(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await k.track(e,o)}});async function oC(n,e,t,r,i){let o=new In(e,n.rootDir),s=new et(e,n.rootDir),a=new Set,c=new Set;for(let{moduleName:I,targetName:ce}of t)for(let G of n.collectNonHarDependentModuleList(I))a.add(`${G}@${ce}`),c.add(G);let l=[...a],d=hl(n,l),g={type:"modules",modulesToBuild:l,moduleTasks:d};for(let I of c)bs.generate(n.rootDir,I,r,e);let y=await zr(n.rootDir,()=>gl(o,s,r,i,g,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion..."));return console.log(`
|
|
80
|
+
`+Yi("Build completed successfully.")),y}async function sC(n,e){let t=q.discover(process.cwd());console.warn(Bs("Ensure the project source is trusted before proceeding."));let r=await C.new();if(n.skipBuild||r.assertJava(),e.bundle_name=t.getBundleName(),n.hotreloadApply){await lC(n,t,r);return}if(n.hotreload){await cC(n,t,r);return}if(n.apply){await uC(n,t,r);return}return zf(n,t,r)}async function aC(n,e,t){n.onSocketDisconnect(()=>{console.log("Daemon disconnected (likely via --hotreload stop). Exiting watch session."),process.exit(0)});let r=new et(e,t.rootDir),i=setInterval(async()=>{await r.isDaemonAlive()||(clearInterval(i),console.log("Daemon stopped (via --hotreload stop). Exiting watch session."),process.exit(0))},3e3);await new Promise(()=>{})}async function cC(n,e,t){if(n.hotreload==="stop"){await Om(t,e);return}let i=Wl(e,n.module).map(Bl),{moduleName:o,targetName:s}=i[0];kl(n.module,o);let a=new rt(t),c=ne.from(t),l=await Ws(c,n.device),d=l.includes("127.0.0.1")||l.includes("localhost"),g=n.product||"default";e.validateProduct(g);let y=e.getBundleName(g),I=Gf(e,i,n.ability);Es.generate(e.rootDir,o,g,t);let ce=new et(t,e.rootDir);console.log(Yi("Ensuring hvigor daemon is running (via --sync --daemon, no hap build)...")),await ce.ensureDaemonRunning();let G=[`${o}@${g}`];for(let xt of e.collectNonHarDependentModuleList(o))G.includes(`${xt}@${g}`)||G.push(`${xt}@${g}`);console.log(Yi("Building hap + starting watch session (socket -> CommonBuild assembleHap --hot-reload-build --watch, kept open)..."));let xe=new Nn(e.rootDir,t);await xe.startWatchSession({moduleSpecs:G,productName:g});let at=Mm(e,o,s,d,g);await qf(a,l,y,at,I,!!n.uninstall),console.log(Yi("Hot-reload watch session active (socket persistent). Edit code, write .hvigor/<file>, then `devecocli run --hotreload-apply <file>` in another terminal. Ctrl+C here to stop.")),await aC(xe,t,e)}async function lC(n,e,t){let r=n.hotreloadApply;if(!r)throw new Error("hotreload-apply requires --hotreload-apply <fileName> (under .hvigor/)");if(Ki.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let i=Wl(e,n.module),{moduleName:o}=Bl(i[0]);kl(n.module,o);let s=ne.from(t),a=await Ws(s,n.device),c=n.product||"default";e.validateProduct(c);let l=e.getBundleName(c);Nm(e,o,r);let d=[`${o}@${c}`],g=await Lm({applyFileName:r,projectPath:e.rootDir,moduleName:o,productName:c,bundleName:l,toolProvider:t,targetDeviceId:a,moduleSpecs:d});if(!g.success)throw new Error(g.message)}function dC(n,e,t,r){let i=new Set;for(let{moduleName:o,targetName:s}of e)for(let a of n.collectNonHarDependentModuleList(o)){i.add(n.findArtifactPath(a,s,t,r));for(let c of n.findRemoteHspPaths(a,s,r))i.add(c)}return[...i]}async function zf(n,e,t){let i=Wl(e,n.module).map(Bl);for(let{moduleName:G}of i){let xe=e.getModuleType(G);if(xe!=="entry"&&xe!=="feature"&&xe!=="shared")throw new S(`Module '${G}' '${xe}' is not runnable. Specify an entry or feature module.`,"Module is not runnable.")}let o=new rt(t),s=ne.from(t),a=await Ws(s,n.device),c=a.includes("127.0.0.1")||a.includes("localhost"),l=n.product||"default";e.validateProduct(l);let d=n.buildMode||"debug",g;n.skipBuild||(g=await oC(e,t,i,l,d));let y=dC(e,i,c,l),I=e.getBundleName(l),ce=Gf(e,i,n.ability);return await qf(o,a,I,y,ce,!!n.uninstall),ce&&await Ul({toolProvider:t,projectRoot:e.rootDir,hdcAdapter:o,targetDeviceId:a,bundleName:I}),g}async function uC(n,e,t){let r=n.apply;if(!r)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(Ki.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let i=Ki.join(e.rootDir,".hvigor",r),o=ne.from(t),s=await Ws(o,n.device),a=n.product||"default";e.validateProduct(a);let c=e.getBundleName(a),l=e.profile.modules.find(y=>e.getModuleType(y.name)==="entry")?.name,d=l?e.getMainAbility(l,n.ability):n.ability||"EntryAbility",g=new Ss(t,e.rootDir);try{await g.execute({applyFile:i,productName:a,targetDeviceId:s,bundleName:c,abilityName:d})}catch(y){console.warn(Bs(`[Apply] failed: ${y.message}`)),console.warn(Bs('[Apply] Falling back to full "devecocli run"...')),await zf(n,e,t);return}console.log(Bs('[Apply] Done. If changes did not take effect, check <module>/build/config/buildConfig.json for content, or run "devecocli run" for a full build.')),await Ul({toolProvider:t,projectRoot:e.rootDir,targetDeviceId:s,bundleName:c})}var Jf=iC;import{Command as FC}from"commander";import*as Xl from"path";import{red as rh,cyan as Js,yellow as Yl}from"colorette";import{execa as Ys}from"execa";import{spawn as wC}from"child_process";import*as Zf from"fs";import*as Gs from"path";import{yellow as SC,cyan as bC}from"colorette";import EC from"proper-lockfile";function jn(){return"@deveco-test/deveco-cli"}function mt(){return"1.3.5-Test.2"}function Hn(){return"daily"}function Pt(){return Number.isFinite(1),1}var jt="@deveco-test/deveco-cli-knowledgebase";function Un(){let n=process.env.DEVECO_CLI_DISABLE_UPDATE;return n==="check"||n==="all"?n:"off"}import*as Xi from"fs";import*as Zi from"path";var pC={lastCheckedTimestamp:null,latestVersion:null,blockedVersions:[],checkError:null,latestDocsVersion:null,latestDocsApiVersion:null,latestCompatibleDocsVersion:null,checkedAgainstDocsApi:null},Vl=new Map,Sr=class n{static CHECK_WINDOW_HOUR=21;static ONE_DAY_MS=1440*60*1e3;cacheFilePath;lockFilePath;constructor(e){this.cacheFilePath=Zi.join(e,"cache.json"),this.lockFilePath=Zi.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=Vl.get(this.cacheFilePath);if(e)return e;try{let t=Xi.readFileSync(this.cacheFilePath,"utf-8"),r=JSON.parse(t);return Vl.set(this.cacheFilePath,r),r}catch{return{...pC}}}async write(e){p(()=>`Writing update cache: lastChecked=${e.lastCheckedTimestamp}, latest=${e.latestVersion}, blocked=[${e.blockedVersions.join(",")}], error=${e.checkError}`),await Xi.promises.mkdir(Zi.dirname(this.cacheFilePath),{recursive:!0}),await Xi.promises.writeFile(this.cacheFilePath,JSON.stringify(e,null,2),"utf-8"),Vl.set(this.cacheFilePath,e)}};import{createRequire as mC}from"module";import{dirname as fC,join as Bn}from"path";import{pathToFileURL as hC}from"url";import{readFile as Yf,access as Gl}from"fs/promises";import*as Kf from"semver";var gC=mC(import.meta.url);async function yC(){try{let n=gC.resolve("@deveco-test/deveco-cli-knowledgebase/package.json"),e=JSON.parse(await Yf(n,"utf8"));return{version:e.version,apiVersion:e.apiVersion??0,dir:fC(n)}}catch{return null}}async function vC(){let n=de(),e=Bn(n,"doc-data","current.json"),t;try{t=JSON.parse(await Yf(e,"utf8"))}catch{return null}let r=Bn(n,"doc-data",t.version);try{return await Gl(Bn(r,"dist","engine","index.js")),await Gl(Bn(r,"docs.zip")),await Gl(Bn(r,"index.zip")),{version:t.version,apiVersion:t.apiVersion,dir:r}}catch{return null}}async function Xf(){return[await vC(),await yC()].filter(e=>e!==null).sort((e,t)=>Kf.rcompare(e.version,t.version))}async function Wn(){let n=Pt();for(let e of await Xf())if(e.apiVersion<=n)return e.version;return null}async function Vs(){let n=Pt(),e=await Xf(),t=!1;for(let r of e){if(r.apiVersion>n){p(`docs: skip candidate v${r.version} (apiVersion ${r.apiVersion} > ${n})`),t=!0;continue}try{let i=Bn(r.dir,"dist","engine","index.js");return await import(hC(i).href)}catch(i){p(`docs: candidate v${r.version} load failed: ${i instanceof Error?i.message:String(i)}`)}}throw t?new Error("Documentation package version is incompatible, please upgrade CLI"):new Error("No available documentation package, please run `devecocli docs update` or reinstall CLI")}var Qi=class{constructor(e){this.actionCommand=e}cache=new Sr(Gs.join(de(),"update"));async checkAndNotify(){if(!this.shouldSkip())try{let e=mt(),t=Hn(),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&&dr(c,e)>0&&a.push(SC(`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.log();for(let d of a)console.log(d)}(o||s||l.stale||this.cache.isCheckNeeded())&&await this.spawnBackgroundCheck()}catch(e){p(`Update check failed: ${e instanceof Error?e.message:String(e)}`)}}async buildDocsMessage(){let e=Pt(),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 Wn();return i&&dr(r,i)<=0?{message:null,stale:!1}:{message:bC(`New docs version ${r} available, run \`devecocli docs update\` to upgrade`),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 PC(this.cache.getLockPath(),()=>{let e=[process.argv[1],"update","_check"];p(`Executing: ${process.execPath} ${e.join(" ")}`),wC(process.execPath,e,{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1"}}).unref()})}catch{p("Update check lock held by another process, skipping")}}};async function PC(n,e){await Zf.promises.mkdir(Gs.dirname(n),{recursive:!0});let t=await EC.lock(n,{stale:6e4,retries:0,realpath:!1});try{await e()}finally{await t()}}import{execa as ql}from"execa";import*as Qf from"semver";function zl(n){return{version:n.version,apiVersion:n.apiVersion??0,dist:n.dist}}function eo(n){return Array.isArray(n)?n[0]:n}async function CC(n){p(`Executing: npm view ${n} --json`);let{stdout:e}=await ql("npm",["view",n,"--json"]);return eo(JSON.parse(e))}async function Vn(n){p(`Executing: npm view ${jt} --json`);let{stdout:e}=await ql("npm",["view",jt,"--json"]),t=eo(JSON.parse(e)),r=zl(t);if(r.apiVersion<=n)return{latest:r,compatible:r};let i=kC(t.versions,n);if(i)return{latest:r,compatible:i};p(`Executing: npm view ${jt} versions --json`);let{stdout:o}=await ql("npm",["view",jt,"versions","--json"]),s=JSON.parse(o);for(let a=s.length-1;a>=0;a--){let c=s[a];if(c===r.version)continue;let l=zl(await CC(`${jt}@${c}`));if(l.apiVersion<=n)return{latest:r,compatible:l}}return{latest:r,compatible:null}}function kC(n,e){if(!n||typeof n!="object"||Array.isArray(n))return null;let t=Object.entries(n).filter(([,r])=>(r.apiVersion??0)<=e).map(([r,i])=>zl({...i,version:i.version??r}));return t.length===0?null:(t.sort((r,i)=>Qf.rcompare(r.version,i.version)),t[0])}import{execa as eh}from"execa";import*as Ct from"path";import*as ue from"fs/promises";import*as th from"crypto";async function IC(n,e){let t=`${n}.tmp.${process.pid}`;await ue.writeFile(t,JSON.stringify(e,null,2),"utf-8"),await ue.rename(t,n)}function DC(n,e){let t=e.indexOf("-");if(t<0)return!1;let r=e.slice(0,t),i=e.slice(t+1);if(r!=="sha512")return!1;let o=Buffer.from(i,"base64");return th.createHash(r).update(n).digest().equals(o)}async function AC(n,e,t){p(`Executing: npm pack ${jt}@${n}`);let{stdout:r}=await eh("npm",["pack",`${jt}@${n}`],{cwd:t}),i=r.trim().split(`
|
|
81
|
+
`).pop(),o=Ct.join(t,i),s=await ue.readFile(o);if(!DC(s,e))throw await ue.unlink(o).catch(()=>{}),new Error("Documentation package integrity verification failed");return o}async function RC(n,e,t){let r=Ct.join(t,e),i=Ct.join(t,`.tmp-${e}-${process.pid}`);return await ue.rm(r,{recursive:!0,force:!0}),await ue.rm(i,{recursive:!0,force:!0}),await ue.mkdir(i,{recursive:!0}),p(`Executing: tar -xzf ${Ct.basename(n)} -C ${i}`),await eh("tar",["-xzf",n,"-C",i]),await ue.rename(Ct.join(i,"package"),r),await ue.rm(i,{recursive:!0,force:!0}),await ue.unlink(n).catch(()=>{}),await ue.access(Ct.join(r,"dist","engine","index.js")),await ue.access(Ct.join(r,"docs.zip")),await ue.access(Ct.join(r,"index.zip")),r}async function qs(n,e,t){await ue.mkdir(e,{recursive:!0});let r=await AC(n.version,n.dist.integrity,e);return await RC(r,n.version,e),await IC(Ct.join(e,"current.json"),{version:n.version,apiVersion:n.apiVersion,installedAt:Date.now(),installedBy:t}),{version:n.version,apiVersion:n.apiVersion}}import*as zs from"fs";import*as Gn from"path";import{execa as TC}from"execa";import{yellow as xC}from"colorette";function LC(n){return n?n.endsWith(".ts"):!0}function NC(n,e){let t=Gn.join(n,"package.json");try{return JSON.parse(zs.readFileSync(t,"utf8")).name===e}catch{return!1}}function MC(n,e){let t;try{t=Gn.dirname(zs.realpathSync(n))}catch{return null}for(let r=0;r<20&&t&&t!==Gn.dirname(t);r++){if(NC(t,e))return t;t=Gn.dirname(t)}return null}async function OC(){try{p("Executing: npm root -g");let{stdout:n}=await TC("npm",["root","-g"]);return n.trim()||null}catch(n){return p(`[install-check] npm root -g failed: ${n instanceof Error?n.message:String(n)}`),null}}function _C(n,e){return el(n,e)}async function Jl(n){if(process.env.DEVECO_CLI_SKIP_INSTALL_CHECK)return;let e=process.argv[1];if(LC(e))return;let t=await OC();if(!t)return;let r=MC(e,n);if(!r){p("[install-check] running package root not found, skipping");return}_C(r,t)||(console.log(),console.log(xC(`Warning: devecocli is running from
|
|
80
82
|
${r}
|
|
81
83
|
but \`npm\` in PATH installs global packages to
|
|
82
84
|
${t}
|
|
83
85
|
The devecocli binary in PATH does not match the npm that \`devecocli update\` uses.
|
|
84
86
|
The update would land in the wrong place and would not reach the binary you are running.
|
|
85
87
|
Continuing with update \u2014 abort if this is unexpected.
|
|
86
|
-
Fix: run \`which -a devecocli\` (Windows: \`where devecocli\`) to list all shims, remove the stale one, or reinstall with the matching npm: \`npm install -g ${n}@latest\`.`)))}
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
Last error: ${
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
`).trim(),a=/Invalid command|无效命令|鏃犳晥鍛戒护/i.test(s)||/please attach the correct parameter/i.test(s),c=(t?.extraReject??[]).some(d=>d.test(s));if(o!==0||a||c)throw new Error(s||`emulator exited with code ${o===null?"null":o}`);if(t?.printOutputOnSuccess!==!1&&s){let d=(t?.transformOutput?t.transformOutput(s):s).trim();d&&console.log(d)}}async checkExistingVirtualDevice(e){let t=await this.listEmulators(e.instancePath),r=Ae(e.name),i=t.find(o=>Ae(o.name)===r);if(i)if(e.force)await this.deleteVirtualDevice(i.name,e.instancePath);else throw new S(`Emulator "${e.name}" already exists. Use \`--force\` to overwrite.`,"Emulator already exists.");return r}buildCreateVirtualDeviceArgs(e){let t=["-create",e.name,"-deviceType",e.deviceType,"-osVersion",e.osVersion];e.instancePath!==void 0&&t.push("-instancePath",e.instancePath),e.imageRoot!==void 0&&t.push("-imageRoot",e.imageRoot),e.screenProfile!==void 0&&t.push("-screenProfile",e.screenProfile),e.screen?.length&&t.push("-screen",...e.screen),e.storage!==void 0&&t.push("-storage",String(e.storage)),e.memory!==void 0&&t.push("-memory",String(e.memory));let r=e.hotBoot??(xf(e.osVersion)?!0:void 0);return r!==void 0&&t.push("-hotBoot",String(r)),t}async createVirtualDevice(e){let t=await this.checkExistingVirtualDevice(e),r=this.buildCreateVirtualDeviceArgs(e);if(await this.runEmulatorChecked(r,{extraReject:[/Device create fail/i,/already exists/i,/Invalid OS version/i,/cannot be empty/i],printOutputOnSuccess:!0,transformOutput:o=>o.split(/\r?\n/).map(s=>s.trim().startsWith("Device create success.")?"Device create success.":s).join(`
|
|
88
|
+
Fix: run \`which -a devecocli\` (Windows: \`where devecocli\`) to list all shims, remove the stale one, or reinstall with the matching npm: \`npm install -g ${n}@latest\`.`)))}var Zl=new FC("update").description("Update deveco-cli to latest");Zl.command("_check",{hidden:!0}).action(async()=>{let n=Date.now(),e=new Sr(Xl.join(de(),"update"));try{let t=Hn(),r=jn();p(`Executing: npm view ${r}@${t} --json`);let{stdout:i}=await Ys("npm",["view",`${r}@${t}`,"--json"]),{latestVersion:o,blockedVersions:s}=jC(i,t),a=await $C().catch(c=>{p(`Docs version check failed: ${c instanceof Error?c.message:String(c)}`)});await e.writeSuccess(o,s,mt(),t,a),await nh(n,!0,null)}catch(t){await e.writeError(t instanceof Error?t.message:String(t));let r=t,i=r.code??r.name??"UnknownError";await nh(n,!1,i)}});async function $C(){let n=Pt(),{latest:e,compatible:t}=await Vn(n);return{latestDocsVersion:e.version,latestDocsApiVersion:e.apiVersion,latestCompatibleDocsVersion:t?.version??null,checkedAgainstDocsApi:n}}function jC(n,e){let t=eo(JSON.parse(n)),r=null;typeof t.version=="string"?r=t.version.trim():t["dist-tags"]?.[e]&&(r=t["dist-tags"][e].trim());let i=[];return Array.isArray(t.blockedVersions)?i=t.blockedVersions:r&&t.versions?.[r]?.blockedVersions&&(i=t.versions[r].blockedVersions),{latestVersion:r,blockedVersions:i}}var HC={event:b.CommandExecuted,args:["update"]},UC={event:b.CommandExecuted,args:["update","_check"]};async function Kl(n,e,t){let r={duration_ms:Date.now()-n,success:e,error_code:t};await k.track(HC,r).catch(()=>{})}async function nh(n,e,t){let r={duration_ms:Date.now()-n,success:e,error_code:t};await k.track(UC,r).catch(()=>{})}async function BC(n,e,t){let r=t,i=r.code??r.name??"UnknownError";console.error(rh(`Failed to update ${n}`)),r.message&&console.error(rh(r.message)),await Kl(e,!1,i),process.exit(1)}Zl.action(async()=>{if(Un()==="all")throw new Error("devecocli update is disabled (DEVECO_CLI_DISABLE_UPDATE=all).");await Jl(jn());let n=Date.now(),e=mt(),t=Hn(),r=jn();console.log(Js("Checking for updates..."));try{let{stdout:i}=await Ys("npm",["view",r,`dist-tags.${t}`]),o=i.trim();if(!o||o===e){console.log(Yl(`
|
|
89
|
+
${r} is already up to date (v${e}, tag: ${t})`)),await Kl(n,!0,null);return}console.log(Js(`
|
|
90
|
+
New version found: ${o} (current: ${e})`)),console.log(Js(`Updating ${r}...`)),await Ys("npm",["install","-g",`${r}@${t}`],{stdio:"inherit"}),console.log(Yl(`
|
|
91
|
+
CLI successfully updated to ${o}`)),await WC(o).catch(s=>{p(`Docs auto-sync failed: ${s instanceof Error?s.message:String(s)}`)}),await Kl(n,!0,null)}catch(i){await BC(r,n,i)}});async function WC(n){let e=jn();p(`Executing: npm view ${e}@${n} --json`);let{stdout:t}=await Ys("npm",["view",`${e}@${n}`,"--json"]),r=eo(JSON.parse(t)),i=typeof r.supportedDocsApi=="number"?r.supportedDocsApi:Pt(),{compatible:o}=await Vn(i);if(!o){p("Docs auto-sync: no compatible docs version found, skipping");return}let s=Xl.join(de(),"doc-data"),a=await Wn();(!a||dr(o.version,a)>0)&&await qs({version:o.version,apiVersion:o.apiVersion,dist:o.dist},s,"cli-update"),console.log(Yl(`Docs has been automatically synced to the compatible version ${o.version}`));let c=await Vn(i).catch(()=>null);c?.compatible&&dr(c.compatible.version,o.version)>0&&console.log(Js(`New docs version ${c.compatible.version} available, run \`devecocli docs update\` to upgrade`))}var ih=Zl;import{Command as wk,Option as wh}from"commander";import{execa as Ks}from"execa";function Ae(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}function oh(n){let e=n.normalize("NFKC").match(/\((\d+)(?:\.\d+)*\)/)?.[1];return e!==void 0&&Number(e)>=26}import{spawn as VC}from"child_process";var GC=2500;function qC(n,e,t,r,i,o){n.once("exit",s=>{if(o())return;clearTimeout(e);let a=t();s===0||s===null?r():i(a||`Emulator process exited with code ${s}`)})}function zC(n,e,t,r){let i=!1,o=()=>i,s=()=>Buffer.concat(e).toString("utf8").trim(),a=()=>{i||(i=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners(),n.stderr?.destroy(),n.unref(),t())},c=d=>{if(!i){i=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners();try{n.kill()}catch{}r(new Error(d))}},l=setTimeout(a,GC);n.once("error",d=>c(d.message)),qC(n,l,s,a,c,o)}function sh(n,e,t){p(`Spawning emulator: ${n} ${t.join(" ")}`);let r=[],i=VC(n,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});i.stderr?.on("data",a=>r.push(a));let o=i.pid!==void 0&&!je()?kn(i.pid,500,!0):void 0,s=new Promise((a,c)=>{zC(i,r,a,c)});return{pid:i.pid,started:s,tracker:o}}import*as qn from"path";function JC(n){let e=new Set,t=[];for(let r of n){let i=JSON.stringify(r);e.has(i)||(e.add(i),t.push(r))}return t}function YC(n){let e=n.instancePath?.trim();if(e)return qn.dirname(qn.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?qn.dirname(qn.normalize(t)).replace(/\\/g,"/"):""}function KC(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function ah(n,e,t){let r=[...n],i=t?.bootMode??e;return i&&r.push("-bootmode",i),t?.hdcPort!==void 0&&r.push("-hdcport",String(t.hdcPort)),t?.noWindow&&r.push("-noWindow"),r}function XC(n,e,t,r){let i=[ah(["-start",n],t,r)],o=YC(e);if(o)for(let s of KC(e.imageRoot))i.push(ah(["-hvd",n,"-path",o,...s],t,r));return JC(i)}async function ch(n,e,t,r,i){let o=new Error("No start strategy ran"),s=XC(n,e,r,i);for(let a of s){let c;try{return c=t(a),await c.started,{ok:!0,args:a,tracker:c.tracker}}catch(l){if(c?.tracker)try{await c.tracker.stop()}catch{}o=l}}return{ok:!1,lastError:o}}function ZC(n){let e=n.normalize("NFKC").match(/^\s*chargingStatus\s*:\s*(\d+)\s*$/im);if(!e)return;let t=Number(e[1]);if(t===1||t===3)return!0;if(t===0||t===2)return!1}async function Ql(n){return(await ne.withHdcPath(n).listDevices()).map(t=>t.serial).filter(Ot)}async function ed(n){let e=await Ql(n);return e.length===0?[]:(await Promise.all(e.map(r=>ws(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function lh(n,e){return(await ed(n)).includes(e)}async function dh(n,e){let t=await ne.withHdcPath(n).listDevicesWithName(),r=e.normalize("NFKC").replace(/\s+/g," ").trim(),i=t.find(a=>a.name.normalize("NFKC").replace(/\s+/g," ").trim()===r);if(!i||!Ot(i.serial))throw new Error(`Cannot resolve the running emulator serial for "${e}".`);let o=["-t",i.serial,"shell","hidumper","-s","3302","-a","-i"];p(`Executing: ${n} ${o.join(" ")}`);let s=await re(n,o);if(s.exitCode===0){let a=ZC(s.stdout);if(a!==void 0)return a}throw new Error(`Cannot determine the battery charging state for emulator "${e}".`)}import*as Jn from"path";import{existsSync as QC,statSync as ek}from"fs";function zn(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function tk(n){let e=zn(n,["instancePath","instance_path","InstancePath","instancepath","instanceDir","instance_dir","InstanceDir","deployPath","deploy_path","deployedPath","deployed_path","workPath","work_path","dataPath","data_path"]);if(e)return e;for(let[t,r]of Object.entries(n)){if(typeof r!="string"||!r.trim())continue;let i=t.toLowerCase();if(i.includes("instance")&&(i.includes("path")||i.includes("dir"))||i==="deployedpath")return r.trim()}return""}function rk(n){return zn(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function nk(n,e){for(let t of e){let r=n[t];if(!(r==null||r===""))return r===!0||String(r).toLowerCase()==="true"}}function ik(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=Jn.dirname(Jn.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let i=E.ensurePathWithinRoot(t,Jn.join(t,r.name));QC(i)&&ek(i).isDirectory()&&(r.instancePath=i.replace(/\\/g,"/"))}}function ok(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=rk(t),i=zn(t,["deviceType","DeviceType","devicetype"]),o=zn(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:tk(t),path:zn(t,["path","Path","hvdPath","hvd_path"]),imageRoot:zn(t,["imageRoot","image_root","ImageRoot"]),uuid:r||void 0,deviceType:i||void 0,osVersion:o||void 0,hotBoot:nk(t,["isHotBoot","ishotboot","hotBoot"])}}).filter(t=>t.name):null}catch{return null}}function sk(n){let e=[],t=/^(name|isrunning|ishotboot|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,r=null,i;for(;(i=t.exec(n))!==null;){let[,o,s]=i;if(o.toLowerCase()==="name")r&&e.push(r),r={name:s.trim()};else if(r){let a=o.toLowerCase();a==="isrunning"?r.isRunning=s.trim().toLowerCase()==="true":a==="ishotboot"?r.hotBoot=s.trim().toLowerCase()==="true":a==="instancepath"?r.instancePath=s.trim():a==="path"?r.path=s.trim():a==="imageroot"?r.imageRoot=s.trim():a==="devicetype"?r.deviceType=s.trim():a==="os.osversion"&&(r.osVersion=s.trim())}}return r&&e.push(r),e}function uh(n){let t=ok(n)??sk(n);return ik(t),t}function td(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function ak(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function ck(n){let e=td(n,["osVersion","OsVersion","OSVersion"]),t=td(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=td(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function ph(n,e=()=>!0){let t=n.trim();if(!t)return[];try{let r=JSON.parse(t);if(!Array.isArray(r))return[];let i=[];for(let o of r){if(!o||typeof o!="object")continue;let s=o;if(!e(s))continue;let a=ck(s);a&&i.push(a)}return i}catch{return[]}}function mh(n){return ph(n)}function fh(n){return ph(n,ak)}var hh=/no images are available/i,lk=/Scenario simulation failed\s*[::]/i,dk="7.0.0";function Kt(n){return n.normalize("NFKC").trim().toLowerCase()}function uk(n){let e=n.message||"";return hh.test(e)}function pk(n){return n.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function to(n,e){return`${n} ${e.join(" ")}`.trim()}function mk(n){switch(n.type){case"gps":return`${n.type}:${n.key}=${n.value}`;case"sensor":return`${n.type}:${n.key}=${n.value}`;case"rotation":case"volume":return`${n.type}:${n.direction}`;case"folded-state":return`${n.type}:${n.state}`;case"battery":return`${n.type}:${n.level}`;case"battery-status":return`${n.type}:${n.status}`;default:return n.type}}var Yn=class n{static supportedControlPaths=new Set;emulatorPath;sdkPath;hdcPath;constructor(e,t,r){this.emulatorPath=e,this.sdkPath=t,this.hdcPath=r}static from(e){return new n(e.emulatorPath,e.sdkPath,e.hdcPath)}async executeEmulator(e){return p(`Executing: ${to(this.emulatorPath,e)}`),Ks(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return sh(this.emulatorPath,this.sdkPath,e)}async listEmulators(e){let t=["-list","-details"];e!==void 0&&t.push("-instancePath",e);let{stdout:r}=await this.executeEmulator(t);return uh(r)}async listEmulatorDetails(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return e}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let r of t)r.name&&r.deviceType&&e.set(Ae(r.name),r.deviceType)}catch{}return e}async startEmulator(e,t){let r=await this.listEmulators(),i=Ae(e),o=r.find(c=>Ae(c.name)===i);if(!o)throw new S(`Emulator "${e}" not found.`,"Emulator not found.");let s=o.name;if(await this.isAlreadyRunning(s,o))return{status:"already-running"};let a=await ch(s,o,c=>this.executeEmulatorDetached(c),o.hotBoot===!1?"coldboot":"snapshot",t);if(a.ok)return{status:"started",args:a.args,tracker:a.tracker};if(await this.isAlreadyRunning(s))return{status:"already-running"};throw new S(`Unable to start emulator "${e}". All methods failed.
|
|
92
|
+
Last error: ${a.lastError.message||"unknown"}`,`Unable to start emulator. All methods failed.
|
|
93
|
+
Last error: ${a.lastError.message||"unknown"}`)}async isAlreadyRunning(e,t){return t?.isRunning===!0||t===void 0&&(await this.listEmulators()).find(i=>i.name===e)?.isRunning===!0?!0:lh(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),r=Ae(e),i=t.find(a=>Ae(a.name)===r);if(!i)throw new S(`Emulator "${e}" not found.`,"Emulator not found.");let o=i.name;return await this.isAlreadyRunning(o,i)?(await this.executeEmulator(["-stop",o]),"stopped"):"already-stopped"}async controlEmulator(e,t){await this.assertControlCommandSupported();let i=(await this.listEmulators()).find(s=>s.name===e);if(!i)throw new S(`Emulator "${e}" not found.`,"Emulator instance not found.");if(!await this.isAlreadyRunning(i.name,i))throw new S(`Emulator "${e}" is not running.`,"Emulator instance is not running.");if(t.type==="battery"&&!(t.assumedCharging?!0:await dh(this.hdcPath,i.name))&&t.level===0)throw new Error("Battery level must be an integer in [1, 100] while the emulator is not charging.");let o=this.buildControlArgs(i.name,t);p(`[EmulatorManager] control ${mk(t)} -> ${to(this.emulatorPath,o)}`),await this.runEmulatorChecked(o,{extraReject:t.type==="folded-state"?[lk]:void 0,printOutputOnSuccess:!1})}async assertControlCommandSupported(){let e=this.emulatorPath;if(n.supportedControlPaths.has(e))return;let t=["-version"];p(`Executing: ${to(this.emulatorPath,t)}`);let{stdout:r,stderr:i,exitCode:o}=await Ks(this.emulatorPath,t,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:1024*1024}),s=[r,i].filter(Boolean).join(`
|
|
94
|
+
`).trim(),a=pk(s);if(o!==0||!a)throw new Error("Emulator scene control commands require Emulator 7.0 or later. Unable to determine the current Emulator version.");if(C.compareVersion(a,dk)<0)throw new Error(`Emulator scene control commands require Emulator 7.0 or later. Current Emulator version is ${a}. Please upgrade DevEco Studio or the Emulator SDK.`);n.supportedControlPaths.add(e)}buildControlArgs(e,t){let r=["-instance",e];switch(t.type){case"shake":return[...r,"-shake"];case"power":return[...r,"-power"];case"rotation":return[...r,"-rotation",t.direction];case"volume":return[...r,"-volume",t.direction];case"folded-state":return[...r,"-foldedState",t.state];case"battery":return[...r,"-battery",String(t.level)];case"battery-status":return[...r,"-batteryStatus",String(t.status)];case"gps":return[...r,"-gps",`-${t.key}`,t.value];case"outdoor-running":return[...r,"-outdoorRunning"];case"outdoor-cycling":return[...r,"-outdoorCycling"];case"driving-navigation":return[...r,"-drivingNavigation"];case"sensor":return[...r,"-sensor",`-${t.key}`,String(t.value)];default:throw new Error(`Unknown emulator control action type: ${t.type}`)}}async executeEmulatorInherit(e){p(`Executing: ${to(this.emulatorPath,e)}`);let{exitCode:t}=await Ks(this.emulatorPath,e,{stdio:"inherit",env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1});if(t!==0)throw new Error(`Emulator exited with code ${t===null?"null":t}.`)}async installEmulatorImage(e){let t=["-install","-deviceType",e.deviceType,"-osVersion",e.osVersion];e.force&&t.push("-force"),await this.executeEmulatorInherit(t)}async hasAvailableEmulatorImage(e){let t=await this.listEmulatorImages({deviceType:e.deviceType}),r=Kt(e.deviceType),i=Kt(e.osVersion);return mh(t).some(o=>Kt(o.deviceType)===r&&Kt(o.osVersion)===i)}async uninstallEmulatorImage(e){let t=await this.resolveSoftwareVersionsForUninstall(e);if(t.length===0)throw new Error(`No downloaded image matches --os-version "${e.osVersion}" for --device-type "${e.deviceType}".`);let r;try{await this.runUninstallImageChecked(e.deviceType,e.osVersion)}catch(o){if(!uk(o))throw o;r=o}(r!==void 0||await this.hasMatchingDownloadedImage(e))&&await this.runSoftwareVersionFallback(e,t,r)}async listEmulatorImages(e){let t=["-imageList"];e.deviceType&&t.push("-deviceType",e.deviceType),e.downloaded!==void 0&&t.push("-downloaded",e.downloaded?"true":"false");let{stdout:r}=await this.executeEmulator(t);return r}async hasMatchingDownloadedImage(e){return(await this.findMatchingDownloadedImages(e)).length>0}async runSoftwareVersionFallback(e,t,r){try{for(let i of t)await this.runUninstallImageChecked(e.deviceType,i)}catch(i){let o=r!==void 0?`Primary uninstall failed: ${r.message}
|
|
95
|
+
`:"";throw new Error(`${o}Fallback uninstall failed: ${i.message}`,{cause:i})}if(await this.hasMatchingDownloadedImage(e))throw new Error(`Image for --device-type "${e.deviceType}" and --os-version "${e.osVersion}" remains listed as downloaded after uninstallation.`)}async resolveSoftwareVersionsForUninstall(e){let t=await this.findMatchingDownloadedImages(e);return[...new Set(t.map(r=>r.softwareVersion).filter(Boolean))]}async findMatchingDownloadedImages(e){let t=await this.listEmulatorImages({deviceType:e.deviceType,downloaded:!0}),r=fh(t),i=Kt(e.deviceType),o=Kt(e.osVersion);return r.filter(s=>Kt(s.deviceType)===i&&(Kt(s.osVersion)===o||Kt(s.softwareVersion)===o))}async runUninstallImageChecked(e,t){await this.runEmulatorChecked(["-uninstall","-deviceType",e,"-osVersion",t,"-force"],{printOutputOnSuccess:!0,extraReject:[hh]})}async runEmulatorChecked(e,t){p(`Executing: ${to(this.emulatorPath,e)}`);let{stdout:r,stderr:i,exitCode:o}=await Ks(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:20*1024*1024}),s=[r,i].filter(Boolean).join(`
|
|
96
|
+
`).trim(),a=/Invalid command|无效命令|鏃犳晥鍛戒护/i.test(s)||/please attach the correct parameter/i.test(s),c=(t?.extraReject??[]).some(d=>d.test(s));if(o!==0||a||c)throw new Error(s||`emulator exited with code ${o===null?"null":o}`);if(t?.printOutputOnSuccess!==!1&&s){let d=(t?.transformOutput?t.transformOutput(s):s).trim();d&&console.log(d)}}async checkExistingVirtualDevice(e){let t=await this.listEmulators(e.instancePath),r=Ae(e.name),i=t.find(o=>Ae(o.name)===r);if(i)if(e.force)await this.deleteVirtualDevice(i.name,e.instancePath);else throw new S(`Emulator "${e.name}" already exists. Use \`--force\` to overwrite.`,"Emulator already exists.");return r}buildCreateVirtualDeviceArgs(e){let t=["-create",e.name,"-deviceType",e.deviceType,"-osVersion",e.osVersion];e.instancePath!==void 0&&t.push("-instancePath",e.instancePath),e.imageRoot!==void 0&&t.push("-imageRoot",e.imageRoot),e.screenProfile!==void 0&&t.push("-screenProfile",e.screenProfile),e.screen?.length&&t.push("-screen",...e.screen),e.storage!==void 0&&t.push("-storage",String(e.storage)),e.memory!==void 0&&t.push("-memory",String(e.memory));let r=e.hotBoot??(oh(e.osVersion)?!0:void 0);return r!==void 0&&t.push("-hotBoot",String(r)),t}async createVirtualDevice(e){let t=await this.checkExistingVirtualDevice(e),r=this.buildCreateVirtualDeviceArgs(e);if(await this.runEmulatorChecked(r,{extraReject:[/Device create fail/i,/already exists/i,/Invalid OS version/i,/cannot be empty/i],printOutputOnSuccess:!0,transformOutput:o=>o.split(/\r?\n/).map(s=>s.trim().startsWith("Device create success.")?"Device create success.":s).join(`
|
|
96
97
|
`)}),!await this.waitForEmulatorPresenceByList(t,e.instancePath))throw new S(`Emulator "${e.name}" was reported as created, but it did not appear in the emulator list within the waiting period. Open the device manager list in DevEco Studio, then run this command again.`,"Emulator was reported as created, but it did not appear in the emulator list within the waiting period.")}async waitForEmulatorPresenceByList(e,t,r=1e4,i=500){let o=Date.now()+r;for(;Date.now()<o;){if((await this.listEmulators(t)).some(c=>Ae(c.name)===e))return!0;await new Promise(c=>setTimeout(c,i))}return!1}async deleteVirtualDevice(e,t){let r=await this.listEmulators(t),i=Ae(e),o=r.find(c=>Ae(c.name)===i);if(!o)throw new S(`Emulator "${e}" not found.`,"Emulator not found.");let s=o.name;if(o.isRunning===!0||await this.isAlreadyRunning(s,o))throw new S(`Failed to delete device: ${s}
|
|
97
|
-
The device may be running.`,"Failed to delete device, The device may be running.");let a=["-delete",s];return t!==void 0&&a.push("-instancePath",t),a.push("-force"),await this.runEmulatorChecked(a,{printOutputOnSuccess:!1}),s}};import{red as
|
|
98
|
-
`)}async function
|
|
99
|
-
`),"Multiple devices connected.")}async function
|
|
98
|
+
The device may be running.`,"Failed to delete device, The device may be running.");let a=["-delete",s];return t!==void 0&&a.push("-instancePath",t),a.push("-force"),await this.runEmulatorChecked(a,{printOutputOnSuccess:!1}),s}};import{red as Sk,yellow as bk,gray as Ek}from"colorette";import Sh from"ora";import{green as fk}from"colorette";var hk=[[4352,4447],[9001,9002],[11904,42191],[43360,43388],[44032,55203],[63744,64255],[65040,65049],[65072,65135],[65281,65376],[65504,65510],[127744,129535],[131072,173791],[173824,177983],[177984,178207],[178208,183983],[183984,191456]],gk=[[0,31],[127,159],[768,879],[6832,6911],[7616,7679],[8203,8207],[8400,8447],[65024,65039],[65056,65071],[8205,8205]],yk=new RegExp("\x1B\\[([0-9;]*)[a-zA-Z]","g");function gh(n,e){for(let[t,r]of e)if(n>=t&&n<=r)return!0;return!1}function rd(n){let e=n.replace(yk,""),t=0,r=0;for(;r<e.length;){let i=e.codePointAt(r);if(i===void 0)break;gh(i,gk)||(gh(i,hk)?t+=2:t+=1),r+=i>65535?2:1}return t}function yh(n,e){let t=rd(n);return n+" ".repeat(Math.max(0,e-t))}function vk(n,e){return n.map((t,r)=>{let i=rd(t);for(let o of e){let s=o.cells[r]??"";i=Math.max(i,rd(s))}return i})}function Xt(n,e){let t=vk(n,e),r=[];r.push(n.map((i,o)=>yh(i,t[o])).join(" ")),r.push(t.map(i=>"-".repeat(i)).join(" "));for(let i of e){let o=i.cells.map((s,a)=>yh(s??"",t[a])).join(" ").trimEnd();r.push(i.highlight?fk(o):o)}return r.join(`
|
|
99
|
+
`)}async function ro(n,e){let t=Date.now(),r=!0,i=null;try{await e()}catch(o){r=!1,i=B(o),console.error(Sk(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await k.track(n,o)}}function Pk(n,e){if(e.size!==0)for(let t of n){if(!t.isEmulator||!t.name)continue;let r=e.get(Ae(t.name));r&&(t.deviceType=r)}}var Ck=["Name","Serial","Kind","Device Type"];function kk(n){return{cells:[n.name??n.serial,n.serial,n.isEmulator?"emulator":"device",n.deviceType??"-"],highlight:!0}}function bh(n,e){return n.isEmulator!==e.isEmulator?n.isEmulator?1:-1:(n.name??n.serial).localeCompare(e.name??e.serial)}function Ik(){console.log(bk(" No active devices.")),console.log(Ek(" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function Dk(n){let t=[...n].sort(bh).map(kk);console.log(Xt(Ck,t))}function Ak(n){return{name:n.name??n.serial,serial:n.serial,kind:n.isEmulator?"emulator":"device",deviceType:n.deviceType}}function Rk(n){let e=[...n].sort(bh);console.log(JSON.stringify(e.map(Ak),null,2))}async function Tk(n,e){if(!n.some(i=>i.isEmulator)||!e.emulatorPath)return;let r=await Yn.from(e).getDeviceTypeByName();Pk(n,r)}async function vh(n,e,t,r="table"){try{let i=await n.getConnectedEntries();if(await Tk(i,e),t?.stop(),r==="json"){Rk(i);return}i.length===0?Ik():Dk(i)}catch(i){throw new S(`Failed to list devices: ${i.message}`,"Failed to list devices.")}finally{t?.stop()}}async function xk(n,e){let t=await n.listDevices();if(t.length<2)return;let r=["Multiple devices connected. Specify a device with:"];for(let i of t){let o=await n.getDeviceName(i.serial);r.push(` ${e} -t ${i.serial} # ${o}`)}throw new S(r.join(`
|
|
100
|
+
`),"Multiple devices connected.")}async function Lk(n,e,t="table"){e||await xk(n,"devecocli device view");let r=await n.listDevices(),i=await n.getDeviceInfo(r,e);if(!i){if(t==="json"){console.error("No connected device found."),process.exitCode=1;return}throw new S("No connected device found.")}let o=await n.getDeviceDetail(i.serial),s=await n.getDeviceName(i.serial);if(t==="json"){let a={name:s,serial:i.serial,kind:Ot(i.serial)?"emulator":"device",deviceType:o.deviceType,osVersion:o.osVersion};console.log(JSON.stringify(a,null,2));return}console.log(` Serial: ${i.serial}`),console.log(` Device Name: ${s}`),o.deviceType&&console.log(` Device Type: ${o.deviceType}`),o.osVersion&&console.log(` OS Version: ${o.osVersion}`)}async function Eh(n,e,t,r,i){let o=await nt(n,i),s=new rt(n),a=e==="send",c=Sh({text:a?`Sending ${t} to ${r} on ${o}...`:`Receiving ${t} from ${o} to ${r}...`,color:"cyan"}).start();try{await s.transferFile(o,e,t,r),c.stop(),console.log(`${a?"Sent to device":"Received from device"} (${o}): ${t} -> ${r}`)}catch(l){c.stop();let d=a?"Send":"Recv";throw new S(`File ${d} failed: ${l.message}`,`File ${d} failed.`)}}async function Nk(n,e,t,r){let i=await nt(n,r),o=new rt(n);try{await o.runSqlite3(i,e,t)}catch(s){throw new S(`sqlite3 failed: ${s.message}`,"sqlite3 failed.")}}async function no(){try{let n=await C.new();return{manager:ne.from(n),toolProvider:n}}catch(n){throw new S(`Failed to initialize device manager: ${n.message}`,"Failed to initialize device manager.")}}var io=new wk("device").description("Manage connected devices");io.command("list").description("List all connected devices").addOption(new wh("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let e={event:b.CommandExecuted,args:["device","list",...n.format==="json"?["--format","json"]:[]]};await ro(e,async()=>{let{manager:t,toolProvider:r}=await no();if(n.format==="json"){await vh(t,r,void 0,"json");return}let i=Sh({text:"Querying connected devices\u2026",color:"cyan"}).start();await vh(t,r,i,"table")})});io.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").addOption(new wh("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let e={event:b.CommandExecuted,args:["device","view",...n.target?["--target"]:[],...n.format==="json"?["--format","json"]:[]]};await ro(e,async()=>{let{manager:t}=await no();await Lk(t,n.target,n.format)})});var Ph=io.command("file").description("Transfer files between the host and a connected device");Ph.command("send").description("Send a local file to a device").option("--device <name|serial>","Target device (name or serial)").argument("<src>","Local file path to upload").argument("<dst>","Remote path on the device").action(async(n,e,t)=>{let{device:r}=t,i={event:b.CommandExecuted,args:["device","file","send",...r?["--device"]:[]]};await ro(i,async()=>{let{toolProvider:o}=await no();await Eh(o,"send",n,e,r)})});Ph.command("recv").description("Receive a file from a device to the host").option("--device <name|serial>","Target device (name or serial)").argument("<src>","Remote path on the device").argument("<dst>","Local file path to save").action(async(n,e,t)=>{let{device:r}=t,i={event:b.CommandExecuted,args:["device","file","recv",...r?["--device"]:[]]};await ro(i,async()=>{let{toolProvider:o}=await no();await Eh(o,"recv",n,e,r)})});io.command("sqlite3").description("Run sqlite3 on a connected device").allowUnknownOption().option("--device <name|serial>","Target device (name or serial)").argument("<db-path>","SQLite database path on the device").argument("[args...]","Arguments forwarded to sqlite3 as-is").action(async(n,e,t)=>{let r={event:b.CommandExecuted,args:["device","sqlite3",n,...t.device?["--device"]:[]]};await ro(r,async()=>{let{toolProvider:i}=await no();await Nk(i,n,e,t.device)})});var Ch=io;import{Argument as ud,Command as pd,InvalidArgumentError as ld,Option as Me}from"commander";import{green as ao,cyan as Xn,red as md,yellow as Er,gray as dd}from"colorette";import Yk from"ora";import Mk from"readline/promises";import{execa as Ih}from"execa";import*as br from"fs/promises";import*as id from"os";import*as sn from"path";var nd=`1/4:\r
|
|
100
101
|
---------------------------------------\r
|
|
101
102
|
Statement About HarmonyOS and Privacy\r
|
|
102
103
|
\r
|
|
@@ -1266,13 +1267,13 @@ Part I: Chinese mainland.\r
|
|
|
1266
1267
|
Part II: Aland Islands, Albania, Andorra, Australia, Austria, Belgium, Bonaire, Bosnia and Herzegovina, Bulgaria, Canada, Croatia, Curacao, Cyprus, Czech Republic, Denmark, Dutch Caribbean, Estonia, Faroe Islands, Finland, France, Germany, Gibraltar, Greece, Greenland, Guernsey, Hungary, Iceland, Israel, Italy, Jersey, Latvia, Liechtenstein, Lithuania, Luxembourg, Malta, Moldova, Monaco, Montenegro, Netherlands, New Zealand, North Macedonia, Norway, Poland, Portugal, Ireland, Romania, Saba, Saint Vincent and the Grenadines, San Marino, Serbia, Sint Eustatius, Sint Maarten, Slovakia, Slovenia, Spain, St. Martin, St. Pierre and Miquelon (France), Sweden, Switzerland, Turkey, Ukraine, United Kingdom, United States, Vatican City.\r
|
|
1267
1268
|
\r
|
|
1268
1269
|
Part III: Other countries and regions.\r
|
|
1269
|
-
---------------------------------------\r`;var
|
|
1270
|
-
`),
|
|
1271
|
-
`)}function
|
|
1272
|
-
${t}.`);return
|
|
1273
|
-
`,"utf8"),!0}catch{}return!1}async function
|
|
1270
|
+
---------------------------------------\r`;var Ok=new Set,Xs=new Map,od="HarmonyOS_Software_Service_Agreement",Dh=["Emulator license agreements are not accepted yet.","","Accept the agreements interactively (shows full text + y/N prompt):"," devecocli emulator license","","Or accept non-interactively (no prompt, for CI/scripts):"," devecocli emulator license accept","","To review the agreement text (read-only):"," devecocli emulator license view"].join(`
|
|
1271
|
+
`),Ah=Dh,sd="HarmonyOS_SDK_Agreement";function Rh(n,e){return`${n}\0${e}`}function Th(){Ok.clear(),Xs.clear()}var _k=Dh,Zt=class extends Error{constructor(e=_k){super(e),this.name="EmulatorLicenseBlockedError"}};function xh(n,e){return[n??"",e??""].join(`
|
|
1272
|
+
`)}function Lh(n){let e=n.normalize("NFKC"),t=e.match(/(\d+)\.(\d+)\.\d+/);if(t)return`${t[1]}.${t[2]}`;let r=e.match(/(\d+)\.(\d+)\b/);return r?`${r[1]}.${r[2]}`:null}function Fk(n){return`Emulator${n.trim()}`}function Nh(n){let e=Fk(n);if(process.platform==="win32"){let r=process.env.LOCALAPPDATA;if(!r)throw new Error("LOCALAPPDATA is not set; cannot resolve .emu_config path.");return sn.join(r,"Huawei",e,".emu_config")}if(process.platform==="darwin")return sn.join(id.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||sn.join(id.homedir(),".cache");return sn.join(t,"Huawei",e,".emu_config")}async function $k(n,e,t){let r=Rh(n,e),i=Xs.get(r);if(i!==void 0)return i;let o=await Ih(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=xh(o.stdout,o.stderr).trim();if(o.exitCode!==0||!s)throw new Zt(t);return Xs.set(r,s),s}function jk(n){let e=n[0],t=n[n.length-1];return(e==='"'||e==="'")&&e===t?n.slice(1,-1):n}function Hk(n){try{let e=JSON.parse(n);if(e&&typeof e=="object"&&!Array.isArray(e)){let t={};for(let[r,i]of Object.entries(e))t[r]={value:typeof i=="string"?i:String(i),delimiter:"json"};return t}}catch{return}}function Uk(n){let e=n.trim();if(!(!e||e.startsWith("#")))for(let t of["=",":"]){let r=e.indexOf(t);if(r<=0)continue;let i=e.slice(0,r).trim();if(!i||t===":"&&i.includes("//"))continue;let o=jk(e.slice(r+1).trim());return{key:i,entry:{value:o,delimiter:t}}}}function Bk(n){let e={};for(let t of n.split(/\r?\n/)){let r=Uk(t);r&&(e[r.key]=r.entry)}return e}function Wk(n){let e=n.trim();if(!e)return{};let t=Hk(e);return t||Bk(n)}function Vk(n){return typeof n!="string"?!1:n.normalize("NFKC").trim().toLowerCase()==="agree"}async function Mh(n,e,t,r){let i=await $k(n,e,r),o=Lh(i);if(!o)throw new Zt(r);let s=Nh(o),a;try{a=await br.readFile(s,"utf8")}catch(d){throw d.code==="ENOENT"?new Zt(r):d}let l=Wk(a)[t];if(!l)throw new Zt(r);if(l.delimiter==="=")throw new Zt(r);if(!Vk(l.value))throw new Zt(r)}async function ad(n,e){await Mh(n,e,od,Ah)}async function cd(n,e){await Mh(n,e,sd,Ah)}async function Gk(n,e){let t=await Ih(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),r=xh(t.stdout,t.stderr).trim();if(t.exitCode!==0||!r)throw new Error(`Emulator -version failed (exit ${String(t.exitCode)}); cannot resolve .emu_config path.`);let i=Rh(n,e);return Xs.set(i,r),r}async function Oh(n,e){let t=await Gk(n,e),r=Lh(t);if(!r)throw new Error(`Cannot parse Emulator major.minor from:
|
|
1273
|
+
${t}.`);return Nh(r)}function kh(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function qk(n,e,t){if(!t.startsWith("{"))return!1;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return r[od]="agree",r[sd]="agree",await br.writeFile(n,`${JSON.stringify(r,null,2)}
|
|
1274
|
+
`,"utf8"),!0}catch{}return!1}async function zk(n,e){let t=od,r=sd,i=[{k:t,re:new RegExp(`^\\s*${kh(t)}\\s*[:=]`)},{k:r,re:new RegExp(`^\\s*${kh(r)}\\s*[:=]`)}],o=e.length===0?[]:e.split(/\r?\n/),s=[],a=new Set;for(let c of o){let l=!1;for(let{k:d,re:g}of i)if(g.test(c)){s.push(`${d}:agree`),a.add(d),l=!0;break}l||s.push(c)}a.has(t)||s.push(`${t}:agree`),a.has(r)||s.push(`${r}:agree`),await br.writeFile(n,s.join(`
|
|
1274
1275
|
`)+(s.length>0?`
|
|
1275
|
-
`:""),"utf8")}async function
|
|
1276
|
+
`:""),"utf8")}async function _h(n){await br.mkdir(sn.dirname(n),{recursive:!0});let e="";try{e=await br.readFile(n,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}let t=e.trim();await qk(n,e,t)||await zk(n,e)}async function Fh(n,e){return console.log(nd),0}var Jk="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function $h(n,e){try{return await ad(n,e),await cd(n,e),!0}catch(t){if(t instanceof Zt)return!1;throw t}}async function jh(n,e){if(await $h(n,e))return console.log("Emulator license agreements are already accepted."),0;if(console.log(nd),!process.stdin.isTTY||!process.stdout.isTTY)return console.error("`devecocli emulator license` requires an interactive terminal.\nFor non-interactive environments, use: devecocli emulator license accept"),1;let r=Mk.createInterface({input:process.stdin,output:process.stdout}),i;try{i=await r.question(Jk)}finally{r.close()}let o=i.trim().toLowerCase();if(o!=="y"&&o!=="yes")return console.error("Agreements not accepted. Emulator features will remain blocked until accepted."),1;try{let s=await Oh(n,e);await _h(s),Th()}catch(s){return console.error(s.message),1}return console.log("Emulator license agreements accepted."),0}async function Hh(n,e){if(await $h(n,e))return console.log("Emulator license agreements are already accepted."),0;try{let t=await Oh(n,e);await _h(t),Th()}catch(t){return console.error(t.message),1}return console.log("Emulator license agreements accepted."),0}async function ft(n,e){let t=Date.now(),r=!0,i=null;try{await e()}catch(o){r=!1,i=B(o),console.error(md(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await k.track(n,o)}}var Kk=["ohos.qemu.hvd.name","const.product.name","const.product.model"],Uh=["open","half-open","close","vertical-open","single","double","triple","left-folded-right-half-folded","left-half-folded-right-expanded","left-expanded-right-folded","left-half-folded-right-folded","left-expanded-right-half-folded","left-half-folded-right-half-folded"],Xk=`
|
|
1276
1277
|
Folded state scene mappings:
|
|
1277
1278
|
foldableFold (3):
|
|
1278
1279
|
open Fully expanded state
|
|
@@ -1295,78 +1296,81 @@ Folded state scene mappings:
|
|
|
1295
1296
|
left-half-folded-right-folded
|
|
1296
1297
|
left-expanded-right-half-folded
|
|
1297
1298
|
left-half-folded-right-half-folded
|
|
1298
|
-
`,
|
|
1299
|
-
${
|
|
1300
|
-
${
|
|
1301
|
-
${
|
|
1302
|
-
`)}});
|
|
1303
|
-
Run \`devecocli emulator image list --all\` and use an exact OS Version value.`)}function Sh(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function bh(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let i=r,o=Xi(Bn(i,["osVersion","OsVersion","OSVersion","os_version"])),s=Xi(Bn(i,["deviceType","DeviceType","device_type"])),a=fh(Bn(i,["downloaded","Downloaded","isDownloaded"])),c=Xi(Bn(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=Xi(Bn(i,["releaseType","ReleaseType","release_type"])),d=fh(Bn(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,l,d,a],highlight:e&&a==="true"})}return t}function Rk(n){let e=n.trim();if(!e)return!0;let t=Sh(e);return t===null?!1:t.length===0?!0:bh(t,!0).length===0}function Tk(n,e){let t=n.trim();if(!t)return"";let r=Sh(t);if(!r)return n.trimEnd();let i=bh(r,e);return zt(Ik,i)}var $s=new Ul("image").description("HarmonyOS emulator system images (download, list, remove)");$s.command("download").description("Download system image").addOption(Wl(!1)).option("--os-version <version>","Example: HarmonyOS 5.1.1(19) or HarmonyOS 6.0.1(21) (required)").option("--force","Overwrite an existing image").action(async n=>{let e={event:b.CommandExecuted,args:["emulator","image","download",...n.deviceType?["--device-type"]:[],...n.osVersion?["--os-version"]:[],...n.force?["--force"]:[]]};await pt(e,async()=>{let{manager:t,toolProvider:r}=await mt();await $l(r.emulatorPath,r.sdkPath);let i=n.deviceType?.trim(),o=n.osVersion?.trim();if(!i)throw new S("Error: missing required option '--device-type <type>'","Missing required device type.");if(!o)throw new S("Error: misssing required option '--os-version <version>'","Missing required OS version.");await Dk(t,i,o),await t.installEmulatorImage({deviceType:i,osVersion:o,force:n.force===!0})})});$s.command("remove").description("Remove a downloaded system image").addOption(Wl(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let e={event:b.CommandExecuted,args:["emulator","image","remove","--device-type","--os-version"]};await pt(e,async()=>{let{manager:t}=await mt();await t.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})})});$s.command("list").description("List system images").addOption(Wl(!1)).option("--all","List all images (local and remote)").addOption(new ut("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let e={event:b.CommandExecuted,args:["emulator","image","list",...n.deviceType?["--device-type"]:[],...n.all?["--all"]:[],...n.format!=="table"?["--format"]:[]]};await pt(e,async()=>{let{manager:t}=await mt(),r;n.all?r=void 0:r=!0;let i=await t.listEmulatorImages({deviceType:n.deviceType,downloaded:r});if(Rk(i)){console.log(Sr(Ak));return}if(n.format==="json"){console.log(i.trimEnd());return}let o=Tk(i,n.all===!0);console.log(o)})});fe.addCommand($s);var js=new Ul("license").description("Review and accept emulator license agreements interactively (prints full text + y/N prompt)");js.command("view").description("Review agreement text (read-only, no changes)").action(async()=>{let n={event:b.CommandExecuted,args:["emulator","license","view"]};await pt(n,async()=>{let{toolProvider:e}=await mt(),t=await lh(e.emulatorPath,e.sdkPath);process.exitCode=t})});js.command("accept").description("Accept all emulator license agreements non-interactively (skips review and prompt)").action(async()=>{let n={event:b.CommandExecuted,args:["emulator","license","accept"]};await pt(n,async()=>{let{toolProvider:e}=await mt(),t=await ph(e.emulatorPath,e.sdkPath);process.exitCode=t})});js.action(async()=>{let n={event:b.CommandExecuted,args:["emulator","license"]};await pt(n,async()=>{let{toolProvider:e}=await mt(),t=await uh(e.emulatorPath,e.sdkPath);process.exitCode=t})});fe.addCommand(js);fe.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Yt(n,()=>({type:"shake"}),"shake"));fe.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Yt(n,()=>({type:"power"}),"power"));fe.command("rotate").description("Rotate emulator").addOption(new ut("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Hl("<direction>").choices(["left","right"])).action((n,e)=>Yt(e,()=>({type:"rotation",direction:n}),"rotate"));fe.command("volume").description("Change volume").addOption(new ut("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Hl("<direction>").choices(["up","down"])).action((n,e)=>Yt(e,()=>({type:"volume",direction:n}),"volume"));fe.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",ZC).action((n,e)=>Yt(e,()=>({type:"folded-state",state:tk(n)}),"fold"));fe.command("battery").description("Set battery level and/or charging status").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--level <0-100>","Battery level, SOC (charging: 0-100; not charging: 1-100)").addOption(new ut("--status <status>","Charging status").choices(["charging","discharging"])).action(n=>Yt(n,()=>bk(n),"battery"));fe.command("geolocation").description("Inject geographic coordinates and direction").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--longitude <value>","Longitude (-180.0 to 180.0)").option("--latitude <value>","Latitude (-90.0 to 90.0)").option("--altitude <value>","Altitude (-10000.0 to 10000.0)").option("--direction <value>","Heading direction in degrees (0.00 to 359.99)").action(n=>Yt(n,()=>wk(n),"geolocation"));fe.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new Hl("<type>","Motion simulation scene").choices(["outdoorRunning","outdoorCycling","drivingNavigation"])).action((n,e)=>{let t={outdoorRunning:{type:"outdoor-running"},outdoorCycling:{type:"outdoor-cycling"},drivingNavigation:{type:"driving-navigation"}};return Yt(e,()=>t[n],"scene")});fe.command("sensor").description("Inject sensor data").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--light-intensity <value>","Light sensor (0 to 100000)").option("--humidity <value>","Humidity sensor (0 to 100)").option("--temperature <value>","Temperature sensor (-273.1 to 100)").option("--steps <value>","Steps sensor (integer 0 to 10000)").option("--heartrate <value>","Heart rate sensor (integer 0 to 255)").action(n=>Yt(n,()=>Sk(n),"sensor"));fe.command("list").description("List all emulator instances").addOption(new ut("--details","Output the raw JSON of `Emulator -list -details` without transformation").conflicts("format")).addOption(new ut("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let e={event:b.CommandExecuted,args:["emulator","list",...n.details?["--details"]:[],...n.format!=="table"?["--format"]:[]]};await pt(e,async()=>{let{manager:t,toolProvider:r}=await mt();if(n.details){let o=await t.listEmulatorDetails();console.log(o.trimEnd());return}let i=n.format==="table"?KC({text:"Listing emulators\u2026",color:"cyan"}).start():void 0;await dk(t,r.hdcPath,n.format,i)})});fe.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let e={event:b.CommandExecuted,args:["emulator","start"],emulatorMemory:"unknown",hotBoot:null};await pt(e,async()=>{let{manager:t,toolProvider:r}=await mt();if(await Fl(r.emulatorPath,r.sdkPath),!n?.length)throw new S("Error: missing required argument 'names'","Missing required emulator name.");let i=await gk(t,r.hdcPath,n);e.emulatorMemory=i.emulatorMemory,e.hotBoot=i.hotBoot})});fe.command("stop <names...>").description("Stop one or more emulator instances (by name or serial,e.g.,127.0.0.1:<port>)").action(async n=>{let e={event:b.CommandExecuted,args:["emulator","stop"]};await pt(e,async()=>{let{manager:t,toolProvider:r}=await mt();if(!n?.length){console.error(Bl("Error: missing required argument 'names'")),process.exitCode=1;return}await vk(t,r.hdcPath,n)})});var xk=fe.command("create <name>").description("Create a local emulator instance.").addOption(Pk()).requiredOption("--os-version <version>",'Downloaded image label. which will be quoted in PowerShell (e.g. "HarmonyOS 6.0.1(21)") or be used in the format --os-version="\u2026";For details, run`devecocli emulator image list`').addOption(new ut("--path, --instance-path <path>","Emulator instance path")).option("--image-root <path>","Emulator image path").option("--screen-profile <model>","Emulator screen profile").addOption(new ut("--screen <config...>",'Screen: "width(px) height(px) DPI screen-diagonal-length(inch)" (720-3500, 720-3500, 240-640, 3.5-9); pass two values for a foldable device')).option("--storage <size>","Storage size in GB (2-1023)").option("--memory <size>","Memory size in GB (2-32)").addOption(new ut("--hot-boot <boolean>","Enable or disable hot boot").choices(["true","false"])).option("--force","Overwrite an existing emulator instance");xk.action(async(n,e)=>{let t={event:b.CommandExecuted,args:["emulator","create",...kk(e)]};await pt(t,async()=>{if(!e.osVersion.trim())throw new Error("--os-version must not be empty.");let r={name:n,deviceType:e.deviceType,osVersion:e.osVersion,instancePath:e.instancePath,imageRoot:e.imageRoot,screenProfile:e.screenProfile,screen:Ck(e.screen),storage:e.storage===void 0?void 0:on("--storage",e.storage,2,1023),memory:e.memory===void 0?void 0:on("--memory",e.memory,2,32),hotBoot:e.hotBoot===void 0?void 0:e.hotBoot==="true",force:e.force===!0},{manager:i}=await mt();console.log(Wn(`Creating emulator "${n}"...`)),await i.createVirtualDevice(r),console.log(Zi(`Emulator "${n}" created successfully.`))})});fe.command("delete <name>").description("Delete a local emulator instance").addOption(new ut("--path, --instance-path <path>","Emulator instance path")).action(async(n,e)=>{let t={event:b.CommandExecuted,args:["emulator","delete",...e.instancePath!==void 0?["--instance-path"]:[]]};await pt(t,async()=>{let{manager:r}=await mt();console.log(Wn(`Deleting emulator "${n}"...`));let i=await r.deleteVirtualDevice(n,e.instancePath);console.log(Zi(`Emulator "${i}" deleted successfully.`))})});var Eh=fe;import{Command as tI}from"commander";import{red as Kl,cyan as Ot}from"colorette";import*as Gh from"readline";import*as Wh from"crypto";import*as Ph from"http";import*as Ch from"crypto";import{URL as Lk}from"url";var Hs=class{server=null;port=0;clientSecret;callbackPath="/callback";resolveCallback=null;rejectCallback=null;timeoutId=null;baseUrl;successRedirectUrl;failedRedirectUrl;constructor(e,t,r,i){this.clientSecret=e,this.baseUrl=t,this.successRedirectUrl=r,this.failedRedirectUrl=i}async start(){return new Promise((e,t)=>{let r=Ph.createServer((i,o)=>{this.handleRequest(i,o)});r.keepAliveTimeout=1,r.on("error",i=>{t(new Error("Failed to start local auth server",{cause:i}))}),r.listen(0,"127.0.0.1",()=>{this.server=r;let i=r.address();this.port=i.port,e()})})}async waitForCallback(e=3e4){return new Promise((t,r)=>{this.resolveCallback=i=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),t(i)},this.rejectCallback=i=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),r(i)},this.timeoutId=setTimeout(()=>{this.timeoutId=null,this.rejectCallback?.(new Error("Callback timeout"))},e)})}async stop(){return this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.server?new Promise(e=>{let t=this.server;this.server=null,typeof t.closeAllConnections=="function"&&t.closeAllConnections();let r=setTimeout(()=>{e()},100);t.close(()=>{clearTimeout(r),e()})}):Promise.resolve()}handleRequest(e,t){let r=e.headers.host||"";if(![`127.0.0.1:${this.port}`,`localhost:${this.port}`].includes(r.toLowerCase())){t.writeHead(400),t.end("Bad Host");return}let o=new Lk(e.url??"",`http://${r}`);if(o.pathname!==this.callbackPath){t.writeHead(404),t.end("Not Found");return}try{let s=o.searchParams;e.method==="POST"?this.readBody(e,t,s):this.handleCallbackRequest(e,t,s,"")}catch(s){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(s)}}readBody(e,t,r){let i="",o=0,s=65536;e.on("data",a=>{if(o+=a.length,o>s){e.destroy(new Error("Request body too large"));return}i+=a.toString()}),e.on("end",()=>{this.handleCallbackRequest(e,t,r,i)})}handleCallbackRequest(e,t,r,i){try{let o=this.parseParams(r,i),s=o.get("code"),a=o.get("tempToken"),c=o.get("siteId"),l=o.get("quit");if(!this.validateCode(s)){t.writeHead(400),t.end("Bad Request");return}if(this.isQuitRequest(l)){this.handleQuitRequest(t);return}if(!a||!c){t.writeHead(400),t.end("Bad Request");return}let d={tempToken:a,siteId:c,quit:l??void 0};this.resolveCallback?.(d),this.sendSuccessResponse(t)}catch(o){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(o)}}parseParams(e,t){return t&&t.trim()?new URLSearchParams(t):e}validateCode(e){let t=Buffer.from(e||"","utf8"),r=Buffer.from(this.clientSecret,"utf8");return t.length===r.length&&Ch.timingSafeEqual(t,r)}isQuitRequest(e){return e==="true"||e==="access_denied"||e==="quit"}handleQuitRequest(e){this.rejectCallback?.(new Error("User quit the login process")),e.writeHead(302,{Location:`${this.baseUrl}/${this.failedRedirectUrl}`}),e.end()}sendSuccessResponse(e){e.writeHead(302,{Location:`${this.baseUrl}/${this.successRedirectUrl}`}),e.end()}getPort(){return this.port}};import*as We from"fs";import*as br from"path";import{homedir as jk}from"os";var Kt={};pw(Kt,{LocalCrypto:()=>Kt,decryptForLocalStorage:()=>_k,decryptForLocalStorageFromDirectory:()=>Fk,encryptForLocalStorage:()=>Ok,isEncryptedBlob:()=>$k});import*as se from"fs";import*as Me from"path";import*as Be from"crypto";import*as Ih from"os";import{homedir as Ah}from"os";var Ne=class extends Error{constructor(e){super(e),this.name="DefinedError"}};var Qi=Ur.ALGORITHM,Dh=Ur.IV_LENGTH,eo=Ur.KEY_LENGTH,to=Ur.KEY_LENGTH,sn=Ur.KEK_VERSIONS,Us=process.env.DEVECO_CLI_DATA_DIR||Me.join(Ah(),Pe.CONFIG_DIR_NAME,Pe.APP_NAME),Bs=Me.join(Ah(),".local","share",Pe.APP_NAME,"keys"),Vn=Me.join(Us,Pe.KEY_FILE_NAME);function kh(n){return Ih.platform()==="win32"?`Permission denied. Please run as administrator or grant write permission to ${n}.`:`Permission denied. You can try: sudo chown -R $(whoami) ${n}`}function Vl(n){return Me.join(Bs,`${n}.bin`)}function Rh(){if(!se.existsSync(Us))try{se.mkdirSync(Us,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new Ne(kh(Us)):n}if(!se.existsSync(Bs))try{se.mkdirSync(Bs,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new Ne(kh(Me.dirname(Bs))):n}}function Th(){Rh();for(let n of sn){let e=Vl(n);se.existsSync(e)||se.writeFileSync(e,Be.randomBytes(eo),{mode:384})}}function xh(n){if(!sn.includes(n))throw new Error(`Invalid kekId: ${n}`);Th();let e=Vl(n),t=se.readFileSync(e);if(t.length===eo)return t;let r=Be.randomBytes(eo);return se.writeFileSync(e,r,{mode:384}),r}function Gl(n,e){let t=Be.randomBytes(Dh),r=xh(e),i=Be.createCipheriv(Qi,r,t),o=Buffer.concat([i.update(n),i.final()]),s=i.getAuthTag();return{version:1,algorithm:Qi,kekId:e,encryptedDek:o.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function Lh(n,e){return Nh(Buffer.from(n.encryptedDek,"base64"),e,n.iv,n.authTag)}function Nh(n,e,t,r){let i=Be.createDecipheriv(Qi,e,Buffer.from(t,"base64"));return i.setAuthTag(Buffer.from(r,"base64")),Buffer.concat([i.update(n),i.final()])}function Mh(n,e){return Nh(Buffer.from(n.ciphertext,"base64"),e,n.iv,n.authTag).toString("utf8")}function Nk(){if(Th(),se.existsSync(Vn))return;let n=Be.randomBytes(to),e=Gl(n,sn[0]);se.writeFileSync(Vn,JSON.stringify(e,null,2),{mode:384})}function Oh(){Nk();let n=JSON.parse(se.readFileSync(Vn,"utf8")),e=Lh(n,xh(n.kekId));if(e.length===to)return e;let t=Be.randomBytes(to),r=Gl(t,sn[0]);return se.writeFileSync(Vn,JSON.stringify(r,null,2),{mode:384}),t}function Mk(){Rh();for(let t of sn){let r=Vl(t);se.existsSync(r)||se.writeFileSync(r,Be.randomBytes(eo),{mode:384})}if(se.existsSync(Vn))return;let n=Be.randomBytes(to),e=Gl(n,sn[0]);se.writeFileSync(Vn,JSON.stringify(e,null,2),{mode:384})}function Ok(n){let e=Oh(),t=Be.randomBytes(Dh),r=Be.createCipheriv(Qi,e,t),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o=r.getAuthTag();return{version:1,algorithm:Qi,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:o.toString("base64"),timeStamp:Date.now()}}function _k(n){try{return Mh(n,Oh())}catch{throw Mk(),new Error("Failed to decrypt local ciphertext")}}function Fk(n,e){let t=Me.join(e,Pe.KEY_FILE_NAME),r=JSON.parse(se.readFileSync(t,"utf8"));if(!sn.includes(r.kekId))throw new Error(`Invalid kekId: ${r.kekId}`);let i=Me.join(e,"keys",`${r.kekId}.bin`),o=Me.resolve(i),s=Me.resolve(Me.join(e,"keys"));if(!o.startsWith(s+Me.sep)&&o!==s)throw new Error("kekId resolves outside the keys directory");let a=se.readFileSync(o);if(a.length!==eo)throw new Error("Invalid external root key");let c=Lh(r,a);if(c.length!==to)throw new Error("Invalid external data encryption key");return Mh(n,c)}function $k(n){if(!n||typeof n!="object")return!1;let e=n;return e.algorithm==="aes-256-gcm"&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}function Ve(){return process.env.DEVECO_CLI_AUTH_SOURCE===Pe.AUTH_SOURCE_DEVECO_CODE}var Ws=class{getLocalTokenFilePath(){let e=process.env.DEVECO_CLI_DATA_DIR||br.join(jk(),Pe.CONFIG_DIR_NAME,Pe.APP_NAME);return br.join(e,Pe.TOKEN_FILE_NAME)}ensureConfigDir(){let e=br.dirname(this.getLocalTokenFilePath());We.existsSync(e)||We.mkdirSync(e,{recursive:!0,mode:448})}async saveJwtToken(e){if(!e)throw new Error("Token is empty");let t=Kt.encryptForLocalStorage(e);this.ensureConfigDir();let r=this.getLocalTokenFilePath();We.writeFileSync(r,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){return Ve()?this.loadDevecoCodeToken():this.loadLocalJwtToken()}loadDevecoCodeToken(){if(!Ve())return null;let e=process.env.DEVECO_CODE_AUTH_DIR?.trim();if(!e)return null;let t=br.resolve(e);try{let r=br.join(t,Pe.TOKEN_FILE_NAME);if(!We.existsSync(r))return null;let i=JSON.parse(We.readFileSync(r,"utf8"));return Kt.isEncryptedBlob(i)?Kt.decryptForLocalStorageFromDirectory(i,e):null}catch{return null}}async loadLocalJwtToken(){let e=this.getLocalTokenFilePath();try{if(!We.existsSync(e))return null;let t=JSON.parse(We.readFileSync(e,"utf8"));return Kt.isEncryptedBlob(t)?Kt.decryptForLocalStorage(t):null}catch(t){let r=t.code;return r==="EACCES"||r==="EPERM"||r==="ENOENT"||await this.clearToken(),null}}async clearToken(){if(Ve()){p("clearToken: skipped, session managed by DevEco Code");return}let e=this.getLocalTokenFilePath();try{We.existsSync(e)&&We.unlinkSync(e)}catch(t){throw new Error("Failed to clear token",{cause:t})}}},Xt=new Ws;import{spawn as Hk}from"child_process";function Uk(n){try{let e=new URL(n);return!(!["http:","https:"].includes(e.protocol)||e.hostname===""||n.includes('"'))}catch{return!1}}function Bk(n){return n.replace(/[&|<>()^%!]/g,e=>`^${e}`)}async function _h(n){if(!Uk(n))throw new Error(`Invalid URL: ${JSON.stringify(n)}`);let e,t;switch(process.platform){case"win32":e="cmd",t=["/c","start",'""',Bk(n)];break;case"darwin":e="open",t=[n];break;default:e="xdg-open",t=[n];break}let r=Hk(e,t,{stdio:"ignore",shell:!1,windowsHide:!0});return new Promise((i,o)=>{r.on("error",s=>{o(new Error("Failed to open browser",{cause:s}))}),r.on("close",s=>{s===0?i():o(new Error(`Browser process exited with code ${s}`))})})}import qk from"axios";var Wk={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function Vk(n){try{return new URL(n)}catch{return null}}function Fh(n){var e=(typeof n=="string"?Vk(n):n)||{},t=e.protocol,r=e.host,i=e.port;if(typeof r!="string"||!r||typeof t!="string"||(t=t.split(":",1)[0],r=r.replace(/:\d*$/,""),i=parseInt(i)||Wk[t]||0,!Gk(r,i)))return"";var o=ql(t+"_proxy")||ql("all_proxy");return o&&o.indexOf("://")===-1&&(o=t+"://"+o),o}function Gk(n,e){var t=ql("no_proxy").toLowerCase();return t?t==="*"?!1:t.split(/[,\s]/).every(function(r){if(!r)return!0;var i=r.match(/^(.+):(\d+)$/),o=i?i[1]:r,s=i?parseInt(i[2]):0;return s&&s!==e?!0:/^[.*]/.test(o)?(o.charAt(0)==="*"&&(o=o.slice(1)),!n.endsWith(o)):n!==o}):!0}function ql(n){return process.env[n.toLowerCase()]||process.env[n.toUpperCase()]||""}function zk(n){let e=new URL(n);return{protocol:e.protocol,host:e.hostname,port:e.port?Number.parseInt(e.port,10):e.protocol==="https:"?443:80,auth:{username:decodeURIComponent(e.username),password:decodeURIComponent(e.password)}}}var zl=class{client;constructor(){let e={timeout:fi.HTTP_TIMEOUT_MS,headers:{"User-Agent":To.USER_AGENT,"accept-language":To.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=qk.create(e),this.client.interceptors.request.use(t=>{let r=Fh(t.url??"");return t.proxy=r?zk(r):!1,t}),this.client.interceptors.response.use(t=>t,t=>{let r=`Network connection failed (${t.code}). Please check your proxy configuration or network settings`;throw new Error(`${t.message}
|
|
1304
|
-
|
|
1305
|
-
`)}function nI(){return new Promise(n=>{let e=Gh.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),n()})})}var ro=new tI("auth").description("Authentication commands (login, logout, status, team)");ro.command("login").description("Log in to your Huawei Developer account").action(async()=>{if(Ve()){console.log(Kl("Login is managed by DevEco Code. Login from DevEco Code instead."));return}let n={event:b.CommandExecuted,args:["auth","login"]};await zs(n,async()=>{let e=await Oe.getUserInfo();if(e){console.log(Ot(`Already logged in, User Name:${e.userName}`));return}console.log(Ot("Starting login process...")),console.log(Ot("Press Enter to open browser for login...")),await nI();let t=await Oe.login();console.log(Ot(`Login successful. Logged in as ${t.userName}.`))},e=>{throw e instanceof Ne||(e instanceof Error?e.message:String(e)).includes("Network connection failed")?e:new Error("Login failed",{cause:e})})});ro.command("logout").description("Log out of your Huawei Developer account").action(async()=>{if(Ve()){console.log(Kl("Login is managed by DevEco Code. Log out from DevEco Code instead."));return}let n={event:b.CommandExecuted,args:["auth","logout"]};await zs(n,async()=>{let e=await Oe.logout();console.log(e?Ot("Logout successful"):Ot("Already logged out."))},e=>new Error("Logout failed",{cause:e}))});ro.command("status").description("Show the currently logged-in user").action(async()=>{let n={event:b.CommandExecuted,args:["auth","status"]};await zs(n,async()=>{let e=await Oe.getUserInfo();if(!e){console.log(Ot("Not logged in"));return}console.log(Ot(`Current user: ${e.userName}`))},()=>{console.log(Ot("Not logged in"))})});var iI=ro.command("team").description("Team-related commands");iI.command("list").description("List team accounts the current user has joined").action(async()=>{let n={event:b.CommandExecuted,args:["auth","team","list"]};await zs(n,async()=>{let e=await Er();console.log(rI(e.teamList))},e=>{if(e instanceof Ne){console.log(Kl(e.message));return}throw new Error("Failed to list teams",{cause:e})})});var qh=ro;import{Command as wI}from"commander";import{green as SI,red as ao,cyan as fg,yellow as hg,dim as gg}from"colorette";import bI from"p-limit";import oI from"ora";var tt=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=oI(e),this.spinner.start(),this.isRunning=!0}stop(){this.spinner&&this.isRunning&&(this.spinner.stop(),this.isRunning=!1)}succeed(e){this.spinner&&(this.spinner.succeed(e),this.isRunning=!1)}fail(e){this.spinner&&(this.spinner.fail(e),this.isRunning=!1)}};import*as Jh from"fs";import*as Xl from"path";import{homedir as zh}from"os";function Pr(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}var Yh=["DevEco"];async function Js(){let n=await N.get(st.TAGS_API_URL),t=Ys(n,"Tags API").data.skill.filter(r=>r.name==="HMOS");if(t.length===0)throw new Error("No HMOS tag found.");return t.map(r=>r.id)}async function sI(n){let e=[],t=st.DEFAULT_PAGE_SIZE,r=st.DEFAULT_MAX_PAGES,i=1;for(;i<=r;){let o=await N.post(st.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:i,pageSize:t,tagIds:[n]}}),s=Ys(o,"Skills API");if(e.push(...s.data.list),s.data.list.length<t)break;i++}return e}async function Zl(n){let e=new Map,t=n.map(i=>sI(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=>!Yh.includes(o.name)))}async function aI(n,e){let t=await N.post(st.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:st.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return Ys(t,"Skills API").data.list}async function Ql(n,e){let t=new Map,r=e.map(o=>aI(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=>!Yh.includes(s.name)))}function Kh(n){Pr(n);let e=[];for(let[,t]of Object.entries(yt)){let r=E.ensurePathWithinRoot(Xl.join(zh(),t.path),Xl.join(zh(),t.path,n));Jh.existsSync(r)&&e.push(t.displayName)}return e.sort()}function Ys(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=N.parseJson(n);if(t.code!==st.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Xh(n){Pr(n);let e=`${st.SKILL_API_BASE}/${n}/checksum`,t=await N.get(e);return Ys(t,"Checksum API").data}import cI from"adm-zip";import lI from"crypto";import{timingSafeEqual as dI}from"crypto";import Qh from"fs";import ue from"path";import{fileURLToPath as uI}from"url";import{homedir as eg}from"os";import{red as pI}from"colorette";var Qt=Qh.promises;function Zh(n,e){let t=ue.resolve(e),r=ue.resolve(n),i=ue.relative(r,t);if(i.startsWith("..")||ue.isAbsolute(i))throw new Error(`Path traversal detected: ${e}.`)}function ed(n){return ue.isAbsolute(n)?n:ue.resolve(process.cwd(),n)}function mI(n){return lI.createHash("sha256").update(n).digest("hex")}async function fI(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=mI(n),i=e.sha256.toLowerCase(),o=Buffer.from(r,"hex"),s=Buffer.from(i,"hex");if(o.length!==s.length||!dI(o,s))throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function tg(n){Pr(n);let e=`${st.SKILL_API_BASE}/${n}/install?format=zip`,t=await N.getBinary(e),r=await Xh(n);return await fI(t,r),t}async function hI(n,e,t){Pr(t);let r=new cI(n),i=r.getEntries();try{await Qt.stat(e)}catch{await Qt.mkdir(e,{recursive:!0})}let o=ue.join(e,t);Zh(e,o);for(let s of i){let a=ue.join(o,s.entryName);Zh(o,a)}r.extractAllTo(o,!0)}async function td(n){let e=yt[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(yt).join(", ")}`);let t=ue.join(eg(),e.path.replace("/skills",""));try{return await Qt.access(t),!0}catch{return!1}}function rd(n){let e=yt[n];return ue.join(eg(),e.path)}function gI(n){let e=yt[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(yt).join(", ")}`);return e}function nd(n,e){let t=gI(e),r="projectPath"in t?t.projectPath:ue.join("."+e,"skills");return ue.join(n,r)}async function yI(n,e,t){Pr(e);let r=ue.join(n,e);try{if(await Qt.access(r),t)await Qt.rm(r,{recursive:!0,force:!0});else return console.log(`Skill ${e} exists in ${n}.`),{skillDir:r,shouldSkip:!0}}catch{}return{skillDir:r,shouldSkip:!1}}async function id(n,e,t){await hI(n,e,t),console.log(`Skill ${t} installed to ${ue.join(e,t)}.`)}async function od(n,e,t){let r=ue.join(e,t);await Qt.mkdir(r,{recursive:!0});let i=ue.join(r,ue.basename(n));await Qt.copyFile(n,i),console.log(`Skill ${t} installed to ${r}.`)}function rg(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(pI(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function qn(n,e,t,r){try{let i=await e(),{shouldSkip:o}=await yI(i,n,r);return o?{success:!0,skipped:!0}:(await t(i),{success:!0})}catch(i){return rg(n,i,"Installation failed")}}async function sd(n,e){try{Pr(n);let t=await e(),r=ue.join(t,n);try{await Qt.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await Qt.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return rg(n,t,"Removal failed")}}async function ng(n,e,t,r=!1){return qn(n,()=>rd(e),i=>id(t,i,n),r)}async function ig(n,e,t,r=!1){return qn(n,()=>t,i=>id(e,i,n),r)}async function og(n,e,t,r,i=!1){return qn(n,()=>nd(t,r),o=>id(e,o,n),i)}async function sg(n,e,t,r=!1){return qn(n,()=>rd(t),i=>od(e,i,n),r)}async function ag(n,e,t,r,i=!1){return qn(n,()=>nd(t,r),o=>od(e,o,n),i)}async function cg(n,e,t,r=!1){return qn(n,()=>t,i=>od(e,i,n),r)}async function ad(n,e){return sd(n,()=>rd(e))}async function lg(n,e){return sd(n,()=>e)}async function dg(n,e,t){return sd(n,()=>nd(e,t))}function ug(){let e=ue.dirname(uI(import.meta.url));for(;;){let t=ue.join(e,"SKILL.md");if(Qh.existsSync(t))return t;let r=ue.dirname(e);if(r===e)break;e=r}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import pg from"fs";import{cyan as vI}from"colorette";async function no(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await td(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function io(){let n=[];for(let e of Object.keys(yt))await td(e)&&n.push(e);return n}function oo(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(vI("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function Cr(n,e,t){if(!pg.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!pg.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function so(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?ed(n):void 0,resolvedProject:e?ed(e):void 0}}async function Ks(n,e,t){let r=[],i=[],o;if(e?o=e:t&&n.agent?i=(await no(n.agent)).map(a=>({project:t,agent:a})):t?i=(await io()).map(a=>({project:t,agent:a})):n.agent?r=await no(n.agent):r=await io(),!o&&r.length===0&&i.length===0)throw new Error("No agents found. Install an AI agent (cursor, opencode, etc.) or use `--path` for a custom location.");return{agents:r,projectAgents:i,customPath:o}}var yg="deveco";async function EI(n){let e=await Js();if(n.all)return(await Zl(e)).map(r=>r.enName);{let r=(await Ql(n.skill,e)).find(i=>i.enName===n.skill);if(!r)throw new cn("errorCode",`Skill "${n.skill}" not found`);return[r.enName]}}async function PI(n,e,t,r){let i=[];if(t.customPath){let o=await ig(n,e,t.customPath,r);return i.push(o),i}for(let o of t.agents){let s=await ng(n,o,e,r);i.push(s)}for(let{project:o,agent:s}of t.projectAgents){let a=await og(n,e,o,s,r);i.push(a)}return i}function CI(n){if(n.all&&n.skill)throw new cn("errorCode","`--all` and `--skill` cannot be specified together.");if(!n.all&&!n.skill)throw new cn("errorCode","Must specify `--all` or `--skill`");let{resolvedPath:e,resolvedProject:t}=so(n.path,n.project,n.agent);return t&&Cr(t,"Project directory",n.force),e&&Cr(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}function kI(n,e,t){return!!(e||t||n.path||n.project||n.agent)}function II(){return{agents:[yg],projectAgents:[],customPath:void 0}}async function AI(n,e,t){let r=Ve()&&!kI(n,e,t)?II():await Ks(n,e,t);return{skillNames:await EI(n),targets:r}}async function DI(n,e,t,r){let i=[],o=0,s=n.length,a=bI(5),c=n.map(l=>a(()=>RI(l)));for(let l=0;l<n.length;l++){let d=n[l],g=s>1?` (${l+1}/${s})`:"";r.start(`Installing ${d}${g}...`);let y=await c[l];if(!y.success){r.fail(),console.log(ao(`${d}: Download failed - ${y.error}`)),i.push({success:!1});continue}o+=y.buffer.length,r.stop();let I=await PI(d,y.buffer,e,t);i.push(...I)}return{results:i,diskBytes:o}}async function RI(n){try{let e=await tg(n);return{name:n,buffer:e,success:!0}}catch(e){let t=e instanceof Error?e.message:"unknown error";return{name:n,error:t,success:!1}}}async function TI(n){let e=new tt;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=CI(n),{skillNames:i,targets:o}=await AI(n,t,r),{results:s,diskBytes:a}=await DI(i,o,n.force||!1,e);return e.stop(),oo(s),{diskBytes:a,results:s}}catch(t){throw e.stop(),t}}function vg(n){let e=n.length,t=n.filter(s=>s.success&&!s.skipped).length,r=n.filter(s=>s.skipped).length,i=n.filter(s=>!s.success).length,o=[...new Set(n.filter(s=>!s.success&&typeof s.error=="string").map(s=>xI(s.error)))];return{opTotal:e,opSuccess:t,opFailed:i,opSkipped:r,...o.length>0?{failedErrors:o}:{}}}function xI(n){let e=/^([A-Za-z_][A-Za-z0-9_-]*)/.exec(n.trim());return e?e[1].slice(0,32):"error"}var cn=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function LI(n){let e=n;return n instanceof cn?n.code:e.code??e.name??"UnknownError"}function Zs(n,e={}){return["skills",n,...e.all?["--all"]:[],...e.long?["--long"]:[],...e.skill?["--skill"]:[],...e.force?["--force"]:[],...e.agent?["--agent",e.agent]:[],...e.project?["--project"]:[],...e.path?["--path"]:[]]}async function Qs(n,e,t){let r=Date.now(),i=!0,o=null,s={};try{s=await e()}catch(a){throw i=!1,o=LI(a),a}finally{let a={event:b.SkillOperation,subAction:n,args:t,...s};await k.track(a,{duration_ms:Date.now()-r,success:i,error_code:o})}}function NI(n){return Qs("add",async()=>{let{diskBytes:e,results:t}=await TI(n);return{diskUsage:te(e),...n.skill?{skillName:n.skill}:{},...vg(t)}},Zs("add",n))}function MI(n){let{resolvedPath:e,resolvedProject:t}=so(n.path,n.project,n.agent);return t&&Cr(t,"Project directory"),e&&Cr(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function OI(n,e){let t=new tt;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:i}=MI(e);t.stop();let o=await _I(e,n,r,i);return t.stop(),oo(o),o}catch(r){throw t.stop(),r}}function mg(n,e=""){if(n.length===0)throw new cn("errorCode",`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function Xs(n,e){let t=[];for(let r of e){let i=r.type==="agent"?await ad(n,r.agent):await dg(n,r.project,r.agent);t.push(i)}return t}async function _I(n,e,t,r){if(t)return[await lg(e,t)];if(r&&n.agent){let a=(await no(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return Xs(e,a)}if(r){let s=await io();mg(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return Xs(e,a)}if(n.agent){let a=(await no(n.agent)).map(c=>({type:"agent",agent:c}));return Xs(e,a)}if(Ve())return[await ad(e,yg)];let i=await io();mg(i,"or use --path for a custom location.");let o=i.map(s=>({type:"agent",agent:s}));return Xs(e,o)}var co=new wI("skills").description("Manage HarmonyOS skills");co.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async n=>{try{await Qs("list",async()=>{let e=new tt;try{e.start("Fetching skills...");let t=await Js(),r=await Zl(t);if(r.length===0)return e.stop(),console.log(hg("No skills available.")),{resultTotal:0};e.succeed(`Fetched ${r.length} skills`);for(let i of r)if(n.long){console.log(fg(i.enName)),console.log(gg(i.description));let o=Kh(i.enName);o.length>0&&console.log(SI(`Installed for: ${o.join(", ")}`)),console.log()}else console.log(i.enName);return{resultTotal:r.length}}finally{e.stop()}},Zs("list",n))}catch(e){console.error(ao(e.message)),process.exit(1)}});co.command("find <keyword>").description("Search skills by keyword").action(async n=>{try{await Qs("find",async()=>{let e=new tt;try{e.start("Searching skills...");let t=await Js(),r=await Ql(n,t);if(r.length===0)return console.log(hg(`No skills found matching '${n}'.`)),e.stop(),{resultTotal:0,queryLen:n.length,keyword:n};e.succeed(`Found ${r.length} skills.`);for(let i of r)console.log(fg(i.enName)),console.log(gg(i.description)),console.log();return{resultTotal:r.length,queryLen:n.length,keyword:n}}finally{e.stop()}},Zs("find"))}catch(e){console.error(ao(e.message)),process.exit(1)}});co.command("add").description("Install skills to AI agents").option("--all","Install all available skills").option("--agent <agents>","Target agents, comma-separated; Omit to install to all available agents").option("--skill <skill-name>","Name of the skill to install").option("-f, --force","Overwrite an existing skill installation").option("--project <path>","Project root directory for skill installation").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").action(async n=>{try{await NI(n)}catch(e){console.error(ao(e.message)),process.exit(1)}});co.command("remove").description("Remove an installed skill from AI agents").requiredOption("--skill <skill-name>","Name of the skill to remove").option("--agent <agents>","Target agents, comma-separated.Omit to remove from all available agents").option("--project <path>","Project root directory for skill removal").option("--path <path>","Path for skill removal").action(async n=>{try{await Qs("remove",async()=>{let e=await OI(n.skill,n);return{skillName:n.skill,...vg(e)}},Zs("remove",n))}catch(e){console.error(ao(e.message)),process.exit(1)}});var wg=co;import{Command as FI,InvalidArgumentError as ea}from"commander";import{cyan as cd,red as bg}from"colorette";import $I from"ora";function jI(n){return["log",...n.device?["--device"]:[],...n.crash?["--crash"]:[],...n.level?["--level"]:[],...n.bundleName?["--bundle-name"]:[],...n.keyword?["--keyword"]:[],...n.tail!==void 0?["--tail"]:[],...n.from!==void 0?["--from"]:[],...n.to!==void 0?["--to"]:[],...n.follow?["--follow"]:[]]}function HI(n){return{event:b.CommandExecuted,args:jI(n),logType:n.crash?"crash":"common",level:n.level??"ALL",bundleName:n.bundleName??"ALL"}}function UI(n){return n instanceof S?n.traceMessage:n instanceof Error?n.code??n.name:"UnknownError"}async function BI(n,e){let t=Date.now(),r=!0,i=null;try{await e()}catch(o){r=!1,i=UI(o),console.error(bg(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await k.track(n,o).catch(()=>{})}}function WI(n){try{return E.parsePositiveInteger(n,"tail")}catch{throw new ea("`tail` must be a positive integer.")}}function Sg(n,e){try{return E.parseDurationToSeconds(n,e)}catch{throw new ea(`${e} must be a valid duration string (e.g.,30s, 5m or 2.5m).Supported units: s and m.when specified in seconds(with \`s\` or as a raw number), the value must be an integer.`)}}function VI(n){try{return E.assertHilogLevel(n),n}catch{throw new ea("`level` must be one of: D, I, W, E, F.")}}function GI(n){try{return E.assertBundleNameStrict(n),n}catch(e){throw new ea(e.message)}}function qI(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.")}async function zI(n,e,t,r,i){return t.crash?await n.getCrashLog(e,t.bundleName):await n.getHilog(e,{level:t.level,bundleName:t.bundleName,keyword:t.keyword,isFollow:!!t.follow,tail:t.tail,fromSeconds:r,toSeconds:i})}function JI(n,e,t,r){let i=E.filterLogsByRelativeWindow(n,t,r);return e.tail?E.getLastLines(i,e.tail):i}var YI=new FI("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(bg(n))}).option("--device <device>","Target device (name or serial)").option("--crash","Only obtain crash logs").option("--level <level>","Log level filter: D, I, W, E, F",VI).option("--bundle-name <bundle-name>","Filter by application bundle name",GI).option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",WI).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>Sg(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>Sg(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await BI(HI(n),()=>KI(n))});async function KI(n){let e=$I({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};e.start();try{qI(n);let r=n.from,i=n.to,o=await C.new(),s=new mr(o),a=await s.selectDevice(n.device);if(!a)throw new S("No active devices found.","No active devices found.");p(cd(`deviceId: ${a}`)),p(cd(`type: ${n.crash?"Crash logs":"Common logs"}`)),p(cd("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await zI(s,a,n,r,i);t(),n.crash&&c&&(c=JI(c,n,r,i)),c&&console.log(c)}finally{t()}}var Eg=YI;import uo from"path";import er from"fs";import ud from"process";import xg from"os";import{Command as lA}from"commander";import{green as Ag,red as ld,cyan as dA,yellow as Dg}from"colorette";import ge from"fs-extra";import U from"path";import*as Cg from"os";import{fileURLToPath as XI}from"url";var Pg={17:{sdkVersion:"5.0.5(17)",modelVersion:"5.0.5"},18:{sdkVersion:"5.1.0(18)",modelVersion:"5.1.0"},19:{sdkVersion:"5.1.1(19)",modelVersion:"5.1.1"},20:{sdkVersion:"6.0.0(20)",modelVersion:"6.0.0"},21:{sdkVersion:"6.0.1(21)",modelVersion:"6.0.1"},22:{sdkVersion:"6.0.2(22)",modelVersion:"6.0.2"},23:{sdkVersion:"6.1.0(23)",modelVersion:"6.1.0"},24:{sdkVersion:"6.1.1(24)",modelVersion:"6.1.1"}},ZI=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function QI(){let n=import.meta.url,e=XI(n);if(e.includes("dist")){let o=U.dirname(e),s=U.dirname(o);return U.join(s,"templates","application")}let t=U.dirname(e),r=U.dirname(t),i=U.dirname(r);return U.join(i,"templates","application")}function kg(n,e){ge.mkdirSync(e,{recursive:!0});for(let t of ge.readdirSync(n,{withFileTypes:!0})){let r=U.join(n,t.name),i=U.join(e,t.name);if(t.isDirectory()){kg(r,i);continue}ge.existsSync(i)||(ge.mkdirSync(U.dirname(i),{recursive:!0}),ge.copyFileSync(r,i))}}function lo(n,e){let t=ge.readFileSync(n,"utf-8"),r=t;for(let[i,o]of e)r=r.replaceAll(i,o);r!==t&&ge.writeFileSync(n,r,"utf-8")}function eA(n){if(Pg[n])return Pg[n];if(n>=26){let e=`${n}.0.0`;return{sdkVersion:e,modelVersion:e}}}function tA(n,e){if(e===22)return;let t=eA(e);t&&(lo(U.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),lo(U.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),lo(U.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function rA(n){return ZI.filter(t=>!ge.existsSync(U.join(n,t))).length===0}function nA(){return Buffer.from([137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,1,0,0,0,1,8,2,0,0,0,144,119,83,222,0,0,0,12,73,68,65,84,8,215,99,248,255,255,255,0,5,254,2,254,0,0,0,0,73,69,78,68,174,66,96,130])}function iA(n){return Cg.platform()==="darwin"?U.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):U.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function oA(n,e){let t=iA(e);if(!ge.existsSync(t))return!1;let r=[["AppScope/resources/base/media/background.png","AppScope/resources/base/media/background.png"],["AppScope/resources/base/media/foreground.png","AppScope/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/background.png"],["entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/startIcon.png","entry/src/main/resources/base/media/startIcon.png"]];for(let[i,o]of r){let s=U.join(t,i),a=U.join(n,o);ge.existsSync(s)&&(ge.mkdirSync(U.dirname(a),{recursive:!0}),ge.copyFileSync(s,a))}return!0}function sA(n){let e=nA(),t=["AppScope/resources/base/media/background.png","AppScope/resources/base/media/foreground.png","entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/startIcon.png"];for(let r of t){let i=U.join(n,r);ge.mkdirSync(U.dirname(i),{recursive:!0}),ge.writeFileSync(i,e)}}function aA(n,e){e&&oA(n,e)||sA(n)}function cA(n){let e=[U.join(n,"gitignore.txt"),U.join(n,"entry","gitignore.txt")];for(let t of e)if(ge.existsSync(t)){let r=U.dirname(t);ge.renameSync(t,U.join(r,".gitignore"))}}function Ig(n,e,t,r,i){let o=QI();if(!ge.existsSync(o))throw new Error(`Template directory not found: ${o}`);ge.mkdirSync(n,{recursive:!0}),kg(o,n),cA(n),aA(n,i),lo(U.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),lo(U.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),tA(n,r);let s=rA(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function uA(n){if(n.length<1||n.length>200)throw new ye("errorCode",`App name length must be 1-200 characters. Current: ${n.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(n))throw new ye("errorCode","Application name must start with a letter (a-z, A-Z) and contain only letters, digits, and underscores")}function Lg(n){if(xg.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function Rg(n){if(n.length===0)throw new ye("errorCode","Project path cannot be empty.");if(n.length>120)throw new ye("errorCode",`Project path cannot exceed 120 characters (current: ${n.length}).`);let e=xg.platform();if(!(e==="win32"?/^[a-zA-Z0-9._\-:\\/]+$/:/^[a-zA-Z0-9._\-/]+$/).test(n)){let o=e==="win32"?"letters, digits, dots, underscores, hyphens, colons, slashes (/) or backslashes (\\)":"letters, digits, dots, underscores, hyphens or slashes (/)";throw new ye("errorCode",`Project path can only contain ${o}.`)}let r=Lg(n);if(/[\u4e00-\u9fff]/.test(r))throw new ye("errorCode","Project path cannot contain Chinese characters.");if(r.endsWith("."))throw new ye("errorCode","Project path cannot end with a dot (.)")}function pA(n){let e=n,t=uo.parse(n).root;for(;e!==t;){if(er.existsSync(e))return e;e=uo.dirname(e)}return er.existsSync(t)?t:null}function Tg(n){let e=pA(n);if(!e)throw new ye("errorCode",`No existing parent directory found for '${n}'. Cannot create project directory.`);try{er.accessSync(e,er.constants.W_OK)}catch{throw new ye("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}let t=uo.join(e,`.deveco_write_test_${Date.now()}`);try{er.writeFileSync(t,"test"),er.unlinkSync(t)}catch{throw new ye("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}}function mA(n){return`com.example.${n.toLowerCase()}`}function fA(n,e){if(e){let i=Lg(e),o=uo.resolve(i);if(er.existsSync(o)){if(er.readdirSync(o).length>0)throw new ye("errorCode",`Directory '${o}' is not empty. Cannot create project here.`)}else Tg(o);return o}let t=ud.cwd(),r=uo.join(t,n);if(er.existsSync(r))throw new ye("errorCode",`Directory '${r}' already exists. Cannot create project here.`);return Tg(r),r}function hA(n,e){let t=e?.getMaxApiLevel(),r=23;if(n.apiLevel){let i=Number(n.apiLevel);if(!Number.isInteger(i)||i<17)throw new ye("errorCode",`Invalid API version ${n.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(i>t)throw new ye("errorCode",`Invalid API version ${n.apiLevel}. Your SDK supports API version 17-${t}`)}else if(i>r)throw new ye("errorCode",`Invalid API version ${n.apiLevel}. Without DevEco Studio, supported range is API version 17-${r}`);return i}return t!==void 0?t:23}async function gA(){try{return await C.new()}catch(n){console.error(Dg(`DevEco Studio not found: ${n.message}`)),console.log(Dg("Use placeholder API level instead."));return}}var ye=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};async function dd(n,e,t,r){let i={event:b.CommandExecuted,args:["create"],apiLevel:r?.apiLevel??null},o={duration_ms:Date.now()-n,success:e,error_code:t};await k.track(i,o).catch(()=>{})}function yA(n){console.log(`
|
|
1306
|
-
`+Ag("Project created successfully.")),console.log(`Project root: ${n.projectRoot}`),console.log(`App name: ${n.appName}`),console.log(`Bundle name: ${n.bundleName}`),console.log(`API level: ${n.apiLevel}`),console.log(Ag("Template integrity check passed."))}var vA=new lA("create").description("Scaffold a new HarmonyOS application project").option("--project-path <path>","Project directory path (default: ./<app-name>)").option("--app-name <name>","Application name").option("--bundle-name <bundle>","Bundle name (auto-derived as com.example.<app-name> if omitted)").option("--api-level <level>","API level (auto-detected from SDK if omitted; minimum: 17)").action(async n=>{let e=Date.now();try{n.appName||(console.error(ld("Error: --app-name is required")),await dd(e,!1,"errorCode",n),ud.exit(1));let t=n.appName;uA(t);let r=n.bundleName||mA(t);E.assertBundleNameStrict(r),n.projectPath&&Rg(n.projectPath);let i=fA(t,n.projectPath);Rg(i),console.log(dA("Initializing project...")),console.log(`Project path: ${i}`),console.log(`App name: ${t}`),console.log(`Bundle name: ${r}`);let o=await gA(),s=hA(n,o);console.log(`API level: ${s}`);let a=o?.devecoStudioPath,c=Ig(i,t,r,s,a);yA(c),await dd(e,!0,null,n)}catch(t){let r=t,o=t instanceof ye?t.code:r.code??r.name??"UnknownError";console.error(ld(`
|
|
1307
|
-
Failed to create project.`)),console.error(ld(r.message)),await dd(e,!1,o,n),ud.exit(1)}}),Ng=vA;import{Command as kA}from"commander";import{red as IA,cyan as Ug}from"colorette";import wA from"fs";import ta from"path";import{cyan as SA}from"colorette";import*as ra from"smol-toml";var zn=wA.promises;async function bA(n){try{let e=await zn.readFile(n,"utf8");return e.trim()===""?{}:JSON.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read configuration file ${n}: ${e.message}`,{cause:e})}}async function EA(n){try{let e=await zn.readFile(n,"utf8");return e.trim()===""?{}:ra.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read TOML config file ${n}: ${e.message}`,{cause:e})}}async function PA(n,e){let t=ta.dirname(n);await zn.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await zn.writeFile(n,r,"utf8")}async function CA(n,e){let t=ta.dirname(n);await zn.mkdir(t,{recursive:!0});let r=ra.stringify(e);await zn.writeFile(n,r,"utf8")}function Mg(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function Og(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 _g(n,e){return n.format==="codex"?EA(e):bA(e)}async function Fg(n,e,t){return n.format==="codex"?CA(e,t):PA(e,t)}async function $g(n,e,t=!1){let r=lr[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(lr).join(", ")}`};if(!r.supportsGlobal)return{success:!1,error:`${r.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`};try{let i=await _g(r,r.globalConfigPath);if(Mg(i,r.mcpServersKey,Tt)&&!t)return console.log(`MCP server ${Tt} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let o=zo(r,void 0);return Og(i,r.mcpServersKey,Tt,o,t),await Fg(r,r.globalConfigPath,i),console.log(`MCP server ${Tt} configured in ${r.globalConfigPath}.`),{success:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"}}catch(i){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${i.message}`}}}async function pd(n,e,t=!1){let r=lr[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(lr).join(", ")}`};let i=ta.isAbsolute(r.projectConfigPath)?r.projectConfigPath:ta.join(e,r.projectConfigPath);try{let o=await _g(r,i);if(Mg(o,r.mcpServersKey,Tt)&&!t)return console.log(`MCP server ${Tt} already configured in ${i}.`),{success:!0,skipped:!0,configPath:i,agentName:n,installType:"project"};let s=zo(r,e);return Og(o,r.mcpServersKey,Tt,s,t),await Fg(r,i,o),console.log(`MCP server ${Tt} configured in ${i}.`),{success:!0,configPath:i,agentName:n,installType:"project"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${o.message}`}}}function jg(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(SA("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)}var md="deveco-cli";async function AA(n,e,t){if(n.customPath)return[await cg(md,e,n.customPath,t.force)];let r=[...n.projectAgents.map(({project:s,agent:a})=>()=>ag(md,e,s,a,t.force)),...n.agents.map(s=>()=>sg(md,e,s,t.force))],i=5,o=[];for(let s=0;s<r.length;s+=i){let a=r.slice(s,s+i);o.push(...await Promise.all(a.map(c=>c())))}return o}function DA(n){return[...new Set([...n.agents,...n.projectAgents.map(({agent:e})=>e)])]}async function Hg(n,e,t,r){await k.track(n,{duration_ms:Date.now()-e,success:t,error_code:r}).catch(()=>{})}async function RA(n,e,t,r,i){let o={event:b.SkillConfigOperation,subAction:"install",targetType:r?"path":i?"project":"global",agents:DA(n)},s=Date.now();try{let a=await AA(n,e,t),c=a.every(l=>l.success||l.skipped);return await Hg(o,s,c,c?null:"SKILL_INSTALL_FAILED"),a}catch(a){let c=a instanceof Error?a.code??a.name:"UnknownError";throw await Hg(o,s,!1,c),a}}async function TA(n,e,t){let r=[];for(let{project:i,agent:o}of n.projectAgents){let s=await pd(o,i,t);r.push(s)}for(let i of n.agents){let o=await pd(i,e,t);r.push(o)}return r}async function xA(n,e){let t=[];for(let r of n){if(!lr[r])continue;let o=await $g(r,process.cwd(),e);t.push(o)}return t}async function LA(n,e,t){let r=["qoder","dsh"];if(t.agent){let l=t.agent.split(",").map(d=>d.trim());for(let d of r)if(l.includes(d))throw new Error(`${d} does not support MCP configuration via DevEco CLI. Use --skill instead, or use other supported agents for MCP.`)}let i=t.force??!1,o=n.projectAgents.filter(l=>!r.includes(l.agent)),s=n.agents.filter(l=>!r.includes(l)),a={...n,projectAgents:o,agents:s},c=e?await TA(a,e,i):await xA(a.agents,i);c.length>0&&(console.log(Ug("MCP Configuration:")),jg(c))}async function NA(n,e,t){let r={event:b.Init,subAction:"install",targetType:e?"project":"global",agentName:t.agent},i=Date.now(),o=!0,s=null;try{await LA(n,e,t)}catch(a){throw o=!1,s=a instanceof Error?a.code??a.name:"UnknownError",a}finally{let a={duration_ms:Date.now()-i,success:o,error_code:s};await k.track(r,a)}}async function MA(n){if(n.skill&&n.mcp)throw new Error("Cannot use `--skill` and `--mcp` together. Use `--skill` for skill installation only, or `--mcp` for MCP configuration only.");let{resolvedPath:e,resolvedProject:t}=so(n.path,n.project,n.agent);t&&Cr(t,"Project directory",n.force),e&&Cr(e,"Directory",n.force);let r=await Ks(n,e,t);if(n.mcp){await NA(r,t,n);return}let i=ug(),o=await RA(r,i,n,e,t);console.log(),o.length>0&&(console.log(Ug("Skill Installation:")),oo(o))}var OA=new kA("init").description("Install the deveco-cli skill or configure the deveco-mcp server into AI agents").option("--agent <agents>","Target agents, comma-separated; installs to all available agents if omitted").option("--project <path>","Project root directory for skill or MCP configuration").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").option("--skill","Install the deveco-cli skill only (same as default behavior; explicit for symmetry with --mcp)").option("--mcp","Configure the deveco-mcp server (syntax checking for .ets and C/C++) only; no skill installation").option("-f, --force","Overwrite existing skill/MCP configuration").action(async n=>{try{await MA(n)}catch(e){console.error(IA(e instanceof Error?e.message:String(e))),process.exit(1)}}),Bg=OA;import{Command as qD}from"commander";import{McpServer as xD}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as LD}from"@modelcontextprotocol/sdk/server/stdio.js";import*as vo from"fs";import*as ci from"path";import{z as ve}from"zod";import na from"path";function Gg(n,e,t,r,i){if(e.isError)return{};let o=e.content?.[0]?.text??"";if(!o)return{};let s;switch(n){case"check":s=_A(o);break;case"hover":s={hit:Jn(o)!=null};break;case"definition":case"declaration":s=Wg(o,t,r,i,!0);break;case"references":s=$A(o);break;case"implementation":s=Wg(o,t,r,i,!1);break;case"documentSymbol":s=jA(o);break;case"callHierarchy":s=HA(o,t,r,i);break;case"workspaceSymbol":s=UA(o,t);break;default:s={}}return s}function qg(n){let e=Array.isArray(n.files)?n.files[0]:n.file;return typeof e!="string"||!e?void 0:na.extname(e).toLowerCase().replace(/^\./,"")||void 0}function Jn(n){let e=n.indexOf(": ");if(e<0)return;let t=n.slice(e+2).trim();if(!(!t||t==="no result"))try{return JSON.parse(t)}catch{return}}function _A(n){let e={total:0,error:0,warn:0,info:0},t=new Set,r=" => Diagnostic: ";for(let o of n.split(`
|
|
1308
|
-
`)
|
|
1309
|
-
|
|
1299
|
+
`,Zk="6.1.0";function Qk(n){let e=n.trim();if(!e)throw new Error("--target must not be empty.");return e}function eI(n){let e=n.trim();if(!Uh.includes(e))throw new Error(`Invalid fold state "${n}". Available values: ${Uh.join(", ")}`);return e}function Wh(n,e,t,r){let i=e.trim();if(!/^-?\d+$/.test(i))throw new Error(`${n} must be an integer in [${t}, ${r}].`);let o=Number(i);if(o<t||o>r)throw new Error(`${n} must be in [${t}, ${r}].`);return o}function Vh(n,e,t,r,i){let o=e.trim(),s=Number(o);if(!o||Number.isNaN(s))throw new Error(`${n} must be a number in [${t}, ${r}].`);if(i!==void 0&&!tI(o,i))throw new Error(`${n} supports at most ${i} decimal place(s).`);if(s<t||s>r)throw new Error(`${n} must be in [${t}, ${r}].`);return o}function tI(n,e){let t=n.split(".")[1];return t===void 0||t.length<=e}function an(n,e,t,r,i){return Number(Vh(n,e,t,r,i))}var rI=["Name","Status","Serial","Device Type","OS Version"];function nI(n){return{cells:[n.name,n.status,n.serial??"-",n.deviceType??"-",n.osVersion??"-"],highlight:n.status==="running"}}async function iI(n,e){let t=await Promise.all(e.map(async r=>{let i=await Tn(n,r,Kk);return[r,i]}));return new Map(t)}async function oI(n){let e=await Ql(n),t=await iI(n,e);return{serials:e,params:t}}function sI(n,e,t,r,i){if(e)for(let o of["const.product.name","const.product.model"]){let s=e.get(o);if(!s)continue;let a=t.indexOf(s);if(a===-1)continue;t.splice(a,1),i.set(s,n);let c=r.indexOf(n);c!==-1&&r.splice(c,1);return}}function aI(n,e,t){let r=new Map,i=new Map,o=[...n],s=[...t];for(let a of n){let c=e.get(a),l=c?.get("ohos.qemu.hvd.name");l&&i.set(l,a),t.length>0&&sI(a,c,s,o,r)}for(let a=0;a<s.length&&a<o.length;a++)r.set(s[a],o[a]);return{productSerialMap:r,hvdSerialMap:i}}function cI(n,e,t){let r=n.map(i=>({emu:i,serial:e.get(i.name)??t.get(i.name),effectiveRunning:i.isRunning===!0||t.has(i.name)}));return r.sort((i,o)=>i.effectiveRunning!==o.effectiveRunning?i.effectiveRunning?-1:1:i.emu.name.localeCompare(o.emu.name)),r.map(({emu:i,serial:o,effectiveRunning:s})=>({name:i.name,status:s?"running":"stopped",serial:o??null,deviceType:i.deviceType??null,osVersion:i.osVersion??null}))}async function lI(n,e,t,r){try{let[i,o]=await Promise.all([n.listEmulators(),oI(e)]);if(i.length===0){r?.stop(),console.log(t==="json"?"[]":Er(" No emulator instances found."));return}let s=i.filter(g=>g.isRunning).map(g=>g.name),{productSerialMap:a,hvdSerialMap:c}=aI(o.serials,o.params,s);r?.stop();let l=cI(i,a,c);if(t==="json"){console.log(JSON.stringify(l,null,2));return}let d=l.map(nI);console.log(Xt(rI,d))}catch(i){throw r?.stop(),new Error(`Failed to list emulators: ${i.message}`,{cause:i})}}function Gh(n,e,t){let r=!1;for(let i=0;i<n.length;i++){let o=n[i];if(o.status!=="rejected")continue;r=!0;let s=o.reason;console.error(md(`Failed to ${t} emulator "${e[i]}": ${s.message}`)),s.stdout&&console.error(dd(s.stdout)),s.stderr&&console.error(dd(s.stderr))}return r}var dI=2e3,uI=6e4;async function pI(n,e){let t=Ae(e);return(await ed(n)).some(i=>Ae(i)===t)}async function qh(n,e,t,r=uI,i=dI){let o=Date.now()+r;for(;Date.now()<o;){if(await pI(n,e)===t)return!0;await new Promise(a=>setTimeout(a,i))}return!1}function mI(n){if(!n)return null;let e=n.indexOf("-bootmode");return e>=0&&e+1<n.length&&n[e+1]==="snapshot"}async function fI(n,e,t,r){let i=await n.startEmulator(t,r);if(i.status==="already-running")return console.log(Er(`Emulator "${t}" is already running.`)),{started:!1,memoryBytes:0,hotBoot:null};console.log(Xn(`Starting emulator "${t}"...`));let o=i.tracker,s=0,a=mI(i.args);try{let c=await qh(e,t,!0);console.log(c?ao(`Emulator "${t}" started successfully.`):Er(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}finally{if(o)try{s=await o.stop()}catch{}}return{started:!0,memoryBytes:s,hotBoot:a}}async function hI(n,e,t,r){let i=await Promise.allSettled(t.map(a=>fI(n,e,a,r)));if(Gh(i,t,"start"))throw new S("One or more emulators failed to start.");let o=i.filter(a=>a.status==="fulfilled").map(a=>a.value).filter(a=>a.started);return{emulatorMemory:o.length===0||o.some(a=>a.memoryBytes===0)?"unknown":te(o.reduce((a,c)=>a+c.memoryBytes,0)),hotBoot:o.length===0?null:o.every(a=>a.hotBoot===!0)}}async function zh(n,e){let t=e.trim();if(!Ot(t))return t;let r=await ne.withHdcPath(n).getDeviceName(t);if(r===t)throw new Error(`Cannot resolve a running emulator with serial "${t}". Use \`devecocli emulator list\` or pass the emulator name instead.`);return r}async function gI(n,e,t){let r=await zh(e,t);if(console.log(Xn(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(Er(`Emulator "${r}" is already stopped.`));return}let o=await qh(e,r,!1);console.log(o?ao(`Emulator "${r}" stopped successfully.`):Er(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function yI(n,e,t){let r=await Promise.allSettled(t.map(i=>gI(n,e,i)));Gh(r,t,"stop")}async function ht(){let n=await C.new();return{manager:Yn.from(n),toolProvider:n}}async function Qt(n,e,t){let r={event:b.CommandExecuted,args:["emulator",t,"--target"]};await ft(r,async()=>{let i=Qk(n.target),o=e(),s=Array.isArray(o)?o:[o],{manager:a,toolProvider:c}=await ht(),l=await zh(c.hdcPath,i);for(let d of s)await a.controlEmulator(l,d);console.log(ao(`Emulator "${i}" operation completed.`))})}function vI(n){let e=[];if(Zs(e,"longitude",n.longitude,-180,180,8),Zs(e,"latitude",n.latitude,-90,90,8),Zs(e,"altitude",n.altitude,-1e4,1e4,2),Zs(e,"bearing",n.direction,0,359.99,2,"--direction"),e.length===0)throw new Error("Specify at least one geolocation option.");return(n.longitude===void 0||n.latitude===void 0)&&console.warn(Er("Warning: --longitude and --latitude should be specified together to form a valid location.")),e}function wI(n){let e=[];if(oo(e,"light",n.lightIntensity,0,1e5,!1,"--light-intensity"),oo(e,"humidity",n.humidity,0,100,!1),oo(e,"temperature",n.temperature,-273.1,100,!1),oo(e,"steps",n.steps,0,1e4,!0),oo(e,"heartrate",n.heartrate,0,255,!0),e.length===0)throw new Error("Specify at least one sensor option.");return e}function Zs(n,e,t,r,i,o,s=`--${e}`){t!==void 0&&n.push({type:"gps",key:e,value:Vh(s,t,r,i,o)})}function oo(n,e,t,r,i,o,s=`--${e}`){if(t===void 0)return;let a=o?Wh(s,t,r,i):an(s,t,r,i,1);n.push({type:"sensor",key:e,value:a})}function SI(n){let e=[];if(n.status!==void 0){let i=n.status==="charging"?1:0;e.push({type:"battery-status",status:i})}if(n.level!==void 0&&e.push({type:"battery",level:Wh("--level",n.level,0,100),assumedCharging:n.status==="charging"}),e.length===0)throw new Error("Specify --level or --status.");let t=e.some(i=>i.type==="battery"&&i.level===0),r=e.some(i=>i.type==="battery-status"&&i.status===0);if(t&&r)throw new Error("Battery level 0 is only allowed while charging; --level 0 cannot be combined with --status discharging.");return e}var ge=new pd("emulator").description("Manage emulator instances");ge.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
|
|
1300
|
+
${Er("Tip: ")}${dd("An option value containing spaces/parentheses must be quoted. Use:")}
|
|
1301
|
+
${Xn('devecocli emulator <subcommand> --<option> "value with spaces"')}
|
|
1302
|
+
${Xn('devecocli emulator <subcommand> --<option>="value with spaces"')}
|
|
1303
|
+
`)}});ge.hook("preAction",async()=>{(await C.new()).require({studio:Zk})});var bI=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function fd(n){let e=new Me("--device-type <type>","Emulator device type").choices([...bI]);return n?e.makeOptionMandatory():e}function EI(){return new Me("--device-type <type>","Emulator device type (case-insensitive)").argParser(n=>{if(!n.trim())throw new ld("--device-type must not be empty.");return n}).makeOptionMandatory()}function PI(n){if(n!==void 0){if(n.length>=4&&n.length%4===0&&n.every(e=>/^\d+(?:\.\d+)?$/.test(e)))throw new Error('--screen value must be quoted: --screen "1316 2832 560 6.9".');if(n.length>2)throw new Error("--screen accepts one or two configurations.");for(let[e,t]of n.entries()){let r=t.trim().split(/\s+/),i=n.length===1?"--screen":`--screen configuration ${e+1}`;if(r.length!==4||r.some(o=>o.length===0))throw new Error(`${i} must contain four values: width(px), height(px), DPI, and screen diagonal length(inch).`);an(`${i} width`,r[0],720,3500),an(`${i} height`,r[1],720,3500),an(`${i} DPI`,r[2],240,640),an(`${i} screen diagonal length`,r[3],3.5,9)}return n}}function CI(n){return["--device-type","--os-version",...n.instancePath!==void 0?["--instance-path"]:[],...n.imageRoot!==void 0?["--image-root"]:[],...n.screenProfile!==void 0?["--screen-profile"]:[],...n.screen!==void 0?["--screen"]:[],...n.storage!==void 0?["--storage"]:[],...n.memory!==void 0?["--memory"]:[],...n.hotBoot!==void 0?["--hot-boot"]:[],...n.force?["--force"]:[]]}function Kn(n,e){for(let t of e)if(t in n)return n[t]}function so(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function Bh(n){let e=so(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var kI=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],II="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";async function DI(n,e,t){if(!await n.hasAvailableEmulatorImage({deviceType:e,osVersion:t}))throw new Error(`Invalid --os-version value "${t}".
|
|
1304
|
+
Run \`devecocli emulator image list --all\` and use an exact OS Version value.`)}function Jh(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function Yh(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let i=r,o=so(Kn(i,["osVersion","OsVersion","OSVersion","os_version"])),s=so(Kn(i,["deviceType","DeviceType","device_type"])),a=Bh(Kn(i,["downloaded","Downloaded","isDownloaded"])),c=so(Kn(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=so(Kn(i,["releaseType","ReleaseType","release_type"])),d=Bh(Kn(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,l,d,a],highlight:e&&a==="true"})}return t}function AI(n){let e=n.trim();if(!e)return!0;let t=Jh(e);return t===null?!1:t.length===0?!0:Yh(t,!0).length===0}function RI(n,e){let t=n.trim();if(!t)return"";let r=Jh(t);if(!r)return n.trimEnd();let i=Yh(r,e);return Xt(kI,i)}var Qs=new pd("image").description("HarmonyOS emulator system images (download, list, remove)");Qs.command("download").description("Download system image").addOption(fd(!1)).option("--os-version <version>","Example: HarmonyOS 5.1.1(19) or HarmonyOS 6.0.1(21) (required)").option("--force","Overwrite an existing image").action(async n=>{let e={event:b.CommandExecuted,args:["emulator","image","download",...n.deviceType?["--device-type"]:[],...n.osVersion?["--os-version"]:[],...n.force?["--force"]:[]]};await ft(e,async()=>{let{manager:t,toolProvider:r}=await ht();await cd(r.emulatorPath,r.sdkPath);let i=n.deviceType?.trim(),o=n.osVersion?.trim();if(!i)throw new S("Error: missing required option '--device-type <type>'","Missing required device type.");if(!o)throw new S("Error: misssing required option '--os-version <version>'","Missing required OS version.");await DI(t,i,o),await t.installEmulatorImage({deviceType:i,osVersion:o,force:n.force===!0})})});Qs.command("remove").description("Remove a downloaded system image").addOption(fd(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let e={event:b.CommandExecuted,args:["emulator","image","remove","--device-type","--os-version"]};await ft(e,async()=>{let{manager:t}=await ht();await t.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})})});Qs.command("list").description("List system images").addOption(fd(!1)).option("--all","List all images (local and remote)").addOption(new Me("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let e={event:b.CommandExecuted,args:["emulator","image","list",...n.deviceType?["--device-type"]:[],...n.all?["--all"]:[],...n.format!=="table"?["--format"]:[]]};await ft(e,async()=>{let{manager:t}=await ht(),r;n.all?r=void 0:r=!0;let i=await t.listEmulatorImages({deviceType:n.deviceType,downloaded:r});if(AI(i)){console.log(Er(II));return}if(n.format==="json"){console.log(i.trimEnd());return}let o=RI(i,n.all===!0);console.log(o)})});ge.addCommand(Qs);var ea=new pd("license").description("Review and accept emulator license agreements interactively (prints full text + y/N prompt)");ea.command("view").description("Review agreement text (read-only, no changes)").action(async()=>{let n={event:b.CommandExecuted,args:["emulator","license","view"]};await ft(n,async()=>{let{toolProvider:e}=await ht(),t=await Fh(e.emulatorPath,e.sdkPath);process.exitCode=t})});ea.command("accept").description("Accept all emulator license agreements non-interactively (skips review and prompt)").action(async()=>{let n={event:b.CommandExecuted,args:["emulator","license","accept"]};await ft(n,async()=>{let{toolProvider:e}=await ht(),t=await Hh(e.emulatorPath,e.sdkPath);process.exitCode=t})});ea.action(async()=>{let n={event:b.CommandExecuted,args:["emulator","license"]};await ft(n,async()=>{let{toolProvider:e}=await ht(),t=await jh(e.emulatorPath,e.sdkPath);process.exitCode=t})});ge.addCommand(ea);ge.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Qt(n,()=>({type:"shake"}),"shake"));ge.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Qt(n,()=>({type:"power"}),"power"));ge.command("rotate").description("Rotate emulator").addOption(new Me("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new ud("<direction>").choices(["left","right"])).action((n,e)=>Qt(e,()=>({type:"rotation",direction:n}),"rotate"));ge.command("volume").description("Change volume").addOption(new Me("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new ud("<direction>").choices(["up","down"])).action((n,e)=>Qt(e,()=>({type:"volume",direction:n}),"volume"));ge.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",Xk).action((n,e)=>Qt(e,()=>({type:"folded-state",state:eI(n)}),"fold"));ge.command("battery").description("Set battery level and/or charging status").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--level <0-100>","Battery level, SOC (charging: 0-100; not charging: 1-100)").addOption(new Me("--status <status>","Charging status").choices(["charging","discharging"])).action(n=>Qt(n,()=>SI(n),"battery"));ge.command("geolocation").description("Inject geographic coordinates and direction").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--longitude <value>","Longitude (-180.0 to 180.0)").option("--latitude <value>","Latitude (-90.0 to 90.0)").option("--altitude <value>","Altitude (-10000.0 to 10000.0)").option("--direction <value>","Heading direction in degrees (0.00 to 359.99)").action(n=>Qt(n,()=>vI(n),"geolocation"));ge.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new ud("<type>","Motion simulation scene").choices(["outdoorRunning","outdoorCycling","drivingNavigation"])).action((n,e)=>{let t={outdoorRunning:{type:"outdoor-running"},outdoorCycling:{type:"outdoor-cycling"},drivingNavigation:{type:"driving-navigation"}};return Qt(e,()=>t[n],"scene")});ge.command("sensor").description("Inject sensor data").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--light-intensity <value>","Light sensor (0 to 100000)").option("--humidity <value>","Humidity sensor (0 to 100)").option("--temperature <value>","Temperature sensor (-273.1 to 100)").option("--steps <value>","Steps sensor (integer 0 to 10000)").option("--heartrate <value>","Heart rate sensor (integer 0 to 255)").action(n=>Qt(n,()=>wI(n),"sensor"));ge.command("list").description("List all emulator instances").addOption(new Me("--details","Output the raw JSON of `Emulator -list -details` without transformation").conflicts("format")).addOption(new Me("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let e={event:b.CommandExecuted,args:["emulator","list",...n.details?["--details"]:[],...n.format!=="table"?["--format"]:[]]};await ft(e,async()=>{let{manager:t,toolProvider:r}=await ht();if(n.details){let o=await t.listEmulatorDetails();console.log(o.trimEnd());return}let i=n.format==="table"?Yk({text:"Listing emulators\u2026",color:"cyan"}).start():void 0;await lI(t,r.hdcPath,n.format,i)})});function TI(n){let e=n.trim();if(!/^\d+$/.test(e))throw new ld("--hdcport must be an integer in [10000, 16555].");let t=Number(e);if(t<1e4||t>16555)throw new ld("--hdcport must be in [10000, 16555].");return t}function xI(n){return{hdcPort:n.hdcport,bootMode:n.bootMode,noWindow:n.window===!1}}function LI(n){return[...n.hdcport!==void 0?["--hdcport"]:[],...n.bootMode!==void 0?["--boot-mode"]:[],...n.window===!1?["--no-window"]:[]]}ge.command("start [names...]").description("Start one or more emulator instances").addOption(new Me("--hdcport <port>","hdc port of the emulator, 10000-16555 (Emulator -hdcport)").argParser(TI)).addOption(new Me("--boot-mode <mode>","Boot mode (Emulator -bootMode): coldboot = cold start keeping user data, snapshot = hot start restoring the last snapshot (needs Quick Boot), reset = wipe data then cold start; overrides the mode chosen when the instance was created").choices(["coldboot","snapshot","reset"])).addOption(new Me("--no-window","Start the emulator without a window (Emulator -noWindow); required on Linux hosts without a GUI")).action(async(n,e)=>{let t={event:b.CommandExecuted,args:["emulator","start",...LI(e)],emulatorMemory:"unknown",hotBoot:null};await ft(t,async()=>{let{manager:r,toolProvider:i}=await ht();if(await ad(i.emulatorPath,i.sdkPath),!n?.length)throw new S("Error: missing required argument 'names'","Missing required emulator name.");if(n.length>1&&e.hdcport!==void 0)throw new S(`Error: --hdcport cannot target ${n.length} emulators.`,"--hdcport sets the hdc port of a single emulator; pass one name, or omit --hdcport.");let o=await hI(r,i.hdcPath,n,xI(e));t.emulatorMemory=o.emulatorMemory,t.hotBoot=o.hotBoot})});ge.command("stop <names...>").description("Stop one or more emulator instances (by name or serial,e.g.,127.0.0.1:<port>)").action(async n=>{let e={event:b.CommandExecuted,args:["emulator","stop"]};await ft(e,async()=>{let{manager:t,toolProvider:r}=await ht();if(!n?.length){console.error(md("Error: missing required argument 'names'")),process.exitCode=1;return}await yI(t,r.hdcPath,n)})});var NI=ge.command("create <name>").description("Create a local emulator instance.").addOption(EI()).requiredOption("--os-version <version>",'Downloaded image label. which will be quoted in PowerShell (e.g. "HarmonyOS 6.0.1(21)") or be used in the format --os-version="\u2026";For details, run`devecocli emulator image list`').addOption(new Me("--path, --instance-path <path>","Emulator instance path")).option("--image-root <path>","Emulator image path").option("--screen-profile <model>","Emulator screen profile").addOption(new Me("--screen <config...>",'Screen: "width(px) height(px) DPI screen-diagonal-length(inch)" (720-3500, 720-3500, 240-640, 3.5-9); pass two values for a foldable device')).option("--storage <size>","Storage size in GB (2-1023)").option("--memory <size>","Memory size in GB (2-32)").addOption(new Me("--hot-boot <boolean>","Enable or disable hot boot").choices(["true","false"])).option("--force","Overwrite an existing emulator instance");NI.action(async(n,e)=>{let t={event:b.CommandExecuted,args:["emulator","create",...CI(e)]};await ft(t,async()=>{if(!e.osVersion.trim())throw new Error("--os-version must not be empty.");let r={name:n,deviceType:e.deviceType,osVersion:e.osVersion,instancePath:e.instancePath,imageRoot:e.imageRoot,screenProfile:e.screenProfile,screen:PI(e.screen),storage:e.storage===void 0?void 0:an("--storage",e.storage,2,1023),memory:e.memory===void 0?void 0:an("--memory",e.memory,2,32),hotBoot:e.hotBoot===void 0?void 0:e.hotBoot==="true",force:e.force===!0},{manager:i}=await ht();console.log(Xn(`Creating emulator "${n}"...`)),await i.createVirtualDevice(r),console.log(ao(`Emulator "${n}" created successfully.`))})});ge.command("delete <name>").description("Delete a local emulator instance").addOption(new Me("--path, --instance-path <path>","Emulator instance path")).action(async(n,e)=>{let t={event:b.CommandExecuted,args:["emulator","delete",...e.instancePath!==void 0?["--instance-path"]:[]]};await ft(t,async()=>{let{manager:r}=await ht();console.log(Xn(`Deleting emulator "${n}"...`));let i=await r.deleteVirtualDevice(n,e.instancePath);console.log(ao(`Emulator "${i}" deleted successfully.`))})});var Kh=ge;import{Command as pD}from"commander";import{red as bd,cyan as kt}from"colorette";import*as kg from"readline";import*as Pg from"crypto";import*as Xh from"http";import*as Zh from"crypto";import{URL as MI}from"url";var ta=class{server=null;port=0;clientSecret;callbackPath="/callback";resolveCallback=null;rejectCallback=null;timeoutId=null;baseUrl;successRedirectUrl;failedRedirectUrl;constructor(e,t,r,i){this.clientSecret=e,this.baseUrl=t,this.successRedirectUrl=r,this.failedRedirectUrl=i}async start(){return new Promise((e,t)=>{let r=Xh.createServer((i,o)=>{this.handleRequest(i,o)});r.keepAliveTimeout=1,r.on("error",i=>{t(new Error("Failed to start local auth server",{cause:i}))}),r.listen(0,"127.0.0.1",()=>{this.server=r;let i=r.address();this.port=i.port,e()})})}async waitForCallback(e=3e4){return new Promise((t,r)=>{this.resolveCallback=i=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),t(i)},this.rejectCallback=i=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),r(i)},this.timeoutId=setTimeout(()=>{this.timeoutId=null,this.rejectCallback?.(new Error("Callback timeout"))},e)})}async stop(){return this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.server?new Promise(e=>{let t=this.server;this.server=null,typeof t.closeAllConnections=="function"&&t.closeAllConnections();let r=setTimeout(()=>{e()},100);t.close(()=>{clearTimeout(r),e()})}):Promise.resolve()}handleRequest(e,t){let r=e.headers.host||"";if(![`127.0.0.1:${this.port}`,`localhost:${this.port}`].includes(r.toLowerCase())){t.writeHead(400),t.end("Bad Host");return}let o=new MI(e.url??"",`http://${r}`);if(o.pathname!==this.callbackPath){t.writeHead(404),t.end("Not Found");return}try{let s=o.searchParams;e.method==="POST"?this.readBody(e,t,s):this.handleCallbackRequest(e,t,s,"")}catch(s){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(s)}}readBody(e,t,r){let i="",o=0,s=65536;e.on("data",a=>{if(o+=a.length,o>s){e.destroy(new Error("Request body too large"));return}i+=a.toString()}),e.on("end",()=>{this.handleCallbackRequest(e,t,r,i)})}handleCallbackRequest(e,t,r,i){try{let o=this.parseParams(r,i),s=o.get("code"),a=o.get("tempToken"),c=o.get("siteId"),l=o.get("quit");if(!this.validateCode(s)){t.writeHead(400),t.end("Bad Request");return}if(this.isQuitRequest(l)){this.handleQuitRequest(t);return}if(!a||!c){t.writeHead(400),t.end("Bad Request");return}let d={tempToken:a,siteId:c,quit:l??void 0};this.resolveCallback?.(d),this.sendSuccessResponse(t)}catch(o){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(o)}}parseParams(e,t){return t&&t.trim()?new URLSearchParams(t):e}validateCode(e){let t=Buffer.from(e||"","utf8"),r=Buffer.from(this.clientSecret,"utf8");return t.length===r.length&&Zh.timingSafeEqual(t,r)}isQuitRequest(e){return e==="true"||e==="access_denied"||e==="quit"}handleQuitRequest(e){this.rejectCallback?.(new Error("User quit the login process")),e.writeHead(302,{Location:`${this.baseUrl}/${this.failedRedirectUrl}`}),e.end()}sendSuccessResponse(e){e.writeHead(302,{Location:`${this.baseUrl}/${this.successRedirectUrl}`}),e.end()}getPort(){return this.port}};import*as qe from"fs";import*as Pr from"path";import{homedir as UI}from"os";var er={};zw(er,{LocalCrypto:()=>er,decryptForLocalStorage:()=>$I,decryptForLocalStorageFromDirectory:()=>jI,encryptForLocalStorage:()=>FI,isEncryptedBlob:()=>HI});import*as oe from"fs";import*as _e from"path";import*as Ge from"crypto";import*as eg from"os";import{homedir as tg}from"os";var Oe=class extends Error{constructor(e){super(e),this.name="DefinedError"}};var co=Wr.ALGORITHM,rg=Wr.IV_LENGTH,lo=Wr.KEY_LENGTH,uo=Wr.KEY_LENGTH,cn=Wr.KEK_VERSIONS,ra=process.env.DEVECO_CLI_DATA_DIR||_e.join(tg(),Ce.CONFIG_DIR_NAME,Ce.APP_NAME),na=_e.join(tg(),".local","share",Ce.APP_NAME,"keys"),Zn=_e.join(ra,Ce.KEY_FILE_NAME);function Qh(n){return eg.platform()==="win32"?`Permission denied. Please run as administrator or grant write permission to ${n}.`:`Permission denied. You can try: sudo chown -R $(whoami) ${n}`}function hd(n){return _e.join(na,`${n}.bin`)}function ng(){if(!oe.existsSync(ra))try{oe.mkdirSync(ra,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new Oe(Qh(ra)):n}if(!oe.existsSync(na))try{oe.mkdirSync(na,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new Oe(Qh(_e.dirname(na))):n}}function ig(){ng();for(let n of cn){let e=hd(n);oe.existsSync(e)||oe.writeFileSync(e,Ge.randomBytes(lo),{mode:384})}}function og(n){if(!cn.includes(n))throw new Error(`Invalid kekId: ${n}`);ig();let e=hd(n),t=oe.readFileSync(e);if(t.length===lo)return t;let r=Ge.randomBytes(lo);return oe.writeFileSync(e,r,{mode:384}),r}function gd(n,e){let t=Ge.randomBytes(rg),r=og(e),i=Ge.createCipheriv(co,r,t),o=Buffer.concat([i.update(n),i.final()]),s=i.getAuthTag();return{version:1,algorithm:co,kekId:e,encryptedDek:o.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function sg(n,e){return ag(Buffer.from(n.encryptedDek,"base64"),e,n.iv,n.authTag)}function ag(n,e,t,r){let i=Ge.createDecipheriv(co,e,Buffer.from(t,"base64"));return i.setAuthTag(Buffer.from(r,"base64")),Buffer.concat([i.update(n),i.final()])}function cg(n,e){return ag(Buffer.from(n.ciphertext,"base64"),e,n.iv,n.authTag).toString("utf8")}function OI(){if(ig(),oe.existsSync(Zn))return;let n=Ge.randomBytes(uo),e=gd(n,cn[0]);oe.writeFileSync(Zn,JSON.stringify(e,null,2),{mode:384})}function lg(){OI();let n=JSON.parse(oe.readFileSync(Zn,"utf8")),e=sg(n,og(n.kekId));if(e.length===uo)return e;let t=Ge.randomBytes(uo),r=gd(t,cn[0]);return oe.writeFileSync(Zn,JSON.stringify(r,null,2),{mode:384}),t}function _I(){ng();for(let t of cn){let r=hd(t);oe.existsSync(r)||oe.writeFileSync(r,Ge.randomBytes(lo),{mode:384})}if(oe.existsSync(Zn))return;let n=Ge.randomBytes(uo),e=gd(n,cn[0]);oe.writeFileSync(Zn,JSON.stringify(e,null,2),{mode:384})}function FI(n){let e=lg(),t=Ge.randomBytes(rg),r=Ge.createCipheriv(co,e,t),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o=r.getAuthTag();return{version:1,algorithm:co,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:o.toString("base64"),timeStamp:Date.now()}}function $I(n){try{return cg(n,lg())}catch{throw _I(),new Error("Failed to decrypt local ciphertext")}}function jI(n,e){let t=_e.join(e,Ce.KEY_FILE_NAME),r=JSON.parse(oe.readFileSync(t,"utf8"));if(!cn.includes(r.kekId))throw new Error(`Invalid kekId: ${r.kekId}`);let i=_e.join(e,"keys",`${r.kekId}.bin`),o=_e.resolve(i),s=_e.resolve(_e.join(e,"keys"));if(!o.startsWith(s+_e.sep)&&o!==s)throw new Error("kekId resolves outside the keys directory");let a=oe.readFileSync(o);if(a.length!==lo)throw new Error("Invalid external root key");let c=sg(r,a);if(c.length!==uo)throw new Error("Invalid external data encryption key");return cg(n,c)}function HI(n){if(!n||typeof n!="object")return!1;let e=n;return e.algorithm==="aes-256-gcm"&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}function ze(){return process.env.DEVECO_CLI_AUTH_SOURCE===Ce.AUTH_SOURCE_DEVECO_CODE}var ia=class{getLocalTokenFilePath(){let e=process.env.DEVECO_CLI_DATA_DIR||Pr.join(UI(),Ce.CONFIG_DIR_NAME,Ce.APP_NAME);return Pr.join(e,Ce.TOKEN_FILE_NAME)}ensureConfigDir(){let e=Pr.dirname(this.getLocalTokenFilePath());qe.existsSync(e)||qe.mkdirSync(e,{recursive:!0,mode:448})}async saveJwtToken(e){if(!e)throw new Error("Token is empty");let t=er.encryptForLocalStorage(e);this.ensureConfigDir();let r=this.getLocalTokenFilePath();qe.writeFileSync(r,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){return ze()?this.loadDevecoCodeToken():this.loadLocalJwtToken()}loadDevecoCodeToken(){if(!ze())return null;let e=process.env.DEVECO_CODE_AUTH_DIR?.trim();if(!e)return null;let t=Pr.resolve(e);try{let r=Pr.join(t,Ce.TOKEN_FILE_NAME);if(!qe.existsSync(r))return null;let i=JSON.parse(qe.readFileSync(r,"utf8"));return er.isEncryptedBlob(i)?er.decryptForLocalStorageFromDirectory(i,e):null}catch{return null}}async loadLocalJwtToken(){let e=this.getLocalTokenFilePath();try{if(!qe.existsSync(e))return null;let t=JSON.parse(qe.readFileSync(e,"utf8"));return er.isEncryptedBlob(t)?er.decryptForLocalStorage(t):null}catch(t){let r=t.code;return r==="EACCES"||r==="EPERM"||r==="ENOENT"||await this.clearToken(),null}}async clearToken(){if(ze()){p("clearToken: skipped, session managed by DevEco Code");return}let e=this.getLocalTokenFilePath();try{qe.existsSync(e)&&qe.unlinkSync(e)}catch(t){throw new Error("Failed to clear token",{cause:t})}}},tr=new ia;import{spawn as BI}from"child_process";function WI(n){try{let e=new URL(n);return!(!["http:","https:"].includes(e.protocol)||e.hostname===""||n.includes('"'))}catch{return!1}}function VI(n){return n.replace(/[&|<>()^%!]/g,e=>`^${e}`)}async function dg(n){if(!WI(n))throw new Error(`Invalid URL: ${JSON.stringify(n)}`);let e,t;switch(process.platform){case"win32":e="cmd",t=["/c","start",'""',VI(n)];break;case"darwin":e="open",t=[n];break;default:e="xdg-open",t=[n];break}let r=BI(e,t,{stdio:"ignore",shell:!1,windowsHide:!0});return new Promise((i,o)=>{r.on("error",s=>{o(new Error("Failed to open browser",{cause:s}))}),r.on("close",s=>{s===0?i():o(new Error(`Browser process exited with code ${s}`))})})}import tD from"axios";var GI={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function qI(n){try{return new URL(n)}catch{return null}}function ug(n){var e=(typeof n=="string"?qI(n):n)||{},t=e.protocol,r=e.host,i=e.port;if(typeof r!="string"||!r||typeof t!="string"||(t=t.split(":",1)[0],r=r.replace(/:\d*$/,""),i=parseInt(i)||GI[t]||0,!zI(r,i)))return"";var o=yd(t+"_proxy")||yd("all_proxy");return o&&o.indexOf("://")===-1&&(o=t+"://"+o),o}function zI(n,e){var t=yd("no_proxy").toLowerCase();return t?t==="*"?!1:t.split(/[,\s]/).every(function(r){if(!r)return!0;var i=r.match(/^(.+):(\d+)$/),o=i?i[1]:r,s=i?parseInt(i[2]):0;return s&&s!==e?!0:/^[.*]/.test(o)?(o.charAt(0)==="*"&&(o=o.slice(1)),!n.endsWith(o)):n!==o}):!0}function yd(n){return process.env[n.toLowerCase()]||process.env[n.toUpperCase()]||""}import{spawn as fg}from"child_process";import*as ln from"fs";import*as hg from"os";import*as oa from"path";var gg=6e4;async function JI(){if(process.platform!=="win32")return null;let n="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",e=await pg(n,"ProxyServer");if(!e)return null;let t=await pg(n,"ProxyEnable");return t!=="1"&&t!=="0x1"?null:e.trim()}function pg(n,e){return new Promise(t=>{let r=fg("reg.exe",["query",n,"/v",e],{windowsHide:!0,stdio:["ignore","pipe","pipe"]}),i="";r.stdout.on("data",o=>{i+=o.toString()}),r.on("error",()=>t(null)),r.on("close",o=>{if(o!==0){t(null);return}let s=/REG_\w+\s+(\S+)/.exec(i);t(s?s[1]:null)})})}function YI(){let n=process.env.HTTPS_PROXY??process.env.HTTP_PROXY??"";if(!n)return null;try{return new URL(n).host}catch{return n}}function KI(){return`${process.env.SystemRoot??"C:\\Windows"}\\System32\\curl.exe`}function mg(n){let e={},t=0,r="";for(let i of n.split(/\r?\n/)){let o=i.trim();if(!o)continue;let s=/^HTTP\/\d(?:\.\d)?\s+(\d{3})\s*(.*)$/.exec(o);if(s){t=parseInt(s[1],10),r=s[2]??"";continue}let a=/^([^:]+):\s*(.*)$/.exec(o);a&&(e[a[1].toLowerCase()]=a[2])}return{statusCode:t,statusText:r,headers:e}}function XI(n,e,t,r){let i=["--silent","--show-error","--location","--ssl-no-revoke","--insecure","-x",`http://${e}`,"--proxy-ntlm","--proxy-user",":","--max-time",String(Math.max(1,Math.floor((n.timeoutMs??gg)/1e3)))];return n.method&&n.method!=="GET"&&i.push("-X",n.method),n.data!==void 0&&i.push("--data-binary",n.data),i.push(...ZI(n.headers,n.data!==void 0)),r?(i.push("--dump-header",t),i.push("--output",r)):i.push("--include"),i.push(n.url),i}function ZI(n,e){let t=new Set(["content-length","host","connection","proxy-authorization","proxy-connection","accept-encoding"]),r=[],i=!1;for(let[o,s]of Object.entries(n??{})){let a=o.toLowerCase();a==="content-type"&&(i=!0),t.has(a)||r.push("-H",`${o}: ${s}`)}return e&&!i&&r.push("-H","Content-Type: application/json"),r}function QI(n,e,t){if(t){let l=ln.readFileSync(e,"utf8"),d=ln.readFileSync(t),g=mg(l);return{statusCode:g.statusCode,statusText:g.statusText,body:d.toString("base64"),headers:g.headers,bodyBuffer:d}}let r=n.lastIndexOf("HTTP/");if(r===-1)return null;let i=n.slice(r),o=i.indexOf(`\r
|
|
1305
|
+
\r
|
|
1306
|
+
`);if(o===-1)return null;let s=i.slice(0,o),a=i.slice(o+4),c=mg(s);return{statusCode:c.statusCode,statusText:c.statusText,body:a,headers:c.headers}}async function yg(n){if(process.platform!=="win32")return null;let e=YI()??await JI();if(!e)return null;let t;n.binary&&(t=ln.mkdtempSync(oa.join(hg.tmpdir(),"curl-")));let r=t?oa.join(t,"header.tmp"):void 0,i=t?oa.join(t,"body.tmp"):void 0;try{let o=XI(n,e,r,i),s=await eD(o,n.timeoutMs);return!s||s.code!==0?null:QI(s.stdout,r,i)}catch{return null}finally{t&&ln.rmSync(t,{recursive:!0,force:!0})}}function eD(n,e){let t=KI();return new Promise(r=>{let i=fg(t,n,{windowsHide:!0,stdio:["ignore","pipe","pipe"]}),o="",s=!1,a=setTimeout(()=>{s||(s=!0,i.kill())},e??gg);i.stdout.on("data",c=>{o+=c.toString()}),i.on("error",()=>{s||(s=!0,clearTimeout(a),r(null))}),i.on("close",c=>{if(clearTimeout(a),s){r(null);return}s=!0,r({code:c??-1,stdout:o})})})}function rD(n){let e=new URL(n);return{protocol:e.protocol,host:e.hostname,port:e.port?Number.parseInt(e.port,10):e.protocol==="https:"?443:80,auth:{username:decodeURIComponent(e.username),password:decodeURIComponent(e.password)}}}var vd=class{client;constructor(){let e={timeout:Ci.HTTP_TIMEOUT_MS,headers:{"User-Agent":Uo.USER_AGENT,"accept-language":Uo.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=tD.create(e),this.client.interceptors.request.use(t=>{let r=ug(t.url??"");return t.proxy=r?rD(r):!1,t}),this.client.interceptors.response.use(t=>t,t=>{let r=`Network connection failed (${t.code}). Please check your proxy configuration or network settings`,i=new Error(`${t.message}
|
|
1307
|
+
${r}`);throw i.code=t.code,i.response=t.response,i})}async get(e,t){try{let r=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}catch(r){return this.withCurlFallback(r,e,"GET",t)}}async post(e,t){try{let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}catch(r){return this.withCurlFallback(r,e,"POST",t)}}convertResponse(e){return{data:typeof e.data=="string"?e.data:JSON.stringify(e.data),statusCode:e.status,statusText:e.statusText??"",headers:e.headers}}parseJson(e){try{return JSON.parse(e.data)}catch(t){throw new Error(`Failed to parse JSON response: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}async getBinary(e,t){try{let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout});if(r.status!==200)throw new Error(`HTTP ${r.status}`);return Buffer.from(r.data)}catch(r){let i=await this.tryCurlFallback(r,e,"GET",t,!0);if(i?.bodyBuffer){if(i.statusCode!==200)throw new Error(`HTTP ${i.statusCode}`);return i.bodyBuffer}throw r}}async postAllowFailure(e,t){try{let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});if(r.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});return this.convertResponse(r)}catch(r){return this.withCurlFallback(r,e,"POST",t)}}async deleteAllowFailure(e,t){try{let r=await this.client.request({method:"DELETE",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});if(r.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});return this.convertResponse(r)}catch(r){return this.withCurlFallback(r,e,"DELETE",t)}}async getBinaryAllowFailure(e,t){try{let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});if(r.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});let i=Buffer.from(r.data),o=i.toString("utf8");return{statusCode:r.status,statusText:r.statusText??"",buffer:i,body:o}}catch(r){let i=await this.tryCurlFallback(r,e,"GET",t,!0);if(i?.bodyBuffer)return{statusCode:i.statusCode,statusText:i.statusText,buffer:i.bodyBuffer,body:i.bodyBuffer.toString("utf8")};throw r}}async withCurlFallback(e,t,r,i){let o=await this.tryCurlFallback(e,t,r,i,!1);if(o)return{data:o.body,statusCode:o.statusCode,statusText:o.statusText,headers:o.headers};throw e}async tryCurlFallback(e,t,r,i,o=!1){if(process.platform!=="win32"||!(e instanceof Error)||!nD(e))return null;let s,a=t;return r==="GET"?i?.params&&(a=iD(t,i.params)):i?.params!==void 0&&i.params!==null&&(s=typeof i.params=="string"?i.params:JSON.stringify(i.params)),yg({url:a,method:r,data:s,headers:i?.headers,timeoutMs:i?.timeout,binary:o})}},N=new vd;function nD(n){if(n.response?.status===407)return!0;let e=n.message??"";return/proxy auth(?:oriz|entic)/i.test(e)?!0:n.code==="SELF_SIGNED_CERT_IN_CHAIN"||n.code==="DEPTH_ZERO_SELF_SIGNED_CERT"||n.code==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||n.code==="CERT_HAS_EXPIRED"||n.code==="ERR_TLS_CERT_ALTNAME_INVALID"}function iD(n,e){if(!e||typeof e!="object")return n;let t=new URLSearchParams;for(let[o,s]of Object.entries(e))if(s!=null)if(Array.isArray(s))for(let a of s)t.append(`${o}[]`,String(a));else t.append(o,String(s));let r=t.toString();if(!r)return n;let i=n.includes("?")?"&":"?";return`${n}${i}${r}`}function vg(n){let e=n.split(".");return e.length===3&&e.every(t=>t.length>0)}var rr={CHINA:"CN",RUSSIA:"RU",SINGAPORE:"SG",EUROPE:"EU"},dn={CHINA:"zh_CN",RUSSIA:"ru_RU",EUROPE:"de_DE"},sa={CHINA:"1",SINGAPORE:"5",EUROPE:"7",RUSSIA:"8"},oD={[rr.CHINA]:dn.CHINA,[rr.RUSSIA]:dn.RUSSIA,[rr.EUROPE]:dn.EUROPE,[rr.SINGAPORE]:dn.CHINA},sD={[sa.CHINA]:rr.CHINA,[sa.SINGAPORE]:rr.SINGAPORE,[sa.EUROPE]:rr.EUROPE,[sa.RUSSIA]:rr.RUSSIA};function wg(n){return oD[n]??dn.CHINA}function Sg(n){return sD[n]??rr.CHINA}var wd=class{async getJwtToken(e,t,r,i,o){let s=e.split("&")[0],a=Sg(t),c={tempToken:s,site:a,version:Ce.API_VERSION,appid:o},l=`${r}/${i}`,d=await N.get(l,{params:c});if(d.statusCode!==200)throw new Error(`Failed to get jwtToken: status=${d.statusCode}`);let g=d.data.trim();if(!vg(g))throw new Error("Invalid jwtToken format");return g}},bg=new wd;var Sd=class{async checkJwtToken(e,t,r=!1){let i={refresh:String(r),jwtToken:e},o=`${t}/${Z.JWT_TOKEN_CHECK_PATH}`,s=await N.get(o,{headers:i});if(s.statusCode!==200)throw new Error(`Failed to check jwtToken: ${s.statusCode}`);return N.parseJson(s)}async refreshToken(e){let t=await tr.loadJwtToken();return t?this.refreshTokenWithToken(t,e):null}async refreshTokenWithToken(e,t){try{let r={refresh:"true",jwtToken:e},i=`${t}/${Z.JWT_TOKEN_CHECK_PATH}`,o=await N.get(i,{headers:r});if(o.statusCode!==200)return null;let s=N.parseJson(o);return!s.status||!s.userInfo?null:{accessToken:s.userInfo.accessToken,refreshToken:s.userInfo.refreshToken??""}}catch(r){let i=r;return console.error(`Failed to refresh token: ${i.code??""} ${i.message??""}`),null}}async getUserInfoFromJwt(e,t,r=!1){let i=await this.checkJwtToken(e,t,r);return!i.status||!i.userInfo||!i.userInfo.accessToken?(p("jwtToken invalid."),await tr.clearToken(),null):{userId:i.userInfo.userId??"",userName:i.userInfo.name??"",accessToken:i.userInfo.accessToken,refreshToken:i.userInfo.refreshToken??"",jwtToken:e,countryCode:i.userInfo.nationalCode,language:wg(i.userInfo.nationalCode),isRealName:String(i.userInfo.realName)==="true"}}async fetchUserInfo(e,t){let r=await tr.loadJwtToken();return r?this.getUserInfoFromJwt(r,e,t):null}},Qn=new Sd;import aD from"querystring";import{spawn as cD}from"child_process";function Eg(n){try{let e=JSON.stringify({signInfo:[{agrType:ki.PRIVACY_ID,country:"CN",language:"zh_CN",isAgree:!0}]}),t=aD.stringify({nsp_svc:"as.user.sign",access_token:n,request:e}),r=cD("curl",["-s","-X","POST",ki.TMS_URL,"-H","Content-Type: application/x-www-form-urlencoded","-d",t,"--max-time","5","-o","/dev/null","-w","%{http_code}"],{detached:!0,stdio:["ignore","pipe","ignore"]});r.unref(),r.stdout?.on("data",i=>{let o=i.toString().trim();o==="200"?p("Agreement sign reported successfully"):p(`Agreement sign failed: HTTP ${o}`)}).on("error",()=>{})}catch(e){p(`Agreement sign error: ${e.message}`)}}var aa=class{config;server=null;constructor(e){this.config={...Ii,...e}}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}async login(){try{p(`Login started, isDevecoCodeAuth: ${ze()}`);let e=this.generateClientSecret();this.server=new ta(e,Z.CN_LOGIN_URL,this.config.successRedirectUrl,this.config.failedRedirectUrl),await this.server.start(),p(`Local auth server started on port ${this.server.getPort()}`),await this.openLoginPage(this.server.getPort(),e),p("Browser opened for authentication");let t=await this.server.waitForCallback(this.config.timeout);if(p(`Callback received: siteId=${t.siteId}`),t.siteId!=="1")throw new Oe("Non-China accounts are not supported.");let r=await bg.getJwtToken(t.tempToken,t.siteId,Z.CN_LOGIN_URL,this.config.tempTokenCheckUrl,this.config.appId);p("JWT token received");let i=await Qn.getUserInfoFromJwt(r,Z.CN_LOGIN_URL);if(!i)throw new Oe("Login failed: failed to get user info");return p(`User info received: ${i.userName}`),await tr.saveJwtToken(r),p("JWT token saved"),Eg(i.accessToken),i}finally{this.server&&(await this.server.stop(),this.server=null)}}async isLoggedIn(){return await this.getUserInfo(!0)!==null}async logout(){let e=await tr.loadJwtToken();if(!e)return!1;let r=`${Z.CN_LOGIN_URL}/${this.config.logoutUrl}?jwtToken=${e}`;try{await N.post(r,{timeout:5e3})}catch{p("Logout: server notification failed, local token cleared")}finally{await tr.clearToken()}return!0}async getUserInfo(e=!0){return Qn.fetchUserInfo(Z.CN_LOGIN_URL,e)}generateClientSecret(){return Pg.randomUUID().replace(/-/g,"")}async openLoginPage(e,t){let i=`${Z.CN_LOGIN_URL}/${this.config.authUrl}?port=${e}&appid=${this.config.appId}&code=${t}`;await dg(i)}async refreshToken(){return Qn.refreshToken(Z.CN_LOGIN_URL)}},Fe=new aa;function dD(){return ze()?"Not logged in. Please login via DevEco Code first.":"Please run `devecocli auth login` first."}function uD(n){if(n==null||typeof n!="object")return[];let e=n;if(e.ret&&e.ret.code!==0)throw new Error(`team list request failed: code=${e.ret.code}${e.ret.msg?`, msg=${e.ret.msg}`:""}`);return Array.isArray(e.teams)?e.teams.filter(t=>typeof t=="object"&&t!==null).map(t=>({id:String(t.id??""),upSiteId:Number(t.upSiteId??0),name:String(t.name??""),countryCode:String(t.countryCode??""),siteId:Number(t.siteId??0),userType:Number(t.userType??0),lastLoginTime:String(t.lastLoginTime??""),isMirror:t.isMirror===!0})).filter(t=>t.id.length>0):[]}var ca=class{config;constructor(e){this.config={...Ii,...e}}updateConfig(e){this.config={...this.config,...e}}async listTeams(){let e=await Qn.fetchUserInfo(Z.CN_LOGIN_URL,!0);if(!e)throw new Oe(dD());let t=await this.fetchTeamList(e.accessToken,e.userId),r=uD(t);return{userId:e.userId,teamList:r}}async fetchTeamList(e,t){let r=this.config.agcTeamListUrl,i;try{i=await N.get(r,{headers:{oauth2Token:e,uid:t,source:"cli",lang:dn.CHINA},timeout:15e3})}catch(o){let s=o.message;throw s.includes("401")?new Oe("Token expired. Run `devecocli auth login` again."):new Error(`Network error while listing teams: ${s}`,{cause:o})}if(i.statusCode!==200)throw new Error(`Failed to list teams: HTTP ${i.statusCode}`);return typeof i.data=="string"?JSON.parse(i.data):i.data}},Cg=new ca;async function Cr(){return Cg.listTeams()}async function la(n,e,t){let r=Date.now(),i=!0,o=null;try{await e()}catch(s){i=!1,o=B(s);let a=t?.(s);if(a)throw a}finally{let s={duration_ms:Date.now()-r,success:i,error_code:o};await k.track(n,s)}}function mD(n){if(n.length===0)return kt("No teams found for the current user.");let e=["Id","Name"],t=n.map(s=>[s.id,s.name]),r=e.map((s,a)=>Math.max(s.length,...t.map(c=>c[a].length))),i=s=>s.map((a,c)=>a.padEnd(r[c])).join(" "),o=r.map(s=>"-".repeat(s)).join(" ");return[i(e),o,...t.map(i)].join(`
|
|
1308
|
+
`)}function fD(){return new Promise(n=>{let e=kg.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),n()})})}var po=new pD("auth").description("Authentication commands (login, logout, status, team)");async function hD(n){if(n||!process.stdin.isTTY){console.log(kt(n?"Opening browser for login... (--no-prompt: Enter confirmation skipped)":"Non-interactive terminal: opening browser for login without the Enter confirmation..."));return}console.log(kt("Press Enter to open browser for login (or pass --no-prompt to skip)...")),await fD()}async function gD(n){if(ze()){console.log(bd("Login is managed by DevEco Code. Login from DevEco Code instead."));return}let e={event:b.CommandExecuted,args:["auth","login"]};await la(e,async()=>{let t=await Fe.getUserInfo();if(t){console.log(kt(`Already logged in, User Name:${t.userName}`));return}console.log(kt("Starting login process...")),await hD(n.prompt===!1);let r=await Fe.login();console.log(kt(`Login successful. Logged in as ${r.userName}.`))},t=>{throw t instanceof Oe||(t instanceof Error?t.message:String(t)).includes("Network connection failed")?t:new Error("Login failed",{cause:t})})}po.command("login").description("Log in to your Huawei Developer account").option("--no-prompt","Open the browser immediately without the interactive Enter confirmation (agents and non-interactive terminals)").action(async n=>{await gD(n)});po.command("logout").description("Log out of your Huawei Developer account").action(async()=>{if(ze()){console.log(bd("Login is managed by DevEco Code. Log out from DevEco Code instead."));return}let n={event:b.CommandExecuted,args:["auth","logout"]};await la(n,async()=>{let e=await Fe.logout();console.log(e?kt("Logout successful"):kt("Already logged out."))},e=>new Error("Logout failed",{cause:e}))});po.command("status").description("Show the currently logged-in user").action(async()=>{let n={event:b.CommandExecuted,args:["auth","status"]};await la(n,async()=>{let e=await Fe.getUserInfo();if(!e){console.log(kt("Not logged in"));return}console.log(kt(`Current user: ${e.userName}`))},()=>{console.log(kt("Not logged in"))})});var yD=po.command("team").description("Team-related commands");yD.command("list").description("List team accounts the current user has joined").action(async()=>{let n={event:b.CommandExecuted,args:["auth","team","list"]};await la(n,async()=>{let e=await Cr();console.log(mD(e.teamList))},e=>{if(e instanceof Oe){console.log(bd(e.message));return}throw new Error("Failed to list teams",{cause:e})})});var Ig=po;import{Command as OD}from"commander";import{green as _D,red as yo,cyan as qg,yellow as zg,dim as Jg}from"colorette";import FD from"p-limit";import vD from"ora";var it=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=vD(e),this.spinner.start(),this.isRunning=!0}stop(){this.spinner&&this.isRunning&&(this.spinner.stop(),this.isRunning=!1)}succeed(e){this.spinner&&(this.spinner.succeed(e),this.isRunning=!1)}fail(e){this.spinner&&(this.spinner.fail(e),this.isRunning=!1)}};import*as Ag from"fs";import*as Ed from"path";import{homedir as Dg}from"os";function kr(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}var Rg=["DevEco"];async function da(){let n=await N.get(lt.TAGS_API_URL),t=ua(n,"Tags API").data.skill.filter(r=>r.name==="HMOS");if(t.length===0)throw new Error("No HMOS tag found.");return t.map(r=>r.id)}async function wD(n){let e=[],t=lt.DEFAULT_PAGE_SIZE,r=lt.DEFAULT_MAX_PAGES,i=1;for(;i<=r;){let o=await N.post(lt.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:i,pageSize:t,tagIds:[n]}}),s=ua(o,"Skills API");if(e.push(...s.data.list),s.data.list.length<t)break;i++}return e}async function Pd(n){let e=new Map,t=n.map(i=>wD(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=>!Rg.includes(o.name)))}async function SD(n,e){let t=await N.post(lt.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:lt.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return ua(t,"Skills API").data.list}async function Cd(n,e){let t=new Map,r=e.map(o=>SD(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=>!Rg.includes(s.name)))}function Tg(n){kr(n);let e=[];for(let[,t]of Object.entries(wt)){let r=E.ensurePathWithinRoot(Ed.join(Dg(),t.path),Ed.join(Dg(),t.path,n));Ag.existsSync(r)&&e.push(t.displayName)}return e.sort()}function ua(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=N.parseJson(n);if(t.code!==lt.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function xg(n){kr(n);let e=`${lt.SKILL_API_BASE}/${n}/checksum`,t=await N.get(e);return ua(t,"Checksum API").data}import bD from"adm-zip";import ED from"crypto";import{timingSafeEqual as PD}from"crypto";import kd from"fs";import pe from"path";import{fileURLToPath as CD}from"url";import{homedir as Ng}from"os";import{red as kD}from"colorette";var be=kd.promises;function Lg(n,e){let t=pe.resolve(e),r=pe.resolve(n),i=pe.relative(r,t);if(i.startsWith("..")||pe.isAbsolute(i))throw new Error(`Path traversal detected: ${e}.`)}function Id(n){return pe.isAbsolute(n)?n:pe.resolve(process.cwd(),n)}function ID(n){return ED.createHash("sha256").update(n).digest("hex")}async function DD(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=ID(n),i=e.sha256.toLowerCase(),o=Buffer.from(r,"hex"),s=Buffer.from(i,"hex");if(o.length!==s.length||!PD(o,s))throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function Mg(n){kr(n);let e=`${lt.SKILL_API_BASE}/${n}/install?format=zip`,t=await N.getBinary(e),r=await xg(n);return await DD(t,r),t}async function AD(n,e,t){kr(t);let r=new bD(n),i=r.getEntries();try{await be.stat(e)}catch{await be.mkdir(e,{recursive:!0})}let o=pe.join(e,t);Lg(e,o);for(let s of i){let a=pe.join(o,s.entryName);Lg(o,a)}r.extractAllTo(o,!0)}async function Dd(n){let e=wt[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(wt).join(", ")}`);let t=pe.join(Ng(),e.path.replace("/skills",""));try{return await be.access(t),!0}catch{return!1}}function mo(n){let e=wt[n];return pe.join(Ng(),e.path)}function RD(n){let e=wt[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(wt).join(", ")}`);return e}function Ad(n,e){let t=RD(e),r="projectPath"in t?t.projectPath:pe.join("."+e,"skills");return pe.join(n,r)}async function TD(n,e,t){kr(e);let r=pe.join(n,e);try{if(await be.access(r),t)await be.rm(r,{recursive:!0,force:!0});else return console.log(`Skill ${e} exists in ${n}.`),{skillDir:r,shouldSkip:!0}}catch{}return{skillDir:r,shouldSkip:!1}}async function Rd(n,e,t){await AD(n,e,t),console.log(`Skill ${t} installed to ${pe.join(e,t)}.`)}function xD(n,e){let t=o=>{let s=pe.resolve(o);return s.startsWith("\\\\?\\")&&(s=s.slice(4)),s.replace(/[\\/]+$/,"")},r=t(n),i=t(e);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}async function Td(n,e){let t=process.platform==="win32"?"junction":"dir",r;try{r=await be.lstat(e)}catch{return await be.mkdir(pe.dirname(e),{recursive:!0}),await be.symlink(n,e,t),!0}if(r.isSymbolicLink()){let i;try{i=await be.realpath(e)}catch{return await be.rm(e,{force:!0}),await be.symlink(n,e,t),!0}return xD(i,n)?!1:(await be.rm(e,{force:!0}),await be.symlink(n,e,t),!0)}return await be.rm(e,{recursive:!0,force:!0}),await be.symlink(n,e,t),!0}async function xd(n,e,t){let r=pe.join(e,t),i=await Td(n,r);return i&&console.log(`Skill ${t} linked to ${n}.`),i}function Og(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(kD(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function ei(n,e,t,r,i=!1){try{let o=await e();if(i)return await t(o)===!1?{success:!0,skipped:!0}:{success:!0};let{shouldSkip:s}=await TD(o,n,r);return s?{success:!0,skipped:!0}:(await t(o),{success:!0})}catch(o){return Og(n,o,"Installation failed")}}async function Ld(n,e){try{kr(n);let t=await e(),r=pe.join(t,n);try{await be.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await be.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return Og(n,t,"Removal failed")}}async function _g(n,e,t,r=!1){return ei(n,()=>mo(e),i=>Rd(t,i,n),r)}async function Fg(n,e,t,r=!1){return ei(n,()=>t,i=>Rd(e,i,n),r)}async function $g(n,e,t,r,i=!1){return ei(n,()=>Ad(t,r),o=>Rd(e,o,n),i)}async function jg(n,e,t,r=!1){return ei(n,()=>mo(t),i=>xd(e,i,n),r,!0)}async function Hg(n,e,t,r,i=!1){return ei(n,()=>Ad(t,r),o=>xd(e,o,n),i,!0)}async function Ug(n,e,t,r=!1){return ei(n,()=>t,i=>xd(e,i,n),r,!0)}async function Nd(n,e){return Ld(n,()=>mo(e))}async function Bg(n,e){return Ld(n,()=>e)}async function Wg(n,e,t){return Ld(n,()=>Ad(e,t))}function pa(){let e=pe.dirname(CD(import.meta.url));for(;;){let t=pe.join(e,"skills","deveco-cli");if(kd.existsSync(t)&&kd.statSync(t).isDirectory())return t;let r=pe.dirname(e);if(r===e)break;e=r}throw new Error("skills/deveco-cli directory not found in deveco-cli package. Reinstall deveco-cli.")}import Md from"fs";import Od from"path";import{cyan as LD}from"colorette";var ma=Md.promises,ND="deveco-cli";async function fo(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await Dd(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function ti(){let n=[];for(let e of Object.keys(wt))await Dd(e)&&n.push(e);return n}async function MD(){let n=pa(),e=0,t=0,r=0,i=await ti();for(let o of i){let s=mo(o),a=Od.join(s,ND);try{let c=!0;try{await ma.lstat(a)}catch{c=!1}if(!c){t++;continue}await Td(n,a)?(console.error(`Converted ${o}/deveco-cli to symlink.`),e++):t++}catch(c){r++,console.error(`Skill link migration failed for ${o}: ${c.message}`)}}if(r>0)throw new Error(`${r} agent(s) failed skill-link migration; will retry next command`);return{updated:e,skipped:t}}async function Vg(){let n;try{n=Od.join(de(),"skills","migration-version")}catch{return}let e="";try{e=(await ma.readFile(n,"utf-8")).trim()}catch{}let t=mt();if(e!==t)try{await MD(),await ma.mkdir(Od.dirname(n),{recursive:!0}),await ma.writeFile(n,t,"utf-8")}catch{}}function ho(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(LD("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function Ir(n,e,t){if(!Md.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!Md.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function go(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?Id(n):void 0,resolvedProject:e?Id(e):void 0}}async function fa(n,e,t){let r=[],i=[],o;if(e?o=e:t&&n.agent?i=(await fo(n.agent)).map(a=>({project:t,agent:a})):t?i=(await ti()).map(a=>({project:t,agent:a})):n.agent?r=await fo(n.agent):r=await ti(),!o&&r.length===0&&i.length===0)throw new Error("No agents found. Install an AI agent (cursor, opencode, etc.) or use `--path` for a custom location.");return{agents:r,projectAgents:i,customPath:o}}var Yg="deveco";async function $D(n){let e=await da();if(n.all)return(await Pd(e)).map(r=>r.enName);{let r=(await Cd(n.skill,e)).find(i=>i.enName===n.skill);if(!r)throw new un("errorCode",`Skill "${n.skill}" not found`);return[r.enName]}}async function jD(n,e,t,r){let i=[];if(t.customPath){let o=await Fg(n,e,t.customPath,r);return i.push(o),i}for(let o of t.agents){let s=await _g(n,o,e,r);i.push(s)}for(let{project:o,agent:s}of t.projectAgents){let a=await $g(n,e,o,s,r);i.push(a)}return i}function HD(n){if(n.all&&n.skill)throw new un("errorCode","`--all` and `--skill` cannot be specified together.");if(!n.all&&!n.skill)throw new un("errorCode","Must specify `--all` or `--skill`");let{resolvedPath:e,resolvedProject:t}=go(n.path,n.project,n.agent);return t&&Ir(t,"Project directory",n.force),e&&Ir(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}function UD(n,e,t){return!!(e||t||n.path||n.project||n.agent)}function BD(){return{agents:[Yg],projectAgents:[],customPath:void 0}}async function WD(n,e,t){let r=ze()&&!UD(n,e,t)?BD():await fa(n,e,t);return{skillNames:await $D(n),targets:r}}async function VD(n,e,t,r){let i=[],o=0,s=n.length,a=FD(5),c=n.map(l=>a(()=>GD(l)));for(let l=0;l<n.length;l++){let d=n[l],g=s>1?` (${l+1}/${s})`:"";r.start(`Installing ${d}${g}...`);let y=await c[l];if(!y.success){r.fail(),console.log(yo(`${d}: Download failed - ${y.error}`)),i.push({success:!1});continue}o+=y.buffer.length,r.stop();let I=await jD(d,y.buffer,e,t);i.push(...I)}return{results:i,diskBytes:o}}async function GD(n){try{let e=await Mg(n);return{name:n,buffer:e,success:!0}}catch(e){let t=e instanceof Error?e.message:"unknown error";return{name:n,error:t,success:!1}}}async function qD(n){let e=new it;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=HD(n),{skillNames:i,targets:o}=await WD(n,t,r),{results:s,diskBytes:a}=await VD(i,o,n.force||!1,e);return e.stop(),ho(s),{diskBytes:a,results:s}}catch(t){throw e.stop(),t}}function Kg(n){let e=n.length,t=n.filter(s=>s.success&&!s.skipped).length,r=n.filter(s=>s.skipped).length,i=n.filter(s=>!s.success).length,o=[...new Set(n.filter(s=>!s.success&&typeof s.error=="string").map(s=>zD(s.error)))];return{opTotal:e,opSuccess:t,opFailed:i,opSkipped:r,...o.length>0?{failedErrors:o}:{}}}function zD(n){let e=/^([A-Za-z_][A-Za-z0-9_-]*)/.exec(n.trim());return e?e[1].slice(0,32):"error"}var un=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function JD(n){let e=n;return n instanceof un?n.code:e.code??e.name??"UnknownError"}function ga(n,e={}){return["skills",n,...e.all?["--all"]:[],...e.long?["--long"]:[],...e.skill?["--skill"]:[],...e.force?["--force"]:[],...e.agent?["--agent",e.agent]:[],...e.project?["--project"]:[],...e.path?["--path"]:[]]}async function ya(n,e,t){let r=Date.now(),i=!0,o=null,s={};try{s=await e()}catch(a){throw i=!1,o=JD(a),a}finally{let a={event:b.SkillOperation,subAction:n,args:t,...s};await k.track(a,{duration_ms:Date.now()-r,success:i,error_code:o})}}function YD(n){return ya("add",async()=>{let{diskBytes:e,results:t}=await qD(n);return{diskUsage:te(e),...n.skill?{skillName:n.skill}:{},...Kg(t)}},ga("add",n))}function KD(n){let{resolvedPath:e,resolvedProject:t}=go(n.path,n.project,n.agent);return t&&Ir(t,"Project directory"),e&&Ir(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function XD(n,e){let t=new it;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:i}=KD(e);t.stop();let o=await ZD(e,n,r,i);return t.stop(),ho(o),o}catch(r){throw t.stop(),r}}function Gg(n,e=""){if(n.length===0)throw new un("errorCode",`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function ha(n,e){let t=[];for(let r of e){let i=r.type==="agent"?await Nd(n,r.agent):await Wg(n,r.project,r.agent);t.push(i)}return t}async function ZD(n,e,t,r){if(t)return[await Bg(e,t)];if(r&&n.agent){let a=(await fo(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return ha(e,a)}if(r){let s=await ti();Gg(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return ha(e,a)}if(n.agent){let a=(await fo(n.agent)).map(c=>({type:"agent",agent:c}));return ha(e,a)}if(ze())return[await Nd(e,Yg)];let i=await ti();Gg(i,"or use --path for a custom location.");let o=i.map(s=>({type:"agent",agent:s}));return ha(e,o)}var vo=new OD("skills").description("Manage HarmonyOS skills");vo.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async n=>{try{await ya("list",async()=>{let e=new it;try{e.start("Fetching skills...");let t=await da(),r=await Pd(t);if(r.length===0)return e.stop(),console.log(zg("No skills available.")),{resultTotal:0};e.succeed(`Fetched ${r.length} skills`);for(let i of r)if(n.long){console.log(qg(i.enName)),console.log(Jg(i.description));let o=Tg(i.enName);o.length>0&&console.log(_D(`Installed for: ${o.join(", ")}`)),console.log()}else console.log(i.enName);return{resultTotal:r.length}}finally{e.stop()}},ga("list",n))}catch(e){console.error(yo(e.message)),process.exit(1)}});vo.command("find <keyword>").description("Search skills by keyword").action(async n=>{try{await ya("find",async()=>{let e=new it;try{e.start("Searching skills...");let t=await da(),r=await Cd(n,t);if(r.length===0)return console.log(zg(`No skills found matching '${n}'.`)),e.stop(),{resultTotal:0,queryLen:n.length,keyword:n};e.succeed(`Found ${r.length} skills.`);for(let i of r)console.log(qg(i.enName)),console.log(Jg(i.description)),console.log();return{resultTotal:r.length,queryLen:n.length,keyword:n}}finally{e.stop()}},ga("find"))}catch(e){console.error(yo(e.message)),process.exit(1)}});vo.command("add").description("Install skills to AI agents").option("--all","Install all available skills").option("--agent <agents>","Target agents, comma-separated; Omit to install to all available agents").option("--skill <skill-name>","Name of the skill to install").option("-f, --force","Overwrite an existing skill installation").option("--project <path>","Project root directory for skill installation").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").action(async n=>{try{await YD(n)}catch(e){console.error(yo(e.message)),process.exit(1)}});vo.command("remove").description("Remove an installed skill from AI agents").requiredOption("--skill <skill-name>","Name of the skill to remove").option("--agent <agents>","Target agents, comma-separated.Omit to remove from all available agents").option("--project <path>","Project root directory for skill removal").option("--path <path>","Path for skill removal").action(async n=>{try{await ya("remove",async()=>{let e=await XD(n.skill,n);return{skillName:n.skill,...Kg(e)}},ga("remove",n))}catch(e){console.error(yo(e.message)),process.exit(1)}});var Xg=vo;import{Command as QD,InvalidArgumentError as va}from"commander";import{cyan as _d,red as Qg}from"colorette";import eA from"ora";function tA(n){return["log",...n.device?["--device"]:[],...n.crash?["--crash"]:[],...n.level?["--level"]:[],...n.bundleName?["--bundle-name"]:[],...n.keyword?["--keyword"]:[],...n.tail!==void 0?["--tail"]:[],...n.from!==void 0?["--from"]:[],...n.to!==void 0?["--to"]:[],...n.follow?["--follow"]:[]]}function rA(n){return{event:b.CommandExecuted,args:tA(n),logType:n.crash?"crash":"common",level:n.level??"ALL",bundleName:n.bundleName??"ALL"}}function nA(n){return n instanceof S?n.traceMessage:n instanceof Error?n.code??n.name:"UnknownError"}async function iA(n,e){let t=Date.now(),r=!0,i=null;try{await e()}catch(o){r=!1,i=nA(o),console.error(Qg(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await k.track(n,o).catch(()=>{})}}function oA(n){try{return E.parsePositiveInteger(n,"tail")}catch{throw new va("`tail` must be a positive integer.")}}function Zg(n,e){try{return E.parseDurationToSeconds(n,e)}catch{throw new va(`${e} must be a valid duration string (e.g.,30s, 5m or 2.5m).Supported units: s and m.when specified in seconds(with \`s\` or as a raw number), the value must be an integer.`)}}function sA(n){try{return E.assertHilogLevel(n),n}catch{throw new va("`level` must be one of: D, I, W, E, F.")}}function aA(n){try{return E.assertBundleNameStrict(n),n}catch(e){throw new va(e.message)}}function cA(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.")}async function lA(n,e,t,r,i){return t.crash?await n.getCrashLog(e,t.bundleName):await n.getHilog(e,{level:t.level,bundleName:t.bundleName,keyword:t.keyword,isFollow:!!t.follow,tail:t.tail,fromSeconds:r,toSeconds:i})}function dA(n,e,t,r){let i=E.filterLogsByRelativeWindow(n,t,r);return e.tail?E.getLastLines(i,e.tail):i}var uA=new QD("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(Qg(n))}).option("--device <device>","Target device (name or serial)").option("--crash","Only obtain crash logs").option("--level <level>","Log level filter: D, I, W, E, F",sA).option("--bundle-name <bundle-name>","Filter by application bundle name",aA).option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",oA).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>Zg(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>Zg(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await iA(rA(n),()=>pA(n))});async function pA(n){let e=eA({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};e.start();try{cA(n);let r=n.from,i=n.to,o=await C.new(),s=new yr(o),a=await s.selectDevice(n.device);if(!a)throw new S("No active devices found.","No active devices found.");p(_d(`deviceId: ${a}`)),p(_d(`type: ${n.crash?"Crash logs":"Common logs"}`)),p(_d("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await lA(s,a,n,r,i);t(),n.crash&&c&&(c=dA(c,n,r,i)),c&&console.log(c)}finally{t()}}var ey=uA;import So from"path";import nr from"fs";import jd from"process";import dy from"os";import{Command as IA}from"commander";import{green as sy,red as Fd,cyan as DA,yellow as ay}from"colorette";import fe from"fs-extra";import j from"path";import*as ny from"os";import{fileURLToPath as mA}from"url";var ty={17:{sdkVersion:"5.0.5(17)",modelVersion:"5.0.5"},18:{sdkVersion:"5.1.0(18)",modelVersion:"5.1.0"},19:{sdkVersion:"5.1.1(19)",modelVersion:"5.1.1"},20:{sdkVersion:"6.0.0(20)",modelVersion:"6.0.0"},21:{sdkVersion:"6.0.1(21)",modelVersion:"6.0.1"},22:{sdkVersion:"6.0.2(22)",modelVersion:"6.0.2"},23:{sdkVersion:"6.1.0(23)",modelVersion:"6.1.0"},24:{sdkVersion:"6.1.1(24)",modelVersion:"6.1.1"}},fA=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"],ri=["phone","tablet","2in1","car","wearable","tv"],ry=["entry","src","main","module.json5"];function hA(){let n=import.meta.url,e=mA(n);if(e.includes("dist")){let o=j.dirname(e),s=j.dirname(o);return j.join(s,"templates","application")}let t=j.dirname(e),r=j.dirname(t),i=j.dirname(r);return j.join(i,"templates","application")}function iy(n,e){fe.mkdirSync(e,{recursive:!0});for(let t of fe.readdirSync(n,{withFileTypes:!0})){let r=j.join(n,t.name),i=j.join(e,t.name);if(t.isDirectory()){iy(r,i);continue}fe.existsSync(i)||(fe.mkdirSync(j.dirname(i),{recursive:!0}),fe.copyFileSync(r,i))}}function wo(n,e){let t=fe.readFileSync(n,"utf-8"),r=t;for(let[i,o]of e)r=r.replaceAll(i,o);r!==t&&fe.writeFileSync(n,r,"utf-8")}function gA(n){if(ty[n])return ty[n];if(n>=26){let e=`${n}.0.0`;return{sdkVersion:e,modelVersion:e}}}function yA(n,e){if(e===22)return;let t=gA(e);t&&(wo(j.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),wo(j.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),wo(j.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function vA(n){return fA.filter(t=>!fe.existsSync(j.join(n,t))).length===0}function wA(n,e){let t=ry.join("/"),r=j.join(n,...ry),i=fe.readFileSync(r,"utf-8"),o=/^([ \t]*)"deviceTypes"\s*:\s*\[[\s\S]*?\]/m.exec(i);if(!o)throw new Error(`"deviceTypes" not found in ${t}.`);let s=i.includes(`\r
|
|
1309
|
+
`)?`\r
|
|
1310
|
+
`:`
|
|
1311
|
+
`,a=o[1],c=e.map((d,g)=>`${a} "${d}"${g<e.length-1?",":""}`).join(s),l=`${a}"deviceTypes": [${s}${c}${s}${a}]`;fe.writeFileSync(r,i.replace(o[0],()=>l),"utf-8")}function SA(){return Buffer.from([137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,1,0,0,0,1,8,2,0,0,0,144,119,83,222,0,0,0,12,73,68,65,84,8,215,99,248,255,255,255,0,5,254,2,254,0,0,0,0,73,69,78,68,174,66,96,130])}function bA(n){return ny.platform()==="darwin"?j.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):j.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function EA(n,e){let t=bA(e);if(!fe.existsSync(t))return!1;let r=[["AppScope/resources/base/media/background.png","AppScope/resources/base/media/background.png"],["AppScope/resources/base/media/foreground.png","AppScope/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/background.png"],["entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/startIcon.png","entry/src/main/resources/base/media/startIcon.png"]];for(let[i,o]of r){let s=j.join(t,i),a=j.join(n,o);fe.existsSync(s)&&(fe.mkdirSync(j.dirname(a),{recursive:!0}),fe.copyFileSync(s,a))}return!0}function PA(n){let e=SA(),t=["AppScope/resources/base/media/background.png","AppScope/resources/base/media/foreground.png","entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/startIcon.png"];for(let r of t){let i=j.join(n,r);fe.mkdirSync(j.dirname(i),{recursive:!0}),fe.writeFileSync(i,e)}}function CA(n,e){e&&EA(n,e)||PA(n)}function kA(n){let e=[j.join(n,"gitignore.txt"),j.join(n,"entry","gitignore.txt")];for(let t of e)if(fe.existsSync(t)){let r=j.dirname(t);fe.renameSync(t,j.join(r,".gitignore"))}}function oy(n,e,t,r,i,o){let s=hA();if(!fe.existsSync(s))throw new Error(`Template directory not found: ${s}`);fe.mkdirSync(n,{recursive:!0}),iy(s,n),kA(n),CA(n,o),wo(j.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),wo(j.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),wA(n,i),yA(n,r);let a=vA(n);if(!a)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,deviceTypes:i,verified:a}}function AA(n){if(n.length<1||n.length>200)throw new ye("errorCode",`App name length must be 1-200 characters. Current: ${n.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(n))throw new ye("errorCode","Application name must start with a letter (a-z, A-Z) and contain only letters, digits, and underscores")}function RA(n){if(!n||n.length===0)return[ri[0]];let e=n.map(r=>r.toLowerCase()),t=n.filter((r,i)=>!ri.includes(e[i]));if(t.length>0)throw new ye("errorCode",`Unsupported device type(s): ${t.map(r=>`"${r}"`).join(", ")}. Supported types: ${ri.join(", ")}`);return[...new Set(e)]}function uy(n){if(dy.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function cy(n){if(n.length===0)throw new ye("errorCode","Project path cannot be empty.");if(n.length>120)throw new ye("errorCode",`Project path cannot exceed 120 characters (current: ${n.length}).`);let e=dy.platform();if(!(e==="win32"?/^[a-zA-Z0-9._\-:\\/]+$/:/^[a-zA-Z0-9._\-/]+$/).test(n)){let o=e==="win32"?"letters, digits, dots, underscores, hyphens, colons, slashes (/) or backslashes (\\)":"letters, digits, dots, underscores, hyphens or slashes (/)";throw new ye("errorCode",`Project path can only contain ${o}.`)}let r=uy(n);if(/[\u4e00-\u9fff]/.test(r))throw new ye("errorCode","Project path cannot contain Chinese characters.");if(r.endsWith("."))throw new ye("errorCode","Project path cannot end with a dot (.)")}function TA(n){let e=n,t=So.parse(n).root;for(;e!==t;){if(nr.existsSync(e))return e;e=So.dirname(e)}return nr.existsSync(t)?t:null}function ly(n){let e=TA(n);if(!e)throw new ye("errorCode",`No existing parent directory found for '${n}'. Cannot create project directory.`);try{nr.accessSync(e,nr.constants.W_OK)}catch{throw new ye("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}let t=So.join(e,`.deveco_write_test_${Date.now()}`);try{nr.writeFileSync(t,"test"),nr.unlinkSync(t)}catch{throw new ye("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}}function xA(n){return`com.example.${n.toLowerCase()}`}function LA(n,e){if(e){let i=uy(e),o=So.resolve(i);if(nr.existsSync(o)){if(nr.readdirSync(o).length>0)throw new ye("errorCode",`Directory '${o}' is not empty. Cannot create project here.`)}else ly(o);return o}let t=jd.cwd(),r=So.join(t,n);if(nr.existsSync(r))throw new ye("errorCode",`Directory '${r}' already exists. Cannot create project here.`);return ly(r),r}function NA(n,e){let t=e?.getMaxApiLevel(),r=23;if(n.apiLevel){let i=Number(n.apiLevel);if(!Number.isInteger(i)||i<17)throw new ye("errorCode",`Invalid API version ${n.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(i>t)throw new ye("errorCode",`Invalid API version ${n.apiLevel}. Your SDK supports API version 17-${t}`)}else if(i>r)throw new ye("errorCode",`Invalid API version ${n.apiLevel}. Without DevEco Studio, supported range is API version 17-${r}`);return i}return t!==void 0?t:23}async function MA(){try{return await C.new()}catch(n){console.error(ay(`DevEco Studio not found: ${n.message}`)),console.log(ay("Use placeholder API level instead."));return}}var ye=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};async function $d(n,e,t,r){let i={event:b.CommandExecuted,args:["create"],apiLevel:r?.apiLevel??null},o={duration_ms:Date.now()-n,success:e,error_code:t};await k.track(i,o).catch(()=>{})}function OA(n){console.log(`
|
|
1312
|
+
`+sy("Project created successfully.")),console.log(`Project root: ${n.projectRoot}`),console.log(`App name: ${n.appName}`),console.log(`Bundle name: ${n.bundleName}`),console.log(`API level: ${n.apiLevel}`),console.log(`Device types: ${n.deviceTypes.join(", ")}`),console.log(sy("Template integrity check passed."))}var _A=new IA("create").description("Scaffold a new HarmonyOS application project").option("--project-path <path>","Project directory path (default: ./<app-name>)").option("--app-name <name>","Application name").option("--bundle-name <bundle>","Bundle name (auto-derived as com.example.<app-name> if omitted)").option("--api-level <level>","API level (auto-detected from SDK if omitted; minimum: 17)").option("--device-types <types...>",`Device types written to module.json5 (default: ${ri[0]}; supported: ${ri.join(", ")})`).action(async n=>{let e=Date.now();try{n.appName||(console.error(Fd("Error: --app-name is required")),await $d(e,!1,"errorCode",n),jd.exit(1));let t=n.appName;AA(t);let r=RA(n.deviceTypes),i=n.bundleName||xA(t);E.assertBundleNameStrict(i),n.projectPath&&cy(n.projectPath);let o=LA(t,n.projectPath);cy(o),console.log(DA("Initializing project...")),console.log(`Project path: ${o}`),console.log(`App name: ${t}`),console.log(`Bundle name: ${i}`),console.log(`Device types: ${r.join(", ")}`);let s=await MA(),a=NA(n,s);console.log(`API level: ${a}`);let c=s?.devecoStudioPath,l=oy(o,t,i,a,r,c);OA(l),await $d(e,!0,null,n)}catch(t){let r=t,o=t instanceof ye?t.code:r.code??r.name??"UnknownError";console.error(Fd(`
|
|
1313
|
+
Failed to create project.`)),console.error(Fd(r.message)),await $d(e,!1,o,n),jd.exit(1)}}),py=_A;import{Command as WA}from"commander";import{red as VA,cyan as Sy}from"colorette";import FA from"fs";import wa from"path";import{cyan as $A}from"colorette";import*as Sa from"smol-toml";var ni=FA.promises;async function jA(n){try{let e=await ni.readFile(n,"utf8");return e.trim()===""?{}:JSON.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read configuration file ${n}: ${e.message}`,{cause:e})}}async function HA(n){try{let e=await ni.readFile(n,"utf8");return e.trim()===""?{}:Sa.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read TOML config file ${n}: ${e.message}`,{cause:e})}}async function UA(n,e){let t=wa.dirname(n);await ni.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await ni.writeFile(n,r,"utf8")}async function BA(n,e){let t=wa.dirname(n);await ni.mkdir(t,{recursive:!0});let r=Sa.stringify(e);await ni.writeFile(n,r,"utf8")}function my(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function fy(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 hy(n,e){return n.format==="codex"?HA(e):jA(e)}async function gy(n,e,t){return n.format==="codex"?BA(e,t):UA(e,t)}async function yy(n,e,t=!1){let r=mr[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(mr).join(", ")}`};if(!r.supportsGlobal)return{success:!1,error:`${r.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`};try{let i=await hy(r,r.globalConfigPath);if(my(i,r.mcpServersKey,Mt)&&!t)return console.log(`MCP server ${Mt} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let o=os(r,void 0);return fy(i,r.mcpServersKey,Mt,o,t),await gy(r,r.globalConfigPath,i),console.log(`MCP server ${Mt} configured in ${r.globalConfigPath}.`),{success:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"}}catch(i){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${i.message}`}}}async function Hd(n,e,t=!1){let r=mr[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(mr).join(", ")}`};let i=wa.isAbsolute(r.projectConfigPath)?r.projectConfigPath:wa.join(e,r.projectConfigPath);try{let o=await hy(r,i);if(my(o,r.mcpServersKey,Mt)&&!t)return console.log(`MCP server ${Mt} already configured in ${i}.`),{success:!0,skipped:!0,configPath:i,agentName:n,installType:"project"};let s=os(r,e);return fy(o,r.mcpServersKey,Mt,s,t),await gy(r,i,o),console.log(`MCP server ${Mt} configured in ${i}.`),{success:!0,configPath:i,agentName:n,installType:"project"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${o.message}`}}}function vy(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($A("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)}var Ud="deveco-cli";async function GA(n,e,t){if(n.customPath)return[await Ug(Ud,e,n.customPath,t.force)];let r=[...n.projectAgents.map(({project:s,agent:a})=>()=>Hg(Ud,e,s,a,t.force)),...n.agents.map(s=>()=>jg(Ud,e,s,t.force))],i=5,o=[];for(let s=0;s<r.length;s+=i){let a=r.slice(s,s+i);o.push(...await Promise.all(a.map(c=>c())))}return o}function qA(n){return[...new Set([...n.agents,...n.projectAgents.map(({agent:e})=>e)])]}async function wy(n,e,t,r){await k.track(n,{duration_ms:Date.now()-e,success:t,error_code:r}).catch(()=>{})}async function zA(n,e,t,r,i){let o={event:b.SkillConfigOperation,subAction:"install",targetType:r?"path":i?"project":"global",agents:qA(n)},s=Date.now();try{let a=await GA(n,e,t),c=a.every(l=>l.success||l.skipped);return await wy(o,s,c,c?null:"SKILL_INSTALL_FAILED"),a}catch(a){let c=a instanceof Error?a.code??a.name:"UnknownError";throw await wy(o,s,!1,c),a}}async function JA(n,e,t){let r=[];for(let{project:i,agent:o}of n.projectAgents){let s=await Hd(o,i,t);r.push(s)}for(let i of n.agents){let o=await Hd(i,e,t);r.push(o)}return r}async function YA(n,e){let t=[];for(let r of n){if(!mr[r])continue;let o=await yy(r,process.cwd(),e);t.push(o)}return t}async function KA(n,e,t){let r=["qoder","dsh"];if(t.agent){let l=t.agent.split(",").map(d=>d.trim());for(let d of r)if(l.includes(d))throw new Error(`${d} does not support MCP configuration via DevEco CLI. Use --skill instead, or use other supported agents for MCP.`)}let i=t.force??!1,o=n.projectAgents.filter(l=>!r.includes(l.agent)),s=n.agents.filter(l=>!r.includes(l)),a={...n,projectAgents:o,agents:s},c=e?await JA(a,e,i):await YA(a.agents,i);c.length>0&&(console.log(Sy("MCP Configuration:")),vy(c))}async function XA(n,e,t){let r={event:b.Init,subAction:"install",targetType:e?"project":"global",agentName:t.agent},i=Date.now(),o=!0,s=null;try{await KA(n,e,t)}catch(a){throw o=!1,s=a instanceof Error?a.code??a.name:"UnknownError",a}finally{let a={duration_ms:Date.now()-i,success:o,error_code:s};await k.track(r,a)}}async function ZA(n){if(n.skill&&n.mcp)throw new Error("Cannot use `--skill` and `--mcp` together. Use `--skill` for skill installation only, or `--mcp` for MCP configuration only.");let{resolvedPath:e,resolvedProject:t}=go(n.path,n.project,n.agent);t&&Ir(t,"Project directory",n.force),e&&Ir(e,"Directory",n.force);let r=await fa(n,e,t);if(n.mcp){await XA(r,t,n);return}let i=pa(),o=await zA(r,i,n,e,t);console.log(),o.length>0&&(console.log(Sy("Skill Installation:")),ho(o))}var QA=new WA("init").description("Install the deveco-cli skill or configure the deveco-mcp server into AI agents").option("--agent <agents>","Target agents, comma-separated; installs to all available agents if omitted").option("--project <path>","Project root directory for skill or MCP configuration").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").option("--skill","Install the deveco-cli skill only (same as default behavior; explicit for symmetry with --mcp)").option("--mcp","Configure the deveco-mcp server (syntax checking for .ets and C/C++) only; no skill installation").option("-f, --force","Overwrite existing skill/MCP configuration").action(async n=>{try{await ZA(n)}catch(e){console.error(VA(e instanceof Error?e.message:String(e))),process.exit(1)}}),by=QA;import{Command as cT}from"commander";import{McpServer as zR}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as JR}from"@modelcontextprotocol/sdk/server/stdio.js";import*as Ao from"fs";import*as vi from"path";import{z as ve}from"zod";import ba from"path";function Cy(n,e,t,r,i){if(e.isError)return{};let o=e.content?.[0]?.text??"";if(!o)return{};let s;switch(n){case"check":s=eR(o);break;case"hover":s={hit:ii(o)!=null};break;case"definition":case"declaration":s=Ey(o,t,r,i,!0);break;case"references":s=rR(o);break;case"implementation":s=Ey(o,t,r,i,!1);break;case"documentSymbol":s=nR(o);break;case"callHierarchy":s=iR(o,t,r,i);break;case"workspaceSymbol":s=oR(o,t);break;default:s={}}return s}function ky(n){let e=Array.isArray(n.files)?n.files[0]:n.file;return typeof e!="string"||!e?void 0:ba.extname(e).toLowerCase().replace(/^\./,"")||void 0}function ii(n){let e=n.indexOf(": ");if(e<0)return;let t=n.slice(e+2).trim();if(!(!t||t==="no result"))try{return JSON.parse(t)}catch{return}}function eR(n){let e={total:0,error:0,warn:0,info:0},t=new Set,r=" => Diagnostic: ";for(let o of n.split(`
|
|
1314
|
+
`)){let s=o.indexOf(r);if(s<0)continue;let a;try{a=JSON.parse(o.slice(s+r.length))}catch{continue}if(Array.isArray(a))for(let c of a)c&&typeof c=="object"&&tR(c,e,t)}let i={diagTotal:e.total,diagError:e.error,diagWarn:e.warn,diagInfo:e.info};return t.size>0&&(i.rules=[...t]),i}function tR(n,e,t){e.total++;let r=n.severity;r===1?e.error++:r===2?e.warn++:(r===3||r===4)&&e.info++,typeof n.source=="string"&&t.add(n.source)}function rR(n){let e=ii(n),t=Array.isArray(e)?e:[],r=new Set;for(let i of t){let o=i?.uri;typeof o=="string"&&r.add(o)}return{refTotal:t.length,fileCount:r.size}}function Ey(n,e,t,r,i){let o=ii(n);if(o==null)return{found:!1};let s=Array.isArray(o)?o:[o],a=s[0]?.uri;return i?{found:!0,sameFile:sR(a,e),sourceType:Dy(a,t,r)}:{implTotal:s.length,found:!0}}function nR(n){let e=ii(n),t=Array.isArray(e)?e:[],r=0,i=new Map,o=s=>{for(let a of s){if(!a||typeof a!="object")continue;r++;let c=a.kind;typeof c=="number"&&i.set(c,(i.get(c)??0)+1);let l=a.children;Array.isArray(l)&&o(l)}};return o(t),{symbolTotal:r,kindDist:Bd(i)}}function iR(n,e,t,r){let o=ii(n)?.calls,s=Array.isArray(o)?o:[],a=e.direction,c=new Map;for(let l of s){if(!l||typeof l!="object")continue;let g=(a==="incoming"?l.from:l.to)?.uri,y=Dy(g,t,r);c.set(y,(c.get(y)??0)+1)}return{callsTotal:s.length,calleeSrcDist:Bd(c)}}function oR(n,e){let t=ii(n),r=Array.isArray(t)?t:[],i=new Map,o=0;for(let c of r){if(!c||typeof c!="object")continue;let l=c.kind;typeof l=="number"&&i.set(l,(i.get(l)??0)+1);let d=c.tags;(Array.isArray(d)&&d.includes(1)||c.deprecated===!0)&&o++}let s={resultTotal:r.length,kindDist:Bd(i),deprecatedHit:o},a=e.query;return typeof a=="string"&&(s.queryLen=a.length),s}function Iy(n){if(typeof n!="string"||!n)return null;let e=n;return e.startsWith("file://")&&(e=e.slice(7),process.platform==="win32"&&e.startsWith("/")&&(e=e.slice(1))),e}function Dy(n,e,t){let r=Iy(n);return r?e&&Py(r,e)?"user_project":t&&Py(r,t)?"sdk":"system":"unknown"}function sR(n,e){let t=Iy(n),r=e.file;return!t||typeof r!="string"?!1:Ea(t)===Ea(r)}function Ea(n){try{return ba.resolve(n).replace(/\\/g,"/").toLowerCase()}catch{return n.replace(/\\/g,"/").toLowerCase()}}function Py(n,e){let t=ba.relative(Ea(e),Ea(n));return t!==""&&!t.startsWith("..")&&!ba.isAbsolute(t)}function Bd(n){let e={};for(let[t,r]of n)e[String(t)]=r;return e}var Pa=class{constructor(e,t,r,i){this.telemetry=e;this.getAceServerPid=t;this.getProjectPath=r;this.getSdkPath=i}tools=new Map;add(e,t){return this.tools.set(e.name,{definition:e,handler:t}),this}getAll(){return Array.from(this.tools.values())}registerToServer(e){for(let{definition:t,handler:r}of this.getAll())e.registerTool(t.name,{description:t.description,inputSchema:t.inputSchema},(async i=>this.invokeTool(t.name,i,r)))}async invokeTool(e,t,r){if(h.debug(`[telemetry] mcp tool call: ${e}`),!this.telemetry)return r(t);let i=te(process.memoryUsage().rss),o=await this.resolveLspMemory(),s=Date.now(),a=!0,c=null,l;try{l=await r(t)}catch(d){throw a=!1,c=d instanceof Error?d.code??d.name:"UnknownError",d}finally{await this.trackToolCall(e,t,l,s,i,o,a,c)}return l}async trackToolCall(e,t,r,i,o,s,a,c){if(!this.telemetry)return;let l=r?.isError===!0,d=r&&!l?Cy(e,r,t,this.getProjectPath?.()??"",this.getSdkPath?.()??""):{},g=l?!1:a,y=l&&r?aR(r):c,I={event:b.McpToolCall,subAction:e,mcpMemory:o,lspMemory:s,fileExt:ky(t),...d};typeof t.direction=="string"&&(I.direction=t.direction),await this.telemetry.track(I,{duration_ms:Date.now()-i,success:g,error_code:y})}async resolveLspMemory(){let e=this.getAceServerPid?.()??null;if(e===null)return"unknown";let t=await Qe(e);return t===null?"unknown":te(Number(t)*1024)}};function aR(n){let e=n.content.map(t=>t.text).join(`
|
|
1315
|
+
`);return/not ready|not initialized|initializing|please retry|retry \d+s|syncing|C\+\+ project initialization failed/i.test(e)?"NotReady":/No project detected|PROJECT_PATH|no project path/i.test(e)?"NoProject":/Missing.*parameter|invalid parameters|Unknown feature|must be|Must specify|cannot be used together|invalid/i.test(e)?"BadRequest":/Too many files|Maximum allowed/i.test(e)?"TooManyFiles":/does not exist|not exist|not found|No valid|not a .ets|not a supported|Unsupported/i.test(e)?"InvalidFile":"ToolError"}function Wd(n,e,t,r){return new Pa(n,e,t,r)}import*as gt from"fs";import*as Re from"path";function Ay(n){return"method"in n&&!("id"in n)}import{spawn as Ry}from"child_process";import*as Ty from"crypto";import{EventEmitter as cR}from"events";import*as ir from"fs";import*as xy from"net";import*as It from"path";var lR=50*1024*1024,dR=60*1e3,uR=10*1e3,pR=64*1024;function mR(n){let e=It.resolve(n).replace(/\\/g,"/");return e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),process.platform==="win32"?e.toLowerCase():e}function fR(n){return Ty.createHash("sha1").update(mR(n)).digest("hex").slice(0,12)}function hR(n){let e=It.resolve(n),t=e.split(It.sep),r=t.lastIndexOf("out");return r>0?t.slice(0,r+1).join(It.sep):It.dirname(e)}var Dr=class extends cR{constructor(t){super();this.config=t}process=null;buffer=Buffer.alloc(0);isClosing=!1;socket=null;_ownsProcess=!1;get pid(){return this.process?.pid??null}get ownsProcess(){return this._ownsProcess}get isSocketMode(){return this.socket!==null}ensureDirectories(){let t=It.join(this.config.logPath,"lspLog");return ir.existsSync(t)||ir.mkdirSync(t,{recursive:!0}),ir.existsSync(this.config.indexingDataLocation)||ir.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){this.config.useSocket&&this.config.projectPath?await this.startSocket(t):await this.startStdio(t)}async startStdio(t){this._ownsProcess=!0;let r=this.ensureDirectories();u.debug(`[LspClient] serverMaxSize=${t}MB`);let i=Oi({serverPath:this.config.serverPath,lspLogPath:r,serverMaxSize:t}),o=Yr(this.config.nodePath);u.debug(`[LspClient] Starting process: node ${i.join(" ")}`),u.debug(`[LspClient] nodePath: ${o}`),this.process=Ry(o,i,{cwd:this.config.cwd||process.cwd(),stdio:["pipe","pipe","pipe"],windowsHide:!0}),this.bindProcessEvents(!0,!0),await new Promise(s=>setTimeout(s,500)),u.info("[LspClient] start lsp process success")}async startSocket(t){let r=this.ensureDirectories(),i=this.config.projectPath,o=hR(this.config.serverPath),s=It.join(i,".idea",".deveco","arkts",".cache",`lsp-socket-${fR(o)}.properties`),a=this.tryReadPortFile(s);if(a!==null)try{u.info(`[LspClient] Port file found (lspSocketPort=${a}), connecting to existing server`),this._ownsProcess=!1,await this.connectSocket(a),u.info("[LspClient] Connected to existing socket server");return}catch(d){u.warn(`[LspClient] Failed to connect to existing socket server (port=${a}): ${d instanceof Error?d.message:d}, falling back to spawn`)}let c=3,l=null;for(let d=1;d<=c;d++)try{d===1?u.info("[LspClient] Spawning server in socket mode"):u.info(`[LspClient] Retry ${d}/${c} spawning socket server`),this._ownsProcess=!0,await this.spawnSocketServer(t,r,i),u.info("[LspClient] Socket server started and connected");return}catch(g){l=g instanceof Error?g:new Error(String(g)),u.warn(`[LspClient] Spawn attempt ${d}/${c} failed: ${l.message}`),this.cleanupSpawnResidue()}throw new Error(`Failed to start socket server after ${c} attempts: ${l?.message}`)}cleanupSpawnResidue(){if(this.process){try{this.process.exitCode===null&&this.process.signalCode===null&&this.process.kill()}catch{}this.process=null}if(this.socket){try{this.socket.destroy()}catch{}this.socket=null}}tryReadPortFile(t){try{if(!ir.existsSync(t))return null;let i=ir.readFileSync(t,"utf8").match(/lspSocketPort\s*=\s*(\d+)/);if(i){let o=parseInt(i[1],10);if(Number.isFinite(o)&&o>0)return o}return null}catch{return null}}async spawnSocketServer(t,r,i){u.debug(`[LspClient] serverMaxSize=${t}MB`);let o=Oi({serverPath:this.config.serverPath,lspLogPath:r,serverMaxSize:t,transportFlag:"--scope=multi",projectPath:i}),s=Yr(this.config.nodePath);u.debug(`[LspClient] Starting process (socket): node ${o.join(" ")}`),u.debug(`[LspClient] nodePath: ${s}`),this.process=Ry(s,o,{cwd:this.config.cwd||process.cwd(),stdio:["pipe","pipe","pipe"],windowsHide:!0,detached:!0});let a=await this.waitForPortFromStdout(dR);u.debug(`[LspClient] LSP_SOCKET_LISTENING port=${a}`),await this.connectSocket(a),this.bindProcessEvents(!0,!1)}waitForPortFromStdout(t){return new Promise((r,i)=>{let o=this.process?.stdout;if(!o){i(new Error("LSP server failed to start: no stdout"));return}let s=/LSP_SOCKET_LISTENING:(\d+)/,a="",c=setTimeout(()=>{o.removeListener("data",l),i(new Error("LSP server failed to start: port not received within timeout"))},t),l=d=>{a+=d.toString("utf8");let g=a.match(s);if(g){clearTimeout(c),o.removeListener("data",l),r(parseInt(g[1],10));return}a=a.slice(-pR)};o.on("data",l)})}connectSocket(t){return new Promise((r,i)=>{let o=xy.connect(t,"127.0.0.1"),s=setTimeout(()=>{o.destroy(),i(new Error(`TCP connection to LSP socket timed out (port ${t})`))},uR);o.on("connect",()=>{clearTimeout(s),this.socket=o,this.bindSocketEvents(o),r()}),o.on("error",a=>{clearTimeout(s),i(new Error(`TCP connection to LSP socket failed: ${a.message}`))})})}bindSocketEvents(t){t.on("data",r=>this.handleData(r)),t.on("error",r=>{u.error(`[LspClient] socket error: ${r.message}`),this.isClosing||this.emit("error",r)}),t.on("close",()=>{u.info("[LspClient] socket closed"),this.isClosing||this.emit("error",new Error("LSP socket closed"))})}attachProcess(t,r){if(this.process)throw new Error("[LspClient] process already attached");this._ownsProcess=!0,this.process=t,this.bindProcessEvents(r?.stderrAsError??!0,!0),u.info("[LspClient] attached to external process")}bindProcessEvents(t=!0,r=!0){this.process&&(r&&this.process.stdout?.on("data",i=>{this.handleData(i)}),this.process.stderr?.on("data",i=>{let o=i.toString("utf8").trim();u.error(`[LspClient] stderr: ${o}`),!this.isClosing&&t&&this.emit("error",new Error(`[LspClient] stderr: ${o}`))}),this.process.on("exit",i=>{u.info(`[LSP EXIT] code=${i}`),this.isClosing||this.emit("error",new Error(`LSP process exited with code ${i}`))}))}sendRaw(t,r){let i=this.buildLspMessage(t);if(this.socket&&!this.socket.destroyed&&this.socket.writable){u.debug(`[LspClient] [SOCKET SEND] ${r}: ${t.slice(0,200)}`),this.socket.write(i,"utf8");return}if(!this.process?.stdin?.writable){u.warn("[LspClient] Cannot send message, no writable transport");return}u.debug(`[LspClient] send message: ${r}`),this.process.stdin.write(i,"utf8")}send(t,r,i){let o={jsonrpc:"2.0",method:t,params:r};i!==void 0&&(o.id=i),this.sendRaw(JSON.stringify(o),t)}sendNotification(t,r){this.sendRaw(JSON.stringify({jsonrpc:"2.0",method:t,params:r}),t)}sendRequest(t,r,i){this.sendRaw(JSON.stringify({jsonrpc:"2.0",id:i,method:t,params:r}),t)}buildLspMessage(t){return`Content-Length: ${Buffer.from(t,"utf8").length}\r
|
|
1310
1316
|
\r
|
|
1311
1317
|
${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this.buffer.indexOf(`\r
|
|
1312
1318
|
\r
|
|
1313
|
-
`);if(r===-1)break;let o=this.buffer.slice(0,r).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!o){u.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(r+4);continue}let s=parseInt(o[1],10);if(!Number.isFinite(s)||s<0||s>GA){u.warn(`[LspClient] Invalid Content-Length: ${o[1]}, drop until next packet`),this.buffer=this.buffer.slice(r+4);continue}let a=r+4,c=a+s;if(this.buffer.length<c)break;let l=this.buffer.slice(a,c).toString("utf8"),d=this.recoverFramedJson(l);if(d&&d.rest.length>0){u.warn(`[LspClient] recovered mixed LSP frame, bodyLen=${l.length}, restLen=${d.rest.length}`),this.logSocketRecv(d.json),this.emit("message",d.json),this.buffer=Buffer.concat([Buffer.from(d.rest,"utf8"),this.buffer.slice(c)]);continue}this.logSocketRecv(l),this.emit("message",l),this.buffer=this.buffer.slice(c)}}logSocketRecv(t){this.socket&&u.debug(`[LspClient] [SOCKET RECV] ${t.slice(0,200)}`)}waitForExitOrTimeout(t){let r=this.process;return!r||r.exitCode!==null||r.signalCode!==null?Promise.resolve():new Promise(i=>{let o=!1,s=()=>{o||(o=!0,clearTimeout(c),r.off("exit",a),i())},a=()=>s();r.once("exit",a);let c=setTimeout(s,t)})}recoverFramedJson(t){let r=t.search(/\S/);if(r<0||t[r]!=="{"&&t[r]!=="[")return null;let i=0,o=!1,s=!1;for(let a=r;a<t.length;a++){let c=t[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(o=!1);continue}if(c==='"'){o=!0;continue}if(c==="{"||c==="["){i++;continue}if((c==="}"||c==="]")&&(i--,i===0)){let l=t.slice(r,a+1),d=t.slice(a+1);return{json:l,rest:d}}}return null}stop(){if(this.isClosing=!0,this.socket){this.socket.destroy(),this.socket=null,this.process=null;return}let t=this.process;if(!t)return;if(this.process=null,t.exitCode===null&&t.signalCode===null)try{t.kill()}catch{}}};var Ir=class{callbacks=new Map;pending=new Map;timeouts=new Map;registerPending(e,t,r){return new Promise((i,o)=>{let s;r>0&&(s=setTimeout(()=>{this.pending.delete(e),this.timeouts.delete(e),o(new Error(`LSP request '${t}' (id=${e}) timeout after ${r}ms`))},r),this.timeouts.set(e,s)),this.pending.set(e,{resolve:i,reject:o,method:t,timer:s})})}resolvePending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.resolve(t),this.pending.delete(e),!0):!1}rejectPending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.reject(t),this.pending.delete(e),!0):!1}register(e,t){this.callbacks.set(e,t)}emit(e,t,r){u.debug(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let i=this.callbacks.get(e);if(i)try{i(t,r)}finally{this.callbacks.delete(e)}else{let o=[...this.callbacks.keys()].map(s=>String(s));u.debug(`[RequestCallbackManager] emit: NO callback for key='${e}', registered keys=[${o.join(",")}]`)}}registerTimeout(e,t,r,i){let o=this.timeouts.get(e);o&&clearTimeout(o);let s=setTimeout(()=>{u.debug(`[RequestCallbackManager] timeout, key=${e}, method=${t}`);try{i()}finally{this.timeouts.delete(e)}},r);this.timeouts.set(e,s)}clearTimeout(e){let t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e))}deleteCallback(e){this.callbacks.delete(e)}hasCallback(e){return this.callbacks.has(e)||this.pending.has(e)}clear(e){this.clearTimeout(e);let t=this.pending.get(e);t&&(t.reject(new Error(`Request '${t.method}' (id=${e}) cancelled`)),this.pending.delete(e)),this.callbacks.delete(e)}rejectAll(e){for(let[,t]of this.pending)t.reject(e);this.pending.clear();for(let[,t]of this.timeouts)clearTimeout(t);this.timeouts.clear(),this.callbacks.clear()}};var sa=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var Yn=class{map=new Map;register(e,t){let r=this.map.get(e);r||(r=new Set,this.map.set(e,r)),r.add(t)}unregister(e,t){let r=this.map.get(e);r&&(t!==void 0?r.delete(t):r.clear(),r.size===0&&this.map.delete(e))}invoke(e,...t){let r=this.map.get(e);if(r)for(let i of r)try{i(...t)}catch(o){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,o)}}invokeOnce(e,...t){this.invoke(e,...t),this.unregister(e)}clear(){this.map.clear()}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}};function T(n){return typeof n=="object"&&n!==null}var Qg=20*1e3,ZA=30*1e3,ey=300,QA=300;function eD(){let n=process.env.DEVECO_CLI_LSP_STANDARD_EXIT_TIMEOUT_MS;if(n===void 0||n==="")return ey;let e=parseInt(n,10);return Number.isFinite(e)?Math.max(QA,e):ey}var aa=class{client;nextRequestId=1;stopOnce=null;callbacks=new Yn;requestCallbacks=new Ir;diagnosticMap=new Map;initProgressReset=null;notificationWaiters=new Map;get lspPid(){return this.client.pid}constructor(e){this.client=new kr(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{u.info("[ClientMessageHandle] Sending shutdown request"),this.client.sendRequest(v.SHUTDOWN,null,this.nextRequestId++),u.info("[ClientMessageHandle] Sending exit notification"),this.client.sendNotification(v.EXIT,null),u.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(eD()),u.info("[ClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(v.BROADCAST),this.callbacks.register(v.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(v.BROADCAST,e)}async sendInitialize(e){let t=this.nextRequestId++,r=this.requestCallbacks.registerPending(t,v.INITIALIZE,Xe);return this.client.sendRequest(v.INITIALIZE,e,t),r}sendInitializeResettable(e,t){let r=this.nextRequestId++,i=this.requestCallbacks.registerPending(r,v.INITIALIZE,0);return this.client.sendRequest(v.INITIALIZE,e,r),new Promise((o,s)=>{let a,c=()=>{a=setTimeout(()=>{this.initProgressReset=null,s(new Error(`LSP initialization timeout after ${t}ms`))},t)},l=()=>{clearTimeout(a),c()};this.initProgressReset=l,c(),i.then(()=>{clearTimeout(a),this.initProgressReset=null,o()},d=>{clearTimeout(a),this.initProgressReset=null,s(d)})})}sendInitialized(){this.client.sendNotification(v.INITIALIZED,{})}sendInitializeAndWaitForNotification(e,t,r,i,o){return new Promise((s,a)=>{let c={initializeResolved:!1,notificationResolved:!1},l=this.startInitTimer(t,r,a);this.initProgressReset=()=>{l.reset(),o?.()};let d=()=>{c.initializeResolved&&c.notificationResolved&&(l.clear(),s())};this.notificationWaiters.set(t,()=>{c.notificationResolved=!0,d()});let g=this.nextRequestId++;this.client.sendRequest(v.INITIALIZE,e,g),this.requestCallbacks.registerPending(g,v.INITIALIZE,0).then(()=>{c.initializeResolved=!0;try{i()}catch(y){l.clear(),a(y instanceof Error?y:new Error(String(y)));return}d()},y=>{l.clear(),a(y)})})}startInitTimer(e,t,r){let i,o=()=>{clearTimeout(i),this.initProgressReset=null,this.notificationWaiters.delete(e)},s=()=>{i=setTimeout(()=>{o(),r(new Error(`LSP initialization timeout after ${t}ms`))},t)},a=()=>{clearTimeout(i),s()};return s(),{reset:a,clear:o}}sendDidOpen(e){let t=e.textDocument.uri;this.diagnosticMap.has(t)||(this.diagnosticMap.set(t,new sa(t)),this.registerDiagnosticTimeout(t)),this.client.sendNotification(v.DID_OPEN,e)}sendDidChange(e){let t=e.textDocument.uri,r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t)),this.client.sendNotification(v.DID_CHANGE,e)}closeFile(e){this.cleanupDiagnosticState(e.textDocument.uri),this.client.sendNotification(v.DID_CLOSE,e)}sendLspRequest(e,t,r=ZA){let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,r);return this.client.sendRequest(e,t,i),o}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}onDidChangeWatchedFiles(e){e.length!==0&&this.client.sendNotification(v.WORKSPACE_DID_CHANGE_WATCHED_FILES,{changes:e})}sendDidChangeConfiguration(e){this.client.sendNotification(v.WORKSPACE_DID_CHANGE_CONFIGURATION,{settings:e})}sendNotification(e,t){this.client.sendNotification(e,t)}getDiagnosticMessages(e){let t=this.diagnosticMap.get(e);return t?t.get():[]}clearDiagnostic(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let i=r instanceof Error?r.message:String(r);u.error(`[LSP] JSON parse error: ${i}, raw: ${e}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotificationOrRequest(t):u.warn(`[LSP] Unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t===void 0)return;let r=t;if(e.error){let i=new Error(`LSP error ${e.error.code}: ${e.error.message}`);this.requestCallbacks.rejectPending(r,i)}else this.requestCallbacks.resolvePending(r,e.result)}handleNotificationOrRequest(e){let t=e.method;if(!t)return;this.initProgressReset?.();let r=this.notificationWaiters.get(t);if(r){this.notificationWaiters.delete(t),r();return}switch(t){case v.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case v.PROGRESS:this.handleProgress(e.params);break;case v.WINDOW_SHOW_MESSAGE:u.debug(`[LSP] window/showMessage: ${JSON.stringify(e.params)}`);break;case v.WINDOW_LOG_MESSAGE:u.debug(`[LSP] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.broadcastToClients(e)}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=e.uri,r=this.diagnosticMap.get(t);if(!r)return;let i=e.diagnostics||[];this.normalizeDiagnostics(i),r.set(i),this.finalizeDiagnostic(t,i)}normalizeDiagnostics(e){for(let t of e)if(t.severity!==void 0){let r={1:"Error",2:"Warning",3:"Information",4:"Hint"};t.severityStr=r[t.severity]||"Unknown"}}handleProgress(e){T(e)&&this.broadcastToClients({jsonrpc:x,method:v.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,v.PUBLISH_DIAGNOSTICS,Qg,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${Qg}ms, uri: ${e}`)})}finalizeDiagnostic(e,t,r){let i={uri:e,diagnostics:t,...r?{errorMessage:r}:{}};this.requestCallbacks.emit(e,v.PUBLISH_DIAGNOSTICS,i),this.diagnosticMap.get(e)?.clear()}handleError(e){let t=Array.from(this.diagnosticMap.keys()).filter(r=>this.requestCallbacks.hasCallback(r));if(t.length>0){let r={range:{start:{line:0,character:0},end:{line:0,character:0}},severity:1,message:e.message};for(let i of t)this.finalizeDiagnostic(i,[r]);return}this.broadcastToClients({jsonrpc:x,method:v.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var ca=class{uri;messages=[];receivedTypes=new Set;uniqueMessages=new Set;isFromEditor=!1;constructor(e){this.uri=e}setReceivedType(e){this.receivedTypes.add(e)}addMessage(e,t){this.receivedTypes.add(e);let r=`${e}:${t}`;if(this.uniqueMessages.has(r)){u.info(`[LegacyDiagnostic] addMessage: duplicate message=${r}`);return}this.uniqueMessages.add(r),this.messages.push(new gd(e,t))}clearMessages(){this.messages=[]}clear(){this.receivedTypes.clear(),this.uniqueMessages.clear(),this.messages=[]}hasReceivedAllTypes(e){for(let t of e)if(!this.receivedTypes.has(t))return!1;return!0}getMessages(){return this.messages.map(e=>e.diagnostics)}},gd=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var tD={EXIT:"exit",INITIALIZED:"initialized",ON_DID_CHANGE_PACKAGE_DEPENDENCIES:"aceProject/onDidChangePackageDependencies",ON_ASYNC_DID_OPEN:"aceProject/onAsyncDidOpen",ON_ASYNC_DID_CHANGE:"aceProject/onAsyncDidChange",DID_CLOSE:"textDocument/didClose",ON_ASYNC_HOVER:"aceProject/onAsyncHover",ON_ASYNC_DEFINITION:"aceProject/onAsyncDefinition",ON_ASYNC_FIND_USAGES:"aceProject/onAsyncFindUsages"},rD={MODULE_INIT_FINISH:ts.MODULE_INIT_FINISH,INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate",ON_FORCE_OPEN_FILE:"aceProject/onForceOpenFile",ON_PACKAGE_CHANGE_FINISH:"aceProject/onPackageChangeFinish",TEXT_DOCUMENT_ON_ASYNC_DEFINITION:"textDocument/onAsyncDefinition",ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:"textDocument/onDidChangePackageDependencies",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",REFERENCES:"textDocument/references",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",BROADCAST:"lsp/broadcast",ARKTS_ERROR:"arkts/error",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing"},L={...tD,...rD},Ar={EXIT:"exit",INITIALIZED:"initialized",EMPTY:"empty",ON_DID_CHANGE_PACKAGE_DEPENDENCIES:"onDidChangePackageDependencies",ON_ASYNC_DID_OPEN:"onAsyncDidOpen",ON_ASYNC_DID_CHANGE:"onAsyncDidChange",DID_CLOSE:"didClose",ON_ASYNC_HOVER:"onAsyncHover",ON_ASYNC_DEFINITION:"onAsyncDefinition",ON_ASYNC_FIND_USAGES:"onAsyncFindUsages"},ty=new Set([1e3,2e3,3e3,3001]);function nD(n){if(!T(n))return!1;let e=n.textDocument;return T(e)&&typeof e.uri=="string"}function iD(n){return T(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function oD(n){return T(n)&&typeof n.moduleName=="string"&&typeof n.current=="number"&&typeof n.total=="number"?`indexing module '${n.moduleName}', ${n.current} of total ${n.total} modules`:`params=${JSON.stringify(n??null)}`}var la=class n{client;isInitialized=!1;stopOnce=null;callbacks=new Yn;requestCallbacks=new Ir;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;get lspPid(){return this.client.pid}constructor(e){this.client=new kr(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{u.info("[LegacyClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:x,method:L.EXIT,params:{}}),Ar.EXIT),u.info("[LegacyClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),u.info("[LegacyClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(L.BROADCAST),this.callbacks.register(L.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(L.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(L.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(L.INDEXING_PROGRESS_UPDATE,e)}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}sendInitialize(e,t){this.client.send("initialize",e,t)}sendInitialized(e){this.client.sendRaw(JSON.stringify({jsonrpc:x,method:L.INITIALIZED,params:{editors:e}}),Ar.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:x,id:0,result:{}}),Ar.EMPTY)}sendAsyncRequest(e,t,r,i){if(!T(t)){u.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!nD(t)){u.warn(`[LSP] sendAsyncRequest missing textDocument.uri, method=${e}, params=${JSON.stringify(t)}`);return}if(typeof r!="number"){u.warn(`[LSP] sendAsyncRequest invalid requestId, method=${e}, requestId=${String(r)}`);return}let o=t.textDocument.uri,s=vt(o);t.textDocument.uri=s,delete t.requestId;let a=i??e;u.info(`[LSP] sendAsyncRequest ${a}, filePath: ${o}`),this.client.sendRaw(JSON.stringify({jsonrpc:x,method:e,params:{params:t,requestId:r}}),a)}onDidChangeWatchedFiles(e){if(u.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let r of e){if(!iD(r)){u.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:x,method:L.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),L.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!T(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){u.warn("[LSP] sendModuleDependencyUpdate, moduleSet is empty or null");return}let t=e.moduleSet;u.info(`[LSP] sending module dependency updated, count: ${t.length}`),this.client.sendRaw(JSON.stringify({jsonrpc:x,method:L.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),Ar.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let i=vt(t);e.textDocument.uri=i,u.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new ca(i),this.diagnosticMap.set(i,o),this.registerDiagnosticTimeout(i,L.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(o.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:x,method:L.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),Ar.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=vt(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,L.PUBLISH_DIAGNOSTICS)),u.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:x,method:L.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),Ar.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=vt(e);u.info(`[LSP] didClose, uri: ${r}`);let i=this.diagnosticMap.get(r);if(!t&&(!i||i.isFromEditor)){u.info(`[LSP] closeFile skip, !diagnostic: ${!i}, isFromEditor: ${i?.isFromEditor}`);return}this.cleanupDiagnosticState(r),this.client.sendRaw(JSON.stringify({jsonrpc:x,method:L.DID_CLOSE,params:{textDocument:{uri:r}}}),Ar.DID_CLOSE)}getDiagnosticMessage(e){let t=vt(e),r=this.diagnosticMap.get(t);return r?r.getMessages():[]}clear(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){try{let t=JSON.parse(e);this.handleLspMessage(t)}catch(t){let r=t instanceof Error?t.message:String(t);u.error(`[LSP] JSON parse error: ${r}, raw: ${e}`)}}handleError(e){let t=this.getPendingDiagnosticUris();if(t.length>0){let r=JSON.stringify({message:e.message,severity:"Error",severityStr:"Error"});for(let i of t)this.finalizeDiagnostic(i,L.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:x,method:L.ARKTS_ERROR,params:{message:e.message}})}handleLspMessage(e){let t=e.method;t!==void 0&&(!this.isInitialized&&this.handlePreInitMessage(t,e)||this.handlePostInitMessage(t,e))}handlePreInitMessage(e,t){switch(e){case L.MODULE_INIT_FINISH:return u.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(L.MODULE_INIT_FINISH),this.callbacks.unregister(L.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case L.INDEXING_PROGRESS_UPDATE:return u.info(`[LSP] onIndexingProgressUpdate: ${oD(t.params)}`),this.callbacks.invoke(L.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case L.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case L.ON_PACKAGE_CHANGE_FINISH:u.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case L.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case L.ON_ASYNC_HOVER:this.handleAsyncResponse(t,L.HOVER);return;case L.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,L.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case L.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,L.REFERENCES);return;default:u.warn(`[LSP] handleLspMessage: no handler for notification, ignoring, method: ${e}, initialized: ${this.isInitialized}`)}}handleOnForceOpenFile(e){u.info("[LSP] handleLspMessage, receive onForceOpenFile");let t=e.params;T(t)&&T(t.result)&&typeof t.result.uri=="string"&&this.handleForceOpenFile(t.result.uri)}handlePublishDiagnostics(e){u.info("[LSP] handleLspMessage, receive publishDiagnostics");let t=e.params;t&&this.parseDiagnostics(t)}handlePackageChangeFinish(e){let t=e.params,r={jsonrpc:x,method:L.ON_PACKAGE_CHANGE_FINISH,params:[!1]};if(!t||!Array.isArray(t)){u.warn("[LSP] aceProject/onPackageChangeFinish params invalid"),this.broadcastToClients(r);return}if(!(t.length>0&&t[0]===!0)){u.warn("[LSP] aceProject/onPackageChangeFinish: package request failed"),this.broadcastToClients(r);return}u.info("[LSP] aceProject/onPackageChangeFinish: success"),this.broadcastToClients(e)}handleAsyncResponse(e,t){u.info(`[LSP] handleAsyncResponse\uFF0C method: ${t}`);let r=e.params;if(!T(r)){u.warn("[LSP] aceProject/onAsyncHover message invalid");return}let i=r.requestId;if(typeof i!="number"){u.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(i,t,r)}handleForceOpenFile(e){if(!e){u.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,L.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){u.info("[LSP] publishDiagnostics uri is null");return}let r=e.version??-1;if(r===-1)return;let i=this.diagnosticMap.get(t);if(!i){u.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let o=e.diagnostics||[];o.length!==0?o.forEach(s=>{this.normalizeDiagnostic(s),i.addMessage(r,JSON.stringify(s))}):i.setReceivedType(r),i.hasReceivedAllTypes(ty)&&this.finalizeDiagnostic(t,L.PUBLISH_DIAGNOSTICS,i.getMessages())}normalizeDiagnostic(e){let t=e;if(delete t.source,t.severity!==void 0){let r=typeof t.severity=="number"?t.severity:parseInt(t.severity),o={1:"Error",2:"Warning",3:"Information",4:"Hint"}[r]||"Unknown";t.severityStr=o,t.severity=o}e.range&&(this.adjustPositionLine(e.range,"start"),this.adjustPositionLine(e.range,"end"))}adjustPositionLine(e,t){let r=e[t];r&&typeof r.line=="number"&&(r.line=r.line+1)}registerDiagnosticTimeout(e,t){this.requestCallbacks.registerTimeout(e,t,n.DIAGNOSTIC_TIMEOUT_MS,()=>{let r=this.diagnosticMap.get(e),i=r?r.getMessages():[];this.finalizeDiagnostic(e,t,i,i.length>0?void 0:`received no diagnostics within ${n.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,r,i){let o={uri:e,diagnostics:r,...i?{errorMessage:i}:{}};this.requestCallbacks.emit(e,t,o),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import yd from"path";import*as ga from"path";var da=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var ua=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var pa=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var ma=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var fa=class{typeSetting=new pa;parameterNames=new ma};var ha=class{constructor(e,t,r,i){this.rootUri=e;this.lspServerWorkspacePath=de(ga.dirname(t)),this.indexingDataLocation=de(i),this.loggerPath=de(ga.join(r,"lspLog"))}modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new da;gutterIconsSetting=new ua;inlayHintsSetting=new fa;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as ry from"path";var po=class{productName="default";buildModeName="debug";targetName="default";arkTSVersion="1.1";resourceDirectories=[];targetESVersion="ES2021";maxFlowDepth=2e3;caseSensitiveCheck=!0;tsImportSendable=!1;compatibleSdkVersionStage="";useNormalizedOHMUrl=!0;reExportCheckMode="noCheck";skipOhModulesLint=!1;byteCodeHar=!0;obfuscationRuleOptionsEnable=!1;enableStrictCheckOHModules=!1;sourceRoots=[];constructor(e){e&&this.resourceDirectories.push(de(ry.join(e,"src","main","resources")))}};var sD="OS",Kn=class{deviceType=[5];aceLoaderPath;modulePath;jsComponentType="declarative";sdkJsPath;compatibleSdkVersion;compatibleSdkLevel;compileSdkLevel;compileSdkVersion="6.0.1.112";compileSdkType="Release";syscap={NDeviceSysCaps:[],addedSysCaps:[]};apiType="stageMode";hosSdkPath;runtimeOs=`Harmony${sD}`;moduleName;moduleType;compileMode="jsbundle";crossPlatform=!1;ignoreCrossPlatform=!1;packageManagerType="ohpm";permissions=[];testPermissions=[];buildProfileParam;appParam={bundleType:"app"};packageName;projectType="OHOS";projectName;moduleDependencies;moduleJsonParam=null;globalDeclarationFiles=[];constructor(e){e?(this.modulePath=e,this.buildProfileParam=new po(e)):this.buildProfileParam=new po}toString(){return JSON.stringify(this)}};var Xn=class{constructor(e=[]){this.pages=e}pagesFileName="main_pages.json";metaDataList=[]};import*as _e from"path";import*as ei from"fs";var ya=class{modulePath;dependencies={};dynamicDependencies={}};var ln=class{registryType;resolved;name;version;type;constructor(e){let t=typeof e=="object"&&e!==null?e:{};this.name=typeof t.name=="string"?t.name:"",this.version=typeof t.version=="string"?t.version:"",typeof t.registryType=="string"?this.registryType=t.registryType:this.registryType=typeof t.path=="string"?"local":"ohpm",typeof t.resolved=="string"?this.resolved=t.resolved:typeof t.storePath=="string"?this.resolved=t.storePath:this.resolved="",this.type=typeof t.type=="string"?t.type:void 0}};var Zn=class{constructor(e,t,r){this.projectPath=e;this.moduleName=t;this.modulePath=r}dependencies=[];devDependencies=[];dynamicDependencies=[];finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[]};import*as rr from"path";import*as va from"fs";var Qn=class{name="";version="";storePath="";dependencyPath="";path=""};var F={HVIGOR_CACHE:".hvigor",DEPENDENCY:"dependencyMap",JSON5:".json5",KEY_DEPENDENCY:"dependencies",KEY_DYNAMIC_DEPENDENCY:"dynamicDependencies",KEY_DEV_DEPENDENCY:"devDependencies",OH_MODULES_PATH:"oh_modules",OHPM_PATH:".ohpm",LOCK_JSON5_FILE:"lock.json5",OH_PACKAGE_JSON5:xe.OH_PACKAGE_JSON5},mo=`${F.HVIGOR_CACHE}/${F.DEPENDENCY}`,dn=`${F.DEPENDENCY}${F.JSON5}`,bz=xe.SYNC_OUTPUT_PATH;var fo=class n{dependencyPath;modulePath;projectPath;static FILE_DEPENDENCY_PREFIX="file:";static PARAMETER_PREFIX="@param:";fileSpecPattern;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;static PACKAGE_JSON_PARSER_MAP=new Map;dependencies=[];devDependencies=[];dynamicDependencies=[];static getInstance(e,t,r){let i=this.PACKAGE_JSON_PARSER_MAP.get(e);return i||(i=new n(e,t,r),this.PACKAGE_JSON_PARSER_MAP.set(e,i)),i}constructor(e,t,r){this.dependencyPath=e,this.modulePath=t,this.projectPath=r,this.fileSpecPattern=n.isWindows()?/^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/:/^(?:[.]|~[/]|[/]|[a-zA-Z]:)/}static isWindows(){return process.platform==="win32"}parseDependency(e){let t=rr.join(this.dependencyPath,F.OH_PACKAGE_JSON5),r=Ze(t);r&&(this.dependencies=this.getDependencyList(r,F.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(r,F.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(r,F.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let r=[];if(!T(e))return r;let i=e[t];if(!T(i))return r;for(let[o,s]of Object.entries(i)){if(typeof s!="string"){u.error(`${o} package dependency value is not String ${t}`);continue}let a=new Qn;a.name=o;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(n.PARAMETER_PREFIX)||this.parseDependencyPath(o,c,a,!1),r.push(a)}return r}parseDependencyPath(e,t,r,i){if(!(!e||!t))try{let o=rr.normalize(rr.join(this.modulePath,F.OH_MODULES_PATH,e));if(!(t.startsWith(n.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){r.dependencyPath=o;return}if(r.path=t,this.fileNameForOhpm.test(t)){r.dependencyPath=o;return}let s=t;if(t.startsWith(n.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(n.FILE_DEPENDENCY_PREFIX.length)),rr.isAbsolute(s)){r.dependencyPath=o;return}i||(o=rr.resolve(this.modulePath,s)),va.existsSync(o)&&va.statSync(o).isDirectory()&&(r.dependencyPath=o)}catch(o){u.error("parser dependency path is invalid",o)}}};import*as un from"fs";import*as Dr from"path";import aD from"json5";var wa=class n{projectPath;static FILE_DEPENDENCY_PREFIX="file:";static MAX_LOCK_FILE_SIZE=20*1024*1024;static MAX_KEYS_PER_OBJECT=5e4;static MAX_JSON_DEPTH=50;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[];storePathMap=new Map;lockFileCache=null;lockFileParsed=!1;constructor(e=""){this.projectPath=e}parseDependencies(e){if(!this.ensureLockFileParsed())return!1;let t=this.lockFileCache;return this.extractDependencies(t.modules,t.storePathMap,e),!0}ensureLockFileParsed(){if(this.lockFileParsed)return this.lockFileCache!==null;this.lockFileParsed=!0;let e=this.getLockFilePath(),t=this.readLockFile(e);if(!t)return!1;let r=this.validateLockFile(t);return r.valid?(this.lockFileCache={modules:r.modules,storePathMap:this.parseStorePathMap(r.packages)},!0):!1}getLockFilePath(){return Dr.join(this.projectPath,F.OH_MODULES_PATH,F.OHPM_PATH,F.LOCK_JSON5_FILE)}static checkObjectDepth(e,t,r=0){if(r>t)return!1;if(typeof e!="object"||e===null)return!0;if(Array.isArray(e)){for(let i of e)if(!n.checkObjectDepth(i,t,r+1))return!1;return!0}for(let i in e)if(Object.prototype.hasOwnProperty.call(e,i)&&!n.checkObjectDepth(e[i],t,r+1))return!1;return!0}readLockFile(e){if(!un.existsSync(e))return u.error("lock file does not exist"),this.clearDependencies(),null;try{let t=un.statSync(e);if(t.size>n.MAX_LOCK_FILE_SIZE)return u.error(`lock file is too large (${t.size} bytes), read aborted`),this.clearDependencies(),null}catch(t){return u.error(`Failed to stat lock file: ${t instanceof Error?t.message:String(t)}`),this.clearDependencies(),null}try{let t=un.readFileSync(e,"utf8"),r=aD.parse(t);return r?n.checkObjectDepth(r,n.MAX_JSON_DEPTH)?r:(u.error("lock.json5 nesting depth exceeds limit"),this.clearDependencies(),null):(u.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return u.error(`Error parsing lock.json5: ${t instanceof Error?t.message:String(t)}`),this.clearDependencies(),null}}validateLockFile(e){if(!T(e))return u.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return u.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let r=e.packages;return r?{valid:!0,modules:t,packages:r}:(u.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,r){this.storePathMap=t,this.finalDependencies=this.getDependencyList(e,F.KEY_DEPENDENCY,r),this.finalDevDependencies=this.getDependencyList(e,F.KEY_DEV_DEPENDENCY,r),this.finalDynamicDependencies=this.getDependencyList(e,F.KEY_DYNAMIC_DEPENDENCY,r)}parseStorePathMap(e){let t=new Map;if(!T(e))return t;let r=0;for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;let o=e[i];if(!T(o)){u.error(`${i} value is not json object`);continue}if(++r>n.MAX_KEYS_PER_OBJECT){u.warn("lock.json5 packages object exceeds key limit, truncating");break}typeof o.storePath=="string"&&t.set(i,o.storePath)}return t}getDependencyList(e,t,r){if(!T(e))return[];let i=0;for(let o in e){if(!Object.prototype.hasOwnProperty.call(e,o))continue;if(++i>n.MAX_KEYS_PER_OBJECT){u.warn("lock.json5 modules object exceeds key limit, truncating");break}let s=e[o];if(T(s)){let a=typeof s.name=="string"?s.name:"";if(r==="."&&a===""||a===r)return this.getFinalDependencyList(e,t,o)}}return[]}getFinalDependencyList(e,t,r){let i=e[r];if(!T(i))return u.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!T(s))return[];let a=0;for(let c in s){if(!Object.prototype.hasOwnProperty.call(s,c))continue;if(++a>n.MAX_KEYS_PER_OBJECT){u.warn("lock.json5 dependencies object exceeds key limit, truncating");break}let l=s[c];if(!T(l))continue;let d=typeof l.specifier=="string"?l.specifier:"",g=typeof l.version=="string"?l.version:"",y=new Qn;y.name=c,y.version=g.startsWith(n.FILE_DEPENDENCY_PREFIX)?g.substring(n.FILE_DEPENDENCY_PREFIX.length):g,this.parseDependencyPath(y,r,c,d,g);let I=`${c}@${g}`;this.storePathMap.has(I)&&(y.storePath=this.storePathMap.get(I)||""),o.push(y)}return o}parseDependencyPath(e,t,r,i,o){let s=Dr.resolve(this.projectPath,Dr.join(t,F.OH_MODULES_PATH,r));try{let a=o.startsWith(n.FILE_DEPENDENCY_PREFIX)?o.substring(n.FILE_DEPENDENCY_PREFIX.length):o,c=Dr.isAbsolute(a)?a:Dr.resolve(this.projectPath,a);un.existsSync(c)?(e.path=i,e.dependencyPath=this.fileNameForOhpm.test(o)?s:c):e.dependencyPath=s}catch(a){u.error("Invalid dependency path in lock.json5, msg:",a instanceof Error?a.message:String(a))}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};function ny(n){return T(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var pn=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new Ht(this.projectPath)}moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=_e.join(t,mo),i=_e.join(r,dn);if(!ei.existsSync(r)||!ei.existsSync(i)){let c="Dependency map or JSON not found";return u.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let o=new Zn(this.projectPath,".",this.projectPath);this.parseProjectDependencies(r,o),this.parseLockJson(o);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let c="No modules found in build-profile.json5";return u.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:c}}let a=Date.now();for(let c=0;c<s.length;c++){let l=s[c];if(ny(l)){try{E.assertModuleName(l.name)}catch{u.warn(`[Parser] Skipping module with invalid name: ${l.name}`);continue}this.parseSingleModule(l,r,o,e),(c+1)%100===0&&u.info(`[Parser] getAllDependencyMap progress: ${c+1}/${s.length} (${Date.now()-a}ms)`)}}return u.info(`[Parser] getAllDependencyMap parsed ${e.length} modules in ${Date.now()-a}ms`),{status:"OK"}}getDependenciesOnly(e){let t=[],r=this.projectPath,i=_e.join(r,mo),o=_e.join(i,dn);if(!ei.existsSync(i)||!ei.existsSync(o))return u.warn("[Parser] Dependency map or JSON not found."),t;let s=e&&e.length>0?new Set(e.map(l=>l.trim()).filter(Boolean)):null,a=new Zn(this.projectPath,".",this.projectPath);this.parseProjectDependencies(i,a),this.parseLockJson(a);let c=this.moduleInfoParse.getAllModuleInfo();if(c.length===0)return u.warn("[Parser] getAllDependencyMap failed: No modules found in build-profile.json5."),t;for(let l of c){if(!ny(l))continue;let d=l.name;try{E.assertModuleName(d)}catch{u.warn(`[Parser] Skipping module with invalid name: ${d}`);continue}if(s&&!s.has(d))continue;let g=_e.resolve(this.projectPath,l.srcPath),y=_e.join(i,d),I=de(g),le=this.buildModuleDependencies(d,I,y,a);le.moduleName=d,t.push(le)}return t}parseSingleModule(e,t,r,i){let o=e.name,s=_e.resolve(this.projectPath,e.srcPath),a=_e.join(t,o),c=de(s),l=new Kn(c),d=this.buildModuleDependencies(o,c,a,r);this.parseModuleJson5(c,l);let g=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=o,l.moduleType=o,l.packageName=o,l.moduleDependencies=d,l.moduleJsonParam=new Xn(g),i.push(l)}buildModuleDependencies(e,t,r,i){let o=new Zn(this.projectPath,e,t);fo.getInstance(r,t,this.projectPath).parseDependency(o),this.parseLockJson(o),o.finalDependencies.push(...i.finalDependencies),o.finalDevDependencies.push(...i.finalDevDependencies),o.finalDynamicDependencies.push(...i.finalDynamicDependencies),o.finalDependencies.push(...o.finalDevDependencies);let a=new ya;return a.modulePath=t,this.toModuleDependencies(o,a),a}toModuleDependencies(e,t){let r={},i={};for(let o of e.finalDependencies)r[o.name]=new ln(o);for(let o of e.finalDynamicDependencies)i[o.name]=new ln(o);t.dependencies=r,t.dynamicDependencies=i}parseProjectDependencies(e,t){let r=_e.join(e,F.OH_PACKAGE_JSON5);if(!ei.existsSync(r))return;fo.getInstance(e,this.projectPath,this.projectPath).parseDependency(t)}parseLockJson(e){let t=this.getLockJson5Parser();t.parseDependencies(e.moduleName)?(e.finalDependencies=t.finalDependencies,e.finalDevDependencies=t.finalDevDependencies,e.finalDynamicDependencies=t.finalDynamicDependencies):(e.finalDependencies=e.dependencies,e.finalDevDependencies=e.devDependencies,e.finalDynamicDependencies=e.dynamicDependencies)}getLockJson5Parser(){return this.lockJson5Parser||(this.lockJson5Parser=new wa(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=_e.join(e,"src","main","module.json5"),i=Ze(r);if(!T(i)||!T(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(T(e)&&Array.isArray(e.requestPermissions))for(let r of e.requestPermissions)T(r)&&typeof r.name=="string"&&t.push(r.name);return t}parseMainPages(e){let t=_e.join(e,"src","main","resources","base","profile","main_pages.json"),r=Ze(t);return!T(r)||!Array.isArray(r.src)?[]:r.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=this.getSdkPkg();if(!(!T(t)||!T(t.data))){if(typeof t.data.apiVersion=="string"){let r=parseInt(t.data.apiVersion,10);!Number.isNaN(r)&&r>=26&&typeof t.data.platformVersion=="string"?e.compileSdkLevel=t.data.platformVersion:e.compileSdkLevel=t.data.apiVersion}typeof t.data.releaseType=="string"&&(e.compileSdkType=t.data.releaseType),typeof t.data.version=="string"&&(e.compileSdkVersion=t.data.version)}}getSdkPkg(){if(this.sdkPkgCache===void 0){let e=_e.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=Ze(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!T(t)||!T(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let r=t.app.products[0];if(!T(r)||typeof r.compatibleSdkVersion!="string")return;let[i,o]=this.parseBySplit(r.compatibleSdkVersion);e.compatibleSdkVersion=i,e.compatibleSdkLevel=o}getBuildProfile(){if(this.buildProfileCache===void 0){let e=_e.join(this.projectPath,"build-profile.json5");this.buildProfileCache=Ze(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,e];let r=e.substring(0,t),i=e.substring(t+1,e.length-1);return[r,i]}parseDeviceTypes(e){return!T(e)||!Array.isArray(e.deviceTypes)?[]:e.deviceTypes.filter(t=>typeof t=="string").map(t=>this.getDeviceType(t))}getDeviceType(e){return{liteWearable:1,wearable:2,tv:3,car:4,phone:5,default:5,smartVision:6,tablet:7,router:8,pc:9,"2in1":10}[e]||0}};var Sa=class{constructor(e=[]){this.valueSet=e}};var ti=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var iy=(A=>(A[A.File=1]="File",A[A.Module=2]="Module",A[A.Namespace=3]="Namespace",A[A.Package=4]="Package",A[A.Class=5]="Class",A[A.Method=6]="Method",A[A.Property=7]="Property",A[A.Field=8]="Field",A[A.Constructor=9]="Constructor",A[A.Enum=10]="Enum",A[A.Interface=11]="Interface",A[A.Function=12]="Function",A[A.Variable=13]="Variable",A[A.Constant=14]="Constant",A[A.String=15]="String",A[A.Number=16]="Number",A[A.Boolean=17]="Boolean",A[A.Array=18]="Array",A[A.Object=19]="Object",A[A.Key=20]="Key",A[A.Null=21]="Null",A[A.EnumMember=22]="EnumMember",A[A.Struct=23]="Struct",A[A.Event=24]="Event",A[A.Operator=25]="Operator",A[A.TypeParameter=26]="TypeParameter",A))(iy||{}),oy=()=>Object.values(iy).filter(n=>typeof n=="number");var ba=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Ea=class{applyEdit=!0;workspaceEdit=new ba;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new Sa(oy());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new ti;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Pa=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Ca=class{constructor(e=[]){this.valueSet=e}};var ka=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var sy=(R=>(R[R.Text=1]="Text",R[R.Method=2]="Method",R[R.Function=3]="Function",R[R.Constructor=4]="Constructor",R[R.Field=5]="Field",R[R.Variable=6]="Variable",R[R.Class=7]="Class",R[R.Interface=8]="Interface",R[R.Module=9]="Module",R[R.Property=10]="Property",R[R.Unit=11]="Unit",R[R.Value=12]="Value",R[R.Enum=13]="Enum",R[R.Keyword=14]="Keyword",R[R.Snippet=15]="Snippet",R[R.Color=16]="Color",R[R.File=17]="File",R[R.Reference=18]="Reference",R[R.Folder=19]="Folder",R[R.EnumMember=20]="EnumMember",R[R.Constant=21]="Constant",R[R.Struct=22]="Struct",R[R.Event=23]="Event",R[R.Operator=24]="Operator",R[R.TypeParameter=25]="TypeParameter",R))(sy||{}),ay=()=>Object.values(sy).filter(n=>typeof n=="number");var Ia=class{completionItemKind=new Ca(ay());completionItem=new ka;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var Aa=class{synchronization=new Pa;completion=new Ia;hover={contentFormat:{},dynamicRegistration:{}};signatureHelp={signatureInformation:{},contextSupport:{},dynamicRegistration:{}};references={dynamicRegistration:{}};documentHighlight={dynamicRegistration:!0};documentSymbol=null;formatting={dynamicRegistration:{}};rangeFormatting={dynamicRegistration:{}};onTypeFormatting={dynamicRegistration:{}};declaration={};definition={linkSupport:{},dynamicRegistration:{}};codeLens=null;documentLink={tooltipSupport:{},dynamicRegistration:{}};colorProvider=null;rename={prepareSupport:!0,prepareSupportDefaultBehavior:null,honorsChangeAnnotations:null,dynamicRegistrationSupport:null};publishDiagnostics=null;foldingRage=null;typeHierarchy=null;callHierarchy={dynamicRegistration:{}};selectionRange=null;semanticTokens=new ti;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var Da=class{workspace=new Ea;textDocument=new Aa;notebookDocument=null;window=null;general=null;experimental=null};var Ra=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}};var Ta=class{constructor(e,t,r,i,o,s=!0,a,c=!1){this.sdkPath=e;this.rootUri=r;this.nodeMaxOldSpaceSize=o;this.useStandardProtocol=s;this.nodePath=a;this.useSocket=c;this.serverPath=wn(t,this.useStandardProtocol),this.logPath=bp(),this.indexLogPath=i||this.logPath,u.debug(`[LspServerProxy] arktsLangServer=${t}`),u.debug(`[LspServerProxy] useStandardProtocol=${this.useStandardProtocol}, useSocket=${this.useSocket}`),u.debug(`[LspServerProxy] serverPath=${this.serverPath}`);let l={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath,projectPath:this.rootUri,useSocket:this.useSocket,nodePath:this.nodePath};this.messageHandle=this.useStandardProtocol?new aa(l):new la(l),this.messageHandle.setBroadcastToClients(d=>this.onLspMessage(d))}messageHandle;get stdHandle(){return this.messageHandle}get legacyHandle(){return this.messageHandle}get lspPid(){return this.messageHandle.lspPid}onAsyncOpenFile(e){this.legacyHandle.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.legacyHandle.closeFile(e,t)}serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}async start(e,t){let r=!1;try{u.debug(`serverPath: ${this.serverPath}`),u.debug(`rootUri: ${this.rootUri}`),u.debug(`sdkPath: ${this.sdkPath}`),u.debug(`logPath: ${this.logPath}`);let i=vt(this.rootUri),o=new ha(i,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new pn(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),o.modules=s;let l=rs(s.length,this.nodeMaxOldSpaceSize);await this.messageHandle.start(l),this.currentParams=new Ra(i,o,new Da),this.useStandardProtocol?await this.startStandardProtocol(this.currentParams):await this.startLegacy(this.currentParams,e),r=!0}catch(i){this.lastStartErrorMessage=i instanceof Error?i.message:String(i),u.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(r)}async startStandardProtocol(e){let t=this.messageHandle,r=()=>t.broadcastToClients({jsonrpc:x,method:v.ARKTS_INDEXING_PROGRESS,params:{}});this.useSocket?(u.info("[LSP] socket mode: waiting for initialize response + aceProject/onModuleInitFinish"),await t.sendInitializeAndWaitForNotification(e,ts.MODULE_INIT_FINISH,Xe,()=>{u.info("[LSP] initialize response received"),r(),t.sendInitialized()},r),u.info("[LSP] initialize response + onModuleInitFinish received, initialization complete")):(await t.sendInitializeResettable(e,Xe),u.info("[LSP] initialize response received"),r(),t.sendInitialized())}async startLegacy(e,t){let r=this.messageHandle;r.sendInitialize(e,1),r.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:x,method:v.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((i,o)=>{r.onIndexingProgressUpdate(o),r.onInitializationCompleted(i)},"LSP initialization",Xe),r.sendInitialized(t)}withResettableTimeout(e,t,r){return new Promise((i,o)=>{let s,a=()=>{s=setTimeout(()=>{o(new Error(`${t} timeout after ${r}ms`))},r)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),i()},c)})}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){u.debug(`[LSP] registerDiagnosticCallback uri='${e}', useStandardProtocol=${this.useStandardProtocol}`),this.messageHandle.registerRequestCallback(e,(t,r)=>{let i=T(r)?r:{};u.debug(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let o={jsonrpc:x,method:t,params:{uri:typeof i.uri=="string"?i.uri:e,diagnostics:Array.isArray(i.diagnostics)?i.diagnostics:[],...typeof i.errorMessage=="string"?{errorMessage:i.errorMessage}:{}}};this.onLspMessage(o)})}async hover(e){let t=e.textDocument.uri;return this.registerDiagnosticCallback(t),this.stdHandle.sendLspRequest(v.HOVER,e)}async definition(e){return this.stdHandle.sendLspRequest(v.DEFINITION,e)}async references(e){return this.stdHandle.sendLspRequest(v.REFERENCES,e)}async completion(e){return this.stdHandle.sendLspRequest(v.COMPLETION,e)}async documentSymbol(e){return this.stdHandle.sendLspRequest(v.DOCUMENT_SYMBOL,e)}async diagnostic(e){return this.stdHandle.sendLspRequest(v.DIAGNOSTIC,e,120*1e3)}async sendFeatureRequest(e,t){return this.stdHandle.sendLspRequest(e,t)}reloadDependenciesOnly(e){let t=e?.fullReload??!1,r=new pn(this.rootUri,this.sdkPath),i=this.getModuleModelsByName();if(t){u.info("[LspServerProxy] Project-level oh-package changed, parsing all modules' dependencies");let l=r.getDependenciesOnly();this.markDependencyTypesIncremental(l);let d=this.mergeDepsOnlyIntoModuleList(l,i);return this.applyModuleModelsUpdate(d),this.sendDidChangeConfiguration({moduleSet:d}),u.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${d.length}`),this.lastDepsOnlyForDiff=l,l}let o=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(o.length===0&&s.size===0)return u.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];u.info(`[LspServerProxy] Module-level deps changed, parsing: [${o.join(", ")}]`);let a=r.getDependenciesOnly(o);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),this.sendDidChangeConfiguration({moduleSet:c}),u.info(`[LspServerProxy] Dependencies only (incremental) reloaded, count: ${c.length}`),this.lastDepsOnlyForDiff=a,a}sendDidChangeConfiguration(e){this.stdHandle.sendDidChangeConfiguration(e)}getModuleModelsByName(){return new Map(this.currentModuleModels.map(e=>[e.moduleName??"",e]))}markDependencyTypesIncremental(e){let t=this.getModuleModelsByName(),r=new Map(this.lastDepsOnlyForDiff.map(i=>[i.moduleName??"",i]));for(let i of e){let o=i.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(o,t,r),c=i.dependencies??{},l=i.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(d,g)=>{(i.dependencies??={})[d]=this.makeDeleteEntry(d,g)}),this.markAddAndDeleteInDeps(a,l,(d,g)=>{(i.dynamicDependencies??={})[d]=this.makeDeleteEntry(d,g)})}}getOldDepsForModule(e,t,r){let i=t.get(e),o=i?.moduleDependencies?.dependencies??{},s=i?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(o).length===0&&Object.keys(s).length===0){let a=r.get(e);a&&(o=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:o,oldDynamic:s}}markAddAndDeleteInDeps(e,t,r){for(let i of Object.keys(t))i in e||(t[i].type="add");for(let i of Object.keys(e))i in t||r(i,e[i])}makeDeleteEntry(e,t){return new ln({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Kn(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new Xn([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let r=[];for(let i of e){let o=i.moduleName??"",s=t.get(o);s?(s.modulePath=i.modulePath,s.moduleDependencies=i):s=this.createMinimalModelFromDepsItem(i),r.push(s)}return r}mergeIncrementalDeps(e,t,r){let i=new Map(r.map(s=>[s.moduleName??"",s])),o=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=i.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,i.delete(a)),o.push(s)}for(let[,s]of i)o.push(this.createMinimalModelFromDepsItem(s));return o}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,r=kn(yd.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=kn(yd.join(t,"default/openharmony/ets/api")),o=kn(yd.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=i,s.hosSdkPath=o}sendRequest(e){switch(e.method){case v.HOVER:this.stdHandle.sendLspRequest(v.HOVER,e.params).then(t=>this.onLspMessage({jsonrpc:x,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:x,id:e.id,error:{code:-32603,message:t.message}}));break;case v.DEFINITION:this.stdHandle.sendLspRequest(v.DEFINITION,e.params).then(t=>this.onLspMessage({jsonrpc:x,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:x,id:e.id,error:{code:-32603,message:t.message}}));break;case v.REFERENCES:this.stdHandle.sendLspRequest(v.REFERENCES,e.params).then(t=>this.onLspMessage({jsonrpc:x,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:x,id:e.id,error:{code:-32603,message:t.message}}));break;default:u.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!Yg(e)){u.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case v.DID_OPEN:this.handleDidOpenNotification(e);break;case v.DID_CHANGE:this.handleDidChangeNotification(e);break;case v.DID_CLOSE:this.handleDidCloseNotification(e);break;case v.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;case v.DID_CREATE_FILES:this.handleDidCreateFiles(e);break;case v.DID_DELETE_FILES:this.handleDidDeleteFiles(e);break;default:u.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){u.error("Invalid textDocument/didOpen params");return}this.stdHandle.sendDidOpen(t)}handleDidChangeNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){u.error("Invalid textDocument/didChange params");return}this.stdHandle.sendDidChange(t)}handleDidCloseNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){u.error("Invalid textDocument/didClose params");return}this.stdHandle.closeFile(t)}handleDidChangeWatchedFiles(e){let t=e.params;!t||!Array.isArray(t.changes)||this.messageHandle.onDidChangeWatchedFiles(t.changes)}handleDidCreateFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(v.DID_CREATE_FILES,t)}handleDidDeleteFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(v.DID_DELETE_FILES,t)}async dispose(){await this.messageHandle.stop()}};import*as nr from"fs";import*as Ge from"path";import{createHash as lD}from"crypto";import{EventEmitter as dD}from"events";var xa=class extends dD{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r}watchers=new Map;debounceTimers=new Map;contentHashes=new Map;buildProfileWatcher=null;lastModulesSnapshot="";lastModules=[];debounceMs;start(){let t=this.parseModulesFromBuildProfile();this.lastModules=t,this.lastModulesSnapshot=this.computeModulesSnapshot(t),this.refreshWatchTargets(),this.watchBuildProfile()}refreshWatchTargets(){let t=new Set(this.collectWatchTargets()),r=new Set(this.watchers.keys());for(let i of t)r.has(i)||this.watchFile(i);for(let i of r)t.has(i)||(this.unwatchFile(i),u.info(`[ConfigFileWatcher] Stopped watching: ${i}`));u.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!nr.existsSync(t)){u.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=nr.watch(t,r=>{r==="change"&&this.onBuildProfileChanged()}),this.buildProfileWatcher.on("error",r=>{u.error(`[ConfigFileWatcher] build-profile.json5 watch error: ${r.message}`)}),u.info(`[ConfigFileWatcher] Watching module registry: ${t}`)}catch(r){u.error(`[ConfigFileWatcher] Failed to watch build-profile.json5: ${r instanceof Error?r.message:String(r)}`)}}emitModuleAddedEvents(t,r){for(let i of t){let o=Ge.resolve(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:o,relativePath:i.srcPath,timestamp:r,moduleName:i.name})}}emitModuleRemovedEvents(t,r){for(let i of t){let o=Ge.resolve(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:o,relativePath:i.srcPath,timestamp:r,removedModuleName:i.name})}}emitModuleRenamedEvents(t,r){for(let i of t){let o=Ge.resolve(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:o,relativePath:i.after.srcPath,timestamp:r,moduleName:i.after.name,removedModuleName:i.before.name})}}emitModuleMovedEvents(t,r){for(let i of t){let o=Ge.resolve(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:o,relativePath:i.after.srcPath,timestamp:r,moduleName:i.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let r=Date.now();this.emitModuleAddedEvents(t.added,r),this.emitModuleRemovedEvents(t.removed,r),this.emitModuleRenamedEvents(t.renamed,r),this.emitModuleMovedEvents(t.moved,r)}onBuildProfileChanged(){let t="__build_profile__",r=this.debounceTimers.get(t);r&&clearTimeout(r);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(o);if(s===this.lastModulesSnapshot){u.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,o);this.lastModules=o,this.lastModulesSnapshot=s,u.info(`[ConfigFileWatcher] build-profile.json5 modules changed, added=${a.added.length}, removed=${a.removed.length}, renamed=${a.renamed.length}, moved=${a.moved.length}`),this.processBuildProfileDiff(a)},this.debounceMs);this.debounceTimers.set(t,i)}computeModulesSnapshot(t){return t.map(i=>`${i.name}::${i.srcPath}`).sort().join("|")}diffModules(t,r){let i=this.buildModuleMatchState(r),o={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,i),this.matchRenamedModules(t,i,o),this.matchMovedModules(t,i,o),this.collectRemovedModules(t,i,o),this.collectAddedModules(r,i,o),o}buildModuleMatchState(t){let r=new Map,i=new Map;for(let o of t)r.set(o.srcPath,o),i.set(o.name,o);return{matchedOld:new Set,matchedNew:new Set,newBySrc:r,newByName:i}}matchExactModules(t,r){for(let i of t){let o=r.newBySrc.get(i.srcPath);o&&o.name===i.name&&(r.matchedOld.add(i),r.matchedNew.add(o))}}matchRenamedModules(t,r,i){for(let o of t){if(r.matchedOld.has(o))continue;let s=r.newBySrc.get(o.srcPath);s&&!r.matchedNew.has(s)&&s.name!==o.name&&(i.renamed.push({before:o,after:s}),r.matchedOld.add(o),r.matchedNew.add(s))}}matchMovedModules(t,r,i){for(let o of t){if(r.matchedOld.has(o))continue;let s=r.newByName.get(o.name);s&&!r.matchedNew.has(s)&&s.srcPath!==o.srcPath&&(i.moved.push({before:o,after:s}),r.matchedOld.add(o),r.matchedNew.add(s))}}collectRemovedModules(t,r,i){for(let o of t)r.matchedOld.has(o)||i.removed.push(o)}collectAddedModules(t,r,i){for(let o of t)r.matchedNew.has(o)||i.added.push(o)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let r=Ze(t);if(typeof r!="object"||r===null)return[];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"}):[]}catch(r){return u.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${r instanceof Error?r.message:String(r)}`),[]}}collectWatchTargets(){let t=[],r=Ge.join(this.projectRoot,F.OH_PACKAGE_JSON5);nr.existsSync(r)&&t.push(r);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=Ge.resolve(this.projectRoot,o.srcPath),a=Ge.join(s,F.OH_PACKAGE_JSON5);nr.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return Ge.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=nr.readFileSync(t,"utf-8");return lD("sha256").update(r).digest("hex")}catch{return null}}watchFile(t){if(!this.watchers.has(t))try{let r=this.computeFileHash(t);r&&this.contentHashes.set(t,r);let i=nr.watch(t,o=>{o==="change"&&this.onFileChanged(t)});i.on("error",o=>{u.error(`[ConfigFileWatcher] Watch error for ${t}: ${o.message}`)}),this.watchers.set(t,i)}catch(r){u.error(`[ConfigFileWatcher] Failed to watch ${t}: ${r instanceof Error?r.message:String(r)}`)}}unwatchFile(t){let r=this.watchers.get(t);r&&(r.close(),this.watchers.delete(t)),this.contentHashes.delete(t);let i=this.debounceTimers.get(t);i&&(clearTimeout(i),this.debounceTimers.delete(t))}onFileChanged(t){let r=this.debounceTimers.get(t);r&&clearTimeout(r);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.computeFileHash(t);if(!o){u.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===o){u.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,o),u.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:Ge.basename(t),relativePath:Ge.relative(this.projectRoot,t),timestamp:Date.now()};this.emit("configChanged",a)},this.debounceMs);this.debounceTimers.set(t,i)}stop(){for(let[,t]of this.watchers)t.close();this.watchers.clear(),this.buildProfileWatcher&&(this.buildProfileWatcher.close(),this.buildProfileWatcher=null);for(let t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.contentHashes.clear(),u.info("[ConfigFileWatcher] All watchers stopped")}};import*as Rr from"fs";import*as Et from"path";import{createHash as uD}from"crypto";import{EventEmitter as pD}from"events";var La=class extends pD{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=Et.join(t,mo)}dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!Rr.existsSync(this.depMapDir)){u.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=Rr.watch(this.depMapDir,{recursive:!0},(t,r)=>this.onDirEvent(t,r)),this.dirWatcher.on("error",t=>{u.error(`[DependencyMapWatcher] Directory watch error for ${this.depMapDir}: ${t.message}`)})}catch(t){u.error(`[DependencyMapWatcher] Failed to watch directory ${this.depMapDir}: ${t instanceof Error?t.message:String(t)}`);return}this.pollInterval=setInterval(()=>this.scanAllCacheFiles(),2500),u.info(`[DependencyMapWatcher] Started, watching directory (recursive): ${this.depMapDir}, modules: [${this.lastModules.map(t=>t.name).join(", ")}]`)}canonicalPath(t){return de(Et.resolve(t))}onDirEvent(t,r){if(!r||typeof r!="string")return;let i=r.replace(/\\/g,"/"),o;if(i===F.OH_PACKAGE_JSON5)o="root-oh-package";else if(i===dn)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=Et.join(this.depMapDir,r);Rr.existsSync(s)&&this.scheduleDebouncedFullScan()}stop(){this.dirWatcher&&(this.dirWatcher.close(),this.dirWatcher=null),this.fullScanTimer&&(clearTimeout(this.fullScanTimer),this.fullScanTimer=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.coalesceTimer&&(clearTimeout(this.coalesceTimer),this.coalesceTimer=null),this.pendingTags=[],this.pendingRenames=[],this.contentHashes.clear(),this.initialScanDone=!1,u.info("[DependencyMapWatcher] All watchers stopped")}scheduleDebouncedFullScan(){this.fullScanTimer&&clearTimeout(this.fullScanTimer),this.fullScanTimer=setTimeout(()=>{this.fullScanTimer=null,this.scanAllCacheFiles()},this.debounceMs)}scanAllCacheFiles(){let t=Et.join(this.depMapDir,F.OH_PACKAGE_JSON5),r=Et.join(this.depMapDir,dn),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...i.map(s=>({path:(E.assertModuleName(s.name),Et.join(this.depMapDir,s.name,F.OH_PACKAGE_JSON5)),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!Rr.existsSync(s))continue;let c=this.canonicalPath(s),l=this.computeFileHash(s);if(!l)continue;let d=this.contentHashes.get(c);if(!this.initialScanDone){this.contentHashes.set(c,l);continue}d!==l&&(this.contentHashes.set(c,l),u.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=Et.join(this.depMapDir,dn);try{let r=Ze(t);if(typeof r!="object"||r===null)return[];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"}):[]}catch(r){return u.warn(`[DependencyMapWatcher] Failed to parse dependencyMap.json5: ${r instanceof Error?r.message:String(r)}`),[]}}scheduleCoalescedReload(t){this.pendingTags.push(t),t==="dep-map-json"&&this.applyDepMapJsonDiff(),this.coalesceTimer&&clearTimeout(this.coalesceTimer),this.coalesceTimer=setTimeout(()=>{this.coalesceTimer=null,this.flushPendingReload()},this.coalesceMs)}collectPendingState(){let t=this.pendingTags,r=this.pendingRenames;return this.pendingTags=[],this.pendingRenames=[],{tags:t,renameEntries:r}}processTagsIntoSets(t,r,i,o){for(let s of t)s.startsWith("module:")?(i.add(s.substring(7)),r.add("moduleDepsChanged")):s.startsWith("dep-added:")?(i.add(s.substring(10)),r.add("moduleAdded")):s.startsWith("dep-removed:")&&(o.add(s.substring(12)),r.add("moduleRemoved"))}processRenameEntries(t,r,i,o,s){for(let a of t)s.push(a.info),i.add(a.info.newName),o.add(a.info.oldName),r.add(a.kind)}buildAddedNamesSet(t,r){let i=new Set;for(let o of t)o.startsWith("dep-added:")&&i.add(o.substring(10));for(let o of r)i.add(o.info.newName);return i}emitIncrementalReload(t,r,i,o,s){u.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...r].join(",")}], removed=[${[...i].join(",")}], added=[${[...o].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...r],removedModuleNames:[...i],addedModuleNames:[...o],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:r}=this.collectPendingState();if(t.length===0&&r.length===0)return;if(u.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${r.length}`),t.includes("root-oh-package")){u.info("[DependencyMapWatcher] Root oh-package.json5 in batch \u2192 full reload"),this.emit("reload",{fullReload:!0,kinds:["projectDepsChanged"]});return}let i=new Set,o=new Set,s=new Set,a=[];this.processTagsIntoSets(t,i,o,s),this.processRenameEntries(r,i,o,s,a);for(let l of o)s.delete(l);if(o.size===0&&s.size===0&&a.length===0){u.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,r);this.emitIncrementalReload(i,o,s,c,a)}normalizeSrcPath(t){return de(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let r=new Map(t.map(o=>[o.name,o])),i=new Map(t.map(o=>[this.normalizeSrcPath(o.srcPath),o]));return{byName:r,bySrcPath:i}}detectModuleRenames(t,r,i,o){for(let[s,a]of t){let c=r.get(s);if(!c||c.name===a.name)continue;this.pendingRenames.push({kind:"moduleRenamed",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleRenamed"}}),i.add(a.name),o.add(c.name);let l=(E.assertModuleName(a.name),Et.join(this.depMapDir,a.name,F.OH_PACKAGE_JSON5));this.contentHashes.delete(this.canonicalPath(l)),u.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,r,i,o){for(let[s,a]of t){if(i.has(s))continue;let c=r.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),i.add(s),o.add(s),u.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,r,i){for(let[o]of t)i.has(o)||r.has(o)||(this.pendingTags.push(`dep-added:${o}`),i.add(o))}detectRemovedModules(t,r,i){for(let[o]of t)if(!i.has(o)&&!r.has(o)){this.pendingTags.push(`dep-removed:${o}`),i.add(o);let s=(E.assertModuleName(o),Et.join(this.depMapDir,o,F.OH_PACKAGE_JSON5));this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(i=>i.startsWith("dep-")),r=this.pendingRenames.map(i=>`${i.kind}(${i.info.oldName}\u2192${i.info.newName})`);u.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${r.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:r,bySrcPath:i}=this.buildModuleLookupMaps(this.lastModules),{byName:o,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(i,s,a,c),this.detectModuleMoves(r,o,a,c),this.detectAddedModules(o,r,c),this.detectRemovedModules(r,o,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let r=Rr.readFileSync(t,"utf-8");return uD("sha256").update(r).digest("hex")}catch{return null}}};import*as _t from"fs";import*as Na from"path";import{EventEmitter as mD}from"events";var vd={Created:1,Changed:2,Deleted:3},fD=new Set(["oh_modules","node_modules","build",".hvigor",".git",".idea",".cxx",".preview"]);function hD(n){let e=n.replace(/\\/g,"/");return e.endsWith("/ets")&&e.includes("/src/")}var Ma=class extends mD{projectRoot;debounceMs;pollMs;sourceDirs=[];watchers=new Map;snapshot=new Map;debounceTimer=null;pollInterval=null;initialScanDone=!1;constructor(e,t=500,r=1e4){super(),this.projectRoot=e,this.debounceMs=t,this.pollMs=r}start(){if(this.sourceDirs=this.discoverSourceDirs(),this.sourceDirs.length===0){u.warn("[SourceFileWatcher] No src/main/ets dir found, skip watching");return}this.refreshSnapshot(),this.initialScanDone=!0;for(let e of this.sourceDirs)this.addSourceDirWatcher(e);this.pollInterval=setInterval(()=>this.scanAndEmit(),this.pollMs),u.info(`[SourceFileWatcher] Started, watching ${this.sourceDirs.length} source dir(s), ${this.snapshot.size} ets file(s)`)}stop(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null);for(let[,e]of this.watchers)e.close();this.watchers.clear(),this.snapshot.clear(),this.initialScanDone=!1,u.info("[SourceFileWatcher] Stopped")}addSourceDirWatcher(e){if(!this.watchers.has(e))try{let t=_t.watch(e,{recursive:!0},(r,i)=>this.onFsEvent(i));t.on("error",r=>{u.error(`[SourceFileWatcher] watch error for ${e}: ${r.message}`)}),this.watchers.set(e,t)}catch(t){u.error(`[SourceFileWatcher] Failed to watch ${e}: ${t instanceof Error?t.message:String(t)}`)}}refreshSourceDirs(){if(!this.initialScanDone)return;let e=this.discoverSourceDirs(),t=new Set(this.sourceDirs),r=new Set(e),i=e.filter(s=>!t.has(s)),o=[...t].filter(s=>!r.has(s));if(!(i.length===0&&o.length===0)){for(let s of i)this.addSourceDirWatcher(s);for(let s of o){let a=this.watchers.get(s);a&&(a.close(),this.watchers.delete(s))}this.sourceDirs=e,this.refreshSnapshot(),u.info(`[SourceFileWatcher] Module dirs changed: +${i.length} -${o.length}, now ${this.sourceDirs.length} source dir(s)`)}}discoverSourceDirs(){let e=[];return this.collectSourceDirs(Na.resolve(this.projectRoot),e,new Set,new Set),e}collectSourceDirs(e,t,r,i){let o;try{o=_t.realpathSync(e)}catch{return}if(i.has(o))return;i.add(o);let s;try{s=_t.readdirSync(e,{withFileTypes:!0})}catch{return}for(let a of s){if(!a.isDirectory()||fD.has(a.name))continue;let c=Na.resolve(e,a.name);if(!hD(c)){this.collectSourceDirs(c,t,r,i);continue}r.has(c)||(r.add(c),t.push(c))}}onFsEvent(e){!e||typeof e!="string"||e.replace(/\\/g,"/").toLowerCase().endsWith(".ets")&&this.scheduleScan()}scheduleScan(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.scanAndEmit()},this.debounceMs)}scanAndEmit(){if(!this.initialScanDone)return;let e=this.diffScan();e.length>0&&this.emit("sourceChanged",{changes:e})}refreshSnapshot(){let e=new Map;for(let t of this.sourceDirs)this.collectEtsFiles(t,e);this.snapshot=e}diffScan(){let e=new Map;for(let r of this.sourceDirs)this.collectEtsFiles(r,e);let t=[];for(let[r,i]of e){let o=this.snapshot.get(r);o?(o.mtimeMs!==i.mtimeMs||o.size!==i.size)&&t.push({uri:gt(r),type:vd.Changed}):t.push({uri:gt(r),type:vd.Created})}for(let[r]of this.snapshot)e.has(r)||t.push({uri:gt(r),type:vd.Deleted});return this.snapshot=e,t}collectEtsFiles(e,t){this.collectEtsFilesInto(e,t,new Set)}collectEtsFilesInto(e,t,r){let i;try{i=_t.realpathSync(e)}catch{return}if(r.has(i))return;r.add(i);let o;try{o=_t.readdirSync(e,{withFileTypes:!0})}catch{return}for(let s of o){let a=Na.resolve(e,s.name);if(s.isDirectory()){this.collectEtsFilesInto(a,t,r);continue}!s.isFile()||!s.name.toLowerCase().endsWith(".ets")||this.recordSnapshot(a,t)}}recordSnapshot(e,t){let r;try{r=_t.statSync(e)}catch{return}t.set(e,{mtimeMs:r.mtimeMs,size:r.size})}};import{spawn as gD}from"child_process";var yD=["install","--all"];async function vD(n,e,t,r){return new Promise(i=>{let o=gD(n,[e,...yD],{cwd:t,env:{...process.env,DEVECO_SDK_HOME:r},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),s="",a="";o.stdout?.on("data",c=>{s+=c.toString()}),o.stderr?.on("data",c=>{a+=c.toString()}),o.on("close",c=>{let l=[s,a].filter(Boolean).join(`
|
|
1314
|
-
`);i({
|
|
1315
|
-
`);i({exitCode:-1,output:l+`
|
|
1316
|
-
`+c.message})})})}function wD(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>u.info("[ohpm] %s",e))}async function cy(n,e,t,r){try{if(!t)return u.error("node \u8DEF\u5F84\u4E0D\u5B58\u5728"),!1;if(!r)return u.error("ohpm (pm-cli.js) \u4E0D\u5B58\u5728"),!1;let{exitCode:i,output:o}=await vD(t,r,n,e);return wD(o),i===0?(u.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(u.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",i),u.error("ohpm \u8F93\u51FA: %s",o),!1)}catch(i){return u.error("ohpm \u5B89\u88C5\u5F02\u5E38",i),!1}}var ly={UNINITIALIZED:-32099,UNKNOWN:-32e3},ho=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,ly.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,ly.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var ri=class{config;lspProxy=null;configWatcher=null;depMapWatcher=null;sourceFileWatcher=null;isInitialized=!1;lastEditorOpenFiles=[];onMessage=()=>{};onConfigChanged=null;disposeOnce=null;get aceServerPid(){return this.lspProxy?.lspPid??null}constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}async start(e=[]){this.lastEditorOpenFiles=e;try{this.startConfigWatcher(),this.startLspProxy(e)}catch(t){throw u.error(`[ArktsLspManager] start() synchronous failure: ${t instanceof Error?t.message:String(t)}`),t}}sendNotification(e){if(!this.lspProxy){u.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){u.warn("[ArktsLspManager] sendRequest before LSP ready, dropped");return}this.lspProxy.sendRequest(e)}async diagnostic(e){if(!this.lspProxy)throw new Error("[ArktsLspManager] diagnostic before LSP ready");return this.lspProxy.diagnostic(e)}async sendFeatureRequest(e,t){if(!this.useStandardProtocol)throw new Error(`Language feature '${e}' is not supported on the installed DevEco Studio. The standard LSP protocol entry (plugins/openharmony/ace-server/out/standardIndex/index.js) was not found. Please upgrade DevEco Studio to version 26.0.0.610 or later to use this tool.`);if(!this.lspProxy)throw new Error("LSP not ready");return this.lspProxy.sendFeatureRequest(e,t)}get useStandardProtocol(){return this.config.useStandardProtocol}onAsyncOpenFile(e){this.lspProxy?.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.lspProxy?.closeFileLegacy(e,t)}registerDiagnosticCallback(e){this.lspProxy?.registerDiagnosticCallback(e)}static async handleSyncProject(e,t,r,i,o,s){if(u.info("[ArktsLspManager] Received arkts/syncProject"),!e||!t)return u.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let a=s?.skipHvigorSync===!0,c=await Ko(e,async()=>await cy(e,t,r??"",i??"")?a?(u.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await Ip(e,t,r??"",o??"")?(u.info("[ArktsLspManager] syncProject completed successfully"),{status:"success"}):(u.error("[ArktsLspManager] syncProject failed"),{status:"failed",reason:"hvigor sync failed"}):(u.error("[ArktsLspManager] ohpm install failed"),{status:"failed",reason:"ohpm install failed"}));return c.acquired?c.result:(u.info("[ArktsLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){try{this.configWatcher?.stop()}catch(e){u.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){u.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}try{this.sourceFileWatcher?.stop()}catch(e){u.warn(`[ArktsLspManager] sourceFileWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.sourceFileWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){u.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e){let t=new Ta(this.config.sdkPath,this.config.arktsLangServerPath,this.config.workspaceRoot,this.config.indexLogPath,this.config.nodeMaxOldSpaceSize,this.config.useStandardProtocol,this.config.nodePath,this.config.useSocket??!1);t.setOnMessage(r=>this.handleLspMessage(r)),t.start(e,r=>this.handleLspInitialized(r)),this.lspProxy=t}handleLspInitialized=e=>{if(this.isInitialized=e,e)u.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.startSourceFileWatcher(),this.onMessage({jsonrpc:x,method:v.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();u.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?ho.uninitialized(t):ho.unknown();this.onMessage({jsonrpc:x,method:v.ARKTS_INITIALIZATION_FAILED,params:r.toJsonRpcErrorParams()}),this.lspProxy=null}};handleLspMessage(e){this.onMessage(e)}maybeRetryLspAfterSuccessfulSync(){this.isInitialized||this.lspProxy!==null||(u.info("[ArktsLspManager] Retrying LSP startup after successful sync"),this.onMessage({jsonrpc:x,method:v.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new xa(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new La(this.config.workspaceRoot),this.depMapWatcher.on("reload",e=>{if(!this.lspProxy){u.warn("[ArktsLspManager] LspServerProxy not initialized, skip reload");return}let r=this.lspProxy.reloadDependenciesOnly(e).map(i=>({modulePath:i.modulePath??"",dependencies:i.dependencies??{},dynamicDependencies:i.dynamicDependencies??{}}));this.onMessage({jsonrpc:x,method:v.ARKTS_SYNC_COMPLETED,params:{success:!0,moduleSet:r}})}),this.depMapWatcher.start())}startSourceFileWatcher(){this.sourceFileWatcher||(this.sourceFileWatcher=new Ma(this.config.workspaceRoot),this.sourceFileWatcher.on("sourceChanged",e=>{if(!this.lspProxy){u.warn("[ArktsLspManager] LspServerProxy not initialized, skip didChangeWatchedFiles");return}this.sendNotification({jsonrpc:x,method:v.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:e.changes}}),u.info(`[ArktsLspManager] Notified didChangeWatchedFiles: ${e.changes.length} change(s)`)}),this.sourceFileWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){u.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),e.kind!==4&&this.sourceFileWatcher?.refreshSourceDirs(),this.onConfigChanged?.()}};var SD=10080*60*1e3,bD=7200*60*1e3,ED=120*1e3,ni=class n{manager=null;get aceServerPid(){return this.manager?.aceServerPid??null}initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;sdkPath;arktsLangServerPath;nodePath;nodeMaxOldSpaceSize;onConfigChangedCallback=null;useStandardProtocol=!0;useSocket;diagnosticWaiters=new Map;documentVersion=0;static FEATURE_METHOD_MAP={hover:v.HOVER,definition:v.DEFINITION,declaration:v.DECLARATION,references:v.REFERENCES,implementation:v.IMPLEMENTATION,completion:v.COMPLETION,signatureHelp:v.SIGNATURE_HELP,documentHighlight:v.DOCUMENT_HIGHLIGHT};constructor(e,t,r,i,o,s=!1){this.projectPath=e,this.sdkPath=t,this.arktsLangServerPath=r,this.nodeMaxOldSpaceSize=i,this.nodePath=o,this.useSocket=s}setOnConfigChanged(e){this.onConfigChangedCallback=e}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initializing=!0,this.initPromise=this.doInitialize().then(()=>{this.initialized=!0}).finally(()=>{this.initializing=!1}),await this.initPromise}}async doInitialize(){let{harmonyRoot:e,arktsLangServerPath:t,useStandardProtocol:r}=this.resolveProjectAndDeveco();this.useStandardProtocol=r;let i=we(e),{logPath:o,indexPath:s}=this.getLogAndIndexPath(i);setImmediate(()=>{Cc(s,SD,"[ArkTS-Check]"),Cc(o,bD,"[ArkTS-Check]")}),es(o);let a=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,c=Number.isNaN(a)?void 0:a;h.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${c??"undefined \u2192 dynamic formula applies"}`);let l=this.sdkPath;h.info(`[ArktsCheck] sdkPath=${l}, arktsLangServerPath=${t}, useStandardProtocol=${r}, useSocket=${this.useSocket}`),this.manager=new ri({sdkPath:l,arktsLangServerPath:t,workspaceRoot:de(i),indexLogPath:s,nodeMaxOldSpaceSize:c,useStandardProtocol:r,nodePath:this.nodePath,useSocket:this.useSocket}),this.manager.setOnMessage(d=>this.handleLspMessage(d)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((d,g)=>{this.initResolve=d,this.initReject=g,this.armInitTimer(Xe),this.manager.start([]).catch(y=>{let I=y instanceof Error?y:new Error(String(y));this.failInit(I)})})}resolveProjectAndDeveco(){let e=jt(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.arktsLangServerPath;if(!t)throw new Error("arkts-lang-server path not found");let r=Fo(t);return{harmonyRoot:e,arktsLangServerPath:t,useStandardProtocol:r}}armInitTimer(e){this.initDeadlineTimer&&clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=setTimeout(()=>{let t=this.initReject;this.clearInitHandlers(),t?.(new Error("LSP initialize timeout"))},e)}clearInitHandlers(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async checkFile(e){this.initialized||await this.initialize();let t=this.manager;if(!t)throw new Error("ArktsLspManager not initialized");let r=gt(e),i=await ft.promises.readFile(e,"utf8"),s=`deveco.apptool.${De.extname(e).replace(/^\./,"")||"plaintext"}`;return t.useStandardProtocol?this.checkFileStandard(t,r,i,s):this.checkFileLegacy(t,e,r,i,s)}async checkFileStandard(e,t,r,i){h.debug(`textDocument/didOpen uri=${t} content_len=${r.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:r,languageId:i,version:++this.documentVersion}});try{h.debug(`textDocument/diagnostic uri=${t}`);let o=await e.diagnostic({textDocument:{uri:t}});return PD(o)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:t}})}}async checkFileLegacy(e,t,r,i,o){let s=r;e.registerDiagnosticCallback(r);let a=new Promise((c,l)=>{let d=setTimeout(()=>{this.diagnosticWaiters.delete(s)&&l(new Error("Wait for diagnostics timeout"))},ED);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:d})});h.debug(`textDocument/didOpen(legacy) uri=${r} content_len=${i.length}`),e.onAsyncOpenFile({textDocument:{uri:r,text:i,languageId:o,version:i.length},editorFiles:[r],isFromEditor:!1});try{return await a}finally{e.closeFileLegacy(r,!1)}}async handleCall(e){if(!this.initialized)return this.buildNotReadyResponse();let t=[],r=[],i=this.collectValidFiles(e.files,t);return i.length===0?{content:[{type:"text",text:t.length>0?t.join(`
|
|
1317
|
-
`):"No valid .ets files"}],isError:!0}:(await this.runDiagnosticsForFiles(i,t,r),this.formatCallResult(t,r))}async handleLspFeature(e,t){if(!this.initialized)return this.buildNotReadyResponse();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`File does not exist or is not a .ets file: ${t.file}`}],isError:!0};let i=n.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};h.info(`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){let s=o instanceof Error?o.message:String(o);return h.error(`handleLspFeature ${e} failed: ${s}`),{content:[{type:"text",text:`${e} failed: ${s}`}],isError:!0}}}async handleWorkspaceSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();h.info(`handleWorkspaceSymbol: query="${e}"`);try{let t=await this.manager.sendFeatureRequest(v.WORKSPACE_SYMBOL,{query:e});return{content:[{type:"text",text:t==null?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(t,null,2)}`}]}}catch(t){let r=t instanceof Error?t.message:String(t);return h.error(`handleWorkspaceSymbol failed: ${r}`),{content:[{type:"text",text:`workspaceSymbol failed: ${r}`}],isError:!0}}}async handleWorkspaceSymbolRaw(e){if(!this.initialized)return null;try{let t=await this.manager.sendFeatureRequest(v.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return h.error(`handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a .ets file: ${e}`}],isError:!0};h.info(`handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(v.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){let i=r instanceof Error?r.message:String(r);return h.error(`handleDocumentSymbol failed: ${i}`),{content:[{type:"text",text:`documentSymbol failed: ${i}`}],isError:!0}}}async handleCallHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a .ets file: ${e.file}`}],isError:!0};h.info(`handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,async o=>{let s=await this.manager.sendFeatureRequest(v.PREPARE_CALL_HIERARCHY,{textDocument:{uri:o},position:{line:e.line,character:e.character}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],calls:[]};let c=e.direction==="incoming"?v.INCOMING_CALLS:v.OUTGOING_CALLS,l=[];for(let d of a){let g=await this.manager.sendFeatureRequest(c,{item:d});Array.isArray(g)?l.push(...g):g&&l.push(g)}return{items:a,calls:l}});return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){let i=r instanceof Error?r.message:String(r);return h.error(`handleCallHierarchy failed: ${i}`),{content:[{type:"text",text:`callHierarchy failed: ${i}`}],isError:!0}}}async withOpenFile(e,t){let r=gt(e),i=await ft.promises.readFile(e,"utf8"),s=`deveco.apptool.${De.extname(e).replace(/^\./,"")||"plaintext"}`;h.debug(`withOpenFile didOpen uri=${r} len=${i.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:r,text:i,languageId:s,version:++this.documentVersion}});try{return await t(r)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:r},isManual:!1})}}resolveSingleFile(e){let t=De.isAbsolute(e)?e:De.join(this.projectPath,e);return!ft.existsSync(t)||!ft.statSync(t).isFile()||!t.endsWith(".ets")?null:t}buildNotReadyResponse(){return{content:[{type:"text",text:this.initializing?"LSP is initializing, please retry later":this.projectPath?"LSP not initialized":"No project path configured; set the PROJECT_PATH parameter"}],isError:!0}}collectValidFiles(e,t){let r=De.resolve(this.projectPath),i=[];for(let o of e){let s=De.resolve(De.isAbsolute(o)?o:De.join(r,o));if(!ft.existsSync(s)){t.push(`File does not exist: ${o}`);continue}if(!ft.statSync(s).isFile()){t.push(`Not a regular file: ${o}`);continue}if(!s.endsWith(".ets")){t.push(`Not a .ets file: ${o}`);continue}i.push(s)}return i}async runDiagnosticsForFiles(e,t,r){for(let i of e){await ju(500);try{let o=await this.checkFile(i);r.push(CD(i,o))}catch(o){t.push(`${i} => wait for diagnostics failed: ${o.message}`)}}}formatCallResult(e,t){let r=[];e.length>0&&r.push(e.join(`
|
|
1319
|
+
`);if(r===-1)break;let o=this.buffer.slice(0,r).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!o){u.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(r+4);continue}let s=parseInt(o[1],10);if(!Number.isFinite(s)||s<0||s>lR){u.warn(`[LspClient] Invalid Content-Length: ${o[1]}, drop until next packet`),this.buffer=this.buffer.slice(r+4);continue}let a=r+4,c=a+s;if(this.buffer.length<c)break;let l=this.buffer.slice(a,c).toString("utf8"),d=this.recoverFramedJson(l);if(d&&d.rest.length>0){u.warn(`[LspClient] recovered mixed LSP frame, bodyLen=${l.length}, restLen=${d.rest.length}`),this.logSocketRecv(d.json),this.emit("message",d.json),this.buffer=Buffer.concat([Buffer.from(d.rest,"utf8"),this.buffer.slice(c)]);continue}this.logSocketRecv(l),this.emit("message",l),this.buffer=this.buffer.slice(c)}}logSocketRecv(t){this.socket&&u.debug(`[LspClient] [SOCKET RECV] ${t.slice(0,200)}`)}waitForExitOrTimeout(t){let r=this.process;return!r||r.exitCode!==null||r.signalCode!==null?Promise.resolve():new Promise(i=>{let o=!1,s=()=>{o||(o=!0,clearTimeout(c),r.off("exit",a),i())},a=()=>s();r.once("exit",a);let c=setTimeout(s,t)})}recoverFramedJson(t){let r=t.search(/\S/);if(r<0||t[r]!=="{"&&t[r]!=="[")return null;let i=0,o=!1,s=!1;for(let a=r;a<t.length;a++){let c=t[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(o=!1);continue}if(c==='"'){o=!0;continue}if(c==="{"||c==="["){i++;continue}if((c==="}"||c==="]")&&(i--,i===0)){let l=t.slice(r,a+1),d=t.slice(a+1);return{json:l,rest:d}}}return null}stop(){if(this.isClosing=!0,this.socket){this.socket.destroy(),this.socket=null,this.process=null;return}let t=this.process;if(!t)return;if(this.process=null,t.exitCode===null&&t.signalCode===null)try{t.kill()}catch{}}};var Ar=class{callbacks=new Map;pending=new Map;timeouts=new Map;registerPending(e,t,r){return new Promise((i,o)=>{let s;r>0&&(s=setTimeout(()=>{this.pending.delete(e),this.timeouts.delete(e),o(new Error(`LSP request '${t}' (id=${e}) timeout after ${r}ms`))},r),this.timeouts.set(e,s)),this.pending.set(e,{resolve:i,reject:o,method:t,timer:s})})}resolvePending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.resolve(t),this.pending.delete(e),!0):!1}rejectPending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.reject(t),this.pending.delete(e),!0):!1}register(e,t){this.callbacks.set(e,t)}emit(e,t,r){u.debug(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let i=this.callbacks.get(e);if(i)try{i(t,r)}finally{this.callbacks.delete(e)}else{let o=[...this.callbacks.keys()].map(s=>String(s));u.debug(`[RequestCallbackManager] emit: NO callback for key='${e}', registered keys=[${o.join(",")}]`)}}registerTimeout(e,t,r,i){let o=this.timeouts.get(e);o&&clearTimeout(o);let s=setTimeout(()=>{u.debug(`[RequestCallbackManager] timeout, key=${e}, method=${t}`);try{i()}finally{this.timeouts.delete(e)}},r);this.timeouts.set(e,s)}clearTimeout(e){let t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e))}deleteCallback(e){this.callbacks.delete(e)}hasCallback(e){return this.callbacks.has(e)||this.pending.has(e)}clear(e){this.clearTimeout(e);let t=this.pending.get(e);t&&(t.reject(new Error(`Request '${t.method}' (id=${e}) cancelled`)),this.pending.delete(e)),this.callbacks.delete(e)}rejectAll(e){for(let[,t]of this.pending)t.reject(e);this.pending.clear();for(let[,t]of this.timeouts)clearTimeout(t);this.timeouts.clear(),this.callbacks.clear()}};var Ca=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var oi=class{map=new Map;register(e,t){let r=this.map.get(e);r||(r=new Set,this.map.set(e,r)),r.add(t)}unregister(e,t){let r=this.map.get(e);r&&(t!==void 0?r.delete(t):r.clear(),r.size===0&&this.map.delete(e))}invoke(e,...t){let r=this.map.get(e);if(r)for(let i of r)try{i(...t)}catch(o){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,o)}}invokeOnce(e,...t){this.invoke(e,...t),this.unregister(e)}clear(){this.map.clear()}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}};function T(n){return typeof n=="object"&&n!==null}var Ly=20*1e3,gR=30*1e3,Ny=300,yR=300;function vR(){let n=process.env.DEVECO_CLI_LSP_STANDARD_EXIT_TIMEOUT_MS;if(n===void 0||n==="")return Ny;let e=parseInt(n,10);return Number.isFinite(e)?Math.max(yR,e):Ny}var ka=class{client;nextRequestId=1;stopOnce=null;callbacks=new oi;requestCallbacks=new Ar;diagnosticMap=new Map;initProgressReset=null;notificationWaiters=new Map;get lspPid(){return this.client.pid}constructor(e){this.client=new Dr(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{u.info("[ClientMessageHandle] Sending shutdown request"),this.client.sendRequest(v.SHUTDOWN,null,this.nextRequestId++),u.info("[ClientMessageHandle] Sending exit notification"),this.client.sendNotification(v.EXIT,null),u.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(vR()),u.info("[ClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(v.BROADCAST),this.callbacks.register(v.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(v.BROADCAST,e)}async sendInitialize(e){let t=this.nextRequestId++,r=this.requestCallbacks.registerPending(t,v.INITIALIZE,We);return this.client.sendRequest(v.INITIALIZE,e,t),r}sendInitializeResettable(e,t){let r=this.nextRequestId++,i=this.requestCallbacks.registerPending(r,v.INITIALIZE,0);return this.client.sendRequest(v.INITIALIZE,e,r),new Promise((o,s)=>{let a,c=()=>{a=setTimeout(()=>{this.initProgressReset=null,s(new Error(`LSP initialization timeout after ${t}ms`))},t)},l=()=>{clearTimeout(a),c()};this.initProgressReset=l,c(),i.then(()=>{clearTimeout(a),this.initProgressReset=null,o()},d=>{clearTimeout(a),this.initProgressReset=null,s(d)})})}sendInitialized(){this.client.sendNotification(v.INITIALIZED,{})}sendInitializeAndWaitForNotification(e,t,r,i,o){return new Promise((s,a)=>{let c={initializeResolved:!1,notificationResolved:!1},l=this.startInitTimer(t,r,a);this.initProgressReset=()=>{l.reset(),o?.()};let d=()=>{c.initializeResolved&&c.notificationResolved&&(l.clear(),s())};this.notificationWaiters.set(t,()=>{c.notificationResolved=!0,d()});let g=this.nextRequestId++;this.client.sendRequest(v.INITIALIZE,e,g),this.requestCallbacks.registerPending(g,v.INITIALIZE,0).then(()=>{c.initializeResolved=!0;try{i()}catch(y){l.clear(),a(y instanceof Error?y:new Error(String(y)));return}d()},y=>{l.clear(),a(y)})})}startInitTimer(e,t,r){let i,o=()=>{clearTimeout(i),this.initProgressReset=null,this.notificationWaiters.delete(e)},s=()=>{i=setTimeout(()=>{o(),r(new Error(`LSP initialization timeout after ${t}ms`))},t)},a=()=>{clearTimeout(i),s()};return s(),{reset:a,clear:o}}sendDidOpen(e){let t=e.textDocument.uri;this.diagnosticMap.has(t)||(this.diagnosticMap.set(t,new Ca(t)),this.registerDiagnosticTimeout(t)),this.client.sendNotification(v.DID_OPEN,e)}sendDidChange(e){let t=e.textDocument.uri,r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t)),this.client.sendNotification(v.DID_CHANGE,e)}closeFile(e){this.cleanupDiagnosticState(e.textDocument.uri),this.client.sendNotification(v.DID_CLOSE,e)}sendLspRequest(e,t,r=gR){let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,r);return this.client.sendRequest(e,t,i),o}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}onDidChangeWatchedFiles(e){e.length!==0&&this.client.sendNotification(v.WORKSPACE_DID_CHANGE_WATCHED_FILES,{changes:e})}sendDidChangeConfiguration(e){this.client.sendNotification(v.WORKSPACE_DID_CHANGE_CONFIGURATION,{settings:e})}sendNotification(e,t){this.client.sendNotification(e,t)}getDiagnosticMessages(e){let t=this.diagnosticMap.get(e);return t?t.get():[]}clearDiagnostic(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let i=r instanceof Error?r.message:String(r);u.error(`[LSP] JSON parse error: ${i}, raw: ${e}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotificationOrRequest(t):u.warn(`[LSP] Unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t===void 0)return;let r=t;if(e.error){let i=new Error(`LSP error ${e.error.code}: ${e.error.message}`);this.requestCallbacks.rejectPending(r,i)}else this.requestCallbacks.resolvePending(r,e.result)}handleNotificationOrRequest(e){let t=e.method;if(!t)return;this.initProgressReset?.();let r=this.notificationWaiters.get(t);if(r){this.notificationWaiters.delete(t),r();return}switch(t){case v.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case v.PROGRESS:this.handleProgress(e.params);break;case v.WINDOW_SHOW_MESSAGE:u.debug(`[LSP] window/showMessage: ${JSON.stringify(e.params)}`);break;case v.WINDOW_LOG_MESSAGE:u.debug(`[LSP] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.broadcastToClients(e)}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=e.uri,r=this.diagnosticMap.get(t);if(!r)return;let i=e.diagnostics||[];this.normalizeDiagnostics(i),r.set(i),this.finalizeDiagnostic(t,i)}normalizeDiagnostics(e){for(let t of e)if(t.severity!==void 0){let r={1:"Error",2:"Warning",3:"Information",4:"Hint"};t.severityStr=r[t.severity]||"Unknown"}}handleProgress(e){T(e)&&this.broadcastToClients({jsonrpc:x,method:v.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,v.PUBLISH_DIAGNOSTICS,Ly,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${Ly}ms, uri: ${e}`)})}finalizeDiagnostic(e,t,r){let i={uri:e,diagnostics:t,...r?{errorMessage:r}:{}};this.requestCallbacks.emit(e,v.PUBLISH_DIAGNOSTICS,i),this.diagnosticMap.get(e)?.clear()}handleError(e){let t=Array.from(this.diagnosticMap.keys()).filter(r=>this.requestCallbacks.hasCallback(r));if(t.length>0){let r={range:{start:{line:0,character:0},end:{line:0,character:0}},severity:1,message:e.message};for(let i of t)this.finalizeDiagnostic(i,[r]);return}this.broadcastToClients({jsonrpc:x,method:v.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var Ia=class{uri;messages=[];receivedTypes=new Set;uniqueMessages=new Set;isFromEditor=!1;constructor(e){this.uri=e}setReceivedType(e){this.receivedTypes.add(e)}addMessage(e,t){this.receivedTypes.add(e);let r=`${e}:${t}`;if(this.uniqueMessages.has(r)){u.info(`[LegacyDiagnostic] addMessage: duplicate message=${r}`);return}this.uniqueMessages.add(r),this.messages.push(new Vd(e,t))}clearMessages(){this.messages=[]}clear(){this.receivedTypes.clear(),this.uniqueMessages.clear(),this.messages=[]}hasReceivedAllTypes(e){for(let t of e)if(!this.receivedTypes.has(t))return!1;return!0}getMessages(){return this.messages.map(e=>e.diagnostics)}},Vd=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var wR={EXIT:"exit",INITIALIZED:"initialized",ON_DID_CHANGE_PACKAGE_DEPENDENCIES:"aceProject/onDidChangePackageDependencies",ON_ASYNC_DID_OPEN:"aceProject/onAsyncDidOpen",ON_ASYNC_DID_CHANGE:"aceProject/onAsyncDidChange",DID_CLOSE:"textDocument/didClose",ON_ASYNC_HOVER:"aceProject/onAsyncHover",ON_ASYNC_DEFINITION:"aceProject/onAsyncDefinition",ON_ASYNC_FIND_USAGES:"aceProject/onAsyncFindUsages"},SR={MODULE_INIT_FINISH:Dn.MODULE_INIT_FINISH,INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate",ON_FORCE_OPEN_FILE:"aceProject/onForceOpenFile",ON_PACKAGE_CHANGE_FINISH:"aceProject/onPackageChangeFinish",TEXT_DOCUMENT_ON_ASYNC_DEFINITION:"textDocument/onAsyncDefinition",ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:"textDocument/onDidChangePackageDependencies",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",REFERENCES:"textDocument/references",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",BROADCAST:"lsp/broadcast",ARKTS_ERROR:"arkts/error",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing"},L={...wR,...SR},Rr={EXIT:"exit",INITIALIZED:"initialized",EMPTY:"empty",ON_DID_CHANGE_PACKAGE_DEPENDENCIES:"onDidChangePackageDependencies",ON_ASYNC_DID_OPEN:"onAsyncDidOpen",ON_ASYNC_DID_CHANGE:"onAsyncDidChange",DID_CLOSE:"didClose",ON_ASYNC_HOVER:"onAsyncHover",ON_ASYNC_DEFINITION:"onAsyncDefinition",ON_ASYNC_FIND_USAGES:"onAsyncFindUsages"},My=new Set([1e3,2e3,3e3,3001]);function bR(n){if(!T(n))return!1;let e=n.textDocument;return T(e)&&typeof e.uri=="string"}function ER(n){return T(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function PR(n){return T(n)&&typeof n.moduleName=="string"&&typeof n.current=="number"&&typeof n.total=="number"?`indexing module '${n.moduleName}', ${n.current} of total ${n.total} modules`:`params=${JSON.stringify(n??null)}`}var Da=class n{client;isInitialized=!1;stopOnce=null;callbacks=new oi;requestCallbacks=new Ar;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;get lspPid(){return this.client.pid}constructor(e){this.client=new Dr(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{u.info("[LegacyClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:x,method:L.EXIT,params:{}}),Rr.EXIT),u.info("[LegacyClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),u.info("[LegacyClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(L.BROADCAST),this.callbacks.register(L.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(L.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(L.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(L.INDEXING_PROGRESS_UPDATE,e)}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}sendInitialize(e,t){this.client.send("initialize",e,t)}sendInitialized(e){this.client.sendRaw(JSON.stringify({jsonrpc:x,method:L.INITIALIZED,params:{editors:e}}),Rr.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:x,id:0,result:{}}),Rr.EMPTY)}sendAsyncRequest(e,t,r,i){if(!T(t)){u.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!bR(t)){u.warn(`[LSP] sendAsyncRequest missing textDocument.uri, method=${e}, params=${JSON.stringify(t)}`);return}if(typeof r!="number"){u.warn(`[LSP] sendAsyncRequest invalid requestId, method=${e}, requestId=${String(r)}`);return}let o=t.textDocument.uri,s=St(o);t.textDocument.uri=s,delete t.requestId;let a=i??e;u.info(`[LSP] sendAsyncRequest ${a}, filePath: ${o}`),this.client.sendRaw(JSON.stringify({jsonrpc:x,method:e,params:{params:t,requestId:r}}),a)}onDidChangeWatchedFiles(e){if(u.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let r of e){if(!ER(r)){u.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:x,method:L.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),L.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!T(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){u.warn("[LSP] sendModuleDependencyUpdate, moduleSet is empty or null");return}let t=e.moduleSet;u.info(`[LSP] sending module dependency updated, count: ${t.length}`),this.client.sendRaw(JSON.stringify({jsonrpc:x,method:L.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),Rr.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let i=St(t);e.textDocument.uri=i,u.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new Ia(i),this.diagnosticMap.set(i,o),this.registerDiagnosticTimeout(i,L.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(o.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:x,method:L.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),Rr.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=St(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,L.PUBLISH_DIAGNOSTICS)),u.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:x,method:L.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),Rr.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=St(e);u.info(`[LSP] didClose, uri: ${r}`);let i=this.diagnosticMap.get(r);if(!t&&(!i||i.isFromEditor)){u.info(`[LSP] closeFile skip, !diagnostic: ${!i}, isFromEditor: ${i?.isFromEditor}`);return}this.cleanupDiagnosticState(r),this.client.sendRaw(JSON.stringify({jsonrpc:x,method:L.DID_CLOSE,params:{textDocument:{uri:r}}}),Rr.DID_CLOSE)}getDiagnosticMessage(e){let t=St(e),r=this.diagnosticMap.get(t);return r?r.getMessages():[]}clear(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){try{let t=JSON.parse(e);this.handleLspMessage(t)}catch(t){let r=t instanceof Error?t.message:String(t);u.error(`[LSP] JSON parse error: ${r}, raw: ${e}`)}}handleError(e){let t=this.getPendingDiagnosticUris();if(t.length>0){let r=JSON.stringify({message:e.message,severity:"Error",severityStr:"Error"});for(let i of t)this.finalizeDiagnostic(i,L.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:x,method:L.ARKTS_ERROR,params:{message:e.message}})}handleLspMessage(e){let t=e.method;t!==void 0&&(!this.isInitialized&&this.handlePreInitMessage(t,e)||this.handlePostInitMessage(t,e))}handlePreInitMessage(e,t){switch(e){case L.MODULE_INIT_FINISH:return u.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(L.MODULE_INIT_FINISH),this.callbacks.unregister(L.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case L.INDEXING_PROGRESS_UPDATE:return u.info(`[LSP] onIndexingProgressUpdate: ${PR(t.params)}`),this.callbacks.invoke(L.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case L.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case L.ON_PACKAGE_CHANGE_FINISH:u.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case L.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case L.ON_ASYNC_HOVER:this.handleAsyncResponse(t,L.HOVER);return;case L.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,L.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case L.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,L.REFERENCES);return;default:u.warn(`[LSP] handleLspMessage: no handler for notification, ignoring, method: ${e}, initialized: ${this.isInitialized}`)}}handleOnForceOpenFile(e){u.info("[LSP] handleLspMessage, receive onForceOpenFile");let t=e.params;T(t)&&T(t.result)&&typeof t.result.uri=="string"&&this.handleForceOpenFile(t.result.uri)}handlePublishDiagnostics(e){u.info("[LSP] handleLspMessage, receive publishDiagnostics");let t=e.params;t&&this.parseDiagnostics(t)}handlePackageChangeFinish(e){let t=e.params,r={jsonrpc:x,method:L.ON_PACKAGE_CHANGE_FINISH,params:[!1]};if(!t||!Array.isArray(t)){u.warn("[LSP] aceProject/onPackageChangeFinish params invalid"),this.broadcastToClients(r);return}if(!(t.length>0&&t[0]===!0)){u.warn("[LSP] aceProject/onPackageChangeFinish: package request failed"),this.broadcastToClients(r);return}u.info("[LSP] aceProject/onPackageChangeFinish: success"),this.broadcastToClients(e)}handleAsyncResponse(e,t){u.info(`[LSP] handleAsyncResponse\uFF0C method: ${t}`);let r=e.params;if(!T(r)){u.warn("[LSP] aceProject/onAsyncHover message invalid");return}let i=r.requestId;if(typeof i!="number"){u.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(i,t,r)}handleForceOpenFile(e){if(!e){u.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,L.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){u.info("[LSP] publishDiagnostics uri is null");return}let r=e.version??-1;if(r===-1)return;let i=this.diagnosticMap.get(t);if(!i){u.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let o=e.diagnostics||[];o.length!==0?o.forEach(s=>{this.normalizeDiagnostic(s),i.addMessage(r,JSON.stringify(s))}):i.setReceivedType(r),i.hasReceivedAllTypes(My)&&this.finalizeDiagnostic(t,L.PUBLISH_DIAGNOSTICS,i.getMessages())}normalizeDiagnostic(e){let t=e;if(delete t.source,t.severity!==void 0){let r=typeof t.severity=="number"?t.severity:parseInt(t.severity),o={1:"Error",2:"Warning",3:"Information",4:"Hint"}[r]||"Unknown";t.severityStr=o,t.severity=o}e.range&&(this.adjustPositionLine(e.range,"start"),this.adjustPositionLine(e.range,"end"))}adjustPositionLine(e,t){let r=e[t];r&&typeof r.line=="number"&&(r.line=r.line+1)}registerDiagnosticTimeout(e,t){this.requestCallbacks.registerTimeout(e,t,n.DIAGNOSTIC_TIMEOUT_MS,()=>{let r=this.diagnosticMap.get(e),i=r?r.getMessages():[];this.finalizeDiagnostic(e,t,i,i.length>0?void 0:`received no diagnostics within ${n.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,r,i){let o={uri:e,diagnostics:r,...i?{errorMessage:i}:{}};this.requestCallbacks.emit(e,t,o),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import Gd from"path";import*as Ma from"path";var Aa=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var Ra=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var Ta=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var xa=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var La=class{typeSetting=new Ta;parameterNames=new xa};var Na=class{constructor(e,t,r,i){this.rootUri=e;this.lspServerWorkspacePath=le(Ma.dirname(t)),this.indexingDataLocation=le(i),this.loggerPath=le(Ma.join(r,"lspLog"))}modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new Aa;gutterIconsSetting=new Ra;inlayHintsSetting=new La;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as Oy from"path";var bo=class{productName="default";buildModeName="debug";targetName="default";arkTSVersion="1.1";resourceDirectories=[];targetESVersion="ES2021";maxFlowDepth=2e3;caseSensitiveCheck=!0;tsImportSendable=!1;compatibleSdkVersionStage="";useNormalizedOHMUrl=!0;reExportCheckMode="noCheck";skipOhModulesLint=!1;byteCodeHar=!0;obfuscationRuleOptionsEnable=!1;enableStrictCheckOHModules=!1;sourceRoots=[];constructor(e){e&&this.resourceDirectories.push(le(Oy.join(e,"src","main","resources")))}};var CR="OS",si=class{deviceType=[5];aceLoaderPath;modulePath;jsComponentType="declarative";sdkJsPath;compatibleSdkVersion;compatibleSdkLevel;compileSdkLevel;compileSdkVersion="6.0.1.112";compileSdkType="Release";syscap={NDeviceSysCaps:[],addedSysCaps:[]};apiType="stageMode";hosSdkPath;runtimeOs=`Harmony${CR}`;moduleName;moduleType;compileMode="jsbundle";crossPlatform=!1;ignoreCrossPlatform=!1;packageManagerType="ohpm";permissions=[];testPermissions=[];buildProfileParam;appParam={bundleType:"app"};packageName;projectType="OHOS";projectName;moduleDependencies;moduleJsonParam=null;globalDeclarationFiles=[];constructor(e){e?(this.modulePath=e,this.buildProfileParam=new bo(e)):this.buildProfileParam=new bo}toString(){return JSON.stringify(this)}};var ai=class{constructor(e=[]){this.pages=e}pagesFileName="main_pages.json";metaDataList=[]};import*as $e from"path";import*as di from"fs";var Oa=class{modulePath;dependencies={};dynamicDependencies={}};var pn=class{registryType;resolved;name;version;type;constructor(e){let t=typeof e=="object"&&e!==null?e:{};this.name=typeof t.name=="string"?t.name:"",this.version=typeof t.version=="string"?t.version:"",typeof t.registryType=="string"?this.registryType=t.registryType:this.registryType=typeof t.path=="string"?"local":"ohpm",typeof t.resolved=="string"?this.resolved=t.resolved:typeof t.storePath=="string"?this.resolved=t.storePath:this.resolved="",this.type=typeof t.type=="string"?t.type:void 0}};var ci=class{constructor(e,t,r){this.projectPath=e;this.moduleName=t;this.modulePath=r}dependencies=[];devDependencies=[];dynamicDependencies=[];finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[]};import*as or from"path";import*as _a from"fs";var li=class{name="";version="";storePath="";dependencyPath="";path=""};var F={HVIGOR_CACHE:".hvigor",DEPENDENCY:"dependencyMap",JSON5:".json5",KEY_DEPENDENCY:"dependencies",KEY_DYNAMIC_DEPENDENCY:"dynamicDependencies",KEY_DEV_DEPENDENCY:"devDependencies",OH_MODULES_PATH:"oh_modules",OHPM_PATH:".ohpm",LOCK_JSON5_FILE:"lock.json5",OH_PACKAGE_JSON5:Le.OH_PACKAGE_JSON5},Eo=`${F.HVIGOR_CACHE}/${F.DEPENDENCY}`,mn=`${F.DEPENDENCY}${F.JSON5}`,cY=Le.SYNC_OUTPUT_PATH;var Po=class n{dependencyPath;modulePath;projectPath;static FILE_DEPENDENCY_PREFIX="file:";static PARAMETER_PREFIX="@param:";fileSpecPattern;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;static PACKAGE_JSON_PARSER_MAP=new Map;dependencies=[];devDependencies=[];dynamicDependencies=[];static getInstance(e,t,r){let i=this.PACKAGE_JSON_PARSER_MAP.get(e);return i||(i=new n(e,t,r),this.PACKAGE_JSON_PARSER_MAP.set(e,i)),i}constructor(e,t,r){this.dependencyPath=e,this.modulePath=t,this.projectPath=r,this.fileSpecPattern=n.isWindows()?/^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/:/^(?:[.]|~[/]|[/]|[a-zA-Z]:)/}static isWindows(){return process.platform==="win32"}parseDependency(e){let t=or.join(this.dependencyPath,F.OH_PACKAGE_JSON5),r=tt(t);r&&(this.dependencies=this.getDependencyList(r,F.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(r,F.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(r,F.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let r=[];if(!T(e))return r;let i=e[t];if(!T(i))return r;for(let[o,s]of Object.entries(i)){if(typeof s!="string"){u.error(`${o} package dependency value is not String ${t}`);continue}let a=new li;a.name=o;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(n.PARAMETER_PREFIX)||this.parseDependencyPath(o,c,a,!1),r.push(a)}return r}parseDependencyPath(e,t,r,i){if(!(!e||!t))try{let o=or.normalize(or.join(this.modulePath,F.OH_MODULES_PATH,e));if(!(t.startsWith(n.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){r.dependencyPath=o;return}if(r.path=t,this.fileNameForOhpm.test(t)){r.dependencyPath=o;return}let s=t;if(t.startsWith(n.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(n.FILE_DEPENDENCY_PREFIX.length)),or.isAbsolute(s)){r.dependencyPath=o;return}i||(o=or.resolve(this.modulePath,s)),_a.existsSync(o)&&_a.statSync(o).isDirectory()&&(r.dependencyPath=o)}catch(o){u.error("parser dependency path is invalid",o)}}};import*as fn from"fs";import*as Tr from"path";import kR from"json5";var Fa=class n{projectPath;static FILE_DEPENDENCY_PREFIX="file:";static MAX_LOCK_FILE_SIZE=20*1024*1024;static MAX_KEYS_PER_OBJECT=5e4;static MAX_JSON_DEPTH=50;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[];storePathMap=new Map;lockFileCache=null;lockFileParsed=!1;constructor(e=""){this.projectPath=e}parseDependencies(e){if(!this.ensureLockFileParsed())return!1;let t=this.lockFileCache;return this.extractDependencies(t.modules,t.storePathMap,e),!0}ensureLockFileParsed(){if(this.lockFileParsed)return this.lockFileCache!==null;this.lockFileParsed=!0;let e=this.getLockFilePath(),t=this.readLockFile(e);if(!t)return!1;let r=this.validateLockFile(t);return r.valid?(this.lockFileCache={modules:r.modules,storePathMap:this.parseStorePathMap(r.packages)},!0):!1}getLockFilePath(){return Tr.join(this.projectPath,F.OH_MODULES_PATH,F.OHPM_PATH,F.LOCK_JSON5_FILE)}static checkObjectDepth(e,t,r=0){if(r>t)return!1;if(typeof e!="object"||e===null)return!0;if(Array.isArray(e)){for(let i of e)if(!n.checkObjectDepth(i,t,r+1))return!1;return!0}for(let i in e)if(Object.prototype.hasOwnProperty.call(e,i)&&!n.checkObjectDepth(e[i],t,r+1))return!1;return!0}readLockFile(e){if(!fn.existsSync(e))return u.error("lock file does not exist"),this.clearDependencies(),null;try{let t=fn.statSync(e);if(t.size>n.MAX_LOCK_FILE_SIZE)return u.error(`lock file is too large (${t.size} bytes), read aborted`),this.clearDependencies(),null}catch(t){return u.error(`Failed to stat lock file: ${t instanceof Error?t.message:String(t)}`),this.clearDependencies(),null}try{let t=fn.readFileSync(e,"utf8"),r=kR.parse(t);return r?n.checkObjectDepth(r,n.MAX_JSON_DEPTH)?r:(u.error("lock.json5 nesting depth exceeds limit"),this.clearDependencies(),null):(u.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return u.error(`Error parsing lock.json5: ${t instanceof Error?t.message:String(t)}`),this.clearDependencies(),null}}validateLockFile(e){if(!T(e))return u.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return u.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let r=e.packages;return r?{valid:!0,modules:t,packages:r}:(u.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,r){this.storePathMap=t,this.finalDependencies=this.getDependencyList(e,F.KEY_DEPENDENCY,r),this.finalDevDependencies=this.getDependencyList(e,F.KEY_DEV_DEPENDENCY,r),this.finalDynamicDependencies=this.getDependencyList(e,F.KEY_DYNAMIC_DEPENDENCY,r)}parseStorePathMap(e){let t=new Map;if(!T(e))return t;let r=0;for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;let o=e[i];if(!T(o)){u.error(`${i} value is not json object`);continue}if(++r>n.MAX_KEYS_PER_OBJECT){u.warn("lock.json5 packages object exceeds key limit, truncating");break}typeof o.storePath=="string"&&t.set(i,o.storePath)}return t}getDependencyList(e,t,r){if(!T(e))return[];let i=0;for(let o in e){if(!Object.prototype.hasOwnProperty.call(e,o))continue;if(++i>n.MAX_KEYS_PER_OBJECT){u.warn("lock.json5 modules object exceeds key limit, truncating");break}let s=e[o];if(T(s)){let a=typeof s.name=="string"?s.name:"";if(r==="."&&a===""||a===r)return this.getFinalDependencyList(e,t,o)}}return[]}getFinalDependencyList(e,t,r){let i=e[r];if(!T(i))return u.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!T(s))return[];let a=0;for(let c in s){if(!Object.prototype.hasOwnProperty.call(s,c))continue;if(++a>n.MAX_KEYS_PER_OBJECT){u.warn("lock.json5 dependencies object exceeds key limit, truncating");break}let l=s[c];if(!T(l))continue;let d=typeof l.specifier=="string"?l.specifier:"",g=typeof l.version=="string"?l.version:"",y=new li;y.name=c,y.version=g.startsWith(n.FILE_DEPENDENCY_PREFIX)?g.substring(n.FILE_DEPENDENCY_PREFIX.length):g,this.parseDependencyPath(y,r,c,d,g);let I=`${c}@${g}`;this.storePathMap.has(I)&&(y.storePath=this.storePathMap.get(I)||""),o.push(y)}return o}parseDependencyPath(e,t,r,i,o){let s=Tr.resolve(this.projectPath,Tr.join(t,F.OH_MODULES_PATH,r));try{let a=o.startsWith(n.FILE_DEPENDENCY_PREFIX)?o.substring(n.FILE_DEPENDENCY_PREFIX.length):o,c=Tr.isAbsolute(a)?a:Tr.resolve(this.projectPath,a);fn.existsSync(c)?(e.path=i,e.dependencyPath=this.fileNameForOhpm.test(o)?s:c):e.dependencyPath=s}catch(a){u.error("Invalid dependency path in lock.json5, msg:",a instanceof Error?a.message:String(a))}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};function _y(n){return T(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var hn=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new Vt(this.projectPath)}moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e,t){let r=this.projectPath,i=$e.join(r,Eo),o=$e.join(i,mn);if(!di.existsSync(i)||!di.existsSync(o)){let l="Dependency map or JSON not found";return u.warn(`[Parser] getAllDependencyMap failed: ${l}.`),{status:"ERROR",message:`${l}, please rebuild project`}}let s=new ci(this.projectPath,".",this.projectPath);this.parseProjectDependencies(i,s),this.parseLockJson(s);let a=this.moduleInfoParse.getAllModuleInfo();if(a.length===0){let l="No modules found in build-profile.json5";return u.warn(`[Parser] getAllDependencyMap failed: ${l}.`),{status:"ERROR",message:l}}let c=Date.now();for(let l=0;l<a.length;l++){let d=a[l];if(_y(d)){try{E.assertModuleName(d.name)}catch{u.warn(`[Parser] Skipping module with invalid name: ${d.name}`);continue}this.parseSingleModule(d,i,s,e),((l+1)%50===0||l+1===a.length)&&(u.info(`[Parser] getAllDependencyMap progress: ${l+1}/${a.length} (${Date.now()-c}ms)`),t?.(l+1,a.length))}}return u.info(`[Parser] getAllDependencyMap parsed ${e.length} modules in ${Date.now()-c}ms`),{status:"OK"}}getDependenciesOnly(e){let t=[],r=this.projectPath,i=$e.join(r,Eo),o=$e.join(i,mn);if(!di.existsSync(i)||!di.existsSync(o))return u.warn("[Parser] Dependency map or JSON not found."),t;let s=e&&e.length>0?new Set(e.map(l=>l.trim()).filter(Boolean)):null,a=new ci(this.projectPath,".",this.projectPath);this.parseProjectDependencies(i,a),this.parseLockJson(a);let c=this.moduleInfoParse.getAllModuleInfo();if(c.length===0)return u.warn("[Parser] getAllDependencyMap failed: No modules found in build-profile.json5."),t;for(let l of c){if(!_y(l))continue;let d=l.name;try{E.assertModuleName(d)}catch{u.warn(`[Parser] Skipping module with invalid name: ${d}`);continue}if(s&&!s.has(d))continue;let g=$e.resolve(this.projectPath,l.srcPath),y=$e.join(i,d),I=le(g),ce=this.buildModuleDependencies(d,I,y,a);ce.moduleName=d,t.push(ce)}return t}parseSingleModule(e,t,r,i){let o=e.name,s=$e.resolve(this.projectPath,e.srcPath),a=$e.join(t,o),c=le(s),l=new si(c),d=this.buildModuleDependencies(o,c,a,r);this.parseModuleJson5(c,l);let g=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=o,l.moduleType=o,l.packageName=o,l.moduleDependencies=d,l.moduleJsonParam=new ai(g),i.push(l)}buildModuleDependencies(e,t,r,i){let o=new ci(this.projectPath,e,t);Po.getInstance(r,t,this.projectPath).parseDependency(o),this.parseLockJson(o),o.finalDependencies.push(...i.finalDependencies),o.finalDevDependencies.push(...i.finalDevDependencies),o.finalDynamicDependencies.push(...i.finalDynamicDependencies),o.finalDependencies.push(...o.finalDevDependencies);let a=new Oa;return a.modulePath=t,this.toModuleDependencies(o,a),a}toModuleDependencies(e,t){let r={},i={};for(let o of e.finalDependencies)r[o.name]=new pn(o);for(let o of e.finalDynamicDependencies)i[o.name]=new pn(o);t.dependencies=r,t.dynamicDependencies=i}parseProjectDependencies(e,t){let r=$e.join(e,F.OH_PACKAGE_JSON5);if(!di.existsSync(r))return;Po.getInstance(e,this.projectPath,this.projectPath).parseDependency(t)}parseLockJson(e){let t=this.getLockJson5Parser();t.parseDependencies(e.moduleName)?(e.finalDependencies=t.finalDependencies,e.finalDevDependencies=t.finalDevDependencies,e.finalDynamicDependencies=t.finalDynamicDependencies):(e.finalDependencies=e.dependencies,e.finalDevDependencies=e.devDependencies,e.finalDynamicDependencies=e.dynamicDependencies)}getLockJson5Parser(){return this.lockJson5Parser||(this.lockJson5Parser=new Fa(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=$e.join(e,"src","main","module.json5"),i=tt(r);if(!T(i)||!T(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(T(e)&&Array.isArray(e.requestPermissions))for(let r of e.requestPermissions)T(r)&&typeof r.name=="string"&&t.push(r.name);return t}parseMainPages(e){let t=$e.join(e,"src","main","resources","base","profile","main_pages.json"),r=tt(t);return!T(r)||!Array.isArray(r.src)?[]:r.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=this.getSdkPkg();if(!(!T(t)||!T(t.data))){if(typeof t.data.apiVersion=="string"){let r=parseInt(t.data.apiVersion,10);!Number.isNaN(r)&&r>=26&&typeof t.data.platformVersion=="string"?e.compileSdkLevel=t.data.platformVersion:e.compileSdkLevel=t.data.apiVersion}typeof t.data.releaseType=="string"&&(e.compileSdkType=t.data.releaseType),typeof t.data.version=="string"&&(e.compileSdkVersion=t.data.version)}}getSdkPkg(){if(this.sdkPkgCache===void 0){let e=$e.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=tt(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!T(t)||!T(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let r=t.app.products[0];if(!T(r)||typeof r.compatibleSdkVersion!="string")return;let[i,o]=this.parseBySplit(r.compatibleSdkVersion);e.compatibleSdkVersion=i,e.compatibleSdkLevel=o}getBuildProfile(){if(this.buildProfileCache===void 0){let e=$e.join(this.projectPath,"build-profile.json5");this.buildProfileCache=tt(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,e];let r=e.substring(0,t),i=e.substring(t+1,e.length-1);return[r,i]}parseDeviceTypes(e){return!T(e)||!Array.isArray(e.deviceTypes)?[]:e.deviceTypes.filter(t=>typeof t=="string").map(t=>this.getDeviceType(t))}getDeviceType(e){return{liteWearable:1,wearable:2,tv:3,car:4,phone:5,default:5,smartVision:6,tablet:7,router:8,pc:9,"2in1":10}[e]||0}};var $a=class{constructor(e=[]){this.valueSet=e}};var ui=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var Fy=(D=>(D[D.File=1]="File",D[D.Module=2]="Module",D[D.Namespace=3]="Namespace",D[D.Package=4]="Package",D[D.Class=5]="Class",D[D.Method=6]="Method",D[D.Property=7]="Property",D[D.Field=8]="Field",D[D.Constructor=9]="Constructor",D[D.Enum=10]="Enum",D[D.Interface=11]="Interface",D[D.Function=12]="Function",D[D.Variable=13]="Variable",D[D.Constant=14]="Constant",D[D.String=15]="String",D[D.Number=16]="Number",D[D.Boolean=17]="Boolean",D[D.Array=18]="Array",D[D.Object=19]="Object",D[D.Key=20]="Key",D[D.Null=21]="Null",D[D.EnumMember=22]="EnumMember",D[D.Struct=23]="Struct",D[D.Event=24]="Event",D[D.Operator=25]="Operator",D[D.TypeParameter=26]="TypeParameter",D))(Fy||{}),$y=()=>Object.values(Fy).filter(n=>typeof n=="number");var ja=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Ha=class{applyEdit=!0;workspaceEdit=new ja;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new $a($y());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new ui;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Ua=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Ba=class{constructor(e=[]){this.valueSet=e}};var Wa=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var jy=(R=>(R[R.Text=1]="Text",R[R.Method=2]="Method",R[R.Function=3]="Function",R[R.Constructor=4]="Constructor",R[R.Field=5]="Field",R[R.Variable=6]="Variable",R[R.Class=7]="Class",R[R.Interface=8]="Interface",R[R.Module=9]="Module",R[R.Property=10]="Property",R[R.Unit=11]="Unit",R[R.Value=12]="Value",R[R.Enum=13]="Enum",R[R.Keyword=14]="Keyword",R[R.Snippet=15]="Snippet",R[R.Color=16]="Color",R[R.File=17]="File",R[R.Reference=18]="Reference",R[R.Folder=19]="Folder",R[R.EnumMember=20]="EnumMember",R[R.Constant=21]="Constant",R[R.Struct=22]="Struct",R[R.Event=23]="Event",R[R.Operator=24]="Operator",R[R.TypeParameter=25]="TypeParameter",R))(jy||{}),Hy=()=>Object.values(jy).filter(n=>typeof n=="number");var Va=class{completionItemKind=new Ba(Hy());completionItem=new Wa;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var Ga=class{synchronization=new Ua;completion=new Va;hover={contentFormat:{},dynamicRegistration:{}};signatureHelp={signatureInformation:{},contextSupport:{},dynamicRegistration:{}};references={dynamicRegistration:{}};documentHighlight={dynamicRegistration:!0};documentSymbol=null;formatting={dynamicRegistration:{}};rangeFormatting={dynamicRegistration:{}};onTypeFormatting={dynamicRegistration:{}};declaration={};definition={linkSupport:{},dynamicRegistration:{}};codeLens=null;documentLink={tooltipSupport:{},dynamicRegistration:{}};colorProvider=null;rename={prepareSupport:!0,prepareSupportDefaultBehavior:null,honorsChangeAnnotations:null,dynamicRegistrationSupport:null};publishDiagnostics=null;foldingRage=null;typeHierarchy=null;callHierarchy={dynamicRegistration:{}};selectionRange=null;semanticTokens=new ui;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var qa=class{workspace=new Ha;textDocument=new Ga;notebookDocument=null;window=null;general=null;experimental=null};var za=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}};var Ja=class{constructor(e,t,r,i,o,s=!0,a,c=!1){this.sdkPath=e;this.rootUri=r;this.nodeMaxOldSpaceSize=o;this.useStandardProtocol=s;this.nodePath=a;this.useSocket=c;this.serverPath=En(t,this.useStandardProtocol),this.logPath=Jp(),this.indexLogPath=i||this.logPath,u.debug(`[LspServerProxy] arktsLangServer=${t}`),u.debug(`[LspServerProxy] useStandardProtocol=${this.useStandardProtocol}, useSocket=${this.useSocket}`),u.debug(`[LspServerProxy] serverPath=${this.serverPath}`);let l={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath,projectPath:this.rootUri,useSocket:this.useSocket,nodePath:this.nodePath};this.messageHandle=this.useStandardProtocol?new ka(l):new Da(l),this.messageHandle.setBroadcastToClients(d=>this.onLspMessage(d))}messageHandle;get stdHandle(){return this.messageHandle}get legacyHandle(){return this.messageHandle}get lspPid(){return this.messageHandle.lspPid}onAsyncOpenFile(e){this.legacyHandle.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.legacyHandle.closeFile(e,t)}serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}async start(e,t,r){let i=!1;try{u.debug(`serverPath: ${this.serverPath}`),u.debug(`rootUri: ${this.rootUri}`),u.debug(`sdkPath: ${this.sdkPath}`),u.debug(`logPath: ${this.logPath}`);let o=St(this.rootUri),s=new Na(o,this.serverPath,this.logPath,this.indexLogPath),a=[],l=new hn(this.rootUri,this.sdkPath).getAllDependencyMap(a,r);if(l.status==="ERROR")throw new Error(`${l.message}`);this.fillModuleModelsPaths(a),s.modules=a;let d=hs(a.length,this.nodeMaxOldSpaceSize);await this.messageHandle.start(d),this.currentParams=new za(o,s,new qa),this.useStandardProtocol?await this.startStandardProtocol(this.currentParams):await this.startLegacy(this.currentParams,e),i=!0}catch(o){this.lastStartErrorMessage=o instanceof Error?o.message:String(o),u.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(i)}async startStandardProtocol(e){let t=this.messageHandle,r=()=>t.broadcastToClients({jsonrpc:x,method:v.ARKTS_INDEXING_PROGRESS,params:{}});this.useSocket?(u.info("[LSP] socket mode: waiting for initialize response + aceProject/onModuleInitFinish"),await t.sendInitializeAndWaitForNotification(e,Dn.MODULE_INIT_FINISH,We,()=>{u.info("[LSP] initialize response received"),r(),t.sendInitialized()},r),u.info("[LSP] initialize response + onModuleInitFinish received, initialization complete")):(await t.sendInitializeResettable(e,We),u.info("[LSP] initialize response received"),r(),t.sendInitialized())}async startLegacy(e,t){let r=this.messageHandle;r.sendInitialize(e,1),r.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:x,method:v.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((i,o)=>{r.onIndexingProgressUpdate(o),r.onInitializationCompleted(i)},"LSP initialization",We),r.sendInitialized(t)}withResettableTimeout(e,t,r){return new Promise((i,o)=>{let s,a=()=>{s=setTimeout(()=>{o(new Error(`${t} timeout after ${r}ms`))},r)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),i()},c)})}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){u.debug(`[LSP] registerDiagnosticCallback uri='${e}', useStandardProtocol=${this.useStandardProtocol}`),this.messageHandle.registerRequestCallback(e,(t,r)=>{let i=T(r)?r:{};u.debug(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let o={jsonrpc:x,method:t,params:{uri:typeof i.uri=="string"?i.uri:e,diagnostics:Array.isArray(i.diagnostics)?i.diagnostics:[],...typeof i.errorMessage=="string"?{errorMessage:i.errorMessage}:{}}};this.onLspMessage(o)})}async hover(e){let t=e.textDocument.uri;return this.registerDiagnosticCallback(t),this.stdHandle.sendLspRequest(v.HOVER,e)}async definition(e){return this.stdHandle.sendLspRequest(v.DEFINITION,e)}async references(e){return this.stdHandle.sendLspRequest(v.REFERENCES,e)}async completion(e){return this.stdHandle.sendLspRequest(v.COMPLETION,e)}async documentSymbol(e){return this.stdHandle.sendLspRequest(v.DOCUMENT_SYMBOL,e)}async diagnostic(e){return this.stdHandle.sendLspRequest(v.DIAGNOSTIC,e,120*1e3)}async sendFeatureRequest(e,t){return this.stdHandle.sendLspRequest(e,t)}reloadDependenciesOnly(e){let t=e?.fullReload??!1,r=new hn(this.rootUri,this.sdkPath),i=this.getModuleModelsByName();if(t){u.info("[LspServerProxy] Project-level oh-package changed, parsing all modules' dependencies");let l=r.getDependenciesOnly();this.markDependencyTypesIncremental(l);let d=this.mergeDepsOnlyIntoModuleList(l,i);return this.applyModuleModelsUpdate(d),this.sendDidChangeConfiguration({moduleSet:d}),u.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${d.length}`),this.lastDepsOnlyForDiff=l,l}let o=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(o.length===0&&s.size===0)return u.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];u.info(`[LspServerProxy] Module-level deps changed, parsing: [${o.join(", ")}]`);let a=r.getDependenciesOnly(o);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),this.sendDidChangeConfiguration({moduleSet:c}),u.info(`[LspServerProxy] Dependencies only (incremental) reloaded, count: ${c.length}`),this.lastDepsOnlyForDiff=a,a}sendDidChangeConfiguration(e){this.stdHandle.sendDidChangeConfiguration(e)}getModuleModelsByName(){return new Map(this.currentModuleModels.map(e=>[e.moduleName??"",e]))}markDependencyTypesIncremental(e){let t=this.getModuleModelsByName(),r=new Map(this.lastDepsOnlyForDiff.map(i=>[i.moduleName??"",i]));for(let i of e){let o=i.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(o,t,r),c=i.dependencies??{},l=i.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(d,g)=>{(i.dependencies??={})[d]=this.makeDeleteEntry(d,g)}),this.markAddAndDeleteInDeps(a,l,(d,g)=>{(i.dynamicDependencies??={})[d]=this.makeDeleteEntry(d,g)})}}getOldDepsForModule(e,t,r){let i=t.get(e),o=i?.moduleDependencies?.dependencies??{},s=i?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(o).length===0&&Object.keys(s).length===0){let a=r.get(e);a&&(o=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:o,oldDynamic:s}}markAddAndDeleteInDeps(e,t,r){for(let i of Object.keys(t))i in e||(t[i].type="add");for(let i of Object.keys(e))i in t||r(i,e[i])}makeDeleteEntry(e,t){return new pn({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new si(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new ai([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let r=[];for(let i of e){let o=i.moduleName??"",s=t.get(o);s?(s.modulePath=i.modulePath,s.moduleDependencies=i):s=this.createMinimalModelFromDepsItem(i),r.push(s)}return r}mergeIncrementalDeps(e,t,r){let i=new Map(r.map(s=>[s.moduleName??"",s])),o=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=i.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,i.delete(a)),o.push(s)}for(let[,s]of i)o.push(this.createMinimalModelFromDepsItem(s));return o}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,r=Rn(Gd.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=Rn(Gd.join(t,"default/openharmony/ets/api")),o=Rn(Gd.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=i,s.hosSdkPath=o}sendRequest(e){switch(e.method){case v.HOVER:this.stdHandle.sendLspRequest(v.HOVER,e.params).then(t=>this.onLspMessage({jsonrpc:x,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:x,id:e.id,error:{code:-32603,message:t.message}}));break;case v.DEFINITION:this.stdHandle.sendLspRequest(v.DEFINITION,e.params).then(t=>this.onLspMessage({jsonrpc:x,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:x,id:e.id,error:{code:-32603,message:t.message}}));break;case v.REFERENCES:this.stdHandle.sendLspRequest(v.REFERENCES,e.params).then(t=>this.onLspMessage({jsonrpc:x,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:x,id:e.id,error:{code:-32603,message:t.message}}));break;default:u.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!Ay(e)){u.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case v.DID_OPEN:this.handleDidOpenNotification(e);break;case v.DID_CHANGE:this.handleDidChangeNotification(e);break;case v.DID_CLOSE:this.handleDidCloseNotification(e);break;case v.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;case v.DID_CREATE_FILES:this.handleDidCreateFiles(e);break;case v.DID_DELETE_FILES:this.handleDidDeleteFiles(e);break;default:u.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){u.error("Invalid textDocument/didOpen params");return}this.stdHandle.sendDidOpen(t)}handleDidChangeNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){u.error("Invalid textDocument/didChange params");return}this.stdHandle.sendDidChange(t)}handleDidCloseNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){u.error("Invalid textDocument/didClose params");return}this.stdHandle.closeFile(t)}handleDidChangeWatchedFiles(e){let t=e.params;!t||!Array.isArray(t.changes)||this.messageHandle.onDidChangeWatchedFiles(t.changes)}handleDidCreateFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(v.DID_CREATE_FILES,t)}handleDidDeleteFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(v.DID_DELETE_FILES,t)}async dispose(){await this.messageHandle.stop()}};import*as sr from"fs";import*as Je from"path";import{createHash as DR}from"crypto";import{EventEmitter as AR}from"events";var Ya=class extends AR{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r}watchers=new Map;debounceTimers=new Map;contentHashes=new Map;buildProfileWatcher=null;lastModulesSnapshot="";lastModules=[];debounceMs;start(){let t=this.parseModulesFromBuildProfile();this.lastModules=t,this.lastModulesSnapshot=this.computeModulesSnapshot(t),this.refreshWatchTargets(),this.watchBuildProfile()}refreshWatchTargets(){let t=new Set(this.collectWatchTargets()),r=new Set(this.watchers.keys());for(let i of t)r.has(i)||this.watchFile(i);for(let i of r)t.has(i)||(this.unwatchFile(i),u.info(`[ConfigFileWatcher] Stopped watching: ${i}`));u.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!sr.existsSync(t)){u.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=sr.watch(t,r=>{r==="change"&&this.onBuildProfileChanged()}),this.buildProfileWatcher.on("error",r=>{u.error(`[ConfigFileWatcher] build-profile.json5 watch error: ${r.message}`)}),u.info(`[ConfigFileWatcher] Watching module registry: ${t}`)}catch(r){u.error(`[ConfigFileWatcher] Failed to watch build-profile.json5: ${r instanceof Error?r.message:String(r)}`)}}emitModuleAddedEvents(t,r){for(let i of t){let o=Je.resolve(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:o,relativePath:i.srcPath,timestamp:r,moduleName:i.name})}}emitModuleRemovedEvents(t,r){for(let i of t){let o=Je.resolve(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:o,relativePath:i.srcPath,timestamp:r,removedModuleName:i.name})}}emitModuleRenamedEvents(t,r){for(let i of t){let o=Je.resolve(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:o,relativePath:i.after.srcPath,timestamp:r,moduleName:i.after.name,removedModuleName:i.before.name})}}emitModuleMovedEvents(t,r){for(let i of t){let o=Je.resolve(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:o,relativePath:i.after.srcPath,timestamp:r,moduleName:i.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let r=Date.now();this.emitModuleAddedEvents(t.added,r),this.emitModuleRemovedEvents(t.removed,r),this.emitModuleRenamedEvents(t.renamed,r),this.emitModuleMovedEvents(t.moved,r)}onBuildProfileChanged(){let t="__build_profile__",r=this.debounceTimers.get(t);r&&clearTimeout(r);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(o);if(s===this.lastModulesSnapshot){u.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,o);this.lastModules=o,this.lastModulesSnapshot=s,u.info(`[ConfigFileWatcher] build-profile.json5 modules changed, added=${a.added.length}, removed=${a.removed.length}, renamed=${a.renamed.length}, moved=${a.moved.length}`),this.processBuildProfileDiff(a)},this.debounceMs);this.debounceTimers.set(t,i)}computeModulesSnapshot(t){return t.map(i=>`${i.name}::${i.srcPath}`).sort().join("|")}diffModules(t,r){let i=this.buildModuleMatchState(r),o={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,i),this.matchRenamedModules(t,i,o),this.matchMovedModules(t,i,o),this.collectRemovedModules(t,i,o),this.collectAddedModules(r,i,o),o}buildModuleMatchState(t){let r=new Map,i=new Map;for(let o of t)r.set(o.srcPath,o),i.set(o.name,o);return{matchedOld:new Set,matchedNew:new Set,newBySrc:r,newByName:i}}matchExactModules(t,r){for(let i of t){let o=r.newBySrc.get(i.srcPath);o&&o.name===i.name&&(r.matchedOld.add(i),r.matchedNew.add(o))}}matchRenamedModules(t,r,i){for(let o of t){if(r.matchedOld.has(o))continue;let s=r.newBySrc.get(o.srcPath);s&&!r.matchedNew.has(s)&&s.name!==o.name&&(i.renamed.push({before:o,after:s}),r.matchedOld.add(o),r.matchedNew.add(s))}}matchMovedModules(t,r,i){for(let o of t){if(r.matchedOld.has(o))continue;let s=r.newByName.get(o.name);s&&!r.matchedNew.has(s)&&s.srcPath!==o.srcPath&&(i.moved.push({before:o,after:s}),r.matchedOld.add(o),r.matchedNew.add(s))}}collectRemovedModules(t,r,i){for(let o of t)r.matchedOld.has(o)||i.removed.push(o)}collectAddedModules(t,r,i){for(let o of t)r.matchedNew.has(o)||i.added.push(o)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let r=tt(t);if(typeof r!="object"||r===null)return[];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"}):[]}catch(r){return u.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${r instanceof Error?r.message:String(r)}`),[]}}collectWatchTargets(){let t=[],r=Je.join(this.projectRoot,F.OH_PACKAGE_JSON5);sr.existsSync(r)&&t.push(r);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=Je.resolve(this.projectRoot,o.srcPath),a=Je.join(s,F.OH_PACKAGE_JSON5);sr.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return Je.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=sr.readFileSync(t,"utf-8");return DR("sha256").update(r).digest("hex")}catch{return null}}watchFile(t){if(!this.watchers.has(t))try{let r=this.computeFileHash(t);r&&this.contentHashes.set(t,r);let i=sr.watch(t,o=>{o==="change"&&this.onFileChanged(t)});i.on("error",o=>{u.error(`[ConfigFileWatcher] Watch error for ${t}: ${o.message}`)}),this.watchers.set(t,i)}catch(r){u.error(`[ConfigFileWatcher] Failed to watch ${t}: ${r instanceof Error?r.message:String(r)}`)}}unwatchFile(t){let r=this.watchers.get(t);r&&(r.close(),this.watchers.delete(t)),this.contentHashes.delete(t);let i=this.debounceTimers.get(t);i&&(clearTimeout(i),this.debounceTimers.delete(t))}onFileChanged(t){let r=this.debounceTimers.get(t);r&&clearTimeout(r);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.computeFileHash(t);if(!o){u.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===o){u.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,o),u.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:Je.basename(t),relativePath:Je.relative(this.projectRoot,t),timestamp:Date.now()};this.emit("configChanged",a)},this.debounceMs);this.debounceTimers.set(t,i)}stop(){for(let[,t]of this.watchers)t.close();this.watchers.clear(),this.buildProfileWatcher&&(this.buildProfileWatcher.close(),this.buildProfileWatcher=null);for(let t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.contentHashes.clear(),u.info("[ConfigFileWatcher] All watchers stopped")}};import*as xr from"fs";import*as Dt from"path";import{createHash as RR}from"crypto";import{EventEmitter as TR}from"events";var Ka=class extends TR{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=Dt.join(t,Eo)}dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!xr.existsSync(this.depMapDir)){u.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=xr.watch(this.depMapDir,{recursive:!0},(t,r)=>this.onDirEvent(t,r)),this.dirWatcher.on("error",t=>{u.error(`[DependencyMapWatcher] Directory watch error for ${this.depMapDir}: ${t.message}`)})}catch(t){u.error(`[DependencyMapWatcher] Failed to watch directory ${this.depMapDir}: ${t instanceof Error?t.message:String(t)}`);return}this.pollInterval=setInterval(()=>this.scanAllCacheFiles(),2500),u.info(`[DependencyMapWatcher] Started, watching directory (recursive): ${this.depMapDir}, modules: [${this.lastModules.map(t=>t.name).join(", ")}]`)}canonicalPath(t){return le(Dt.resolve(t))}onDirEvent(t,r){if(!r||typeof r!="string")return;let i=r.replace(/\\/g,"/"),o;if(i===F.OH_PACKAGE_JSON5)o="root-oh-package";else if(i===mn)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=Dt.join(this.depMapDir,r);xr.existsSync(s)&&this.scheduleDebouncedFullScan()}stop(){this.dirWatcher&&(this.dirWatcher.close(),this.dirWatcher=null),this.fullScanTimer&&(clearTimeout(this.fullScanTimer),this.fullScanTimer=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.coalesceTimer&&(clearTimeout(this.coalesceTimer),this.coalesceTimer=null),this.pendingTags=[],this.pendingRenames=[],this.contentHashes.clear(),this.initialScanDone=!1,u.info("[DependencyMapWatcher] All watchers stopped")}scheduleDebouncedFullScan(){this.fullScanTimer&&clearTimeout(this.fullScanTimer),this.fullScanTimer=setTimeout(()=>{this.fullScanTimer=null,this.scanAllCacheFiles()},this.debounceMs)}scanAllCacheFiles(){let t=Dt.join(this.depMapDir,F.OH_PACKAGE_JSON5),r=Dt.join(this.depMapDir,mn),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...i.map(s=>({path:(E.assertModuleName(s.name),Dt.join(this.depMapDir,s.name,F.OH_PACKAGE_JSON5)),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!xr.existsSync(s))continue;let c=this.canonicalPath(s),l=this.computeFileHash(s);if(!l)continue;let d=this.contentHashes.get(c);if(!this.initialScanDone){this.contentHashes.set(c,l);continue}d!==l&&(this.contentHashes.set(c,l),u.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=Dt.join(this.depMapDir,mn);try{let r=tt(t);if(typeof r!="object"||r===null)return[];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"}):[]}catch(r){return u.warn(`[DependencyMapWatcher] Failed to parse dependencyMap.json5: ${r instanceof Error?r.message:String(r)}`),[]}}scheduleCoalescedReload(t){this.pendingTags.push(t),t==="dep-map-json"&&this.applyDepMapJsonDiff(),this.coalesceTimer&&clearTimeout(this.coalesceTimer),this.coalesceTimer=setTimeout(()=>{this.coalesceTimer=null,this.flushPendingReload()},this.coalesceMs)}collectPendingState(){let t=this.pendingTags,r=this.pendingRenames;return this.pendingTags=[],this.pendingRenames=[],{tags:t,renameEntries:r}}processTagsIntoSets(t,r,i,o){for(let s of t)s.startsWith("module:")?(i.add(s.substring(7)),r.add("moduleDepsChanged")):s.startsWith("dep-added:")?(i.add(s.substring(10)),r.add("moduleAdded")):s.startsWith("dep-removed:")&&(o.add(s.substring(12)),r.add("moduleRemoved"))}processRenameEntries(t,r,i,o,s){for(let a of t)s.push(a.info),i.add(a.info.newName),o.add(a.info.oldName),r.add(a.kind)}buildAddedNamesSet(t,r){let i=new Set;for(let o of t)o.startsWith("dep-added:")&&i.add(o.substring(10));for(let o of r)i.add(o.info.newName);return i}emitIncrementalReload(t,r,i,o,s){u.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...r].join(",")}], removed=[${[...i].join(",")}], added=[${[...o].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...r],removedModuleNames:[...i],addedModuleNames:[...o],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:r}=this.collectPendingState();if(t.length===0&&r.length===0)return;if(u.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${r.length}`),t.includes("root-oh-package")){u.info("[DependencyMapWatcher] Root oh-package.json5 in batch \u2192 full reload"),this.emit("reload",{fullReload:!0,kinds:["projectDepsChanged"]});return}let i=new Set,o=new Set,s=new Set,a=[];this.processTagsIntoSets(t,i,o,s),this.processRenameEntries(r,i,o,s,a);for(let l of o)s.delete(l);if(o.size===0&&s.size===0&&a.length===0){u.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,r);this.emitIncrementalReload(i,o,s,c,a)}normalizeSrcPath(t){return le(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let r=new Map(t.map(o=>[o.name,o])),i=new Map(t.map(o=>[this.normalizeSrcPath(o.srcPath),o]));return{byName:r,bySrcPath:i}}detectModuleRenames(t,r,i,o){for(let[s,a]of t){let c=r.get(s);if(!c||c.name===a.name)continue;this.pendingRenames.push({kind:"moduleRenamed",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleRenamed"}}),i.add(a.name),o.add(c.name);let l=(E.assertModuleName(a.name),Dt.join(this.depMapDir,a.name,F.OH_PACKAGE_JSON5));this.contentHashes.delete(this.canonicalPath(l)),u.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,r,i,o){for(let[s,a]of t){if(i.has(s))continue;let c=r.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),i.add(s),o.add(s),u.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,r,i){for(let[o]of t)i.has(o)||r.has(o)||(this.pendingTags.push(`dep-added:${o}`),i.add(o))}detectRemovedModules(t,r,i){for(let[o]of t)if(!i.has(o)&&!r.has(o)){this.pendingTags.push(`dep-removed:${o}`),i.add(o);let s=(E.assertModuleName(o),Dt.join(this.depMapDir,o,F.OH_PACKAGE_JSON5));this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(i=>i.startsWith("dep-")),r=this.pendingRenames.map(i=>`${i.kind}(${i.info.oldName}\u2192${i.info.newName})`);u.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${r.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:r,bySrcPath:i}=this.buildModuleLookupMaps(this.lastModules),{byName:o,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(i,s,a,c),this.detectModuleMoves(r,o,a,c),this.detectAddedModules(o,r,c),this.detectRemovedModules(r,o,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let r=xr.readFileSync(t,"utf-8");return RR("sha256").update(r).digest("hex")}catch{return null}}};import*as Ht from"fs";import*as Xa from"path";import{EventEmitter as xR}from"events";var qd={Created:1,Changed:2,Deleted:3},LR=new Set(["oh_modules","node_modules","build",".hvigor",".git",".idea",".cxx",".preview"]);function NR(n){let e=n.replace(/\\/g,"/");return e.endsWith("/ets")&&e.includes("/src/")}var Za=class extends xR{projectRoot;debounceMs;pollMs;sourceDirs=[];watchers=new Map;snapshot=new Map;debounceTimer=null;pollInterval=null;initialScanDone=!1;constructor(e,t=500,r=1e4){super(),this.projectRoot=e,this.debounceMs=t,this.pollMs=r}start(){if(this.sourceDirs=this.discoverSourceDirs(),this.sourceDirs.length===0){u.warn("[SourceFileWatcher] No src/main/ets dir found, skip watching");return}this.refreshSnapshot(),this.initialScanDone=!0;for(let e of this.sourceDirs)this.addSourceDirWatcher(e);this.pollInterval=setInterval(()=>this.scanAndEmit(),this.pollMs),u.info(`[SourceFileWatcher] Started, watching ${this.sourceDirs.length} source dir(s), ${this.snapshot.size} ets file(s)`)}stop(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null);for(let[,e]of this.watchers)e.close();this.watchers.clear(),this.snapshot.clear(),this.initialScanDone=!1,u.info("[SourceFileWatcher] Stopped")}addSourceDirWatcher(e){if(!this.watchers.has(e))try{let t=Ht.watch(e,{recursive:!0},(r,i)=>this.onFsEvent(i));t.on("error",r=>{u.error(`[SourceFileWatcher] watch error for ${e}: ${r.message}`)}),this.watchers.set(e,t)}catch(t){u.error(`[SourceFileWatcher] Failed to watch ${e}: ${t instanceof Error?t.message:String(t)}`)}}refreshSourceDirs(){if(!this.initialScanDone)return;let e=this.discoverSourceDirs(),t=new Set(this.sourceDirs),r=new Set(e),i=e.filter(s=>!t.has(s)),o=[...t].filter(s=>!r.has(s));if(!(i.length===0&&o.length===0)){for(let s of i)this.addSourceDirWatcher(s);for(let s of o){let a=this.watchers.get(s);a&&(a.close(),this.watchers.delete(s))}this.sourceDirs=e,this.refreshSnapshot(),u.info(`[SourceFileWatcher] Module dirs changed: +${i.length} -${o.length}, now ${this.sourceDirs.length} source dir(s)`)}}discoverSourceDirs(){let e=[];return this.collectSourceDirs(Xa.resolve(this.projectRoot),e,new Set,new Set),e}collectSourceDirs(e,t,r,i){let o;try{o=Ht.realpathSync(e)}catch{return}if(i.has(o))return;i.add(o);let s;try{s=Ht.readdirSync(e,{withFileTypes:!0})}catch{return}for(let a of s){if(!a.isDirectory()||LR.has(a.name))continue;let c=Xa.resolve(e,a.name);if(!NR(c)){this.collectSourceDirs(c,t,r,i);continue}r.has(c)||(r.add(c),t.push(c))}}onFsEvent(e){!e||typeof e!="string"||e.replace(/\\/g,"/").toLowerCase().endsWith(".ets")&&this.scheduleScan()}scheduleScan(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.scanAndEmit()},this.debounceMs)}scanAndEmit(){if(!this.initialScanDone)return;let e=this.diffScan();e.length>0&&this.emit("sourceChanged",{changes:e})}refreshSnapshot(){let e=new Map;for(let t of this.sourceDirs)this.collectEtsFiles(t,e);this.snapshot=e}diffScan(){let e=new Map;for(let r of this.sourceDirs)this.collectEtsFiles(r,e);let t=[];for(let[r,i]of e){let o=this.snapshot.get(r);o?(o.mtimeMs!==i.mtimeMs||o.size!==i.size)&&t.push({uri:vt(r),type:qd.Changed}):t.push({uri:vt(r),type:qd.Created})}for(let[r]of this.snapshot)e.has(r)||t.push({uri:vt(r),type:qd.Deleted});return this.snapshot=e,t}collectEtsFiles(e,t){this.collectEtsFilesInto(e,t,new Set)}collectEtsFilesInto(e,t,r){let i;try{i=Ht.realpathSync(e)}catch{return}if(r.has(i))return;r.add(i);let o;try{o=Ht.readdirSync(e,{withFileTypes:!0})}catch{return}for(let s of o){let a=Xa.resolve(e,s.name);if(s.isDirectory()){this.collectEtsFilesInto(a,t,r);continue}!s.isFile()||!s.name.toLowerCase().endsWith(".ets")||this.recordSnapshot(a,t)}}recordSnapshot(e,t){let r;try{r=Ht.statSync(e)}catch{return}t.set(e,{mtimeMs:r.mtimeMs,size:r.size})}};import{spawn as MR}from"child_process";var Uy=["install","--all"];function By(n,e){let t=n.split(/\r?\n/),r=t.pop()??"";for(let i of t)i&&(u.info("[ohpm] %s",i),e?.(i));return r}async function OR(n,e,t,r,i){return new Promise(o=>{u.info("[ohpm] spawning: %s %s %s, cwd=%s",n,e,Uy.join(" "),t);let s=MR(n,[e,...Uy],{cwd:t,env:{...process.env,DEVECO_SDK_HOME:r},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),a="",c="";s.stdout?.on("data",l=>{a=By(a+l.toString(),i)}),s.stderr?.on("data",l=>{c=By(c+l.toString(),i)}),s.on("close",l=>{a&&(u.info("[ohpm] %s",a),i?.(a)),c&&(u.info("[ohpm] %s",c),i?.(c)),u.info("[ohpm] process exited, code=%s",l),o({exitCode:l??-1})}),s.on("error",l=>{u.error("[ohpm] process error: %s",l.message),o({exitCode:-1})})})}async function Wy(n,e,t,r,i){try{if(!t)return u.error("node \u8DEF\u5F84\u4E0D\u5B58\u5728"),!1;if(!r)return u.error("ohpm (pm-cli.js) \u4E0D\u5B58\u5728"),!1;let{exitCode:o}=await OR(t,r,n,e,i);return o===0?(u.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(u.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",o),!1)}catch(o){return u.error("ohpm \u5B89\u88C5\u5F02\u5E38",o),!1}}var Vy={UNINITIALIZED:-32099,UNKNOWN:-32e3},Co=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,Vy.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,Vy.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var pi=class{config;lspProxy=null;configWatcher=null;depMapWatcher=null;sourceFileWatcher=null;isInitialized=!1;lastEditorOpenFiles=[];onMessage=()=>{};onConfigChanged=null;disposeOnce=null;get aceServerPid(){return this.lspProxy?.lspPid??null}constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}async start(e=[],t){this.lastEditorOpenFiles=e;try{this.startConfigWatcher(),this.startLspProxy(e,t)}catch(r){throw u.error(`[ArktsLspManager] start() synchronous failure: ${r instanceof Error?r.message:String(r)}`),r}}sendNotification(e){if(!this.lspProxy){u.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){u.warn("[ArktsLspManager] sendRequest before LSP ready, dropped");return}this.lspProxy.sendRequest(e)}async diagnostic(e){if(!this.lspProxy)throw new Error("[ArktsLspManager] diagnostic before LSP ready");return this.lspProxy.diagnostic(e)}async sendFeatureRequest(e,t){if(!this.useStandardProtocol)throw new Error(`Language feature '${e}' is not supported on the installed DevEco Studio. The standard LSP protocol entry (plugins/openharmony/ace-server/out/standardIndex/index.js) was not found. Please upgrade DevEco Studio to version 26.0.0.610 or later to use this tool.`);if(!this.lspProxy)throw new Error("LSP not ready");return this.lspProxy.sendFeatureRequest(e,t)}get useStandardProtocol(){return this.config.useStandardProtocol}onAsyncOpenFile(e){this.lspProxy?.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.lspProxy?.closeFileLegacy(e,t)}registerDiagnosticCallback(e){this.lspProxy?.registerDiagnosticCallback(e)}static async handleSyncProject(e,t,r,i,o,s,a,c){if(u.info("[ArktsLspManager] Received arkts/syncProject"),!e||!t)return u.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let l=s?.skipHvigorSync===!0,d=await ds(e,async()=>await Wy(e,t,r??"",i??"",a)?l?(u.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await em(e,t,r??"",o??"",c)?(u.info("[ArktsLspManager] syncProject completed successfully"),{status:"success"}):(u.error("[ArktsLspManager] syncProject failed"),{status:"failed",reason:"hvigor sync failed"}):(u.error("[ArktsLspManager] ohpm install failed"),{status:"failed",reason:"ohpm install failed"}));return d.acquired?d.result:(u.info("[ArktsLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){try{this.configWatcher?.stop()}catch(e){u.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){u.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}try{this.sourceFileWatcher?.stop()}catch(e){u.warn(`[ArktsLspManager] sourceFileWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.sourceFileWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){u.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e,t){let r=new Ja(this.config.sdkPath,this.config.arktsLangServerPath,this.config.workspaceRoot,this.config.indexLogPath,this.config.nodeMaxOldSpaceSize,this.config.useStandardProtocol,this.config.nodePath,this.config.useSocket??!1);r.setOnMessage(i=>this.handleLspMessage(i)),r.start(e,i=>this.handleLspInitialized(i),t),this.lspProxy=r}handleLspInitialized=e=>{if(this.isInitialized=e,e)u.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.startSourceFileWatcher(),this.onMessage({jsonrpc:x,method:v.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();u.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?Co.uninitialized(t):Co.unknown();this.onMessage({jsonrpc:x,method:v.ARKTS_INITIALIZATION_FAILED,params:r.toJsonRpcErrorParams()}),this.lspProxy=null}};handleLspMessage(e){this.onMessage(e)}maybeRetryLspAfterSuccessfulSync(){this.isInitialized||this.lspProxy!==null||(u.info("[ArktsLspManager] Retrying LSP startup after successful sync"),this.onMessage({jsonrpc:x,method:v.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new Ya(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new Ka(this.config.workspaceRoot),this.depMapWatcher.on("reload",e=>{if(!this.lspProxy){u.warn("[ArktsLspManager] LspServerProxy not initialized, skip reload");return}let r=this.lspProxy.reloadDependenciesOnly(e).map(i=>({modulePath:i.modulePath??"",dependencies:i.dependencies??{},dynamicDependencies:i.dynamicDependencies??{}}));this.onMessage({jsonrpc:x,method:v.ARKTS_SYNC_COMPLETED,params:{success:!0,moduleSet:r}})}),this.depMapWatcher.start())}startSourceFileWatcher(){this.sourceFileWatcher||(this.sourceFileWatcher=new Za(this.config.workspaceRoot),this.sourceFileWatcher.on("sourceChanged",e=>{if(!this.lspProxy){u.warn("[ArktsLspManager] LspServerProxy not initialized, skip didChangeWatchedFiles");return}this.sendNotification({jsonrpc:x,method:v.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:e.changes}}),u.info(`[ArktsLspManager] Notified didChangeWatchedFiles: ${e.changes.length} change(s)`)}),this.sourceFileWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){u.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),e.kind!==4&&this.sourceFileWatcher?.refreshSourceDirs(),this.onConfigChanged?.()}};var _R=10080*60*1e3,FR=7200*60*1e3,$R=120*1e3,mi=class n{manager=null;get aceServerPid(){return this.manager?.aceServerPid??null}initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;sdkPath;arktsLangServerPath;nodePath;nodeMaxOldSpaceSize;onConfigChangedCallback=null;onInitProgress=null;onDepParseProgress=null;useStandardProtocol=!0;useSocket;diagnosticWaiters=new Map;documentVersion=0;static FEATURE_METHOD_MAP={hover:v.HOVER,definition:v.DEFINITION,declaration:v.DECLARATION,references:v.REFERENCES,implementation:v.IMPLEMENTATION,completion:v.COMPLETION,signatureHelp:v.SIGNATURE_HELP,documentHighlight:v.DOCUMENT_HIGHLIGHT};constructor(e,t,r,i,o,s=!1){this.projectPath=e,this.sdkPath=t,this.arktsLangServerPath=r,this.nodeMaxOldSpaceSize=i,this.nodePath=o,this.useSocket=s}setOnConfigChanged(e){this.onConfigChangedCallback=e}setOnInitProgress(e){this.onInitProgress=e}setOnDepParseProgress(e){this.onDepParseProgress=e}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initializing=!0,this.initPromise=this.doInitialize().then(()=>{this.initialized=!0}).finally(()=>{this.initializing=!1}),await this.initPromise}}async doInitialize(){let{harmonyRoot:e,arktsLangServerPath:t,useStandardProtocol:r}=this.resolveProjectAndDeveco();this.useStandardProtocol=r;let i=we(e),{logPath:o,indexPath:s}=this.getLogAndIndexPath(i);setImmediate(()=>{Wc(s,_R,"[ArkTS-Check]"),Wc(o,FR,"[ArkTS-Check]")}),fs(o);let a=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,c=Number.isNaN(a)?void 0:a;h.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${c??"undefined \u2192 dynamic formula applies"}`);let l=this.sdkPath;h.info(`[ArktsCheck] sdkPath=${l}, arktsLangServerPath=${t}, useStandardProtocol=${r}, useSocket=${this.useSocket}`),this.manager=new pi({sdkPath:l,arktsLangServerPath:t,workspaceRoot:le(i),indexLogPath:s,nodeMaxOldSpaceSize:c,useStandardProtocol:r,nodePath:this.nodePath,useSocket:this.useSocket}),this.manager.setOnMessage(d=>this.handleLspMessage(d)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((d,g)=>{this.initResolve=d,this.initReject=g,this.armInitTimer(We),this.manager.start([],this.onDepParseProgress??void 0).catch(y=>{let I=y instanceof Error?y:new Error(String(y));this.failInit(I)})})}resolveProjectAndDeveco(){let e=Wt(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.arktsLangServerPath;if(!t)throw new Error("arkts-lang-server path not found");let r=Jo(t);return{harmonyRoot:e,arktsLangServerPath:t,useStandardProtocol:r}}armInitTimer(e){this.initDeadlineTimer&&clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=setTimeout(()=>{let t=this.initReject;this.clearInitHandlers(),t?.(new Error("LSP initialize timeout"))},e)}clearInitHandlers(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async checkFile(e){this.initialized||await this.initialize();let t=this.manager;if(!t)throw new Error("ArktsLspManager not initialized");let r=vt(e),i=await gt.promises.readFile(e,"utf8"),s=`deveco.apptool.${Re.extname(e).replace(/^\./,"")||"plaintext"}`;return t.useStandardProtocol?this.checkFileStandard(t,r,i,s):this.checkFileLegacy(t,e,r,i,s)}async checkFileStandard(e,t,r,i){h.debug(`textDocument/didOpen uri=${t} content_len=${r.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:r,languageId:i,version:++this.documentVersion}});try{h.debug(`textDocument/diagnostic uri=${t}`);let o=await e.diagnostic({textDocument:{uri:t}});return jR(o)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:t}})}}async checkFileLegacy(e,t,r,i,o){let s=r;e.registerDiagnosticCallback(r);let a=new Promise((c,l)=>{let d=setTimeout(()=>{this.diagnosticWaiters.delete(s)&&l(new Error("Wait for diagnostics timeout"))},$R);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:d})});h.debug(`textDocument/didOpen(legacy) uri=${r} content_len=${i.length}`),e.onAsyncOpenFile({textDocument:{uri:r,text:i,languageId:o,version:i.length},editorFiles:[r],isFromEditor:!1});try{return await a}finally{e.closeFileLegacy(r,!1)}}async handleCall(e){if(!this.initialized)return this.buildNotReadyResponse();let t=[],r=[],i=this.collectValidFiles(e.files,t);return i.length===0?{content:[{type:"text",text:t.length>0?t.join(`
|
|
1320
|
+
`):"No valid .ets files"}],isError:!0}:(await this.runDiagnosticsForFiles(i,t,r),this.formatCallResult(t,r))}async handleLspFeature(e,t){if(!this.initialized)return this.buildNotReadyResponse();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`File does not exist or is not a .ets file: ${t.file}`}],isError:!0};let i=n.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};h.info(`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){let s=o instanceof Error?o.message:String(o);return h.error(`handleLspFeature ${e} failed: ${s}`),{content:[{type:"text",text:`${e} failed: ${s}`}],isError:!0}}}async handleWorkspaceSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();h.info(`handleWorkspaceSymbol: query="${e}"`);try{let t=await this.manager.sendFeatureRequest(v.WORKSPACE_SYMBOL,{query:e});return{content:[{type:"text",text:t==null?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(t,null,2)}`}]}}catch(t){let r=t instanceof Error?t.message:String(t);return h.error(`handleWorkspaceSymbol failed: ${r}`),{content:[{type:"text",text:`workspaceSymbol failed: ${r}`}],isError:!0}}}async handleWorkspaceSymbolRaw(e){if(!this.initialized)return null;try{let t=await this.manager.sendFeatureRequest(v.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return h.error(`handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a .ets file: ${e}`}],isError:!0};h.info(`handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(v.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){let i=r instanceof Error?r.message:String(r);return h.error(`handleDocumentSymbol failed: ${i}`),{content:[{type:"text",text:`documentSymbol failed: ${i}`}],isError:!0}}}async handleCallHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a .ets file: ${e.file}`}],isError:!0};h.info(`handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,async o=>{let s=await this.manager.sendFeatureRequest(v.PREPARE_CALL_HIERARCHY,{textDocument:{uri:o},position:{line:e.line,character:e.character}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],calls:[]};let c=e.direction==="incoming"?v.INCOMING_CALLS:v.OUTGOING_CALLS,l=[];for(let d of a){let g=await this.manager.sendFeatureRequest(c,{item:d});Array.isArray(g)?l.push(...g):g&&l.push(g)}return{items:a,calls:l}});return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){let i=r instanceof Error?r.message:String(r);return h.error(`handleCallHierarchy failed: ${i}`),{content:[{type:"text",text:`callHierarchy failed: ${i}`}],isError:!0}}}async withOpenFile(e,t){let r=vt(e),i=await gt.promises.readFile(e,"utf8"),s=`deveco.apptool.${Re.extname(e).replace(/^\./,"")||"plaintext"}`;h.debug(`withOpenFile didOpen uri=${r} len=${i.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:r,text:i,languageId:s,version:++this.documentVersion}});try{return await t(r)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:r},isManual:!1})}}resolveSingleFile(e){let t=Re.isAbsolute(e)?e:Re.join(this.projectPath,e);return!gt.existsSync(t)||!gt.statSync(t).isFile()||!t.endsWith(".ets")?null:t}buildNotReadyResponse(){return{content:[{type:"text",text:this.initializing?"LSP is initializing, please retry later":this.projectPath?"LSP not initialized":"No project path configured; set the PROJECT_PATH parameter"}],isError:!0}}collectValidFiles(e,t){let r=Re.resolve(this.projectPath),i=[];for(let o of e){let s=Re.resolve(Re.isAbsolute(o)?o:Re.join(r,o));if(!gt.existsSync(s)){t.push(`File does not exist: ${o}`);continue}if(!gt.statSync(s).isFile()){t.push(`Not a regular file: ${o}`);continue}if(!s.endsWith(".ets")){t.push(`Not a .ets file: ${o}`);continue}i.push(s)}return i}async runDiagnosticsForFiles(e,t,r){for(let i of e){await up(500);try{let o=await this.checkFile(i);r.push(HR(i,o))}catch(o){t.push(`${i} => wait for diagnostics failed: ${o.message}`)}}}formatCallResult(e,t){let r=[];e.length>0&&r.push(e.join(`
|
|
1318
1321
|
`)),t.length>0&&r.push(t.join(`
|
|
1319
1322
|
`));let i=r.join(`
|
|
1320
|
-
`).trim(),o=e.length>0;return!o&&t.length===0&&(i="No diagnostics collected"),{content:[{type:"text",text:i}],isError:o}}async shutdown(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(t){h.warn(`Failed to dispose ArktsLspManager: ${t}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,r=t.method;if(r)switch(r){case"textDocument/publishDiagnostics":
|
|
1321
|
-
`):"No valid C/C++ files"}],isError:!0};for(let c of i){await
|
|
1323
|
+
`).trim(),o=e.length>0;return!o&&t.length===0&&(i="No diagnostics collected"),{content:[{type:"text",text:i}],isError:o}}async shutdown(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(t){h.warn(`Failed to dispose ArktsLspManager: ${t}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,r=t.method;if(r)switch(r){case"textDocument/publishDiagnostics":this.handleDiagnosticsNotification(t.params);break;case"arkts/indexingProgress":this.handleIndexingProgress(t.params);break;case Dn.INDEXING_PROGRESS_UPDATE:this.handleIndexingProgress(t.params);break;case v.PROGRESS:this.handleProgressNotification(t.params);break;case"arkts/initialized":{h.info("Received arkts/initialized");let i=this.initResolve;this.clearInitHandlers(),i?.();break}case"arkts/initializationFailed":{let i=t.params?.message??"unknown";h.error(`LSP initialization failed: ${i}`);let o=this.initReject;this.clearInitHandlers(),o?.(new Error(`LSP initialize failed: ${i}`));break}case"workspace/didChangeConfiguration":h.info("Received workspace/didChangeConfiguration, sync deferred to next check");break;default:break}}handleIndexingProgress(e){let t=e;if(t?.current!=null&&t?.total!=null&&t.total>0){let r=Math.round(t.current/t.total*100),i=`indexing ${t.current}/${t.total} modules`+(t.moduleName?` (${t.moduleName})`:"");this.onInitProgress?.(i,r)}this.initResolve&&this.armInitTimer(We)}handleProgressNotification(e){let t=e?.value;if(t&&(t.kind==="report"||t.kind==="begin")){let r=typeof t.percentage=="number"?Math.round(t.percentage):null,i=t.message??(r!==null?`${r}%`:"indexing");this.onInitProgress?.(i,r)}this.initResolve&&this.armInitTimer(We)}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let r=this.popDiagnosticWaiter(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.popDiagnosticWaiter(s)}if(!r)return;if(typeof e.errorMessage=="string"){h.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),r.resolve({errorMessage:e.errorMessage});return}let i=e.diagnostics,o=Array.isArray(i)?i.length:0;h.debug(`diagnostics received uri=${t} count=${o}`),r.resolve(Array.isArray(i)?i:[])}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}getLogAndIndexPath(e){try{let t=Re.join(lr(),"ArkTSCheck"),r=Re.join(t,"mapping-config.properties"),i=pp(e,r),o=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=Re.join(t,"lsp-log",String(i),o),a=Re.join(t,"lsp-index",String(i));return gt.mkdirSync(s,{recursive:!0}),gt.mkdirSync(a,{recursive:!0}),{logPath:we(s),indexPath:we(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function jR(n){if(Array.isArray(n))return n;if(n&&typeof n=="object"){let e=n;if(e.kind==="full"&&Array.isArray(e.items))return e.items}return[]}function HR(n,e){if(Array.isArray(e))return e.length===0?`${n} => no diagnostics`:`${n} => Diagnostic: ${JSON.stringify(e)}`;if(e&&typeof e=="object"&&typeof e.errorMessage=="string"){let t=e.errorMessage;return`${n} diagnostic failed, error_message: ${t}`}return`${n} => diagnostic failed, result: ${JSON.stringify(e)}`}import*as Lr from"fs";import*as gn from"path";import{z as zd}from"zod";function fi(){return{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}}function Qa(n,e){let t=e instanceof Error?e.message:String(e);return h.error(`[CppLsp] ${n} failed: ${t}`),{content:[{type:"text",text:`${n} failed: ${t}`}],isError:!0}}var UR=500,hi=class{manager;constructor(e){this.manager=e}static getToolDefinition(){return{name:"check_cpp_files",description:"Perform static syntax checks on the provided C/C++ files and return clangd diagnostics.",inputSchema:zd.object({files:zd.array(zd.string()).describe('List of C/C++ file paths to check, format: ["file1.cpp","file2.hpp",...]')})}}async handleCall(e){if(!this.manager.ready)return fi();let t=[],r=[],i=this.collectValidFiles(e.files,t);if(i.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
|
|
1324
|
+
`):"No valid C/C++ files"}],isError:!0};for(let c of i){await WR(UR);try{let l=await this.checkFile(c);r.push(BR(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(`
|
|
1322
1325
|
`)),r.length>0&&s.push(r.join(`
|
|
1323
1326
|
`));let a=s.join(`
|
|
1324
|
-
`).trim();return!o&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:o}}async checkFile(e){let t=gt(e),r=await Tr.promises.readFile(e,"utf8"),i=$o(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=mn.resolve(this.manager.projectRoot),i=[];for(let o of e){let s=mn.resolve(mn.isAbsolute(o)?o:mn.join(r,o));if(!Tr.existsSync(s)){t.push(`File does not exist: ${o}`);continue}if(!Tr.statSync(s).isFile()){t.push(`Not a regular file: ${o}`);continue}if(!Wr(s)){t.push(`Not a supported C/C++ file: ${o}`);continue}try{i.push(Tr.realpathSync(s))}catch{i.push(s)}}return i}};function ID(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 AD(n){return new Promise(e=>setTimeout(e,n))}import*as ai from"fs";import*as _a from"path";var si=class n{manager;static FEATURE_METHOD_MAP={hover:v.HOVER,definition:v.DEFINITION,declaration:v.DECLARATION,references:v.REFERENCES,implementation:v.IMPLEMENTATION};constructor(e){this.manager=e}async handleLspFeature(e,t){if(!this.manager.ready)return ii();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};h.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 Oa(e,o)}}async handleWorkspaceSymbolRaw(e){if(!this.manager.ready)return null;try{let t=await this.manager.sendFeatureRequest(v.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return h.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return ii();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e}`}],isError:!0};h.info(`[ClangdLspTool] handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(v.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){return Oa("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return ii();if(e.direction==="outgoing")return{content:[{type:"text",text:"callHierarchy outgoing is not supported by clangd (incoming only)"}],isError:!0};let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e.file}`}],isError:!0};h.info(`[ClangdLspTool] handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,o=>this.fetchCallHierarchyResult(o,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return Oa("callHierarchy",r)}}async fetchCallHierarchyResult(e,t){let r=await this.manager.sendFeatureRequest(v.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(v.INCOMING_CALLS,{item:e});return Array.isArray(t)?t:t?[t]:[]}async withOpenFile(e,t){let r=gt(e),i=await ai.promises.readFile(e,"utf8"),o=$o(e);h.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=_a.isAbsolute(e)?e:_a.join(this.manager.projectRoot,e);return!ai.existsSync(t)||!ai.statSync(t).isFile()||!Wr(t)?null:t}};import{spawn as DD}from"child_process";import*as $a from"fs";import*as dy from"path";var RD=30*1e3,TD=30*1e3,Fa=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new Ir;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{u.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),u.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),u.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 kr(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(v.INITIALIZE,i,Xe),u.info("[ClangdLspProxy] initialize response received"),this.sendNotification(v.INITIALIZED,{}),t=!0}catch(r){this.lastStartErrorMessage=r instanceof Error?r.message:String(r),u.error(`[ClangdLspProxy] initialization failed: ${this.lastStartErrorMessage}`),await this.dispose()}e?.(t)}async hover(e){return this.sendLspRequest(v.HOVER,e)}async definition(e){return this.sendLspRequest(v.DEFINITION,e)}async declaration(e){return this.sendLspRequest(v.DECLARATION,e)}async references(e){return this.sendLspRequest(v.REFERENCES,e)}async implementation(e){return this.sendLspRequest(v.IMPLEMENTATION,e)}async documentSymbol(e){return this.sendLspRequest(v.DOCUMENT_SYMBOL,e)}async workspaceSymbol(e){return this.sendLspRequest(v.WORKSPACE_SYMBOL,e)}async prepareCallHierarchy(e){return this.sendLspRequest(v.PREPARE_CALL_HIERARCHY,e)}async incomingCalls(e){return this.sendLspRequest(v.INCOMING_CALLS,e)}async sendFeatureRequest(e,t){return this.sendLspRequest(e,t)}sendDidOpen(e){this.sendNotification(v.DID_OPEN,e)}sendDidChange(e){this.sendNotification(v.DID_CHANGE,e)}sendDidClose(e){this.sendNotification(v.DID_CLOSE,e)}sendNotification(e,t){if(!this.client){u.warn("[ClangdLspProxy] sendNotification before ready, dropped");return}this.client.sendNotification(e,t)}registerDiagnosticCallback(e){let t=this.normalizeClangdUri(e);if(this.diagnosticWaiters.has(t)){u.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}`))},TD);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(v.SHUTDOWN,null,3e3).catch(e=>{u.warn(`[ClangdLspProxy] shutdown request failed: ${e}`)}),this.sendNotification(v.EXIT,null),await this.client.waitForExitOrTimeout(300)}catch(e){u.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=${de(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];u.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=DD(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=kn(this.config.workspaceRoot),t=vt(e),r=dy.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.3.5-Test.1"},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=RD){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);u.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):u.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;u.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 v.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case v.PROGRESS:this.onMessage({jsonrpc:x,method:v.PROGRESS,params:e.params});break;case v.WINDOW_SHOW_MESSAGE:u.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case v.WINDOW_LOG_MESSAGE:u.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:x,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;u.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:x,method:v.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{$a.existsSync(this.config.logPath)||$a.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)),vt(r)}}catch{}return e}};import*as go from"path";import*as Sd from"fs";var yo=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){u.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(u.info("[ClangdLspManager] Received cpp/syncProject"),!e||!t)return u.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};if(pr(e).length===0)return u.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let a=o?.skipCompileNative===!0,c=await Ko(e,a?async()=>(u.info("[ClangdLspManager] compileNative skipped (C++ project up-to-date)"),{status:"success"}):async()=>n.executeCompileNative(e,t,r,i));return c.acquired?c.result:(u.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 Tp(e,t,r,i),u.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(o){let s=o instanceof Error?o.message:String(o);return u.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(Xe);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=jt(this.config.workspaceRoot);this.resolvedRoot=e?we(e):we(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();es(t);let r=this.config.clangdPath;if(!r){let s="clangd not found (install DevEco Studio / CLT)";u.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let i=this.config.compileCommandsDir??go.dirname(Br(this.resolvedRoot));try{Sd.mkdirSync(i,{recursive:!0})}catch(s){u.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${s}`)}u.info(`[ClangdLspManager] clangdPath: ${r}`),u.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),u.info(`[ClangdLspManager] compileCommandsDir: ${i}`);let o=new Fa({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,u.info("[ClangdLspManager] clangd initialized");let r=this.initResolve;this.clearInitHandlers(),r?.()}else{let r=t??this.proxy?.consumeStartErrorMessage()??"unknown error";u.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){u.warn("[ClangdLspManager] dispatchNotification: missing method");return}let i=t.params;switch(r){case v.DID_OPEN:this.proxy.sendDidOpen(i);break;case v.DID_CHANGE:this.proxy.sendDidChange(i);break;case v.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){u.warn(`[ClangdLspManager] proxy dispose error: ${t}`)}this.proxy=null}this.isInitialized=!1,this.initPromise=null}getLogPath(){try{let e=go.join(sr(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=go.join(e,"lsp-log",t);return Sd.mkdirSync(r,{recursive:!0}),we(r)}catch{return"auto"}}};function uy(n){let e=Zo(n);return u.info(`[SyncGuard] ${e.reason}`),e}var Pd=(s=>(s[s.IDLE=0]="IDLE",s[s.DISCOVERING=1]="DISCOVERING",s[s.SYNCING=2]="SYNCING",s[s.INITIALIZING=3]="INITIALIZING",s[s.READY=4]="READY",s[s.ERROR=5]="ERROR",s))(Pd||{}),py=(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))(py||{}),Ft=3,bd=600*1e3,Ed=100,ja=class{server;toolRouter;config={};arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";sdkPath="";arktsLangServerPath=null;nodePath="";ohpmJsPath="";hvigorJsPath="";clangdPath=null;initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;standardProtocolAvailable=!1;socketAvailable=!1;cppProjectState=0;cppInitPromise=null;cppNeedsReinit=!1;cppInitRetryCount=0;cppSyncSkippedDueToLock=!1;cppSyncSkipStartedAt=0;cppHasNoCppCode=!1;cppEnabled;cppCustomCompileCommandsDir;constructor(e={}){this.config=e,Vr(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),h.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",h.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,h.info(`Constructor: using configured path as startPath: '${t}'`));let i=jt(t);h.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,this.cppCustomCompileCommandsDir=os(this.config.cppCompileCommandsPath),h.info(`Constructor: sdkPath='${this.sdkPath}', arktsLangServerPath='${this.arktsLangServerPath??"(null)"}', cppEnabled=${this.cppEnabled}, cppCustomCompileCommandsDir='${this.cppCustomCompileCommandsDir??"(none)"}'`),this.server=new xD({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=hd(e.telemetry,()=>this.arktsCheckTool?.aceServerPid??null,()=>this.config.projectPath??"",()=>this.sdkPath??""),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:ve.object({target:ve.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:ve.object({files:ve.array(ve.string()).min(1).describe("List of source file paths to check, relative to the project root (absolute paths within the project are also accepted). Supports ArkTS and C/C++ files in the same call.")})},async e=>this.handleCheckCall(e))}registerLspFeatureTools(){if(!this.standardProtocolAvailable){h.info("Skip registering LSP feature tools (hover/definition/declaration/references/implementation, workspaceSymbol, documentSymbol, callHierarchy): standard LSP protocol unavailable (standardIndex/index.js not found). These tools require a DevEco Studio version that ships the standard LSP server entry.");return}let e=ve.object({file:ve.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:ve.number().describe("Line number (0-based)"),character:ve.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:ve.object({query:ve.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:ve.object({file:ve.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:ve.object({file:ve.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:ve.number().describe("Line number (0-based)"),character:ve.number().describe("Character offset in the line (0-based)"),direction:ve.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.arktsLangServerPath;if(!e)return h.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=Fo(e);return h.info(`ArktsCheck protocol: ${t?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${t})`),t}catch(e){return h.warn(`Failed to detect standard LSP protocol availability: ${e}`),!1}}async detectSocketAvailable(){try{let e=this.arktsLangServerPath;if(!e){this.socketAvailable=!1;return}this.socketAvailable=await $u(e,zr(this.nodePath)),h.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 h.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};if(t.length>Ed)return h.warn(`check tool called with ${t.length} files (max: ${Ed})`),{content:[{type:"text",text:`Too many files: ${t.length}. Maximum allowed is ${Ed}.`}],isError:!0};let{etsFiles:r,cppFiles:i,unsupported:o}=ND(t);o.length>0&&h.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(`
|
|
1327
|
+
`).trim();return!o&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:o}}async checkFile(e){let t=vt(e),r=await Lr.promises.readFile(e,"utf8"),i=Yo(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=gn.resolve(this.manager.projectRoot),i=[];for(let o of e){let s=gn.resolve(gn.isAbsolute(o)?o:gn.join(r,o));if(!Lr.existsSync(s)){t.push(`File does not exist: ${o}`);continue}if(!Lr.statSync(s).isFile()){t.push(`Not a regular file: ${o}`);continue}if(!Gr(s)){t.push(`Not a supported C/C++ file: ${o}`);continue}try{i.push(Lr.realpathSync(s))}catch{i.push(s)}}return i}};function BR(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 WR(n){return new Promise(e=>setTimeout(e,n))}import*as yi from"fs";import*as ec from"path";var gi=class n{manager;static FEATURE_METHOD_MAP={hover:v.HOVER,definition:v.DEFINITION,declaration:v.DECLARATION,references:v.REFERENCES,implementation:v.IMPLEMENTATION};constructor(e){this.manager=e}async handleLspFeature(e,t){if(!this.manager.ready)return fi();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};h.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 Qa(e,o)}}async handleWorkspaceSymbolRaw(e){if(!this.manager.ready)return null;try{let t=await this.manager.sendFeatureRequest(v.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return h.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return fi();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e}`}],isError:!0};h.info(`[ClangdLspTool] handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(v.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){return Qa("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return fi();if(e.direction==="outgoing")return{content:[{type:"text",text:"callHierarchy outgoing is not supported by clangd (incoming only)"}],isError:!0};let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e.file}`}],isError:!0};h.info(`[ClangdLspTool] handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,o=>this.fetchCallHierarchyResult(o,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return Qa("callHierarchy",r)}}async fetchCallHierarchyResult(e,t){let r=await this.manager.sendFeatureRequest(v.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(v.INCOMING_CALLS,{item:e});return Array.isArray(t)?t:t?[t]:[]}async withOpenFile(e,t){let r=vt(e),i=await yi.promises.readFile(e,"utf8"),o=Yo(e);h.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=ec.isAbsolute(e)?e:ec.join(this.manager.projectRoot,e);return!yi.existsSync(t)||!yi.statSync(t).isFile()||!Gr(t)?null:t}};import{spawn as VR}from"child_process";import*as rc from"fs";import*as Gy from"path";var GR=30*1e3,qR=30*1e3,tc=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new Ar;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{u.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),u.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),u.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 Dr(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(v.INITIALIZE,i,We),u.info("[ClangdLspProxy] initialize response received"),this.sendNotification(v.INITIALIZED,{}),t=!0}catch(r){this.lastStartErrorMessage=r instanceof Error?r.message:String(r),u.error(`[ClangdLspProxy] initialization failed: ${this.lastStartErrorMessage}`),await this.dispose()}e?.(t)}async hover(e){return this.sendLspRequest(v.HOVER,e)}async definition(e){return this.sendLspRequest(v.DEFINITION,e)}async declaration(e){return this.sendLspRequest(v.DECLARATION,e)}async references(e){return this.sendLspRequest(v.REFERENCES,e)}async implementation(e){return this.sendLspRequest(v.IMPLEMENTATION,e)}async documentSymbol(e){return this.sendLspRequest(v.DOCUMENT_SYMBOL,e)}async workspaceSymbol(e){return this.sendLspRequest(v.WORKSPACE_SYMBOL,e)}async prepareCallHierarchy(e){return this.sendLspRequest(v.PREPARE_CALL_HIERARCHY,e)}async incomingCalls(e){return this.sendLspRequest(v.INCOMING_CALLS,e)}async sendFeatureRequest(e,t){return this.sendLspRequest(e,t)}sendDidOpen(e){this.sendNotification(v.DID_OPEN,e)}sendDidChange(e){this.sendNotification(v.DID_CHANGE,e)}sendDidClose(e){this.sendNotification(v.DID_CLOSE,e)}sendNotification(e,t){if(!this.client){u.warn("[ClangdLspProxy] sendNotification before ready, dropped");return}this.client.sendNotification(e,t)}registerDiagnosticCallback(e){let t=this.normalizeClangdUri(e);if(this.diagnosticWaiters.has(t)){u.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}`))},qR);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(v.SHUTDOWN,null,3e3).catch(e=>{u.warn(`[ClangdLspProxy] shutdown request failed: ${e}`)}),this.sendNotification(v.EXIT,null),await this.client.waitForExitOrTimeout(300)}catch(e){u.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=${le(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];u.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=VR(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=Rn(this.config.workspaceRoot),t=St(e),r=Gy.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.3.5-Test.2"},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=GR){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);u.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):u.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;u.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 v.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case v.PROGRESS:this.onMessage({jsonrpc:x,method:v.PROGRESS,params:e.params});break;case v.WINDOW_SHOW_MESSAGE:u.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case v.WINDOW_LOG_MESSAGE:u.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:x,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;u.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:x,method:v.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{rc.existsSync(this.config.logPath)||rc.mkdirSync(this.config.logPath,{recursive:!0})}catch{}}normalizeClangdUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=decodeURIComponent(t.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(r)&&(r=r.slice(1)),St(r)}}catch{}return e}};import*as ko from"path";import*as Jd from"fs";var Io=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){u.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(u.info("[ClangdLspManager] Received cpp/syncProject"),!e||!t)return u.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};if(gr(e).length===0)return u.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let a=o?.skipCompileNative===!0,c=await ds(e,a?async()=>(u.info("[ClangdLspManager] compileNative skipped (C++ project up-to-date)"),{status:"success"}):async()=>n.executeCompileNative(e,t,r,i));return c.acquired?c.result:(u.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 im(e,t,r,i),u.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(o){let s=o instanceof Error?o.message:String(o);return u.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(We);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=Wt(this.config.workspaceRoot);this.resolvedRoot=e?we(e):we(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();fs(t);let r=this.config.clangdPath;if(!r){let s="clangd not found (install DevEco Studio / CLT)";u.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let i=this.config.compileCommandsDir??ko.dirname(Vr(this.resolvedRoot));try{Jd.mkdirSync(i,{recursive:!0})}catch(s){u.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${s}`)}u.info(`[ClangdLspManager] clangdPath: ${r}`),u.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),u.info(`[ClangdLspManager] compileCommandsDir: ${i}`);let o=new tc({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,u.info("[ClangdLspManager] clangd initialized");let r=this.initResolve;this.clearInitHandlers(),r?.()}else{let r=t??this.proxy?.consumeStartErrorMessage()??"unknown error";u.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){u.warn("[ClangdLspManager] dispatchNotification: missing method");return}let i=t.params;switch(r){case v.DID_OPEN:this.proxy.sendDidOpen(i);break;case v.DID_CHANGE:this.proxy.sendDidChange(i);break;case v.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){u.warn(`[ClangdLspManager] proxy dispose error: ${t}`)}this.proxy=null}this.isInitialized=!1,this.initPromise=null}getLogPath(){try{let e=ko.join(lr(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=ko.join(e,"lsp-log",t);return Jd.mkdirSync(r,{recursive:!0}),we(r)}catch{return"auto"}}};function qy(n){let e=ps(n);return u.info(`[SyncGuard] ${e.reason}`),e}var Jy=(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))(Jy||{}),Ut=3,Yd=600*1e3,Kd=100,nc=["ohpm","hvigor","dep-parse","lsp-init"],zy={ohpm:"ohpm install",hvigor:"hvigor sync","dep-parse":"dependency parse","lsp-init":"LSP init"},Do=15,ic=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;constructor(e={}){this.config=e,qr(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),h.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",h.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,h.info(`Constructor: using configured path as startPath: '${t}'`));let i=Wt(t);h.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,this.cppCustomCompileCommandsDir=vs(this.config.cppCompileCommandsPath),h.info(`Constructor: sdkPath='${this.sdkPath}', arktsLangServerPath='${this.arktsLangServerPath??"(null)"}', cppEnabled=${this.cppEnabled}, cppCustomCompileCommandsDir='${this.cppCustomCompileCommandsDir??"(none)"}'`),this.server=new zR({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=Wd(e.telemetry,()=>this.arktsCheckTool?.aceServerPid??null,()=>this.config.projectPath??"",()=>this.sdkPath??""),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:ve.object({target:ve.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:ve.object({files:ve.array(ve.string()).min(1).describe("List of source file paths to check, relative to the project root (absolute paths within the project are also accepted). Supports ArkTS and C/C++ files in the same call.")})},async e=>this.handleCheckCall(e))}registerLspFeatureTools(){if(!this.standardProtocolAvailable){h.info("Skip registering LSP feature tools (hover/definition/declaration/references/implementation, workspaceSymbol, documentSymbol, callHierarchy): standard LSP protocol unavailable (standardIndex/index.js not found). These tools require a DevEco Studio version that ships the standard LSP server entry.");return}let e=ve.object({file:ve.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:ve.number().describe("Line number (0-based)"),character:ve.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:ve.object({query:ve.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:ve.object({file:ve.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:ve.object({file:ve.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:ve.number().describe("Line number (0-based)"),character:ve.number().describe("Character offset in the line (0-based)"),direction:ve.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.arktsLangServerPath;if(!e)return h.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=Jo(e);return h.info(`ArktsCheck protocol: ${t?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${t})`),t}catch(e){return h.warn(`Failed to detect standard LSP protocol availability: ${e}`),!1}}async detectSocketAvailable(){try{let e=this.arktsLangServerPath;if(!e){this.socketAvailable=!1;return}this.socketAvailable=await dp(e,Yr(this.nodePath)),h.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 h.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};if(t.length>Kd)return h.warn(`check tool called with ${t.length} files (max: ${Kd})`),{content:[{type:"text",text:`Too many files: ${t.length}. Maximum allowed is ${Kd}.`}],isError:!0};let{etsFiles:r,cppFiles:i,unsupported:o}=YR(t);o.length>0&&h.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(`
|
|
1325
1328
|
`),s.join(`
|
|
1326
1329
|
`)].filter(d=>d.trim().length>0).join(`
|
|
1327
|
-
`).trim()||"No diagnostics collected"}],isError:c}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:
|
|
1328
|
-
`);i&&(e.isError?t.push(i):r.push(i))}assertRestartAllowed(e){if(e==="arkts"||e==="all"){let t=this.projectState;if(t!==4&&t!==0&&t!==5)return{content:[{type:"text",text:`ArkTS project state: ${this.describeArktsState()}, sync/init in progress, restart unavailable (would interrupt the current flow). Wait for the state to become ready and retry other tools directly\u2014no restart needed. restart is only available in ready/idle/error states.`}],isError:!0}}if(e==="cpp"||e==="all"){let t=this.cppProjectState;if(t!==4&&t!==0&&t!==5)return{content:[{type:"text",text:`C++ project state: ${this.describeCppState()}, sync/init in progress, restart unavailable (would interrupt the current flow). Wait for the state to become ready and retry other tools directly\u2014no restart needed. restart is only available in ready/idle/error states.`}],isError:!0}}return null}async handleRestartCall(e){let t=e.target,r=t==="cpp"?"cpp":t==="arkts"?"arkts":"all";if(r==="cpp"&&!this.cppEnabled)return{content:[{type:"text",text:"C++ LSP is disabled, cannot restart. Set DEVECO_CLI_CPP_ENABLED=true to enable."}],isError:!0};let i=this.assertRestartAllowed(r);return i||(this.restartProject(r),{content:[{type:"text",text:`MCP server is restarting in-place (${r==="all"?"ArkTS + C++":r==="cpp"?"C++":"ArkTS"}): re-sync project + re-initialize LSP. Client connection preserved\u2014no need to exit the agent. Please retry tools in ~10 seconds.`}]})}restartProject(e){h.info(`[restart] resetting tools + state, re-init (target=${e})`),(e==="arkts"||e==="all")&&this.restartArkts(),(e==="cpp"||e==="all")&&this.cppEnabled&&this.restartCpp()}restartArkts(){this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(e=>h.warn("Failed to shutdown ArktsCheckTool during restart:",e)),this.arktsCheckTool=null),this.initRetryCount=0,this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.configChangedTriggeredResync=!1,this.initPromise?(this.needsReinit=!0,h.info("[restart] ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(e=>h.warn("Failed to re-init ArkTS project during restart:",e)))}restartCpp(){this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(e=>h.warn("Failed to dispose ClangdLspManager during restart:",e)),this.cppLspManager=null),this.cppInitRetryCount=0,this.cppHasNoCppCode=!1,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitPromise?(this.cppNeedsReinit=!0,h.info("[restart] C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>h.warn("Failed to re-init C++ project during restart:",e)))}async start(){await this.detectSocketAvailable(),this.registerTools(),this.toolRouter.registerToServer(this.server);let e=new LD;if(await this.server.connect(e),h.info("devecocli-mcp-server started"),!this.config.debug){let t=Vu();t&&h.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=jt(t);r?(h.info(`Detected project path from client root: ${r}`),this.config.projectPath=r):h.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?h.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):h.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{h.warn("Background project init failed:",t)})}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return h.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return h.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){h.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,h.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{h.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{h.error("shutdown failed:",r),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{h.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?jt(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=jt(this.originalProjectPath),t&&h.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(!this.discoverProject()||!await this.ensureProjectSynced())return;this.ensureCppProjectReady().catch(t=>{h.warn("Background C++ project init failed:",t)}),this.projectState=3,this.arktsCheckTool=new ni(this.config.projectPath,this.sdkPath,this.arktsLangServerPath,this.config.nodeMaxOldSpaceSize,this.nodePath,this.socketAvailable),this.arktsCheckTool.setOnConfigChanged(()=>{h.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});let e=Date.now();try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,h.info("Project fully initialized, check tool is available"),await this.trackInit("init_arkts",e,!0,null,this.arktsCheckTool?.aceServerPid??null)}catch(t){h.error("LSP initialization failed:",t);let r=B(t),i=this.arktsCheckTool?.aceServerPid??null;this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5,await this.trackInit("init_arkts",e,!1,r,i)}}async ensureProjectSynced(){let e=this.config.projectPath,t=uy(e),r=vo.existsSync(ci.join(e,"oh-package-lock.json5")),i=vo.existsSync(ci.join(e,"oh_modules"))&&vo.readdirSync(ci.join(e,"oh_modules")).length>0;if(r&&i)return t.required?(h.info(`Sync required: ${t.reason}`),this.runSync(e,{skipHvigorSync:!1})):(h.info(`Sync skipped: ${t.reason}`),!0);let o=!t.required;return h.info(`Sync check: skipHvigor=${o}, ohpm install forced (lock=${r}, ohModules=${i}), reason=${t.reason}`),this.runSync(e,{skipHvigorSync:o})}async runSync(e,t){this.projectState=2,h.info("Starting project sync...");let r=await ri.handleSyncProject(e,this.sdkPath,this.nodePath,this.ohpmJsPath,this.hvigorJsPath,t);switch(r.status){case"success":return this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,!0;case"skipped":{this.syncSkippedDueToLock=!0,this.syncSkipStartedAt===0&&(this.syncSkipStartedAt=Date.now());let i=Date.now()-this.syncSkipStartedAt,o=Math.round(i/1e3);return i>=bd?(h.error(`Sync skipped for ${o}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(h.warn(`Sync skipped: ${r.reason}, resetting to IDLE for retry (elapsed ${o}s / ${bd/1e3}s)`),this.projectState=0,!1)}case"failed":return h.error(`Project sync failed: ${r.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:return h.error(`Project sync: unknown status ${r.status}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}async ensureCppProjectReady(){if(!this.cppEnabled){h.info("[Cpp] C++ LSP disabled by config, skipping initialization"),this.cppHasNoCppCode=!0,this.cppProjectState=4;return}if(!this.cppInitPromise){this.cppInitPromise=this.doEnsureCppProjectReady();try{await this.cppInitPromise}finally{this.cppInitPromise=null}this.cppNeedsReinit&&(this.cppNeedsReinit=!1,this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>{h.warn("Failed to re-init C++ project after cppNeedsReinit:",e)}))}}async doEnsureCppProjectReady(){let e=this.config.projectPath;if(!e){h.info("[Cpp] No project path, skipping C++ init");return}if(this.cppCustomCompileCommandsDir){h.info(`[Cpp] Custom compile_commands.json configured, skipping compileNative sync (dir: ${this.cppCustomCompileCommandsDir})`),this.cppHasNoCppCode=!1,await this.initCppLsp(e);return}this.cppProjectState=1;let t=pr(e);if(t.length===0){h.info('[Cpp] No C++ modules found, C++ tools will return "no C++ code"'),this.cppHasNoCppCode=!0,this.cppProjectState=4,this.cppInitRetryCount=0;return}this.cppHasNoCppCode=!1,h.info(`[Cpp] Found ${t.length} C++ module(s): ${t.map(o=>o.name).join(", ")}`);let r=Mp(e),i=!r.required;h.info(`[Cpp] C++ sync check: skipCompileNative=${i}, reason=${r.reason}`),await this.runSyncCpp(e,{skipCompileNative:i})&&await this.initCppLsp(e)}async initCppLsp(e){this.cppProjectState=3,this.cppLspManager=new yo({workspaceRoot:e,clangdPath:this.clangdPath??"",...this.cppCustomCompileCommandsDir?{compileCommandsDir:this.cppCustomCompileCommandsDir}:{}});let t=Date.now();try{await this.cppLspManager.start(),this.cppCheckTool=new oi(this.cppLspManager),this.cppLspTool=new si(this.cppLspManager),this.cppProjectState=4,this.cppInitRetryCount=0,h.info("[Cpp] C++ project fully initialized, C++ tools are available"),await this.trackInit("init_cpp",t,!0,null,this.cppLspManager?.clangdPid??null)}catch(r){h.error("[Cpp] C++ LSP initialization failed:",r);let i=B(r),o=this.cppLspManager?.clangdPid??null;this.cppLspManager&&this.cppLspManager.dispose().catch(()=>{}),this.cppLspManager=null,this.cppCheckTool=null,this.cppLspTool=null,this.cppInitRetryCount++,this.cppProjectState=5,await this.trackInit("init_cpp",t,!1,i,o)}}async trackInit(e,t,r,i,o){if(!this.config.telemetry)return;let s="unknown";if(o!==null){let l=await He(o);l!==null&&(s=te(Number(l)*1024))}let a={event:b.McpToolCall,subAction:e,mcpMemory:te(process.memoryUsage().rss),lspMemory:s},c={duration_ms:Date.now()-t,success:r,error_code:i};await this.config.telemetry.track(a,c).catch(()=>{})}async runSyncCpp(e,t){this.cppProjectState=2,h.info("[Cpp] Starting C++ project sync (compileNative)...");let r=await yo.handleSyncCppProject(e,this.sdkPath,this.nodePath,this.hvigorJsPath,t);switch(r.status){case"success":return this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,!0;case"skipped":{this.cppSyncSkippedDueToLock=!0,this.cppSyncSkipStartedAt===0&&(this.cppSyncSkipStartedAt=Date.now());let i=Date.now()-this.cppSyncSkipStartedAt,o=Math.round(i/1e3);return i>=bd?(h.error(`[Cpp] C++ sync skipped for ${o}s due to lock contention, giving up`),this.cppInitRetryCount++,this.cppSyncSkipStartedAt=0,this.cppProjectState=5,!1):(h.warn(`[Cpp] C++ sync skipped: ${r.reason}, resetting to IDLE_CPP for retry (elapsed ${o}s)`),this.cppProjectState=0,!1)}case"failed":return h.error(`[Cpp] C++ project sync failed: ${r.reason}`),this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitRetryCount++,this.cppProjectState=5,!1}return!1}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppLspManager&&await this.cppLspManager.dispose(),this.cppCheckTool=null,this.cppLspTool=null;try{await this.server.close()}catch(e){h.warn("Failed to close MCP server connection:",e)}h.info("devecocli-mcp-server stopped"),Wu(),Bu()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function ND(n){let e=[],t=[],r=[];for(let i of n)ci.extname(i).toLowerCase()===".ets"?e.push(i):Wr(i)?t.push(i):r.push(i);return{etsFiles:e,cppFiles:t,unsupported:r}}function Cd(n={}){return new ja(n)}import*as kd from"fs";import*as wo from"path";import{spawn as MD}from"child_process";async function my(n){Vr(!1);let{serverPath:e,logPath:t,projectPath:r,sdkPath:i,serverMaxSize:o,nodePath:s}=await OD(n),a=$D(e,t,r,i,o,s);h.info("ace-server started, bridging stdio (initialize is left to the client)"),jD(a),await Ad(a.pid,Id("--arkts",n))}function Id(n,e){return[n,...e.projectPath?["--project-path"]:[],...e.autoDetect?["--auto-detect"]:[]]}async function Ad(n,e){let t="unknown";if(n!==null){let i=await He(n);i!==null&&(t=te(Number(i)*1024))}let r={event:b.ServeLsp,args:e,lspMemory:t};await k.track(r)}async function OD(n){let e=await C.new(),t;if(n.projectPath)t=we(wo.resolve(n.projectPath)),h.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let c=_o(process.cwd());t=we(c??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${c??"null, fallback to cwd"}`)}else t=we(process.cwd()),h.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=e.sdkPath,i=e.arktsLangServerPath;i||(h.error("ace-server not found (install DevEco Studio / CLT)."),process.exit(1));let o=wn(i,!0),s=wo.join(sr(),"lsp-server",String(Date.now()));kd.mkdirSync(s,{recursive:!0});let a=_D(t,r);return h.info(`projectPath=${t}, sdkPath=${r}, arktsLangServerPath=${i}, serverPath=${o}, logPath=${s}, serverMaxSize=${a}MB`),{projectPath:t,sdkPath:r,serverPath:o,logPath:s,serverMaxSize:a,nodePath:e.nodePath}}function _D(n,e){let t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=t?parseInt(t,10):NaN,i=Number.isFinite(r)&&r>0?r:void 0,o=FD(n,e),s=rs(o,i);return h.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${o}, override=${i??"none"})`),s}function FD(n,e){try{let t=[];return new pn(n,e).getAllDependencyMap(t).status==="OK"?t.length:new Ht(n).getAllModuleInfo().length}catch{return 0}}function $D(n,e,t,r,i,o){let s=wo.join(e,"lspLog");kd.mkdirSync(s,{recursive:!0});let a=ki({serverPath:n,lspLogPath:s,serverMaxSize:i,projectPath:t,sdkPath:r}),c=zr(o);return h.info(`[serve-lsp] spawn: ${c} ${a.join(" ")}`),MD(c,a,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function jD(n){n.on("error",e=>{h.error(`[ace-server] spawn error: ${e.message}`),process.exit(1)}),n.stdout?.on("error",e=>{h.error(`[ace-server] stdout error: ${e.message}`)}),n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("error",e=>{h.error(`[ace-server] stderr error: ${e.message}`)}),n.stderr?.on("data",e=>{h.error(`[ace-server] ${e.toString("utf8").trim()}`)}),n.stdin?.on("error",e=>{h.error(`[ace-server] stdin error: ${e.message}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{h.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{h.info(`ace-server exited with code ${e}`),process.exit(e??0)})}import*as fy from"fs";import*as fn from"path";import{spawn as HD}from"child_process";async function hy(n){Vr(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await UD(n),i=fn.join(t,"compile_commands.json");fy.existsSync(i)||h.warn(`compile_commands.json not found at ${i}. Cross-file navigation/completion will be limited. Run \`devecocli build\` first to generate it.`);let o=WD(e,t,r);h.info("clangd started, bridging stdio (initialize is left to the client)"),GD(o),await Ad(o.pid,Id("--cpp",n))}async function UD(n){let e=await BD();e?.clangdPath||(h.error("clangd not found. Ensure DevEco Studio / CLT is installed."),process.exit(1));let t;if(n.projectPath)t=we(fn.resolve(n.projectPath)),h.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let c=_o(process.cwd());t=we(c??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${c??"null, fallback to cwd"}`)}else t=we(fn.resolve(process.cwd())),h.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=e.sdkPath,i=e.clangdPath,o=Br(t),s=fn.dirname(o),a=os(process.env.DEVECO_CLI_CPP_COMPILE_COMMANDS);return a&&(h.info(`Using custom compile_commands dir: ${a}`),s=a),h.info(`projectPath=${t}, sdkPath=${r}, clangdPath=${i}, compileCommandsDir=${s}`),{projectPath:t,clangdPath:i,compileCommandsDir:s}}async function BD(){try{return await C.new()}catch{let n=Fu();if(!n)return null;try{return C.fromIDE(n)}catch{return null}}}function WD(n,e,t){let r=VD(e);return h.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),HD(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function VD(n){return[`--compile-commands-dir=${de(n)}`,"--log=info","--pch-storage=memory"]}function GD(n){n.on("error",e=>{h.error(`[clangd] spawn error: ${e.message}`),process.exit(1)}),n.stdout?.on("error",e=>{h.error(`[clangd] stdout error: ${e.message}`)}),n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("error",e=>{h.error(`[clangd] stderr error: ${e.message}`)}),n.stderr?.on("data",e=>{h.error(`[clangd] ${e.toString("utf8").trim()}`)}),n.stdin?.on("error",e=>{h.error(`[clangd] stdin error: ${e.message}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{h.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{h.info(`clangd exited with code ${e}`),process.exit(e??0)})}async function zD(){let n=process.env.PROJECT_PATH||"",e=process.env.NODE_MAX_OLD_SPACE_SIZE,t=process.env.DEBUG==="true"||process.env.DEBUG==="1",r=process.env.DEVECO_CLI_CPP_ENABLED!=="false"&&process.env.DEVECO_CLI_CPP_ENABLED!=="0",i=process.env.DEVECO_CLI_CPP_COMPILE_COMMANDS?.trim()||"",o=n,s=await C.new(),a=Cd({projectPath:o,sdkPath:s.sdkPath,arktsLangServerPath:s.arktsLangServerPath??void 0,nodePath:s.nodePath,ohpmJsPath:s.ohpmJsPath,hvigorJsPath:s.hvigorJsPath,clangdPath:s.clangdPath??void 0,nodeMaxOldSpaceSize:e,debug:t,cppEnabled:r,cppCompileCommandsPath:i||void 0,telemetry:k}),c,l=new Promise(g=>{c=g}),d=async()=>{await a.shutdown(),c()};process.once("SIGINT",d),process.once("SIGTERM",d),process.platform==="win32"&&process.once("SIGBREAK",d);try{await a.start()}catch(g){console.error("Failed to start MCP server:",g instanceof Error?g.message:String(g)),process.exit(1)}await l}var Dd=new qD("serve").description("Host bundled auxiliary protocol servers");Dd.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await zD()});Dd.command("lsp").description("Start a bundled LSP language server").option("--arkts","Start the ArkTS language server (ace-server)").option("--cpp","Start the C/C++ language server (clangd)").option("--project-path <path>","project root path (used as-is, no search)").option("--auto-detect","When --project-path is not specified, search the current directory and its subdirectories for the project root (no upward search)").action(async n=>{n.arkts&&n.cpp&&(console.error("--arkts and --cpp are mutually exclusive. Specify only one."),process.exit(1)),n.arkts?await my({projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await hy({projectPath:n.projectPath,autoDetect:n.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var gy=Dd;import{Command as eR,InvalidArgumentError as by}from"commander";import{red as tR,dim as rR}from"colorette";import{createRequire as JD}from"module";import{dirname as YD,join as li}from"path";import{pathToFileURL as KD}from"url";import{readFile as vy,access as Rd}from"fs/promises";import*as wy from"semver";var XD=JD(import.meta.url),yy=1;async function ZD(){try{let n=XD.resolve("@deveco-test/deveco-cli-knowledgebase/package.json"),e=JSON.parse(await vy(n,"utf8"));return{version:e.version,apiVersion:e.apiVersion??0,dir:YD(n)}}catch{return null}}async function QD(){let n=he(),e=li(n,"doc-data","current.json"),t;try{t=JSON.parse(await vy(e,"utf8"))}catch{return null}let r=li(n,"doc-data",t.version);try{return await Rd(li(r,"dist","engine","index.js")),await Rd(li(r,"docs.zip")),await Rd(li(r,"index.zip")),{version:t.version,apiVersion:t.apiVersion,dir:r}}catch{return null}}async function Ha(){let n=[await QD(),await ZD()].filter(t=>t!==null).sort((t,r)=>wy.rcompare(t.version,r.version)),e=!1;for(let t of n){if(t.apiVersion>yy){p(`docs: skip candidate v${t.version} (apiVersion ${t.apiVersion} > ${yy})`),e=!0;continue}try{let r=li(t.dir,"dist","engine","index.js");return await import(KD(r).href)}catch(r){p(`docs: candidate v${t.version} load failed: ${r instanceof Error?r.message:String(r)}`)}}throw e?new Error("Documentation package version is incompatible, please upgrade CLI"):new Error("No available documentation package, please update docs or reinstall CLI")}async function Td(n,e){let t=Date.now();try{let r=await e();return await Sy(n,Date.now()-t,!0,null),r}catch(r){let i=r instanceof Error?r.code??r.name:"UnknownError";throw await Sy(n,Date.now()-t,!1,i),r}}async function Sy(n,e,t,r){await k.track(n,{duration_ms:e,success:t,error_code:r}).catch(()=>{})}function nR(n){return n instanceof Error&&(n.name==="CacheDirError"||n.name==="DocPathSafetyError")}function xd(n){console.error(tR(iR(n))),process.exitCode=1}function iR(n){let e=n instanceof Error?n.message:String(n);return nR(n)?e:/\b(EACCES|EPERM|ENOSPC|ENOTDIR|ELOOP)\b/.test(e)?"Documentation data directory is unavailable. Check DEVECO_CLI_DATA_DIR and retry.":e}function Ey(...n){return e=>{if(!n.includes(e))throw new by(`Allowed values: ${n.join(", ")}`);return e}}function oR(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new by("Must be a positive integer.");return e}var sR=Ey("json","default"),aR=Ey("json","default");function cR(n){let e=n.map(t=>t.trim()).filter(Boolean);if(e.length===0)throw new Error("Keywords cannot be empty.");return e}function lR(n){for(let e=0;e<n.length;e++){let t=n[e];console.log(t.documentId),console.log(` Title: ${t.title}`),t.snippet&&console.log(` Content: ${t.snippet}`),e<n.length-1&&console.log()}}var Ua=new eR("docs").description("Search and read HarmonyOS documentation from local docs directory");Ua.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)","all").option("--format <fmt>","Output format (default, json)",sR,"default").option("--limit <n>","Max number of results",oR,10).action(async(n,e)=>{let t={event:b.DocOperation,subAction:"search",queryLen:n.join(" ").length,catalog:e.catalog??"all"};try{await Td(t,async()=>{let r=cR(n),i=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=await Ha(),s=o.CATALOG_NAMES;if(i&&s&&!s.includes(i))throw new Error(`Invalid catalog "${e.catalog}". Allowed: all, ${s.join(", ")}`);let a=await o.createDocsEngine({cacheDir:he()});try{let c=await a.search({keywords:r,catalog:i,limit:e.limit});e.format==="json"?console.log(JSON.stringify(c,null,2)):lR(c)}finally{await a.close()}})}catch(r){xd(r)}});Ua.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{let e=n.trim(),t={event:b.DocOperation,subAction:"read",documentId:e};try{await Td(t,async()=>{if(!e)throw new Error("Document ID cannot be empty.");let i=await(await Ha()).createDocsEngine({cacheDir:he()});try{let o=await i.read({relativePath:e});console.log(o)}finally{await i.close()}})}catch(r){xd(r)}});Ua.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",aR,"default").action(async n=>{let e={event:b.DocOperation,subAction:"catalog",fmt:n.format??"default"};try{await Td(e,async()=>{let r=await(await Ha()).createDocsEngine({cacheDir:he()});try{let i=await r.catalog();if(n.format==="json")console.log(JSON.stringify(i.map(o=>({name:o.nodeId,title:o.nodeName})),null,2));else for(let o of i)console.log(` ${o.nodeId.padEnd(20)} ${rR(o.nodeName)}`)}finally{await r.close()}})}catch(t){xd(t)}});var Py=Ua;import{Command as ZR}from"commander";import{Command as dR,InvalidArgumentError as uR,Option as Ld}from"commander";import pR from"ora";function mR(n){let e=parseInt(n,10);if(!Number.isInteger(e)||e<0||String(e)!==n.trim())throw new uR("depth must be a non-negative integer");return e}function fR(n){let e=[];(n.type||n.id)&&e.push(n.type?n.id?`${n.type}#${n.id}`:n.type:`#${n.id}`),e.push(n.bounds?`[${n.bounds.join(",")}]`:"[]"),n.text&&e.push(`"${JSON.stringify(n.text).slice(1,-1)}"`);let t=[];return n.clickable&&t.push("clickable"),n.longClickable&&t.push("longClickable"),n.scrollable&&t.push("scrollable"),n.checkable&&t.push("checkable"),t.length>0&&e.push(...t),e.join(" ")}function Cy(n,e=0){let t=[],r=" ".repeat(e);for(let i of n)t.push(`${r}${fR(i)}`),i.children.length>0&&t.push(...Cy(i.children,e+1).split(`
|
|
1330
|
+
`).trim()||"No diagnostics collected"}],isError:c}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:return h.warn(`ArkTS check rejected: project is DISCOVERING, files: ${e.join(", ")}`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 2:return h.warn(`ArkTS check rejected: project is SYNCING, files: ${e.join(", ")}`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 3:return h.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 h.error(`ArkTS check: unknown project state ${this.projectState}, files: ${e.join(", ")}`),{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],isError:!0}}}async handleLspFeatureCall(e,t){let r=t.file,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 h.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){h.warn(`workspaceSymbol ArkTS query failed: ${a.message}`)}if(r)try{this.mergeSymbolItems(await this.cppLspTool.handleWorkspaceSymbolRaw(e),o,i)}catch(a){h.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 ${Do}s)`;case 3:return`initializing (retry ${Do}s)`;case 5:return`error (${this.initRetryCount}/${Ut})`;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}/${Ut})`;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 h.warn(`ArkTS ${e} rejected: project is DISCOVERING`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 2:return h.warn(`ArkTS ${e} rejected: project is SYNCING`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 3:return h.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 h.warn(`ArkTS ${e} rejected: unknown project state ${this.projectState}`),{content:[{type:"text",text:"Unknown project state, please retry"}],isError:!0}}}async handleIdleCheck(){if(this.ensureProjectReady(),this.config.projectPath){let e,t;return this.syncSkippedDueToLock?(e=`Another build process is running, sync deferred (waiting ${this.syncSkipStartedAt>0?Math.round((Date.now()-this.syncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,t="lock contention",this.syncSkippedDueToLock=!1):this.configChangedTriggeredResync?(e=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"),h.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(h.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:`Initializing.${this.buildRetrySuffix()}`}],isError:!0}):(h.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"No HarmonyOS project detected. Please verify the project directory or create a project first."}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=Ut?(h.error(`Init retry limit reached (${this.initRetryCount}/${Ut}), will not auto-retry`),{content:[{type:"text",text:`Project initialization failed repeatedly (auto-retry exhausted: ${this.initRetryCount}/${Ut}). Ask the user to investigate and confirm \`ohpm install\` + \`hvigor\` sync succeed manually. Do NOT call the \`restart\` tool repeatedly \u2014 call it at most once after the user fixes the root cause; if it fails again, stop retrying and escalate to the user.`}],isError:!0}):(h.info(`Error check: auto-retrying (${this.initRetryCount}/${Ut})`),this.arktsInitProgress=null,this.ensureProjectReady(),{content:[{type:"text",text:`Project initialization failed, auto-retrying.${this.buildRetrySuffix()}`}],isError:!0})}buildRetrySuffix(){return` Retry in ${Do}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=nc.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] ${zy[e.phase]}: ${e.detail}${o} [${r}s, total ${i}s]`,this.buildPipelineLine(e.phase),`Retry in ${Do}s. Expected total: 30s\u201310min (depends on project size).`].join(`
|
|
1331
|
+
`)}buildPipelineLine(e){return`Pipeline: ${nc.map(r=>{let i=nc.indexOf(r)<nc.indexOf(e),o=r===e,s=zy[r];return i?`${s} \u2713`:o?`${s}(\u2026)`:s}).join(" \u2192 ")}`}async routeCppRequest(e,t){switch(this.cppProjectState){case 0:return this.handleCppIdleCheck();case 1:case 2:return h.warn(`C++ ${e} rejected: C++ project is ${Jy[this.cppProjectState]}`),{content:[{type:"text",text:"C++ project is syncing (compileNative), please retry in 25 seconds"}],isError:!0};case 3:return h.warn(`C++ ${e} rejected: clangd is initializing`),{content:[{type:"text",text:"C++ LSP (clangd) is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleCppErrorCheck();case 4:return this.cppEnabled?this.cppHasNoCppCode?{content:[{type:"text",text:"No C++ code in this project"}],isError:!0}:this.cppLspManager?.ready?t():{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}:{content:[{type:"text",text:"C++ LSP is disabled. Set DEVECO_CLI_CPP_ENABLED=true to enable."}],isError:!0};default:return h.warn(`C++ ${e} rejected: unknown C++ project state ${this.cppProjectState}`),{content:[{type:"text",text:"Unknown C++ project state, please retry"}],isError:!0}}}async routeLspRequest(e,t,r){return e.endsWith(".ets")?this.routeArktsRequest(t,r):Gr(e)?this.routeCppRequest(t,r):{content:[{type:"text",text:`Unsupported file type: ${e} (only .ets and C/C++ source/header files are supported)`}],isError:!0}}async handleCppIdleCheck(){if(this.ensureCppProjectReady(),this.config.projectPath){let e;return this.cppSyncSkippedDueToLock?(e=`Another build process is running, C++ sync deferred (waiting ${this.cppSyncSkipStartedAt>0?Math.round((Date.now()-this.cppSyncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,this.cppSyncSkippedDueToLock=!1):e="C++ project detected, syncing (compileNative), please retry in 25 seconds",h.info(`C++ idle check: project '${this.config.projectPath}', triggering C++ init`),{content:[{type:"text",text:e}],isError:!0}}return{content:[{type:"text",text:"No HarmonyOS project detected for C++ tools."}],isError:!0}}async handleCppErrorCheck(){return this.cppInitRetryCount>=Ut?(h.error(`C++ init retry limit reached (${this.cppInitRetryCount}/${Ut}), will not auto-retry`),{content:[{type:"text",text:`C++ project initialization failed repeatedly (auto-retry exhausted: ${this.cppInitRetryCount}/${Ut}). Ask the user to investigate and confirm \`hvigor compileNative\` succeeds manually. Do NOT call the \`restart\` tool repeatedly \u2014 call it at most once after the user fixes the root cause; if it fails again, stop retrying and escalate to the user.`}],isError:!0}):(h.info(`C++ error check: auto-retrying (${this.cppInitRetryCount}/${Ut})`),this.ensureCppProjectReady(),{content:[{type:"text",text:"C++ project initialization failed, auto-retrying, please retry in 25 seconds"}],isError:!0})}async callCppCheck(e){return this.routeCppRequest("check",async()=>this.cppCheckTool.handleCall({files:e}))}mergeCheckResult(e,t,r){let i=e.content.map(o=>o.text).filter(o=>o&&o.trim().length>0).join(`
|
|
1332
|
+
`);i&&(e.isError?t.push(i):r.push(i))}assertRestartAllowed(e){if(e==="arkts"||e==="all"){let t=this.projectState;if(t!==4&&t!==0&&t!==5)return{content:[{type:"text",text:`ArkTS project state: ${this.describeArktsState()}, sync/init in progress, restart unavailable (would interrupt the current flow). Wait for the state to become ready and retry other tools directly\u2014no restart needed. restart is only available in ready/idle/error states.`}],isError:!0}}if(e==="cpp"||e==="all"){let t=this.cppProjectState;if(t!==4&&t!==0&&t!==5)return{content:[{type:"text",text:`C++ project state: ${this.describeCppState()}, sync/init in progress, restart unavailable (would interrupt the current flow). Wait for the state to become ready and retry other tools directly\u2014no restart needed. restart is only available in ready/idle/error states.`}],isError:!0}}return null}async handleRestartCall(e){let t=e.target,r=t==="cpp"?"cpp":t==="arkts"?"arkts":"all";if(r==="cpp"&&!this.cppEnabled)return{content:[{type:"text",text:"C++ LSP is disabled, cannot restart. Set DEVECO_CLI_CPP_ENABLED=true to enable."}],isError:!0};let i=this.assertRestartAllowed(r);return i||(this.restartProject(r),{content:[{type:"text",text:`MCP server is restarting in-place (${r==="all"?"ArkTS + C++":r==="cpp"?"C++":"ArkTS"}): re-sync project + re-initialize LSP. Client connection preserved\u2014no need to exit the agent. Please retry tools in ~${Do}s.`}]})}restartProject(e){h.info(`[restart] resetting tools + state, re-init (target=${e})`),(e==="arkts"||e==="all")&&this.restartArkts(),(e==="cpp"||e==="all")&&this.cppEnabled&&this.restartCpp()}restartArkts(){this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(e=>h.warn("Failed to shutdown ArktsCheckTool during restart:",e)),this.arktsCheckTool=null),this.initRetryCount=0,this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.configChangedTriggeredResync=!1,this.initPromise?(this.needsReinit=!0,h.info("[restart] ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(e=>h.warn("Failed to re-init ArkTS project during restart:",e)))}restartCpp(){this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(e=>h.warn("Failed to dispose ClangdLspManager during restart:",e)),this.cppLspManager=null),this.cppInitRetryCount=0,this.cppHasNoCppCode=!1,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitPromise?(this.cppNeedsReinit=!0,h.info("[restart] C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>h.warn("Failed to re-init C++ project during restart:",e)))}async start(){await this.detectSocketAvailable(),this.registerTools(),this.toolRouter.registerToServer(this.server);let e=new JR;if(await this.server.connect(e),h.info("devecocli-mcp-server started"),!this.config.debug){let t=gp();t&&h.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=Wt(t);r?(h.info(`Detected project path from client root: ${r}`),this.config.projectPath=r):h.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?h.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):h.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{h.warn("Background project init failed:",t)})}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return h.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return h.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){h.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,h.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{h.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{h.error("shutdown failed:",r),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{h.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?Wt(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=Wt(this.originalProjectPath),t&&h.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(!this.discoverProject())return;if(this.arktsPipelineStartedAt=Date.now(),this.arktsInitProgress={phase:"ohpm",detail:"installing dependencies",percent:null,startedAt:Date.now(),updatedAt:Date.now()},!await this.ensureProjectSynced()){this.arktsInitProgress=null;return}this.ensureCppProjectReady().catch(t=>{h.warn("Background C++ project init failed:",t)}),this.projectState=3,this.arktsInitProgress={phase:"dep-parse",detail:"parsing dependency map",percent:null,startedAt:Date.now(),updatedAt:Date.now()},this.arktsCheckTool=this.createArktsCheckTool();let e=Date.now();try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,this.arktsInitProgress=null,h.info("Project fully initialized, check tool is available"),await this.trackInit("init_arkts",e,!0,null,this.arktsCheckTool?.aceServerPid??null)}catch(t){h.error("LSP initialization failed:",t);let r=B(t),i=this.arktsCheckTool?.aceServerPid??null;this.arktsCheckTool=null,this.arktsInitProgress=null,this.initRetryCount++,this.projectState=5,await this.trackInit("init_arkts",e,!1,r,i)}}createArktsCheckTool(){let e=new mi(this.config.projectPath,this.sdkPath,this.arktsLangServerPath,this.config.nodeMaxOldSpaceSize,this.nodePath,this.socketAvailable);return e.setOnConfigChanged(()=>{h.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0}),e.setOnInitProgress((t,r)=>{this.arktsInitProgress&&(this.arktsInitProgress.phase="lsp-init",this.arktsInitProgress.detail=t,this.arktsInitProgress.percent=r,this.arktsInitProgress.updatedAt=Date.now())}),e.setOnDepParseProgress((t,r)=>{this.arktsInitProgress&&(this.arktsInitProgress.phase="dep-parse",this.arktsInitProgress.detail=`${t}/${r} modules`,this.arktsInitProgress.percent=r>0?Math.round(t/r*100):null,this.arktsInitProgress.updatedAt=Date.now())}),e}async ensureProjectSynced(){let e=this.config.projectPath,t=qy(e),r=Ao.existsSync(vi.join(e,"oh-package-lock.json5")),i=Ao.existsSync(vi.join(e,"oh_modules"))&&Ao.readdirSync(vi.join(e,"oh_modules")).length>0;if(r&&i)return t.required?(h.info(`Sync required: ${t.reason}`),this.runSync(e,{skipHvigorSync:!1})):(h.info(`Sync skipped: ${t.reason}`),!0);let o=!t.required;return h.info(`Sync check: skipHvigor=${o}, ohpm install forced (lock=${r}, ohModules=${i}), reason=${t.reason}`),this.runSync(e,{skipHvigorSync:o})}async runSync(e,t){this.projectState=2,h.info("Starting project sync...");let r=s=>{this.arktsInitProgress&&(this.arktsInitProgress.phase="ohpm",this.arktsInitProgress.detail=s,this.arktsInitProgress.percent=null,this.arktsInitProgress.updatedAt=Date.now())},i=s=>{this.arktsInitProgress&&(this.arktsInitProgress.phase="hvigor",this.arktsInitProgress.detail=s,this.arktsInitProgress.percent=null,this.arktsInitProgress.updatedAt=Date.now())},o=await pi.handleSyncProject(e,this.sdkPath,this.nodePath,this.ohpmJsPath,this.hvigorJsPath,t,r,i);return this.handleSyncResult(o)}handleSyncResult(e){switch(e.status){case"success":return this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,!0;case"skipped":{this.syncSkippedDueToLock=!0,this.syncSkipStartedAt===0&&(this.syncSkipStartedAt=Date.now());let t=Date.now()-this.syncSkipStartedAt,r=Math.round(t/1e3);return t>=Yd?(h.error(`Sync skipped for ${r}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(h.warn(`Sync skipped: ${e.reason}, resetting to IDLE for retry (elapsed ${r}s / ${Yd/1e3}s)`),this.projectState=0,!1)}case"failed":return h.error(`Project sync failed: ${e.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:return h.error(`Project sync: unknown status ${e.status}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}async ensureCppProjectReady(){if(!this.cppEnabled){h.info("[Cpp] C++ LSP disabled by config, skipping initialization"),this.cppHasNoCppCode=!0,this.cppProjectState=4;return}if(!this.cppInitPromise){this.cppInitPromise=this.doEnsureCppProjectReady();try{await this.cppInitPromise}finally{this.cppInitPromise=null}this.cppNeedsReinit&&(this.cppNeedsReinit=!1,this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>{h.warn("Failed to re-init C++ project after cppNeedsReinit:",e)}))}}async doEnsureCppProjectReady(){let e=this.config.projectPath;if(!e){h.info("[Cpp] No project path, skipping C++ init");return}if(this.cppCustomCompileCommandsDir){h.info(`[Cpp] Custom compile_commands.json configured, skipping compileNative sync (dir: ${this.cppCustomCompileCommandsDir})`),this.cppHasNoCppCode=!1,await this.initCppLsp(e);return}this.cppProjectState=1;let t=gr(e);if(t.length===0){h.info('[Cpp] No C++ modules found, C++ tools will return "no C++ code"'),this.cppHasNoCppCode=!0,this.cppProjectState=4,this.cppInitRetryCount=0;return}this.cppHasNoCppCode=!1,h.info(`[Cpp] Found ${t.length} C++ module(s): ${t.map(o=>o.name).join(", ")}`);let r=cm(e),i=!r.required;h.info(`[Cpp] C++ sync check: skipCompileNative=${i}, reason=${r.reason}`),await this.runSyncCpp(e,{skipCompileNative:i})&&await this.initCppLsp(e)}async initCppLsp(e){this.cppProjectState=3,this.cppLspManager=new Io({workspaceRoot:e,clangdPath:this.clangdPath??"",...this.cppCustomCompileCommandsDir?{compileCommandsDir:this.cppCustomCompileCommandsDir}:{}});let t=Date.now();try{await this.cppLspManager.start(),this.cppCheckTool=new hi(this.cppLspManager),this.cppLspTool=new gi(this.cppLspManager),this.cppProjectState=4,this.cppInitRetryCount=0,h.info("[Cpp] C++ project fully initialized, C++ tools are available"),await this.trackInit("init_cpp",t,!0,null,this.cppLspManager?.clangdPid??null)}catch(r){h.error("[Cpp] C++ LSP initialization failed:",r);let i=B(r),o=this.cppLspManager?.clangdPid??null;this.cppLspManager&&this.cppLspManager.dispose().catch(()=>{}),this.cppLspManager=null,this.cppCheckTool=null,this.cppLspTool=null,this.cppInitRetryCount++,this.cppProjectState=5,await this.trackInit("init_cpp",t,!1,i,o)}}async trackInit(e,t,r,i,o){if(!this.config.telemetry)return;let s="unknown";if(o!==null){let l=await Qe(o);l!==null&&(s=te(Number(l)*1024))}let a={event:b.McpToolCall,subAction:e,mcpMemory:te(process.memoryUsage().rss),lspMemory:s},c={duration_ms:Date.now()-t,success:r,error_code:i};await this.config.telemetry.track(a,c).catch(()=>{})}async runSyncCpp(e,t){this.cppProjectState=2,h.info("[Cpp] Starting C++ project sync (compileNative)...");let r=await Io.handleSyncCppProject(e,this.sdkPath,this.nodePath,this.hvigorJsPath,t);switch(r.status){case"success":return this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,!0;case"skipped":{this.cppSyncSkippedDueToLock=!0,this.cppSyncSkipStartedAt===0&&(this.cppSyncSkipStartedAt=Date.now());let i=Date.now()-this.cppSyncSkipStartedAt,o=Math.round(i/1e3);return i>=Yd?(h.error(`[Cpp] C++ sync skipped for ${o}s due to lock contention, giving up`),this.cppInitRetryCount++,this.cppSyncSkipStartedAt=0,this.cppProjectState=5,!1):(h.warn(`[Cpp] C++ sync skipped: ${r.reason}, resetting to IDLE_CPP for retry (elapsed ${o}s)`),this.cppProjectState=0,!1)}case"failed":return h.error(`[Cpp] C++ project sync failed: ${r.reason}`),this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitRetryCount++,this.cppProjectState=5,!1}return!1}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppLspManager&&await this.cppLspManager.dispose(),this.cppCheckTool=null,this.cppLspTool=null;try{await this.server.close()}catch(e){h.warn("Failed to close MCP server connection:",e)}h.info("devecocli-mcp-server stopped"),hp(),fp()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function YR(n){let e=[],t=[],r=[];for(let i of n)vi.extname(i).toLowerCase()===".ets"?e.push(i):Gr(i)?t.push(i):r.push(i);return{etsFiles:e,cppFiles:t,unsupported:r}}function Xd(n={}){return new ic(n)}import*as Zd from"fs";import*as Ro from"path";import{spawn as KR}from"child_process";async function Yy(n){qr(!1);let{serverPath:e,logPath:t,projectPath:r,sdkPath:i,serverMaxSize:o,nodePath:s}=await XR(n),a=eT(e,t,r,i,o,s);h.info("ace-server started, bridging stdio (initialize is left to the client)"),tT(a),await eu(a.pid,Qd("--arkts",n))}function Qd(n,e){return[n,...e.projectPath?["--project-path"]:[],...e.autoDetect?["--auto-detect"]:[]]}async function eu(n,e){let t="unknown";if(n!==null){let i=await Qe(n);i!==null&&(t=te(Number(i)*1024))}let r={event:b.ServeLsp,args:e,lspMemory:t};await k.track(r)}async function XR(n){let e=await C.new(),t;if(n.projectPath)t=we(Ro.resolve(n.projectPath)),h.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let c=zo(process.cwd());t=we(c??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${c??"null, fallback to cwd"}`)}else t=we(process.cwd()),h.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=e.sdkPath,i=e.arktsLangServerPath;i||(h.error("ace-server not found (install DevEco Studio / CLT)."),process.exit(1));let o=En(i,!0),s=Ro.join(lr(),"lsp-server",String(Date.now()));Zd.mkdirSync(s,{recursive:!0});let a=ZR(t,r);return h.info(`projectPath=${t}, sdkPath=${r}, arktsLangServerPath=${i}, serverPath=${o}, logPath=${s}, serverMaxSize=${a}MB`),{projectPath:t,sdkPath:r,serverPath:o,logPath:s,serverMaxSize:a,nodePath:e.nodePath}}function ZR(n,e){let t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=t?parseInt(t,10):NaN,i=Number.isFinite(r)&&r>0?r:void 0,o=QR(n,e),s=hs(o,i);return h.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${o}, override=${i??"none"})`),s}function QR(n,e){try{let t=[];return new hn(n,e).getAllDependencyMap(t).status==="OK"?t.length:new Vt(n).getAllModuleInfo().length}catch{return 0}}function eT(n,e,t,r,i,o){let s=Ro.join(e,"lspLog");Zd.mkdirSync(s,{recursive:!0});let a=Oi({serverPath:n,lspLogPath:s,serverMaxSize:i,projectPath:t,sdkPath:r}),c=Yr(o);return h.info(`[serve-lsp] spawn: ${c} ${a.join(" ")}`),KR(c,a,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function tT(n){n.on("error",e=>{h.error(`[ace-server] spawn error: ${e.message}`),process.exit(1)}),n.stdout?.on("error",e=>{h.error(`[ace-server] stdout error: ${e.message}`)}),n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("error",e=>{h.error(`[ace-server] stderr error: ${e.message}`)}),n.stderr?.on("data",e=>{h.error(`[ace-server] ${e.toString("utf8").trim()}`)}),n.stdin?.on("error",e=>{h.error(`[ace-server] stdin error: ${e.message}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{h.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{h.info(`ace-server exited with code ${e}`),process.exit(e??0)})}import*as Ky from"fs";import*as yn from"path";import{spawn as rT}from"child_process";async function Xy(n){qr(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await nT(n),i=yn.join(t,"compile_commands.json");Ky.existsSync(i)||h.warn(`compile_commands.json not found at ${i}. Cross-file navigation/completion will be limited. Run \`devecocli build\` first to generate it.`);let o=oT(e,t,r);h.info("clangd started, bridging stdio (initialize is left to the client)"),aT(o),await eu(o.pid,Qd("--cpp",n))}async function nT(n){let e=await iT();e?.clangdPath||(h.error("clangd not found. Ensure DevEco Studio / CLT is installed."),process.exit(1));let t;if(n.projectPath)t=we(yn.resolve(n.projectPath)),h.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let c=zo(process.cwd());t=we(c??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${c??"null, fallback to cwd"}`)}else t=we(yn.resolve(process.cwd())),h.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=e.sdkPath,i=e.clangdPath,o=Vr(t),s=yn.dirname(o),a=vs(process.env.DEVECO_CLI_CPP_COMPILE_COMMANDS);return a&&(h.info(`Using custom compile_commands dir: ${a}`),s=a),h.info(`projectPath=${t}, sdkPath=${r}, clangdPath=${i}, compileCommandsDir=${s}`),{projectPath:t,clangdPath:i,compileCommandsDir:s}}async function iT(){try{return await C.new()}catch{let n=lp();if(!n)return null;try{return C.fromIDE(n)}catch{return null}}}function oT(n,e,t){let r=sT(e);return h.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),rT(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function sT(n){return[`--compile-commands-dir=${le(n)}`,"--log=info","--pch-storage=memory"]}function aT(n){n.on("error",e=>{h.error(`[clangd] spawn error: ${e.message}`),process.exit(1)}),n.stdout?.on("error",e=>{h.error(`[clangd] stdout error: ${e.message}`)}),n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("error",e=>{h.error(`[clangd] stderr error: ${e.message}`)}),n.stderr?.on("data",e=>{h.error(`[clangd] ${e.toString("utf8").trim()}`)}),n.stdin?.on("error",e=>{h.error(`[clangd] stdin error: ${e.message}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{h.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{h.info(`clangd exited with code ${e}`),process.exit(e??0)})}async function lT(){let n=process.env.PROJECT_PATH||"",e=process.env.NODE_MAX_OLD_SPACE_SIZE,t=process.env.DEBUG==="true"||process.env.DEBUG==="1",r=process.env.DEVECO_CLI_CPP_ENABLED!=="false"&&process.env.DEVECO_CLI_CPP_ENABLED!=="0",i=process.env.DEVECO_CLI_CPP_COMPILE_COMMANDS?.trim()||"",o=n,s=await C.new(),a=Xd({projectPath:o,sdkPath:s.sdkPath,arktsLangServerPath:s.arktsLangServerPath??void 0,nodePath:s.nodePath,ohpmJsPath:s.ohpmJsPath,hvigorJsPath:s.hvigorJsPath,clangdPath:s.clangdPath??void 0,nodeMaxOldSpaceSize:e,debug:t,cppEnabled:r,cppCompileCommandsPath:i||void 0,telemetry:k}),c,l=new Promise(g=>{c=g}),d=async()=>{await a.shutdown(),c()};process.once("SIGINT",d),process.once("SIGTERM",d),process.platform==="win32"&&process.once("SIGBREAK",d);try{await a.start()}catch(g){console.error("Failed to start MCP server:",g instanceof Error?g.message:String(g)),process.exit(1)}await l}var tu=new cT("serve").description("Host bundled auxiliary protocol servers");tu.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await lT()});tu.command("lsp").description("Start a bundled LSP language server").option("--arkts","Start the ArkTS language server (ace-server)").option("--cpp","Start the C/C++ language server (clangd)").option("--project-path <path>","project root path (used as-is, no search)").option("--auto-detect","When --project-path is not specified, search the current directory and its subdirectories for the project root (no upward search)").action(async n=>{n.arkts&&n.cpp&&(console.error("--arkts and --cpp are mutually exclusive. Specify only one."),process.exit(1)),n.arkts?await Yy({projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await Xy({projectPath:n.projectPath,autoDetect:n.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var Zy=tu;import{Command as gT,InvalidArgumentError as rv}from"commander";import{red as yT,dim as vT}from"colorette";import{Command as dT}from"commander";import{cyan as oc,yellow as wi}from"colorette";import*as Qy from"path";function sc(n){return wi(`If you want the latest docs(${n}), please update CLI first: run \`devecocli update\` to update`)}function uT(n){console.log(wi(`Latest docs v${n.version} (apiVersion ${n.apiVersion}) is incompatible with current CLI, and no compatible historical version was found.`)),console.log(sc(n.version))}function pT(n,e,t,r,i){console.log(t?oc(`New docs version ${n} found (current v${e??"none"})`):oc(`Documentation is already up to date v${n}`)),r||console.log(sc(i))}function mT(n,e,t,r){e?console.log(wi(`Docs successfully upgrade to ${n}`)):(console.log(wi(`Docs latest version ${t} is incompatible with your current CLI (v${r})`)),console.log(wi(`Docs has been upgraded to the compatible version ${n}`)),console.log(sc(t)))}async function fT(n){let e=Pt();console.log(oc("Checking for documentation updates..."));let{latest:t,compatible:r}=await Vn(e);if(!r){uT(t);return}let i=await Wn(),o=r.version===t.version,s=!i||dr(r.version,i)>0;if(n.check){pT(r.version,i,s,o,t.version);return}if(!n.force&&!s){console.log(wi(`Docs is already up to date v${r.version}`)),o||console.log(sc(t.version));return}console.log(oc(`Downloading documentation package v${r.version}...`)),await qs({version:r.version,apiVersion:r.apiVersion,dist:r.dist},Qy.join(de(),"doc-data"),"docs-update"),mT(r.version,o,t.version,mt())}var hT=new dT("update").description("Update documentation to the latest compatible version").option("--force","Force re-download even if up to date").option("--check","Check for updates without installing").action(async n=>{await fT(n)}),ev=hT;async function ru(n,e){let t=Date.now();try{let r=await e();return await tv(n,Date.now()-t,!0,null),r}catch(r){let i=r instanceof Error?r.code??r.name:"UnknownError";throw await tv(n,Date.now()-t,!1,i),r}}async function tv(n,e,t,r){await k.track(n,{duration_ms:e,success:t,error_code:r}).catch(()=>{})}function wT(n){return n instanceof Error&&(n.name==="CacheDirError"||n.name==="DocPathSafetyError")}function nu(n){console.error(yT(ST(n))),process.exitCode=1}function ST(n){let e=n instanceof Error?n.message:String(n);return wT(n)?e:/\b(EACCES|EPERM|ENOSPC|ENOTDIR|ELOOP)\b/.test(e)?"Documentation data directory is unavailable. Check DEVECO_CLI_DATA_DIR and retry.":e}function nv(...n){return e=>{if(!n.includes(e))throw new rv(`Allowed values: ${n.join(", ")}`);return e}}function bT(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new rv("Must be a positive integer.");return e}var ET=nv("json","default"),PT=nv("json","default");function CT(n){let e=n.map(t=>t.trim()).filter(Boolean);if(e.length===0)throw new Error("Keywords cannot be empty.");return e}function kT(n){for(let e=0;e<n.length;e++){let t=n[e];console.log(t.documentId),console.log(` Title: ${t.title}`),t.snippet&&console.log(` Content: ${t.snippet}`),e<n.length-1&&console.log()}}var To=new gT("docs").description("HarmonyOS documentation commands (search, read, catalog, update)");To.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)","all").option("--format <fmt>","Output format (default, json)",ET,"default").option("--limit <n>","Max number of results",bT,10).action(async(n,e)=>{let t={event:b.DocOperation,subAction:"search",keywords:n,queryLen:n.join(" ").length,catalog:e.catalog??"all"};try{await ru(t,async()=>{let r=CT(n),i=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=await Vs(),s=o.CATALOG_NAMES;if(i&&s&&!s.includes(i))throw new Error(`Invalid catalog "${e.catalog}". Allowed: all, ${s.join(", ")}`);let a=await o.createDocsEngine({cacheDir:de()});try{let c=await a.search({keywords:r,catalog:i,limit:e.limit});e.format==="json"?console.log(JSON.stringify(c,null,2)):kT(c)}finally{await a.close()}})}catch(r){nu(r)}});To.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{let e=n.trim(),t={event:b.DocOperation,subAction:"read",documentId:e};try{await ru(t,async()=>{if(!e)throw new Error("Document ID cannot be empty.");let i=await(await Vs()).createDocsEngine({cacheDir:de()});try{let o=await i.read({relativePath:e});console.log(o)}finally{await i.close()}})}catch(r){nu(r)}});To.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",PT,"default").action(async n=>{let e={event:b.DocOperation,subAction:"catalog",fmt:n.format??"default"};try{await ru(e,async()=>{let r=await(await Vs()).createDocsEngine({cacheDir:de()});try{let i=await r.catalog();if(n.format==="json")console.log(JSON.stringify(i.map(o=>({name:o.nodeId,title:o.nodeName})),null,2));else for(let o of i)console.log(` ${o.nodeId.padEnd(20)} ${vT(o.nodeName)}`)}finally{await r.close()}})}catch(t){nu(t)}});To.addCommand(ev);var iv=To;import{Command as fx}from"commander";import{Command as IT,InvalidArgumentError as DT,Option as iu}from"commander";import AT from"ora";function RT(n){let e=parseInt(n,10);if(!Number.isInteger(e)||e<0||String(e)!==n.trim())throw new DT("depth must be a non-negative integer");return e}function TT(n){let e=[];(n.type||n.id)&&e.push(n.type?n.id?`${n.type}#${n.id}`:n.type:`#${n.id}`),e.push(n.bounds?`[${n.bounds.join(",")}]`:"[]"),n.text&&e.push(`"${JSON.stringify(n.text).slice(1,-1)}"`);let t=[];return n.clickable&&t.push("clickable"),n.longClickable&&t.push("longClickable"),n.scrollable&&t.push("scrollable"),n.checkable&&t.push("checkable"),t.length>0&&e.push(...t),e.join(" ")}function ov(n,e=0){let t=[],r=" ".repeat(e);for(let i of n)t.push(`${r}${TT(i)}`),i.children.length>0&&t.push(...ov(i.children,e+1).split(`
|
|
1329
1333
|
`));return t.join(`
|
|
1330
|
-
`)}function hR(n){if(n.allWindows&&n.window)throw new Error("--all-windows and --window are mutually exclusive.")}function gR(n,e){let t=Tn(n,e);if(t.length===0)throw new Error(`Node '${e}' not found.`);let r=t.map(i=>({...i,children:[]}));return JSON.stringify(r,null,2)}function yR(n,e){return e.id?gR(n,e.id):e.format==="json"?JSON.stringify(n,null,2):Cy(n)}async function vR(n){hR(n);let e=pR({text:"Dumping layout\u2026",color:"cyan"}).start(),t;try{let i=await C.new(),o=await et(i,n.device),s=new Zr(i.hdcPath);t=n.mode==="full"?await s.dumpFullTree(o,n.depth,n.window,n.allWindows):await s.dumpCollapsedTree(o,n.depth,n.window,n.allWindows)}catch(i){throw e.stop(),new Error(`Failed to dump layout: ${i.message}`,{cause:i})}e.stop();let r=yR(t,n);return console.log(r),Buffer.byteLength(r,"utf8")}function wR(n){return{event:b.CommandExecuted,args:["ui","layout",...n.device?["--device"]:[]],mode:n.mode,outputSize:0}}async function SR(n){let e=wR(n),t=Date.now(),r=!0,i=null;try{e.outputSize=await vR(n)}catch(o){throw r=!1,i=B(o),o}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await k.track(e,o)}}var ky=new dR("layout").description("Inspect on-screen node(s) for UI testing").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Layout node id").option("--window <windowId>","Target window id").option("--all-windows","Include all windows (mutually exclusive with --window)").addOption(new Ld("--depth <n>","Tree depth limit (0=unlimited, 1=root only, 2=root+children)").argParser(mR).default(0)).addOption(new Ld("--format <format>","Output format").choices(["default","json"]).default("default")).addOption(new Ld("--mode <mode>","Output mode: full | simplified").choices(["full","simplified"]).default("simplified")).action(async n=>{await SR(n)});import{Command as bR,Option as ER}from"commander";import{yellow as PR}from"colorette";import CR from"ora";var kR=["Id","Name","Pid","DisplayId","Focused"];function IR(n,e){if(e==="json"){let r=n.map(i=>({id:i.id,name:i.name,pid:i.pid,displayId:i.displayId,focused:i.focused}));console.log(JSON.stringify(r,null,2));return}let t=n.map(r=>({cells:[String(r.id),r.name,String(r.pid),String(r.displayId),String(r.focused)],highlight:r.focused}));console.log(zt(kR,t))}async function AR(n){let e=CR({text:"Listing windows\u2026",color:"cyan"}).start(),t;try{let r=await C.new(),i=await et(r,n.device);t=await new Bt(r.hdcPath,i).listWindows({all:n.all})}catch(r){throw e.stop(),new Error(`Failed to list windows: ${r.message}`,{cause:r})}if(e.stop(),t.length===0){console.log(PR(" No windows found."));return}IR(t,n.format)}function DR(n){let e=[];return n.device&&e.push("--device"),n.format!=="default"&&e.push("--format"),n.all&&e.push("--all"),{event:b.CommandExecuted,args:["ui","window","list",...e]}}async function RR(n){let e=DR(n),t=Date.now(),r=!0,i=null;try{await AR(n)}catch(o){throw r=!1,i=B(o),o}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await k.track(e,o)}}var Nd=new bR("window").description("Manage device windows");Nd.command("list").description("List windows on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new ER("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show all windows including system windows").action(async n=>{await RR(n)});import{Command as TR}from"commander";import{green as xR}from"colorette";function LR(n){return{event:b.CommandExecuted,args:["ui","screenshot",...n.device?["--device"]:[]]}}function NR(n){let e=n.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}async function MR(n){let e=LR(n),t=Date.now(),r=!0,i=null;try{if(n.device!==void 0&&!n.device.trim())throw new Error("--device must not be empty.");let o=n.display!==void 0?NR(n.display):void 0,s=await C.new(),a=new Qr(s),c=a.resolveDestinationPath(n.path),l=await et(s,n.device);await a.captureToPath(l,c,o),console.log(xR(`Screenshot saved to ${c}`))}catch(o){throw r=!1,i=B(o),o}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await k.track(e,o)}}var Iy=new TR("screenshot").description("Capture a screenshot of the device screen").option("--device <name|serial>","Target device name or serial; required when multiple devices are connected").option("--display <displayId>","Target display id; omit for default screen").option("--path <path>","Required directory or PNG file path; destination must be writable").action(MR);import{Command as Ba,Option as OR}from"commander";import{green as Md,yellow as _R}from"colorette";var Wa=["--device <name|serial>","Target physical device name or serial; required when multiple devices are connected"],Dy=["--path <dir|file.mp4>","Required writable destination: existing directory or a new .mp4 file"];function Va(n){return new w("INVALID_ARGUMENT",n)}function Ay(n){if(n!==void 0&&!n.trim())throw Va("--device must not be empty.")}function Ga(n,e){let t=n.parent?.opts()?.device;if(Ay(t),Ay(e),t&&e&&t!==e)throw Va(`Conflicting --device values: ${JSON.stringify(t)} and ${JSON.stringify(e)}`);return e??t}function Ry(n,e){if(n.parent?.opts()?.path!==void 0)throw Va(`--path is not valid for ui screenrecord ${e}.`)}function Ty(n,e){let t=n.parent?.opts()?.path;if(t!==void 0&&e!==void 0&&t!==e)throw Va(`Conflicting --path values: ${JSON.stringify(t)} and ${JSON.stringify(e)}`);return e??t}function qa(n,e){let t=n.parent?.opts();return e.filter(r=>r.value!==void 0||t?.[r.name.slice(2)]!==void 0).map(r=>r.name)}function FR(n,e){return n.getOptionValueSource(e)==="cli"}async function za(n,e,t){let r={event:b.CommandExecuted,args:["ui","screenrecord",...n,...e]},i=Date.now(),o=!0,s=null;try{await t()}catch(a){throw o=!1,s=B(a),a}finally{let a={duration_ms:Date.now()-i,success:o,error_code:s};await k.track(r,a)}}function xy(n){if(n.kind==="saved"){console.log(Md(`Saved successfully to ${n.localPath}`));for(let e of n.warnings??[])console.error(_R(`Warning: ${e}`))}else n.kind==="external-stopped"&&console.log(Md("Recording stopped. View the file in the device gallery; this CLI cannot retrieve it."))}async function $R(n,e){let t=qa(e,[{name:"--device",value:n.device},{name:"--path",value:n.path}]);await za([],t,async()=>{let r=Ga(e,n.device),i=Ty(e,n.path),s=await new hr(await C.new()).recordInteractively(r,i,{onStarted:()=>{console.log("Recording... press Ctrl+C to stop and save")}});xy(s)})}async function jR(n,e){let t=qa(e,[{name:"--device",value:n.device},{name:"--path",value:n.path}]);await za(["start"],t,async()=>{let r=Ga(e,n.device),i=Ty(e,n.path);await new hr(await C.new()).startDetached(r,i),console.log(Md("Recording started. Stop with devecocli ui screenrecord stop"))})}async function HR(n,e){let t=[...qa(e,[{name:"--device",value:n.device}]),...n.force?["--force"]:[]];await za(["stop"],t,async()=>{let r=Ga(e,n.device);Ry(e,"stop");let o=await new hr(await C.new()).stopRecording(r,n.force??!1);xy(o)})}var UR={recording:"Status: recording - a recording started by this CLI is in progress",busy:"Status: busy - a recording started outside this CLI is in progress",idle:"Status: idle - no recording is in progress"};async function BR(n,e){let t=[...qa(e,[{name:"--device",value:n.device}]),...FR(e,"format")?["--format"]:[]];await za(["status"],t,async()=>{let r=Ga(e,n.device);Ry(e,"status");let o=await new hr(await C.new()).getRecordingStatus(r);if(n.format==="json"){console.log(JSON.stringify(o));return}console.log(UR[o.status]),o.status==="idle"&&o.note&&console.log(o.note)})}var So=new Ba("screenrecord").description("Record the screen of a physical device to an MP4 file").option(...Wa).option(...Dy).action($R);So.addCommand(new Ba("start").description("Start recording and return immediately (detached)").option(...Wa).option(...Dy).action(jR));So.addCommand(new Ba("stop").description("Stop the current recording and save the file").option(...Wa).option("--force","Stop a recording that was not started by this CLI (no download)").action(HR));So.addCommand(new Ba("status").description("Show the recording status without changing it").option(...Wa).addOption(new OR("--format <format>","Output format").choices(["table","json"]).default("table")).action(BR));import{Command as xr}from"commander";function Lr(n,e){let t=[];return"device"in e&&e.device&&t.push("--device"),"id"in e&&e.id&&t.push("--id"),"window"in e&&e.window&&t.push("--window"),"speed"in e&&e.speed&&t.push("--speed"),{event:b.CommandExecuted,args:["ui",n,...t]}}function WR(n){let t=`"$(printf '%s' '${Buffer.from(n,"utf8").toString("base64")}' | base64 -d)"`;return p(`escapeShellText: ${n} -> ${t}`),t}async function Nr(n,e,t,r){let i=new tt;i.start(n);let o=Date.now(),s=!0,a=null;try{await r(i)}catch(c){throw i.stop(),s=!1,a=B(c),new Error(`${e}: ${c.message}`,{cause:c})}finally{let c={duration_ms:Date.now()-o,success:s,error_code:a};await k.track(t,c)}}async function VR(n,e,t){let r=Lr("click",t);await Nr("Executing click...","click failed",r,async i=>{Nn(n,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await Mt(t.device),{x:a,y:c}=await Mn(o,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await lt(o,s,["uitest","uiInput","click",String(a),String(c)]),i.succeed(`click at (${a}, ${c})`)})}async function GR(n,e,t){let r=Lr("doubleclick",t);await Nr("Executing doubleclick...","doubleclick failed",r,async i=>{Nn(n,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await Mt(t.device),{x:a,y:c}=await Mn(o,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await lt(o,s,["uitest","uiInput","doubleClick",String(a),String(c)]),i.succeed(`doubleclick at (${a}, ${c})`)})}async function qR(n,e,t){let r=Lr("longclick",t);await Nr("Executing longclick...","longclick failed",r,async i=>{Nn(n,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await Mt(t.device),{x:a,y:c}=await Mn(o,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await lt(o,s,["uitest","uiInput","longClick",String(a),String(c)]),i.succeed(`longclick at (${a}, ${c})`)})}async function zR(n,e,t,r,i){let o=Lr("swipe",i);await Nr("Executing swipe...","swipe failed",o,async s=>{Le(n,"x1"),Le(e,"y1"),Le(t,"x2"),Le(r,"y2");let a=Oi(i.speed),{hdcPath:c,deviceId:l}=await Mt(i.device),d=["uitest","uiInput","swipe",n,e,t,r];a&&d.push(a),await lt(c,l,d),s.succeed(`swipe from (${n}, ${e}) to (${t}, ${r})`)})}async function JR(n,e,t,r,i){let o=Lr("fling",i);await Nr("Executing fling...","fling failed",o,async s=>{Le(n,"x1"),Le(e,"y1"),Le(t,"x2"),Le(r,"y2");let a=Oi(i.speed),{hdcPath:c,deviceId:l}=await Mt(i.device),d=["uitest","uiInput","fling",n,e,t,r];a&&d.push(a),await lt(c,l,d),s.succeed(`fling from (${n}, ${e}) to (${t}, ${r})`)})}async function YR(n,e,t,r,i){let o=Lr("drag",i);await Nr("Executing drag...","drag failed",o,async s=>{Le(n,"x1"),Le(e,"y1"),Le(t,"x2"),Le(r,"y2");let a=Oi(i.speed),{hdcPath:c,deviceId:l}=await Mt(i.device),d=["uitest","uiInput","drag",n,e,t,r];a&&d.push(a),await lt(c,l,d),s.succeed(`drag from (${n}, ${e}) to (${t}, ${r})`)})}async function KR(n,e){let t=Lr("dircfling",e);await Nr("Executing dircfling...","dircfling failed",t,async r=>{let i=Es[n];if(i===void 0)throw new Error(`Invalid direction "${n}". Valid values: ${Object.keys(Es).join(", ")}`);let{hdcPath:o,deviceId:s}=await Mt(e.device);await lt(o,s,["uitest","uiInput","dircFling",i]),r.succeed(`dircfling ${n}`)})}async function XR(n,e,t,r){let i=Lr("text",r);await Nr("Executing text input...","input failed",i,async o=>{Nn(e,t,r.id,r.window,!1),Ps(n,"text");let{hdcPath:s,deviceId:a}=await Mt(r.device),c=WR(n);if(e!==void 0)await lt(s,a,[`uitest uiInput inputText ${e} ${t} ${c}`]),o.succeed(`input ${n} at (${e}, ${t})`);else if(r.id){let{x:l,y:d}=await Mn(s,a,void 0,void 0,r.id,r.window);await lt(s,a,[`uitest uiInput inputText ${l} ${d} ${c}`]),o.succeed(`input ${n} at (${l}, ${d})`)}else await lt(s,a,[`uitest uiInput text ${c}`]),o.succeed(`input ${n}`)})}var Ly=new xr("click").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Tap at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(VR),Ny=new xr("doubleclick").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Double-tap at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(GR),My=new xr("longclick").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Long-press at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(qR),Oy=new xr("swipe").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Swipe from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(zR),_y=new xr("fling").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Fling from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(JR),Fy=new xr("drag").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Drag from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(YR),$y=new xr("dircfling").argument("<direction>","Direction: up, down, left, right").description("Fling in a specified direction").option("--device <name|serial>","Target device (name or serial)").action(KR),jy=new xr("text").argument("<text>","Text to input").argument("[x]","Optional X coordinate").argument("[y]","Optional Y coordinate").description("Input text at a target location or the currently focused field").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id to target before input (auto-resolves to center)").option("--window <windowId>","Target window id (used with --id)").action(XR);var rt=new ZR("ui").description("Inspect and interact with UI on a connected device");rt.addCommand(ky);rt.addCommand(Nd);rt.addCommand(Iy);rt.addCommand(So);rt.addCommand(Ly);rt.addCommand(Ny);rt.addCommand(My);rt.addCommand(Oy);rt.addCommand(_y);rt.addCommand(Fy);rt.addCommand($y);rt.addCommand(jy);var Hy=rt;import{Command as bv,InvalidArgumentError as Jx}from"commander";import{execa as ET}from"execa";import $t from"fs";import*as jd from"os";import*as _ from"path";var QR=new RegExp("\x1B\\[[0-?]*[ -/]*[@-~]","g"),eT=/\r/g,tT=/^(Working|Finished)\.\.\.\[[^\]]*\]\d+%$/,rT=/^<+\s*/,nT=/\s*>+$/,iT=[/^The configuration file .+ is in use\.$/,/^The configuration file .+ in the project is in use\.$/,/^Currently active product: ?.+$/,/^Writing the result to .+\.$/,/^Write finished\.$/,/^CodeLinter found some defects in your code\.$/],oT=new Set([1]);function _d(n){if(!n)return"";let e=n.replace(QR,"").replace(eT,`
|
|
1334
|
+
`)}function xT(n){if(n.allWindows&&n.window)throw new Error("--all-windows and --window are mutually exclusive.")}function LT(n,e){let t=Mn(n,e);if(t.length===0)throw new Error(`Node '${e}' not found.`);let r=t.map(i=>({...i,children:[]}));return JSON.stringify(r,null,2)}function NT(n,e){return e.id?LT(n,e.id):e.format==="json"?JSON.stringify(n,null,2):ov(n)}async function MT(n){xT(n);let e=AT({text:"Dumping layout\u2026",color:"cyan"}).start(),t;try{let i=await C.new(),o=await nt(i,n.device),s=new en(i.hdcPath);t=n.mode==="full"?await s.dumpFullTree(o,n.depth,n.window,n.allWindows):await s.dumpCollapsedTree(o,n.depth,n.window,n.allWindows)}catch(i){throw e.stop(),new Error(`Failed to dump layout: ${i.message}`,{cause:i})}e.stop();let r=NT(t,n);return console.log(r),Buffer.byteLength(r,"utf8")}function OT(n){return{event:b.CommandExecuted,args:["ui","layout",...n.device?["--device"]:[]],mode:n.mode,outputSize:0}}async function _T(n){let e=OT(n),t=Date.now(),r=!0,i=null;try{e.outputSize=await MT(n)}catch(o){throw r=!1,i=B(o),o}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await k.track(e,o)}}var sv=new IT("layout").description("Inspect on-screen node(s) for UI testing").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Layout node id").option("--window <windowId>","Target window id").option("--all-windows","Include all windows (mutually exclusive with --window)").addOption(new iu("--depth <n>","Tree depth limit (0=unlimited, 1=root only, 2=root+children)").argParser(RT).default(0)).addOption(new iu("--format <format>","Output format").choices(["default","json"]).default("default")).addOption(new iu("--mode <mode>","Output mode: full | simplified").choices(["full","simplified"]).default("simplified")).action(async n=>{await _T(n)});import{Command as FT,Option as $T}from"commander";import{yellow as jT}from"colorette";import HT from"ora";var UT=["Id","Name","Pid","DisplayId","Focused"];function BT(n,e){if(e==="json"){let r=n.map(i=>({id:i.id,name:i.name,pid:i.pid,displayId:i.displayId,focused:i.focused}));console.log(JSON.stringify(r,null,2));return}let t=n.map(r=>({cells:[String(r.id),r.name,String(r.pid),String(r.displayId),String(r.focused)],highlight:r.focused}));console.log(Xt(UT,t))}async function WT(n){let e=HT({text:"Listing windows\u2026",color:"cyan"}).start(),t;try{let r=await C.new(),i=await nt(r,n.device);t=await new qt(r.hdcPath,i).listWindows({all:n.all})}catch(r){throw e.stop(),new Error(`Failed to list windows: ${r.message}`,{cause:r})}if(e.stop(),t.length===0){console.log(jT(" No windows found."));return}BT(t,n.format)}function VT(n){let e=[];return n.device&&e.push("--device"),n.format!=="default"&&e.push("--format"),n.all&&e.push("--all"),{event:b.CommandExecuted,args:["ui","window","list",...e]}}async function GT(n){let e=VT(n),t=Date.now(),r=!0,i=null;try{await WT(n)}catch(o){throw r=!1,i=B(o),o}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await k.track(e,o)}}var ou=new FT("window").description("Manage device windows");ou.command("list").description("List windows on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new $T("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show all windows including system windows").action(async n=>{await GT(n)});import{Command as qT}from"commander";import{green as zT}from"colorette";function JT(n){return{event:b.CommandExecuted,args:["ui","screenshot",...n.device?["--device"]:[]]}}function YT(n){let e=n.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}async function KT(n){let e=JT(n),t=Date.now(),r=!0,i=null;try{if(n.device!==void 0&&!n.device.trim())throw new Error("--device must not be empty.");let o=n.display!==void 0?YT(n.display):void 0,s=await C.new(),a=new tn(s),c=a.resolveDestinationPath(n.path),l=await nt(s,n.device);await a.captureToPath(l,c,o),console.log(zT(`Screenshot saved to ${c}`))}catch(o){throw r=!1,i=B(o),o}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await k.track(e,o)}}var av=new qT("screenshot").description("Capture a screenshot of the device screen").option("--device <name|serial>","Target device name or serial; required when multiple devices are connected").option("--display <displayId>","Target display id; omit for default screen").option("--path <path>","Required directory or PNG file path; destination must be writable").action(KT);import{Command as ac,Option as XT}from"commander";import{green as su,yellow as ZT}from"colorette";var cc=["--device <name|serial>","Target physical device name or serial; required when multiple devices are connected"],lv=["--path <dir|file.mp4>","Required writable destination: existing directory or a new .mp4 file"];function lc(n){return new w("INVALID_ARGUMENT",n)}function cv(n){if(n!==void 0&&!n.trim())throw lc("--device must not be empty.")}function dc(n,e){let t=n.parent?.opts()?.device;if(cv(t),cv(e),t&&e&&t!==e)throw lc(`Conflicting --device values: ${JSON.stringify(t)} and ${JSON.stringify(e)}`);return e??t}function dv(n,e){if(n.parent?.opts()?.path!==void 0)throw lc(`--path is not valid for ui screenrecord ${e}.`)}function uv(n,e){let t=n.parent?.opts()?.path;if(t!==void 0&&e!==void 0&&t!==e)throw lc(`Conflicting --path values: ${JSON.stringify(t)} and ${JSON.stringify(e)}`);return e??t}function uc(n,e){let t=n.parent?.opts();return e.filter(r=>r.value!==void 0||t?.[r.name.slice(2)]!==void 0).map(r=>r.name)}function QT(n,e){return n.getOptionValueSource(e)==="cli"}async function pc(n,e,t){let r={event:b.CommandExecuted,args:["ui","screenrecord",...n,...e]},i=Date.now(),o=!0,s=null;try{await t()}catch(a){throw o=!1,s=B(a),a}finally{let a={duration_ms:Date.now()-i,success:o,error_code:s};await k.track(r,a)}}function pv(n){if(n.kind==="saved"){console.log(su(`Saved successfully to ${n.localPath}`));for(let e of n.warnings??[])console.error(ZT(`Warning: ${e}`))}else n.kind==="external-stopped"&&console.log(su("Recording stopped. View the file in the device gallery; this CLI cannot retrieve it."))}async function ex(n,e){let t=uc(e,[{name:"--device",value:n.device},{name:"--path",value:n.path}]);await pc([],t,async()=>{let r=dc(e,n.device),i=uv(e,n.path),s=await new wr(await C.new()).recordInteractively(r,i,{onStarted:()=>{console.log("Recording... press Ctrl+C to stop and save")}});pv(s)})}async function tx(n,e){let t=uc(e,[{name:"--device",value:n.device},{name:"--path",value:n.path}]);await pc(["start"],t,async()=>{let r=dc(e,n.device),i=uv(e,n.path);await new wr(await C.new()).startDetached(r,i),console.log(su("Recording started. Stop with devecocli ui screenrecord stop"))})}async function rx(n,e){let t=[...uc(e,[{name:"--device",value:n.device}]),...n.force?["--force"]:[]];await pc(["stop"],t,async()=>{let r=dc(e,n.device);dv(e,"stop");let o=await new wr(await C.new()).stopRecording(r,n.force??!1);pv(o)})}var nx={recording:"Status: recording - a recording started by this CLI is in progress",busy:"Status: busy - a recording started outside this CLI is in progress",idle:"Status: idle - no recording is in progress"};async function ix(n,e){let t=[...uc(e,[{name:"--device",value:n.device}]),...QT(e,"format")?["--format"]:[]];await pc(["status"],t,async()=>{let r=dc(e,n.device);dv(e,"status");let o=await new wr(await C.new()).getRecordingStatus(r);if(n.format==="json"){console.log(JSON.stringify(o));return}console.log(nx[o.status]),o.status==="idle"&&o.note&&console.log(o.note)})}var xo=new ac("screenrecord").description("Record the screen of a physical device to an MP4 file").option(...cc).option(...lv).action(ex);xo.addCommand(new ac("start").description("Start recording and return immediately (detached)").option(...cc).option(...lv).action(tx));xo.addCommand(new ac("stop").description("Stop the current recording and save the file").option(...cc).option("--force","Stop a recording that was not started by this CLI (no download)").action(rx));xo.addCommand(new ac("status").description("Show the recording status without changing it").option(...cc).addOption(new XT("--format <format>","Output format").choices(["table","json"]).default("table")).action(ix));import{Command as Nr}from"commander";function Mr(n,e){let t=[];return"device"in e&&e.device&&t.push("--device"),"id"in e&&e.id&&t.push("--id"),"window"in e&&e.window&&t.push("--window"),"speed"in e&&e.speed&&t.push("--speed"),{event:b.CommandExecuted,args:["ui",n,...t]}}function ox(n){let t=`"$(printf '%s' '${Buffer.from(n,"utf8").toString("base64")}' | base64 -d)"`;return p(`escapeShellText: ${n} -> ${t}`),t}async function Or(n,e,t,r){let i=new it;i.start(n);let o=Date.now(),s=!0,a=null;try{await r(i)}catch(c){throw i.stop(),s=!1,a=B(c),new Error(`${e}: ${c.message}`,{cause:c})}finally{let c={duration_ms:Date.now()-o,success:s,error_code:a};await k.track(t,c)}}async function sx(n,e,t){let r=Mr("click",t);await Or("Executing click...","click failed",r,async i=>{Fn(n,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await $t(t.device),{x:a,y:c}=await $n(o,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await pt(o,s,["uitest","uiInput","click",String(a),String(c)]),i.succeed(`click at (${a}, ${c})`)})}async function ax(n,e,t){let r=Mr("doubleclick",t);await Or("Executing doubleclick...","doubleclick failed",r,async i=>{Fn(n,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await $t(t.device),{x:a,y:c}=await $n(o,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await pt(o,s,["uitest","uiInput","doubleClick",String(a),String(c)]),i.succeed(`doubleclick at (${a}, ${c})`)})}async function cx(n,e,t){let r=Mr("longclick",t);await Or("Executing longclick...","longclick failed",r,async i=>{Fn(n,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await $t(t.device),{x:a,y:c}=await $n(o,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await pt(o,s,["uitest","uiInput","longClick",String(a),String(c)]),i.succeed(`longclick at (${a}, ${c})`)})}async function lx(n,e,t,r,i){let o=Mr("swipe",i);await Or("Executing swipe...","swipe failed",o,async s=>{Ne(n,"x1"),Ne(e,"y1"),Ne(t,"x2"),Ne(r,"y2");let a=Gi(i.speed),{hdcPath:c,deviceId:l}=await $t(i.device),d=["uitest","uiInput","swipe",n,e,t,r];a&&d.push(a),await pt(c,l,d),s.succeed(`swipe from (${n}, ${e}) to (${t}, ${r})`)})}async function dx(n,e,t,r,i){let o=Mr("fling",i);await Or("Executing fling...","fling failed",o,async s=>{Ne(n,"x1"),Ne(e,"y1"),Ne(t,"x2"),Ne(r,"y2");let a=Gi(i.speed),{hdcPath:c,deviceId:l}=await $t(i.device),d=["uitest","uiInput","fling",n,e,t,r];a&&d.push(a),await pt(c,l,d),s.succeed(`fling from (${n}, ${e}) to (${t}, ${r})`)})}async function ux(n,e,t,r,i){let o=Mr("drag",i);await Or("Executing drag...","drag failed",o,async s=>{Ne(n,"x1"),Ne(e,"y1"),Ne(t,"x2"),Ne(r,"y2");let a=Gi(i.speed),{hdcPath:c,deviceId:l}=await $t(i.device),d=["uitest","uiInput","drag",n,e,t,r];a&&d.push(a),await pt(c,l,d),s.succeed(`drag from (${n}, ${e}) to (${t}, ${r})`)})}async function px(n,e){let t=Mr("dircfling",e);await Or("Executing dircfling...","dircfling failed",t,async r=>{let i=Os[n];if(i===void 0)throw new Error(`Invalid direction "${n}". Valid values: ${Object.keys(Os).join(", ")}`);let{hdcPath:o,deviceId:s}=await $t(e.device);await pt(o,s,["uitest","uiInput","dircFling",i]),r.succeed(`dircfling ${n}`)})}async function mx(n,e,t,r){let i=Mr("text",r);await Or("Executing text input...","input failed",i,async o=>{Fn(e,t,r.id,r.window,!1),_s(n,"text");let{hdcPath:s,deviceId:a}=await $t(r.device),c=ox(n);if(e!==void 0)await pt(s,a,[`uitest uiInput inputText ${e} ${t} ${c}`]),o.succeed(`input ${n} at (${e}, ${t})`);else if(r.id){let{x:l,y:d}=await $n(s,a,void 0,void 0,r.id,r.window);await pt(s,a,[`uitest uiInput inputText ${l} ${d} ${c}`]),o.succeed(`input ${n} at (${l}, ${d})`)}else await pt(s,a,[`uitest uiInput text ${c}`]),o.succeed(`input ${n}`)})}var mv=new Nr("click").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Tap at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(sx),fv=new Nr("doubleclick").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Double-tap at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(ax),hv=new Nr("longclick").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Long-press at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(cx),gv=new Nr("swipe").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Swipe from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(lx),yv=new Nr("fling").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Fling from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(dx),vv=new Nr("drag").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Drag from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(ux),wv=new Nr("dircfling").argument("<direction>","Direction: up, down, left, right").description("Fling in a specified direction").option("--device <name|serial>","Target device (name or serial)").action(px),Sv=new Nr("text").argument("<text>","Text to input").argument("[x]","Optional X coordinate").argument("[y]","Optional Y coordinate").description("Input text at a target location or the currently focused field").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id to target before input (auto-resolves to center)").option("--window <windowId>","Target window id (used with --id)").action(mx);var ot=new fx("ui").description("Inspect and interact with UI on a connected device");ot.addCommand(sv);ot.addCommand(ou);ot.addCommand(av);ot.addCommand(xo);ot.addCommand(mv);ot.addCommand(fv);ot.addCommand(hv);ot.addCommand(gv);ot.addCommand(yv);ot.addCommand(vv);ot.addCommand(wv);ot.addCommand(Sv);var bv=ot;import{Command as rw,InvalidArgumentError as dN}from"commander";import{execa as $x}from"execa";import Bt from"fs";import*as uu from"os";import*as _ from"path";var hx=new RegExp("\x1B\\[[0-?]*[ -/]*[@-~]","g"),gx=/\r/g,yx=/^(Working|Finished)\.\.\.\[[^\]]*\]\d+%$/,vx=/^<+\s*/,wx=/\s*>+$/,Sx=[/^The configuration file .+ is in use\.$/,/^The configuration file .+ in the project is in use\.$/,/^Currently active product: ?.+$/,/^Writing the result to .+\.$/,/^Write finished\.$/,/^CodeLinter found some defects in your code\.$/],bx=new Set([1]);function cu(n){if(!n)return"";let e=n.replace(hx,"").replace(gx,`
|
|
1331
1335
|
`).split(`
|
|
1332
|
-
`).map(
|
|
1336
|
+
`).map(Ex).map(t=>t.trimEnd()).filter(t=>Cx(t));return e.length>0?`${e.join(`
|
|
1333
1337
|
`)}
|
|
1334
|
-
`:""}function
|
|
1335
|
-
[output truncated: exceeded ${
|
|
1336
|
-
`};if(
|
|
1337
|
-
`);if(t.length>1&&t.every(
|
|
1338
|
+
`:""}function Ex(n){let e=n.trim();if(!e.startsWith("{"))return n;try{let t=JSON.parse(e);return typeof t.content!="string"||typeof t.messageType!="number"?n:bx.has(t.messageType)?"":t.content}catch{return n}}var Ev=50*1024*1024;function Iv(n){let e=cu(n).trim();if(!e)return{jsonText:void 0,diagnostics:""};if(e.length>Ev)return{jsonText:void 0,diagnostics:`${e.slice(0,1024)}
|
|
1339
|
+
[output truncated: exceeded ${Ev} bytes]
|
|
1340
|
+
`};if(au(e))return{jsonText:e,diagnostics:""};let t=e.split(`
|
|
1341
|
+
`);if(t.length>1&&t.every(au))return{jsonText:JSON.stringify(t.map(o=>JSON.parse(o))),diagnostics:""};let r=kx(e);if(!r)return{jsonText:void 0,diagnostics:`${e}
|
|
1338
1342
|
`};let i=[e.slice(0,r.start).trim(),e.slice(r.end).trim()].filter(Boolean).join(`
|
|
1339
1343
|
`);return{jsonText:e.slice(r.start,r.end),diagnostics:i?`${i}
|
|
1340
|
-
`:""}}function
|
|
1341
|
-
${
|
|
1342
|
-
`;let t=e===void 0?n.issues:n.issues.slice(0,e),r=[
|
|
1344
|
+
`:""}}function Px(n){return yx.test(n.trim())}function Cx(n){let e=n.trim();return!!e&&!Px(e)&&!Sx.some(t=>t.test(e))}function au(n){try{return JSON.parse(n),!0}catch{return!1}}function kx(n){for(let e=0;e<n.length;e++){let t=n[e];if(t!=="["&&t!=="{")continue;let i=Ix(n,e,t,t==="["?"]":"}");if(i!==-1&&au(n.slice(e,i+1)))return{start:e,end:i+1}}}function Ix(n,e,t,r){let i=0,o=!1,s=!1;for(let a=e;a<n.length;a++){let c=n[a];if(s){s=!1;continue}if(c==="\\"&&o){s=!0;continue}if(c==='"'){o=!o;continue}if(!o){if(c===t)i++;else if(c===r&&(i--,i===0))return a}}return-1}var Pv=["Error","Warning","Suggestion","Info","Off","Unknown"];function Dv(n){let e=lu(n);return{issues:Tx(e),summary:Dx(n,e)}}function Dx(n,e){let t=Lx(e);return{filesChecked:Nx(n).size,issues:e.length,errors:t.get("Error")??0,warnings:t.get("Warning")??0,suggestions:t.get("Suggestion")??0}}function lu(n,e=""){if(Array.isArray(n))return n.flatMap(o=>lu(o,e));if(!Av(n))return[];let t=Lo(n,["filePath","file","path"])??e,r=Ax(n,t);if(r.length>0)return r;let i=Rx(n,t);return i?[i]:[]}function Ax(n,e){let t=["messages","defects","issues","results","files"];for(let r of t){let i=n[r];if(Array.isArray(i)){let o=i.flatMap(s=>lu(s,e));if(o.length>0)return o}}return[]}function Rx(n,e){let t=Lo(n,["message","description","desc","detail"])??"",r=Fx(Lo(n,["rule","ruleId","ruleName"])),i=Ox(n,["severity","level"]),o=Lo(n,["filePath","file","path"])??e;if(!(!t&&!r&&i==="Unknown"))return{file:o,line:kv(n,["line","reportLine"]),column:kv(n,["column","reportColumn"]),severity:i,rule:r,message:t}}function Tx(n){return[...n].sort((e,t)=>{let r=Cv(e.severity)-Cv(t.severity);return r===0?xx(e,t):r})}function xx(n,e){let t=n.file.localeCompare(e.file);if(t!==0)return t;let r=(n.line??Number.MAX_SAFE_INTEGER)-(e.line??Number.MAX_SAFE_INTEGER);return r!==0?r:(n.column??Number.MAX_SAFE_INTEGER)-(e.column??Number.MAX_SAFE_INTEGER)}function Lx(n){let e=new Map;for(let t of n){let r=t.severity;e.set(r,(e.get(r)??0)+1)}return e}function Nx(n){let e=new Set;return du(e,n,""),e}function du(n,e,t){if(Array.isArray(e)){for(let i of e)du(n,i,t);return}if(!Av(e))return;let r=Lo(e,["filePath","file","path"])??t;r&&n.add(r),Mx(n,e,r)}function Mx(n,e,t){let r=["messages","defects","issues","results","files"];for(let i of r){let o=e[i];if(Array.isArray(o))for(let s of o)du(n,s,t)}}function Ox(n,e){for(let t of e){let r=n[t];if(typeof r=="string"||typeof r=="number")return _x(r)}return"Unknown"}function _x(n){let e=String(n).normalize("NFKC").trim().toLowerCase();return e==="2"||e==="error"||e==="err"?"Error":e==="1"||e==="warn"||e==="warning"?"Warning":e==="3"||e==="suggest"||e==="suggestion"?"Suggestion":e==="info"||e==="information"?"Info":e==="0"||e==="off"?"Off":"Unknown"}function Fx(n){let e=n?.normalize("NFKC").trim();if(e)return e.replace(vx,"").replace(wx,"").toLowerCase()}function Cv(n){let e=Pv.indexOf(n);return e===-1?Pv.length:e}function Lo(n,e){for(let t of e){let r=n[t];if(typeof r=="string")return r}}function kv(n,e){for(let t of e){let r=n[t];if(typeof r=="number")return r}}function Av(n){return typeof n=="object"&&n!==null}var _r=class extends Error{code;constructor(e,t,r){super(t,r),this.name="ValidationError",this.code=e}},Rv="deveco-codelinter-",Tv=[".ets",".ts",".js"],No=class n{resolution;cwd;toolProvider;constructor(e,t){this.toolProvider=e,this.resolution=n.resolveWithToolProvider(e),this.cwd=t}get supportsReportOptions(){return!this.resolution.isLegacyStudioArgs}static resolveProjectRoot(e){try{return q.discover(e).rootDir}catch{return e}}async check(e){let t=Bt.mkdtempSync(_.join(uu.tmpdir(),Rv)),r=_.join(t,"report.json");try{let i=n.resolveProjectRoot(this.cwd),o=this.resolveLintTarget(e.lintPath,i),s=this.resolveConfigPath(e.configPath,o),a=this.buildNativeArgs(e,o.path,s,r,t,o.projectRoot??i),c=await this.run(a),l=Iv(c.stdout),d=l.diagnostics+cu(c.stderr);try{let g=this.readJsonReport(r,l.jsonText);return{exitCode:c.exitCode,diagnostics:d,report:Dv(g)}}catch(g){return{exitCode:c.exitCode,diagnostics:d,reportError:g}}}finally{this.removeTempDir(t)}}resolveLintTarget(e,t){let r=e?_.resolve(this.cwd,e):t,i=this.resolveRealPath(r,"Lint path"),o=Bt.statSync(i);if(!o.isFile()&&!o.isDirectory())throw new _r("errorCode",`Lint path must be a file or directory: ${r}`);if(o.isFile()){let a=_.extname(i).toLowerCase();if(!Tv.some(l=>l===a))throw new Error(`Unsupported lint file extension "${a||"<none>"}": ${i}. Supported extensions: ${Tv.join(", ")}.`)}let s=this.discoverProjectRoot(i,o.isDirectory());if(e!==void 0&&s===void 0)throw new _r("errorCode",`Lint path is not in a valid project directory (project-level build-profile.json5 not found or invalid): ${i}`);return{path:i,projectRoot:s}}resolveConfigPath(e,t){let r=e?_.resolve(this.cwd,e):_.join(t.projectRoot??this.cwd,"code-linter.json5"),i=this.resolveRealPath(r,"`--config-path`");if(!Bt.statSync(i).isFile())throw new _r("errorCode",`--config-path must point to a file: ${r}`);if(t.projectRoot){let o=this.discoverProjectRoot(i,!1);if(o===void 0||_.relative(t.projectRoot,o)!=="")throw new _r("errorCode",`\`--config-path\` must belong to the same project as the lint path. Lint project: ${t.projectRoot}; Config project: ${o??"not found"}.`)}return i}discoverProjectRoot(e,t){let r=t?e:_.dirname(e);try{return Bt.realpathSync(q.discover(r).rootDir)}catch{return}}resolveRealPath(e,t){try{return Bt.realpathSync(e)}catch(r){throw new _r("errorCode",`${t} does not exist or cannot be resolved: ${e}`,{cause:r})}}buildNativeArgs(e,t,r,i,o,s){if(this.resolution.isLegacyStudioArgs)return this.buildLegacyNativeArgs(e,t,r,o,s);let a=["--config",r];return e.fix&&a.push("--fix"),e.incremental&&a.push("--incremental"),a.push("--product",e.product,"--format","json","--output",i,t),a}buildLegacyNativeArgs(e,t,r,i,o){let s=String(this.toolProvider.getMaxApiLevel()),a=this.toolProvider.getSdkPlatformVersion(),c=_.join(i,"check-paths.json");Bt.writeFileSync(c,JSON.stringify([t]),"utf8");let l=["--dir",c,"--isTooManyFiles","true","--config",r,"--product",e.product,"--sdkPath",this.toolProvider.sdkPath,"--sdkNumberVersion",s,"--sdkStringVersion",a,"--project",o,"--logPath",_.join(i,"codelinter.log"),"--workdir",_.dirname(this.toolProvider.codelinterPath),"--inIde","true"];return e.fix&&l.push("--fix","true"),e.incremental&&l.push("--incremental","true"),l}async run(e){let t=this.resolution.isLegacyStudioArgs?[this.resolution.argsPrefix[0],...e]:[...this.resolution.argsPrefix,...e],r=this.resolution.workingDirectory??this.cwd;this.prepareRuntimeDirectories(),p(`Executing: ${this.resolution.command} ${t.join(" ")}`),p(`[CodelinterAdapter] Working directory: ${r}`);let i=await $x(this.resolution.command,t,{cwd:r,env:this.resolution.env,stdout:"pipe",stderr:"pipe",reject:!1});return{exitCode:i.exitCode??1,stdout:i.stdout,stderr:i.stderr}}prepareRuntimeDirectories(){for(let e of this.resolution.runtimeDirectories??[])Bt.mkdirSync(e,{recursive:!0})}readJsonReport(e,t){let i=(Bt.existsSync(e)?Bt.readFileSync(e,"utf-8").trim():void 0)||t?.trim();if(!i)throw new _r("errorCode","Native JSON report was not generated.");return JSON.parse(i)}removeTempDir(e){let t=_.resolve(e),r=_.resolve(uu.tmpdir());!(t.startsWith(`${r}${_.sep}`)||t===r)||!_.basename(t).startsWith(Rv)||Bt.rmSync(t,{recursive:!0,force:!0})}static isModernStudioEntry(e){let t=["plugins","codelinter","run","index.js"],r=_.normalize(e).split(_.sep).slice(-t.length);return t.every((i,o)=>r[o]?.toLowerCase()===i)}static resolveWithToolProvider(e){let t=n.getSource(e),r=e.toolchainRoot,i=e.codelinterPath,o=e.sdkPath,s=n.getPathEntries(e,t),a=t==="ide"?"DevEco Studio":"DevEco Command Line Tools",c=t==="ide"&&!n.isModernStudioEntry(i),l={command:e.nodePath,argsPrefix:[i,o],env:{...process.env,PATH:[...s,process.env.PATH||""].join(_.delimiter),DEVECO_SDK_HOME:o},isLegacyStudioArgs:c};return t==="command-line-tools"&&(l.workingDirectory=r,l.runtimeDirectories=[n.getResultDirectory(i)]),p(`[CodelinterAdapter] Selected ${a} entry: ${i}`),l}static getPathEntries(e,t){let r=[_.dirname(e.nodePath)];return t==="ide"&&e.javaPath&&r.unshift(_.dirname(e.javaPath)),r}static getResultDirectory(e){return _.resolve(e,"..","linter","result")}static getSource(e){return e.sourceType==="studio"?"ide":"command-line-tools"}};import{red as fc,yellow as $v}from"colorette";import{Argument as Yx,Command as Kx,InvalidArgumentError as $r}from"commander";import Oo from"fs";import*as Ye from"path";import*as Mo from"path";var xv="n/a",Lv=/\\/g,jx=/\|/g,Hx=/\r?\n/g;function Nv(n,e){if(n.issues.length===0)return`No defects found.
|
|
1345
|
+
${pu(n.summary)}
|
|
1346
|
+
`;let t=e===void 0?n.issues:n.issues.slice(0,e),r=[Bx(t),pu(n.summary)];return e!==void 0&&t.length<n.issues.length&&r.push(Ux(n.issues.length,t.length)),`${r.join(`
|
|
1343
1347
|
`)}
|
|
1344
|
-
`}function
|
|
1345
|
-
`)}function
|
|
1346
|
-
`)}function
|
|
1347
|
-
`}function
|
|
1348
|
-
`)}function
|
|
1348
|
+
`}function Mv(n,e){return[pu(n.summary),`Full report: ${mu(e)}`,""].join(`
|
|
1349
|
+
`)}function Ov(n){let e=["# CodeLinter report",""];return n.issues.length===0?e.push("No defects found.",""):e.push(...Wx(n.issues),""),e.push("## Summary","",...Gx(n.summary),""),e.join(`
|
|
1350
|
+
`)}function _v(n){return`${JSON.stringify(n,null,2)}
|
|
1351
|
+
`}function pu(n){return`Summary: Issues: ${yt(n.issues)} | Errors: ${yt(n.errors)} | Warnings: ${yt(n.warnings)} | Suggestions: ${yt(n.suggestions)} | Files checked: ${yt(n.filesChecked)}`}function Ux(n,e){return`Showing ${yt(e)} of ${yt(n)} issues. Use --output-path <path> to write all results.`}function Bx(n){let e=["No","File","Line","Column","Severity","Rule","Message"],t=n.map((r,i)=>({cells:zx(r,i+1)}));return["CodeLinter report","",Xt(e,t)].join(`
|
|
1352
|
+
`)}function Wx(n){let e=["| No | File | Line | Column | Severity | Rule | Message |","| ---: | --- | ---: | ---: | --- | --- | --- |"];for(let[t,r]of n.entries())e.push(Vx(r,t+1));return e}function Vx(n,e){return`| ${[String(e),mu(Fr(n.file)),mc(n.line),mc(n.column),Fr(n.severity),Fr(n.rule),Fr(n.message)].map(qx).join(" | ")} |`}function Gx(n){return[`- Issues: ${yt(n.issues)}`,`- Errors: ${yt(n.errors)}`,`- Warnings: ${yt(n.warnings)}`,`- Suggestions: ${yt(n.suggestions)}`,`- Files checked: ${yt(n.filesChecked)}`]}function qx(n){return n.replace(Lv,"\\\\").replace(jx,"\\|").replace(Hx,"<br>")}function zx(n,e){return[String(e),mu(Fr(Jx(n.file))),mc(n.line),mc(n.column),Fr(n.severity),Fr(n.rule),Fr(n.message)]}function Jx(n){if(!Mo.isAbsolute(n))return n;let e=Mo.relative(process.cwd(),n);return!e||e.startsWith("..")||Mo.isAbsolute(e)?n:e}function mu(n){return n.replace(Lv,"/")}function Fr(n){let e=n?.trim();return e||xv}function mc(n){return n===void 0?xv:String(n)}function yt(n){return n.toLocaleString("en-US")}var fu=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function Xx(n){let e=n;return n instanceof fu?n.code:e.code??e.name??"UnknownError"}async function Fv(n,e,t,r){let i=await Qe(process.pid),o=i!==null?te(Number(i)*1024):"unknown",s={event:b.CheckCommand,args:r,mcpMemory:o,lspMemory:"unknown"},a={duration_ms:Date.now()-n,success:e,error_code:t};await k.track(s,a).catch(()=>{})}var Zx=/^-?\d+$/;function hu(){return new Kx("lint").description("Run DevEco Code Linter checks for TS/ArkTS code").helpOption("-h, --help","display help for command").addArgument(new Yx("[path]","File or directory to lint").argParser(nL)).option("--fix","Auto-fix fixable code issues").option("--incremental","Only check uncommitted files").option("--config-path <path>","Path to lint configuration file",eL).option("--product <product>","Product name defined in build-profile.json5",tL,"default").option("--format <format>","Report format (choices: default, json)",Qx,"default").option("--output-path <path>","Complete report file or directory",rL).option("--limit <number>","Maximum terminal issues to display when --output-path is omitted",iL).action(oL)}function Qx(n){if(n==="default"||n==="json")return n;throw new $r("Invalid --format. Expected one of: default, json.")}function eL(n){gu(n,"--config-path");let e=Ye.extname(n).toLowerCase();if(e!==".json"&&e!==".json5")throw new $r("`--config-path` must point to a .json or .json5 file.");return n}function tL(n){return jv(n,"product"),n}function rL(n){return gu(n,"--output-path"),n}function nL(n){return gu(n,"path"),n}function iL(n){if(jv(n,"limit"),!Zx.test(n))throw new $r("`--limit` must be a positive integer.");let e=Number.parseInt(n,10);if(e<=0||!Number.isSafeInteger(e))throw new $r("`--limit` must be an integer greater than 0.");return e}function jv(n,e){if(n.trim().length===0||Bv(n))throw new $r(`Invalid --${e} value.`)}function gu(n,e){let t=`\`${e}\``;if(n.length===0||Bv(n))throw new $r(`${t} must be a non-empty path without control characters.`)}async function oL(n,e,t){let r=Date.now(),i=["check","lint"];try{let o=process.cwd(),s=await C.new(),a=new No(s,o),c=cL(s,a,t,e),l=pL(c.outputPath,c.format,o);e.fix&&console.warn($v("Running codelinter with --fix. Ensure your project source is trusted."));let d=await sL(a,n,e);yL(d.diagnostics),process.exitCode=dL(d,l,c.format,e.limit,o),await Fv(r,!0,null,i)}catch(o){let s=Xx(o);throw await Fv(r,!1,s,i),o}}async function sL(n,e,t){return lL(n,{lintPath:e,configPath:t.configPath,product:t.product,fix:t.fix,incremental:t.incremental})}function aL(n){return[["format","--format"],["outputPath","--output-path"]].filter(([e])=>n.getOptionValueSource(e)==="cli").map(([,e])=>e)}function cL(n,e,t,r){let i=aL(t);if(i.length===0||e.supportsReportOptions)return r;let o=ur(n.toolchainRoot),s=i.length===1?"option":"options";return console.warn($v(`Warning: The detected DevEco Studio version is: ${o??"unknown"}. The bundled legacy Code Linter does not support ${s}: ${i.join(", ")}. Action: ignore the unsupported ${s} and continue the lint check with default terminal output.`)),{format:i.includes("--format")?"default":r.format,outputPath:i.includes("--output-path")?void 0:r.outputPath}}async function lL(n,e){let t=new it;process.stderr.isTTY&&t.start("Checking code...");try{let r=await n.check(e);return t.stop(),r}catch(r){throw t.fail("Code check failed"),r}}function dL(n,e,t,r,i){if(!n.report)return console.error(fc("Failed to generate Code Linter report.")),console.error(fc(n.reportError?.message??"Native JSON report was not generated.")),n.exitCode===0?1:n.exitCode;try{if(e){uL(e,t,n.report);let o=Uv(e,i);process.stdout.write(Mv(n.report,o))}else process.stdout.write(Nv(n.report,r));return n.exitCode}catch(o){return console.error(fc("Failed to generate Code Linter report.")),console.error(fc(o.message)),n.exitCode===0?1:n.exitCode}}function uL(n,e,t){Oo.mkdirSync(Ye.dirname(n),{recursive:!0});let r=e==="json"?_v(t):Ov(t);try{Oo.writeFileSync(n,r,{encoding:"utf-8",flag:"wx"})}catch(i){throw i.code==="EEXIST"?new Error(`Output file already exists: ${n}`,{cause:i}):i}}function pL(n,e,t){if(!n)return;let r=hL(n,t),i=fL(n,r),o=i?Ye.join(r,gL(e)):r;if(i||mL(n,e),Oo.existsSync(o))throw new $r(`Output file already exists: ${Uv(o,t)}`);return o}function mL(n,e){let t=Hv(e);if(Ye.extname(n).toLowerCase()!==t)throw new $r(`--output-path must use the ${t} extension for --format ${e}.`)}function fL(n,e){return Oo.existsSync(e)?Oo.statSync(e).isDirectory():n.endsWith("/")||n.endsWith("\\")||Ye.extname(n)===""}function hL(n,e){return Ye.resolve(e,n)}function gL(n){let e=new Date,t=[e.getFullYear(),e.getMonth()+1,e.getDate()].map((o,s)=>String(o).padStart(s===0?4:2,"0")).join(""),r=[e.getHours(),e.getMinutes(),e.getSeconds()].map(o=>String(o).padStart(2,"0")).join(""),i=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${r}-${i}${Hv(n)}`}function Hv(n){return n==="json"?".json":".md"}function Uv(n,e){let t=Ye.relative(e,n);return t&&!t.startsWith("..")&&!Ye.isAbsolute(t)?t:n}function yL(n){n&&process.stderr.write(n)}function Bv(n){for(let e of n){let t=e.charCodeAt(0);if(t<=31||t===127)return!0}return!1}import{execa as vL}from"execa";import ar from"fs";import wL from"os";import*as Y from"path";import{fileURLToPath as SL}from"url";var Wv=Y.join("resources","arkts-check.cjs"),_o=class{toolProvider;cwd;constructor(e,t){this.toolProvider=e,this.cwd=t}async check(e){let t=this.resolveProjectRoot(e.projectRoot,e.files),r=this.resolveFiles(t,e.files),i=this.resolveScriptPath(),o=this.buildArgs(i,t,r,e.fix),s=this.buildEnv();p(`Executing: ${this.toolProvider.nodePath} ${o.join(" ")}`);let a=await vL(this.toolProvider.nodePath,o,{cwd:t,env:s,stdout:"pipe",stderr:"pipe",reject:!1});return this.parseResult(a.stdout,a.stderr,a.exitCode??1)}resolveProjectRoot(e,t){if(e){let i=Y.resolve(this.cwd,e);if(!ar.existsSync(i))throw new Error(`Project path not found: ${i}`);if(ar.statSync(i).isFile()){let s=this.discoverRootFrom(Y.dirname(i));if(s)return s;throw new Error(`--project path is a file, not a project root: ${i}
|
|
1349
1353
|
Could not find a project-level build-profile.json5 above it. Pass the project root directory instead.`)}if(this.discoverRootFrom(i)!==i)throw new Error(`Not a valid Harmony project root: ${i}
|
|
1350
|
-
(project-level build-profile.json5 not found).`);return i}if(t&&t.length>0)for(let i of t){let o=Y.isAbsolute(i)?i:Y.resolve(this.cwd,i),s=this.discoverRootFrom(Y.dirname(o));if(s)return s}let r=this.discoverRootFrom(this.cwd);if(r)return r;throw new Error("Not in a valid Harmony project directory (project-level build-profile.json5 not found). Run this command inside a project, or pass --project <path>.")}discoverRootFrom(e){try{return q.discover(e).rootDir}catch{return}}resolveFiles(e,t){if(t.length===0)return[];let r=t.map(a=>{if(Y.isAbsolute(a))return a;let c=Y.resolve(this.cwd,a);return
|
|
1354
|
+
(project-level build-profile.json5 not found).`);return i}if(t&&t.length>0)for(let i of t){let o=Y.isAbsolute(i)?i:Y.resolve(this.cwd,i),s=this.discoverRootFrom(Y.dirname(o));if(s)return s}let r=this.discoverRootFrom(this.cwd);if(r)return r;throw new Error("Not in a valid Harmony project directory (project-level build-profile.json5 not found). Run this command inside a project, or pass --project <path>.")}discoverRootFrom(e){try{return q.discover(e).rootDir}catch{return}}resolveFiles(e,t){if(t.length===0)return[];let r=t.map(a=>{if(Y.isAbsolute(a))return a;let c=Y.resolve(this.cwd,a);return ar.existsSync(c)?c:Y.resolve(e,a)}),i=r.filter(a=>!ar.existsSync(a));if(i.length>0)throw new Error(`File(s) not found:
|
|
1351
1355
|
`+i.map(a=>` ${a}`).join(`
|
|
1352
1356
|
`));let o=r.filter(a=>{let c=Y.relative(e,a);return c.startsWith("..")||Y.isAbsolute(c)});if(o.length>0)throw new Error(`File(s) outside the project root ${e}:
|
|
1353
1357
|
`+o.map(a=>` ${a}`).join(`
|
|
1354
|
-
`));let s=r.filter(a=>
|
|
1358
|
+
`));let s=r.filter(a=>ar.statSync(a).isFile()&&a.endsWith(".ets")&&!a.endsWith(".d.ets"));if(s.length===0)throw new Error(`No .ets files found in the given file(s):
|
|
1355
1359
|
`+r.map(a=>` ${a}`).join(`
|
|
1356
|
-
`));return s}buildArgs(e,t,r,i){let o=[e,"--project",t];return o.push(i?"--fix":"--no-fix"),r.length>0&&o.push("--files",...r),o}buildEnv(){return{...process.env,DEVECO_HOME:this.resolveDevecoHome()}}resolveDevecoHome(){let e=this.toolProvider.toolchainRoot;if(
|
|
1357
|
-
Warnings (${r}):`));for(let i of t){let o=i.rule?` (${i.rule})`:"";console.warn(
|
|
1358
|
-
`))}await
|
|
1359
|
-
`?(t.push(r),e.push(t),t=[],r="",o+=1):(s==="\r"||(r+=s),o+=1)}return(r.length>0||t.length>0)&&(t.push(r),e.push(t)),e}function
|
|
1360
|
+
`));return s}buildArgs(e,t,r,i){let o=[e,"--project",t];return o.push(i?"--fix":"--no-fix"),r.length>0&&o.push("--files",...r),o}buildEnv(){return{...process.env,DEVECO_HOME:this.resolveDevecoHome()}}resolveDevecoHome(){let e=this.toolProvider.toolchainRoot;if(wL.platform()==="darwin"&&!ar.existsSync(Y.join(e,"sdk"))){let t=Y.join(e,"Contents");if(ar.existsSync(Y.join(t,"sdk")))return t}return e}parseResult(e,t,r){let i=e.trim();if(!i){let o=t.trim();throw new Error(`arkts-check exited with code ${r} but produced no output`+(o?`: ${o}`:""))}try{let o=JSON.parse(i);return{success:o.success??!1,error:o.error,errors:o.errors??[],fixed:o.fixed??[],alsoModified:o.alsoModified??[],summary:{errorCount:o.summary?.errorCount??0,warnCount:o.summary?.warnCount??0,fixedCount:o.summary?.fixedCount??0,checkerDiagCount:o.summary?.checkerDiagCount,fileCount:o.summary?.fileCount??0}}}catch(o){throw new Error(`Failed to parse arkts-check output: ${i.slice(0,500)}`,{cause:o})}}resolveScriptPath(){let e=SL(import.meta.url),t=Y.dirname(e);if(e.includes("dist")){let s=Y.dirname(t),a=Y.join(s,"src",Wv);if(ar.existsSync(a))return a}let r=Y.dirname(t),i=Y.dirname(r),o=Y.join(i,"src",Wv);if(ar.existsSync(o))return o;throw new Error("arkts-check.cjs not found in deveco-cli package resources. Reinstall deveco-cli.")}};import{red as vu,yellow as wu,green as Vv}from"colorette";import{Command as bL}from"commander";function EL(n){let e=n;return e.code??e.name??"UnknownError"}async function yu(n,e,t,r){let i=await Qe(process.pid),o=i!==null?te(Number(i)*1024):"unknown",s={event:b.CheckCommand,args:r,mcpMemory:o,lspMemory:"unknown"},a={duration_ms:Date.now()-n,success:e,error_code:t};await k.track(s,a).catch(()=>{})}function Su(){return new bL("arkts").description("Run ArkTS static checks on .ets source files").arguments("[files...]").option("--fix","Auto-fix high-confidence errors before reporting").option("--project <path>","Project root directory (default: auto-detected from cwd)").action(async(n,e)=>{await PL(n,e)})}async function PL(n,e){let t=Date.now(),r=["check","arkts"];try{let i=await C.new(),o=new _o(i,process.cwd()),s=new it;process.stderr.isTTY&&s.start("Checking ArkTS...");let a;try{a=await o.check({files:n,fix:e.fix,projectRoot:e.project})}catch(c){throw s.fail("ArkTS check failed"),c}if(a.error&&a.errors.length===0){s.fail("ArkTS check failed"),console.error(vu(a.error)),process.exitCode=1,await yu(t,!1,"CheckFailed",r);return}s.stop(),CL(a),await yu(t,!0,null,r)}catch(i){throw await yu(t,!1,EL(i),r),i}}function CL(n){let{errorCount:e,warnCount:t,fixedCount:r,fileCount:i}=n.summary;if(kL(n.fixed,r,n.alsoModified),e===0){console.log(Vv(`No errors found in ${i} file(s).`)),Gv(n.errors);return}IL(n.errors,e,t),process.exitCode=1}function kL(n,e,t){if(n.length!==0){console.log(Vv(`\u2713 Auto-fixed ${e} issue(s):`));for(let r of n)console.log(` ${r.file}:${r.line}:${r.column} - ${r.message}`);if(t.length>0){console.log(wu(`Note: auto-fix also modified ${t.length} file(s) outside the checked list (added missing 'export'):`));for(let r of t)console.log(` ${r}`)}console.log()}}function IL(n,e,t){let r=n.filter(i=>i.severity==="error");console.error(vu(`ArkTS check found ${e} error(s):`));for(let i of r){let o=i.rule?` (${i.rule})`:"";console.error(vu(`${i.file}:${i.line}:${i.column} - ${i.severity}: ${i.message}${o}`))}Gv(n,t)}function Gv(n,e){let t=n.filter(i=>i.severity!=="error");if(t.length===0)return;let r=e??t.length;console.warn(wu(`
|
|
1361
|
+
Warnings (${r}):`));for(let i of t){let o=i.rule?` (${i.rule})`:"";console.warn(wu(`${i.file}:${i.line}:${i.column} - ${i.severity}: ${i.message}${o}`))}}import{InvalidArgumentError as DL}from"commander";import*as X from"path";import*as bu from"os";import{readdirSync as AL,existsSync as hc,readFileSync as RL,unlinkSync as TL,copyFileSync as Yv,writeFileSync as Kv}from"fs";import{execa as xL}from"execa";import{cyan as Ee,yellow as Xv}from"colorette";import LL from"ora";var se=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function Eu(n){let e=n;return n instanceof se?n.code:e.code??e.name??"UnknownError"}async function Si(n,e,t,r){let i=await Qe(process.pid),o=i!==null?te(Number(i)*1024):"unknown",s={event:b.CheckCommand,args:r,mcpMemory:o,lspMemory:"unknown"},a={duration_ms:Date.now()-n,success:e,error_code:t};await k.track(s,a).catch(()=>{})}var NL=["default","csv","json"],qv=["default","json"];function ML(n){return[...n].sort((e,t)=>{let r=zv(e),i=zv(t);return r.apiVersion-i.apiVersion||r.suffix.localeCompare(i.suffix)})}function zv(n){let e=n.match(/\((\d+)\)/),t=e?Number(e[1]):0,r=n.lastIndexOf("_"),i=r>=0?n.slice(r+1):n;return{apiVersion:t,suffix:i}}function Zv(n){let t=AL(n,{withFileTypes:!0}).filter(r=>r.isFile()&&r.name.toLowerCase().endsWith(".json")).map(r=>r.name.slice(0,-5));return ML(t)}async function Qv(n){if(n=n===void 0?"default":n,!qv.includes(n))throw new Error(`--format must be ${qv.join(" or ")}. got "${n}"`);let e=Date.now(),t=["check","compat","versions"];try{let r=await C.new(),{apiChangeDir:i}=r.getApiscanPaths();p(Ee(`[compat:versions] apiChangeDir: "${i}"`));let o=Zv(i);if(n==="json")console.log(JSON.stringify({versions:o,count:o.length},null,2));else{if(o.length===0){console.log("No SDK versions available."),await Si(e,!0,null,t);return}console.log(o.join(`
|
|
1362
|
+
`))}await Si(e,!0,null,t)}catch(r){let i=Eu(r);throw await Si(e,!1,i,t),r}}var Jv=new Set([".ets",".c",".cpp"]);function OL(n,e){let t=new Set(n.profile.modules.map(s=>s.name)),r=e.filter(s=>!t.has(s));if(r.length===0)return;let i=n.profile.modules.map(s=>s.name).join(", "),o=r.length>1?"are":"is";throw new se("errorCode",`Module ${r.map(s=>`"${s}"`).join(", ")} ${o} not defined in build-profile.json5. Available modules: ${i}.`)}function _L(n){for(let e of n){let t=X.resolve(e);if(!hc(t))throw new se("errorCode",`File "${e}" does not exist.`);let r=X.extname(t).toLowerCase();if(!Jv.has(r)){let i=Array.from(Jv).join(", ");throw new se("errorCode",`Unsupported file extension "${r}" for "${e}". Supported: ${i}.`)}}}function FL(n){let e=[],t=[];for(let r of n)X.extname(r).toLowerCase()===".ets"?e.push(r):t.push(r);return{arkTs:e,cpp:t}}function $L(n){let e=[],t=[],r="",i=!1,o=0;for(;o<n.length;){let s=n[o];i?{field:r,inQuotes:i,i:o}=jL(n,o,s,r,i):s==='"'?(i=!0,o+=1):s===","?(t.push(r),r="",o+=1):s===`
|
|
1363
|
+
`?(t.push(r),e.push(t),t=[],r="",o+=1):(s==="\r"||(r+=s),o+=1)}return(r.length>0||t.length>0)&&(t.push(r),e.push(t)),e}function jL(n,e,t,r,i){return t!=='"'?{field:r+t,inQuotes:i,i:e+1}:n[e+1]==='"'?{field:r+'"',inQuotes:i,i:e+2}:{field:r,inQuotes:!1,i:e+1}}function HL(n,e){return e.map(t=>{let r=i=>{let o=n.indexOf(i);return o>=0&&o<t.length?t[o]:""};return{apiDefinition:r("Api Definition"),language:r("Language"),changeId:r("ChangeId"),changedInSdk:r("Changed in SDK"),affectedVersions:r("Affected Versions"),title:r("Title"),codeLocation:r("Code Location"),changeType:r("Change Type")}})}function UL(n){let e=RL(n,"utf8"),t=e.startsWith("\uFEFF")?e.slice(1):e,r=$L(t);if(r.length<2)return[];let[i,...o]=r;return HL(i,o)}function BL(n,e){let t=n.match(/CSV saved to:\s*([^\r\n]+\.csv)/);if(!t)return null;let r=t[1].trim();if(X.isAbsolute(r))return r;let i=X.join(e,r);return E.ensurePathWithinRoot(e,i)}function WL(n,e){let t=new Map;for(let o of n){let s=o.changeType||"(unknown)";t.set(s,(t.get(s)??0)+1)}let r=Array.from(t.entries()).sort((o,s)=>s[1]-o[1]||o[0].localeCompare(s[0])),i=Math.max(5,...r.map(([o])=>o.length));console.log(Ee("API change scan summary:")),console.log(` ${"Total".padEnd(i)} ${n.length}`);for(let[o,s]of r)console.log(` ${o.padEnd(i)} ${s}`);e&&console.log(` ${"Report".padEnd(i)} ${e}`)}function VL(n,e){if(console.log(),n.length===0){console.log("No API changes detected.");return}let t=n.slice(0,e),r=n.length-t.length;console.log(Ee(`Details (showing ${t.length}${r>0?` of ${n.length}`:""}):`));let i=[["Title","title"],["Language","language"],["ChangeId","changeId"],["Changed in","changedInSdk"],["Affected Versions","affectedVersions"],["Code Location","codeLocation"]],o=Math.max(...i.map(([a])=>a.length)),s=a=>a||"<unknown>";for(let a of t){console.log(` [${s(a.changeType)}] ${s(a.apiDefinition)}`);for(let[c,l]of i)console.log(` ${c.padEnd(o)} ${s(a[l])}`)}r>0&&console.log(Xv(` ... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function GL(n,e){let t=n.slice(0,e),r=n.length-t.length;console.log(),console.log(JSON.stringify({records:t,count:n.length},null,2)),r>0&&console.log(Xv(`... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function qL(n,e){let t=[];for(let r of e){let i=n.profile.modules.find(o=>o.name===r);if(!i)throw new se("errorCode",`Module "${r}" not found in build-profile.json5.`);t.push(X.resolve(n.rootDir,i.srcPath))}return t}function zL(n,e,t,r){if(!r.sourceVersion||!r.targetVersion)throw new se("errorCode","source-version and target-version are required.");let i=[n,"--startVersion",r.sourceVersion,"--endVersion",r.targetVersion];if(e.length>0){let{arkTs:o,cpp:s}=FL(e),a=d=>X.resolve(process.cwd(),d),c=o.map(a),l=s.map(a);c.length>0&&i.push("--arkTsFiles",c.join(",")),l.length>0&&i.push("--cppFiles",l.join(","))}else if(r.modules&&r.modules.length>0){let o=qL(t,r.modules);i.push("--modulePaths",o.join(","))}else i.push("--projectPath",t.rootDir);return i.push("--outputPath",bu.tmpdir()),i}async function JL(n,e){let t=X.dirname(e[0]);try{let i=(await xL(n.nodePath,e,{cwd:t,stdin:"ignore",stdout:"pipe",stderr:"inherit"})).stdout;return process.env.DEVECO_CLI_DEBUG&&(console.log(Ee("[compat:check] === scan stdout ===")),process.stdout.write(i),i.endsWith(`
|
|
1360
1364
|
`)||process.stdout.write(`
|
|
1361
|
-
`),console.log(
|
|
1365
|
+
`),console.log(Ee("[compat:check] === end stdout ==="))),i}catch(r){let i=r;process.env.DEVECO_CLI_DEBUG&&i.stdout&&(console.log(Ee("[compat:check] === scan stdout (on error) ===")),process.stdout.write(i.stdout),i.stdout.endsWith(`
|
|
1362
1366
|
`)||process.stdout.write(`
|
|
1363
|
-
`),console.log(
|
|
1364
|
-
${i.stderr}`:""));throw i.stdout&&(o.stdout=i.stdout),o}}function
|
|
1365
|
-
Run \`devecocli compat versions\` to see all available versions.`)}if(n.sourceVersion&&n.targetVersion){let r=e.indexOf(n.sourceVersion),i=e.indexOf(n.targetVersion);if(r>=i)throw new
|
|
1366
|
-
`}function Bx(n,e,t,r){r===".csv"?fv(n,t):hv(t,wv(e),"utf8"),p(be(`[compat:check] saved report: "${t}"`))}function Wx(n,e,t,r){if(r==="json"){let o=X.basename(n,".csv"),s=X.join(t,`${o}.json`);return hv(s,wv(e),"utf8"),p(be(`[compat:check] saved report: "${s}"`)),s}let i=X.join(t,X.basename(n));return fv(n,i),p(be(`[compat:check] saved report: "${i}"`)),i}async function Vx(n,e){let t=new Ke(n,process.cwd(),!0),r=e.modules&&e.modules.length>0?e.modules[0]:void 0;try{await t.compileNative("default",r)}catch(i){throw new ae("errorCode",`hvigorw compileNative failed (module=${r??"<project>"}): `+i.message,{cause:i})}}async function Gx(n,e){Nx(n,e);let t=q.discover(process.cwd());e.modules&&e.modules.length>0&&wx(t,e.modules),n.length>0&&Sx(n);let r=await C.new(),{apiChangeDir:i,scriptPath:o}=r.getApiscanPaths();p(be(`[compat:check] script: "${o}"`));let s=yv(i);Mx(e,s),e.outputPath&&p(be(`[compat:check] outputPath: "${e.outputPath}"`));let a=Hx(e.outputPath,e.format);return p(be(`[compat:check] outputTarget: ${a.kind}`)),Ux(a),{project:t,scriptPath:o,target:a,toolProvider:r}}function qx(n,e,t,r){if(t.kind==="file")return Bx(n,e,t.filePath,t.ext),t.filePath;if(t.kind==="dir")return Wx(n,e,t.dirPath,r);if(t.kind==="none")return null;throw new ae("errorCode",`Unexpected output target kind: ${t.kind}`)}async function zx(n,e,t,r,i){let o=gx({text:"Running compatibility check...",color:"cyan"}).start();try{await Vx(n.toolProvider,t);let s=xx(n.scriptPath,e,n.project,t);_x(n.scriptPath,s);let a=await Lx(n.toolProvider,s),c=Ix(a,Yd.tmpdir());if(!c)throw new ae("errorCode","Scanner output format unexpected: missing report path.");p(be(`[compat:check] tmp csv: "${c}"`));let l=kx(c),d=qx(c,l,n.target,t.format);Fx(c),o.stop(),Ox(l,d,t.format,t.limit,n.target.kind),await di(r,!0,null,i)}catch(s){o.fail("Compatibility check failed");let a=Kd(s);throw await di(r,!1,a,i),s}}async function Sv(n,e){let t=Date.now(),r=["check","compat"];try{let i=await Gx(n,e);await zx(i,n,e,t,r)}catch(i){let o=Kd(i);throw await di(t,!1,o,r),i}}function Yx(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new Jx(`--limit must be a positive integer (got "${n}")`);return e}var Xd=new bv("compat").description("Compatibility checking utilities.");Xd.description("Check source code compatibility against a target SDK version. By default, performs a project-level scan; pass positional `files...` for file-level scanning; pass `--modules` for module-level scanning.").arguments("[files...]").option("--source-version <version>","Current project SDK version (required; use `compat versions` to list available versions). On zsh, quote the value because version strings contain parentheses; run `compat versions` first to copy a real example.").option("--target-version <version>","Target SDK version (required; use `compat versions` to list available versions). On zsh, quote the value because version strings contain parentheses; run `compat versions` first to copy a real example.").option("--modules <modules...>","Modules to check (default: all modules in the project). Mutually exclusive with positional file arguments.").option("--format <format>",'Output format: "json" or "default" (text) for console; "csv", "json", or "default" for file output (--output-path). "csv" requires --output-path.',"default").option("--output-path <path>","Directory to write the detailed report CSV to (default: ./compat-output)").option("--limit <num>","Maximum number of change records to display (default: 100)",Yx,100).action(async(n,e)=>{await Sv(n,e)});Xd.command("versions").description("List all available target SDK versions for compatibility checking").option("--format <format>","Output format: default or json").action(async(n,e)=>{let t=e.optsWithGlobals().format;await vv(t)});var Kx=new bv("check").description("Run DevEco project checks").addCommand(Xd).addCommand(Wd()).addCommand(Jd()),Ev=Kx;import{Command as $N}from"commander";import{green as Su,red as jN}from"colorette";import bu from"fs";import sw from"path";import aw from"json5";import{readFileSync as kL}from"fs";import{join as Xx}from"path";var pe={BASE_URL:"https://connect-api.cloud.huawei.com",CERT_LIST_PATH:"/api/cps/harmony-cert-manage/v1/cert/list",CERT_DELETE_PATH:"/api/cps/harmony-cert-manage/v1/cert/delete",CERT_ADD_PATH:"/api/cps/harmony-cert-manage/v1/cert/add",CERT_DOWNLOAD_URL_PATH:"/api/amis/app-manage/v1/objects/url/reapply",DEVICE_ADD_PATH:"/api/cps/device-manage/v1/device/add",DEVICE_LIST_PATH:"/api/cps/device-manage/v1/device/list",PROVISION_ADD_REAL_PATH:"/api/cps/provision-manage/v1/ide/real/provision/add",PROVISION_ADD_TEST_PATH:"/api/cps/provision-manage/v1/ide/test/provision/add",PROVISION_DELETE_PATH:"/api/cps/provision-manage/v1/provision/delete"},ze={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:Xx(".ohos","config"),DOWNLOAD_CONNECT_TIMEOUT_MS:5e3},Ee={SUCCESS_MARKER:'"code":0',SQUARE_BRACKETS:"[]",OPENPROXY_BLOCKED_URL:"Openproxy_Blocked_URL_list",CERT_LIMIT_CODE:"205389872",USER_NOT_HARMONY_CODE:"205389904",DEVICE_EXCEEDS_LIMIT_CODE:"205389859",DEVICE_NAME_REPEAT_CODE:"205389857",PROVISION_EXCEEDS_LIMIT_CODE:"205389938",PROVISION_NAME_REPEAT_CODE:"205389830"},Pt={FORBIDDEN:403,UNAUTHORIZED:401},P={ERR_FORBIDDEN:"You do not have AppGallery Connect permissions for the current team. Request access from the team administrator or switch to a team where you have permissions.",ERR_UNAUTHORIZED:"Invalid AccessToken. Sign in and try again.",ERR_CERT_LIMIT_REACHED:"The number of certificates has reached the limit. Delete some certificates and try again.",ERR_CERT_NETWORK_ERROR:"Ensure the external network connection is available before downloading the certificate.",ERR_CERT_INVALIDATE:"The downloaded .cer file is invalid. Try again.",ERR_DOWNLOAD_CER:"Failed to download the certificate file. Check the following configurations: Network connection, HTTP Proxy, etc.",ERR_USER_NOT_HARMONY:"The user is not in harmony allow list, please grant the permission",ERR_READ_CSR:"Failed to read the .csr file, please try again later",ERROR_WHILE_ADD_DEVICE:"Failed to add the device, please try again.",DEVICE_LIMIT_REACHED:"The number of devices has reached the limit. Delete some unused devices and try again.",DEVICE_NAME_REPEAT:"Duplicate device name, please try again.",DEVICE_LIST_EMPTY:"No devices available.",ADD_PROFILE_FAIL:"Failed to add the profile, please try again.",NO_AGC_PERMISSION:"You do not have the AppGallery Connect permission with the current team. Apply for the permission form the team administrator, or switch to a team with which you already have the permission.",ERROR_WHILE_DOWNLOAD_PROFILE:"Failed to download the profile, please try again.",PROFILE_NAME_REPEAT:"The profile name already exists in the AGC.",ERROR_WHILE_PARSE_PROFILE:"Failed to parse the profile, please try again.",TEST_PROVISION_EXCEEDS_LIMIT:"Provision number exceeds limit.",CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT:"The certificate application file is inconsistent with the file in profile, please try again.",CERTIFICATE_HAS_EXPIRED:"The signature does not take effect or has expired. It may be the current system time is inaccurate, please calibrate the system time and sign again.",ERROR_SIGN_BUNDLE_NAME_VALIDATE:"The bundle name contains 7 to 128 characters, including only letters, digits, and underscores (_). It must be start with a letter and contain at least three segments separated by periods (.), each of the segments ending with a digit or letter."},me={TOOLCHAIN_INIT_FAILED:"Auto-sign failed: unable to initialize toolchain",LOGIN_REQUIRED:"Failed to automatically generate signatures.Run devecocli auth login to sign in.",TEAM_INFO_FAILED:"Failed to obtain user team information.Check the network connection, HTTP proxy, and other configurations.",REALNAME_REQUIRED:"Users without real-name verification are not supported.Complete real-name verification in AppGallery Connect.",SESSION_EXPIRED:"User session expired or token invalid. Please login again.",REGION_CHINA_ONLY:"This feature is only available for accounts registered in Chinese mainland.",DEVICE_MISSING:"Unable to create the profile file due to missing devices.Connect a device through IP or USB, or manually add a device in AppGallery Connect first.If you are installing the HAP package on an emulator, you can skip the signing step.",DEVICE_DETECT_FAILED:"Unable to detect devices. Please check hdc status. If installing HAP on an emulator, signature step can be skipped.",PROJECT_DIR_MISSING:"Not in a valid project directory (project-level build-profile.json5 not found).",ATOMIC_SERVICE_UNSUPPORTED:"AtomicService projects are not yet supported. Please configure signing manually."};function Xa(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}function Zd(n){let e=n.replace(ze.TEAM_ID_INVALID_CHARS,"");return`${ze.CERT_NAME_PREFIX}${e}.cer`}function ui(n,e,t){if(n===Pt.FORBIDDEN)return e===Ee.OPENPROXY_BLOCKED_URL?new Error(P.ERR_CERT_NETWORK_ERROR):new Error(P.ERR_FORBIDDEN);if(n===Pt.UNAUTHORIZED)return new Error(P.ERR_UNAUTHORIZED);if(t.includes(Ee.USER_NOT_HARMONY_CODE))return new Error(P.ERR_USER_NOT_HARMONY);if(t.includes(Ee.CERT_LIMIT_CODE))return new Error(P.ERR_CERT_LIMIT_REACHED);let r=Zx(t);return new Error(r??P.ERR_DOWNLOAD_CER)}function Zx(n){let e=Pv(n);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let r=typeof t=="string"?Pv(t):t;if(r&&typeof r=="object"){let i=r.msg;if(typeof i=="string"&&i.trim()!=="")return i}return null}function Pv(n){try{return JSON.parse(n)}catch{return null}}function Qd(n){return JSON.parse(n)}async function Cv(n){let e=`${pe.BASE_URL}${pe.CERT_LIST_PATH}`,t=await N.postAllowFailure(e,{headers:Xa(n)});if(t.statusCode!==200)throw ui(t.statusCode,t.statusText,t.data);return Qd(t.data)?.certList??[]}async function Za(n,e){return(await Cv(n)).find(r=>r.certName===e)??null}async function eu(n,e){let t=`${pe.BASE_URL}${pe.CERT_DELETE_PATH}`,r=await N.deleteAllowFailure(t,{headers:Xa(n),params:{certIds:[e]}});if(r.statusCode!==200)throw ui(r.statusCode,r.statusText,r.data);return Qd(r.data)?.ret?.code===0}async function tu(n,e,t){let r=`${pe.BASE_URL}${pe.CERT_ADD_PATH}`,i={csr:e,certName:t,certType:ze.CERT_TYPE_DEBUG},o=await N.postAllowFailure(r,{headers:Xa(n),params:i});if(o.statusCode!==200)throw ui(o.statusCode,o.statusText,o.data);if(!o.data.includes(Ee.SUCCESS_MARKER))throw ui(void 0,o.statusText,o.data)}async function ru(n,e){let t=`${pe.BASE_URL}${pe.CERT_DOWNLOAD_URL_PATH}`,r=await N.postAllowFailure(t,{headers:Xa(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw ui(r.statusCode,r.statusText,r.data);return Qd(r.data)?.urlsInfo?.[0]??null}import{mkdirSync as Qx,writeFileSync as eL,existsSync as tL}from"fs";import{dirname as rL}from"path";import{createHash as nL}from"crypto";function iL(n){let e;try{e=new URL(n)}catch{throw new Error(`Invalid download URL: ${JSON.stringify(n)}`)}if(e.protocol!=="https:")throw new Error(`Download URL must use HTTPS: ${e.protocol}`);let t=e.hostname.toLowerCase();if(t==="localhost"||t==="127.0.0.1"||t==="::1"||t.startsWith("169.254.")||t.startsWith("10.")||t.startsWith("192.168.")||/^172\.(1[6-9]|2\d|3[0-1])\./.test(t)||t.endsWith(".internal")||t.endsWith(".local"))throw new Error(`Download URL points to internal/private address: ${t}`)}async function Io(n,e,t){iL(n);let{statusCode:r,statusText:i,buffer:o}=await N.getBinaryAllowFailure(n,{timeout:ze.DOWNLOAD_CONNECT_TIMEOUT_MS});if(r!==200)throw r===Pt.FORBIDDEN&&i===Ee.OPENPROXY_BLOCKED_URL?new Error(P.ERR_CERT_NETWORK_ERROR):new Error(P.ERR_DOWNLOAD_CER);if(t){let a=nL("sha256").update(o).digest("hex");if(a!==t.toLowerCase())throw new Error(`SHA-256 mismatch for ${e}: expected ${t.toLowerCase()}, got ${a}`)}let s=rL(e);tL(s)||Qx(s,{recursive:!0}),eL(e,o)}import EL from"fs/promises";import{readFileSync as PL}from"fs";import Qa from"path";import Av from"crypto";import oL from"os";import Ao from"fs/promises";var Dv={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},kv=["ECC","RSA"],Iv=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],sL={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},aL=8,nu=64,cL=/[\\/:*?"<>|=-]/g,Ct={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function lL(n){if(!n.keyAlias.trim())throw new Error("keyAlias cannot be empty");if(!n.keystoreFile.trim())throw new Error("keystoreFile cannot be empty");if(n.keyAlias.length>nu)throw new Error(`The length of keyAlias cannot exceed ${nu}`);if(!kv.includes(n.keyAlg))throw new Error(`Invalid key algorithm ${n.keyAlg}, available: ${kv.join(" / ")}`);let e=sL[n.keyAlg];if(!e.includes(n.keySize))throw new Error(`Key algorithm ${n.keyAlg} does not support size ${n.keySize}, available: ${e.join(", ")}`)}function dL(n){if(!n.keyAlias.trim())throw new Error("keyAlias cannot be empty");if(!n.keystoreFile.trim())throw new Error("keystoreFile cannot be empty");if(!n.subject.trim())throw new Error("subject cannot be empty");if(!Iv.includes(n.signAlg))throw new Error(`Invalid sign algorithm ${n.signAlg}, available: ${Iv.join(" / ")}`)}function uL(n){return Av.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function pL(n){let e=n?.trim()??"";return e&&e.replace(cL,"_").replace(/\.+/g,"_").slice(0,nu)||Ct.productName}async function Rv(){let n=await C.new();n.assertJava();let e=n.javaPath,t=n.sdkPath;u.info(`\u8BFB\u53D6SDK\u6839\u76EE\u5F55\uFF1A${t}`);let r=Qa.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");try{await Ao.access(r)}catch(i){throw new Error(`Sign tool jar not found: ${r}`,{cause:i})}return{javaPath:e,jarPath:r}}async function mL(n){let{javaPath:e,jarPath:t}=await Rv(),r=["-jar",t,Dv.GENERATE_KEYPAIR,"-keyAlias",n.keyAlias,"-keyAlg",n.keyAlg,"-keySize",n.keySize,"-keystoreFile",n.keystoreFile,"-keystorePwd",n.keystorePwd];n.keyPwd&&r.push("-keyPwd",n.keyPwd),n.pwdInputMode&&r.push("-pwdInputMode",n.pwdInputMode);let i=r.map((o,s)=>s>0&&["-keyPwd","-keystorePwd"].includes(r[s-1])?"******":o);return u.debug("generate-keypair \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",i.join(" ")),[e,...r]}async function fL(n){let{javaPath:e,jarPath:t}=await Rv(),r=["-jar",t,Dv.GENERATE_CSR,"-keyAlias",n.keyAlias,"-subject",n.subject,"-signAlg",n.signAlg,"-keystoreFile",n.keystoreFile,"-keystorePwd",n.keystorePwd];n.outFile&&r.push("-outFile",n.outFile),n.keyPwd&&r.push("-keyPwd",n.keyPwd),n.pwdInputMode&&r.push("-pwdInputMode",n.pwdInputMode);let i=r.map((o,s)=>s>0&&["-keyPwd","-keystorePwd"].includes(r[s-1])?"******":o);return u.debug("generate-csr \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",i.join(" ")),[e,...r]}async function hL(n){u.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),lL(n);let e=await mL(n),t=await Ai(e[0],e.slice(1));if(t.exitCode!==0){let r=t.stderr||t.stdout||"Unknown tool error";throw new Error(`An error occurred while generating the private key P12, exit code${t.exitCode}\uFF1A${r}`)}return u.info("\u751F\u6210P12\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}async function gL(n){u.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),dL(n);let e=await fL(n),t=await Ai(e[0],e.slice(1));if(t.exitCode!==0){let r=t.stderr||t.stdout||"Unknown tool error";throw new Error(`An error occurred while generating the CSR, exit code${t.exitCode}\uFF1A${r}`)}return u.info("\u751F\u6210CSR\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}function yL(n=aL){return Av.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function vL(){let n=oL.homedir();try{await Ao.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=Qa.join(n,".ohos","config");try{await Ao.mkdir(e,{recursive:!0,mode:448})}catch(t){throw new Error(`Failed to create directory ${e}`,{cause:t})}return u.info(`\u7B7E\u540D\u914D\u7F6E\u76EE\u5F55\u5C31\u7EEA\uFF1A${e}`),e}async function Re(n,e,t){let r=pL(n),i=Qa.basename(e),o=uL(e),s=`${r}_${i}_${o}=.${t}`,a=await vL();return Qa.join(a,s)}function wL(n){let e;try{e=q.discover(n).rootDir}catch(t){throw new Error(`Current directory ${n} is not a valid project root`,{cause:t})}return e}async function SL(n){try{await Ao.access(n)}catch(e){throw new Error(`Project directory ${n} is not accessible, missing read/write permissions`,{cause:e})}}async function bL(n){try{await Ao.access(n)}catch(e){throw new Error(`P12 file ${n} does not exist, terminating CSR generation.`,{cause:e})}}async function iu(n,e,t){let r=process.cwd(),i=wL(r);await SL(i),u.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${i}`);let o=yL(),s=await Re(n??"",i,"p12"),a=await Re(n??"",i,"csr");return console.log("Start generating p12"),await hL({keyAlias:e?.keyAlias??Ct.keyAlias,keyPwd:o,keyAlg:e?.keyAlg??Ct.keyAlg,keySize:e?.keySize??Ct.keySize,keystoreFile:s,keystorePwd:o}),await bL(s),console.log("Start generating csr"),await gL({subject:t?.subject??Ct.csrSubject,outFile:a,keyAlias:t?.keyAlias??Ct.keyAlias,keyPwd:o,signAlg:t?.signAlg??Ct.signAlg,keystoreFile:s,keystorePwd:o}),{p12FilePath:s,csrFilePath:a,keyPwd:o,keyAlias:e?.keyAlias??Ct.keyAlias}}var CL=["p12","cer","csr","p7b"];async function ou(n,e){for(let t of CL){let r=await Re(n,e,t);await EL.rm(r,{force:!0})}}function su(n){let e;try{e=PL(n,"utf-8")}catch{throw new Error(P.ERR_CERT_INVALIDATE)}if(!ze.CERT_PATTERN.test(e))throw new Error(P.ERR_CERT_INVALIDATE)}async function Tv(n,e){return{certPath:await Re(n,e,"cer"),csrPath:await Re(n,e,"csr"),p12Path:await Re(n,e,"p12"),profilePath:await Re(n,e,"p7b")}}async function au(n,e){let t=e??"",r=q.discover(process.cwd()).rootDir;await ou(t,r);let i=Zd(n.teamId),o=await Za(n,i);if(o&&!await eu(n,o.id))throw new Error(P.ERR_DOWNLOAD_CER);let s=await iu(e),a;try{a=kL(s.csrFilePath,"utf-8")}catch{throw new Error(P.ERR_READ_CSR)}console.log("Start generating certificate"),await tu(n,a,i);let c=await Za(n,i);if(!c)throw new Error(P.ERR_DOWNLOAD_CER);let l=await ru(n,c.certObjectId);if(!l)throw new Error(P.ERR_DOWNLOAD_CER);let d=await Re(t,r,"cer");await Io(l.newUrl,d,l.sha256),su(d);let g=await Re(t,r,"p7b");return{p12FilePath:s.p12FilePath,csrFilePath:s.csrFilePath,cerFilePath:d,profileFilePath:g,certId:c.id,keyAlias:s.keyAlias,keyPwd:s.keyPwd,storePassword:s.keyPwd}}import lc from"crypto";import Hr from"fs";import*as Gv from"path";import zL from"json5";import{execa as Bv}from"execa";import Wv from"node-forge";import{createCipheriv as IL,createDecipheriv as AL,pbkdf2Sync as DL,randomBytes as uu}from"crypto";import{promises as gn}from"fs";import{dirname as RL,join as kt}from"path";var ec=3,Do=16,TL=1e4,xv="material",xL=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Ov="aes-128-gcm",hn=12,tc=16,Fr=4;function cu(n){return new Uint8Array(uu(n))}function LL(n){return uu(n).toString("hex")}function NL(...n){if(n.length===0)return new Uint8Array(0);let e=n[0].length,t=new Uint8Array(e);for(let r=0;r<e;r++){let i=0;for(let o of n)i^=o[r];t[r]=i}return t}function Lv(n,e,t=TL,r=Do){let i=[...n,xL],o=NL(...i),s=Buffer.from(o).toString("utf8"),a=Buffer.from(s,"utf8"),c=DL(a,e,t,r,"sha256");return new Uint8Array(c)}function Nv(n,e){let t=uu(hn),r=IL(Ov,n,t),i=Buffer.concat([r.update(e),r.final()]),o=r.getAuthTag(),s=Buffer.concat([i,o]),a=s.length,c=Buffer.alloc(Fr+hn+s.length);return c.writeUInt32BE(a,0),t.copy(c,Fr),s.copy(c,Fr+hn),c}function Mv(n,e){if(e.length<Fr+hn+tc)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(Fr,Fr+hn),i=e.subarray(Fr+hn,Fr+hn+t);if(i.length<tc)throw new Error("Ciphertext too short for auth tag");let o=i.subarray(0,i.length-tc),s=i.subarray(i.length-tc),a=AL(Ov,n,r);return a.setAuthTag(s),Buffer.concat([a.update(o),a.final()])}async function ML(n){try{await gn.rm(n,{recursive:!0,force:!0})}catch{}}async function lu(n){let e=await gn.readdir(n),t=e.filter(r=>r!==".DS_Store");if(t.length!==1)throw new Error(`Expected exactly 1 file in ${n}, but found ${t.length} (filtered from ${e.length})`);return gn.readFile(kt(n,t[0]))}async function du(n,e){let t=LL(Do),r=kt(n,t);return await gn.writeFile(r,e,{mode:384}),t}var $r=class{static keyChain=Promise.resolve();static async generateMaterial(e){let t=kt(e,xv);await ML(t);let r=kt(t,"ac"),i=kt(t,"ce");await gn.mkdir(r,{recursive:!0,mode:448}),await gn.mkdir(i,{recursive:!0,mode:448});for(let d=0;d<ec;d++)await gn.mkdir(kt(t,"fd",String(d)),{recursive:!0,mode:448});let o=cu(Do),s=[];for(let d=0;d<ec;d++)s.push(cu(Do));let a=cu(Do),c=Lv(s,o),l=Nv(c,a);await du(r,o),await du(i,l);for(let d=0;d<ec;d++){let g=kt(t,"fd",String(d));await du(g,s[d])}return a}static async readMaterial(e){let t=kt(e,xv),r=kt(t,"ac"),i=new Uint8Array(await lu(r)),o=[];for(let d=0;d<ec;d++){let g=kt(t,"fd",String(d)),y=await lu(g);o.push(new Uint8Array(y))}let s=kt(t,"ce"),a=await lu(s),c=Lv(o,i),l=Mv(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t,r=this.keyChain;this.keyChain=new Promise(i=>{t=i}),await r;try{let i=RL(e);try{return await this.readMaterial(i)}catch{return await this.generateMaterial(i)}}finally{t()}}static async encryptedPassword(e,t){let r=await this.getStoreKey(t),i=Buffer.from(e,"utf8");return Nv(r,i).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let r=await this.getStoreKey(t),i=Buffer.from(e,"hex");return Mv(r,i).toString("utf8")}};import Hv from"fs";import ac from"path";import HL from"json5";import*as rc from"fs";import*as _v from"path";function nc(n){let e=_v.resolve(n);if(!rc.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=rc.readFileSync(e,"utf-8")}catch(s){throw new Error(`Failed to read SDK info file: ${e}`,{cause:s})}let r;try{r=JSON.parse(t)}catch(s){throw new Error(`Invalid JSON in SDK info file: ${e}`,{cause:s})}let i=r?.data?.apiVersion;if(i==null||i==="")throw new Error(`Missing data.apiVersion in SDK info file: ${e}`);let o=Number(i);if(!Number.isFinite(o))throw new Error(`Invalid data.apiVersion in SDK info file: ${String(i)}`);return o}import*as mi from"fs";import*as Je from"path";import{debuglog as pi}from"util";var Fv={"acl.SYSTEM_FLOAT_WINDOW.instead.name":"PiPWindow","acl.READ_CONTACTS.instead.name":"contact.selectContacts","acl.READ_IMAGEVIDEO.instead.name":"PhotoViewPicker","acl.WRITE_IMAGEVIDEO.instead.name":"SaveButton","acl.READ_AUDIO.instead.name":"AudioViewPicker","acl.WRITE_AUDIO.instead.name":"AudioViewPicker","acl.READ_PASTEBOARD.instead.name":"PasteButton"};function OL(n){return Object.prototype.hasOwnProperty.call(Fv,n)}function ic(n){if(OL(n))return Fv[n]}var $v={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as _L}from"url";var sc=class{permissionName;permissionDisplayName;minSupportApiLevel;permissionInsteadName;permissionHelpUrlKey;constructor(e={}){this.permissionName=e.permissionName??"",this.permissionDisplayName=e.permissionDisplayName??"",this.minSupportApiLevel=e.minSupportApiLevel??"",this.permissionInsteadName=e.permissionInsteadName,this.permissionHelpUrlKey=e.permissionHelpUrlKey}};function oc(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function jv(n){return n==null||n.length===0}function FL(n){return!jv(n)}function pu(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function $L(n,e){let t=n[e];if(typeof t=="boolean")return t;if(typeof t=="number")return t!==0;if(typeof t=="string"){let r=t.trim().toLowerCase();return r==="true"||r==="1"}return!1}function jL(n,e){let t=n[e];if(typeof t=="number")return Math.trunc(t);if(typeof t=="string"){let r=Number.parseInt(t,10);return Number.isNaN(r)?0:r}return 0}var jr=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=Je.join("aclPermission","aclPermissionsInfo.json");static ACL_HAVE_INSTEAD_NAME=new Set(["ohos.permission.SYSTEM_FLOAT_WINDOW","ohos.permission.READ_CONTACTS","ohos.permission.READ_IMAGEVIDEO","ohos.permission.WRITE_IMAGEVIDEO","ohos.permission.READ_AUDIO","ohos.permission.WRITE_AUDIO","ohos.permission.READ_PASTEBOARD"]);static ACL_AVAILABLE_LEVEL_VALUE="system_basic";static ACL_AVAILABLE_TYPE_VALUE="NORMAL";static ACL_AVAILABLE_LEVEL_KEY="availableLevel";static ACL_AVAILABLE_TYPE_KEY="availableType";static ACL_PROVISION_ENABLE_KEY="provisionEnable";static ACL_NAME_KEY="name";static ACL_CONFIG_PREFIX="acl.";static ACL_INSTEAD_NAME_SUFFIX=".instead.name";static ACL_HELP_URL_KEY_SUFFIX=".help.key";static ACL_DEFINE_PERMISSION_KEY="definePermissions";static ACL_SINCE_KEY="since";static PERMISSION_DEFINITIONS_RELATIVE_PATH=Je.join("lib","PermissionDefinitions.json");static INCLUDE_ACL_PERMISSIONS=new Set(["ohos.permission.FILE_ACCESS_PERSIST","ohos.permission.READ_WRITE_DOWNLOAD_DIRECTORY","ohos.permission.READ_WRITE_DOCUMENTS_DIRECTORY"]);static EXCLUDE_ACL_PERMISSIONS=new Set(["ohos.permission.READ_DOCUMENT","ohos.permission.WRITE_DOCUMENT"]);static handleSpecificAclPermissions(){this.addAclWhiteList(this.INCLUDE_ACL_PERMISSIONS),this.addAclBlackList(this.EXCLUDE_ACL_PERMISSIONS)}static aclPermissionInfoMap=new Map;static aclPermissionNamesMap=new Map;static aclWhiteList=new Set;static aclBlackList=new Set;static builtInConfigTextLoader;static initAclPermission(e,t){let r=e.rootDir,i=this.getOrCreateSet(this.aclPermissionNamesMap,r),o=this.getOrCreateSet(this.aclPermissionInfoMap,r);i.clear(),o.clear();let s=Je.join(t.sdkPath,"default","sdk-pkg.json"),a=nc(s);this.MIN_API_TO_FIND_ACL_IN_SDK-a>0?this.initAclPermissionFromBuiltInConfig(i,o):this.initAclPermissionFromSDK(t,i,o)}static getAclPermissionInfos(e){return this.aclPermissionInfoMap.get(e.rootDir)??new Set}static getAclPermissionNames(e){return this.aclPermissionNamesMap.get(e.rootDir)??new Set}static addAclWhiteList(e){for(let t of e)this.aclWhiteList.add(t)}static addAclBlackList(e){for(let t of e)this.aclBlackList.add(t)}static getOrCreateSet(e,t){let r=e.get(t);return r||(r=new Set,e.set(t,r)),r}static readBuiltInConfigText(){if(this.builtInConfigTextLoader)return this.builtInConfigTextLoader();let e=Je.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(mi.existsSync(e))return mi.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=_L(e);if(t.includes("dist")){let s=Je.dirname(t),a=Je.dirname(s);return Je.join(a,"src","resources")}let r=Je.dirname(t),i=Je.dirname(r),o=Je.dirname(i);return Je.join(o,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let r;try{r=this.readBuiltInConfigText()}catch{pi("read builtin acl permission failed.");return}if(r!==void 0)try{let i=JSON.parse(r),s=(Array.isArray(i)?i:oc(i)?Object.values(i):[]).filter(oc).map(a=>new sc(a));s.forEach(a=>{let c=a.permissionInsteadName;FL(c)&&(a.permissionInsteadName=ic(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(i){pi(`failed to parse aclPermissionsInfo.json: ${i}`)}}static initAclPermissionFromSDK(e,t,r){let i=this.parsePermissionDefinitionFile(e);i&&i.forEach(o=>{if(!oc(o))return;let s=o,a=pu(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(jv(a)||(this.generateAclInfos(r,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||pu(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||pu(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:$L(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let i=new sc;i.permissionName=t;let o=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;i.permissionDisplayName=o;let s=jL(r,this.ACL_SINCE_KEY);i.minSupportApiLevel=String(s),this.handleInsteadName(i,o),e.add(i)}static parsePermissionDefinitionFile(e){let t=Je.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!mi.existsSync(t))return;let r;try{r=mi.readFileSync(t,"utf-8")}catch(s){pi(`failed to load permissionDefinitions.json: ${s}`);return}let i;try{let s=JSON.parse(r);if(!oc(s)){pi("json object is null");return}i=s}catch(s){pi(`failed to parse permissionDefinitions.json: ${s}`);return}let o=i[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(o)){pi("definePermissions is not an array");return}return o}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=ic(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=ic(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function cc(n,e){let t=new Set,r=new Set;jr.handleSpecificAclPermissions(),jr.initAclPermission(n,e);for(let i of n.profile.modules){let o=Uv(i,n,e,r,ac.join("src","main"));for(let a of o)t.add(a);let s=Uv(i,n,e,r,ac.join("src","ohosTest"));for(let a of s)t.add(a)}return UL(r),t}function UL(n){if(n.size>0)throw new Error($v.DUPLICATE_PERMISSION)}function Uv(n,e,t,r,i){let o=WL(e.rootDir,n,i);if(o==null)return new Set;let s=[];for(let y of o){if(typeof y!="object"||y===null)continue;let I=BL(y,"name");I&&s.push(I)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=ac.join(t.sdkPath,"default","sdk-pkg.json"),l=nc(c),d=jr.getAclPermissionInfos(e),g=new Set(Array.from(d).filter(y=>{let I=Number(y.minSupportApiLevel);return Number.isFinite(I)&&I<=l}).map(y=>y.permissionName));for(let y of Array.from(a))g.has(y)||a.delete(y);return a}function BL(n,e){let t=n[e];return typeof t=="string"?t:""}function WL(n,e,t){let r=ac.join(n,e.srcPath,t,"module.json5"),i=VL(r);if(i==null)return null;let o=GL(i,"module");return o==null?null:qL(o,"requestPermissions")}function VL(n){try{if(!Hv.existsSync(n))return null;let e=Hv.readFileSync(n,"utf-8");return HL.parse(e)}catch{return null}}function GL(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return t!=null&&typeof t=="object"&&!Array.isArray(t)?t:null}function qL(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}var fu=class{verifyStorePassword(e,t){try{let r=Hr.readFileSync(e),i=Wv.asn1.fromDer(r.toString("binary"));return Wv.pkcs12.pkcs12FromAsn1(i,t),!0}catch{return!1}}getLocalCerFingerprints(e){let r=Hr.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(r&&r.length>0)return r.map(i=>this.formatFp(new lc.X509Certificate(i).fingerprint256));try{return[this.formatFp(new lc.X509Certificate(Hr.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let i=Hr.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let o of i)try{let s=new lc.X509Certificate(o);if(this.formatFp(s.fingerprint256)===t){let a=new Date(s.validTo);return isNaN(a.getTime())?null:a}}catch{}return null}formatFp(e){let t=e.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}};function JL(n){let e=Hr.readFileSync(n,"utf-8"),t=YL(e),r=null;if(t)try{r=JSON.parse(t)}catch{r=null}let i=r?.["bundle-info"]??{};return{rawContent:e,bundleNameInProfile:mu(i["bundle-name"]),expiryDate:KL(r?.validity?.["not-after"]),cerFingerprintInProfile:XL(mu(i["development-certificate"])),deviceUdidsInProfile:ZL(r?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:QL(r?.acls?.["allowed-acls"]),teamIdInProfile:mu(i["developer-id"])}}function YL(n){let e=n.indexOf("{");if(e<0)return null;let t=0,r=-1,i=!1,o=!1;for(let s=e;s<n.length;s++){let a=n[s];if(i){o?o=!1:a==="\\"?o=!0:a==='"'&&(i=!1);continue}if(a==='"')i=!0;else if(a==="{")t++;else if(a==="}"&&(t--,t===0)){r=s;break}}return r<0?null:n.slice(e,r+1)}function KL(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function XL(n){if(!n)return null;try{let t=new lc.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function ZL(n){if(!Array.isArray(n))return[];let e=[];for(let t of n)if(typeof t=="string"){let r=t.toUpperCase();e.includes(r)||e.push(r)}return e}function QL(n){if(!Array.isArray(n))return[];let e=[];for(let t of n)typeof t=="string"?e.push(t):t&&typeof t=="object"&&typeof t.name=="string"&&e.push(t.name);return[...new Set(e)].sort()}function mu(n){return typeof n=="string"?n:null}var Ro=class n{static async shouldRegenerate(e,t){let r=await n.#e(e,t);return n.#t(r)??n.#r(r)??n.#n(r)??n.#i(r)??n.#o(r)??n.#s(r)??n.#a(r)??n.#c(r)??n.#l(r)??n.#d(r)??await n.#u(r)??n.#p()}static async#e(e,t){let r=e.force,i=e.teamId,o=e.productName??"default",s=q.discover(process.cwd()),a=s.rootDir,[c,l]=await Promise.all([eN(o,a),rN(t.hdcPath)]),d=null;if(Vv(c).allExist)try{d=JL(c.profileFile)}catch{}return{force:r,teamId:i,productName:o,projectPath:a,materialPaths:c,bundleName:s.getBundleName(o),deviceUdids:l,storePassword:await tN(a,o,c.storeFile),localAclPermissions:[...cc(s,t)].sort(),hapSignTool:new fu,profileInfo:d}}static#t(e){return e.force?(p("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:nt({force:!0})}):null}static#r(e){let t=Vv(e.materialPaths);return t.allExist?null:(p(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:nt({allFilesExist:!1,missingFiles:t.missing})})}static#n(e){return(e.profileInfo?.rawContent??"").trim().length>0?null:(p("[reGenerateSign] profile content is empty"),{shouldRegenerate:!0,reason:"Profile file content is empty",checkDetails:nt({allFilesExist:!0,profileContentNotEmpty:!1})})}static#i(e){let t=e.profileInfo?.expiryDate;return!t||t>=new Date?null:(p(`[reGenerateSign] profile expired at ${t.toISOString()}`),{shouldRegenerate:!0,reason:`Profile expired at ${t.toISOString()}`,checkDetails:nt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!1})})}static#o(e){let t=e.profileInfo?.bundleNameInProfile;return t&&t===e.bundleName?null:(p(`[reGenerateSign] bundleName mismatch \u2014 current=${e.bundleName}, profile=${t}`),{shouldRegenerate:!0,reason:`bundleName mismatch: current=${e.bundleName}, in profile=${t}`,checkDetails:nt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!1})})}static#s(e){let t=e.profileInfo?.teamIdInProfile;return t&&t===e.teamId?null:(p(`[reGenerateSign] teamId mismatch \u2014 current=${e.teamId}, profile=${t}`),{shouldRegenerate:!0,reason:`teamId mismatch: current=${e.teamId}, in profile=${t}`,checkDetails:nt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=iN(e.profileInfo?.deviceUdidsInProfile??[],e.deviceUdids);return t.allPresent?null:(p(`[reGenerateSign] missing device UDIDs: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Device UDID(s) not in profile: ${t.missing.join(", ")}`,checkDetails:nt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return oN(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(p("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:nt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!1})})}static#l(e){let t=e.hapSignTool.getLocalCerFingerprints(e.materialPaths.cerFile),r=e.profileInfo?.cerFingerprintInProfile;return r&&t.includes(r)?null:(p("[reGenerateSign] certificate mismatch"),{shouldRegenerate:!0,reason:"Certificate mismatch between profile and local .cer file",checkDetails:nt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!1})})}static#d(e){let t=e.profileInfo?.cerFingerprintInProfile,r=e.hapSignTool.getLocalCerExpiry(e.materialPaths.cerFile,t);return!r||r>=new Date?null:(p(`[reGenerateSign] local certificate expired at ${r.toISOString()}`),{shouldRegenerate:!0,reason:`Local certificate expired at ${r.toISOString()}`,checkDetails:nt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!1})})}static async#u(e){return e.storePassword?e.hapSignTool.verifyStorePassword(e.materialPaths.storeFile,e.storePassword)?null:(p("[reGenerateSign] keystore password verification failed"),{shouldRegenerate:!0,reason:"Keystore password verification failed (storeFile may be corrupted or password changed)",checkDetails:nt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})}):(p("[reGenerateSign] no stored keystore password"),{shouldRegenerate:!0,reason:"No stored keystore password available for verification",checkDetails:nt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})})}static#p(){return p("[reGenerateSign] all checks passed \u2014 skip regeneration"),{shouldRegenerate:!1,reason:"",checkDetails:nt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function eN(n,e){let[t,r,i,o]=await Promise.all([Re(n,e,"p12"),Re(n,e,"csr"),Re(n,e,"cer"),Re(n,e,"p7b")]);return{storeFile:t,csrFile:r,cerFile:i,profileFile:o}}async function tN(n,e,t){let r=Gv.join(n,"build-profile.json5");if(!Hr.existsSync(r))return;let i;try{i=zL.parse(Hr.readFileSync(r,"utf-8"))}catch{return}let a=(i?.app?.signingConfigs??[]).find(c=>c.name===e)?.material?.storePassword;if(a)try{return await $r.decryptPassword(a,t)}catch{return}}async function rN(n){p(`Executing: ${n} list targets`);let{stdout:e}=await Bv(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
|
|
1367
|
-
`)){let o=i.trim();if(!o||o.startsWith("[Empty]"))continue;let s=o.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let r=[];for(let i of t)try{p(`Executing: ${n} -t ${i} shell bm get -u`);let{stdout:o}=await
|
|
1368
|
-
`);for(let i=0;i<t.length-1;i++)if(t[i].includes("udid of current device is")){let s=t[i+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(s)return s[0].toUpperCase()}let r=e.match(/[A-Fa-f0-9]{64}/);return r?r[0].toUpperCase():null}function
|
|
1369
|
-
`)){let o=i.trim();if(!o||o.startsWith("[Empty]"))continue;let s=o.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let r=[];for(let i of t)try{let o=await
|
|
1370
|
-
`);for(let s=0;s<i.length-1;s++)if(i[s].includes("udid of current device is")){let c=i[s+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(c)return c[0].toUpperCase()}let o=r.match(/[A-Fa-f0-9]{64}/);return o?o[0].toUpperCase():""}async function dN(n,e){let{stdout:t}=await gu(e,["-c","-t",n,"shell","getprop","hw_sc.build.os.deviceType"],{stdio:["ignore","pipe","pipe"]});return uN(t)}function uN(n){let e=n.trim();return!e||e.includes("inaccessible")?"phone":n.includes("liteWearable")?"liteWearable":n.includes("wearable")?"wearable":n.includes("tv")?"tv":"phone"}import yn from"fs";import{createHash as pN}from"crypto";import{debuglog as or}from"util";import{Buffer as Qv}from"buffer";import{createPublicKey as mN,X509Certificate as yu}from"crypto";import{readFileSync as fN}from"fs";import vn from"node-forge";async function ew(n,e){console.log("Start generating profile");let{productName:t,bundleName:r,projectPath:i,aclPermissionList:o,allDeviceIds:s,certIds:a,keyAlias:c,keyPwd:l}=e;if(s==null||s.length===0)throw new Error(P.DEVICE_LIST_EMPTY);let d=`${pe.BASE_URL}${pe.PROVISION_ADD_TEST_PATH}`,g=hN(t,r),y=await yN(n,d,a||[],r,s,g,o||[]);if(!y||!y.profileInfo||!y.profileInfo.provisionFileUrl)throw or("add provision failed, the provision file url is null"),new Error(P.ADD_PROFILE_FAIL);let I=y.profileInfo,G=(await bN(n,I.provisionFileUrl)).urlList,Te=y.profileInfo.id;if(G&&G.length>0){let it=await Tv(t,i),It=it.profilePath;if(!await EN(G,It))throw await Zv(n,Te),new Error(P.ERROR_WHILE_DOWNLOAD_PROFILE);if(await Zv(n,Te),yn.existsSync(it.certPath)&&yn.existsSync(It)&&yn.existsSync(it.p12Path)){let yc=yn.readFileSync(it.certPath,"utf8"),vc=yn.readFileSync(It,"utf8");return PN(vc,yc,it.p12Path,c,l)||SN(It),It}}throw new Error(P.ADD_PROFILE_FAIL)}function hN(n,e){let t=n?`${n}_`:"";return`${gN(`${t}${e}_${e}`)}`}function gN(n){return pN("sha256").update(n).digest("hex").substring(0,16)}async function yN(n,e,t,r,i,o,s){vN(r);let a=wu(n),c={certList:t,packageName:r,deviceList:i,provisionName:o};s.length&&(c.aclPermissionList=s);let l=await N.postAllowFailure(e,{headers:a,params:c});if(!l)throw or("add provision failed: response is null"),new Error(P.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw vu(l.statusCode,l.statusText,l.data);let d=JSON.parse(l.data);if(!d||!d.ret||d.ret.code!==0)throw or(`add provision fail: ${l.data}`),wN(l.data,o),new Error(d.ret?.msg||P.ADD_PROFILE_FAIL);let g=d.provisionFileUrl;return{profileInfo:{id:d.id,name:o,provisionFileUrl:g}}}function vu(n,e,t){return n===Pt.FORBIDDEN?e===Ee.OPENPROXY_BLOCKED_URL?new Error(P.ERR_CERT_NETWORK_ERROR):new Error(P.ERR_FORBIDDEN):n===Pt.UNAUTHORIZED?new Error(P.ERR_UNAUTHORIZED):t.includes(Ee.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(P.TEST_PROVISION_EXCEEDS_LIMIT):new Error(P.ADD_PROFILE_FAIL)}function vN(n){if(!n||n.trim().length===0)throw new Error(P.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!ze.BUNDLE_NAME_REGEX.test(n))throw new Error(P.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function wN(n,e){if(n.includes(Ee.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(P.TEST_PROVISION_EXCEEDS_LIMIT);if(n.includes(Ee.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(P.PROFILE_NAME_REPEAT)}async function Zv(n,e){if(!e||e.trim().length===0)return;let t=`${pe.BASE_URL}${pe.PROVISION_DELETE_PATH}?id=${e}`,r=await N.deleteAllowFailure(t,{headers:wu(n)});if(r.statusCode!==200)throw vu(r.statusCode,r.statusText,r.data);let i=JSON.parse(r.data);(!i||!i.ret||i.ret.code!==0)&&or(`delete provision failed: ${r.data}`)}function SN(...n){for(let e of n)try{yn.existsSync(e)&&yn.unlinkSync(e)}catch(t){or(`delete local sign file error: ${t.message}`)}}async function bN(n,e){let t=`${pe.BASE_URL}${pe.CERT_DOWNLOAD_URL_PATH}`,r=wu(n),i={sourceUrls:e},o=await N.postAllowFailure(t,{headers:r,params:i});if(!o)throw or("get download list failed: response is null"),new Error(P.ADD_PROFILE_FAIL);if(o.statusCode!==200)throw vu(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw or("download: The application does not exist"),new Error(s.ret?.msg||P.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function EN(n,e){if(!n||n.length===0)return!1;let t=n[0];return await Io(t.newUrl,e,t.sha256),!0}function PN(n,e,t,r,i){return CN(n,e),r=r||ze.TARGET_FRIENDLY_NAME,i=i||"",kN(e,t,r,i),!0}function CN(n,e){if(e.lastIndexOf(ze.CERT_BEGIN_HEADER)<0)throw new Error(P.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(ze.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!n.includes(t))throw new Error(P.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}function kN(n,e,t,r){let i=n.matchAll(ze.CERTIFICATE_PATTERN_GLOBAL),o=[],s=new Date;for(let c of i)try{let l=c[0],d=IN(l),g=new Date(d.validFrom),y=new Date(d.validTo);if(s<g||s>y){let I=`Certificate is not valid, Valid from ${g} to ${y}`;throw console.warn(`checkCertificateInValidityPeriod: ${I}`),new Error(P.CERTIFICATE_HAS_EXPIRED)}o.push(d)}catch(l){throw console.warn(`checkCertificateInValidityPeriod\uFF1A ${l.message}`),new Error(P.CERTIFICATE_HAS_EXPIRED,{cause:l})}if(!o||o.length===0)throw new Error(P.CERTIFICATE_HAS_EXPIRED);if(!DN(e,t,r,o))throw new Error(P.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function IN(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new yu(t);let r=Qv.from(t,"base64");return new yu(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}function AN(n){if(n.cert){let e=vn.pki.publicKeyToPem(n.cert.publicKey);return mN(e).export({type:"spki",format:"der"})}if(n.asn1)try{let e=vn.asn1.toDer(n.asn1).getBytes(),t=Qv.from(e,"binary");return new yu(t).publicKey.export({type:"spki",format:"der"})}catch(e){return or(`Failed to parse cert from asn1: ${e}`),null}return null}function DN(n,e,t,r){try{let i=fN(n),o=vn.asn1.fromDer(vn.util.createBuffer(i)),c=vn.pkcs12.pkcs12FromAsn1(o,t).getBags({bagType:vn.pki.oids.certBag})[vn.pki.oids.certBag]||[];for(let l of c){let d=l.attributes?.friendlyName?.[0];if(!d||d.toLowerCase()!==e.toLowerCase())continue;let g=AN(l);if(!g)continue;if(r.some(I=>{let le=I.publicKey.export({type:"spki",format:"der"});return g.equals(le)}))return!0}return!1}catch(i){let o=i instanceof Error?i.message:String(i);return or(`Failed to process P12 file: ${n}, error: ${o}`),!1}}function wu(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var rw="https://developer.huawei.com",RN={"ohos.permission.SYSTEM_FLOAT_WINDOW":"/consumer/cn/doc/harmonyos-guides/window-pipwindow","ohos.permission.READ_CONTACTS":"/consumer/cn/doc/harmonyos-references/js-apis-contact#contactselectcontacts10","ohos.permission.READ_IMAGEVIDEO":"/consumer/cn/doc/harmonyos-guides/select-user-file#%E9%80%89%E6%8B%A9%E5%9B%BE%E7%89%87%E6%88%96%E8%A7%86%E9%A2%91%E7%B1%BB%E6%96%87%E4%BB%B6","ohos.permission.WRITE_IMAGEVIDEO":"/consumer/cn/doc/harmonyos-guides/savebutton","ohos.permission.READ_AUDIO":"/consumer/cn/doc/harmonyos-guides/select-user-file#%E9%80%89%E6%8B%A9%E9%9F%B3%E9%A2%91%E7%B1%BB%E6%96%87%E4%BB%B6","ohos.permission.WRITE_AUDIO":"/consumer/cn/doc/harmonyos-guides/save-user-file#%E4%BF%9D%E5%AD%98%E9%9F%B3%E9%A2%91%E7%B1%BB%E6%96%87%E4%BB%B6","ohos.permission.READ_PASTEBOARD":"/consumer/cn/doc/harmonyos-guides/pastebutton"},TN="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function xN(n){let e=RN[n];return e?`${rw}${e}`:void 0}function LN(){return`${rw}${TN}`}var NN={"acl.can.apply.text":"Permission Application Scenarios","acl.permissions.warn":"Note: You are applying for restricted ACL permissions: {0} These permissions are subject to review together with your app release. For a faster review process, apply for the following permissions instead, if they are sufficient for your purposes: {1} {2}"};function tw(n,e){return(NN[n]??n).replace(/\{(\d+)\}/g,(r,i)=>String(e[Number(i)]??""))}function MN(n){return Array.from(n).join(", ")}function nw(n,e){if(n.size===0)return;let t=jr.getAclPermissionInfos(e),r=new Set;for(let g of t)n.has(g.permissionName)&&r.add(g);for(let g of r){let y=xN(g.permissionName);y!=null&&(g.permissionHelpUrlKey=y)}let i=new Set;for(let g of r)i.add(g.permissionDisplayName);let o=new Set;for(let g of r)if(g.permissionHelpUrlKey!=null){let y=g.permissionInsteadName??g.permissionDisplayName;o.add(`${y} (${g.permissionHelpUrlKey})`)}let s=LN(),a=tw("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=o.size>0?Array.from(o).join(", ")+".":"",d=tw("acl.permissions.warn",[MN(i),l,c]);console.log(d)}var uc=class{_project=null;get project(){if(!this._project)throw new Error("Project not initialized. Call checkProjectDir first.");return this._project}checkProjectDir(e){try{return this._project=q.discover(process.cwd()),{passed:!0,message:""}}catch(t){return p(`[EnvCheck] Project.discover() failed: ${t.message}`),e(me.PROJECT_DIR_MISSING)}}checkProduct(e,t){try{return this._project.validateProduct(e),{passed:!0,message:""}}catch(r){return p(`[EnvCheck] Product validation failed: ${r.message}`),t(`Product "${e}" not found.Check the product property in the build-profile.json5 file.`)}}checkBundleName(e,t){try{return this._project.getBundleName(),{passed:!0,message:""}}catch(r){return p(`[EnvCheck] BundleName check failed: ${r.message}`),t(`bundleName was not found under product "${e}".Check the bundleName configuration.`)}}checkAtomicService(){return this._project.isAtomicService()?{passed:!1,message:me.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import ON from"fs";import iw from"path";var pc=class{constructor(e){this.toolProvider=e}checkJava(e){try{return this.toolProvider.assertJava(),{passed:!0,message:""}}catch(t){return p(`[EnvCheck] Java check failed: ${t.message}`),e(`${t.message}`)}}checkHapSignTools(e){let t=this.toolProvider.sdkPath,r=iw.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");if(!ON.existsSync(r)){let i=iw.join("sdk","default","openharmony","toolchains","lib","hap_sign_tools.jar");return e(`hap_sign_tools.jar not found.Check whether ${i} exists.`)}return{passed:!0,message:""}}};var mc=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await Oe.getUserInfo()}catch(e){return p(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await Oe.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(me.LOGIN_REQUIRED)}catch(t){return p(`[EnvCheck] Login check failed: ${t.message}`),e(me.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(me.TEAM_INFO_FAILED);try{if((await Er()).teamList.length>0)return{passed:!0,message:""}}catch(r){return p(`[EnvCheck] Team API error: ${r.message}`),e(me.TEAM_INFO_FAILED)}return p("[EnvCheck] No teams found for current user"),e(me.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(me.REALNAME_REQUIRED):t.isRealName!==!0?(p("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(me.REALNAME_REQUIRED)):{passed:!0,message:""}:e(me.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let r=e??"";try{let i=await Er();if(r=e??(i.teamList.length>0?i.teamList[0].id:t.userId)??"",!i.teamList.some(s=>s.id===r)){let s=`team-id for ${r} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`;return p(`[EnvCheck] ${s}`),{passed:!1,message:s}}return{passed:!0,message:""}}catch(i){return p(`[EnvCheck] Team ID check failed: ${i.message}`),{passed:!1,message:`team-id for ${r} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`}}}async checkRegion(e){let t=await this.ensureUserInfo();return t?t.countryCode?t.countryCode!=="CN"?e(me.REGION_CHINA_ONLY):{passed:!0,message:""}:(p("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(me.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function _N(n){try{let{teamList:e}=await Er();if(e.length>0)return e[0].id}catch(e){p(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function FN(n){let e=await Oe.getUserInfo(),t=await Oe.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await _N(e.userId);if(!r)throw new Error("No team found");let i={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await dc(i)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var fc=class{constructor(e){this.toolProvider=e}async checkDevice(e,t){try{let r=await FN(t);if(r.length>0)return p(`[EnvCheck] Scenario 4 Device check: ${r.length} device(s) found in AGC cloud, skipping local device check`),{passed:!0,message:""};p("[EnvCheck] Scenario 4 Device check: no cloud devices found, falling back to local hdc");let o=await ne.from(this.toolProvider).listDevices();return o.length===0?(p("[EnvCheck] Scenario 4 Device check: no local devices found"),e(me.DEVICE_MISSING)):o.some(a=>xt(a.serial))?{passed:!0,message:""}:(p("[EnvCheck] Scenario 4 Device check: local device found but not an emulator"),e(me.DEVICE_MISSING))}catch(r){return p(`[EnvCheck] Scenario 4 Device check failed: ${r.message}`),e(me.DEVICE_DETECT_FAILED)}}};var hc=class{projectChecker=new uc;toolchainChecker=null;authChecker=new mc;deviceChecker=null;constructor(){}async preflight(e){let t=r=>this.blockingFail(r);return!(!await this.runAuthChain(e,t)||!await this.initToolchain()||!await this.runDeviceCheck(e,t)||!await this.runProjectChecks(e,t)||!await this.runAuxChecks(e))}async runAuthChain(e,t){let r=o=>(o.passed||this.fail(o),!0),i=[()=>this.authChecker.checkLogin(t),()=>this.authChecker.checkRealname(t),()=>this.authChecker.checkTeamInfo(t)];for(let o of i)if(!r(await o()))return!1;return!(e.teamId&&!r(await this.authChecker.checkTeamId(e.teamId)))}async initToolchain(){try{let e=await C.new();return this.toolchainChecker=new pc(e),this.deviceChecker=new fc(e),!0}catch(e){throw p(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(me.TOOLCHAIN_INIT_FAILED,{cause:e})}}async runDeviceCheck(e,t){return(i=>i.passed?!0:(this.fail(i),!1))(await this.deviceChecker.checkDevice(t,e.teamId))}async runProjectChecks(e,t){let r=o=>o.passed?!0:(this.fail(o),!1);if(!r(this.projectChecker.checkProjectDir(t))||!r(this.projectChecker.checkAtomicService()))return!1;let i=[()=>this.projectChecker.checkProduct(e.productName,t),()=>this.projectChecker.checkBundleName(e.productName,t),()=>this.toolchainChecker.checkJava(t),()=>this.toolchainChecker.checkHapSignTools(t)];for(let o of i)if(!r(o()))return!1;return!0}async runAuxChecks(e){let t=r=>r.passed?!0:(this.fail(r),!1);return!e.teamId&&!t(await this.authChecker.checkTeamId(e.teamId))?!1:(await this.authChecker.checkRegion(r=>this.blockingFail(r)),!0)}blockingFail(e){return{passed:!1,message:e}}fail(e){throw p(`[EnvCheck] FAIL: ${e.message}`),new Error(e.message)}};var ow=5*1024*1024;function HN(n){try{let e=bu.statSync(n);if(e.size>ow)throw new Error(`Profile file too large: ${e.size} bytes (max ${ow} bytes): ${n}`);let t=bu.readFileSync(n,"utf-8");return aw.parse(t)}catch(e){if(e.code==="ENOENT")return{app:{signingConfigs:[],products:[]}};throw new Error(`Failed to read profile: ${n}`,{cause:e})}}function UN(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function BN(n){if(n.keyPwd===n.storePassword){let r=await $r.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await $r.encryptedPassword(n.keyPwd,n.p12FilePath),t=await $r.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function WN(n,e,t){let r=sw.join(n,"build-profile.json5"),i=HN(r);UN(i);let o=t??"default",{keyPassword:s,storePassword:a}=await BN(e),c={name:o,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:s,profile:e.profileFilePath,signAlg:Ct.signAlg,storeFile:e.p12FilePath,storePassword:a}},l=i.app?.signingConfigs?.findIndex(g=>g.name===o);l!==void 0&&l>=0?i.app.signingConfigs[l]=c:i.app.signingConfigs.push(c);let d=i.app?.products?.findIndex(g=>g.name===o);d!==void 0&&d>=0?i.app.products[d].signingConfig=o:i.app.products.push({name:o,signingConfig:o}),bu.writeFileSync(r,aw.stringify(i,null,2),"utf-8")}async function VN(n){let e=await Oe.getUserInfo(),t=await Oe.refreshToken();if(!e||!t)throw new Error("Failed to obtain login credentials. Run `devecocli auth login` again.");return{uid:e.userId??"",teamId:n.teamId??e.userId??"",accessToken:t.accessToken??""}}async function GN(n){let e=n.product||"default";await new hc().preflight({productName:e,teamId:n.teamId}),console.log("Executing signature generate command");let r=await VN(n),i=await C.new(),{shouldRegenerate:o}=await Ro.shouldRegenerate({force:n.force??!1,teamId:r.teamId,productName:n.product},i);if(!o){console.log(Su("Signature generation completed successfully."));return}await qN(n,r,i),console.log(Su("Signature generation completed successfully."))}async function qN(n,e,t){let r=await au(e,n.product),i=zN(n,e,r,t);i.allDeviceIds=await zv(e,t.hdcPath),await ew(e,i);let o=q.discover(process.cwd()).rootDir;await WN(o,r,n.product??"default"),console.log(Su(`Signing config written to ${sw.join(o,"build-profile.json5")}`))}function zN(n,e,t,r){let i=process.cwd(),o=q.discover(i),s=cc(o,r);return nw(s,o),{productName:n.product||"default",bundleName:o.getBundleName(n.product||"default"),projectPath:o.rootDir,teamId:e.teamId,force:n.force||!1,aclPermissionList:[...s],certIds:[t.certId],keyAlias:t.keyAlias,keyPwd:t.keyPwd}}var cw=new $N("signature").description("Generate application signature.");cw.command("generate").description("Automatically generate signing materials and write them to the project configuration.").option("--force","Force overwrite existing local signing materials.").option("--team-id <team-id>","Specify the team ID to use.").option("--product <product>","Specify the product. The default value is default.").action(async n=>{let e={event:b.CommandExecuted,args:["signature","generate",...n.force?["--force"]:[],...n.teamId?["--team-id"]:[],...n.product?["--product"]:[]]},t=Date.now(),r=!0,i=null;try{await GN(n)}catch(o){r=!1,i=B(o),console.error(jN(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await k.track(e,o)}});var lw=cw;if(!At())try{k.init(gc.join(he(),"TraceLogData")),k.startScheduler()}catch(n){h.error(`[telemetry] init failed: ${n instanceof Error?n.message:String(n)}`)}(async()=>{if(!At())try{let n=await C.new();k.setSourceType(n.sourceType);let e=n.readVersion();e&&(n.sourceType==="clt"?k.setCltVersion(e):k.setStudioVersion(e))}catch(n){h.error(`[telemetry] toolchain info failed: ${n instanceof Error?n.message:String(n)}`)}})();ce.name("devecocli").description(`HarmonyOS application development command line tool
|
|
1367
|
+
`),console.log(Ee("[compat:check] === end stdout ===")));let o=new se("errorCode",`Compatibility scan failed: ${i.message}`+(i.stderr?`
|
|
1368
|
+
${i.stderr}`:""));throw i.stdout&&(o.stdout=i.stdout),o}}function YL(n,e){if(!NL.includes(e.format))throw new DL(`--format must be default, csv, or json (console: default|json, file: default|csv|json). got "${e.format}"`);if(n.length>0&&e.modules&&e.modules.length>0)throw new se("errorCode","Cannot use `--modules` together with file arguments. Use either file-level scanning (with files) or module-level scanning (with --modules).");if(!e.sourceVersion)throw new se("errorCode","--source-version is required.");if(!e.targetVersion)throw new se("errorCode","--target-version is required.");if(!e.outputPath&&e.format==="csv")throw new se("errorCode","--format csv requires --output-path. For console output, use --format json or --format default (or omit the flag).")}function KL(n,e){let t=[];if(n.sourceVersion&&!e.includes(n.sourceVersion)&&t.push(`--source-version "${n.sourceVersion}"`),n.targetVersion&&!e.includes(n.targetVersion)&&t.push(`--target-version "${n.targetVersion}"`),t.length>0){let r=t.length>1?"are":"is";throw new se("errorCode",`${t.join(" and ")} ${r} not in the available SDK version list.
|
|
1369
|
+
Run \`devecocli compat versions\` to see all available versions.`)}if(n.sourceVersion&&n.targetVersion){let r=e.indexOf(n.sourceVersion),i=e.indexOf(n.targetVersion);if(r>=i)throw new se("errorCode",`--target-version "${n.targetVersion}" must be later than --source-version "${n.sourceVersion}". Run \`devecocli compat versions\` to see the available order.`)}}function XL(n,e,t,r,i){i==="none"&&(t==="json"?GL(n,r):VL(n,r)),WL(n,e)}function ZL(n,e){let t=X.dirname(n),r=X.basename(n),i=e.slice(1).map(o=>o.startsWith("--")?o:`"${o}"`).join(" ");p(Ee(`[compat:check] command: cd "${t}" && node "${r}" ${i}`))}function QL(n){try{TL(n),p(Ee(`[compat:check] cleaned up tmp report: "${n}"`))}catch(e){p(Ee(`[compat:check] failed to clean up tmp report: ${e.message}`))}}var eN=[".csv",".json"];function tN(n){return eN.includes(n.toLowerCase())}function rN(n,e){if(!n)return{kind:"none"};let t=X.extname(n).toLowerCase();if(!tN(t))return{kind:"dir",dirPath:X.resolve(n)};if(t===".csv"&&!(e==="default"||e==="csv")||t===".json"&&e!=="json")throw new se("errorCode",`The --output-path file extension '${t}' does not match --format ${e}. Use --format ${t===".json"?"json":"default"}, or rename the file.`);return{kind:"file",filePath:X.resolve(n),ext:t}}function nN(n){if(n.kind==="file"){if(hc(n.filePath))throw new se("errorCode",`Target file "${n.filePath}" already exists. Remove it first, or choose a different --output-path.`);let e=X.dirname(n.filePath);if(!hc(e))throw new se("errorCode",`Target directory "${e}" does not exist. Create it first, or choose a different --output-path.`)}else if(n.kind==="dir"&&!hc(n.dirPath))throw new se("errorCode",`Target directory "${n.dirPath}" does not exist. Create it first, or choose a different --output-path.`)}function ew(n){return JSON.stringify({records:n,count:n.length},null,2)+`
|
|
1370
|
+
`}function iN(n,e,t,r){r===".csv"?Yv(n,t):Kv(t,ew(e),"utf8"),p(Ee(`[compat:check] saved report: "${t}"`))}function oN(n,e,t,r){if(r==="json"){let o=X.basename(n,".csv"),s=X.join(t,`${o}.json`);return Kv(s,ew(e),"utf8"),p(Ee(`[compat:check] saved report: "${s}"`)),s}let i=X.join(t,X.basename(n));return Yv(n,i),p(Ee(`[compat:check] saved report: "${i}"`)),i}async function sN(n,e){let t=new et(n,process.cwd(),!0),r=e.modules&&e.modules.length>0?e.modules[0]:void 0;try{await t.compileNative("default",r)}catch(i){throw new se("errorCode",`hvigorw compileNative failed (module=${r??"<project>"}): `+i.message,{cause:i})}}async function aN(n,e){YL(n,e);let t=q.discover(process.cwd());e.modules&&e.modules.length>0&&OL(t,e.modules),n.length>0&&_L(n);let r=await C.new(),{apiChangeDir:i,scriptPath:o}=r.getApiscanPaths();p(Ee(`[compat:check] script: "${o}"`));let s=Zv(i);KL(e,s),e.outputPath&&p(Ee(`[compat:check] outputPath: "${e.outputPath}"`));let a=rN(e.outputPath,e.format);return p(Ee(`[compat:check] outputTarget: ${a.kind}`)),nN(a),{project:t,scriptPath:o,target:a,toolProvider:r}}function cN(n,e,t,r){if(t.kind==="file")return iN(n,e,t.filePath,t.ext),t.filePath;if(t.kind==="dir")return oN(n,e,t.dirPath,r);if(t.kind==="none")return null;throw new se("errorCode",`Unexpected output target kind: ${t.kind}`)}async function lN(n,e,t,r,i){let o=LL({text:"Running compatibility check...",color:"cyan"}).start();try{await sN(n.toolProvider,t);let s=zL(n.scriptPath,e,n.project,t);ZL(n.scriptPath,s);let a=await JL(n.toolProvider,s),c=BL(a,bu.tmpdir());if(!c)throw new se("errorCode","Scanner output format unexpected: missing report path.");p(Ee(`[compat:check] tmp csv: "${c}"`));let l=UL(c),d=cN(c,l,n.target,t.format);QL(c),o.stop(),XL(l,d,t.format,t.limit,n.target.kind),await Si(r,!0,null,i)}catch(s){o.fail("Compatibility check failed");let a=Eu(s);throw await Si(r,!1,a,i),s}}async function tw(n,e){let t=Date.now(),r=["check","compat"];try{let i=await aN(n,e);await lN(i,n,e,t,r)}catch(i){let o=Eu(i);throw await Si(t,!1,o,r),i}}function uN(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new dN(`--limit must be a positive integer (got "${n}")`);return e}var Pu=new rw("compat").description("Compatibility checking utilities.");Pu.description("Check source code compatibility against a target SDK version. By default, performs a project-level scan; pass positional `files...` for file-level scanning; pass `--modules` for module-level scanning.").arguments("[files...]").option("--source-version <version>","Current project SDK version (required; use `compat versions` to list available versions). On zsh, quote the value because version strings contain parentheses; run `compat versions` first to copy a real example.").option("--target-version <version>","Target SDK version (required; use `compat versions` to list available versions). On zsh, quote the value because version strings contain parentheses; run `compat versions` first to copy a real example.").option("--modules <modules...>","Modules to check (default: all modules in the project). Mutually exclusive with positional file arguments.").option("--format <format>",'Output format: "json" or "default" (text) for console; "csv", "json", or "default" for file output (--output-path). "csv" requires --output-path.',"default").option("--output-path <path>","Directory to write the detailed report CSV to (default: ./compat-output)").option("--limit <num>","Maximum number of change records to display (default: 100)",uN,100).action(async(n,e)=>{await tw(n,e)});Pu.command("versions").description("List all available target SDK versions for compatibility checking").option("--format <format>","Output format: default or json").action(async(n,e)=>{let t=e.optsWithGlobals().format;await Qv(t)});var pN=new rw("check").description("Run DevEco project checks").addCommand(Pu).addCommand(hu()).addCommand(Su()),nw=pN;import{Command as eO}from"commander";import{green as qu,red as tO}from"colorette";import zu from"fs";import Uw from"path";import Bw from"json5";import{readFileSync as UN}from"fs";import{join as mN}from"path";var me={BASE_URL:"https://connect-api.cloud.huawei.com",CERT_LIST_PATH:"/api/cps/harmony-cert-manage/v1/cert/list",CERT_DELETE_PATH:"/api/cps/harmony-cert-manage/v1/cert/delete",CERT_ADD_PATH:"/api/cps/harmony-cert-manage/v1/cert/add",CERT_DOWNLOAD_URL_PATH:"/api/amis/app-manage/v1/objects/url/reapply",DEVICE_ADD_PATH:"/api/cps/device-manage/v1/device/add",DEVICE_LIST_PATH:"/api/cps/device-manage/v1/device/list",PROVISION_ADD_REAL_PATH:"/api/cps/provision-manage/v1/ide/real/provision/add",PROVISION_ADD_TEST_PATH:"/api/cps/provision-manage/v1/ide/test/provision/add",PROVISION_DELETE_PATH:"/api/cps/provision-manage/v1/provision/delete"},Ke={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:mN(".ohos","config"),DOWNLOAD_CONNECT_TIMEOUT_MS:5e3},Pe={SUCCESS_MARKER:'"code":0',SQUARE_BRACKETS:"[]",OPENPROXY_BLOCKED_URL:"Openproxy_Blocked_URL_list",CERT_LIMIT_CODE:"205389872",USER_NOT_HARMONY_CODE:"205389904",DEVICE_EXCEEDS_LIMIT_CODE:"205389859",DEVICE_NAME_REPEAT_CODE:"205389857",PROVISION_EXCEEDS_LIMIT_CODE:"205389938",PROVISION_NAME_REPEAT_CODE:"205389830"},At={FORBIDDEN:403,UNAUTHORIZED:401},P={ERR_FORBIDDEN:"You do not have AppGallery Connect permissions for the current team. Request access from the team administrator or switch to a team where you have permissions.",ERR_UNAUTHORIZED:"Invalid AccessToken. Sign in and try again.",ERR_CERT_LIMIT_REACHED:"The number of certificates has reached the limit. Delete some certificates and try again.",ERR_CERT_NETWORK_ERROR:"Ensure the external network connection is available before downloading the certificate.",ERR_CERT_INVALIDATE:"The downloaded .cer file is invalid. Try again.",ERR_DOWNLOAD_CER:"Failed to download the certificate file. Check the following configurations: Network connection, HTTP Proxy, etc.",ERR_USER_NOT_HARMONY:"The user is not in harmony allow list, please grant the permission",ERR_READ_CSR:"Failed to read the .csr file, please try again later",ERROR_WHILE_ADD_DEVICE:"Failed to add the device, please try again.",DEVICE_LIMIT_REACHED:"The number of devices has reached the limit. Delete some unused devices and try again.",DEVICE_NAME_REPEAT:"Duplicate device name, please try again.",DEVICE_LIST_EMPTY:"No devices available.",ADD_PROFILE_FAIL:"Failed to add the profile, please try again.",NO_AGC_PERMISSION:"You do not have the AppGallery Connect permission with the current team. Apply for the permission form the team administrator, or switch to a team with which you already have the permission.",ERROR_WHILE_DOWNLOAD_PROFILE:"Failed to download the profile, please try again.",PROFILE_NAME_REPEAT:"The profile name already exists in the AGC.",ERROR_WHILE_PARSE_PROFILE:"Failed to parse the profile, please try again.",TEST_PROVISION_EXCEEDS_LIMIT:"Provision number exceeds limit.",CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT:"The certificate application file is inconsistent with the file in profile, please try again.",CERTIFICATE_HAS_EXPIRED:"The signature does not take effect or has expired. It may be the current system time is inaccurate, please calibrate the system time and sign again.",ERROR_SIGN_BUNDLE_NAME_VALIDATE:"The bundle name contains 7 to 128 characters, including only letters, digits, and underscores (_). It must be start with a letter and contain at least three segments separated by periods (.), each of the segments ending with a digit or letter."},he={TOOLCHAIN_INIT_FAILED:"Auto-sign failed: unable to initialize toolchain",LOGIN_REQUIRED:"Failed to automatically generate signatures.Run devecocli auth login to sign in.",TEAM_INFO_FAILED:"Failed to obtain user team information.Check the network connection, HTTP proxy, and other configurations.",REALNAME_REQUIRED:"Users without real-name verification are not supported.Complete real-name verification in AppGallery Connect.",SESSION_EXPIRED:"User session expired or token invalid. Please login again.",REGION_CHINA_ONLY:"This feature is only available for accounts registered in Chinese mainland.",DEVICE_MISSING:"Unable to create the profile file due to missing devices.Connect a device through IP or USB, or manually add a device in AppGallery Connect first.If you are installing the HAP package on an emulator, you can skip the signing step.",DEVICE_DETECT_FAILED:"Unable to detect devices. Please check hdc status. If installing HAP on an emulator, signature step can be skipped.",PROJECT_DIR_MISSING:"Not in a valid project directory (project-level build-profile.json5 not found).",ATOMIC_SERVICE_UNSUPPORTED:"AtomicService projects are not yet supported. Please configure signing manually."};function gc(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}function Cu(n){let e=n.replace(Ke.TEAM_ID_INVALID_CHARS,"");return`${Ke.CERT_NAME_PREFIX}${e}.cer`}function bi(n,e,t){if(n===At.FORBIDDEN)return e===Pe.OPENPROXY_BLOCKED_URL?new Error(P.ERR_CERT_NETWORK_ERROR):new Error(P.ERR_FORBIDDEN);if(n===At.UNAUTHORIZED)return new Error(P.ERR_UNAUTHORIZED);if(t.includes(Pe.USER_NOT_HARMONY_CODE))return new Error(P.ERR_USER_NOT_HARMONY);if(t.includes(Pe.CERT_LIMIT_CODE))return new Error(P.ERR_CERT_LIMIT_REACHED);let r=fN(t);return new Error(r??P.ERR_DOWNLOAD_CER)}function fN(n){let e=iw(n);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let r=typeof t=="string"?iw(t):t;if(r&&typeof r=="object"){let i=r.msg;if(typeof i=="string"&&i.trim()!=="")return i}return null}function iw(n){try{return JSON.parse(n)}catch{return null}}function ku(n){return JSON.parse(n)}async function ow(n){let e=`${me.BASE_URL}${me.CERT_LIST_PATH}`,t=await N.postAllowFailure(e,{headers:gc(n)});if(t.statusCode!==200)throw bi(t.statusCode,t.statusText,t.data);return ku(t.data)?.certList??[]}async function yc(n,e){return(await ow(n)).find(r=>r.certName===e)??null}async function Iu(n,e){let t=`${me.BASE_URL}${me.CERT_DELETE_PATH}`,r=await N.deleteAllowFailure(t,{headers:gc(n),params:{certIds:[e]}});if(r.statusCode!==200)throw bi(r.statusCode,r.statusText,r.data);return ku(r.data)?.ret?.code===0}async function Du(n,e,t){let r=`${me.BASE_URL}${me.CERT_ADD_PATH}`,i={csr:e,certName:t,certType:Ke.CERT_TYPE_DEBUG},o=await N.postAllowFailure(r,{headers:gc(n),params:i});if(o.statusCode!==200)throw bi(o.statusCode,o.statusText,o.data);if(!o.data.includes(Pe.SUCCESS_MARKER))throw bi(void 0,o.statusText,o.data)}async function Au(n,e){let t=`${me.BASE_URL}${me.CERT_DOWNLOAD_URL_PATH}`,r=await N.postAllowFailure(t,{headers:gc(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw bi(r.statusCode,r.statusText,r.data);return ku(r.data)?.urlsInfo?.[0]??null}import{mkdirSync as hN,writeFileSync as gN,existsSync as yN}from"fs";import{dirname as vN}from"path";import{createHash as wN}from"crypto";function SN(n){let e;try{e=new URL(n)}catch{throw new Error(`Invalid download URL: ${JSON.stringify(n)}`)}if(e.protocol!=="https:")throw new Error(`Download URL must use HTTPS: ${e.protocol}`);let t=e.hostname.toLowerCase();if(t==="localhost"||t==="127.0.0.1"||t==="::1"||t.startsWith("169.254.")||t.startsWith("10.")||t.startsWith("192.168.")||/^172\.(1[6-9]|2\d|3[0-1])\./.test(t)||t.endsWith(".internal")||t.endsWith(".local"))throw new Error(`Download URL points to internal/private address: ${t}`)}async function Fo(n,e,t){SN(n);let{statusCode:r,statusText:i,buffer:o}=await N.getBinaryAllowFailure(n,{timeout:Ke.DOWNLOAD_CONNECT_TIMEOUT_MS});if(r!==200)throw r===At.FORBIDDEN&&i===Pe.OPENPROXY_BLOCKED_URL?new Error(P.ERR_CERT_NETWORK_ERROR):new Error(P.ERR_DOWNLOAD_CER);if(t){let a=wN("sha256").update(o).digest("hex");if(a!==t.toLowerCase())throw new Error(`SHA-256 mismatch for ${e}: expected ${t.toLowerCase()}, got ${a}`)}let s=vN(e);yN(s)||hN(s,{recursive:!0}),gN(e,o)}import $N from"fs/promises";import{readFileSync as jN}from"fs";import vc from"path";import cw from"crypto";import bN from"os";import $o from"fs/promises";var lw={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},sw=["ECC","RSA"],aw=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],EN={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},PN=8,Ru=64,CN=/[\\/:*?"<>|=-]/g,Rt={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function kN(n){if(!n.keyAlias.trim())throw new Error("keyAlias cannot be empty");if(!n.keystoreFile.trim())throw new Error("keystoreFile cannot be empty");if(n.keyAlias.length>Ru)throw new Error(`The length of keyAlias cannot exceed ${Ru}`);if(!sw.includes(n.keyAlg))throw new Error(`Invalid key algorithm ${n.keyAlg}, available: ${sw.join(" / ")}`);let e=EN[n.keyAlg];if(!e.includes(n.keySize))throw new Error(`Key algorithm ${n.keyAlg} does not support size ${n.keySize}, available: ${e.join(", ")}`)}function IN(n){if(!n.keyAlias.trim())throw new Error("keyAlias cannot be empty");if(!n.keystoreFile.trim())throw new Error("keystoreFile cannot be empty");if(!n.subject.trim())throw new Error("subject cannot be empty");if(!aw.includes(n.signAlg))throw new Error(`Invalid sign algorithm ${n.signAlg}, available: ${aw.join(" / ")}`)}function DN(n){return cw.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function AN(n){let e=n?.trim()??"";return e&&e.replace(CN,"_").replace(/\.+/g,"_").slice(0,Ru)||Rt.productName}async function dw(){let n=await C.new();n.assertJava();let e=n.javaPath,t=n.sdkPath;u.info(`\u8BFB\u53D6SDK\u6839\u76EE\u5F55\uFF1A${t}`);let r=vc.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");try{await $o.access(r)}catch(i){throw new Error(`Sign tool jar not found: ${r}`,{cause:i})}return{javaPath:e,jarPath:r}}async function RN(n){let{javaPath:e,jarPath:t}=await dw(),r=["-jar",t,lw.GENERATE_KEYPAIR,"-keyAlias",n.keyAlias,"-keyAlg",n.keyAlg,"-keySize",n.keySize,"-keystoreFile",n.keystoreFile,"-keystorePwd",n.keystorePwd];n.keyPwd&&r.push("-keyPwd",n.keyPwd),n.pwdInputMode&&r.push("-pwdInputMode",n.pwdInputMode);let i=r.map((o,s)=>s>0&&["-keyPwd","-keystorePwd"].includes(r[s-1])?"******":o);return u.debug("generate-keypair \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",i.join(" ")),[e,...r]}async function TN(n){let{javaPath:e,jarPath:t}=await dw(),r=["-jar",t,lw.GENERATE_CSR,"-keyAlias",n.keyAlias,"-subject",n.subject,"-signAlg",n.signAlg,"-keystoreFile",n.keystoreFile,"-keystorePwd",n.keystorePwd];n.outFile&&r.push("-outFile",n.outFile),n.keyPwd&&r.push("-keyPwd",n.keyPwd),n.pwdInputMode&&r.push("-pwdInputMode",n.pwdInputMode);let i=r.map((o,s)=>s>0&&["-keyPwd","-keystorePwd"].includes(r[s-1])?"******":o);return u.debug("generate-csr \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",i.join(" ")),[e,...r]}async function xN(n){u.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),kN(n);let e=await RN(n),t=await Fi(e[0],e.slice(1));if(t.exitCode!==0){let r=t.stderr||t.stdout||"Unknown tool error";throw new Error(`An error occurred while generating the private key P12, exit code${t.exitCode}\uFF1A${r}`)}return u.info("\u751F\u6210P12\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}async function LN(n){u.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),IN(n);let e=await TN(n),t=await Fi(e[0],e.slice(1));if(t.exitCode!==0){let r=t.stderr||t.stdout||"Unknown tool error";throw new Error(`An error occurred while generating the CSR, exit code${t.exitCode}\uFF1A${r}`)}return u.info("\u751F\u6210CSR\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}function NN(n=PN){return cw.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function MN(){let n=bN.homedir();try{await $o.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=vc.join(n,".ohos","config");try{await $o.mkdir(e,{recursive:!0,mode:448})}catch(t){throw new Error(`Failed to create directory ${e}`,{cause:t})}return u.info(`\u7B7E\u540D\u914D\u7F6E\u76EE\u5F55\u5C31\u7EEA\uFF1A${e}`),e}async function Te(n,e,t){let r=AN(n),i=vc.basename(e),o=DN(e),s=`${r}_${i}_${o}=.${t}`,a=await MN();return vc.join(a,s)}function ON(n){let e;try{e=q.discover(n).rootDir}catch(t){throw new Error(`Current directory ${n} is not a valid project root`,{cause:t})}return e}async function _N(n){try{await $o.access(n)}catch(e){throw new Error(`Project directory ${n} is not accessible, missing read/write permissions`,{cause:e})}}async function FN(n){try{await $o.access(n)}catch(e){throw new Error(`P12 file ${n} does not exist, terminating CSR generation.`,{cause:e})}}async function Tu(n,e,t){let r=process.cwd(),i=ON(r);await _N(i),u.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${i}`);let o=NN(),s=await Te(n??"",i,"p12"),a=await Te(n??"",i,"csr");return console.log("Start generating p12"),await xN({keyAlias:e?.keyAlias??Rt.keyAlias,keyPwd:o,keyAlg:e?.keyAlg??Rt.keyAlg,keySize:e?.keySize??Rt.keySize,keystoreFile:s,keystorePwd:o}),await FN(s),console.log("Start generating csr"),await LN({subject:t?.subject??Rt.csrSubject,outFile:a,keyAlias:t?.keyAlias??Rt.keyAlias,keyPwd:o,signAlg:t?.signAlg??Rt.signAlg,keystoreFile:s,keystorePwd:o}),{p12FilePath:s,csrFilePath:a,keyPwd:o,keyAlias:e?.keyAlias??Rt.keyAlias}}var HN=["p12","cer","csr","p7b"];async function xu(n,e){for(let t of HN){let r=await Te(n,e,t);await $N.rm(r,{force:!0})}}function Lu(n){let e;try{e=jN(n,"utf-8")}catch{throw new Error(P.ERR_CERT_INVALIDATE)}if(!Ke.CERT_PATTERN.test(e))throw new Error(P.ERR_CERT_INVALIDATE)}async function uw(n,e){return{certPath:await Te(n,e,"cer"),csrPath:await Te(n,e,"csr"),p12Path:await Te(n,e,"p12"),profilePath:await Te(n,e,"p7b")}}async function Nu(n,e){let t=e??"",r=q.discover(process.cwd()).rootDir;await xu(t,r);let i=Cu(n.teamId),o=await yc(n,i);if(o&&!await Iu(n,o.id))throw new Error(P.ERR_DOWNLOAD_CER);let s=await Tu(e),a;try{a=UN(s.csrFilePath,"utf-8")}catch{throw new Error(P.ERR_READ_CSR)}console.log("Start generating certificate"),await Du(n,a,i);let c=await yc(n,i);if(!c)throw new Error(P.ERR_DOWNLOAD_CER);let l=await Au(n,c.certObjectId);if(!l)throw new Error(P.ERR_DOWNLOAD_CER);let d=await Te(t,r,"cer");await Fo(l.newUrl,d,l.sha256),Lu(d);let g=await Te(t,r,"p7b");return{p12FilePath:s.p12FilePath,csrFilePath:s.csrFilePath,cerFilePath:d,profileFilePath:g,certId:c.id,keyAlias:s.keyAlias,keyPwd:s.keyPwd,storePassword:s.keyPwd}}import Ac from"crypto";import Br from"fs";import*as Iw from"path";import lM from"json5";import{execa as Pw}from"execa";import Cw from"node-forge";import{createCipheriv as BN,createDecipheriv as WN,pbkdf2Sync as VN,randomBytes as Fu}from"crypto";import{promises as wn}from"fs";import{dirname as GN,join as Tt}from"path";var wc=3,jo=16,qN=1e4,pw="material",zN=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),gw="aes-128-gcm",vn=12,Sc=16,jr=4;function Mu(n){return new Uint8Array(Fu(n))}function JN(n){return Fu(n).toString("hex")}function YN(...n){if(n.length===0)return new Uint8Array(0);let e=n[0].length,t=new Uint8Array(e);for(let r=0;r<e;r++){let i=0;for(let o of n)i^=o[r];t[r]=i}return t}function mw(n,e,t=qN,r=jo){let i=[...n,zN],o=YN(...i),s=Buffer.from(o).toString("utf8"),a=Buffer.from(s,"utf8"),c=VN(a,e,t,r,"sha256");return new Uint8Array(c)}function fw(n,e){let t=Fu(vn),r=BN(gw,n,t),i=Buffer.concat([r.update(e),r.final()]),o=r.getAuthTag(),s=Buffer.concat([i,o]),a=s.length,c=Buffer.alloc(jr+vn+s.length);return c.writeUInt32BE(a,0),t.copy(c,jr),s.copy(c,jr+vn),c}function hw(n,e){if(e.length<jr+vn+Sc)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(jr,jr+vn),i=e.subarray(jr+vn,jr+vn+t);if(i.length<Sc)throw new Error("Ciphertext too short for auth tag");let o=i.subarray(0,i.length-Sc),s=i.subarray(i.length-Sc),a=WN(gw,n,r);return a.setAuthTag(s),Buffer.concat([a.update(o),a.final()])}async function KN(n){try{await wn.rm(n,{recursive:!0,force:!0})}catch{}}async function Ou(n){let e=await wn.readdir(n),t=e.filter(r=>r!==".DS_Store");if(t.length!==1)throw new Error(`Expected exactly 1 file in ${n}, but found ${t.length} (filtered from ${e.length})`);return wn.readFile(Tt(n,t[0]))}async function _u(n,e){let t=JN(jo),r=Tt(n,t);return await wn.writeFile(r,e,{mode:384}),t}var Hr=class{static keyChain=Promise.resolve();static async generateMaterial(e){let t=Tt(e,pw);await KN(t);let r=Tt(t,"ac"),i=Tt(t,"ce");await wn.mkdir(r,{recursive:!0,mode:448}),await wn.mkdir(i,{recursive:!0,mode:448});for(let d=0;d<wc;d++)await wn.mkdir(Tt(t,"fd",String(d)),{recursive:!0,mode:448});let o=Mu(jo),s=[];for(let d=0;d<wc;d++)s.push(Mu(jo));let a=Mu(jo),c=mw(s,o),l=fw(c,a);await _u(r,o),await _u(i,l);for(let d=0;d<wc;d++){let g=Tt(t,"fd",String(d));await _u(g,s[d])}return a}static async readMaterial(e){let t=Tt(e,pw),r=Tt(t,"ac"),i=new Uint8Array(await Ou(r)),o=[];for(let d=0;d<wc;d++){let g=Tt(t,"fd",String(d)),y=await Ou(g);o.push(new Uint8Array(y))}let s=Tt(t,"ce"),a=await Ou(s),c=mw(o,i),l=hw(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t,r=this.keyChain;this.keyChain=new Promise(i=>{t=i}),await r;try{let i=GN(e);try{return await this.readMaterial(i)}catch{return await this.generateMaterial(i)}}finally{t()}}static async encryptedPassword(e,t){let r=await this.getStoreKey(t),i=Buffer.from(e,"utf8");return fw(r,i).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let r=await this.getStoreKey(t),i=Buffer.from(e,"hex");return hw(r,i).toString("utf8")}};import bw from"fs";import Ic from"path";import rM from"json5";import*as bc from"fs";import*as yw from"path";function Ec(n){let e=yw.resolve(n);if(!bc.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=bc.readFileSync(e,"utf-8")}catch(s){throw new Error(`Failed to read SDK info file: ${e}`,{cause:s})}let r;try{r=JSON.parse(t)}catch(s){throw new Error(`Invalid JSON in SDK info file: ${e}`,{cause:s})}let i=r?.data?.apiVersion;if(i==null||i==="")throw new Error(`Missing data.apiVersion in SDK info file: ${e}`);let o=Number(i);if(!Number.isFinite(o))throw new Error(`Invalid data.apiVersion in SDK info file: ${String(i)}`);return o}import*as Pi from"fs";import*as Xe from"path";import{debuglog as Ei}from"util";var vw={"acl.SYSTEM_FLOAT_WINDOW.instead.name":"PiPWindow","acl.READ_CONTACTS.instead.name":"contact.selectContacts","acl.READ_IMAGEVIDEO.instead.name":"PhotoViewPicker","acl.WRITE_IMAGEVIDEO.instead.name":"SaveButton","acl.READ_AUDIO.instead.name":"AudioViewPicker","acl.WRITE_AUDIO.instead.name":"AudioViewPicker","acl.READ_PASTEBOARD.instead.name":"PasteButton"};function XN(n){return Object.prototype.hasOwnProperty.call(vw,n)}function Pc(n){if(XN(n))return vw[n]}var ww={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as ZN}from"url";var kc=class{permissionName;permissionDisplayName;minSupportApiLevel;permissionInsteadName;permissionHelpUrlKey;constructor(e={}){this.permissionName=e.permissionName??"",this.permissionDisplayName=e.permissionDisplayName??"",this.minSupportApiLevel=e.minSupportApiLevel??"",this.permissionInsteadName=e.permissionInsteadName,this.permissionHelpUrlKey=e.permissionHelpUrlKey}};function Cc(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Sw(n){return n==null||n.length===0}function QN(n){return!Sw(n)}function $u(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function eM(n,e){let t=n[e];if(typeof t=="boolean")return t;if(typeof t=="number")return t!==0;if(typeof t=="string"){let r=t.trim().toLowerCase();return r==="true"||r==="1"}return!1}function tM(n,e){let t=n[e];if(typeof t=="number")return Math.trunc(t);if(typeof t=="string"){let r=Number.parseInt(t,10);return Number.isNaN(r)?0:r}return 0}var Ur=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=Xe.join("aclPermission","aclPermissionsInfo.json");static ACL_HAVE_INSTEAD_NAME=new Set(["ohos.permission.SYSTEM_FLOAT_WINDOW","ohos.permission.READ_CONTACTS","ohos.permission.READ_IMAGEVIDEO","ohos.permission.WRITE_IMAGEVIDEO","ohos.permission.READ_AUDIO","ohos.permission.WRITE_AUDIO","ohos.permission.READ_PASTEBOARD"]);static ACL_AVAILABLE_LEVEL_VALUE="system_basic";static ACL_AVAILABLE_TYPE_VALUE="NORMAL";static ACL_AVAILABLE_LEVEL_KEY="availableLevel";static ACL_AVAILABLE_TYPE_KEY="availableType";static ACL_PROVISION_ENABLE_KEY="provisionEnable";static ACL_NAME_KEY="name";static ACL_CONFIG_PREFIX="acl.";static ACL_INSTEAD_NAME_SUFFIX=".instead.name";static ACL_HELP_URL_KEY_SUFFIX=".help.key";static ACL_DEFINE_PERMISSION_KEY="definePermissions";static ACL_SINCE_KEY="since";static PERMISSION_DEFINITIONS_RELATIVE_PATH=Xe.join("lib","PermissionDefinitions.json");static INCLUDE_ACL_PERMISSIONS=new Set(["ohos.permission.FILE_ACCESS_PERSIST","ohos.permission.READ_WRITE_DOWNLOAD_DIRECTORY","ohos.permission.READ_WRITE_DOCUMENTS_DIRECTORY"]);static EXCLUDE_ACL_PERMISSIONS=new Set(["ohos.permission.READ_DOCUMENT","ohos.permission.WRITE_DOCUMENT"]);static handleSpecificAclPermissions(){this.addAclWhiteList(this.INCLUDE_ACL_PERMISSIONS),this.addAclBlackList(this.EXCLUDE_ACL_PERMISSIONS)}static aclPermissionInfoMap=new Map;static aclPermissionNamesMap=new Map;static aclWhiteList=new Set;static aclBlackList=new Set;static builtInConfigTextLoader;static initAclPermission(e,t){let r=e.rootDir,i=this.getOrCreateSet(this.aclPermissionNamesMap,r),o=this.getOrCreateSet(this.aclPermissionInfoMap,r);i.clear(),o.clear();let s=Xe.join(t.sdkPath,"default","sdk-pkg.json"),a=Ec(s);this.MIN_API_TO_FIND_ACL_IN_SDK-a>0?this.initAclPermissionFromBuiltInConfig(i,o):this.initAclPermissionFromSDK(t,i,o)}static getAclPermissionInfos(e){return this.aclPermissionInfoMap.get(e.rootDir)??new Set}static getAclPermissionNames(e){return this.aclPermissionNamesMap.get(e.rootDir)??new Set}static addAclWhiteList(e){for(let t of e)this.aclWhiteList.add(t)}static addAclBlackList(e){for(let t of e)this.aclBlackList.add(t)}static getOrCreateSet(e,t){let r=e.get(t);return r||(r=new Set,e.set(t,r)),r}static readBuiltInConfigText(){if(this.builtInConfigTextLoader)return this.builtInConfigTextLoader();let e=Xe.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(Pi.existsSync(e))return Pi.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=ZN(e);if(t.includes("dist")){let s=Xe.dirname(t),a=Xe.dirname(s);return Xe.join(a,"src","resources")}let r=Xe.dirname(t),i=Xe.dirname(r),o=Xe.dirname(i);return Xe.join(o,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let r;try{r=this.readBuiltInConfigText()}catch{Ei("read builtin acl permission failed.");return}if(r!==void 0)try{let i=JSON.parse(r),s=(Array.isArray(i)?i:Cc(i)?Object.values(i):[]).filter(Cc).map(a=>new kc(a));s.forEach(a=>{let c=a.permissionInsteadName;QN(c)&&(a.permissionInsteadName=Pc(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(i){Ei(`failed to parse aclPermissionsInfo.json: ${i}`)}}static initAclPermissionFromSDK(e,t,r){let i=this.parsePermissionDefinitionFile(e);i&&i.forEach(o=>{if(!Cc(o))return;let s=o,a=$u(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(Sw(a)||(this.generateAclInfos(r,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||$u(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||$u(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:eM(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let i=new kc;i.permissionName=t;let o=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;i.permissionDisplayName=o;let s=tM(r,this.ACL_SINCE_KEY);i.minSupportApiLevel=String(s),this.handleInsteadName(i,o),e.add(i)}static parsePermissionDefinitionFile(e){let t=Xe.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!Pi.existsSync(t))return;let r;try{r=Pi.readFileSync(t,"utf-8")}catch(s){Ei(`failed to load permissionDefinitions.json: ${s}`);return}let i;try{let s=JSON.parse(r);if(!Cc(s)){Ei("json object is null");return}i=s}catch(s){Ei(`failed to parse permissionDefinitions.json: ${s}`);return}let o=i[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(o)){Ei("definePermissions is not an array");return}return o}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=Pc(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=Pc(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function Dc(n,e){let t=new Set,r=new Set;Ur.handleSpecificAclPermissions(),Ur.initAclPermission(n,e);for(let i of n.profile.modules){let o=Ew(i,n,e,r,Ic.join("src","main"));for(let a of o)t.add(a);let s=Ew(i,n,e,r,Ic.join("src","ohosTest"));for(let a of s)t.add(a)}return nM(r),t}function nM(n){if(n.size>0)throw new Error(ww.DUPLICATE_PERMISSION)}function Ew(n,e,t,r,i){let o=oM(e.rootDir,n,i);if(o==null)return new Set;let s=[];for(let y of o){if(typeof y!="object"||y===null)continue;let I=iM(y,"name");I&&s.push(I)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=Ic.join(t.sdkPath,"default","sdk-pkg.json"),l=Ec(c),d=Ur.getAclPermissionInfos(e),g=new Set(Array.from(d).filter(y=>{let I=Number(y.minSupportApiLevel);return Number.isFinite(I)&&I<=l}).map(y=>y.permissionName));for(let y of Array.from(a))g.has(y)||a.delete(y);return a}function iM(n,e){let t=n[e];return typeof t=="string"?t:""}function oM(n,e,t){let r=Ic.join(n,e.srcPath,t,"module.json5"),i=sM(r);if(i==null)return null;let o=aM(i,"module");return o==null?null:cM(o,"requestPermissions")}function sM(n){try{if(!bw.existsSync(n))return null;let e=bw.readFileSync(n,"utf-8");return rM.parse(e)}catch{return null}}function aM(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return t!=null&&typeof t=="object"&&!Array.isArray(t)?t:null}function cM(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}var Hu=class{verifyStorePassword(e,t){try{let r=Br.readFileSync(e),i=Cw.asn1.fromDer(r.toString("binary"));return Cw.pkcs12.pkcs12FromAsn1(i,t),!0}catch{return!1}}getLocalCerFingerprints(e){let r=Br.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(r&&r.length>0)return r.map(i=>this.formatFp(new Ac.X509Certificate(i).fingerprint256));try{return[this.formatFp(new Ac.X509Certificate(Br.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let i=Br.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let o of i)try{let s=new Ac.X509Certificate(o);if(this.formatFp(s.fingerprint256)===t){let a=new Date(s.validTo);return isNaN(a.getTime())?null:a}}catch{}return null}formatFp(e){let t=e.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}};function dM(n){let e=Br.readFileSync(n,"utf-8"),t=uM(e),r=null;if(t)try{r=JSON.parse(t)}catch{r=null}let i=r?.["bundle-info"]??{};return{rawContent:e,bundleNameInProfile:ju(i["bundle-name"]),expiryDate:pM(r?.validity?.["not-after"]),cerFingerprintInProfile:mM(ju(i["development-certificate"])),deviceUdidsInProfile:fM(r?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:hM(r?.acls?.["allowed-acls"]),teamIdInProfile:ju(i["developer-id"])}}function uM(n){let e=n.indexOf("{");if(e<0)return null;let t=0,r=-1,i=!1,o=!1;for(let s=e;s<n.length;s++){let a=n[s];if(i){o?o=!1:a==="\\"?o=!0:a==='"'&&(i=!1);continue}if(a==='"')i=!0;else if(a==="{")t++;else if(a==="}"&&(t--,t===0)){r=s;break}}return r<0?null:n.slice(e,r+1)}function pM(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function mM(n){if(!n)return null;try{let t=new Ac.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function fM(n){if(!Array.isArray(n))return[];let e=[];for(let t of n)if(typeof t=="string"){let r=t.toUpperCase();e.includes(r)||e.push(r)}return e}function hM(n){if(!Array.isArray(n))return[];let e=[];for(let t of n)typeof t=="string"?e.push(t):t&&typeof t=="object"&&typeof t.name=="string"&&e.push(t.name);return[...new Set(e)].sort()}function ju(n){return typeof n=="string"?n:null}var Ho=class n{static async shouldRegenerate(e,t){let r=await n.#e(e,t);return n.#t(r)??n.#r(r)??n.#n(r)??n.#i(r)??n.#o(r)??n.#s(r)??n.#a(r)??n.#c(r)??n.#l(r)??n.#d(r)??await n.#u(r)??n.#p()}static async#e(e,t){let r=e.force,i=e.teamId,o=e.productName??"default",s=q.discover(process.cwd()),a=s.rootDir,[c,l]=await Promise.all([gM(o,a),vM(t.hdcPath)]),d=null;if(kw(c).allExist)try{d=dM(c.profileFile)}catch{}return{force:r,teamId:i,productName:o,projectPath:a,materialPaths:c,bundleName:s.getBundleName(o),deviceUdids:l,storePassword:await yM(a,o,c.storeFile),localAclPermissions:[...Dc(s,t)].sort(),hapSignTool:new Hu,profileInfo:d}}static#t(e){return e.force?(p("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:st({force:!0})}):null}static#r(e){let t=kw(e.materialPaths);return t.allExist?null:(p(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:st({allFilesExist:!1,missingFiles:t.missing})})}static#n(e){return(e.profileInfo?.rawContent??"").trim().length>0?null:(p("[reGenerateSign] profile content is empty"),{shouldRegenerate:!0,reason:"Profile file content is empty",checkDetails:st({allFilesExist:!0,profileContentNotEmpty:!1})})}static#i(e){let t=e.profileInfo?.expiryDate;return!t||t>=new Date?null:(p(`[reGenerateSign] profile expired at ${t.toISOString()}`),{shouldRegenerate:!0,reason:`Profile expired at ${t.toISOString()}`,checkDetails:st({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!1})})}static#o(e){let t=e.profileInfo?.bundleNameInProfile;return t&&t===e.bundleName?null:(p(`[reGenerateSign] bundleName mismatch \u2014 current=${e.bundleName}, profile=${t}`),{shouldRegenerate:!0,reason:`bundleName mismatch: current=${e.bundleName}, in profile=${t}`,checkDetails:st({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!1})})}static#s(e){let t=e.profileInfo?.teamIdInProfile;return t&&t===e.teamId?null:(p(`[reGenerateSign] teamId mismatch \u2014 current=${e.teamId}, profile=${t}`),{shouldRegenerate:!0,reason:`teamId mismatch: current=${e.teamId}, in profile=${t}`,checkDetails:st({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=SM(e.profileInfo?.deviceUdidsInProfile??[],e.deviceUdids);return t.allPresent?null:(p(`[reGenerateSign] missing device UDIDs: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Device UDID(s) not in profile: ${t.missing.join(", ")}`,checkDetails:st({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return bM(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(p("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:st({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!1})})}static#l(e){let t=e.hapSignTool.getLocalCerFingerprints(e.materialPaths.cerFile),r=e.profileInfo?.cerFingerprintInProfile;return r&&t.includes(r)?null:(p("[reGenerateSign] certificate mismatch"),{shouldRegenerate:!0,reason:"Certificate mismatch between profile and local .cer file",checkDetails:st({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!1})})}static#d(e){let t=e.profileInfo?.cerFingerprintInProfile,r=e.hapSignTool.getLocalCerExpiry(e.materialPaths.cerFile,t);return!r||r>=new Date?null:(p(`[reGenerateSign] local certificate expired at ${r.toISOString()}`),{shouldRegenerate:!0,reason:`Local certificate expired at ${r.toISOString()}`,checkDetails:st({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!1})})}static async#u(e){return e.storePassword?e.hapSignTool.verifyStorePassword(e.materialPaths.storeFile,e.storePassword)?null:(p("[reGenerateSign] keystore password verification failed"),{shouldRegenerate:!0,reason:"Keystore password verification failed (storeFile may be corrupted or password changed)",checkDetails:st({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})}):(p("[reGenerateSign] no stored keystore password"),{shouldRegenerate:!0,reason:"No stored keystore password available for verification",checkDetails:st({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})})}static#p(){return p("[reGenerateSign] all checks passed \u2014 skip regeneration"),{shouldRegenerate:!1,reason:"",checkDetails:st({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function gM(n,e){let[t,r,i,o]=await Promise.all([Te(n,e,"p12"),Te(n,e,"csr"),Te(n,e,"cer"),Te(n,e,"p7b")]);return{storeFile:t,csrFile:r,cerFile:i,profileFile:o}}async function yM(n,e,t){let r=Iw.join(n,"build-profile.json5");if(!Br.existsSync(r))return;let i;try{i=lM.parse(Br.readFileSync(r,"utf-8"))}catch{return}let a=(i?.app?.signingConfigs??[]).find(c=>c.name===e)?.material?.storePassword;if(a)try{return await Hr.decryptPassword(a,t)}catch{return}}async function vM(n){p(`Executing: ${n} list targets`);let{stdout:e}=await Pw(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
|
|
1371
|
+
`)){let o=i.trim();if(!o||o.startsWith("[Empty]"))continue;let s=o.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let r=[];for(let i of t)try{p(`Executing: ${n} -t ${i} shell bm get -u`);let{stdout:o}=await Pw(n,["-t",i,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),s=wM(o);s&&r.push(s)}catch{p(`[reGenerateSign] Failed to get UDID for ${i}, skipping`)}return r}function wM(n){let e=n.trim();if(!e)return null;let t=e.split(`
|
|
1372
|
+
`);for(let i=0;i<t.length-1;i++)if(t[i].includes("udid of current device is")){let s=t[i+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(s)return s[0].toUpperCase()}let r=e.match(/[A-Fa-f0-9]{64}/);return r?r[0].toUpperCase():null}function kw(n){let e=[n.storeFile,n.csrFile,n.cerFile,n.profileFile],t=[];for(let r of e)Br.existsSync(r)||t.push(r);return{allExist:t.length===0,missing:t}}function SM(n,e){let t=[];for(let r of e)n.includes(r)||t.push(r);return{allPresent:t.length===0,missing:t}}function bM(n,e){let t=[...n].sort(),r=[...e].sort();return t.length!==r.length?!1:t.every((i,o)=>i===r[o])}function st(n){let e={force:!1,allFilesExist:!1,missingFiles:[],profileContentNotEmpty:!1,profileNotExpired:!1,bundleNameMatched:!1,teamIdMatched:!1,allDevicesInProfile:!1,missingDeviceUdids:[],aclMatched:!1,cerMatched:!1,cerNotExpired:!1,storePasswordValid:!1};return n.force?{...e,force:!0}:{...e,...n,force:!1}}import{debuglog as Uu}from"util";import{execa as Bu}from"execa";async function Aw(n,e){let t=await Rc(n);if(!t)throw new Error(P.DEVICE_LIST_EMPTY);let r=await CM(e);if(t.length===0)for(let s of r)await EM(n,s.udid,s.deviceName);else for(let s of r)await PM(n,t,s.udid,s.deviceName);let o=(await Rc(n)).map(s=>s.id);if(o.length===0)throw new Error(P.DEVICE_LIST_EMPTY);return o}async function EM(n,e,t){await xw(n,e,Rw(t))}async function PM(n,e,t,r){for(let i=0;i<e.length;i++){if(t===e[i].udid)return;if(i===e.length-1){await xw(n,t,Rw(r));return}}}function Rw(n){switch(n){case"liteWearable":return"1";case"wearable":return"2";case"tv":return"3";default:return"4"}}async function Dw(n,e=1,t=100){let r=`${me.BASE_URL}${me.DEVICE_LIST_PATH}?encodeFlag=0&start=${e}&pageSize=${t}`,i=Lw(n),o=await N.get(r,{headers:i});if(!o)throw Uu("query devices failed: response is null"),new Error(P.ERROR_WHILE_ADD_DEVICE);if(o.statusCode!==200)throw Tw(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.list)throw Uu("query devices failed: response list is null"),new Error(s.ret?.msg||P.ERROR_WHILE_ADD_DEVICE);return{deviceList:s.list,total:s.totalCount||0}}function Tw(n,e,t){return n===At.FORBIDDEN?e===Pe.OPENPROXY_BLOCKED_URL?new Error(P.ERR_CERT_NETWORK_ERROR):new Error(P.ERR_FORBIDDEN):n===At.UNAUTHORIZED?new Error(P.ERR_UNAUTHORIZED):t.includes(Pe.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(P.DEVICE_LIMIT_REACHED):new Error(P.ERROR_WHILE_ADD_DEVICE)}async function Rc(n){let t=await Dw(n,1,100);if(!t||!t.deviceList||t.deviceList.length===0)return[];let r=[...t.deviceList],i=t.total,o=Math.floor(i/100)+(i%100===0?0:1);for(let s=2;s<=o;s++){let a=await Dw(n,s,100);if(!a||!a.deviceList||a.deviceList.length===0)break;r.push(...a.deviceList)}return r}async function xw(n,e,t){let r=`${me.BASE_URL}${me.DEVICE_ADD_PATH}`,i=Lw(n),s={deviceName:`auto_sign_device_No.${Math.floor(Math.random()*3e3)}${Date.now()}`,udid:e,deviceType:t},a=await N.postAllowFailure(r,{headers:i,params:s});if(!a)throw Uu("add device failed: response is null"),new Error(P.ERROR_WHILE_ADD_DEVICE);if(a.statusCode!==200)throw Tw(a.statusCode,a.statusText,a.data);let c=a.data,l=JSON.parse(a.data);if(!l||!l.ret||l.ret.code!==0)throw c.includes(Pe.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(P.DEVICE_LIMIT_REACHED):c.includes(Pe.DEVICE_NAME_REPEAT_CODE)?new Error(P.DEVICE_NAME_REPEAT):new Error(P.ERROR_WHILE_ADD_DEVICE)}function Lw(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}async function CM(n){let{stdout:e}=await Bu(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
|
|
1373
|
+
`)){let o=i.trim();if(!o||o.startsWith("[Empty]"))continue;let s=o.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let r=[];for(let i of t)try{let o=await kM(i,n),s=await IM(i,n);o.length>0&&r.push({id:"",udid:o,deviceName:s})}catch{p(`Failed to get device info for ${i}, skipping`)}return r}async function kM(n,e){let{stdout:t}=await Bu(e,["-t",n,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),r=t.trim();if(!r)return"";let i=r.split(`
|
|
1374
|
+
`);for(let s=0;s<i.length-1;s++)if(i[s].includes("udid of current device is")){let c=i[s+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(c)return c[0].toUpperCase()}let o=r.match(/[A-Fa-f0-9]{64}/);return o?o[0].toUpperCase():""}async function IM(n,e){let{stdout:t}=await Bu(e,["-c","-t",n,"shell","getprop","hw_sc.build.os.deviceType"],{stdio:["ignore","pipe","pipe"]});return DM(t)}function DM(n){let e=n.trim();return!e||e.includes("inaccessible")?"phone":n.includes("liteWearable")?"liteWearable":n.includes("wearable")?"wearable":n.includes("tv")?"tv":"phone"}import Sn from"fs";import{createHash as AM}from"crypto";import{debuglog as cr}from"util";import{Buffer as Mw}from"buffer";import{createPublicKey as RM,X509Certificate as Wu}from"crypto";import{readFileSync as TM}from"fs";import bn from"node-forge";async function Ow(n,e){console.log("Start generating profile");let{productName:t,bundleName:r,projectPath:i,aclPermissionList:o,allDeviceIds:s,certIds:a,keyAlias:c,keyPwd:l}=e;if(s==null||s.length===0)throw new Error(P.DEVICE_LIST_EMPTY);let d=`${me.BASE_URL}${me.PROVISION_ADD_TEST_PATH}`,g=xM(t,r),y=await NM(n,d,a||[],r,s,g,o||[]);if(!y||!y.profileInfo||!y.profileInfo.provisionFileUrl)throw cr("add provision failed, the provision file url is null"),new Error(P.ADD_PROFILE_FAIL);let I=y.profileInfo,G=(await FM(n,I.provisionFileUrl)).urlList,xe=y.profileInfo.id;if(G&&G.length>0){let at=await uw(t,i),xt=at.profilePath;if(!await $M(G,xt))throw await Nw(n,xe),new Error(P.ERROR_WHILE_DOWNLOAD_PROFILE);if(await Nw(n,xe),Sn.existsSync(at.certPath)&&Sn.existsSync(xt)&&Sn.existsSync(at.p12Path)){let _c=Sn.readFileSync(at.certPath,"utf8"),Fc=Sn.readFileSync(xt,"utf8");return jM(Fc,_c,at.p12Path,c,l)||_M(xt),xt}}throw new Error(P.ADD_PROFILE_FAIL)}function xM(n,e){let t=n?`${n}_`:"";return`${LM(`${t}${e}_${e}`)}`}function LM(n){return AM("sha256").update(n).digest("hex").substring(0,16)}async function NM(n,e,t,r,i,o,s){MM(r);let a=Gu(n),c={certList:t,packageName:r,deviceList:i,provisionName:o};s.length&&(c.aclPermissionList=s);let l=await N.postAllowFailure(e,{headers:a,params:c});if(!l)throw cr("add provision failed: response is null"),new Error(P.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw Vu(l.statusCode,l.statusText,l.data);let d=JSON.parse(l.data);if(!d||!d.ret||d.ret.code!==0)throw cr(`add provision fail: ${l.data}`),OM(l.data,o),new Error(d.ret?.msg||P.ADD_PROFILE_FAIL);let g=d.provisionFileUrl;return{profileInfo:{id:d.id,name:o,provisionFileUrl:g}}}function Vu(n,e,t){return n===At.FORBIDDEN?e===Pe.OPENPROXY_BLOCKED_URL?new Error(P.ERR_CERT_NETWORK_ERROR):new Error(P.ERR_FORBIDDEN):n===At.UNAUTHORIZED?new Error(P.ERR_UNAUTHORIZED):t.includes(Pe.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(P.TEST_PROVISION_EXCEEDS_LIMIT):new Error(P.ADD_PROFILE_FAIL)}function MM(n){if(!n||n.trim().length===0)throw new Error(P.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!Ke.BUNDLE_NAME_REGEX.test(n))throw new Error(P.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function OM(n,e){if(n.includes(Pe.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(P.TEST_PROVISION_EXCEEDS_LIMIT);if(n.includes(Pe.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(P.PROFILE_NAME_REPEAT)}async function Nw(n,e){if(!e||e.trim().length===0)return;let t=`${me.BASE_URL}${me.PROVISION_DELETE_PATH}?id=${e}`,r=await N.deleteAllowFailure(t,{headers:Gu(n)});if(r.statusCode!==200)throw Vu(r.statusCode,r.statusText,r.data);let i=JSON.parse(r.data);(!i||!i.ret||i.ret.code!==0)&&cr(`delete provision failed: ${r.data}`)}function _M(...n){for(let e of n)try{Sn.existsSync(e)&&Sn.unlinkSync(e)}catch(t){cr(`delete local sign file error: ${t.message}`)}}async function FM(n,e){let t=`${me.BASE_URL}${me.CERT_DOWNLOAD_URL_PATH}`,r=Gu(n),i={sourceUrls:e},o=await N.postAllowFailure(t,{headers:r,params:i});if(!o)throw cr("get download list failed: response is null"),new Error(P.ADD_PROFILE_FAIL);if(o.statusCode!==200)throw Vu(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw cr("download: The application does not exist"),new Error(s.ret?.msg||P.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function $M(n,e){if(!n||n.length===0)return!1;let t=n[0];return await Fo(t.newUrl,e,t.sha256),!0}function jM(n,e,t,r,i){return HM(n,e),r=r||Ke.TARGET_FRIENDLY_NAME,i=i||"",UM(e,t,r,i),!0}function HM(n,e){if(e.lastIndexOf(Ke.CERT_BEGIN_HEADER)<0)throw new Error(P.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(Ke.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!n.includes(t))throw new Error(P.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}function UM(n,e,t,r){let i=n.matchAll(Ke.CERTIFICATE_PATTERN_GLOBAL),o=[],s=new Date;for(let c of i)try{let l=c[0],d=BM(l),g=new Date(d.validFrom),y=new Date(d.validTo);if(s<g||s>y){let I=`Certificate is not valid, Valid from ${g} to ${y}`;throw console.warn(`checkCertificateInValidityPeriod: ${I}`),new Error(P.CERTIFICATE_HAS_EXPIRED)}o.push(d)}catch(l){throw console.warn(`checkCertificateInValidityPeriod\uFF1A ${l.message}`),new Error(P.CERTIFICATE_HAS_EXPIRED,{cause:l})}if(!o||o.length===0)throw new Error(P.CERTIFICATE_HAS_EXPIRED);if(!VM(e,t,r,o))throw new Error(P.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function BM(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new Wu(t);let r=Mw.from(t,"base64");return new Wu(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}function WM(n){if(n.cert){let e=bn.pki.publicKeyToPem(n.cert.publicKey);return RM(e).export({type:"spki",format:"der"})}if(n.asn1)try{let e=bn.asn1.toDer(n.asn1).getBytes(),t=Mw.from(e,"binary");return new Wu(t).publicKey.export({type:"spki",format:"der"})}catch(e){return cr(`Failed to parse cert from asn1: ${e}`),null}return null}function VM(n,e,t,r){try{let i=TM(n),o=bn.asn1.fromDer(bn.util.createBuffer(i)),c=bn.pkcs12.pkcs12FromAsn1(o,t).getBags({bagType:bn.pki.oids.certBag})[bn.pki.oids.certBag]||[];for(let l of c){let d=l.attributes?.friendlyName?.[0];if(!d||d.toLowerCase()!==e.toLowerCase())continue;let g=WM(l);if(!g)continue;if(r.some(I=>{let ce=I.publicKey.export({type:"spki",format:"der"});return g.equals(ce)}))return!0}return!1}catch(i){let o=i instanceof Error?i.message:String(i);return cr(`Failed to process P12 file: ${n}, error: ${o}`),!1}}function Gu(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var Fw="https://developer.huawei.com",GM={"ohos.permission.SYSTEM_FLOAT_WINDOW":"/consumer/cn/doc/harmonyos-guides/window-pipwindow","ohos.permission.READ_CONTACTS":"/consumer/cn/doc/harmonyos-references/js-apis-contact#contactselectcontacts10","ohos.permission.READ_IMAGEVIDEO":"/consumer/cn/doc/harmonyos-guides/select-user-file#%E9%80%89%E6%8B%A9%E5%9B%BE%E7%89%87%E6%88%96%E8%A7%86%E9%A2%91%E7%B1%BB%E6%96%87%E4%BB%B6","ohos.permission.WRITE_IMAGEVIDEO":"/consumer/cn/doc/harmonyos-guides/savebutton","ohos.permission.READ_AUDIO":"/consumer/cn/doc/harmonyos-guides/select-user-file#%E9%80%89%E6%8B%A9%E9%9F%B3%E9%A2%91%E7%B1%BB%E6%96%87%E4%BB%B6","ohos.permission.WRITE_AUDIO":"/consumer/cn/doc/harmonyos-guides/save-user-file#%E4%BF%9D%E5%AD%98%E9%9F%B3%E9%A2%91%E7%B1%BB%E6%96%87%E4%BB%B6","ohos.permission.READ_PASTEBOARD":"/consumer/cn/doc/harmonyos-guides/pastebutton"},qM="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function zM(n){let e=GM[n];return e?`${Fw}${e}`:void 0}function JM(){return`${Fw}${qM}`}var YM={"acl.can.apply.text":"Permission Application Scenarios","acl.permissions.warn":"Note: You are applying for restricted ACL permissions: {0} These permissions are subject to review together with your app release. For a faster review process, apply for the following permissions instead, if they are sufficient for your purposes: {1} {2}"};function _w(n,e){return(YM[n]??n).replace(/\{(\d+)\}/g,(r,i)=>String(e[Number(i)]??""))}function KM(n){return Array.from(n).join(", ")}function $w(n,e){if(n.size===0)return;let t=Ur.getAclPermissionInfos(e),r=new Set;for(let g of t)n.has(g.permissionName)&&r.add(g);for(let g of r){let y=zM(g.permissionName);y!=null&&(g.permissionHelpUrlKey=y)}let i=new Set;for(let g of r)i.add(g.permissionDisplayName);let o=new Set;for(let g of r)if(g.permissionHelpUrlKey!=null){let y=g.permissionInsteadName??g.permissionDisplayName;o.add(`${y} (${g.permissionHelpUrlKey})`)}let s=JM(),a=_w("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=o.size>0?Array.from(o).join(", ")+".":"",d=_w("acl.permissions.warn",[KM(i),l,c]);console.log(d)}var Tc=class{_project=null;get project(){if(!this._project)throw new Error("Project not initialized. Call checkProjectDir first.");return this._project}checkProjectDir(e){try{return this._project=q.discover(process.cwd()),{passed:!0,message:""}}catch(t){return p(`[EnvCheck] Project.discover() failed: ${t.message}`),e(he.PROJECT_DIR_MISSING)}}checkProduct(e,t){try{return this._project.validateProduct(e),{passed:!0,message:""}}catch(r){return p(`[EnvCheck] Product validation failed: ${r.message}`),t(`Product "${e}" not found.Check the product property in the build-profile.json5 file.`)}}checkBundleName(e,t){try{return this._project.getBundleName(),{passed:!0,message:""}}catch(r){return p(`[EnvCheck] BundleName check failed: ${r.message}`),t(`bundleName was not found under product "${e}".Check the bundleName configuration.`)}}checkAtomicService(){return this._project.isAtomicService()?{passed:!1,message:he.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import XM from"fs";import jw from"path";var xc=class{constructor(e){this.toolProvider=e}checkJava(e){try{return this.toolProvider.assertJava(),{passed:!0,message:""}}catch(t){return p(`[EnvCheck] Java check failed: ${t.message}`),e(`${t.message}`)}}checkHapSignTools(e){let t=this.toolProvider.sdkPath,r=jw.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");if(!XM.existsSync(r)){let i=jw.join("sdk","default","openharmony","toolchains","lib","hap_sign_tools.jar");return e(`hap_sign_tools.jar not found.Check whether ${i} exists.`)}return{passed:!0,message:""}}};var Lc=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await Fe.getUserInfo()}catch(e){return p(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await Fe.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(he.LOGIN_REQUIRED)}catch(t){return p(`[EnvCheck] Login check failed: ${t.message}`),e(he.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(he.TEAM_INFO_FAILED);try{if((await Cr()).teamList.length>0)return{passed:!0,message:""}}catch(r){return p(`[EnvCheck] Team API error: ${r.message}`),e(he.TEAM_INFO_FAILED)}return p("[EnvCheck] No teams found for current user"),e(he.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(he.REALNAME_REQUIRED):t.isRealName!==!0?(p("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(he.REALNAME_REQUIRED)):{passed:!0,message:""}:e(he.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let r=e??"";try{let i=await Cr();if(r=e??(i.teamList.length>0?i.teamList[0].id:t.userId)??"",!i.teamList.some(s=>s.id===r)){let s=`team-id for ${r} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`;return p(`[EnvCheck] ${s}`),{passed:!1,message:s}}return{passed:!0,message:""}}catch(i){return p(`[EnvCheck] Team ID check failed: ${i.message}`),{passed:!1,message:`team-id for ${r} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`}}}async checkRegion(e){let t=await this.ensureUserInfo();return t?t.countryCode?t.countryCode!=="CN"?e(he.REGION_CHINA_ONLY):{passed:!0,message:""}:(p("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(he.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function ZM(n){try{let{teamList:e}=await Cr();if(e.length>0)return e[0].id}catch(e){p(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function QM(n){let e=await Fe.getUserInfo(),t=await Fe.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await ZM(e.userId);if(!r)throw new Error("No team found");let i={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await Rc(i)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var Nc=class{constructor(e){this.toolProvider=e}async checkDevice(e,t){try{let r=await QM(t);if(r.length>0)return p(`[EnvCheck] Scenario 4 Device check: ${r.length} device(s) found in AGC cloud, skipping local device check`),{passed:!0,message:""};p("[EnvCheck] Scenario 4 Device check: no cloud devices found, falling back to local hdc");let o=await ne.from(this.toolProvider).listDevices();return o.length===0?(p("[EnvCheck] Scenario 4 Device check: no local devices found"),e(he.DEVICE_MISSING)):o.some(a=>Ot(a.serial))?{passed:!0,message:""}:(p("[EnvCheck] Scenario 4 Device check: local device found but not an emulator"),e(he.DEVICE_MISSING))}catch(r){return p(`[EnvCheck] Scenario 4 Device check failed: ${r.message}`),e(he.DEVICE_DETECT_FAILED)}}};var Mc=class{projectChecker=new Tc;toolchainChecker=null;authChecker=new Lc;deviceChecker=null;constructor(){}async preflight(e){let t=r=>this.blockingFail(r);return!(!await this.runAuthChain(e,t)||!await this.initToolchain()||!await this.runDeviceCheck(e,t)||!await this.runProjectChecks(e,t)||!await this.runAuxChecks(e))}async runAuthChain(e,t){let r=o=>(o.passed||this.fail(o),!0),i=[()=>this.authChecker.checkLogin(t),()=>this.authChecker.checkRealname(t),()=>this.authChecker.checkTeamInfo(t)];for(let o of i)if(!r(await o()))return!1;return!(e.teamId&&!r(await this.authChecker.checkTeamId(e.teamId)))}async initToolchain(){try{let e=await C.new();return this.toolchainChecker=new xc(e),this.deviceChecker=new Nc(e),!0}catch(e){throw p(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(he.TOOLCHAIN_INIT_FAILED,{cause:e})}}async runDeviceCheck(e,t){return(i=>i.passed?!0:(this.fail(i),!1))(await this.deviceChecker.checkDevice(t,e.teamId))}async runProjectChecks(e,t){let r=o=>o.passed?!0:(this.fail(o),!1);if(!r(this.projectChecker.checkProjectDir(t))||!r(this.projectChecker.checkAtomicService()))return!1;let i=[()=>this.projectChecker.checkProduct(e.productName,t),()=>this.projectChecker.checkBundleName(e.productName,t),()=>this.toolchainChecker.checkJava(t),()=>this.toolchainChecker.checkHapSignTools(t)];for(let o of i)if(!r(o()))return!1;return!0}async runAuxChecks(e){let t=r=>r.passed?!0:(this.fail(r),!1);return!e.teamId&&!t(await this.authChecker.checkTeamId(e.teamId))?!1:(await this.authChecker.checkRegion(r=>this.blockingFail(r)),!0)}blockingFail(e){return{passed:!1,message:e}}fail(e){throw p(`[EnvCheck] FAIL: ${e.message}`),new Error(e.message)}};var Hw=5*1024*1024;function rO(n){try{let e=zu.statSync(n);if(e.size>Hw)throw new Error(`Profile file too large: ${e.size} bytes (max ${Hw} bytes): ${n}`);let t=zu.readFileSync(n,"utf-8");return Bw.parse(t)}catch(e){if(e.code==="ENOENT")return{app:{signingConfigs:[],products:[]}};throw new Error(`Failed to read profile: ${n}`,{cause:e})}}function nO(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function iO(n){if(n.keyPwd===n.storePassword){let r=await Hr.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await Hr.encryptedPassword(n.keyPwd,n.p12FilePath),t=await Hr.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function oO(n,e,t){let r=Uw.join(n,"build-profile.json5"),i=rO(r);nO(i);let o=t??"default",{keyPassword:s,storePassword:a}=await iO(e),c={name:o,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:s,profile:e.profileFilePath,signAlg:Rt.signAlg,storeFile:e.p12FilePath,storePassword:a}},l=i.app?.signingConfigs?.findIndex(g=>g.name===o);l!==void 0&&l>=0?i.app.signingConfigs[l]=c:i.app.signingConfigs.push(c);let d=i.app?.products?.findIndex(g=>g.name===o);d!==void 0&&d>=0?i.app.products[d].signingConfig=o:i.app.products.push({name:o,signingConfig:o}),zu.writeFileSync(r,Bw.stringify(i,null,2),"utf-8")}async function sO(n){let e=await Fe.getUserInfo(),t=await Fe.refreshToken();if(!e||!t)throw new Error("Failed to obtain login credentials. Run `devecocli auth login` again.");return{uid:e.userId??"",teamId:n.teamId??e.userId??"",accessToken:t.accessToken??""}}async function aO(n){let e=n.product||"default";await new Mc().preflight({productName:e,teamId:n.teamId}),console.log("Executing signature generate command");let r=await sO(n),i=await C.new(),{shouldRegenerate:o}=await Ho.shouldRegenerate({force:n.force??!1,teamId:r.teamId,productName:n.product},i);if(!o){console.log(qu("Signature generation completed successfully."));return}await cO(n,r,i),console.log(qu("Signature generation completed successfully."))}async function cO(n,e,t){let r=await Nu(e,n.product),i=lO(n,e,r,t);i.allDeviceIds=await Aw(e,t.hdcPath),await Ow(e,i);let o=q.discover(process.cwd()).rootDir;await oO(o,r,n.product??"default"),console.log(qu(`Signing config written to ${Uw.join(o,"build-profile.json5")}`))}function lO(n,e,t,r){let i=process.cwd(),o=q.discover(i),s=Dc(o,r);return $w(s,o),{productName:n.product||"default",bundleName:o.getBundleName(n.product||"default"),projectPath:o.rootDir,teamId:e.teamId,force:n.force||!1,aclPermissionList:[...s],certIds:[t.certId],keyAlias:t.keyAlias,keyPwd:t.keyPwd}}var Ww=new eO("signature").description("Generate application signature.");Ww.command("generate").description("Automatically generate signing materials and write them to the project configuration.").option("--force","Force overwrite existing local signing materials.").option("--team-id <team-id>","Specify the team ID to use.").option("--product <product>","Specify the product. The default value is default.").action(async n=>{let e={event:b.CommandExecuted,args:["signature","generate",...n.force?["--force"]:[],...n.teamId?["--team-id"]:[],...n.product?["--product"]:[]]},t=Date.now(),r=!0,i=null;try{await aO(n)}catch(o){r=!1,i=B(o),console.error(tO(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await k.track(e,o)}});var Vw=Ww;if(!je())try{k.init(Oc.join(de(),"TraceLogData")),k.startScheduler()}catch(n){h.error(`[telemetry] init failed: ${n instanceof Error?n.message:String(n)}`)}(async()=>{if(!je())try{let n=await C.new();k.setSourceType(n.sourceType);let e=n.readVersion();e&&(n.sourceType==="clt"?k.setCltVersion(e):k.setStudioVersion(e))}catch(n){h.error(`[telemetry] toolchain info failed: ${n instanceof Error?n.message:String(n)}`)}})();ae.name("devecocli").description(`HarmonyOS application development command line tool
|
|
1371
1375
|
|
|
1372
|
-
Privacy: ${
|
|
1376
|
+
Privacy: ${ki.PRIVACY_URL}`).version("1.3.5-Test.2");var Gw=ae.options.find(n=>n.long==="--version");Gw&&(Gw.flags="-V, -v, --version");ae.addCommand(pm);ae.addCommand(Jf);ae.addCommand(ih);ae.addCommand(Ch);ae.addCommand(Kh);ae.addCommand(Ig);ae.addCommand(Xg);ae.addCommand(ey);ae.addCommand(py);ae.addCommand(by);ae.addCommand(Zy);ae.addCommand(iv);ae.addCommand(bv);ae.addCommand(nw);ae.addCommand(Vw);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 Ju=process.argv.slice(2);Ju.length>=2&&Ju[Ju.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);function uO(n){let e=n;for(;e.parent&&e.parent!==ae;)e=e.parent;return e}var pO=new Set(["update","auth","serve"]);ae.hook("preAction",async(n,e)=>{await Vg().catch(()=>{});let t=uO(e),r=Un();if(t.name()==="update"||t.name()==="docs"&&e.name()==="update")return;let i=new Sr(Oc.join(de(),"update")),o=mt();if(r==="off"&&i.getBlockedVersions().includes(o))throw new Error(`devecocli ${o} has been disabled, run \`devecocli update\` to upgrade`);process.env.DEVECO_CLI_SKIP_VERSION_CHECK||pO.has(t.name())||await C.checkVersion()});function mO(n){if(n.name()!=="status"||n.opts().format!=="json")return!1;let t=n.parent;for(;t&&t!==ae;){if(t.name()==="screenrecord")return!0;t=t.parent}return!1}ae.hook("postAction",async(n,e)=>{if(process.exitCode||Un()!=="off"||mO(e))return;await new Qi(e).checkAndNotify()});ae.parseAsync(process.argv).finally(()=>{k.stopScheduler();try{Zc(Oc.join(de(),"TraceLogData"))}catch(n){h.error(`[telemetry] background upload spawn check failed: ${n instanceof Error?n.message:String(n)}`)}}).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(dO(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
|