@deveco-test/deveco-cli-openharmony-arm64 1.3.6-Test.1 → 1.3.11-Test.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +844 -837
- package/SKILL.md +190 -187
- package/THIRD-PARTY-LICENSES +342 -233
- package/dist/cli.js +135 -137
- package/dist/internal/doc-init-background.js +9 -9
- package/dist/internal/telemetry-upload-background.js +1 -1
- package/index.zip +0 -0
- package/package.json +110 -108
- package/scripts/install-better-sqlite3.mjs +51 -51
- package/scripts/install-jieba-wasm.mjs +47 -47
- package/scripts/lib/better-sqlite3-vendor.mjs +128 -128
- package/scripts/lib/cli-data-dir.mjs +44 -44
- package/scripts/lib/doc-init-log-path.mjs +15 -15
- package/scripts/lib/jieba-wasm-vendor.mjs +102 -102
- package/scripts/postinstall.mjs +64 -64
- package/src/resources/aclPermission/aclPermissionsInfo.json +310 -310
- package/templates/application/AppScope/app.json5 +10 -10
- package/templates/application/AppScope/resources/base/element/string.json +8 -8
- package/templates/application/AppScope/resources/base/media/layered_image.json +6 -6
- package/templates/application/build-profile.json5 +41 -41
- package/templates/application/code-linter.json5 +31 -31
- package/templates/application/entry/build-profile.json5 +32 -32
- package/templates/application/entry/gitignore.txt +5 -5
- package/templates/application/entry/hvigorfile.ts +7 -7
- package/templates/application/entry/obfuscation-rules.txt +19 -19
- package/templates/application/entry/oh-package.json5 +10 -10
- package/templates/application/entry/src/main/ets/entryability/EntryAbility.ets +62 -62
- package/templates/application/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets +30 -30
- package/templates/application/entry/src/main/ets/pages/Index.ets +37 -37
- package/templates/application/entry/src/main/module.json5 +49 -49
- package/templates/application/entry/src/main/resources/base/element/color.json +7 -7
- package/templates/application/entry/src/main/resources/base/element/float.json +8 -8
- package/templates/application/entry/src/main/resources/base/element/string.json +15 -15
- package/templates/application/entry/src/main/resources/base/media/layered_image.json +6 -6
- package/templates/application/entry/src/main/resources/base/profile/backup_config.json +2 -2
- package/templates/application/entry/src/main/resources/base/profile/main_pages.json +5 -5
- package/templates/application/entry/src/main/resources/dark/element/color.json +7 -7
- package/templates/application/gitignore.txt +11 -11
- package/templates/application/hvigor/hvigor-config.json5 +23 -23
- package/templates/application/hvigorfile.ts +7 -7
- package/templates/application/oh-package.json5 +10 -10
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import*as h from"fs";import*as T from"path";import Mi from"adm-zip";import ki from"proper-lockfile";import vi from"ora";import*as A from"fs";import*as at from"path";var Bt=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],dt={"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 H="1.9.1",Vi=48*1024*1024,Ae=280,De=6,Ie=100,Te=3,Ce=28,Mt=10,Re=/API参考|APIReference/i;var Ne=6,mt=700,kt=250,vt=400,Pe=1320,Oe=120,Le=450,Be=250,Me=500,ke=480,ve=80,Fe=200,ze=60,He=200,je=40,Ue=200,Ze=200,$e=40,j=500,Ge=Object.fromEntries(Bt.map((t,e)=>[dt[t],e])),O=Object.fromEntries(Bt.map((t,e)=>[t,e]));import*as tt from"fs";import*as m from"path";import{fileURLToPath as Ve}from"url";import*as L from"fs";import*as Qe from"path";import{homedir as xr}from"os";import*as Xe from"fs";import*as E from"path";function V(t,e){let n=E.relative(e,t);return n===""||!E.isAbsolute(n)&&!n.startsWith(`..${E.sep}`)&&n!==".."}function U(t){let e=E.resolve(t),n=[],r=e;for(;;)try{let o=Xe.realpathSync(r);return n.length===0?o:E.join(o,...n.reverse())}catch(o){if(o.code!=="ENOENT")throw o;let i=E.dirname(r);if(i===r)return e;n.push(E.basename(r)),r=i}}function We(t,e){let n=U(e),r=U(t);return V(r,n)?r:null}function Ft(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=Ft(t);if(!e)throw new Error("Path must not be empty.");return U(e)}var Er="deveco-cli",zt,k=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===""?"":Ft(t))||Qe.join(xr(),".local","share",Er);try{return qe(n)}catch(r){throw new k(r instanceof Error?r.message:String(r))}}async function Ye(){let t=Je();await L.promises.mkdir(t,{recursive:!0});let e;try{e=await L.promises.realpath(t)}catch(r){throw new k(`DEVECO_CLI_DATA_DIR is not usable: ${r instanceof Error?r.message:String(r)}`)}if(!(await L.promises.stat(e)).isDirectory())throw new k("DEVECO_CLI_DATA_DIR must be a writable directory.");return zt=e,e}function K(){if(zt!==void 0)return zt;let t=Je();try{if(L.existsSync(t))return L.realpathSync(t)}catch{}return t}var _r="docs";function Z(){return m.join(K(),_r)}function g(){return m.join(Z(),".index")}function ft(){return m.join(g(),"build.lock")}function et(){return m.join(g(),"build-status.json")}function $(){return m.join(g(),"build-meta.json")}function G(){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 C(){return m.join(g(),".tmp")}function br(){return m.join(K(),"logs")}function Ht(){return m.join(br(),"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 Ke(t,e){return m.dirname(wr(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=tt.realpathSync(e);for(let r of Ar(...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(!V(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 v(){return en("docs.zip")}function jt(){return en("index.zip")}function nn(){return m.join(tn(),"index","data")}import*as R from"fs";import*as F from"path";var N=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],Ut=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};var Zt=null;function $t(t){Zt=t}function rn(){if(Zt)return Zt;let t=g();if(N.every(o=>R.existsSync(F.join(t,o))))return t;let n=nn();if(N.every(o=>R.existsSync(F.join(n,o))))return n;throw new Ut("Lexicon files not found. Install the documentation index first (index.zip).")}function X(t){let e=F.join(rn(),t);return R.readFileSync(e,"utf-8")}function on(t,e){return R.readFileSync(F.join(e,t),"utf-8")}async function sn(t,e=rn()){await R.promises.mkdir(t,{recursive:!0});for(let n of N){let r=F.join(e,n),o=F.join(t,n);await R.promises.copyFile(r,o)}}import*as Gt from"fs";import*as Dr from"yauzl";function Xt(){let t=v();return t!==null&&Gt.existsSync(t)}import*as y from"fs";import*as P from"path";import an from"adm-zip";import*as ot from"fs";import*as gt from"path";var pt=class extends Error{constructor(e){super(`Unsafe documentation path: ${e}`),this.name="DocPathSafetyError"}};function Qt(t){return t instanceof k||t instanceof pt||t instanceof Error&&(t.name==="CliDataDirError"||t.name==="DocPathSafetyError")}function Jt(t){return new pt(t)}function Ir(){return U(K())}function qt(t,e,n){let r=We(t,e);if(r===null)throw Jt(`${n} resolves outside the data directory.`);return r}async function Wt(t,e){await ot.promises.mkdir(t,{recursive:!0});let n=qt(t,e,"directory");if(!(await ot.promises.stat(n)).isDirectory())throw Jt("path must be a directory.")}function it(t){let e=Ir();try{let n=qt(t,e,"file");if(!ot.statSync(n).isFile())throw Jt("path must be a regular file.")}catch(n){if(n.code==="ENOENT"){qt(gt.dirname(t),e,"file parent");return}throw n}}async function st(t={}){let e=t.mode??"write",n=await Ye();await Wt(Z(),n),await Wt(g(),n),e==="write"&&await Wt(C(),n);for(let r of[G(),$(),et(),ft(),rt(),nt(),...N.map(o=>gt.join(g(),o))])it(r)}var Yt=["search.db","build-meta.json",...N],Tr=["corpus.json","corpus-offsets.json","orama.dpack"];async function Cr(t){for(let e of Tr)await y.promises.rm(P.join(t,e),{force:!0})}async function Rr(t){let e=await y.promises.readdir(t,{withFileTypes:!0});for(let n of e)n.name!==".index"&&await y.promises.rm(P.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 y.promises.mkdir(e,{recursive:!0});for(let n of Yt){let r=P.join(e,n);await y.promises.rm(r,{force:!0}),await y.promises.rename(P.join(t,n),r)}await Cr(e),await y.promises.rm(C(),{recursive:!0,force:!0})}function un(t){let e=jt();if(!e)return!1;try{let n=cn(e);return n.indexVersion===H&&n.docsZipSha256===t&&n.segmentCount>0}catch{return!1}}async function ln(t){await st({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=C();await y.promises.rm(r,{recursive:!0,force:!0}),await y.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 y.promises.writeFile(P.join(r,s),a.getData())}let i=JSON.parse(await y.promises.readFile(P.join(r,"build-meta.json"),"utf-8"));if(!y.existsSync(P.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await Nr(r),await y.promises.mkdir(Z(),{recursive:!0}),await Rr(Z()),i}async function dn(){await y.promises.rm(C(),{recursive:!0,force:!0});let t=g();for(let e of Yt)await y.promises.rm(P.join(t,e),{force:!0})}import{createHash as mn}from"crypto";import*as fn from"fs";async function ht(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):X(t);return pn(n)}function St(t){return gn("harmonyos-synonyms.json",t)}function yt(t){return gn("harmonyos-terms.txt",t)}var Pr={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function hn(){try{let t=await A.promises.readFile(et(),"utf-8");return JSON.parse(t)}catch{return{...Pr}}}async function Vt(t){let e=et();await A.promises.mkdir(at.dirname(e),{recursive:!0}),await A.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 B(t){let n={...await hn(),...t,updatedAt:Date.now()};return await Vt(n),n}async function Kt(){let t=v();return t?ht(t):null}async function te(){try{let t=await A.promises.readFile($(),"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!==H?"engine-upgraded":e.termsHash!==yt()?"terms-changed":e.synonymsHash!==St()?"synonyms-changed":null}function ne(){if(!Xt()||!A.existsSync(G())||!A.existsSync($()))return!1;let t=at.dirname(G());if(!N.every(e=>A.existsSync(at.join(t,e))))return!1;try{let e=A.readFileSync($(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function yn(t=!1){return t?!0:Xt()?ne()?await ee()!==null:!0:!1}import*as x from"fs";import*as mr from"os";import*as _ from"path";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 Or=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,Lr=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,Br=/[A-Z][a-zA-Z0-9]{2,}/g,Mr=/@[A-Z][a-zA-Z0-9]*/g,kr=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,bn=6,vr=/^[a-z][a-z0-9]{2,}$/,Fr=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,zr=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,Hr=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,jr=/^[A-Z][a-zA-Z0-9]+$/;function re(t){return zr.test(t)}function Ur(t){return Hr.test(t)&&t.length>=bn}function Zr(t){return jr.test(t)}function oe(t){return re(t)||Ur(t)||Zr(t)}function $r(t){let e=t.trim().toLowerCase();return _n.has(e)?!1:xn.has(e)}function Gr(t,e){let n=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${t.trim().toLowerCase()}${n}${r}`}function xt(t){let n=t.replace(/^@ohos\./i,"").split(".").filter(Boolean);return n[n.length-1]?.trim()||void 0}function ie(t){return[...t.matchAll(Or)].map(e=>e[0])}function se(t,e=bn){let n=[];for(let r of t.matchAll(Lr))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 D(t,e){let n=e.trim();if(!n)return;t.add(n);let r=n.toLowerCase();r!==n&&t.add(r)}function Xr(t){let e=new Set;D(e,t);let n=xt(t);return n&&D(e,n),W([...e])}function ae(t){if(re(t))return Xr(t);let e=new Set;return D(e,t),W([...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(!vr.test(r)||En.has(r)||!$r(o))return null;let i=Gr(r,o);return{first:r,second:o,camelCase:i,lower:i.toLowerCase()}}function wn(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 An(t){let e=t.trim();if(oe(e))return ae(e);let n=new Set;for(let r of ie(t)){D(n,r);let o=xt(r);o&&D(n,o)}for(let r of se(t))D(n,r);for(let r of t.matchAll(Mr))n.add(r[0]);for(let r of t.matchAll(kr))n.add(r[0]);for(let r of t.matchAll(Br))r[0].length>=4&&n.add(r[0]);return W([...n])}function Dn(t){let e=t.trim();if(oe(e))return ae(e);let n=new Set,r=ce(e);r&&D(n,r.camelCase);for(let o of An(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 I={pureApiSymbol:/^[A-Z][a-zA-Z0-9]+$/,stageModelExact:/^Stage\s*模型$/i,stageModelEnglishExact:/^stage\s+model$/i,stageModel:/Stage\s*模型/i,stageModelEntryPage:/Stage\s*模型.*EntryAbility.*(页面|新页面)/,declarePermissionBoost:/声明.*权限|应用权限.*声明|如何声明应用权限/,declarePermissionCatalog:/如何声明应用权限/,declarePermissionTokens:/如何声明应用权限|声明应用权限/,uiAbilityLifecycleBoost:/UIAbility.*生命周期|生命周期.*UIAbility|UIAblity/i,uiAbilityLifecycleCatalog:/UIAblity.*生命周期|UIAbility.*生命周期/i,entryAbilityPage:/EntryAbility.*(页面|启动|跳转|新页面)/,stateDecoratorBoost:/@State|@Prop|@Link|@Provide|@Consume/,stateDecoratorCatalog:/@State\s*装饰器|@Prop\s*装饰器|@Link\s*装饰器/,stateManagement:/状态管理原理/,routerRoute:/Router\s+路由/,dialogPopupExact:/^Dialog\s+弹窗$/,dialogPopupBoost:/Dialog\s+弹窗/};function Tn(t){return I.pureApiSymbol.test(t.trim())}function In(t){let e=t.trim();return I.stageModelExact.test(e)||I.stageModelEnglishExact.test(e)}var Wr=[{matches:t=>I.uiAbilityLifecycleBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:t=>In(t),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:t=>!In(t)&&I.stageModel.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:t=>I.entryAbilityPage.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:t=>I.declarePermissionBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:t=>I.stateDecoratorBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:t=>I.stateManagement.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:t=>I.routerRoute.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:1.4},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]},{matches:t=>I.dialogPopupBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function qr(t,e){for(let{catalog:n,multiplier:r}of e){let o=O[n];t.set(o,(t.get(o)??1)*r)}}function Cn(t,e){for(let n of Wr)n.matches(t)&&qr(e,n.weights)}import*as Rn from"os";function le(){return Qr().toLowerCase().includes("openharmony")}function Qr(){return Rn.platform()}import*as q from"fs";import*as Pn from"path";function z(t){process.env.DEVECO_CLI_DEBUG&&process.stderr.write(`[DEBUG] ${t}
|
|
2
|
-
`)}var
|
|
3
|
-
`).map(e=>e.trim()).filter(Boolean)),
|
|
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=`
|
|
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 h from"fs";import*as T from"path";import Mi from"adm-zip";import ki fr
|
|
|
9
9
|
WHERE segments_fts MATCH ?
|
|
10
10
|
ORDER BY bm25(segments_fts)
|
|
11
11
|
LIMIT ?
|
|
12
|
-
`,
|
|
12
|
+
`,mo=`
|
|
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 h from"fs";import*as T from"path";import Mi from"adm-zip";import ki fr
|
|
|
18
18
|
WHERE segments_fts MATCH ? AND d.catalog_id = ?
|
|
19
19
|
ORDER BY bm25(segments_fts)
|
|
20
20
|
LIMIT ?
|
|
21
|
-
`,
|
|
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=`
|
|
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
|
|
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(`
|
|
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
|
|
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(`
|
|
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+=j){let f=n.slice(c,c+j),p=await Promise.all(f.map(async b=>({source:b,searchText:await bt(b)})));o.transaction(b=>{for(let S of b){let w=Lo(o,i,S.source);s.run(w,S.source.sectionTitle,S.source.leadText,S.searchText,S.source.excerptTruncated?1:0)}})(p),await r?.(Math.min(c+f.length,a),a)}o.exec("ANALYZE"),o.exec("VACUUM"),o.close()}function Mo(t,e,n,r,o,i,s){let a=Po(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)=>Bo(e,n,r,o),searchIndex:(n,r,o,i,s,a,c)=>Promise.resolve(Mo(e,i,r,o,s,a,c))}}import{readFile as ko,stat as vo,writeFile as Fo}from"fs/promises";var he=null,M=null;async function Se(){return he||(he=(async()=>{let t=(await import("@sqlite.org/sqlite-wasm")).default;return t()})()),he}function zo(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 Ho(t){let e=await vo(t);if(M&&M.dbPath===t&&M.mtimeMs===e.mtimeMs)return M.db;M?.db.close();let n=await Se(),r=n.capi,o=n.wasm,i=new Uint8Array(await ko(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),M={dbPath:t,mtimeMs:e.mtimeMs,db:a},a}function Un(){M?.db.close(),M=null}async function jo(t,e,n,r){t.exec("BEGIN");for(let o of r){let i=n(o.source);e.bind([i,o.source.sectionTitle,o.source.leadText,o.searchText,o.source.excerptTruncated?1:0]),e.step(),e.reset()}t.exec("COMMIT")}function Uo(t,e,n){return r=>{let o=e.get(r.documentId);if(o!==void 0)return o;let i=t.selectValue("SELECT id FROM documents WHERE document_id = ?",[r.documentId]);if(i!=null){let a=Number(i);return e.set(r.documentId,a),a}n.bind([r.documentId,r.catalogId,r.docTitle]),n.step(),n.reset();let s=Number(t.selectValue("SELECT last_insert_rowid()"));return e.set(r.documentId,s),s}}async function Zo(t,e,n){await Q();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=Uo(o,i,s),f=e.length;for(let d=0;d<f;d+=j){let b=e.slice(d,d+j),S=await Promise.all(b.map(async w=>({source:w,searchText:await bt(w)})));await jo(o,a,c,S),await n?.(Math.min(d+b.length,f),f)}o.exec("ANALYZE");let p=r.capi.sqlite3_js_db_export(o);await Fo(t,p),o.close(),Un()}async function $o(t,e,n,r,o,i){let s=await Ho(t);return At(zo(s),e,n,r,o,i)}async function ye(){return await Se(),{kind:"sqlite-wasm",resetCache:Un,buildSearchIndex:Zo,searchIndex:(t,e,n,r,o,i,s)=>$o(r,e,n,o,i,s)}}var It=null,xe=null;function Go(){return Y.existsSync(nt())}function Xo(t){let e=nt(),n={backend:"sqlite-wasm",reason:"better-sqlite3-load-failed",message:t,createdAt:new Date().toISOString()};Y.mkdirSync(Zn.dirname(e),{recursive:!0}),it(e),Y.writeFileSync(e,JSON.stringify(n,null,2))}async function Wo(){if(Go())return ye();try{let t=await jn();return z("doc-index: using better-sqlite3 SQLite backend"),t}catch(t){let e=t instanceof Error?t.message:String(t);Xo(e),z(`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 Rt}from"mdast-util-to-string";var qo=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,Qo=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,Jo=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,Yo=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,Vo=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function Ct(t){let e=t.trim(),n=e.match(Yo);return n?n[1]:e}function Ko(t){let e=t.match(qo);if(!e)return;let n=Ct(e[1].trim());return{displayTitle:t,symbolName:n,searchExtras:[n,e[3]]}}function ti(t){let e=Ct(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?Ko(e)??(()=>{let n=e.match(Qo);if(n){let r=n[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let n=e.match(Jo);if(!n)return;let r=n[1].trim(),o=n[2].trim();return{displayTitle:e,symbolName:o,searchExtras:[r,o]}})()??ti(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function ei(t){if(t.length<2||t.length>36||Vo.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 Xn(t){for(let e of t){let n=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(ei(n))return n}return""}function Wn(t,e,n){let r=[t,...n.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var ni=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,lt=/@[A-Z][a-zA-Z]+/g,ri=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,oi=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,ii=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,si=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),ai=new Set(["HAP","HSP","HAR","NAPI","CAPI","NDK","ArkTS","ArkUI","OHPM"]),ci=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)){D(n,i);let s=xt(i);s&&D(n,s)}for(let i of se(o))D(n,i);for(let i of o.matchAll(ni)){let s=i[0];ui(s)&&n.add(s)}for(let i of o.matchAll(lt))n.add(i[0])}return W([...n])}function ui(t){let e=t.trim();if(!e||lt.test(e))return!!e;if(e.includes(".")){let n=e.split(".")[0]??"";return ci.has(n)?!1:/^[A-Z]/.test(n)}return si.has(e)?!1:ai.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||ii.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=fi(t,"").trim(),o=e.fileName.trim();return n&&!qn(n)?n:r&&!qn(r)?r:n||r||o}function or(t){return ri.test(t.trim())}function _e(t){let e=t.trim().replace(/\([^)]*\)$/,""),n=Ct(e);return oi.test(n)}function Nt(t){let e=t.trim();return e?lt.test(e)||or(e)||_e(e)?!0:!!ut(e).symbolName:!1}function li(t){let e=t.trim();return!(!e||or(e)||_e(e))}function di(t){let e=new Set,n=[];for(let r of t){let o=r.trim();!li(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 mi(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(mi),[...n,...o].slice(0,je)}function Pt(t){return t.replace(/\s+/g," ").trim()}function Jn(t){return t.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function fi(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=Pt(t.join(" "));if(e.length<=mt)return e;let n=e.slice(0,mt);return e.length<=mt+kt?n:`${n} ${e.slice(-kt)}`}function pi(t){let e=di(t).join(" ");return e.length<=vt?e:e.slice(0,vt)}function ar(t){let e=Pt(t),{text:n,excerptTruncated:r}=vn(e,Ue);return{leadText:n,excerptTruncated:r}}function gi(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=Pt(Rt(t));n&&e.bodyParts.push(n)}function hi(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=Rt(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 Si(t){return Re.test(t)}function yi(t){return t.filter(e=>e.sectionTitle&&Nt(e.sectionTitle)).length}function xi(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||lt.test(e)?lt.test(e):/对象说明$|枚举说明$/.test(e)?!0:_e(e)}function Ei(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+=Mt)p.push(xi(f.slice(d,d+Mt)));return[...e,...r,...s,...c,...p]}function _i(t,e,n){let r=t.split(/\r?\n/).length,o=yi(e);return o===0?!1:Si(n)?r>=Ie&&o>=Te:r>=Ae&&o>=De}var bi=/^\[h2\][A-Za-z]/;function Vn(t){return bi.test(t.trim())}function ur(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=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=ut(r),i=Xn(t.bodyParts),s=Wn(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}=gi(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 lr(t,e){for(let n of t){if(n.type==="heading"){let o=Rt(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=Pt(Rt(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:pi(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=hi(t);return _i(t,r,e.documentId)?Ei(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})]}async function Ti(t){let e=[];async function n(r){let o=await x.promises.readdir(r,{withFileTypes:!0});for(let i of o){if(i.name.startsWith("."))continue;let s=_.join(r,i.name);i.isDirectory()?await n(s):i.isFile()&&i.name.endsWith(".md")&&e.push(s)}}return await n(t),e}function Ci(t,e){let n=_.relative(e,t).split(_.sep).join("/").split("/");if(n[0]==="docs"&&(n=n.slice(1)),n.length<2)return null;let r=n[0],o=Ge[r];if(o===void 0)return null;let i=n[n.length-1].replace(/\.md$/,"");return n[n.length-1]=i,{documentId:n.join("/"),catalogId:o,docTitle:i}}async function Ri(t){let e=t.replace(/\.md$/,".json");try{let n=await x.promises.readFile(e,"utf-8");return JSON.parse(n).title?.trim()||void 0}catch{return}}async function Ni(t,e){let n=Ci(t,e);if(!n)return[];let r=await x.promises.readFile(t,"utf-8"),o=rr(r,{jsonTitle:await Ri(t),fileName:n.docTitle});return dr(r,{...n,docTitle:o})}async function Pi(t,e,n){let r=_.join(e,"search.db");return await Gn(r,t,async(o,i)=>{await n?.({current:o,total:i,message:`Building search index\u2026 ${o.toLocaleString()} / ${i.toLocaleString()} segments`})}),t.length}async function Oi(t){let e=await Ti(t),n=[];for(let r of e){let o=await Ni(r,t);n.push(...o)}return n}function Li(t,e){return{indexVersion:H,docsZipSha256:t.docsZipSha256,termsHash:t.termsHash,synonymsHash:t.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:t.builtBy}}async function fr(t){t.lexiconDir&&$t(t.lexiconDir);try{let e=await Oi(t.docsDir);await t.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await x.promises.mkdir(t.tmpDir,{recursive:!0});let n=await Pi(e,t.tmpDir,t.onProgress),r=Li(t,n);return await x.promises.writeFile(_.join(t.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await sn(t.tmpDir),r}finally{t.lexiconDir&&$t(null)}}async function pr(){return x.promises.mkdtemp(_.join(mr.tmpdir(),"deveco-docs-"))}async function Bi(t,e){try{await x.promises.rename(t,e)}catch(n){let r=n.code;if(r!=="EPERM"&&r!=="EXDEV")throw n;await x.promises.cp(t,e,{recursive:!0}),await x.promises.rm(t,{recursive:!0,force:!0})}}async function gr(t){let e=_.join(t,"docs");try{await x.promises.access(e)}catch{return}let n=new Set(["docs","docs.zip"]);for(let r of await x.promises.readdir(e,{withFileTypes:!0})){if(n.has(r.name))continue;let o=_.join(e,r.name),i=_.join(t,r.name);await x.promises.rm(i,{recursive:!0,force:!0}),await Bi(o,i)}await x.promises.rm(_.join(e,"docs"),{recursive:!0,force:!0}),await x.promises.rm(_.join(e,"docs.zip"),{force:!0}),await x.promises.rm(e,{recursive:!0,force:!0})}async function Sr(t){let e=Ht();await h.promises.mkdir(T.dirname(e),{recursive:!0}),await h.promises.appendFile(e,`${new Date().toISOString()} ${t}
|
|
66
|
-
`)}async function
|
|
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)});
|
|
@@ -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 W from"fs";import*as g from"path";function J(n){let t=g.resolve(n),e=[],r=t;for(;;)try{let i=W.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(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(n);if(!t)throw new Error("Path must not be empty.");return J(t)}var Et="deveco-cli",X,$=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(n))||Y.join(xt(),".local","share",Et);try{return K(e)}catch(r){throw new $(r instanceof Error?r.message:String(r))}}function G(){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 q={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var D=class n{static ENDPOINT=q.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 w=[];h.on("data",Tt=>w.push(Tt)),h.on("end",()=>{s({code:h.statusCode??0,body:Buffer.concat(w).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()},M=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 M({namingStrategy:Z.snakeCase,fieldNames:{}});import b from"crypto";import C from"fs";import Lt from"path";var L="aes-256-gcm",_t=12,Ft="deveco-cli-trace-file",At="trace-file-secret",et=32;function tt(n){try{let t=C.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 j(e);let r=b.randomBytes(et).toString("base64");try{C.mkdirSync(n,{recursive:!0});try{C.writeFileSync(t,r,{flag:"wx"})}catch{let i=tt(t);if(i)return j(i);C.writeFileSync(t,r)}}catch{}return j(r)}function j(n){return b.createHash("sha256").update(Ft).update(n).digest()}function nt(n,t){let e=b.randomBytes(_t),r=b.createCipheriv(L,t,e),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o={version:1,algorithm:L,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(L,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===L&&typeof t.ciphertext=="string"&&typeof t.iv=="string"&&typeof t.authTag=="string"}import*as a from"fs";import*as A from"path";import*as _ from"os";import*as y from"path";import ye from"json5";import*as ot from"os";function B(){return Ot().toLowerCase().includes("openharmony")}function Ot(){return ot.platform()}var Se=[B()?".bitfun":".idea",".deveco",B()?".cxx":"cxx","compile_commands.json"];function st(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??y.join(_.homedir(),"AppData","Local");return y.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?y.join(_.homedir(),"Library","Logs","devecocli-mcp-server"):y.join(_.homedir(),".local","share","devecocli-mcp-server","logs")}var at="mcp-server.log",It="mcp-server",Rt={maxSize:10*1024*1024,maxFiles:4},U=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,`${It}-${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}},T=null;function Pt(n=!1){T&&T.dispose(),T=new U(n)}function F(){return T||Pt(!1),T}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,O=3600*1e3,ut=10080*60*1e3,v=8*1024*1024,pt=3600*1e3,lt=".pending",$t=/\.reclaim-\d+-\d+$/;function I(){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 V(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 z(n,t){try{ct.writeFileSync(ft(n),JSON.stringify(t),"utf8")}catch{}}function dt(n){let t=V(n);t.firstEventAt===null&&(t.firstEventAt=Date.now(),z(n,t))}function mt(n){let t=V(n);t.lastUploadAt=Date.now(),t.firstEventAt=null,z(n,t)}function gt(n){let t=V(n);t.lastRetryAt=Date.now(),z(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 H(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 H(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 x=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 D;storageDir="";failedDir="";installId="";disabled=I();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.
|
|
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}},T=null;function Pt(n=!1){T&&T.dispose(),T=new U(n)}function F(){return T||Pt(!1),T}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,O=3600*1e3,ut=10080*60*1e3,v=8*1024*1024,pt=3600*1e3,lt=".pending",$t=/\.reclaim-\d+-\d+$/;function I(){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 V(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 z(n,t){try{ct.writeFileSync(ft(n),JSON.stringify(t),"utf8")}catch{}}function dt(n){let t=V(n);t.firstEventAt===null&&(t.firstEventAt=Date.now(),z(n,t))}function mt(n){let t=V(n);t.lastUploadAt=Date.now(),t.firstEventAt=null,z(n,t)}function gt(n){let t=V(n);t.lastRetryAt=Date.now(),z(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 H(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 H(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 x=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 D;storageDir="";failedDir="";installId="";disabled=I();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.11-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+`
|
|
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 ${O/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(()=>{})},O)},O)}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=H(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 w=e.slice(i).join(`
|
|
5
5
|
`)+`
|
package/index.zip
CHANGED
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,108 +1,110 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@deveco-test/deveco-cli-openharmony-arm64",
|
|
3
|
-
"version": "1.3.
|
|
4
|
-
"description": "HarmonyOS application development command line tool",
|
|
5
|
-
"license": "MIT",
|
|
6
|
-
"type": "module",
|
|
7
|
-
"bin": {
|
|
8
|
-
"devecocli": "dist/cli.js"
|
|
9
|
-
},
|
|
10
|
-
"files": [
|
|
11
|
-
"dist",
|
|
12
|
-
"scripts/postinstall.mjs",
|
|
13
|
-
"scripts/install-better-sqlite3.mjs",
|
|
14
|
-
"scripts/install-jieba-wasm.mjs",
|
|
15
|
-
"scripts/lib/better-sqlite3-vendor.mjs",
|
|
16
|
-
"scripts/lib/jieba-wasm-vendor.mjs",
|
|
17
|
-
"scripts/lib/cli-data-dir.mjs",
|
|
18
|
-
"scripts/lib/doc-init-log-path.mjs",
|
|
19
|
-
"templates",
|
|
20
|
-
"src/resources",
|
|
21
|
-
"THIRD-PARTY-LICENSES",
|
|
22
|
-
"SKILL.md",
|
|
23
|
-
"docs.zip",
|
|
24
|
-
"index.zip"
|
|
25
|
-
],
|
|
26
|
-
"scripts": {
|
|
27
|
-
"prepare": "husky",
|
|
28
|
-
"postinstall": "node scripts/postinstall.mjs",
|
|
29
|
-
"build": "tsup",
|
|
30
|
-
"build:index": "tsx index/build-index-bundle.ts",
|
|
31
|
-
"dev": "tsx watch src/cli.ts",
|
|
32
|
-
"start": "tsx src/cli.ts",
|
|
33
|
-
"lint": "eslint src",
|
|
34
|
-
"lint:fix": "eslint src --fix",
|
|
35
|
-
"format": "prettier --write src",
|
|
36
|
-
"license": "generate-license-file --input package.json --output THIRD-PARTY-LICENSES --overwrite --ci",
|
|
37
|
-
"prepublishOnly": "npm run lint && npm run license && npm run build"
|
|
38
|
-
},
|
|
39
|
-
"engines": {
|
|
40
|
-
"node": ">=18"
|
|
41
|
-
},
|
|
42
|
-
"os": [
|
|
43
|
-
"openharmony"
|
|
44
|
-
],
|
|
45
|
-
"cpu": [
|
|
46
|
-
"arm64"
|
|
47
|
-
],
|
|
48
|
-
"keywords": [
|
|
49
|
-
"harmonyos",
|
|
50
|
-
"deveco",
|
|
51
|
-
"cli"
|
|
52
|
-
],
|
|
53
|
-
"devDependencies": {
|
|
54
|
-
"@eslint/js": "^10.0.1",
|
|
55
|
-
"@types/adm-zip": "^0.5.8",
|
|
56
|
-
"@types/better-sqlite3": "^7.6.13",
|
|
57
|
-
"@types/fs-extra": "^11.0.4",
|
|
58
|
-
"@types/global-agent": "^3.0.0",
|
|
59
|
-
"@types/node": "^25.6.0",
|
|
60
|
-
"@types/
|
|
61
|
-
"@types/
|
|
62
|
-
"
|
|
63
|
-
"
|
|
64
|
-
"
|
|
65
|
-
"
|
|
66
|
-
"
|
|
67
|
-
"
|
|
68
|
-
"
|
|
69
|
-
"
|
|
70
|
-
"
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
"
|
|
76
|
-
"
|
|
77
|
-
"
|
|
78
|
-
"
|
|
79
|
-
"
|
|
80
|
-
"
|
|
81
|
-
"
|
|
82
|
-
"
|
|
83
|
-
"
|
|
84
|
-
"
|
|
85
|
-
"
|
|
86
|
-
"
|
|
87
|
-
"
|
|
88
|
-
"
|
|
89
|
-
"
|
|
90
|
-
"
|
|
91
|
-
"
|
|
92
|
-
"
|
|
93
|
-
"
|
|
94
|
-
"
|
|
95
|
-
"
|
|
96
|
-
"
|
|
97
|
-
"
|
|
98
|
-
"
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
"
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "@deveco-test/deveco-cli-openharmony-arm64",
|
|
3
|
+
"version": "1.3.11-Test.1",
|
|
4
|
+
"description": "HarmonyOS application development command line tool",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": {
|
|
8
|
+
"devecocli": "dist/cli.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"dist",
|
|
12
|
+
"scripts/postinstall.mjs",
|
|
13
|
+
"scripts/install-better-sqlite3.mjs",
|
|
14
|
+
"scripts/install-jieba-wasm.mjs",
|
|
15
|
+
"scripts/lib/better-sqlite3-vendor.mjs",
|
|
16
|
+
"scripts/lib/jieba-wasm-vendor.mjs",
|
|
17
|
+
"scripts/lib/cli-data-dir.mjs",
|
|
18
|
+
"scripts/lib/doc-init-log-path.mjs",
|
|
19
|
+
"templates",
|
|
20
|
+
"src/resources",
|
|
21
|
+
"THIRD-PARTY-LICENSES",
|
|
22
|
+
"SKILL.md",
|
|
23
|
+
"docs.zip",
|
|
24
|
+
"index.zip"
|
|
25
|
+
],
|
|
26
|
+
"scripts": {
|
|
27
|
+
"prepare": "husky",
|
|
28
|
+
"postinstall": "node scripts/postinstall.mjs",
|
|
29
|
+
"build": "tsup",
|
|
30
|
+
"build:index": "tsx index/build-index-bundle.ts",
|
|
31
|
+
"dev": "tsx watch src/cli.ts",
|
|
32
|
+
"start": "tsx src/cli.ts",
|
|
33
|
+
"lint": "eslint src",
|
|
34
|
+
"lint:fix": "eslint src --fix",
|
|
35
|
+
"format": "prettier --write src",
|
|
36
|
+
"license": "generate-license-file --input package.json --output THIRD-PARTY-LICENSES --overwrite --ci",
|
|
37
|
+
"prepublishOnly": "npm run lint && npm run license && npm run build"
|
|
38
|
+
},
|
|
39
|
+
"engines": {
|
|
40
|
+
"node": ">=18"
|
|
41
|
+
},
|
|
42
|
+
"os": [
|
|
43
|
+
"openharmony"
|
|
44
|
+
],
|
|
45
|
+
"cpu": [
|
|
46
|
+
"arm64"
|
|
47
|
+
],
|
|
48
|
+
"keywords": [
|
|
49
|
+
"harmonyos",
|
|
50
|
+
"deveco",
|
|
51
|
+
"cli"
|
|
52
|
+
],
|
|
53
|
+
"devDependencies": {
|
|
54
|
+
"@eslint/js": "^10.0.1",
|
|
55
|
+
"@types/adm-zip": "^0.5.8",
|
|
56
|
+
"@types/better-sqlite3": "^7.6.13",
|
|
57
|
+
"@types/fs-extra": "^11.0.4",
|
|
58
|
+
"@types/global-agent": "^3.0.0",
|
|
59
|
+
"@types/node": "^25.6.0",
|
|
60
|
+
"@types/proper-lockfile": "^4.1.4",
|
|
61
|
+
"@types/node-forge": "^1.3.14",
|
|
62
|
+
"@types/turndown": "^5.0.5",
|
|
63
|
+
"@types/yauzl": "^2.10.3",
|
|
64
|
+
"eslint": "^10.2.1",
|
|
65
|
+
"generate-license-file": "^4.2.1",
|
|
66
|
+
"husky": "^9.1.7",
|
|
67
|
+
"prettier": "^3.8.3",
|
|
68
|
+
"tsup": "^8.5.1",
|
|
69
|
+
"tsx": "^4.21.0",
|
|
70
|
+
"turndown": "^7.2.4",
|
|
71
|
+
"typescript": "^6.0.3",
|
|
72
|
+
"typescript-eslint": "^8.59.1"
|
|
73
|
+
},
|
|
74
|
+
"dependencies": {
|
|
75
|
+
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
76
|
+
"@sqlite.org/sqlite-wasm": "3.53.4-build1",
|
|
77
|
+
"adm-zip": "^0.6.1",
|
|
78
|
+
"axios": "1.20.0",
|
|
79
|
+
"colorette": "^2.0.20",
|
|
80
|
+
"commander": "^13.1.0",
|
|
81
|
+
"execa": "^9.6.1",
|
|
82
|
+
"fs-extra": "^11.3.4",
|
|
83
|
+
"global-agent": "^4.1.3",
|
|
84
|
+
"jieba-wasm": "^2.4.0",
|
|
85
|
+
"json5": "^2.2.3",
|
|
86
|
+
"mdast-util-to-string": "^4.0.0",
|
|
87
|
+
"node-forge": "^1.4.2",
|
|
88
|
+
"ora": "^8.2.0",
|
|
89
|
+
"p-limit": "^5.0.0",
|
|
90
|
+
"proper-lockfile": "^4.1.2",
|
|
91
|
+
"proxy-from-env": "^2.1.0",
|
|
92
|
+
"regedit": "^5.1.4",
|
|
93
|
+
"remark-gfm": "^4.0.1",
|
|
94
|
+
"remark-parse": "^11.0.0",
|
|
95
|
+
"smol-toml": "^1.6.1",
|
|
96
|
+
"socket.io-client": "^4.7.5",
|
|
97
|
+
"unified": "^11.0.5",
|
|
98
|
+
"xdg-basedir": "^5.1.0",
|
|
99
|
+
"yauzl": "^3.2.0",
|
|
100
|
+
"zod": "^4.4.3"
|
|
101
|
+
},
|
|
102
|
+
"optionalDependencies": {
|
|
103
|
+
"@node-rs/jieba": "^2.0.1",
|
|
104
|
+
"@node-rs/jieba-wasm32-wasi": "2.0.1",
|
|
105
|
+
"better-sqlite3": "^12.11.1"
|
|
106
|
+
},
|
|
107
|
+
"overrides": {
|
|
108
|
+
"dotenv": "16.4.7"
|
|
109
|
+
}
|
|
110
|
+
}
|