@deveco-test/deveco-cli-openharmony-arm64 1.3.12-Test.1 → 1.3.12-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.
@@ -1,6 +1,6 @@
1
- import*as x from"fs";import*as Y from"path";import ki from"proper-lockfile";import Fi from"ora";import*as b from"fs";import*as st from"path";var Lt=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],lt={"harmonyos-guides":"\u5F00\u53D1\u6307\u5357","harmonyos-references":"API\u53C2\u8003","best-practices":"\u6700\u4F73\u5B9E\u8DF5","harmonyos-faqs":"FAQ","harmonyos-releases":"\u7248\u672C\u8BF4\u660E","harmonyos-roadmap":"\u53D8\u66F4\u9884\u544A"};var v="1.9.1",Yi=48*1024*1024,De=280,Ie=6,Te=100,we=3,Ce=28,Bt=10,Ne=/API参考|APIReference/i;var Re=6,dt=700,Mt=250,kt=400,Pe=1320,Oe=120,Le=450,Be=250,Me=500,ke=480,Fe=80,ve=200,ze=60,He=200,je=40,Ze=200,Ue=200,$e=40,z=500,Ge=Object.fromEntries(Lt.map((t,e)=>[lt[t],e])),N=Object.fromEntries(Lt.map((t,e)=>[t,e]));import*as K from"fs";import*as m from"path";import{fileURLToPath as Ve}from"url";import*as R from"fs";import*as Qe from"path";import{homedir as yr}from"os";import*as We from"fs";import*as y from"path";function Ft(t,e){let n=y.relative(e,t);return n===""||!y.isAbsolute(n)&&!n.startsWith(`..${y.sep}`)&&n!==".."}function H(t){let e=y.resolve(t),n=[],r=e;for(;;)try{let o=We.realpathSync(r);return n.length===0?o:y.join(o,...n.reverse())}catch(o){if(o.code!=="ENOENT")throw o;let i=y.dirname(r);if(i===r)return e;n.push(y.basename(r)),r=i}}function Xe(t,e){let n=H(e),r=H(t);return Ft(r,n)?r:null}function vt(t){let e=t.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function qe(t){let e=vt(t);if(!e)throw new Error("Path must not be empty.");return H(e)}var xr="deveco-cli",zt,B=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function Je(){let t=process.env.DEVECO_CLI_DATA_DIR,n=(t===void 0||t===""?"":vt(t))||Qe.join(yr(),".local","share",xr);try{return qe(n)}catch(r){throw new B(r instanceof Error?r.message:String(r))}}async function Ye(){let t=Je();await R.promises.mkdir(t,{recursive:!0});let e;try{e=await R.promises.realpath(t)}catch(r){throw new B(`DEVECO_CLI_DATA_DIR is not usable: ${r instanceof Error?r.message:String(r)}`)}if(!(await R.promises.stat(e)).isDirectory())throw new B("DEVECO_CLI_DATA_DIR must be a writable directory.");return zt=e,e}function V(){if(zt!==void 0)return zt;let t=Je();try{if(R.existsSync(t))return R.realpathSync(t)}catch{}return t}var Er="docs";function j(){return m.join(V(),Er)}function g(){return m.join(j(),".index")}function mt(){return m.join(g(),"build.lock")}function tt(){return m.join(g(),"build-status.json")}function Z(){return m.join(g(),"build-meta.json")}function U(){return m.join(g(),"search.db")}function et(){return m.join(g(),"sqlite-backend.json")}function nt(){return m.join(g(),"jieba-backend.json")}function I(){return m.join(g(),".tmp")}function _r(){return m.join(V(),"logs")}function Ht(){return m.join(_r(),"doc-init.log")}function br(t,e){let n=e;for(;!n.endsWith(`${m.sep}dist`)&&n!==m.dirname(n);)n=m.dirname(n);return n}function Ke(t,e){return m.dirname(br(t,e))}function tn(){let t=Ve(import.meta.url),e=m.dirname(t);return t.includes(`${m.sep}dist${m.sep}`)?Ke(t,e):m.join(e,"..","..","..")}function Ar(...t){let e=Ve(import.meta.url),n=m.dirname(e);return e.includes(`${m.sep}dist${m.sep}`)?[m.join(Ke(e,n),...t)]:[m.join(n,"..","..","..",...t)]}function en(...t){let e=tn(),n=K.realpathSync(e);for(let r of Ar(...t))try{let o=K.lstatSync(r);if(o.isSymbolicLink()||!o.isFile())throw new Error(`Unsafe documentation package asset: ${t.join("/")} must be a regular file.`);let i=K.realpathSync(r);if(!Ft(i,n))throw new Error(`Unsafe documentation package asset: ${t.join("/")} is outside the package.`);return i}catch(o){if(o.code!=="ENOENT")throw o}return null}function M(){return en("docs.zip")}function jt(){return en("index.zip")}function nn(){return m.join(tn(),"index","data")}import*as T from"fs";import*as k from"path";var w=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],Zt=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};var Ut=null;function $t(t){Ut=t}function rn(){if(Ut)return Ut;let t=g();if(w.every(o=>T.existsSync(k.join(t,o))))return t;let n=nn();if(w.every(o=>T.existsSync(k.join(n,o))))return n;throw new Zt("Lexicon files not found. Install the documentation index first (index.zip).")}function $(t){let e=k.join(rn(),t);return T.readFileSync(e,"utf-8")}function on(t,e){return T.readFileSync(k.join(e,t),"utf-8")}async function sn(t,e=rn()){await T.promises.mkdir(t,{recursive:!0});for(let n of w){let r=k.join(e,n),o=k.join(t,n);await T.promises.copyFile(r,o)}}import*as Gt from"fs";import*as Dr from"yauzl";function Wt(){let t=M();return t!==null&&Gt.existsSync(t)}import*as S from"fs";import*as C from"path";import an from"adm-zip";import*as rt from"fs";import*as pt from"path";var ft=class extends Error{constructor(e){super(`Unsafe documentation path: ${e}`),this.name="DocPathSafetyError"}};function Qt(t){return t instanceof B||t instanceof ft||t instanceof Error&&(t.name==="CliDataDirError"||t.name==="DocPathSafetyError")}function Jt(t){return new ft(t)}function Ir(){return H(V())}function qt(t,e,n){let r=Xe(t,e);if(r===null)throw Jt(`${n} resolves outside the data directory.`);return r}async function Xt(t,e){await rt.promises.mkdir(t,{recursive:!0});let n=qt(t,e,"directory");if(!(await rt.promises.stat(n)).isDirectory())throw Jt("path must be a directory.")}function ot(t){let e=Ir();try{let n=qt(t,e,"file");if(!rt.statSync(n).isFile())throw Jt("path must be a regular file.")}catch(n){if(n.code==="ENOENT"){qt(pt.dirname(t),e,"file parent");return}throw n}}async function it(t={}){let e=t.mode??"write",n=await Ye();await Xt(j(),n),await Xt(g(),n),e==="write"&&await Xt(I(),n);for(let r of[U(),Z(),tt(),mt(),nt(),et(),...w.map(o=>pt.join(g(),o))])ot(r)}var Yt=["search.db","build-meta.json",...w],Tr=["corpus.json","corpus-offsets.json","orama.dpack"];async function wr(t){for(let e of Tr)await S.promises.rm(C.join(t,e),{force:!0})}async function Cr(t){let e=await S.promises.readdir(t,{withFileTypes:!0});for(let n of e)n.name!==".index"&&await S.promises.rm(C.join(t,n.name),{recursive:!0,force:!0})}function cn(t){let n=new an(t).getEntry("build-meta.json");if(!n)throw new Error("index.zip is missing build-meta.json");return JSON.parse(n.getData().toString("utf-8"))}async function Nr(t){let e=g();await S.promises.mkdir(e,{recursive:!0});for(let n of Yt){let r=C.join(e,n);await S.promises.rm(r,{force:!0}),await S.promises.rename(C.join(t,n),r)}await wr(e),await S.promises.rm(I(),{recursive:!0,force:!0})}function un(t){let e=jt();if(!e)return!1;try{let n=cn(e);return n.indexVersion===v&&n.docsZipSha256===t&&n.segmentCount>0}catch{return!1}}async function ln(t){await it({mode:"write"});let e=jt();if(!e)throw new Error("index.zip not found");let n=cn(e);if(n.docsZipSha256!==t)throw new Error("Bundled index.zip does not match docs.zip. Rebuild index.zip with npm run build:index.");if(n.segmentCount<=0)throw new Error("Bundled index.zip is empty");let r=I();await S.promises.rm(r,{recursive:!0,force:!0}),await S.promises.mkdir(r,{recursive:!0});let o=new an(e);for(let s of Yt){let a=o.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await S.promises.writeFile(C.join(r,s),a.getData())}let i=JSON.parse(await S.promises.readFile(C.join(r,"build-meta.json"),"utf-8"));if(!S.existsSync(C.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await Nr(r),await S.promises.mkdir(j(),{recursive:!0}),await Cr(j()),i}async function dn(){await S.promises.rm(I(),{recursive:!0,force:!0});let t=g();for(let e of Yt)await S.promises.rm(C.join(t,e),{force:!0})}import{createHash as mn}from"crypto";import*as fn from"fs";async function gt(t){return new Promise((e,n)=>{let r=mn("sha256"),o=fn.createReadStream(t);o.on("data",i=>r.update(i)),o.on("error",n),o.on("end",()=>e(r.digest("hex")))})}function pn(t){return mn("sha256").update(t,"utf8").digest("hex")}function gn(t,e){let n=e?on(t,e):$(t);return pn(n)}function ht(t){return gn("harmonyos-synonyms.json",t)}function St(t){return gn("harmonyos-terms.txt",t)}var Rr={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function hn(){try{let t=await b.promises.readFile(tt(),"utf-8");return JSON.parse(t)}catch{return{...Rr}}}async function Vt(t){let e=tt();await b.promises.mkdir(st.dirname(e),{recursive:!0}),await b.promises.writeFile(e,JSON.stringify(t,null,2))}function Sn(t){let e=Date.now();return{state:"extracting",phase:1,phaseLabel:"Extracting documentation",current:0,total:0,message:t,startedAt:e,updatedAt:e,error:null}}async function P(t){let n={...await hn(),...t,updatedAt:Date.now()};return await Vt(n),n}async function Kt(){let t=M();return t?gt(t):null}async function te(){try{let t=await b.promises.readFile(Z(),"utf-8");return JSON.parse(t)}catch{return null}}async function ee(t=!1){if(t)return"no-index";let e=await te();if(!e||e.segmentCount===0)return"no-index";let n=await Kt();return n&&e.docsZipSha256!==n?"docs-changed":e.indexVersion!==v?"engine-upgraded":e.termsHash!==St()?"terms-changed":e.synonymsHash!==ht()?"synonyms-changed":null}function ne(){if(!Wt()||!b.existsSync(U())||!b.existsSync(Z()))return!1;let t=st.dirname(U());if(!w.every(e=>b.existsSync(st.join(t,e))))return!1;try{let e=b.readFileSync(Z(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function yn(t=!1){return t?!0:Wt()?ne()?await ee()!==null:!0:!1}import*as J from"fs";import*as L from"path";import Ti from"adm-zip";var xn=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]);var En=new Set(["a","an","and","api","app","application","arkts","arkui","for","get","harmonyos","how","in","oh","ohos","on","or","set","the","to","use","using","what","when","where","which","with","without","data","file","main","model","name","network","stage","system","type","user"]),_n=new Set(["ability","extension","module","service","context","options","config","info","event","code","state","type","data","request","response","client","server","handler","helper","utils","factory","builder","listener","callback","observer","provider","consumer","delegate","adapter","driver","buffer","stream","channel","session","task","worker","controller","component","container","attribute","descriptor","modifier","validator","parser","formatter","encoder","decoder","filter","converter","generator","iterator","dispatcher","resolver","scanner","tracker","monitor","scheduler","renderer","loader","subscriber","proxy","button","surface","stack","heap","map","set","array","list"]);var Pr=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,Or=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,Lr=/[A-Z][a-zA-Z0-9]{2,}/g,Br=/@[A-Z][a-zA-Z0-9]*/g,Mr=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,bn=6,kr=/^[a-z][a-z0-9]{2,}$/,Fr=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,vr=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,zr=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,Hr=/^[A-Z][a-zA-Z0-9]+$/;function re(t){return vr.test(t)}function jr(t){return zr.test(t)&&t.length>=bn}function Zr(t){return Hr.test(t)}function oe(t){return re(t)||jr(t)||Zr(t)}function Ur(t){let e=t.trim().toLowerCase();return _n.has(e)?!1:xn.has(e)}function $r(t,e){let n=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${t.trim().toLowerCase()}${n}${r}`}function yt(t){let n=t.replace(/^@ohos\./i,"").split(".").filter(Boolean);return n[n.length-1]?.trim()||void 0}function ie(t){return[...t.matchAll(Pr)].map(e=>e[0])}function se(t,e=bn){let n=[];for(let r of t.matchAll(Or))r[0].length>=e&&n.push(r[0]);return n}function G(t){return t.filter(e=>{let n=e.toLowerCase();return!t.some(r=>{if(r===e)return!1;let o=r.toLowerCase();return o.length>n.length&&o.endsWith(n)&&n.length>=4})})}function A(t,e){let n=e.trim();if(!n)return;t.add(n);let r=n.toLowerCase();r!==n&&t.add(r)}function Gr(t){let e=new Set;A(e,t);let n=yt(t);return n&&A(e,n),G([...e])}function ae(t){if(re(t))return Gr(t);let e=new Set;return A(e,t),G([...e])}function ce(t){let e=t.trim();if(/[A-Z]/.test(e))return null;let n=e.match(Fr);if(!n)return null;let r=n[1].toLowerCase(),o=n[2].toLowerCase();if(!kr.test(r)||En.has(r)||!Ur(o))return null;let i=$r(r,o);return{first:r,second:o,camelCase:i,lower:i.toLowerCase()}}function An(t){let e=ce(t.trim());return!e||e.second!=="manager"?null:e}function ue(t,e,n){let r=n.toLowerCase(),o=new RegExp(`@ohos\\.[^\\s(]*${n}`,"i");for(let i of[t,e])if(i&&(i.toLowerCase().includes(r)||o.test(i)))return!0;return!1}function Dn(t){let e=t.trim();if(oe(e))return ae(e);let n=new Set;for(let r of ie(t)){A(n,r);let o=yt(r);o&&A(n,o)}for(let r of se(t))A(n,r);for(let r of t.matchAll(Br))n.add(r[0]);for(let r of t.matchAll(Mr))n.add(r[0]);for(let r of t.matchAll(Lr))r[0].length>=4&&n.add(r[0]);return G([...n])}function In(t){let e=t.trim();if(oe(e))return ae(e);let n=new Set,r=ce(e);r&&A(n,r.camelCase);for(let o of Dn(e))n.add(o);for(let o of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let i=o[0];i!==i.toLowerCase()&&n.add(i)}return G([...n])}var D={pureApiSymbol:/^[A-Z][a-zA-Z0-9]+$/,stageModelExact:/^Stage\s*模型$/i,stageModelEnglishExact:/^stage\s+model$/i,stageModel:/Stage\s*模型/i,stageModelEntryPage:/Stage\s*模型.*EntryAbility.*(页面|新页面)/,declarePermissionBoost:/声明.*权限|应用权限.*声明|如何声明应用权限/,declarePermissionCatalog:/如何声明应用权限/,declarePermissionTokens:/如何声明应用权限|声明应用权限/,uiAbilityLifecycleBoost:/UIAbility.*生命周期|生命周期.*UIAbility|UIAblity/i,uiAbilityLifecycleCatalog:/UIAblity.*生命周期|UIAbility.*生命周期/i,entryAbilityPage:/EntryAbility.*(页面|启动|跳转|新页面)/,stateDecoratorBoost:/@State|@Prop|@Link|@Provide|@Consume/,stateDecoratorCatalog:/@State\s*装饰器|@Prop\s*装饰器|@Link\s*装饰器/,stateManagement:/状态管理原理/,routerRoute:/Router\s+路由/,dialogPopupExact:/^Dialog\s+弹窗$/,dialogPopupBoost:/Dialog\s+弹窗/};function wn(t){return D.pureApiSymbol.test(t.trim())}function Tn(t){let e=t.trim();return D.stageModelExact.test(e)||D.stageModelEnglishExact.test(e)}var Wr=[{matches:t=>D.uiAbilityLifecycleBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:t=>Tn(t),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:t=>!Tn(t)&&D.stageModel.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:t=>D.entryAbilityPage.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:t=>D.declarePermissionBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:t=>D.stateDecoratorBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:t=>D.stateManagement.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:t=>D.routerRoute.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:1.4},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]},{matches:t=>D.dialogPopupBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function Xr(t,e){for(let{catalog:n,multiplier:r}of e){let o=N[n];t.set(o,(t.get(o)??1)*r)}}function Cn(t,e){for(let n of Wr)n.matches(t)&&Xr(e,n.weights)}import*as Nn from"os";function le(){return qr().toLowerCase().includes("openharmony")}function qr(){return Nn.platform()}import*as W from"fs";import*as Pn from"path";function F(t){process.env.DEVECO_CLI_DEBUG&&process.stderr.write(`[DEBUG] ${t}
2
- `)}var xt=null,de=null,me=null;function Qr(){return W.existsSync(nt())}function Jr(t){let e=nt(),n={backend:"jieba-wasm",reason:"native-jieba-load-failed",message:t,createdAt:new Date().toISOString()};W.mkdirSync(Pn.dirname(e),{recursive:!0}),ot(e),W.writeFileSync(e,JSON.stringify(n,null,2))}function Yr(){if(xt)return xt;let t=$("harmonyos-stopwords.txt");return xt=new Set(t.split(`
3
- `).map(e=>e.trim()).filter(Boolean)),xt}function Vr(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n]?.trim();if(!r)continue;let o=t[n+1]?.trim();if(r==="@"&&o&&/^[A-Z][a-zA-Z0-9]*$/.test(o)){e.push(`@${o}`),n+=1;continue}e.push(r)}return e}function Kr(t){let e=Yr(),n=[];for(let r of Vr(t)){let o=r.trim();!o||e.has(o)||(n.push(o.toLowerCase()),/[A-Z]/.test(o)&&/[a-zA-Z]/.test(o)&&n.push(o))}return n}async function On(t){let{dict:e}=await import("@node-rs/jieba/dict.js"),n=t.withDict(e),r=$("harmonyos-terms.txt");return n.loadDict(Buffer.from(r,"utf-8")),n}async function to(){let{Jieba:t}=await import("@node-rs/jieba");return On(t)}async function Rn(){let{Jieba:t}=await import("@node-rs/jieba-wasm32-wasi");return On(t)}async function eo(){let t=await import("jieba-wasm"),e=$("harmonyos-terms.txt");return t.with_dict(e),{cut:t.cut,cutForSearch:t.cut_for_search}}async function no(){if(le())return eo();if(Qr())return Rn();try{let e=await to();return F("doc-index: using @node-rs/jieba backend"),e}catch(e){let n=e instanceof Error?e.message:String(e);Jr(n),F(`doc-index: @node-rs/jieba unavailable (${n}); falling back to wasm32-wasi`)}let t=await Rn();return F("doc-index: using @node-rs/jieba-wasm32-wasi backend"),t}async function X(){return de||(me||(me=no().then(t=>(de=t,t))),me)}async function ro(t){let e=await X();return Kr(e.cutForSearch(t,!0))}async function Et(t,e){let n=t.trim();if(!n||e<=0)return"";let r=(await ro(n)).join(" ");return r.length<=e?r:r.slice(0,e)}async function oo(t,e){let n=[];for(let o of t){let i=o.trim();i&&(n.push(i.toLowerCase()),/[A-Z]/.test(i)&&n.push(i))}let r=[...new Set(n)].join(" ");return r.length<=e?r:r.slice(0,e)}async function _t(t){let e=!!t.sectionTitle.trim(),n=t.titleTokens.trim(),r=e?ke:Pe,o=e?ve:Le,i=e?await oo(t.apiSymbols,o):await Et(t.apiSymbols.join(" "),o),a=(await Promise.all([Et(n,e?Fe:Oe),Promise.resolve(i),Et(t.headingsText,e?ze:Be),Et(t.bodySample,e?He:Me)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}var Ln=["harmonyos-releases","harmonyos-roadmap"],io=new Set(Ln.map(t=>N[t])),Ha=Ln.map(t=>`${lt[t]}/`);function so(t){return io.has(t)}function Bn(t){let e=[],n=[];for(let r of t)so(r.catalog_id)?n.push(r):e.push(r);return[...e,...n]}var ao=[{pattern:/@ohos\./i,catalog:"harmonyos-references",multiplier:1.5},{pattern:/@[A-Z][a-zA-Z]+/,catalog:"harmonyos-guides",multiplier:1.35},{pattern:/(如何|怎么|怎样|步骤)/,catalog:"harmonyos-guides",multiplier:1.45},{pattern:/(生命周期|原理|概述|什么是|模型|介绍)/,catalog:"harmonyos-guides",multiplier:1.35},{pattern:/(报错|失败|错误|异常|排查)/,catalog:"harmonyos-guides",multiplier:1.25},{pattern:/(报错|失败|FAQ)/i,catalog:"harmonyos-faqs",multiplier:1.2},{pattern:/(构建|签名|打包|发布|上架|应用市场|hvigor|ohpm)/i,catalog:"harmonyos-guides",multiplier:1.3},{pattern:/(行为变更|changelog|升级|适配|版本说明)/i,catalog:"harmonyos-releases",multiplier:1.3},{pattern:/(路由|弹窗|手势|页面|权限|装饰器)/,catalog:"harmonyos-guides",multiplier:1.25,skipForPureApiSymbol:!0}];function at(t,e,n){let r=N[e];t.set(r,(t.get(r)??1)*n)}function co(t,e){let n=t.trim(),r=/[\u4e00-\u9fff]/.test(n),o=/\b[A-Z][a-zA-Z0-9]{2,}\b/.test(n),i=/\b[a-z][a-zA-Z0-9]{3,}\b/.test(n);if(r&&(o||i)){at(e,"harmonyos-guides",1.45),at(e,"harmonyos-references",1.35);return}(o||i)&&at(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(n)&&at(e,"harmonyos-references",1.75)}function Mn(t){let e=new Map,n=t.trim();if(!n)return e;let r=wn(n);co(n,e),Cn(n,e);for(let o of ao)o.pattern.test(n)&&(o.skipForPureApiSymbol&&r||at(e,o.catalog,o.multiplier));return e}import*as Q from"fs";import*as Un from"path";var uo=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function kn(t,e){let n=-1;for(let r of uo){let o=t.lastIndexOf(r);o>n&&(n=o)}return n>=e?n:-1}function Fn(t,e){let n=t.trim();if(n.length<=e)return{text:n,excerptTruncated:!1};let r=n.slice(0,e),o=kn(r,e-20),i=o>=0?o:e;return{text:n.slice(0,i).trimEnd(),excerptTruncated:!0}}function vn(t,e,n={}){let{maxLen:r=Ue,contextChars:o=$e,excerptTruncated:i=!1}=n,s=t.replace(/\s+/g," ").trim();if(!s)return"";if(s.length<=r)return i?`${s}...`:s;let a=e.split(/\s+/).map(Ot=>Ot.trim()).filter(Boolean),c=0;for(let Ot of a){let Ae=s.toLowerCase().indexOf(Ot.toLowerCase());if(Ae>=0){c=Ae;break}}let f=Math.max(0,c-o),p=Math.min(s.length,f+r),d=s.slice(f,p),E=kn(d,r-25);E>=0&&(p=f+E);let h=s.slice(f,p).trim(),_=f>0?"...":"",Sr=p<s.length||i?"...":"";return`${_}${h}${Sr}`}var lo=`
1
+ import*as x from"fs";import*as V from"path";import ji from"proper-lockfile";import Zi from"ora";import*as b from"fs";import*as at from"path";var Lt=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],B={"harmonyos-guides":"\u5F00\u53D1\u6307\u5357","harmonyos-references":"API\u53C2\u8003","best-practices":"\u6700\u4F73\u5B9E\u8DF5","harmonyos-faqs":"FAQ","harmonyos-releases":"\u7248\u672C\u8BF4\u660E","harmonyos-roadmap":"\u53D8\u66F4\u9884\u544A"};var z="1.10.0",ns=48*1024*1024,we=280,Ce=6,Re=100,Oe=3,Ne=28,Bt=10,Pe=/API参考|APIReference/i;var Le=6,dt=700,Mt=250,kt=400,Be=1320,Me=120,ke=450,Fe=250,ve=500,ze=480,He=80,je=200,Ze=60,Ue=200,$e=40,Ge=200,We=200,Xe=40,H=500,qe=Object.fromEntries(Lt.map((t,e)=>[B[t],e])),R=Object.fromEntries(Lt.map((t,e)=>[t,e])),Ft="kb",vt="source",zt={guides:"harmonyos-guides","harmonyos-references":"harmonyos-references","best-practices":"best-practices",faq:"harmonyos-faqs","release-notes":"harmonyos-releases",changelogs:"harmonyos-roadmap"},br=Object.fromEntries(Object.entries(zt).map(([t,e])=>[B[e],t]));import*as tt from"fs";import*as m from"path";import{fileURLToPath as en}from"url";import*as O from"fs";import*as Ve from"path";import{homedir as Ar}from"os";import*as Qe from"fs";import*as y from"path";function Ht(t,e){let n=y.relative(e,t);return n===""||!y.isAbsolute(n)&&!n.startsWith(`..${y.sep}`)&&n!==".."}function j(t){let e=y.resolve(t),n=[],r=e;for(;;)try{let o=Qe.realpathSync(r);return n.length===0?o:y.join(o,...n.reverse())}catch(o){if(o.code!=="ENOENT")throw o;let i=y.dirname(r);if(i===r)return e;n.push(y.basename(r)),r=i}}function Je(t,e){let n=j(e),r=j(t);return Ht(r,n)?r:null}function jt(t){let e=t.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function Ye(t){let e=jt(t);if(!e)throw new Error("Path must not be empty.");return j(e)}var Dr="deveco-cli",Zt,M=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function Ke(){let t=process.env.DEVECO_CLI_DATA_DIR,n=(t===void 0||t===""?"":jt(t))||Ve.join(Ar(),".local","share",Dr);try{return Ye(n)}catch(r){throw new M(r instanceof Error?r.message:String(r))}}async function tn(){let t=Ke();await O.promises.mkdir(t,{recursive:!0});let e;try{e=await O.promises.realpath(t)}catch(r){throw new M(`DEVECO_CLI_DATA_DIR is not usable: ${r instanceof Error?r.message:String(r)}`)}if(!(await O.promises.stat(e)).isDirectory())throw new M("DEVECO_CLI_DATA_DIR must be a writable directory.");return Zt=e,e}function K(){if(Zt!==void 0)return Zt;let t=Ke();try{if(O.existsSync(t))return O.realpathSync(t)}catch{}return t}var Ir="docs";function Z(){return m.join(K(),Ir)}function g(){return m.join(Z(),".index")}function mt(){return m.join(g(),"build.lock")}function et(){return m.join(g(),"build-status.json")}function U(){return m.join(g(),"build-meta.json")}function $(){return m.join(g(),"search.db")}function nt(){return m.join(g(),"sqlite-backend.json")}function rt(){return m.join(g(),"jieba-backend.json")}function I(){return m.join(g(),".tmp")}function Tr(){return m.join(K(),"logs")}function Ut(){return m.join(Tr(),"doc-init.log")}function wr(t,e){let n=e;for(;!n.endsWith(`${m.sep}dist`)&&n!==m.dirname(n);)n=m.dirname(n);return n}function nn(t,e){return m.dirname(wr(t,e))}function rn(){let t=en(import.meta.url),e=m.dirname(t);return t.includes(`${m.sep}dist${m.sep}`)?nn(t,e):m.join(e,"..","..","..")}function Cr(...t){let e=en(import.meta.url),n=m.dirname(e);return e.includes(`${m.sep}dist${m.sep}`)?[m.join(nn(e,n),...t)]:[m.join(n,"..","..","..",...t)]}function on(...t){let e=rn(),n=tt.realpathSync(e);for(let r of Cr(...t))try{let o=tt.lstatSync(r);if(o.isSymbolicLink()||!o.isFile())throw new Error(`Unsafe documentation package asset: ${t.join("/")} must be a regular file.`);let i=tt.realpathSync(r);if(!Ht(i,n))throw new Error(`Unsafe documentation package asset: ${t.join("/")} is outside the package.`);return i}catch(o){if(o.code!=="ENOENT")throw o}return null}function k(){return on("docs.zip")}function $t(){return on("index.zip")}function sn(){return m.join(rn(),"index","data")}import*as T from"fs";import*as F from"path";var w=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],Gt=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};var Wt=null;function Xt(t){Wt=t}function an(){if(Wt)return Wt;let t=g();if(w.every(o=>T.existsSync(F.join(t,o))))return t;let n=sn();if(w.every(o=>T.existsSync(F.join(n,o))))return n;throw new Gt("Lexicon files not found. Install the documentation index first (index.zip).")}function G(t){let e=F.join(an(),t);return T.readFileSync(e,"utf-8")}function cn(t,e){return T.readFileSync(F.join(e,t),"utf-8")}async function un(t,e=an()){await T.promises.mkdir(t,{recursive:!0});for(let n of w){let r=F.join(e,n),o=F.join(t,n);await T.promises.copyFile(r,o)}}import*as qt from"fs";import*as Rr from"yauzl";function Qt(){let t=k();return t!==null&&qt.existsSync(t)}import*as S from"fs";import*as C from"path";import ln from"adm-zip";import*as ot from"fs";import*as pt from"path";var ft=class extends Error{constructor(e){super(`Unsafe documentation path: ${e}`),this.name="DocPathSafetyError"}};function Vt(t){return t instanceof M||t instanceof ft||t instanceof Error&&(t.name==="CliDataDirError"||t.name==="DocPathSafetyError")}function Kt(t){return new ft(t)}function Or(){return j(K())}function Yt(t,e,n){let r=Je(t,e);if(r===null)throw Kt(`${n} resolves outside the data directory.`);return r}async function Jt(t,e){await ot.promises.mkdir(t,{recursive:!0});let n=Yt(t,e,"directory");if(!(await ot.promises.stat(n)).isDirectory())throw Kt("path must be a directory.")}function it(t){let e=Or();try{let n=Yt(t,e,"file");if(!ot.statSync(n).isFile())throw Kt("path must be a regular file.")}catch(n){if(n.code==="ENOENT"){Yt(pt.dirname(t),e,"file parent");return}throw n}}async function st(t={}){let e=t.mode??"write",n=await tn();await Jt(Z(),n),await Jt(g(),n),e==="write"&&await Jt(I(),n);for(let r of[$(),U(),et(),mt(),rt(),nt(),...w.map(o=>pt.join(g(),o))])it(r)}var te=["search.db","build-meta.json",...w],Nr=["corpus.json","corpus-offsets.json","orama.dpack"];async function Pr(t){for(let e of Nr)await S.promises.rm(C.join(t,e),{force:!0})}async function Lr(t){let e=await S.promises.readdir(t,{withFileTypes:!0});for(let n of e)n.name!==".index"&&await S.promises.rm(C.join(t,n.name),{recursive:!0,force:!0})}function dn(t){let n=new ln(t).getEntry("build-meta.json");if(!n)throw new Error("index.zip is missing build-meta.json");return JSON.parse(n.getData().toString("utf-8"))}async function Br(t){let e=g();await S.promises.mkdir(e,{recursive:!0});for(let n of te){let r=C.join(e,n);await S.promises.rm(r,{force:!0}),await S.promises.rename(C.join(t,n),r)}await Pr(e),await S.promises.rm(I(),{recursive:!0,force:!0})}function mn(t){let e=$t();if(!e)return!1;try{let n=dn(e);return n.indexVersion===z&&n.docsZipSha256===t&&n.segmentCount>0}catch{return!1}}async function fn(t){await st({mode:"write"});let e=$t();if(!e)throw new Error("index.zip not found");let n=dn(e);if(n.docsZipSha256!==t)throw new Error("Bundled index.zip does not match docs.zip. Rebuild index.zip with npm run build:index.");if(n.segmentCount<=0)throw new Error("Bundled index.zip is empty");let r=I();await S.promises.rm(r,{recursive:!0,force:!0}),await S.promises.mkdir(r,{recursive:!0});let o=new ln(e);for(let s of te){let a=o.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await S.promises.writeFile(C.join(r,s),a.getData())}let i=JSON.parse(await S.promises.readFile(C.join(r,"build-meta.json"),"utf-8"));if(!S.existsSync(C.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await Br(r),await S.promises.mkdir(Z(),{recursive:!0}),await Lr(Z()),i}async function pn(){await S.promises.rm(I(),{recursive:!0,force:!0});let t=g();for(let e of te)await S.promises.rm(C.join(t,e),{force:!0})}import{createHash as gn}from"crypto";import*as hn from"fs";async function gt(t){return new Promise((e,n)=>{let r=gn("sha256"),o=hn.createReadStream(t);o.on("data",i=>r.update(i)),o.on("error",n),o.on("end",()=>e(r.digest("hex")))})}function Sn(t){return gn("sha256").update(t,"utf8").digest("hex")}function yn(t,e){let n=e?cn(t,e):G(t);return Sn(n)}function ht(t){return yn("harmonyos-synonyms.json",t)}function St(t){return yn("harmonyos-terms.txt",t)}var Mr={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function xn(){try{let t=await b.promises.readFile(et(),"utf-8");return JSON.parse(t)}catch{return{...Mr}}}async function ee(t){let e=et();await b.promises.mkdir(at.dirname(e),{recursive:!0}),await b.promises.writeFile(e,JSON.stringify(t,null,2))}function _n(t){let e=Date.now();return{state:"extracting",phase:1,phaseLabel:"Extracting documentation",current:0,total:0,message:t,startedAt:e,updatedAt:e,error:null}}async function N(t){let n={...await xn(),...t,updatedAt:Date.now()};return await ee(n),n}async function ne(){let t=k();return t?gt(t):null}async function re(){try{let t=await b.promises.readFile(U(),"utf-8");return JSON.parse(t)}catch{return null}}async function oe(t=!1){if(t)return"no-index";let e=await re();if(!e||e.segmentCount===0)return"no-index";let n=await ne();return n&&e.docsZipSha256!==n?"docs-changed":e.indexVersion!==z?"engine-upgraded":e.termsHash!==St()?"terms-changed":e.synonymsHash!==ht()?"synonyms-changed":null}function ie(){if(!Qt()||!b.existsSync($())||!b.existsSync(U()))return!1;let t=at.dirname($());if(!w.every(e=>b.existsSync(at.join(t,e))))return!1;try{let e=b.readFileSync(U(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function En(t=!1){return t?!0:Qt()?ie()?await oe()!==null:!0:!1}import*as Y from"fs";import*as L from"path";import Ni from"adm-zip";var bn=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]);var An=new Set(["a","an","and","api","app","application","arkts","arkui","for","get","harmonyos","how","in","oh","ohos","on","or","set","the","to","use","using","what","when","where","which","with","without","data","file","main","model","name","network","stage","system","type","user"]),Dn=new Set(["ability","extension","module","service","context","options","config","info","event","code","state","type","data","request","response","client","server","handler","helper","utils","factory","builder","listener","callback","observer","provider","consumer","delegate","adapter","driver","buffer","stream","channel","session","task","worker","controller","component","container","attribute","descriptor","modifier","validator","parser","formatter","encoder","decoder","filter","converter","generator","iterator","dispatcher","resolver","scanner","tracker","monitor","scheduler","renderer","loader","subscriber","proxy","button","surface","stack","heap","map","set","array","list"]);var kr=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,Fr=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,vr=/[A-Z][a-zA-Z0-9]{2,}/g,zr=/@[A-Z][a-zA-Z0-9]*/g,Hr=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,In=6,jr=/^[a-z][a-z0-9]{2,}$/,Zr=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,Ur=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,$r=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,Gr=/^[A-Z][a-zA-Z0-9]+$/;function se(t){return Ur.test(t)}function Wr(t){return $r.test(t)&&t.length>=In}function Xr(t){return Gr.test(t)}function ae(t){return se(t)||Wr(t)||Xr(t)}function qr(t){let e=t.trim().toLowerCase();return Dn.has(e)?!1:bn.has(e)}function Qr(t,e){let n=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${t.trim().toLowerCase()}${n}${r}`}function yt(t){let n=t.replace(/^@ohos\./i,"").split(".").filter(Boolean);return n[n.length-1]?.trim()||void 0}function ce(t){return[...t.matchAll(kr)].map(e=>e[0])}function ue(t,e=In){let n=[];for(let r of t.matchAll(Fr))r[0].length>=e&&n.push(r[0]);return n}function W(t){return t.filter(e=>{let n=e.toLowerCase();return!t.some(r=>{if(r===e)return!1;let o=r.toLowerCase();return o.length>n.length&&o.endsWith(n)&&n.length>=4})})}function A(t,e){let n=e.trim();if(!n)return;t.add(n);let r=n.toLowerCase();r!==n&&t.add(r)}function Jr(t){let e=new Set;A(e,t);let n=yt(t);return n&&A(e,n),W([...e])}function le(t){if(se(t))return Jr(t);let e=new Set;return A(e,t),W([...e])}function de(t){let e=t.trim();if(/[A-Z]/.test(e))return null;let n=e.match(Zr);if(!n)return null;let r=n[1].toLowerCase(),o=n[2].toLowerCase();if(!jr.test(r)||An.has(r)||!qr(o))return null;let i=Qr(r,o);return{first:r,second:o,camelCase:i,lower:i.toLowerCase()}}function Tn(t){let e=de(t.trim());return!e||e.second!=="manager"?null:e}function me(t,e,n){let r=n.toLowerCase(),o=new RegExp(`@ohos\\.[^\\s(]*${n}`,"i");for(let i of[t,e])if(i&&(i.toLowerCase().includes(r)||o.test(i)))return!0;return!1}function wn(t){let e=t.trim();if(ae(e))return le(e);let n=new Set;for(let r of ce(t)){A(n,r);let o=yt(r);o&&A(n,o)}for(let r of ue(t))A(n,r);for(let r of t.matchAll(zr))n.add(r[0]);for(let r of t.matchAll(Hr))n.add(r[0]);for(let r of t.matchAll(vr))r[0].length>=4&&n.add(r[0]);return W([...n])}function Cn(t){let e=t.trim();if(ae(e))return le(e);let n=new Set,r=de(e);r&&A(n,r.camelCase);for(let o of wn(e))n.add(o);for(let o of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let i=o[0];i!==i.toLowerCase()&&n.add(i)}return W([...n])}var D={pureApiSymbol:/^[A-Z][a-zA-Z0-9]+$/,stageModelExact:/^Stage\s*模型$/i,stageModelEnglishExact:/^stage\s+model$/i,stageModel:/Stage\s*模型/i,stageModelEntryPage:/Stage\s*模型.*EntryAbility.*(页面|新页面)/,declarePermissionBoost:/声明.*权限|应用权限.*声明|如何声明应用权限/,declarePermissionCatalog:/如何声明应用权限/,declarePermissionTokens:/如何声明应用权限|声明应用权限/,uiAbilityLifecycleBoost:/UIAbility.*生命周期|生命周期.*UIAbility|UIAblity/i,uiAbilityLifecycleCatalog:/UIAblity.*生命周期|UIAbility.*生命周期/i,entryAbilityPage:/EntryAbility.*(页面|启动|跳转|新页面)/,stateDecoratorBoost:/@State|@Prop|@Link|@Provide|@Consume/,stateDecoratorCatalog:/@State\s*装饰器|@Prop\s*装饰器|@Link\s*装饰器/,stateManagement:/状态管理原理/,routerRoute:/Router\s+路由/,dialogPopupExact:/^Dialog\s+弹窗$/,dialogPopupBoost:/Dialog\s+弹窗/};function On(t){return D.pureApiSymbol.test(t.trim())}function Rn(t){let e=t.trim();return D.stageModelExact.test(e)||D.stageModelEnglishExact.test(e)}var Yr=[{matches:t=>D.uiAbilityLifecycleBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:t=>Rn(t),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:t=>!Rn(t)&&D.stageModel.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:t=>D.entryAbilityPage.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:t=>D.declarePermissionBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:t=>D.stateDecoratorBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:t=>D.stateManagement.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:t=>D.routerRoute.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:1.4},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]},{matches:t=>D.dialogPopupBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function Vr(t,e){for(let{catalog:n,multiplier:r}of e){let o=R[n];t.set(o,(t.get(o)??1)*r)}}function Nn(t,e){for(let n of Yr)n.matches(t)&&Vr(e,n.weights)}import*as Pn from"os";function fe(){return Kr().toLowerCase().includes("openharmony")}function Kr(){return Pn.platform()}import*as X from"fs";import*as Bn from"path";function v(t){process.env.DEVECO_CLI_DEBUG&&process.stderr.write(`[DEBUG] ${t}
2
+ `)}var xt=null,pe=null,ge=null;function to(){return X.existsSync(rt())}function eo(t){let e=rt(),n={backend:"jieba-wasm",reason:"native-jieba-load-failed",message:t,createdAt:new Date().toISOString()};X.mkdirSync(Bn.dirname(e),{recursive:!0}),it(e),X.writeFileSync(e,JSON.stringify(n,null,2))}function no(){if(xt)return xt;let t=G("harmonyos-stopwords.txt");return xt=new Set(t.split(`
3
+ `).map(e=>e.trim()).filter(Boolean)),xt}function ro(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n]?.trim();if(!r)continue;let o=t[n+1]?.trim();if(r==="@"&&o&&/^[A-Z][a-zA-Z0-9]*$/.test(o)){e.push(`@${o}`),n+=1;continue}e.push(r)}return e}function oo(t){let e=no(),n=[];for(let r of ro(t)){let o=r.trim();!o||e.has(o)||(n.push(o.toLowerCase()),/[A-Z]/.test(o)&&/[a-zA-Z]/.test(o)&&n.push(o))}return n}async function Mn(t){let{dict:e}=await import("@node-rs/jieba/dict.js"),n=t.withDict(e),r=G("harmonyos-terms.txt");return n.loadDict(Buffer.from(r,"utf-8")),n}async function io(){let{Jieba:t}=await import("@node-rs/jieba");return Mn(t)}async function Ln(){let{Jieba:t}=await import("@node-rs/jieba-wasm32-wasi");return Mn(t)}async function so(){let t=await import("jieba-wasm"),e=G("harmonyos-terms.txt");return t.with_dict(e),{cut:t.cut,cutForSearch:t.cut_for_search}}async function ao(){if(fe())return so();if(to())return Ln();try{let e=await io();return v("doc-index: using @node-rs/jieba backend"),e}catch(e){let n=e instanceof Error?e.message:String(e);eo(n),v(`doc-index: @node-rs/jieba unavailable (${n}); falling back to wasm32-wasi`)}let t=await Ln();return v("doc-index: using @node-rs/jieba-wasm32-wasi backend"),t}async function q(){return pe||(ge||(ge=ao().then(t=>(pe=t,t))),ge)}async function co(t){let e=await q();return oo(e.cutForSearch(t,!0))}async function _t(t,e){let n=t.trim();if(!n||e<=0)return"";let r=(await co(n)).join(" ");return r.length<=e?r:r.slice(0,e)}async function uo(t,e){let n=[];for(let o of t){let i=o.trim();i&&(n.push(i.toLowerCase()),/[A-Z]/.test(i)&&n.push(i))}let r=[...new Set(n)].join(" ");return r.length<=e?r:r.slice(0,e)}async function Et(t){let e=!!t.sectionTitle.trim(),n=t.titleTokens.trim(),r=e?ze:Be,o=e?je:ke,i=e?await uo(t.apiSymbols,o):await _t(t.apiSymbols.join(" "),o),a=(await Promise.all([_t(n,e?He:Me),Promise.resolve(i),_t(t.headingsText,e?Ze:Fe),_t(t.bodySample,e?Ue:ve)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}var kn=["harmonyos-releases","harmonyos-roadmap"],lo=new Set(kn.map(t=>R[t])),Wa=kn.map(t=>`${B[t]}/`);function mo(t){return lo.has(t)}function Fn(t){let e=[],n=[];for(let r of t)mo(r.catalog_id)?n.push(r):e.push(r);return[...e,...n]}var fo=[{pattern:/@ohos\./i,catalog:"harmonyos-references",multiplier:1.5},{pattern:/@[A-Z][a-zA-Z]+/,catalog:"harmonyos-guides",multiplier:1.35},{pattern:/(如何|怎么|怎样|步骤)/,catalog:"harmonyos-guides",multiplier:1.45},{pattern:/(生命周期|原理|概述|什么是|模型|介绍)/,catalog:"harmonyos-guides",multiplier:1.35},{pattern:/(报错|失败|错误|异常|排查)/,catalog:"harmonyos-guides",multiplier:1.25},{pattern:/(报错|失败|FAQ)/i,catalog:"harmonyos-faqs",multiplier:1.2},{pattern:/(构建|签名|打包|发布|上架|应用市场|hvigor|ohpm)/i,catalog:"harmonyos-guides",multiplier:1.3},{pattern:/(行为变更|changelog|升级|适配|版本说明)/i,catalog:"harmonyos-releases",multiplier:1.3},{pattern:/(路由|弹窗|手势|页面|权限|装饰器)/,catalog:"harmonyos-guides",multiplier:1.25,skipForPureApiSymbol:!0}];function ct(t,e,n){let r=R[e];t.set(r,(t.get(r)??1)*n)}function po(t,e){let n=t.trim(),r=/[\u4e00-\u9fff]/.test(n),o=/\b[A-Z][a-zA-Z0-9]{2,}\b/.test(n),i=/\b[a-z][a-zA-Z0-9]{3,}\b/.test(n);if(r&&(o||i)){ct(e,"harmonyos-guides",1.45),ct(e,"harmonyos-references",1.35);return}(o||i)&&ct(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(n)&&ct(e,"harmonyos-references",1.75)}function vn(t){let e=new Map,n=t.trim();if(!n)return e;let r=On(n);po(n,e),Nn(n,e);for(let o of fo)o.pattern.test(n)&&(o.skipForPureApiSymbol&&r||ct(e,o.catalog,o.multiplier));return e}import*as J from"fs";import*as Wn from"path";var go=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function zn(t,e){let n=-1;for(let r of go){let o=t.lastIndexOf(r);o>n&&(n=o)}return n>=e?n:-1}function Hn(t,e){let n=t.trim();if(n.length<=e)return{text:n,excerptTruncated:!1};let r=n.slice(0,e),o=zn(r,e-20),i=o>=0?o:e;return{text:n.slice(0,i).trimEnd(),excerptTruncated:!0}}function jn(t,e,n={}){let{maxLen:r=We,contextChars:o=Xe,excerptTruncated:i=!1}=n,s=t.replace(/\s+/g," ").trim();if(!s)return"";if(s.length<=r)return i?`${s}...`:s;let a=e.split(/\s+/).map(Pt=>Pt.trim()).filter(Boolean),c=0;for(let Pt of a){let Te=s.toLowerCase().indexOf(Pt.toLowerCase());if(Te>=0){c=Te;break}}let f=Math.max(0,c-o),p=Math.min(s.length,f+r),d=s.slice(f,p),_=zn(d,r-25);_>=0&&(p=f+_);let h=s.slice(f,p).trim(),E=f>0?"...":"",Er=p<s.length||i?"...":"";return`${E}${h}${Er}`}var ho=`
4
4
  SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
5
5
  d.catalog_id, bm25(segments_fts) AS bm25
6
6
  FROM segments_fts
@@ -9,7 +9,7 @@ import*as x from"fs";import*as Y from"path";import ki from"proper-lockfile";impo
9
9
  WHERE segments_fts MATCH ?
10
10
  ORDER BY bm25(segments_fts)
11
11
  LIMIT ?
12
- `,mo=`
12
+ `,So=`
13
13
  SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
14
14
  d.catalog_id, bm25(segments_fts) AS bm25
15
15
  FROM segments_fts
@@ -18,7 +18,7 @@ import*as x from"fs";import*as Y from"path";import ki from"proper-lockfile";impo
18
18
  WHERE segments_fts MATCH ? AND d.catalog_id = ?
19
19
  ORDER BY bm25(segments_fts)
20
20
  LIMIT ?
21
- `,fo=3.5,po=1.4,go=4,ho=1.8,So=1.35,yo=3.5,xo=1.8,Eo=120,zn=6;function pe(t){return t.toLowerCase().replace(/[^\p{L}\p{N}@.]+/gu,"")}function _o(t){return t.split(/[^\p{L}\p{N}@.]+/u).map(pe).filter(e=>e.length>=2)}function bo(t,e){return e.length>1&&e.every(n=>t.includes(n))}function Ao(t){return/^[a-z0-9]{1,4}$/.test(t.trim().toLowerCase())}function Do(t,e){return t===e?yo:t.startsWith(e)||t.includes(`@ohos.${e}`)?xo:1}function Io(t,e){let n=pe(e);if(n.length<2)return 1;let r=pe(t.doc_title);if(Ao(e))return Do(r,n);if(r.includes(n))return go;if(n.length>=zn&&r.includes(n.slice(0,zn)))return ho;let o=_o(e);return bo(r,o)?So:1}function To(t,e){return e<=1?t:t<0?t*e:t/e}function bt(t,e,n,r){let o=t.bm25/(e.get(t.catalog_id)??1);return o=To(o,Io(t,n)),r&&ue(t.doc_title,t.section_title,r)&&(o/=fo,t.catalog_id===N["harmonyos-references"]&&(o/=po)),o}function fe(t,e,n,r){return t.reduce((o,i)=>bt(i,e,n,r)<bt(o,e,n,r)?i:o)}function wo(t,e){return e.some(n=>t.section_title.includes(n)||t.doc_title.includes(n))}function Co(t,e,n,r,o){if(o){let i=t.filter(s=>ue(s.doc_title,s.section_title,o));if(i.length>0)return fe(i,n,r,o)}if(e.length>0){let i=t.filter(s=>wo(s,e));if(i.length>0)return fe(i,n,r,o)}return fe(t,n,r,o)}function Hn(t,e,n,r,o){let i=Mn(e),s=In(e),c=An(e)?.camelCase,f=new Map;for(let h of t){let _=f.get(h.document_id)??[];_.push(h),f.set(h.document_id,_)}let p=[];for(let h of f.values())p.push(Co(h,s,i,n,c));let d=p.sort((h,_)=>bt(h,i,n,c)-bt(_,i,n,c));return(o?Bn(d):d).slice(0,r)}function At(t,e,n,r,o,i){let s=e?N[e]:void 0,a=Math.max(n,n*Re,Eo),c=s===void 0?t.all(lo,r,a):t.all(mo,r,s,a);return(s===void 0?Hn(c,i,o,n,!0):Hn(c,i,o,n,!1)).map(p=>({title:p.doc_title,documentId:p.document_id,sectionTitle:p.section_title||void 0,snippet:vn(p.lead_text,o,{excerptTruncated:!!p.excerpt_truncated})}))}var Dt=`
21
+ `,yo=3.5,xo=1.4,_o=4,Eo=1.8,bo=1.35,Ao=3.5,Do=1.8,Io=120,Zn=6;function Se(t){return t.toLowerCase().replace(/[^\p{L}\p{N}@.]+/gu,"")}function To(t){return t.split(/[^\p{L}\p{N}@.]+/u).map(Se).filter(e=>e.length>=2)}function wo(t,e){return e.length>1&&e.every(n=>t.includes(n))}function Co(t){return/^[a-z0-9]{1,4}$/.test(t.trim().toLowerCase())}function Ro(t,e){return t===e?Ao:t.startsWith(e)||t.includes(`@ohos.${e}`)?Do:1}function Oo(t,e){let n=Se(e);if(n.length<2)return 1;let r=Se(t.doc_title);if(Co(e))return Ro(r,n);if(r.includes(n))return _o;if(n.length>=Zn&&r.includes(n.slice(0,Zn)))return Eo;let o=To(e);return wo(r,o)?bo:1}function No(t,e){return e<=1?t:t<0?t*e:t/e}function bt(t,e,n,r){let o=t.bm25/(e.get(t.catalog_id)??1);return o=No(o,Oo(t,n)),r&&me(t.doc_title,t.section_title,r)&&(o/=yo,t.catalog_id===R["harmonyos-references"]&&(o/=xo)),o}function he(t,e,n,r){return t.reduce((o,i)=>bt(i,e,n,r)<bt(o,e,n,r)?i:o)}function Po(t,e){return e.some(n=>t.section_title.includes(n)||t.doc_title.includes(n))}function Lo(t,e,n,r,o){if(o){let i=t.filter(s=>me(s.doc_title,s.section_title,o));if(i.length>0)return he(i,n,r,o)}if(e.length>0){let i=t.filter(s=>Po(s,e));if(i.length>0)return he(i,n,r,o)}return he(t,n,r,o)}function Un(t,e,n,r,o){let i=vn(e),s=Cn(e),c=Tn(e)?.camelCase,f=new Map;for(let h of t){let E=f.get(h.document_id)??[];E.push(h),f.set(h.document_id,E)}let p=[];for(let h of f.values())p.push(Lo(h,s,i,n,c));let d=p.sort((h,E)=>bt(h,i,n,c)-bt(E,i,n,c));return(o?Fn(d):d).slice(0,r)}function At(t,e,n,r,o,i){let s=e?R[e]:void 0,a=Math.max(n,n*Le,Io),c=s===void 0?t.all(ho,r,a):t.all(So,r,s,a);return(s===void 0?Un(c,i,o,n,!0):Un(c,i,o,n,!1)).map(p=>({title:p.doc_title,documentId:p.document_id,sectionTitle:p.section_title||void 0,snippet:jn(p.lead_text,o,{excerptTruncated:!!p.excerpt_truncated})}))}var Dt=`
22
22
  CREATE TABLE documents (
23
23
  id INTEGER PRIMARY KEY,
24
24
  document_id TEXT NOT NULL UNIQUE,
@@ -56,11 +56,11 @@ CREATE TRIGGER segments_au AFTER UPDATE ON segments BEGIN
56
56
  END;
57
57
 
58
58
  CREATE INDEX segments_doc_id_idx ON segments(doc_id);
59
- `;var q=null,ge=null;function No(){q?.close(),q=null,ge=null}function Ro(t,e){if(q&&ge===e)return q;q?.close();let n=new t(e,{readonly:!0,fileMustExist:!0});return q=n,ge=e,n.pragma("mmap_size = 268435456"),n.pragma("cache_size = -8000"),n.pragma("query_only = ON"),n}function Po(t,e){let n=new t(e);return n.pragma("journal_mode = OFF"),n.pragma("synchronous = OFF"),n.pragma("temp_store = MEMORY"),n.exec(Dt),n}function Oo(t,e,n){let r=e.get(n.documentId);if(r!==void 0)return r;let i=t.prepare("SELECT id FROM documents WHERE document_id = ?").get(n.documentId);if(i)return e.set(n.documentId,i.id),i.id;let a=t.prepare(`
59
+ `;var Q=null,ye=null;function Bo(){Q?.close(),Q=null,ye=null}function Mo(t,e){if(Q&&ye===e)return Q;Q?.close();let n=new t(e,{readonly:!0,fileMustExist:!0});return Q=n,ye=e,n.pragma("mmap_size = 268435456"),n.pragma("cache_size = -8000"),n.pragma("query_only = ON"),n}function ko(t,e){let n=new t(e);return n.pragma("journal_mode = OFF"),n.pragma("synchronous = OFF"),n.pragma("temp_store = MEMORY"),n.exec(Dt),n}function Fo(t,e,n){let r=e.get(n.documentId);if(r!==void 0)return r;let i=t.prepare("SELECT id FROM documents WHERE document_id = ?").get(n.documentId);if(i)return e.set(n.documentId,i.id),i.id;let a=t.prepare(`
60
60
  INSERT INTO documents(document_id, catalog_id, doc_title)
61
61
  VALUES (?, ?, ?)
62
- `).run(n.documentId,n.catalogId,n.docTitle),c=Number(a.lastInsertRowid);return e.set(n.documentId,c),c}async function Lo(t,e,n,r){await X();let o=Po(t,e),i=new Map,s=o.prepare(`
62
+ `).run(n.documentId,n.catalogId,n.docTitle),c=Number(a.lastInsertRowid);return e.set(n.documentId,c),c}async function vo(t,e,n,r){await q();let o=ko(t,e),i=new Map,s=o.prepare(`
63
63
  INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated)
64
64
  VALUES (?, ?, ?, ?, ?)
65
- `),a=n.length;for(let c=0;c<a;c+=z){let f=n.slice(c,c+z),p=await Promise.all(f.map(async E=>({source:E,searchText:await _t(E)})));o.transaction(E=>{for(let h of E){let _=Oo(o,i,h.source);s.run(_,h.source.sectionTitle,h.source.leadText,h.searchText,h.source.excerptTruncated?1:0)}})(p),await r?.(Math.min(c+f.length,a),a)}o.exec("ANALYZE"),o.exec("VACUUM"),o.close()}function Bo(t,e,n,r,o,i,s){let a=Ro(t,e);return At({all(c,...f){return a.prepare(c).all(...f)}},n,r,o,i,s)}async function jn(){let e=(await import("better-sqlite3")).default;return{kind:"better-sqlite3",resetCache:No,buildSearchIndex:(n,r,o)=>Lo(e,n,r,o),searchIndex:(n,r,o,i,s,a,c)=>Promise.resolve(Bo(e,i,r,o,s,a,c))}}import{readFile as Mo,stat as ko,writeFile as Fo}from"fs/promises";var he=null,O=null;async function Se(){return he||(he=(async()=>{let t=(await import("@sqlite.org/sqlite-wasm")).default;return t()})()),he}function vo(t){return{all(e,...n){let r=t.prepare(e);n.length>0&&r.bind(n);let o=[];for(;r.step();)o.push(r.get({}));return r.finalize(),o}}}async function zo(t){let e=await ko(t);if(O&&O.dbPath===t&&O.mtimeMs===e.mtimeMs)return O.db;O?.db.close();let n=await Se(),r=n.capi,o=n.wasm,i=new Uint8Array(await Mo(t)),s=o.allocFromTypedArray(i),a=new n.oo1.DB(":memory:"),c=a.pointer;if(c===void 0)throw new Error("sqlite3_deserialize: database pointer is undefined");let f=r.SQLITE_DESERIALIZE_READONLY|r.SQLITE_DESERIALIZE_RESIZEABLE|r.SQLITE_DESERIALIZE_FREEONCLOSE;return r.sqlite3_deserialize(c,"main",s,i.byteLength,i.byteLength,f),O={dbPath:t,mtimeMs:e.mtimeMs,db:a},a}function Zn(){O?.db.close(),O=null}async function Ho(t,e,n,r){t.exec("BEGIN");for(let o of r){let i=n(o.source);e.bind([i,o.source.sectionTitle,o.source.leadText,o.searchText,o.source.excerptTruncated?1:0]),e.step(),e.reset()}t.exec("COMMIT")}function jo(t,e,n){return r=>{let o=e.get(r.documentId);if(o!==void 0)return o;let i=t.selectValue("SELECT id FROM documents WHERE document_id = ?",[r.documentId]);if(i!=null){let a=Number(i);return e.set(r.documentId,a),a}n.bind([r.documentId,r.catalogId,r.docTitle]),n.step(),n.reset();let s=Number(t.selectValue("SELECT last_insert_rowid()"));return e.set(r.documentId,s),s}}async function Zo(t,e,n){await X();let r=await Se(),o=new r.oo1.DB(":memory:","c");o.exec(Dt);let i=new Map,s=o.prepare("INSERT INTO documents(document_id, catalog_id, doc_title) VALUES (?, ?, ?)"),a=o.prepare("INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated) VALUES (?, ?, ?, ?, ?)"),c=jo(o,i,s),f=e.length;for(let d=0;d<f;d+=z){let E=e.slice(d,d+z),h=await Promise.all(E.map(async _=>({source:_,searchText:await _t(_)})));await Ho(o,a,c,h),await n?.(Math.min(d+E.length,f),f)}o.exec("ANALYZE");let p=r.capi.sqlite3_js_db_export(o);await Fo(t,p),o.close(),Zn()}async function Uo(t,e,n,r,o,i){let s=await zo(t);return At(vo(s),e,n,r,o,i)}async function ye(){return await Se(),{kind:"sqlite-wasm",resetCache:Zn,buildSearchIndex:Zo,searchIndex:(t,e,n,r,o,i,s)=>Uo(r,e,n,o,i,s)}}var It=null,xe=null;function $o(){return Q.existsSync(et())}function Go(t){let e=et(),n={backend:"sqlite-wasm",reason:"better-sqlite3-load-failed",message:t,createdAt:new Date().toISOString()};Q.mkdirSync(Un.dirname(e),{recursive:!0}),ot(e),Q.writeFileSync(e,JSON.stringify(n,null,2))}async function Wo(){if($o())return ye();try{let t=await jn();return F("doc-index: using better-sqlite3 SQLite backend"),t}catch(t){let e=t instanceof Error?t.message:String(t);Go(e),F(`doc-index: better-sqlite3 unavailable (${e}); falling back to sqlite-wasm`)}return ye()}async function Ee(){return It||(It=Wo().then(t=>(xe=t,t))),It}function $n(){xe?.resetCache(),It=null,xe=null}function Tt(){$n()}async function Gn(t,e,n){await(await Ee()).buildSearchIndex(t,e,n)}import{unified as Kn}from"unified";import tr from"remark-parse";import er from"remark-gfm";import{toString as Ct}from"mdast-util-to-string";var Xo=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,qo=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,Qo=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,Jo=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,Yo=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function wt(t){let e=t.trim(),n=e.match(Jo);return n?n[1]:e}function Vo(t){let e=t.match(Xo);if(!e)return;let n=wt(e[1].trim());return{displayTitle:t,symbolName:n,searchExtras:[n,e[3]]}}function Ko(t){let e=wt(t.replace(/\([^)]*\)$/,""));if(/^[A-Z][A-Za-z0-9]*$/.test(e))return{displayTitle:t,symbolName:e,searchExtras:[e]};if(/^[A-Z][A-Za-z0-9]*(\([^)]*\))?$/.test(t))return{displayTitle:t,symbolName:e,searchExtras:[e]}}function ct(t){let e=t.trim();return e?Vo(e)??(()=>{let n=e.match(qo);if(n){let r=n[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let n=e.match(Qo);if(!n)return;let r=n[1].trim(),o=n[2].trim();return{displayTitle:e,symbolName:o,searchExtras:[r,o]}})()??Ko(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function ti(t){if(t.length<2||t.length>36||Yo.test(t))return!1;let e=[...t.replace(/\s/g,"")];return e.length===0?!1:e.filter(r=>new RegExp("\\p{Script=Han}","u").test(r)).length/e.length>=.4}function Wn(t){for(let e of t){let n=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(ti(n))return n}return""}function Xn(t,e,n){let r=[t,...n.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var ei=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,ut=/@[A-Z][a-zA-Z]+/g,ni=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,ri=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,oi=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,ii=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),si=new Set(["HAP","HSP","HAR","NAPI","CAPI","NDK","ArkTS","ArkUI","OHPM"]),ai=new Set(["JSON","Object","Array","Promise","console","Math","Date","String","Number","Boolean","Error","Function","Map","Set","RegExp"]);function nr(t,e){let n=new Set,r=[t,...e];for(let o of r){for(let i of ie(o)){A(n,i);let s=yt(i);s&&A(n,s)}for(let i of se(o))A(n,i);for(let i of o.matchAll(ei)){let s=i[0];ci(s)&&n.add(s)}for(let i of o.matchAll(ut))n.add(i[0])}return G([...n])}function ci(t){let e=t.trim();if(!e||ut.test(e))return!!e;if(e.includes(".")){let n=e.split(".")[0]??"";return ai.has(n)?!1:/^[A-Z]/.test(n)}return ii.has(e)?!1:si.has(e)?!0:e.length<=3?!1:/^[A-Z][a-z]+[A-Z]/.test(e)?!0:e.length>=6&&/^[A-Z][A-Za-z0-9]+$/.test(e)}function qn(t){let e=t.trim();return!!(!e||oi.test(e)||e.length>28&&!/[A-Z\u4e00-\u9fff]/.test(e)&&/^[a-z0-9_-]+$/.test(e))}function rr(t,e){let n=e.jsonTitle?.trim(),r=mi(t,"").trim(),o=e.fileName.trim();return n&&!qn(n)?n:r&&!qn(r)?r:n||r||o}function or(t){return ni.test(t.trim())}function _e(t){let e=t.trim().replace(/\([^)]*\)$/,""),n=wt(e);return ri.test(n)}function Nt(t){let e=t.trim();return e?ut.test(e)||or(e)||_e(e)?!0:!!ct(e).symbolName:!1}function ui(t){let e=t.trim();return!(!e||or(e)||_e(e))}function li(t){let e=new Set,n=[];for(let r of t){let o=r.trim();!ui(o)||e.has(o)||(e.add(o),n.push(o))}return n}function Qn(t){if(!t.includes("."))return 0;let e=t.split(".").pop()??"";return/^[a-z]/.test(e)?1:2}function di(t,e){let n=Qn(t)-Qn(e);return n!==0?n:t.localeCompare(e)}function ir(t,e=[]){let n=[...new Set(e.map(i=>i.trim()).filter(Boolean))],r=new Set(n),o=[...new Set(t.map(i=>i.trim()).filter(Boolean))].filter(i=>!r.has(i));return o.sort(di),[...n,...o].slice(0,je)}function Rt(t){return t.replace(/\s+/g," ").trim()}function Jn(t){return t.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function mi(t,e=""){let n=t.split(/\r?\n/),r=0;for(;r<n.length&&!n[r].trim();)r+=1;if(r>=n.length)return e;let o=Jn(n[r].trim()),i=o.match(/^#+\s+(.+)$/);if(i)return Jn(i[1].trim());if(r+1<n.length){let s=n[r+1].trim();if(/^=+$/.test(s)||/^-+$/.test(s))return o}return o||e}function sr(t){let e=Rt(t.join(" "));if(e.length<=dt)return e;let n=e.slice(0,dt);return e.length<=dt+Mt?n:`${n} ${e.slice(-Mt)}`}function fi(t){let e=li(t).join(" ");return e.length<=kt?e:e.slice(0,kt)}function ar(t){let e=Rt(t),{text:n,excerptTruncated:r}=Fn(e,Ze);return{leadText:n,excerptTruncated:r}}function pi(t,e){let{leadText:n,excerptTruncated:r}=ar(t);return{leadText:n,excerptTruncated:r||!!e.trim()}}function cr(t,e){if(t.type==="code"){e.codeBlocks.push(t.value??"");return}if("children"in t&&Array.isArray(t.children)){for(let r of t.children)cr(r,e);return}let n=Rt(Ct(t));n&&e.bodyParts.push(n)}function gi(t){let e=Kn().use(tr).use(er).parse(t),n=[],r=null,o=()=>{r&&((r.sectionTitle||r.bodyParts.length||r.codeBlocks.length)&&n.push(r),r=null)},i=()=>{r||(r={sectionTitle:"",bodyParts:[],codeBlocks:[]})};for(let s of e.children){if(s.type==="heading"){let a=s,c=Ct(a).trim();if(a.depth>=4&&c&&Nt(c)){o(),r={sectionTitle:c,bodyParts:[],codeBlocks:[]};continue}i(),c&&r.bodyParts.push(c);continue}i(),cr(s,r)}return o(),n.length===0?[{sectionTitle:"",bodyParts:[],codeBlocks:[]}]:n}function hi(t){return Ne.test(t)}function Si(t){return t.filter(e=>e.sectionTitle&&Nt(e.sectionTitle)).length}function yi(t){return{sectionTitle:t.map(e=>e.sectionTitle.trim()).join(" | "),bodyParts:t.flatMap(e=>e.bodyParts).slice(0,40),codeBlocks:t.flatMap(e=>e.codeBlocks).slice(0,8)}}function Yn(t){let e=t.trim();return!e||ut.test(e)?ut.test(e):/对象说明$|枚举说明$/.test(e)?!0:_e(e)}function xi(t){let e=t.filter(d=>!d.sectionTitle||!Nt(d.sectionTitle)),n=t.filter(d=>d.sectionTitle&&Nt(d.sectionTitle)),r=n.filter(d=>Yn(d.sectionTitle)),o=n.filter(d=>!Yn(d.sectionTitle)),i=Math.max(0,Ce-r.length),s=o.slice(0,i),a=o.slice(i),c=a.filter(d=>Vn(d.sectionTitle)),f=a.filter(d=>!Vn(d.sectionTitle)),p=[];for(let d=0;d<f.length;d+=Bt)p.push(yi(f.slice(d,d+Bt)));return[...e,...r,...s,...c,...p]}function Ei(t,e,n){let r=t.split(/\r?\n/).length,o=Si(e);return o===0?!1:hi(n)?r>=Te&&o>=we:r>=De&&o>=Ie}var _i=/^\[h2\][A-Za-z]/;function Vn(t){return _i.test(t.trim())}function ur(t){if(!t.includes(" | ")){let n=ct(t);return n.symbolName?[n.symbolName]:[]}let e=[];for(let n of t.split(" | ")){let r=ct(n.trim()).symbolName;r&&e.push(r)}return e}function bi(t,e,n,r){let o=ur(t),i=nr(n,r);return e.symbolName&&i.push(e.symbolName),ir([...o,...i],o)}function Ai(t,e){let n=sr(t.bodyParts),r=t.sectionTitle.trim(),o=ct(r),i=Wn(t.bodyParts),s=Xn(r,i,o),a=ur(r),c=r?a.length>0?`${e.docTitle} ${a.join(" ")}`:`${e.docTitle} ${o.symbolName??r}`:e.docTitle,f=[e.docTitle,s,...t.bodyParts].join(" "),{leadText:p,excerptTruncated:d}=pi(n,r);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:e.docTitle,sectionTitle:r,titleTokens:c,headingsText:s,apiSymbols:bi(r,o,f,t.codeBlocks),bodySample:n,leadText:p,excerptTruncated:d}}function lr(t,e){for(let n of t){if(n.type==="heading"){let o=Ct(n).trim();o&&e.headings.push(o);continue}if(n.type==="code"){e.codeBlocks.push(n.value??"");continue}if("children"in n&&Array.isArray(n.children)){lr(n.children,e);continue}let r=Rt(Ct(n));r&&e.bodyParts.push(r)}}function Di(t){let e=Kn().use(tr).use(er).parse(t),n={headings:[],bodyParts:[],codeBlocks:[]};return lr(e.children,n),n}function Ii(t,e){let n=Di(t),r=e.docTitle?.trim()||e.documentId,o=sr(n.bodyParts),i=[r,...n.headings,o].join(" "),{leadText:s,excerptTruncated:a}=ar(o);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:r,sectionTitle:"",titleTokens:r,headingsText:fi(n.headings),apiSymbols:ir(nr(i,n.codeBlocks)),bodySample:o,leadText:s,excerptTruncated:a}}function dr(t,e){let n=e.docTitle?.trim()||e.documentId,r=gi(t);return Ei(t,r,e.documentId)?xi(r).filter(o=>o.sectionTitle||o.bodyParts.length>0||o.codeBlocks.length>0).map(o=>Ai(o,{...e,docTitle:n})):[Ii(t,{...e,docTitle:n})]}function mr(t){let e=t.split("/");if(e[0]==="docs"&&(e=e.slice(1)),e.length<2)return null;let n=Ge[e[0]];if(n===void 0)return null;let r=e[e.length-1].replace(/\.md$/,"");return e[e.length-1]=r,{documentId:e.join("/"),catalogId:n,docTitle:r}}function fr(t,e,n){let r=rr(t,{jsonTitle:e,fileName:n.docTitle});return dr(t,{...n,docTitle:r})}function wi(t){return t.getEntries().filter(e=>e.isDirectory||!e.entryName.endsWith(".md")?!1:e.entryName.split("/").every(n=>!n.startsWith(".")))}function Ci(t,e){let n=t.getEntry(e.replace(/\.md$/,".json"));if(n)try{return JSON.parse(n.getData().toString("utf-8")).title?.trim()||void 0}catch{return}}function Ni(t){let e=new Ti(t),n=[];for(let r of wi(e)){let o=mr(r.entryName);o&&n.push(...fr(r.getData().toString("utf-8"),Ci(e,r.entryName),o))}return n}async function Ri(t){let e=[];async function n(r){let o=await J.promises.readdir(r,{withFileTypes:!0});for(let i of o){if(i.name.startsWith("."))continue;let s=L.join(r,i.name);i.isDirectory()?await n(s):i.isFile()&&i.name.endsWith(".md")&&e.push(s)}}return await n(t),e}async function Pi(t){let e=t.replace(/\.md$/,".json");try{let n=await J.promises.readFile(e,"utf-8");return JSON.parse(n).title?.trim()||void 0}catch{return}}async function Oi(t){let e=[];for(let n of await Ri(t)){let r=L.relative(t,n).split(L.sep).join("/"),o=mr(r);if(!o)continue;let i=await J.promises.readFile(n,"utf-8");e.push(...fr(i,await Pi(n),o))}return e}async function Li(t){return"docsZipPath"in t?Ni(t.docsZipPath):Oi(t.docsDir)}async function Bi(t,e,n){let r=L.join(e,"search.db");return await Gn(r,t,async(o,i)=>{await n?.({current:o,total:i,message:`Building search index\u2026 ${o.toLocaleString()} / ${i.toLocaleString()} segments`})}),t.length}function Mi(t,e){return{indexVersion:v,docsZipSha256:t.docsZipSha256,termsHash:t.termsHash,synonymsHash:t.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:t.builtBy}}async function pr(t){t.lexiconDir&&$t(t.lexiconDir);try{let e=await Li(t);await t.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await J.promises.mkdir(t.tmpDir,{recursive:!0});let n=await Bi(e,t.tmpDir,t.onProgress),r=Mi(t,n);return await J.promises.writeFile(L.join(t.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await sn(t.tmpDir),r}finally{t.lexiconDir&&$t(null)}}async function hr(t){let e=Ht();await x.promises.mkdir(Y.dirname(e),{recursive:!0}),await x.promises.appendFile(e,`${new Date().toISOString()} ${t}
66
- `)}async function vi(){await it({mode:"write"});let t=g(),e=I(),n=await x.promises.readdir(e);for(let r of n){let o=Y.join(t,r);await x.promises.rm(o,{force:!0}),await x.promises.rename(Y.join(e,r),o)}await x.promises.rm(e,{recursive:!0,force:!0}),await x.promises.rm(Y.join(t,"orama.dpack"),{force:!0})}async function gr(t,e,n){e?.start(n),await P({state:"installing",phase:1,phaseLabel:"Installing index",message:n}),await ln(t),Tt(),e&&(e.text="Documentation index installed.")}async function zi(t,e){try{return await gr(t,e,"Installing documentation index\u2026"),await be(e),!0}catch(n){if(Qt(n))throw n}try{return await dn(),Tt(),await gr(t,e,"Retrying documentation index install\u2026"),await be(e),!0}catch(n){if(Qt(n))throw n;let r=n instanceof Error?n.message:String(n);return await hr(`Bundled index install failed; falling back to local rebuild: ${r}`),!1}}async function Hi(t,e,n){let r=M();if(!r)throw new Error("docs.zip not found");let o=I();await x.promises.mkdir(g(),{recursive:!0}),await x.promises.rm(o,{recursive:!0,force:!0}),n?.start("Building search index\u2026"),await P({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"}),await pr({docsZipPath:r,tmpDir:o,docsZipSha256:e,termsHash:St(),synonymsHash:ht(),builtBy:t.builtBy??"doc-init",onProgress:async i=>{n&&(n.text=i.message),await P({state:"indexing",current:i.current,total:i.total,message:i.message})}}),await P({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await vi(),Tt()}async function be(t){await P({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),t?.succeed("Documentation ready.")}async function ji(t){let e=await te(),n=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";t?.succeed(n),await P({state:"done",message:n,error:null})}async function Zi(t,e){let n=t instanceof Error?t.message:String(t);throw await P({state:"error",error:n}),await hr(`ERROR: ${n}`),e?.fail(n),t}async function Ui(){let t=g();await x.promises.mkdir(t,{recursive:!0});let e=mt();return x.existsSync(e)||await x.promises.writeFile(e,"","utf-8"),e}async function $i(){let t=await Ui();return ki.lock(t,{stale:1800*1e3})}async function Gi(){let t=M(),e=(t?await gt(t):null)??await Kt();if(!e)throw new Error("docs.zip not found");return e}async function Wi(t,e){let n=await Gi(),r=t.force||await yn(t.force),o=await ee(t.force);if(!r&&!o&&ne()){await ji(e);return}!t.force&&un(n)&&await zi(n,e)||(await Hi(t,n,e),await be(e))}var Pt=class{static async run(e={}){let n=e.background??!1,o=e.quiet??n?void 0:Fi({text:"Checking documentation\u2026",color:"cyan"}),i;try{e.assumeStorageSafe||await it({mode:"write"}),i=await $i(),await Vt(Sn("Starting documentation setup\u2026")),await Wi(e,o)}catch(s){throw i&&await Zi(s,o),s}finally{i&&await i()}}};var Xi=process.env.DEVECO_CLI_POSTINSTALL?"postinstall":"doc-init";Pt.run({background:!0,builtBy:Xi}).then(()=>{process.exit(0)}).catch(()=>{process.exit(1)});
65
+ `),a=n.length;for(let c=0;c<a;c+=H){let f=n.slice(c,c+H),p=await Promise.all(f.map(async _=>({source:_,searchText:await Et(_)})));o.transaction(_=>{for(let h of _){let E=Fo(o,i,h.source);s.run(E,h.source.sectionTitle,h.source.leadText,h.searchText,h.source.excerptTruncated?1:0)}})(p),await r?.(Math.min(c+f.length,a),a)}o.exec("ANALYZE"),o.exec("VACUUM"),o.close()}function zo(t,e,n,r,o,i,s){let a=Mo(t,e);return At({all(c,...f){return a.prepare(c).all(...f)}},n,r,o,i,s)}async function $n(){let e=(await import("better-sqlite3")).default;return{kind:"better-sqlite3",resetCache:Bo,buildSearchIndex:(n,r,o)=>vo(e,n,r,o),searchIndex:(n,r,o,i,s,a,c)=>Promise.resolve(zo(e,i,r,o,s,a,c))}}import{readFile as Ho,stat as jo,writeFile as Zo}from"fs/promises";var xe=null,P=null;async function _e(){return xe||(xe=(async()=>{let t=(await import("@sqlite.org/sqlite-wasm")).default;return t()})()),xe}function Uo(t){return{all(e,...n){let r=t.prepare(e);n.length>0&&r.bind(n);let o=[];for(;r.step();)o.push(r.get({}));return r.finalize(),o}}}async function $o(t){let e=await jo(t);if(P&&P.dbPath===t&&P.mtimeMs===e.mtimeMs)return P.db;P?.db.close();let n=await _e(),r=n.capi,o=n.wasm,i=new Uint8Array(await Ho(t)),s=o.allocFromTypedArray(i),a=new n.oo1.DB(":memory:"),c=a.pointer;if(c===void 0)throw new Error("sqlite3_deserialize: database pointer is undefined");let f=r.SQLITE_DESERIALIZE_READONLY|r.SQLITE_DESERIALIZE_RESIZEABLE|r.SQLITE_DESERIALIZE_FREEONCLOSE;return r.sqlite3_deserialize(c,"main",s,i.byteLength,i.byteLength,f),P={dbPath:t,mtimeMs:e.mtimeMs,db:a},a}function Gn(){P?.db.close(),P=null}async function Go(t,e,n,r){t.exec("BEGIN");for(let o of r){let i=n(o.source);e.bind([i,o.source.sectionTitle,o.source.leadText,o.searchText,o.source.excerptTruncated?1:0]),e.step(),e.reset()}t.exec("COMMIT")}function Wo(t,e,n){return r=>{let o=e.get(r.documentId);if(o!==void 0)return o;let i=t.selectValue("SELECT id FROM documents WHERE document_id = ?",[r.documentId]);if(i!=null){let a=Number(i);return e.set(r.documentId,a),a}n.bind([r.documentId,r.catalogId,r.docTitle]),n.step(),n.reset();let s=Number(t.selectValue("SELECT last_insert_rowid()"));return e.set(r.documentId,s),s}}async function Xo(t,e,n){await q();let r=await _e(),o=new r.oo1.DB(":memory:","c");o.exec(Dt);let i=new Map,s=o.prepare("INSERT INTO documents(document_id, catalog_id, doc_title) VALUES (?, ?, ?)"),a=o.prepare("INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated) VALUES (?, ?, ?, ?, ?)"),c=Wo(o,i,s),f=e.length;for(let d=0;d<f;d+=H){let _=e.slice(d,d+H),h=await Promise.all(_.map(async E=>({source:E,searchText:await Et(E)})));await Go(o,a,c,h),await n?.(Math.min(d+_.length,f),f)}o.exec("ANALYZE");let p=r.capi.sqlite3_js_db_export(o);await Zo(t,p),o.close(),Gn()}async function qo(t,e,n,r,o,i){let s=await $o(t);return At(Uo(s),e,n,r,o,i)}async function Ee(){return await _e(),{kind:"sqlite-wasm",resetCache:Gn,buildSearchIndex:Xo,searchIndex:(t,e,n,r,o,i,s)=>qo(r,e,n,o,i,s)}}var It=null,be=null;function Qo(){return J.existsSync(nt())}function Jo(t){let e=nt(),n={backend:"sqlite-wasm",reason:"better-sqlite3-load-failed",message:t,createdAt:new Date().toISOString()};J.mkdirSync(Wn.dirname(e),{recursive:!0}),it(e),J.writeFileSync(e,JSON.stringify(n,null,2))}async function Yo(){if(Qo())return Ee();try{let t=await $n();return v("doc-index: using better-sqlite3 SQLite backend"),t}catch(t){let e=t instanceof Error?t.message:String(t);Jo(e),v(`doc-index: better-sqlite3 unavailable (${e}); falling back to sqlite-wasm`)}return Ee()}async function Ae(){return It||(It=Yo().then(t=>(be=t,t))),It}function Xn(){be?.resetCache(),It=null,be=null}function Tt(){Xn()}async function qn(t,e,n){await(await Ae()).buildSearchIndex(t,e,n)}import{unified as nr}from"unified";import rr from"remark-parse";import or from"remark-gfm";import{toString as Ct}from"mdast-util-to-string";var Vo=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,Ko=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,ti=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,ei=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,ni=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function wt(t){let e=t.trim(),n=e.match(ei);return n?n[1]:e}function ri(t){let e=t.match(Vo);if(!e)return;let n=wt(e[1].trim());return{displayTitle:t,symbolName:n,searchExtras:[n,e[3]]}}function oi(t){let e=wt(t.replace(/\([^)]*\)$/,""));if(/^[A-Z][A-Za-z0-9]*$/.test(e))return{displayTitle:t,symbolName:e,searchExtras:[e]};if(/^[A-Z][A-Za-z0-9]*(\([^)]*\))?$/.test(t))return{displayTitle:t,symbolName:e,searchExtras:[e]}}function ut(t){let e=t.trim();return e?ri(e)??(()=>{let n=e.match(Ko);if(n){let r=n[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let n=e.match(ti);if(!n)return;let r=n[1].trim(),o=n[2].trim();return{displayTitle:e,symbolName:o,searchExtras:[r,o]}})()??oi(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function ii(t){if(t.length<2||t.length>36||ni.test(t))return!1;let e=[...t.replace(/\s/g,"")];return e.length===0?!1:e.filter(r=>new RegExp("\\p{Script=Han}","u").test(r)).length/e.length>=.4}function Qn(t){for(let e of t){let n=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(ii(n))return n}return""}function Jn(t,e,n){let r=[t,...n.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var si=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,lt=/@[A-Z][a-zA-Z]+/g,ai=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,ci=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,ui=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,li=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),di=new Set(["HAP","HSP","HAR","NAPI","CAPI","NDK","ArkTS","ArkUI","OHPM"]),mi=new Set(["JSON","Object","Array","Promise","console","Math","Date","String","Number","Boolean","Error","Function","Map","Set","RegExp"]);function ir(t,e){let n=new Set,r=[t,...e];for(let o of r){for(let i of ce(o)){A(n,i);let s=yt(i);s&&A(n,s)}for(let i of ue(o))A(n,i);for(let i of o.matchAll(si)){let s=i[0];fi(s)&&n.add(s)}for(let i of o.matchAll(lt))n.add(i[0])}return W([...n])}function fi(t){let e=t.trim();if(!e||lt.test(e))return!!e;if(e.includes(".")){let n=e.split(".")[0]??"";return mi.has(n)?!1:/^[A-Z]/.test(n)}return li.has(e)?!1:di.has(e)?!0:e.length<=3?!1:/^[A-Z][a-z]+[A-Z]/.test(e)?!0:e.length>=6&&/^[A-Z][A-Za-z0-9]+$/.test(e)}function Yn(t){let e=t.trim();return!!(!e||ui.test(e)||e.length>28&&!/[A-Z\u4e00-\u9fff]/.test(e)&&/^[a-z0-9_-]+$/.test(e))}function sr(t,e){let n=e.jsonTitle?.trim(),r=Si(t,"").trim(),o=e.fileName.trim();return n&&!Yn(n)?n:r&&!Yn(r)?r:n||r||o}function ar(t){return ai.test(t.trim())}function De(t){let e=t.trim().replace(/\([^)]*\)$/,""),n=wt(e);return ci.test(n)}function Rt(t){let e=t.trim();return e?lt.test(e)||ar(e)||De(e)?!0:!!ut(e).symbolName:!1}function pi(t){let e=t.trim();return!(!e||ar(e)||De(e))}function gi(t){let e=new Set,n=[];for(let r of t){let o=r.trim();!pi(o)||e.has(o)||(e.add(o),n.push(o))}return n}function Vn(t){if(!t.includes("."))return 0;let e=t.split(".").pop()??"";return/^[a-z]/.test(e)?1:2}function hi(t,e){let n=Vn(t)-Vn(e);return n!==0?n:t.localeCompare(e)}function cr(t,e=[]){let n=[...new Set(e.map(i=>i.trim()).filter(Boolean))],r=new Set(n),o=[...new Set(t.map(i=>i.trim()).filter(Boolean))].filter(i=>!r.has(i));return o.sort(hi),[...n,...o].slice(0,$e)}function Ot(t){return t.replace(/\s+/g," ").trim()}function Kn(t){return t.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function Si(t,e=""){let n=t.split(/\r?\n/),r=0;for(;r<n.length&&!n[r].trim();)r+=1;if(r>=n.length)return e;let o=Kn(n[r].trim()),i=o.match(/^#+\s+(.+)$/);if(i)return Kn(i[1].trim());if(r+1<n.length){let s=n[r+1].trim();if(/^=+$/.test(s)||/^-+$/.test(s))return o}return o||e}function ur(t){let e=Ot(t.join(" "));if(e.length<=dt)return e;let n=e.slice(0,dt);return e.length<=dt+Mt?n:`${n} ${e.slice(-Mt)}`}function yi(t){let e=gi(t).join(" ");return e.length<=kt?e:e.slice(0,kt)}function lr(t){let e=Ot(t),{text:n,excerptTruncated:r}=Hn(e,Ge);return{leadText:n,excerptTruncated:r}}function xi(t,e){let{leadText:n,excerptTruncated:r}=lr(t);return{leadText:n,excerptTruncated:r||!!e.trim()}}function dr(t,e){if(t.type==="code"){e.codeBlocks.push(t.value??"");return}if("children"in t&&Array.isArray(t.children)){for(let r of t.children)dr(r,e);return}let n=Ot(Ct(t));n&&e.bodyParts.push(n)}function _i(t){let e=nr().use(rr).use(or).parse(t),n=[],r=null,o=()=>{r&&((r.sectionTitle||r.bodyParts.length||r.codeBlocks.length)&&n.push(r),r=null)},i=()=>{r||(r={sectionTitle:"",bodyParts:[],codeBlocks:[]})};for(let s of e.children){if(s.type==="heading"){let a=s,c=Ct(a).trim();if(a.depth>=4&&c&&Rt(c)){o(),r={sectionTitle:c,bodyParts:[],codeBlocks:[]};continue}i(),c&&r.bodyParts.push(c);continue}i(),dr(s,r)}return o(),n.length===0?[{sectionTitle:"",bodyParts:[],codeBlocks:[]}]:n}function Ei(t){return Pe.test(t)}function bi(t){return t.filter(e=>e.sectionTitle&&Rt(e.sectionTitle)).length}function Ai(t){return{sectionTitle:t.map(e=>e.sectionTitle.trim()).join(" | "),bodyParts:t.flatMap(e=>e.bodyParts).slice(0,40),codeBlocks:t.flatMap(e=>e.codeBlocks).slice(0,8)}}function tr(t){let e=t.trim();return!e||lt.test(e)?lt.test(e):/对象说明$|枚举说明$/.test(e)?!0:De(e)}function Di(t){let e=t.filter(d=>!d.sectionTitle||!Rt(d.sectionTitle)),n=t.filter(d=>d.sectionTitle&&Rt(d.sectionTitle)),r=n.filter(d=>tr(d.sectionTitle)),o=n.filter(d=>!tr(d.sectionTitle)),i=Math.max(0,Ne-r.length),s=o.slice(0,i),a=o.slice(i),c=a.filter(d=>er(d.sectionTitle)),f=a.filter(d=>!er(d.sectionTitle)),p=[];for(let d=0;d<f.length;d+=Bt)p.push(Ai(f.slice(d,d+Bt)));return[...e,...r,...s,...c,...p]}function Ii(t,e,n){let r=t.split(/\r?\n/).length,o=bi(e);return o===0?!1:Ei(n)?r>=Re&&o>=Oe:r>=we&&o>=Ce}var Ti=/^\[h2\][A-Za-z]/;function er(t){return Ti.test(t.trim())}function mr(t){if(!t.includes(" | ")){let n=ut(t);return n.symbolName?[n.symbolName]:[]}let e=[];for(let n of t.split(" | ")){let r=ut(n.trim()).symbolName;r&&e.push(r)}return e}function wi(t,e,n,r){let o=mr(t),i=ir(n,r);return e.symbolName&&i.push(e.symbolName),cr([...o,...i],o)}function Ci(t,e){let n=ur(t.bodyParts),r=t.sectionTitle.trim(),o=ut(r),i=Qn(t.bodyParts),s=Jn(r,i,o),a=mr(r),c=r?a.length>0?`${e.docTitle} ${a.join(" ")}`:`${e.docTitle} ${o.symbolName??r}`:e.docTitle,f=[e.docTitle,s,...t.bodyParts].join(" "),{leadText:p,excerptTruncated:d}=xi(n,r);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:e.docTitle,sectionTitle:r,titleTokens:c,headingsText:s,apiSymbols:wi(r,o,f,t.codeBlocks),bodySample:n,leadText:p,excerptTruncated:d}}function fr(t,e){for(let n of t){if(n.type==="heading"){let o=Ct(n).trim();o&&e.headings.push(o);continue}if(n.type==="code"){e.codeBlocks.push(n.value??"");continue}if("children"in n&&Array.isArray(n.children)){fr(n.children,e);continue}let r=Ot(Ct(n));r&&e.bodyParts.push(r)}}function Ri(t){let e=nr().use(rr).use(or).parse(t),n={headings:[],bodyParts:[],codeBlocks:[]};return fr(e.children,n),n}function Oi(t,e){let n=Ri(t),r=e.docTitle?.trim()||e.documentId,o=ur(n.bodyParts),i=[r,...n.headings,o].join(" "),{leadText:s,excerptTruncated:a}=lr(o);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:r,sectionTitle:"",titleTokens:r,headingsText:yi(n.headings),apiSymbols:cr(ir(i,n.codeBlocks)),bodySample:o,leadText:s,excerptTruncated:a}}function pr(t,e){let n=e.docTitle?.trim()||e.documentId,r=_i(t);return Ii(t,r,e.documentId)?Di(r).filter(o=>o.sectionTitle||o.bodyParts.length>0||o.codeBlocks.length>0).map(o=>Ci(o,{...e,docTitle:n})):[Oi(t,{...e,docTitle:n})]}function gr(t,e){let n=qe[t];if(n===void 0||e.length<1)return null;let r=e[e.length-1].replace(/\.md$/,"");return{documentId:[t,...e.slice(0,-1),r].join("/"),catalogId:n,docTitle:r}}function hr(t){let e=t.split("/");if(e[0]==="docs"&&(e=e.slice(1)),e[0]===Ft&&e[1]===vt){let n=zt[e[2]];return n===void 0?null:gr(B[n],e.slice(3))}return gr(e[0],e.slice(1))}function Sr(t,e,n){let r=sr(t,{jsonTitle:e,fileName:n.docTitle});return pr(t,{...n,docTitle:r})}function Pi(t){return t.getEntries().filter(e=>e.isDirectory||!e.entryName.endsWith(".md")?!1:e.entryName.split("/").every(n=>!n.startsWith(".")))}function Li(t,e){let n=t.getEntry(e.replace(/\.md$/,".json"));if(n)try{return JSON.parse(n.getData().toString("utf-8")).title?.trim()||void 0}catch{return}}function Bi(t){let e=new Ni(t),n=[];for(let r of Pi(e)){let o=hr(r.entryName);o&&n.push(...Sr(r.getData().toString("utf-8"),Li(e,r.entryName),o))}return n}async function Mi(t){let e=[];async function n(r){let o=await Y.promises.readdir(r,{withFileTypes:!0});for(let i of o){if(i.name.startsWith("."))continue;let s=L.join(r,i.name);i.isDirectory()?await n(s):i.isFile()&&i.name.endsWith(".md")&&e.push(s)}}return await n(t),e}async function ki(t){let e=t.replace(/\.md$/,".json");try{let n=await Y.promises.readFile(e,"utf-8");return JSON.parse(n).title?.trim()||void 0}catch{return}}async function Fi(t){let e=[];for(let n of await Mi(t)){let r=L.relative(t,n).split(L.sep).join("/"),o=hr(r);if(!o)continue;let i=await Y.promises.readFile(n,"utf-8");e.push(...Sr(i,await ki(n),o))}return e}async function vi(t){return"docsZipPath"in t?Bi(t.docsZipPath):Fi(t.docsDir)}async function zi(t,e,n){let r=L.join(e,"search.db");return await qn(r,t,async(o,i)=>{await n?.({current:o,total:i,message:`Building search index\u2026 ${o.toLocaleString()} / ${i.toLocaleString()} segments`})}),t.length}function Hi(t,e){return{indexVersion:z,docsZipSha256:t.docsZipSha256,termsHash:t.termsHash,synonymsHash:t.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:t.builtBy}}async function yr(t){t.lexiconDir&&Xt(t.lexiconDir);try{let e=await vi(t);await t.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await Y.promises.mkdir(t.tmpDir,{recursive:!0});let n=await zi(e,t.tmpDir,t.onProgress),r=Hi(t,n);return await Y.promises.writeFile(L.join(t.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await un(t.tmpDir),r}finally{t.lexiconDir&&Xt(null)}}async function _r(t){let e=Ut();await x.promises.mkdir(V.dirname(e),{recursive:!0}),await x.promises.appendFile(e,`${new Date().toISOString()} ${t}
66
+ `)}async function Ui(){await st({mode:"write"});let t=g(),e=I(),n=await x.promises.readdir(e);for(let r of n){let o=V.join(t,r);await x.promises.rm(o,{force:!0}),await x.promises.rename(V.join(e,r),o)}await x.promises.rm(e,{recursive:!0,force:!0}),await x.promises.rm(V.join(t,"orama.dpack"),{force:!0})}async function xr(t,e,n){e?.start(n),await N({state:"installing",phase:1,phaseLabel:"Installing index",message:n}),await fn(t),Tt(),e&&(e.text="Documentation index installed.")}async function $i(t,e){try{return await xr(t,e,"Installing documentation index\u2026"),await Ie(e),!0}catch(n){if(Vt(n))throw n}try{return await pn(),Tt(),await xr(t,e,"Retrying documentation index install\u2026"),await Ie(e),!0}catch(n){if(Vt(n))throw n;let r=n instanceof Error?n.message:String(n);return await _r(`Bundled index install failed; falling back to local rebuild: ${r}`),!1}}async function Gi(t,e,n){let r=k();if(!r)throw new Error("docs.zip not found");let o=I();await x.promises.mkdir(g(),{recursive:!0}),await x.promises.rm(o,{recursive:!0,force:!0}),n?.start("Building search index\u2026"),await N({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"}),await yr({docsZipPath:r,tmpDir:o,docsZipSha256:e,termsHash:St(),synonymsHash:ht(),builtBy:t.builtBy??"doc-init",onProgress:async i=>{n&&(n.text=i.message),await N({state:"indexing",current:i.current,total:i.total,message:i.message})}}),await N({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await Ui(),Tt()}async function Ie(t){await N({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),t?.succeed("Documentation ready.")}async function Wi(t){let e=await re(),n=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";t?.succeed(n),await N({state:"done",message:n,error:null})}async function Xi(t,e){let n=t instanceof Error?t.message:String(t);throw await N({state:"error",error:n}),await _r(`ERROR: ${n}`),e?.fail(n),t}async function qi(){let t=g();await x.promises.mkdir(t,{recursive:!0});let e=mt();return x.existsSync(e)||await x.promises.writeFile(e,"","utf-8"),e}async function Qi(){let t=await qi();return ji.lock(t,{stale:1800*1e3})}async function Ji(){let t=k(),e=(t?await gt(t):null)??await ne();if(!e)throw new Error("docs.zip not found");return e}async function Yi(t,e){let n=await Ji(),r=t.force||await En(t.force),o=await oe(t.force);if(!r&&!o&&ie()){await Wi(e);return}!t.force&&mn(n)&&await $i(n,e)||(await Gi(t,n,e),await Ie(e))}var Nt=class{static async run(e={}){let n=e.background??!1,o=e.quiet??n?void 0:Zi({text:"Checking documentation\u2026",color:"cyan"}),i;try{e.assumeStorageSafe||await st({mode:"write"}),i=await Qi(),await ee(_n("Starting documentation setup\u2026")),await Yi(e,o)}catch(s){throw i&&await Xi(s,o),s}finally{i&&await i()}}};var Vi=process.env.DEVECO_CLI_POSTINSTALL?"postinstall":"doc-init";Nt.run({background:!0,builtBy:Vi}).then(()=>{process.exit(0)}).catch(()=>{process.exit(1)});
@@ -1,5 +1,5 @@
1
1
  import Wt from"path";import*as S from"fs";import*as Y from"path";import{homedir as xt}from"os";import*as J from"fs";import*as g from"path";function N(n){let t=g.resolve(n),e=[],r=t;for(;;)try{let i=J.realpathSync(r);return e.length===0?i:g.join(i,...e.reverse())}catch(i){if(i.code!=="ENOENT")throw i;let o=g.dirname(r);if(o===r)return t;e.push(g.basename(r)),r=o}}function $(n){let t=n.trim();return(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))&&(t=t.slice(1,-1).trim()),t}function K(n){let t=$(n);if(!t)throw new Error("Path must not be empty.");return N(t)}var Et="deveco-cli",X,M=class extends Error{constructor(t){super(t),this.name="CliDataDirError"}};function wt(){let n=process.env.DEVECO_CLI_DATA_DIR,e=(n===void 0||n===""?"":$(n))||Y.join(xt(),".local","share",Et);try{return K(e)}catch(r){throw new M(r instanceof Error?r.message:String(r))}}function q(){if(X!==void 0)return X;let n=wt();try{if(S.existsSync(n))return S.realpathSync(n)}catch{}return n}import bt from"crypto";import c from"fs";import P from"os";import m from"path";import Ct from"https";var G={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var C=class n{static ENDPOINT=G.devecoApiTraceUpload;static SENDER="deveco-cli";async upload(t,e){let r={"Content-Type":"application/json",sender:n.SENDER,deviceid:e.replace(/-/g,""),"Content-Length":String(Buffer.byteLength(t,"utf8"))};try{let{body:i}=await this.httpPost(n.ENDPOINT,r,Buffer.from(t,"utf8"),6e4);return n.isSuccess(i)}catch{return!1}}static isSuccess(t){try{let e=JSON.parse(t),r=e?.code??e?.errorCode;return String(r)==="200"}catch{return!1}}async httpPost(t,e,r,i){let o=new URL(t);return new Promise((s,l)=>{let p=Ct.request({protocol:o.protocol,hostname:o.hostname,port:o.port||(o.protocol==="https:"?443:80),path:o.pathname+o.search,method:"POST",headers:e,timeout:i},h=>{let D=[];h.on("data",Tt=>D.push(Tt)),h.on("end",()=>{s({code:h.statusCode??0,body:Buffer.concat(D).toString("utf8")})})});p.on("timeout",()=>{p.destroy(new Error("request timeout"))}),p.on("error",l),p.write(r),p.end()})}};var Z={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()},j=class{constructor(t={}){this.config=t}config;serialize(t){let e=this.transform(t);return this.config.pretty?JSON.stringify(e,null,2):JSON.stringify(e)}toObject(t){return this.transform(t)}transform(t){if(t==null)return t;if(Array.isArray(t))return t.map(o=>this.transform(o));if(typeof t!="object")return t;let e=this.config.namingStrategy??Z.identity,r=this.config.fieldNames??{},i={};for(let[o,s]of Object.entries(t)){let l=r[o]??e(o);i[l]=this.transform(s)}return i}},Q=new j({namingStrategy:Z.snakeCase,fieldNames:{}});import b from"crypto";import L from"fs";import Lt from"path";var _="aes-256-gcm",_t=12,Ft="deveco-cli-trace-file",At="trace-file-secret",et=32;function tt(n){try{let t=L.readFileSync(n,"utf8").trim();return t&&Buffer.from(t,"base64").length===et?t:null}catch{return null}}function rt(n){let t=Lt.join(n,At),e=tt(t);if(e)return B(e);let r=b.randomBytes(et).toString("base64");try{L.mkdirSync(n,{recursive:!0});try{L.writeFileSync(t,r,{flag:"wx"})}catch{let i=tt(t);if(i)return B(i);L.writeFileSync(t,r)}}catch{}return B(r)}function B(n){return b.createHash("sha256").update(Ft).update(n).digest()}function nt(n,t){let e=b.randomBytes(_t),r=b.createCipheriv(_,t,e),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o={version:1,algorithm:_,ciphertext:i.toString("base64"),iv:e.toString("base64"),authTag:r.getAuthTag().toString("base64")};return JSON.stringify(o)}function it(n,t){let e;try{e=JSON.parse(n)}catch{return null}if(!kt(e))return n;try{let r=b.createDecipheriv(_,t,Buffer.from(e.iv,"base64"));return r.setAuthTag(Buffer.from(e.authTag,"base64")),Buffer.concat([r.update(Buffer.from(e.ciphertext,"base64")),r.final()]).toString("utf8")}catch{return null}}function kt(n){if(!n||typeof n!="object")return!1;let t=n;return t.version===1&&t.algorithm===_&&typeof t.ciphertext=="string"&&typeof t.iv=="string"&&typeof t.authTag=="string"}import*as a from"fs";import*as A from"path";import*as T from"os";import*as y from"path";import ve from"json5";import*as ot from"os";function U(){return It().toLowerCase().includes("openharmony")}function It(){return ot.platform()}var Te=[U()?".bitfun":".idea",".deveco",U()?".cxx":"cxx","compile_commands.json"];function st(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??y.join(T.homedir(),"AppData","Local");return y.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?y.join(T.homedir(),"Library","Logs","devecocli-mcp-server"):y.join(T.homedir(),".local","share","devecocli-mcp-server","logs")}var at="mcp-server.log",Ot="mcp-server",Rt={maxSize:10*1024*1024,maxFiles:4},V=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(t,e){this.rotationOptions={...Rt,...e},this.minLevel=t?"debug":"info",t?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=st(),this.currentLogFile=A.join(this.logDir,at),a.existsSync(this.logDir)||a.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let t=new Date,e=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0");return`${e}-${r}-${i}`}getRotatedFileName(t,e){return A.join(this.logDir,`${Ot}-${t}.log.${e}`)}fileExists(t){try{return a.accessSync(t,a.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let t=a.readdirSync(this.logDir),e=[];for(let i of t)if(i===at||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=A.join(this.logDir,i),s=a.statSync(o);e.push({name:i,mtime:s.mtime,path:o})}e.sort((i,o)=>o.mtime.getTime()-i.mtime.getTime());let r=1+this.rotationOptions.maxFiles;for(let i=r;i<e.length;i++)try{a.unlinkSync(e[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 t=this.getCurrentDateString(),e=this.getRotatedFileName(t,this.rotationOptions.maxFiles);this.fileExists(e)&&a.unlinkSync(e);for(let i=this.rotationOptions.maxFiles-1;i>=1;i--){let o=this.getRotatedFileName(t,i),s=this.getRotatedFileName(t,i+1);this.fileExists(o)&&a.renameSync(o,s)}let r=this.getRotatedFileName(t,1);a.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 t=a.statSync(this.currentLogFile);this.currentFileSize=t.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=a.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{a.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(t){let e=this.getCurrentDateString();this.currentDate&&this.currentDate!==e&&(this.rotateLog(),this.currentDate=e),this.currentFileSize+=t,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(t,e,...r){if(this.mode==="silent"||n.LEVEL_ORDER[t]<n.LEVEL_ORDER[this.minLevel])return;let i=r.map(p=>p instanceof Error?`${p.name}: ${p.message}`:typeof p=="object"?JSON.stringify(p,null,2):String(p)).join(" "),o=i?`${e} ${i}`:e,l=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${t.toUpperCase()}] ${o}
2
- `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let p=Buffer.from(l);a.writeSync(this.fd,p),this.checkRotation(p.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(l)}debug(t,...e){this.write("debug",t,...e)}info(t,...e){this.write("info",t,...e)}warn(t,...e){this.write("warn",t,...e)}error(t,...e){this.write("error",t,...e)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{a.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},x=null;function Pt(n=!1){x&&x.dispose(),x=new V(n)}function F(){return x||Pt(!1),x}var u={debug:(n,...t)=>F().debug(n,...t),info:(n,...t)=>F().info(n,...t),warn:(n,...t)=>F().warn(n,...t),error:(n,...t)=>F().error(n,...t)};import ct from"fs";import Nt from"path";var k=300*1e3,I=3600*1e3,ut=10080*60*1e3,v=8*1024*1024,pt=3600*1e3,lt=".pending",$t=/\.reclaim-\d+-\d+$/;function O(){let n=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return n==="1"||n==="true"}var Mt="upload-state.json";function ft(n){return Nt.join(n,Mt)}function jt(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function z(n){try{let t=ct.readFileSync(ft(n),"utf8"),e=JSON.parse(t);return{firstEventAt:typeof e.firstEventAt=="number"?e.firstEventAt:null,lastUploadAt:typeof e.lastUploadAt=="number"?e.lastUploadAt:null,lastRetryAt:typeof e.lastRetryAt=="number"?e.lastRetryAt:null}}catch{return jt()}}function H(n,t){try{ct.writeFileSync(ft(n),JSON.stringify(t),"utf8")}catch{}}function dt(n){let t=z(n);t.firstEventAt===null&&(t.firstEventAt=Date.now(),H(n,t))}function mt(n){let t=z(n);t.lastUploadAt=Date.now(),t.firstEventAt=null,H(n,t)}function gt(n){let t=z(n);t.lastRetryAt=Date.now(),H(n,t)}function ht(n){let t=n.match(/^telemetry-(\d{4})-(\d{2})-(\d{2})\.txt$/);if(!t)return null;let e=Date.parse(`${t[1]}-${t[2]}-${t[3]}T00:00:00`);return Number.isFinite(e)?e:null}function W(n){if(!n.startsWith("telemetry-"))return null;let t=$t.exec(n),e=t?n.slice(0,t.index):n;if(!e.endsWith(lt))return null;let r=e.slice(0,-lt.length);return r.endsWith(".txt")?r:null}function yt(n){return W(n)!==null}import Bt from"crypto";import R from"fs";import Ut from"path";var Vt="install-id";function zt(n){return Ut.join(n,Vt)}function vt(n){try{let t=R.readFileSync(n,"utf8").trim();return Ht(t)?t:null}catch{return null}}function Ht(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 St(n){let t=zt(n),e=vt(t);if(e)return e;let r=Bt.randomUUID();try{R.mkdirSync(n,{recursive:!0});try{R.writeFileSync(t,r,{flag:"wx"})}catch{let i=vt(t);if(i)return i;R.writeFileSync(t,r)}}catch{}return r}var E=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 C;storageDir="";failedDir="";installId="";disabled=O();traceFileKey=Buffer.alloc(0);sessionId=bt.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){u.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(t){this.storageDir=t,this.failedDir=m.join(t,"failed"),this.cliVersion="1.3.12-Test.1",this.nodeVersion=process.version,this.installId=St(t).replace(/-/g,""),this.traceFileKey=rt(t),c.mkdirSync(t,{recursive:!0}),c.mkdirSync(this.failedDir,{recursive:!0}),u.debug(`[telemetry] init: dir=${t}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(t){this.devecoStudioVersion=t,u.debug(`[telemetry] studio version set: ${t}`)}setSourceType(t){this.sourceType=t,u.debug(`[telemetry] sourceType set: ${t}`)}setCltVersion(t){this.cltVersion=t,u.debug(`[telemetry] CLT version set: ${t}`)}async track(t,e){if(this.disabled)return typeof e=="function"?e():void 0;if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");if(!e){await this.record(t,0,!0,null);return}if(typeof e!="function"){let o=e;await this.record(t,o.duration_ms,o.success,o.error_code);return}let r=e,i=Date.now();try{let o=await r(),s=Date.now()-i;return await this.record(t,s,!0,null),o}catch(o){let s=Date.now()-i,l=this.toErrorCode(o);throw await this.record(t,s,!1,l),o}}async record(t,e,r,i){let o=this.buildTraceEvent(t,e,r,i);try{let s=nt(JSON.stringify(o),this.traceFileKey);await c.promises.appendFile(this.currentFile(),s+`
2
+ `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let p=Buffer.from(l);a.writeSync(this.fd,p),this.checkRotation(p.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(l)}debug(t,...e){this.write("debug",t,...e)}info(t,...e){this.write("info",t,...e)}warn(t,...e){this.write("warn",t,...e)}error(t,...e){this.write("error",t,...e)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{a.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},x=null;function Pt(n=!1){x&&x.dispose(),x=new V(n)}function F(){return x||Pt(!1),x}var u={debug:(n,...t)=>F().debug(n,...t),info:(n,...t)=>F().info(n,...t),warn:(n,...t)=>F().warn(n,...t),error:(n,...t)=>F().error(n,...t)};import ct from"fs";import Nt from"path";var k=300*1e3,I=3600*1e3,ut=10080*60*1e3,v=8*1024*1024,pt=3600*1e3,lt=".pending",$t=/\.reclaim-\d+-\d+$/;function O(){let n=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return n==="1"||n==="true"}var Mt="upload-state.json";function ft(n){return Nt.join(n,Mt)}function jt(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function z(n){try{let t=ct.readFileSync(ft(n),"utf8"),e=JSON.parse(t);return{firstEventAt:typeof e.firstEventAt=="number"?e.firstEventAt:null,lastUploadAt:typeof e.lastUploadAt=="number"?e.lastUploadAt:null,lastRetryAt:typeof e.lastRetryAt=="number"?e.lastRetryAt:null}}catch{return jt()}}function H(n,t){try{ct.writeFileSync(ft(n),JSON.stringify(t),"utf8")}catch{}}function dt(n){let t=z(n);t.firstEventAt===null&&(t.firstEventAt=Date.now(),H(n,t))}function mt(n){let t=z(n);t.lastUploadAt=Date.now(),t.firstEventAt=null,H(n,t)}function gt(n){let t=z(n);t.lastRetryAt=Date.now(),H(n,t)}function ht(n){let t=n.match(/^telemetry-(\d{4})-(\d{2})-(\d{2})\.txt$/);if(!t)return null;let e=Date.parse(`${t[1]}-${t[2]}-${t[3]}T00:00:00`);return Number.isFinite(e)?e:null}function W(n){if(!n.startsWith("telemetry-"))return null;let t=$t.exec(n),e=t?n.slice(0,t.index):n;if(!e.endsWith(lt))return null;let r=e.slice(0,-lt.length);return r.endsWith(".txt")?r:null}function yt(n){return W(n)!==null}import Bt from"crypto";import R from"fs";import Ut from"path";var Vt="install-id";function zt(n){return Ut.join(n,Vt)}function vt(n){try{let t=R.readFileSync(n,"utf8").trim();return Ht(t)?t:null}catch{return null}}function Ht(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 St(n){let t=zt(n),e=vt(t);if(e)return e;let r=Bt.randomUUID();try{R.mkdirSync(n,{recursive:!0});try{R.writeFileSync(t,r,{flag:"wx"})}catch{let i=vt(t);if(i)return i;R.writeFileSync(t,r)}}catch{}return r}var E=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 C;storageDir="";failedDir="";installId="";disabled=O();traceFileKey=Buffer.alloc(0);sessionId=bt.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){u.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(t){this.storageDir=t,this.failedDir=m.join(t,"failed"),this.cliVersion="0.4.0",this.nodeVersion=process.version,this.installId=St(t).replace(/-/g,""),this.traceFileKey=rt(t),c.mkdirSync(t,{recursive:!0}),c.mkdirSync(this.failedDir,{recursive:!0}),u.debug(`[telemetry] init: dir=${t}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(t){this.devecoStudioVersion=t,u.debug(`[telemetry] studio version set: ${t}`)}setSourceType(t){this.sourceType=t,u.debug(`[telemetry] sourceType set: ${t}`)}setCltVersion(t){this.cltVersion=t,u.debug(`[telemetry] CLT version set: ${t}`)}async track(t,e){if(this.disabled)return typeof e=="function"?e():void 0;if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");if(!e){await this.record(t,0,!0,null);return}if(typeof e!="function"){let o=e;await this.record(t,o.duration_ms,o.success,o.error_code);return}let r=e,i=Date.now();try{let o=await r(),s=Date.now()-i;return await this.record(t,s,!0,null),o}catch(o){let s=Date.now()-i,l=this.toErrorCode(o);throw await this.record(t,s,!1,l),o}}async record(t,e,r,i){let o=this.buildTraceEvent(t,e,r,i);try{let s=nt(JSON.stringify(o),this.traceFileKey);await c.promises.appendFile(this.currentFile(),s+`
3
3
  `,"utf8"),dt(this.storageDir)}catch{}}buildTraceEvent(t,e,r,i){let o=`${n.EVENT_PREFIX}${t.event}`,s=Q.toObject(t);return s&&typeof s=="object"&&delete s.event,{countryCode:n.COUNTRY_CODE,event:o,eventtime:String(Date.now()),properties:{uid:this.installId,trace_uuid:bt.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:e,success:r,error_code:i,event_detail:s}}}toErrorCode(t){return t instanceof Error?t.code??t.name:"UnknownError"}resolveOsArch(){let t=P.arch();return t==="x64"?"amd64":t}resolveOsName(){switch(process.platform){case"win32":{let t=P.release().split(".");return(parseInt(t[t.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 P.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(P.totalmem()/1024)}KB`}formatVersion(t){return t?`${t}_${this.resolveOsSuffix()}`:""}dateString(){let t=new Date,e=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${t.getFullYear()}-${e}-${r}`}currentFile(){return m.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){u.debug("[telemetry] scheduler not started (telemetry disabled)");return}u.debug(`[telemetry] scheduler started (flush every ${k/1e3}s, retry failed every ${I/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},k)},k),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},I)},I)}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),u.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 t=await this.listPendingFiles(),e=!0;for(let r of t)await this.flushFile(r)||(e=!1);return mt(this.storageDir),e}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 t=Date.now(),e;try{e=await c.promises.readdir(this.failedDir)}catch{return!0}let r=e.filter(o=>o.startsWith("telemetry-")&&o.endsWith(".txt")).map(o=>m.join(this.failedDir,o)),i=!0;for(let o of r){let s=m.basename(o),l=ht(s);if(l!==null){if(t-l>ut){try{await c.promises.unlink(o)}catch{}continue}await this.flushFile(o)||(i=!1)}}return i||u.warn("[telemetry] retry failed"),gt(this.storageDir),i}async reclaimStalePending(){let t=Date.now();for(let e of[this.storageDir,this.failedDir]){let r;try{r=await c.promises.readdir(e)}catch{continue}for(let i of r)yt(i)&&await this.reclaimOrphan(m.join(e,i),t)}}async reclaimOrphan(t,e){let r;try{let h=await c.promises.stat(t);if(e-h.mtimeMs<pt)return;r=h.size}catch{return}let i=m.dirname(t),o=W(m.basename(t));if(o===null)return;let s=await this.claimOrphan(t,i,o);if(s===null)return;let l=m.join(i,o),p=v-await this.fileSize(l);if(r>p){try{await c.promises.unlink(s)}catch{}u.warn(`[telemetry] dropped stale orphan pending: ${s} (${r} bytes > budget ${p})`);return}if(await this.mergeOrphanInto(s,l)){u.warn(`[telemetry] reclaimed orphan pending: ${s} (${r} bytes)`);return}u.warn(`[telemetry] merge failed, kept orphan pending for retry: ${s} (${r} bytes)`)}async claimOrphan(t,e,r){let i=m.join(e,`${r}.pending.reclaim-${process.pid}-${Date.now()}`);try{await c.promises.rename(t,i)}catch{return null}return await this.touch(i),i}async mergeOrphanInto(t,e){try{await c.promises.appendFile(e,await c.promises.readFile(t))}catch(r){return u.warn(`[telemetry] merge orphan pending failed: ${t} -> ${e}: ${r instanceof Error?r.message:String(r)}`),!1}try{await c.promises.unlink(t)}catch(r){u.warn(`[telemetry] merged but failed to remove orphan pending: ${t}: ${r instanceof Error?r.message:String(r)}`)}return!0}async fileSize(t){try{return(await c.promises.stat(t)).size}catch{return 0}}async touch(t){let e=new Date;try{await c.promises.utimes(t,e,e)}catch{}}runExclusive(t){let e=()=>t(),r=this.flushChain.then(e,e);return this.flushChain=r.then(()=>{},()=>{}),r}async listPendingFiles(){let t;try{t=await c.promises.readdir(this.storageDir)}catch{return[]}return t.filter(e=>e.startsWith("telemetry-")&&e.endsWith(".txt")).map(e=>m.join(this.storageDir,e)).sort()}async flushFile(t){let e=await this.fileSize(t);if(e>v){u.warn(`[telemetry] ${m.basename(t)} is ${e} bytes (> ${v}), dropped without uploading`);try{await c.promises.unlink(t)}catch{}return!0}let r=t+".pending";try{await c.promises.rename(t,r)}catch{return!1}await this.touch(r);let i;try{i=await c.promises.readFile(r,"utf8")}catch{return!1}let o=i.split(`
4
4
  `).map(s=>s.trim()).filter(Boolean);if(o.length===0){try{await c.promises.unlink(r)}catch{}return!0}return this.uploadInBatches(r,o)}collectDecryptBatch(t,e){let r=[],i=16,o=e;for(;o<t.length&&r.length<n.MAX_BATCH;){let s=it(t[o],this.traceFileKey);if(s===null){o++;continue}let l=Buffer.byteLength(s,"utf8")+1;if(r.length>0&&i+l>n.MAX_PAYLOAD_BYTES)break;r.push(s),i+=l,o++}return{batch:r,next:o}}async uploadInBatches(t,e){let r=0;for(;r<e.length;){let i=r,{batch:o,next:s}=this.collectDecryptBatch(e,r);r=s;let l=this.buildPayloadItems(o);if(l.length===0)continue;let p=JSON.stringify(l),h=!1;try{h=await this.uploader.upload(p,this.installId)}catch{}if(!h){u.warn("[telemetry] upload failed");let D=e.slice(i).join(`
5
5
  `)+`
package/docs.zip CHANGED
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/docs.zip
3
- size: 40538363 bytes
4
- sha256: 69cea82c1729991ed37837dc115cb43463b45b6381de6005f9d0c153399f6d1f
3
+ size: 54562672 bytes
4
+ sha256: 5597a86cdacbb9448f980562a6eff021f05aa2628f748bf2036657bd2d40d6d5
package/index.zip CHANGED
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deveco-test/deveco-cli-openharmony-arm64",
3
- "version": "1.3.12-Test.1",
3
+ "version": "1.3.12-Test.2",
4
4
  "description": "HarmonyOS application development command line tool",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -39,12 +39,6 @@
39
39
  "engines": {
40
40
  "node": ">=18"
41
41
  },
42
- "os": [
43
- "openharmony"
44
- ],
45
- "cpu": [
46
- "arm64"
47
- ],
48
42
  "keywords": [
49
43
  "harmonyos",
50
44
  "deveco",
@@ -101,10 +95,15 @@
101
95
  },
102
96
  "optionalDependencies": {
103
97
  "@node-rs/jieba": "^2.0.1",
104
- "@node-rs/jieba-wasm32-wasi": "2.0.1",
105
- "better-sqlite3": "^12.11.1"
98
+ "@node-rs/jieba-wasm32-wasi": "2.0.1"
106
99
  },
107
100
  "overrides": {
108
101
  "dotenv": "16.4.7"
109
- }
102
+ },
103
+ "os": [
104
+ "openharmony"
105
+ ],
106
+ "cpu": [
107
+ "arm64"
108
+ ]
110
109
  }