@0xobelisk/sui-cli 1.2.0-pre.48 → 1.2.0-pre.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/dubhe.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import Go from"yargs";import{hideBin as Yo}from"yargs/helpers";import lt from"chalk";import{execSync as B,spawn as Ee}from"child_process";import x from"chalk";import dt from"chalk";function te(){console.log(dt.yellow(`
2
+ import Xo from"yargs";import{hideBin as Qo}from"yargs/helpers";import dt from"chalk";import{execSync as B,spawn as Ie}from"child_process";import x from"chalk";import pt from"chalk";function te(){console.log(pt.yellow(`
3
3
  Welcome to Dubhe
4
4
  --from team@obelisk
5
5
  ________ ___ ___ ________ ___ ___ _______
@@ -10,16 +10,16 @@ Welcome to Dubhe
10
10
  \\ \\_______\\ \\_______\\ \\_______\\ \\__\\ \\__\\ \\_______\\
11
11
  \\|_______|\\|_______|\\|_______|\\|__|\\|__|\\|_______|
12
12
 
13
- `))}import{Transaction as re}from"@0xobelisk/sui-client";import{execSync as St}from"child_process";import _ from"chalk";import*as ue from"fs/promises";import{mkdirSync as ft,writeFileSync as ht}from"fs";import{dirname as yt}from"path";import{SUI_PRIVATE_KEY_PREFIX as bt}from"@mysten/sui/cryptography";import G from"chalk";import{ZodError as ut}from"zod";import{fromZodError as pt,ValidationError as gt}from"zod-validation-error";var ce=class extends Error{name="NotInsideProjectError";message="You are not inside a Dubhe project"},N=class extends Error{name="DubheCliError"};function H(e){if(e instanceof gt)console.log(G.redBright(e.message));else if(e instanceof ut){let t=pt(e,{prefixSeparator:`
13
+ `))}import{Transaction as re}from"@0xobelisk/sui-client";import{execSync as _t}from"child_process";import P from"chalk";import*as ue from"fs/promises";import{mkdirSync as yt,writeFileSync as bt}from"fs";import{dirname as wt}from"path";import{SUI_PRIVATE_KEY_PREFIX as vt}from"@mysten/sui/cryptography";import G from"chalk";import{ZodError as gt}from"zod";import{fromZodError as mt,ValidationError as ft}from"zod-validation-error";var ce=class extends Error{name="NotInsideProjectError";message="You are not inside a Dubhe project"},A=class extends Error{name="DubheCliError"};function H(e){if(e instanceof ft)console.log(G.redBright(e.message));else if(e instanceof gt){let t=mt(e,{prefixSeparator:`
14
14
  - `,issueSeparator:`
15
- - `});console.log(G.redBright(t.message))}else e instanceof ce?(console.log(G.red(e.message)),console.log(""),console.log(G.blue("To learn more about Dubhe's configuration, please go to https://github.com/0xobelisk"))):e instanceof N?console.log(G.red(e)):console.log(e)}import*as W from"fs";import j from"chalk";import{spawn as xe}from"child_process";import{Dubhe as wt,loadMetadata as vt}from"@0xobelisk/sui-client";var R={name:"@0xobelisk/sui-cli",version:"1.2.0-pre.48",description:"Tookit for interacting with move eps framework",keywords:["sui","obelisk labs","move","blockchain"],type:"module",author:"team@obelisk.build",homepage:"https://github.com/0xobelisk/dubhe/tree/main/packages/sui-cli#readme",bugs:"https://github.com/0xobelisk/dubhe/issues",repository:{type:"git",url:"https://github.com/0xobelisk/dubhe.git"},license:"Apache-2.0",publishConfig:{access:"public"},engines:{node:">=18"},exports:{".":"./dist/index.js"},types:"src/index.ts",bin:{dubhe:"./dist/dubhe.js"},scripts:{build:"pnpm run type-check && pnpm run build:js","build:js":"tsup && chmod +x ./dist/dubhe.js",clean:"pnpm run clean:js","clean:js":"rimraf dist",dev:"tsup --watch",lint:"eslint . --ext .ts",format:"prettier --write .","format:check":"prettier --check .","type-check":"tsc --noEmit",validate:"pnpm format:check && pnpm type-check"},dependencies:{"@0xobelisk/sui-client":"workspace:*","@0xobelisk/sui-common":"workspace:*","@mysten/sui":"^1.19.0","@types/sqlite3":"^3.1.11","@types/wait-on":"^5.3.4",chalk:"^5.0.1",child_process:"^1.0.2",chokidar:"^3.5.3","cli-progress":"^3.12.0","cli-table3":"^0.6.5",dotenv:"^16.0.3",ejs:"^3.1.8",execa:"^7.0.0",glob:"^8.0.3","http-proxy-agent":"^7.0.2","https-proxy-agent":"^7.0.6",inquirer:"^9.2.15",ora:"^5.4.1",path:"^0.12.7",sqlite:"^5.1.1",sqlite3:"^5.1.7",typescript:"5.1.6","wait-on":"^7.0.1",yargs:"^17.7.1",zod:"^3.22.3","zod-validation-error":"^1.3.0"},devDependencies:{"@types/cli-progress":"^3.11.5","@types/ejs":"^3.1.1","@types/glob":"^7.2.0","@types/inquirer":"^9.0.7","@types/node":"^18.15.11","@types/yargs":"^17.0.10",eslint:"^8.56.0","eslint-config-prettier":"^9.1.0",prettier:"3.3.3","ts-node":"^10.9.1",tsup:"^6.7.0",tsx:"^3.12.6",vitest:"0.31.4"}};function pe(e){if(e.startsWith(bt))return e.length===70?e:!1;if(e.startsWith("0x")){let t=e.slice(2);return t.length===64?t:!1}else return e.length===64?e:!1}async function ge(e,t){try{let o=await ue.readFile(`${e}/.history/sui_${t}/latest.json`,"utf8");return JSON.parse(o)}catch(o){throw new Error(`read .history/sui_${t}/latest.json failed. ${o}`)}}async function oe(e,t){try{let o=await ue.readFile(`${e}/.history/sui_${t}/latest.json`,"utf8");return JSON.parse(o).dappHub}catch{return""}}async function ne(e){let o=`${process.cwd()}/src/dubhe`;switch(e){case"mainnet":return await oe(o,"mainnet");case"testnet":return await oe(o,"testnet");case"devnet":return await oe(o,"devnet");case"localnet":return await oe(o,"localnet");default:throw new Error(`Invalid network: ${e}`)}}async function ke(e,t){return(await ge(e,t)).packageId}async function me(e,t,o,n,s,i,a,u,d,c){let m={projectName:e,network:t,startCheckpoint:o,packageId:n,dappHub:s,upgradeCap:i,version:a,components:u,resources:d,enums:c},f=process.cwd(),h=JSON.stringify(m,null,2);await de(h,`${f}/src/${e}/.history/sui_${t}/latest.json`,"Update deploy log")}async function Y(e,t,o){let n=process.cwd();try{let s=await vt(t,o);if(s){let i=JSON.stringify(s,null,2);await de(i,`${n}/src/${e}/.history/sui_${t}/${o}.json`,"Save package metadata"),await de(i,`${n}/metadata.json`,"Save latest metadata")}}catch(s){console.warn(j.yellow(`Warning: Failed to save metadata: ${s}`))}}async function de(e,t,o){ft(yt(t),{recursive:!0}),ht(t,e),o!==void 0&&console.log(`${o}: ${t}`)}function xt(e){switch(e){case"localnet":return'Dubhe = { local = "../dubhe" }';case"testnet":return`Dubhe = { git = "https://github.com/0xobelisk/dubhe-wip.git", subdir = "packages/sui-framework/src/dubhe", rev = "v${R.version}" }`;case"mainnet":return`Dubhe = { git = "https://github.com/0xobelisk/dubhe-wip.git", subdir = "packages/sui-framework/src/dubhe", rev = "v${R.version}" }`;default:throw new Error(`Unsupported network: ${e}`)}}async function se(e,t){let o=W.readFileSync(e,"utf-8"),n=xt(t),s=o.replace(/Dubhe = \{.*\}/,n);W.writeFileSync(e,s,"utf-8"),console.log(`Updated Dubhe dependency in ${e} for ${t}.`)}async function kt(e){try{let t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"sui_getLatestCheckpointSequenceNumber",params:[]})});return t.ok?!(await t.json()).error:!1}catch{return!1}}async function Ct(e){let t={localnet:"http://127.0.0.1:9000",devnet:"https://fullnode.devnet.sui.io:443/",testnet:"https://fullnode.testnet.sui.io:443/",mainnet:"https://fullnode.mainnet.sui.io:443/"},o=t[e];if(!await kt(o))throw new Error(`RPC endpoint ${o} is not available. Please check your network connection or try again later.`);return new Promise((s,i)=>{let a="",u="",d=xe("sui",["client","new-env","--alias",e,"--rpc",t[e]],{env:{...process.env},stdio:"pipe"});d.stdout.on("data",c=>{u+=c.toString()}),d.stderr.on("data",c=>{a+=c.toString()}),d.on("error",c=>{console.error(j.red(`
16
- \u274C Failed to execute sui command: ${c.message}`)),i(new Error(`Failed to execute sui command: ${c.message}`))}),d.on("exit",c=>{if(a.includes("already exists")||u.includes("already exists")){console.log(j.yellow(`Environment ${e} already exists, proceeding...`)),s();return}if(c===0)console.log(j.green(`Successfully added environment ${e}`)),s();else{let m=a||u||`Process exited with code ${c}`;console.error(j.red(`
17
- \u274C Failed to add environment ${e}`)),console.error(j.red(` \u2514\u2500 ${m.trim()}`)),i(new Error(m))}})})}async function q(e){try{return await Ct(e),new Promise((t,o)=>{let n="",s="",i=xe("sui",["client","switch","--env",e],{env:{...process.env},stdio:"pipe"});i.stdout.on("data",a=>{s+=a.toString()}),i.stderr.on("data",a=>{n+=a.toString()}),i.on("error",a=>{console.error(j.red(`
18
- \u274C Failed to execute sui command: ${a.message}`)),o(new Error(`Failed to execute sui command: ${a.message}`))}),i.on("exit",a=>{if(a===0)console.log(j.green(`Successfully switched to environment ${e}`)),t();else{let u=n||s||`Process exited with code ${a}`;console.error(j.red(`
19
- \u274C Failed to switch to environment ${e}`)),console.error(j.red(` \u2514\u2500 ${u.trim()}`)),o(new Error(u))}})})}catch(t){throw t}}var L=e=>new Promise(t=>setTimeout(t,e));function $t(){let e=process.env.PRIVATE_KEY||process.env.NEXT_PUBLIC_PRIVATE_KEY;if(!e)throw new N(`Missing private key environment variable.
15
+ - `});console.log(G.redBright(t.message))}else e instanceof ce?(console.log(G.red(e.message)),console.log(""),console.log(G.blue("To learn more about Dubhe's configuration, please go to https://github.com/0xobelisk"))):e instanceof A?console.log(G.red(e)):console.log(e)}import*as W from"fs";import F from"chalk";import{spawn as ke}from"child_process";import{Dubhe as xt,loadMetadata as kt}from"@0xobelisk/sui-client";var M={name:"@0xobelisk/sui-cli",version:"1.2.0-pre.49",description:"Tookit for interacting with move eps framework",keywords:["sui","obelisk labs","move","blockchain"],type:"module",author:"team@obelisk.build",homepage:"https://github.com/0xobelisk/dubhe/tree/main/packages/sui-cli#readme",bugs:"https://github.com/0xobelisk/dubhe/issues",repository:{type:"git",url:"https://github.com/0xobelisk/dubhe.git"},license:"Apache-2.0",publishConfig:{access:"public"},engines:{node:">=18"},exports:{".":"./dist/index.js"},types:"src/index.ts",bin:{dubhe:"./dist/dubhe.js"},scripts:{build:"pnpm run type-check && pnpm run build:js","build:js":"tsup && chmod +x ./dist/dubhe.js",clean:"pnpm run clean:js","clean:js":"rimraf dist",dev:"tsup --watch",lint:"eslint . --ext .ts",format:"prettier --write .","format:check":"prettier --check .","type-check":"tsc --noEmit",validate:"pnpm format:check && pnpm type-check"},dependencies:{"@0xobelisk/sui-client":"workspace:*","@0xobelisk/sui-common":"workspace:*","@mysten/sui":"^1.19.0","@types/sqlite3":"^3.1.11","@types/wait-on":"^5.3.4",chalk:"^5.0.1",child_process:"^1.0.2",chokidar:"^3.5.3","cli-progress":"^3.12.0","cli-table3":"^0.6.5",dotenv:"^16.0.3",ejs:"^3.1.8",execa:"^7.0.0",glob:"^8.0.3","http-proxy-agent":"^7.0.2","https-proxy-agent":"^7.0.6",inquirer:"^9.2.15",ora:"^5.4.1",path:"^0.12.7",sqlite:"^5.1.1",sqlite3:"^5.1.7",typescript:"5.1.6","wait-on":"^7.0.1",yargs:"^17.7.1",zod:"^3.22.3","zod-validation-error":"^1.3.0"},devDependencies:{"@types/cli-progress":"^3.11.5","@types/ejs":"^3.1.1","@types/glob":"^7.2.0","@types/inquirer":"^9.0.7","@types/node":"^18.15.11","@types/yargs":"^17.0.10",eslint:"^8.56.0","eslint-config-prettier":"^9.1.0",prettier:"3.3.3","ts-node":"^10.9.1",tsup:"^6.7.0",tsx:"^3.12.6",vitest:"0.31.4"}};function pe(e){if(e.startsWith(vt))return e.length===70?e:!1;if(e.startsWith("0x")){let t=e.slice(2);return t.length===64?t:!1}else return e.length===64?e:!1}async function ge(e,t){try{let o=await ue.readFile(`${e}/.history/sui_${t}/latest.json`,"utf8");return JSON.parse(o)}catch(o){throw new Error(`read .history/sui_${t}/latest.json failed. ${o}`)}}async function oe(e,t){try{let o=await ue.readFile(`${e}/.history/sui_${t}/latest.json`,"utf8");return JSON.parse(o).dappHub}catch{return""}}async function ne(e){let o=`${process.cwd()}/src/dubhe`;switch(e){case"mainnet":return await oe(o,"mainnet");case"testnet":return await oe(o,"testnet");case"devnet":return await oe(o,"devnet");case"localnet":return await oe(o,"localnet");default:throw new Error(`Invalid network: ${e}`)}}async function Ce(e,t){return(await ge(e,t)).packageId}async function me(e,t,o,n,s,i,a,u,d,c){let m={projectName:e,network:t,startCheckpoint:o,packageId:n,dappHub:s,upgradeCap:i,version:a,components:u,resources:d,enums:c},f=process.cwd(),h=JSON.stringify(m,null,2);await de(h,`${f}/src/${e}/.history/sui_${t}/latest.json`,"Update deploy log")}async function Y(e,t,o){let n=process.cwd();try{let s=await kt(t,o);if(s){let i=JSON.stringify(s,null,2);await de(i,`${n}/src/${e}/.history/sui_${t}/${o}.json`,"Save package metadata"),await de(i,`${n}/metadata.json`,"Save latest metadata")}}catch(s){console.warn(F.yellow(`Warning: Failed to save metadata: ${s}`))}}async function de(e,t,o){yt(wt(t),{recursive:!0}),bt(t,e),o!==void 0&&console.log(`${o}: ${t}`)}function Ct(e){switch(e){case"localnet":return'Dubhe = { local = "../dubhe" }';case"testnet":return`Dubhe = { git = "https://github.com/0xobelisk/dubhe-wip.git", subdir = "packages/sui-framework/src/dubhe", rev = "v${M.version}" }`;case"mainnet":return`Dubhe = { git = "https://github.com/0xobelisk/dubhe-wip.git", subdir = "packages/sui-framework/src/dubhe", rev = "v${M.version}" }`;default:throw new Error(`Unsupported network: ${e}`)}}async function se(e,t){let o=W.readFileSync(e,"utf-8"),n=Ct(t),s=o.replace(/Dubhe = \{.*\}/,n);W.writeFileSync(e,s,"utf-8"),console.log(`Updated Dubhe dependency in ${e} for ${t}.`)}async function $t(e){try{let t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"sui_getLatestCheckpointSequenceNumber",params:[]})});return t.ok?!(await t.json()).error:!1}catch{return!1}}async function St(e){let t={localnet:"http://127.0.0.1:9000",devnet:"https://fullnode.devnet.sui.io:443/",testnet:"https://fullnode.testnet.sui.io:443/",mainnet:"https://fullnode.mainnet.sui.io:443/"},o=t[e];if(!await $t(o))throw new Error(`RPC endpoint ${o} is not available. Please check your network connection or try again later.`);return new Promise((s,i)=>{let a="",u="",d=ke("sui",["client","new-env","--alias",e,"--rpc",t[e]],{env:{...process.env},stdio:"pipe"});d.stdout.on("data",c=>{u+=c.toString()}),d.stderr.on("data",c=>{a+=c.toString()}),d.on("error",c=>{console.error(F.red(`
16
+ \u274C Failed to execute sui command: ${c.message}`)),i(new Error(`Failed to execute sui command: ${c.message}`))}),d.on("exit",c=>{if(a.includes("already exists")||u.includes("already exists")){console.log(F.yellow(`Environment ${e} already exists, proceeding...`)),s();return}if(c===0)console.log(F.green(`Successfully added environment ${e}`)),s();else{let m=a||u||`Process exited with code ${c}`;console.error(F.red(`
17
+ \u274C Failed to add environment ${e}`)),console.error(F.red(` \u2514\u2500 ${m.trim()}`)),i(new Error(m))}})})}async function q(e){try{return await St(e),new Promise((t,o)=>{let n="",s="",i=ke("sui",["client","switch","--env",e],{env:{...process.env},stdio:"pipe"});i.stdout.on("data",a=>{s+=a.toString()}),i.stderr.on("data",a=>{n+=a.toString()}),i.on("error",a=>{console.error(F.red(`
18
+ \u274C Failed to execute sui command: ${a.message}`)),o(new Error(`Failed to execute sui command: ${a.message}`))}),i.on("exit",a=>{if(a===0)console.log(F.green(`Successfully switched to environment ${e}`)),t();else{let u=n||s||`Process exited with code ${a}`;console.error(F.red(`
19
+ \u274C Failed to switch to environment ${e}`)),console.error(F.red(` \u2514\u2500 ${u.trim()}`)),o(new Error(u))}})})}catch(t){throw t}}var L=e=>new Promise(t=>setTimeout(t,e));function Pt(){let e=process.env.PRIVATE_KEY||process.env.NEXT_PUBLIC_PRIVATE_KEY;if(!e)throw new A(`Missing private key environment variable.
20
20
  Run 'echo "PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
21
21
  or 'echo "NEXT_PUBLIC_PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
22
- in your contracts directory to use the default sui private key.`);let t=pe(e);if(t===!1)throw new N("Please check your privateKey.");return t}function V({network:e,packageId:t,metadata:o}){let n=$t();return new wt({networkType:e,secretKey:n,packageId:t,metadata:o})}function Ce(e){let t=Object.entries(e.components).map(([s,i])=>{if(typeof i=="string")return{[s]:{fields:[{entity_id:"address"},{value:i}],keys:["entity_id"],offchain:!1}};if(Object.keys(i).length===0)return{[s]:{fields:[{entity_id:"address"}],keys:["entity_id"],offchain:!1}};let a=i.fields||{},u=i.keys||["entity_id"],d=i.offchain??!1;return!a.entity_id&&u.includes("entity_id")&&(a.entity_id="address"),{[s]:{fields:Object.entries(a).map(([c,m])=>({[c]:m})),keys:u,offchain:d}}}),o=Object.entries(e.resources).map(([s,i])=>{if(typeof i=="string")return{[s]:{fields:[{value:i}],keys:[],offchain:!1}};if(Object.keys(i).length===0)return{[s]:{fields:[],keys:[],offchain:!1}};let a=i.fields||{},u=i.keys||[],d=i.offchain??!1;return{[s]:{fields:Object.entries(a).map(([c,m])=>({[c]:m})),keys:u,offchain:d}}}),n=Object.entries(e.enums||{}).map(([s,i])=>{let a=i.sort((u,d)=>u.localeCompare(d)).map((u,d)=>({[d]:u}));return{[s]:a}});return JSON.stringify({components:t,resources:o,enums:n},null,2)}function fe(e,t){let o=`${e}/Move.toml`,s=W.readFileSync(o,"utf-8").replace(/dubhe\s*=\s*"[^"]*"/,`dubhe = "${t}"`);W.writeFileSync(o,s,"utf-8")}import*as M from"fs";import*as $e from"path";async function Se(e,t){if(!M.existsSync(e))return;let o=M.readFileSync(e,"utf-8"),n=new RegExp(`\\[env\\.${t}\\][\\s\\S]*?(?=\\[|$)`,"g"),s=o.replace(n,"");M.writeFileSync(e,s,"utf-8")}function _e(e,t,o,n,s){let i=$e.resolve(e),a=M.readFileSync(i,"utf-8"),u=a.split(`
22
+ in your contracts directory to use the default sui private key.`);let t=pe(e);if(t===!1)throw new A("Please check your privateKey.");return t}function V({network:e,packageId:t,metadata:o}){let n=Pt();return new xt({networkType:e,secretKey:n,packageId:t,metadata:o})}function $e(e){let t=Object.entries(e.components).map(([s,i])=>{if(typeof i=="string")return{[s]:{fields:[{entity_id:"address"},{value:i}],keys:["entity_id"],offchain:!1}};if(Object.keys(i).length===0)return{[s]:{fields:[{entity_id:"address"}],keys:["entity_id"],offchain:!1}};let a=i.fields||{},u=i.keys||["entity_id"],d=i.offchain??!1;return!a.entity_id&&u.includes("entity_id")&&(a.entity_id="address"),{[s]:{fields:Object.entries(a).map(([c,m])=>({[c]:m})),keys:u,offchain:d}}}),o=Object.entries(e.resources).map(([s,i])=>{if(typeof i=="string")return{[s]:{fields:[{value:i}],keys:[],offchain:!1}};if(Object.keys(i).length===0)return{[s]:{fields:[],keys:[],offchain:!1}};let a=i.fields||{},u=i.keys||[],d=i.offchain??!1;return{[s]:{fields:Object.entries(a).map(([c,m])=>({[c]:m})),keys:u,offchain:d}}}),n=Object.entries(e.enums||{}).map(([s,i])=>{let a=i.sort((u,d)=>u.localeCompare(d)).map((u,d)=>({[d]:u}));return{[s]:a}});return JSON.stringify({components:t,resources:o,enums:n},null,2)}function fe(e,t){let o=`${e}/Move.toml`,s=W.readFileSync(o,"utf-8").replace(/dubhe\s*=\s*"[^"]*"/,`dubhe = "${t}"`);W.writeFileSync(o,s,"utf-8")}import*as N from"fs";import*as Se from"path";async function Pe(e,t){if(!N.existsSync(e))return;let o=N.readFileSync(e,"utf-8"),n=new RegExp(`\\[env\\.${t}\\][\\s\\S]*?(?=\\[|$)`,"g"),s=o.replace(n,"");N.writeFileSync(e,s,"utf-8")}function _e(e,t,o,n,s){let i=Se.resolve(e),a=N.readFileSync(i,"utf-8"),u=a.split(`
23
23
  `),d=u.findIndex(h=>h.trim()===`[env.${t}]`),c={chainId:n,originalPublishedId:"",latestPublishedId:"",publishedVersion:0};if(d===-1)if(o==="publish")c.originalPublishedId=s,c.latestPublishedId=s,c.publishedVersion=1;else throw new Error(`Network type [env.${t}] not found in the file and cannot upgrade.`);else{for(let h=d+1;h<u.length;h++){let y=u[h].trim();if(y.startsWith("["))break;let[C,D]=y.split("=").map(l=>l.trim().replace(/"/g,""));switch(C){case"original-published-id":c.originalPublishedId=D;break;case"latest-published-id":c.latestPublishedId=D;break;case"published-version":c.publishedVersion=parseInt(D,10);break}}o==="publish"?(c.originalPublishedId=s,c.latestPublishedId=s,c.publishedVersion=1):o==="upgrade"&&(c.latestPublishedId=s,c.publishedVersion+=1)}let m=`
24
24
  [env.${t}]
25
25
  chain-id = "${c.chainId}"
@@ -27,67 +27,67 @@ original-published-id = "${c.originalPublishedId}"
27
27
  latest-published-id = "${c.latestPublishedId}"
28
28
  published-version = "${c.publishedVersion}"
29
29
  `,f=d===-1?a+m:u.slice(0,d).join(`
30
- `)+m;M.writeFileSync(i,f,"utf-8")}function Pe(e){let t,o;try{let n=JSON.parse(St(`sui move build --dump-bytecode-as-base64 --path ${e}`,{encoding:"utf-8",stdio:"pipe"}));t=n.modules,o=n.dependencies}catch(n){console.error(_.red(" \u2514\u2500 Build failed")),console.error(n.stdout),process.exit(1)}return[t,o]}async function De(e){let t=await e.suiInteractor.currentClient.getChainIdentifier();console.log(` \u251C\u2500 ChainId: ${t}`);let o=e.getAddress(),n=await e.suiInteractor.currentClient.getCoins({owner:o,coinType:"0x2::sui::SUI"});if(n.data.length>0){let s=n.data.reduce((i,a)=>i+Number(a.balance),0);if(s>0)return console.log(` \u251C\u2500 Deployer balance: ${s/10**9} SUI`),t;console.log(_.yellow(" \u251C\u2500 Deployer balance: 0 SUI, please ensure your account has sufficient SUI balance"))}return t}async function _t(e,t,o,n,s){console.log(`
31
- \u{1F680} Starting Contract Publication...`),console.log(` \u251C\u2500 Project: ${n}`),console.log(` \u251C\u2500 Network: ${o}`),console.log(" \u251C\u2500 Waiting for node...");let i=await De(e);console.log(" \u251C\u2500 Validating Environment..."),await Se(`${n}/Move.lock`,o),console.log(` \u2514\u2500 Account: ${e.getAddress()}`),console.log(`
32
- \u{1F4E6} Building Contract...`);let[a,u]=Pe(n);console.log(`
33
- \u{1F504} Publishing Contract...`);let d=new re;s&&d.setGasBudget(s);let[c]=d.publish({modules:a,dependencies:u});d.transferObjects([c],e.getAddress());let m;try{m=await e.signAndSendTxn({tx:d})}catch(g){console.error(_.red(" \u2514\u2500 Publication failed")),console.error(g.message),process.exit(1)}(!m||m.effects?.status.status==="failure")&&(console.log(_.red(" \u2514\u2500 Publication failed")),process.exit(1)),console.log(" \u251C\u2500 Processing publication results...");let f=1,h="",y="",C=t.components,D=t.resources,l=t.enums,$="",p="",b=[];m.objectChanges.map(g=>{g.type==="published"&&(console.log(` \u251C\u2500 Package ID: ${g.packageId}`),h=g.packageId||""),g.type==="created"&&g.objectType&&g.objectType==="0x2::package::UpgradeCap"&&(console.log(` \u251C\u2500 Upgrade Cap: ${g.objectId}`),$=g.objectId||""),g.type==="created"&&g.objectType&&g.objectType.includes("dapp_service::DappHub")&&(y=g.objectId||""),g.type==="created"&&b.push(g)}),console.log(` \u2514\u2500 Transaction: ${m.digest}`),_e(`${n}/Move.lock`,o,"publish",i,h),console.log(`
34
- \u26A1 Executing Deploy Hook...`),await L(5e3),p=await e.suiInteractor.currentClient.getLatestCheckpointSequenceNumber();let k=new re,T=[],S=t.name==="dubhe"?y:await ne(o);T.push(k.object(S)),T.push(k.object("0x6")),k.moveCall({target:`${h}::genesis::run`,arguments:T});let E;try{E=await e.signAndSendTxn({tx:k})}catch(g){console.error(_.red(" \u2514\u2500 Deploy hook execution failed")),console.error(g.message),process.exit(1)}if(E.effects?.status.status==="success"){console.log(" \u251C\u2500 Hook execution successful"),console.log(` \u251C\u2500 Transaction: ${E.digest}`),console.log(`
35
- \u{1F4CB} Created Objects:`),b.map(v=>{console.log(` \u251C\u2500 ID: ${v.objectId}`),console.log(` \u2514\u2500 Type: ${v.objectType}`)}),await me(t.name,o,p,h,y,$,f,C,D,l),await Y(t.name,o,h);let g=JSON.parse(M.readFileSync(`${process.cwd()}/dubhe.config.json`,"utf-8"));g.package_id=h,g.start_checkpoint=p,M.writeFileSync(`${process.cwd()}/dubhe.config.json`,JSON.stringify(g,null,2)),console.log(`
30
+ `)+m;N.writeFileSync(i,f,"utf-8")}function De(e){let t,o;try{let n=JSON.parse(_t(`sui move build --dump-bytecode-as-base64 --path ${e}`,{encoding:"utf-8",stdio:"pipe"}));t=n.modules,o=n.dependencies}catch(n){console.error(P.red(" \u2514\u2500 Build failed")),console.error(n.stdout),process.exit(1)}return[t,o]}async function Te(e){let t=await e.suiInteractor.currentClient.getChainIdentifier();console.log(` \u251C\u2500 ChainId: ${t}`);let o=e.getAddress(),n=await e.suiInteractor.currentClient.getCoins({owner:o,coinType:"0x2::sui::SUI"});if(n.data.length>0){let s=n.data.reduce((i,a)=>i+Number(a.balance),0);if(s>0)return console.log(` \u251C\u2500 Deployer balance: ${s/10**9} SUI`),t;console.log(P.yellow(" \u251C\u2500 Deployer balance: 0 SUI, please ensure your account has sufficient SUI balance"))}return t}async function Dt(e,t,o,n,s){console.log(`
31
+ \u{1F680} Starting Contract Publication...`),console.log(` \u251C\u2500 Project: ${n}`),console.log(` \u251C\u2500 Network: ${o}`),console.log(" \u251C\u2500 Waiting for node...");let i=await Te(e);console.log(" \u251C\u2500 Validating Environment..."),await Pe(`${n}/Move.lock`,o),console.log(` \u2514\u2500 Account: ${e.getAddress()}`),console.log(`
32
+ \u{1F4E6} Building Contract...`);let[a,u]=De(n);console.log(`
33
+ \u{1F504} Publishing Contract...`);let d=new re;s&&d.setGasBudget(s);let[c]=d.publish({modules:a,dependencies:u});d.transferObjects([c],e.getAddress());let m;try{m=await e.signAndSendTxn({tx:d})}catch(g){console.error(P.red(" \u2514\u2500 Publication failed")),console.error(g.message),process.exit(1)}(!m||m.effects?.status.status==="failure")&&(console.log(P.red(" \u2514\u2500 Publication failed")),process.exit(1)),console.log(" \u251C\u2500 Processing publication results...");let f=1,h="",y="",C=t.components,D=t.resources,l=t.enums,$="",p="",b=[];m.objectChanges.map(g=>{g.type==="published"&&(console.log(` \u251C\u2500 Package ID: ${g.packageId}`),h=g.packageId||""),g.type==="created"&&g.objectType&&g.objectType==="0x2::package::UpgradeCap"&&(console.log(` \u251C\u2500 Upgrade Cap: ${g.objectId}`),$=g.objectId||""),g.type==="created"&&g.objectType&&g.objectType.includes("dapp_service::DappHub")&&(y=g.objectId||""),g.type==="created"&&b.push(g)}),console.log(` \u2514\u2500 Transaction: ${m.digest}`),_e(`${n}/Move.lock`,o,"publish",i,h),console.log(`
34
+ \u26A1 Executing Deploy Hook...`),await L(5e3),p=await e.suiInteractor.currentClient.getLatestCheckpointSequenceNumber();let k=new re,T=[],S=t.name==="dubhe"?y:await ne(o);T.push(k.object(S)),T.push(k.object("0x6")),k.moveCall({target:`${h}::genesis::run`,arguments:T});let E;try{E=await e.signAndSendTxn({tx:k})}catch(g){console.error(P.red(" \u2514\u2500 Deploy hook execution failed")),console.error(g.message),process.exit(1)}if(E.effects?.status.status==="success"){console.log(" \u251C\u2500 Hook execution successful"),console.log(` \u251C\u2500 Transaction: ${E.digest}`),console.log(`
35
+ \u{1F4CB} Created Objects:`),b.map(v=>{console.log(` \u251C\u2500 ID: ${v.objectId}`),console.log(` \u2514\u2500 Type: ${v.objectType}`)}),await me(t.name,o,p,h,y,$,f,C,D,l),await Y(t.name,o,h);let g=JSON.parse(N.readFileSync(`${process.cwd()}/dubhe.config.json`,"utf-8"));g.package_id=h,g.start_checkpoint=p,N.writeFileSync(`${process.cwd()}/dubhe.config.json`,JSON.stringify(g,null,2)),console.log(`
36
36
  \u2705 Contract Publication Complete
37
- `)}else console.log(_.yellow(" \u2514\u2500 Deploy hook execution failed")),console.log(_.yellow(" Please republish or manually call deploy_hook::run")),console.log(_.yellow(" Please check the transaction digest:")),console.log(_.yellow(` ${E.digest}`)),process.exit(1)}async function Pt(e){return M.existsSync(e)?!0:(console.log(_.yellow(`
38
- \u2139\uFE0F Dubhe Framework Files Not Found`)),console.log(_.yellow(" \u251C\u2500 Expected Path:"),e),console.log(_.yellow(" \u251C\u2500 To set up Dubhe Framework:")),console.log(_.yellow(" \u2502 1. Create directory: mkdir -p contracts/dubhe")),console.log(_.yellow(" \u2502 2. Clone repository: git clone https://github.com/0xobelisk/dubhe contracts/dubhe")),console.log(_.yellow(" \u2502 3. Or download from: https://github.com/0xobelisk/dubhe")),console.log(_.yellow(" \u2514\u2500 After setup, restart the local node")),!1)}async function Dt(e,t){let n=`${process.cwd()}/src/dubhe`;if(!await Pt(n))return;console.log(`
39
- \u{1F680} Starting Dubhe Framework Publication...`),console.log(" \u251C\u2500 Waiting for node...");let s=await De(e);await Se(`${n}/Move.lock`,t),await fe(n,"0x0");let[i,a]=Pe(n),u=new re,[d]=u.publish({modules:i,dependencies:a});u.transferObjects([d],e.getAddress());let c;try{c=await e.signAndSendTxn({tx:u})}catch(l){console.error(_.red(" \u2514\u2500 Publication failed")),console.error(l.message),process.exit(1)}(!c||c.effects?.status.status==="failure")&&(console.log(_.red(" \u2514\u2500 Publication failed")),process.exit(1));let m=1,f="",h="",y="";c.objectChanges.map(l=>{l.type==="published"&&(f=l.packageId||""),l.type==="created"&&l.objectType&&l.objectType==="0x2::package::UpgradeCap"&&(y=l.objectId||""),l.type==="created"&&l.objectType&&l.objectType.includes("dapp_service::DappHub")&&(h=l.objectId||"")}),await L(3e3);let C=new re;C.moveCall({target:`${f}::genesis::run`,arguments:[C.object(h),C.object("0x6")]});let D;try{D=await e.signAndSendTxn({tx:C})}catch(l){console.error(_.red(" \u2514\u2500 Deploy hook execution failed")),console.error(l.message),process.exit(1)}if(D.effects?.status.status!=="success")throw new Error("Deploy hook execution failed");await fe(n,f),await me("dubhe",t,f,"0",h,y,m,{},{},{}),_e(`${n}/Move.lock`,t,"publish",s,f)}async function Te(e,t,o){await q(t);let n=V({network:t}),i=`${process.cwd()}/src/${e.name}`;t==="localnet"&&e.name!=="dubhe"&&await Dt(n,t),e.name!=="dubhe"&&await se(`${i}/Move.toml`,t),await _t(n,e,t,i,o)}import{Dubhe as Tt}from"@0xobelisk/sui-client";import*as ie from"fs";function Et(){console.log(x.yellow("\u{1F514} Stopping existing Local Node..."));let e=!1;if(process.platform==="win32")try{B("taskkill /F /IM sui.exe",{stdio:"ignore"}),e=!0}catch{}else{let t=["sui start","sui.*start","^sui","sui.*--with-faucet"];for(let o of t)try{let n=B(`pgrep -f "${o}"`,{stdio:"pipe"}).toString().trim();if(n){let s=n.split(`
40
- `).filter(i=>i);console.log(x.cyan(` \u251C\u2500 Found ${s.length} process(es) matching "${o}"`)),s.forEach(i=>{try{B(`kill -TERM ${i}`,{stdio:"ignore"}),console.log(x.cyan(` \u251C\u2500 Sent SIGTERM to process ${i}`))}catch{try{B(`kill -KILL ${i}`,{stdio:"ignore"}),console.log(x.cyan(` \u251C\u2500 Force killed process ${i}`))}catch{console.log(x.gray(` \u251C\u2500 Process ${i} already terminated`))}}}),e=!0;break}}catch{continue}}console.log(e?x.green(" \u2514\u2500 Local Node stopped successfully"):x.gray(" \u2514\u2500 No running Local Node found"))}function It(e){try{ie.existsSync(e)?(console.log(x.yellow(`\u{1F5D1}\uFE0F Removing directory: ${e}`)),ie.rmSync(e,{recursive:!0,force:!0}),console.log(x.green(" \u2514\u2500 Directory removed successfully"))):console.log(x.gray(` \u2514\u2500 Directory ${e} does not exist`))}catch(t){console.error(x.red(` \u2514\u2500 Error removing directory: ${t.message}`))}}function At(){try{if(process.platform==="win32")return B('tasklist /FI "IMAGENAME eq sui.exe" /FO CSV /NH').toString().trim().toLowerCase().includes("sui.exe");{let e=["sui start","sui.*start","^sui","sui.*--with-faucet"];for(let t of e)try{let o=B(`pgrep -f "${t}"`,{stdio:"pipe"}).toString().trim();if(o&&o.length>0)return!0}catch{continue}return!1}}catch{return!1}}async function Nt(){let e=["suiprivkey1qq3ez3dje66l8pypgxynr7yymwps6uhn7vyczespj84974j3zya0wdpu76v","suiprivkey1qp6vcyg8r2x88fllmjmxtpzjl95gd9dugqrgz7xxf50w6rqdqzetg7x4d7s","suiprivkey1qpy3a696eh3m55fwa8h38ss063459u4n2dm9t24w2hlxxzjp2x34q8sdsnc","suiprivkey1qzxwp29favhzrjd95f6uj9nskjwal6nh9g509jpun395y6g72d6jqlmps4c","suiprivkey1qzhq4lv38sesah4uzsqkkmeyjx860xqjdz8qgw36tmrdd5tnle3evxpng57","suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c"];console.log("\u{1F4DD}Accounts"),console.log("=========="),e.forEach((t,o)=>{let s=new Tt({secretKey:t}).getSigner();Ee("curl",["--location","--request","POST","http://127.0.0.1:9123/gas","--header","Content-Type: application/json","--data-raw",`{"FixedAmountRequest": {"recipient": "${s.toSuiAddress()}"}}`],{env:{...process.env},stdio:"ignore",detached:!0}),console.log(` \u250C\u2500 Account #${o}: ${s.toSuiAddress()}(1000 SUI)`),console.log(` \u2514\u2500 Private Key: ${t}`)}),console.log("=========="),console.log(x.yellow("\u2139\uFE0F WARNING: These accounts, and their private keys, are publicly known.")),console.log(x.yellow("Any funds sent to them on Mainnet or any other live network WILL BE LOST."))}function Mt(e){let t=()=>{console.log(x.yellow(`
41
- \u{1F514} Stopping Local Node...`)),e&&e.kill("SIGINT"),process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t)}async function Ie(e,t){if(t)console.log(x.cyan(`
42
- \u{1F504} Force mode enabled`)),Et(),console.log(x.yellow(" \u251C\u2500 Waiting for processes to terminate...")),await L(3e3),It(e),console.log("");else if(At()){console.log(x.yellow(`
43
- \u26A0\uFE0F Warning: Local Node Already Running`)),console.log(x.yellow(" \u251C\u2500 Cannot start a new instance")),console.log(x.yellow(" \u2514\u2500 Please stop the existing process first"));return}te(),console.log("\u{1F680} Starting Local Node...");let o=null;try{let n=["start","--with-faucet"];if(t&&n.push("--force-regenesis"),n.push("--data-ingestion-dir",e),o=Ee("sui",n,{env:{...process.env,RUST_LOG:"off,sui_node=info"},stdio:"ignore"}),o.on("error",i=>{console.error(x.red(`
44
- \u274C Failed to Start Local Node`)),console.error(x.red(` \u2514\u2500 Error: ${i.message}`))}),await L(5e3),console.log(" \u251C\u2500 Faucet: Enabled"),console.log(` \u251C\u2500 Force Regenesis: ${t?"Yes":"No"}`),console.log(" \u251C\u2500 HTTP server: http://127.0.0.1:9000/"),console.log(" \u2514\u2500 Faucet server: http://127.0.0.1:9123/"),await Nt(),await L(2e3),pe("suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c")===!1)throw new N("Please check your privateKey.");console.log(x.green("\u{1F389} Local environment is ready!")),Mt(o),await new Promise(i=>{o?.on("exit",()=>i())})}catch(n){console.error(x.red(`
45
- \u274C Failed to Start Local Node`)),console.error(x.red(` \u2514\u2500 Error: ${n.message}`)),o&&o.kill("SIGINT"),process.exit(1)}}var Ft={command:"node",describe:"Manage local Sui node",builder:{"data-dir":{type:"string",default:".chk",desc:"Path to the data directory"},force:{type:"boolean",default:!1,desc:"Force restart: stop existing node and remove data directory"}},async handler({"data-dir":e,force:t}){try{await Ie(e,t)}catch(o){console.error("Error executing command:",o),process.exit(1)}}},Ae=Ft;import{requestSuiFromFaucetV0 as Rt,getFaucetHost as jt}from"@mysten/sui/faucet";import{SuiClient as Ot,getFullnodeUrl as Ht}from"@mysten/sui/client";var he=60,Vt=1e3,Ne=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Lt={command:"faucet",describe:"Interact with a Dubhe faucet",builder(e){return e.options({network:{type:"string",desc:"URL of the Dubhe faucet",choices:["testnet","devnet","localnet"],default:"localnet"},recipient:{type:"string",desc:"Sui address to fund"}})},async handler({network:e,recipient:t}){let o="";t===void 0?o=V(e).getAddress():o=t,console.log(`
37
+ `)}else console.log(P.yellow(" \u2514\u2500 Deploy hook execution failed")),console.log(P.yellow(" Please republish or manually call deploy_hook::run")),console.log(P.yellow(" Please check the transaction digest:")),console.log(P.yellow(` ${E.digest}`)),process.exit(1)}async function Tt(e){return N.existsSync(e)?!0:(console.log(P.yellow(`
38
+ \u2139\uFE0F Dubhe Framework Files Not Found`)),console.log(P.yellow(" \u251C\u2500 Expected Path:"),e),console.log(P.yellow(" \u251C\u2500 To set up Dubhe Framework:")),console.log(P.yellow(" \u2502 1. Create directory: mkdir -p contracts/dubhe")),console.log(P.yellow(" \u2502 2. Clone repository: git clone https://github.com/0xobelisk/dubhe contracts/dubhe")),console.log(P.yellow(" \u2502 3. Or download from: https://github.com/0xobelisk/dubhe")),console.log(P.yellow(" \u2514\u2500 After setup, restart the local node")),!1)}async function Et(e,t){let n=`${process.cwd()}/src/dubhe`;if(!await Tt(n))return;console.log(`
39
+ \u{1F680} Starting Dubhe Framework Publication...`),console.log(" \u251C\u2500 Waiting for node...");let s=await Te(e);await Pe(`${n}/Move.lock`,t),await fe(n,"0x0");let[i,a]=De(n),u=new re,[d]=u.publish({modules:i,dependencies:a});u.transferObjects([d],e.getAddress());let c;try{c=await e.signAndSendTxn({tx:u})}catch(l){console.error(P.red(" \u2514\u2500 Publication failed")),console.error(l.message),process.exit(1)}(!c||c.effects?.status.status==="failure")&&(console.log(P.red(" \u2514\u2500 Publication failed")),process.exit(1));let m=1,f="",h="",y="";c.objectChanges.map(l=>{l.type==="published"&&(f=l.packageId||""),l.type==="created"&&l.objectType&&l.objectType==="0x2::package::UpgradeCap"&&(y=l.objectId||""),l.type==="created"&&l.objectType&&l.objectType.includes("dapp_service::DappHub")&&(h=l.objectId||"")}),await L(3e3);let C=new re;C.moveCall({target:`${f}::genesis::run`,arguments:[C.object(h),C.object("0x6")]});let D;try{D=await e.signAndSendTxn({tx:C})}catch(l){console.error(P.red(" \u2514\u2500 Deploy hook execution failed")),console.error(l.message),process.exit(1)}if(D.effects?.status.status!=="success")throw new Error("Deploy hook execution failed");await fe(n,f),await me("dubhe",t,f,"0",h,y,m,{},{},{}),_e(`${n}/Move.lock`,t,"publish",s,f)}async function Ee(e,t,o){await q(t);let n=V({network:t}),i=`${process.cwd()}/src/${e.name}`;t==="localnet"&&e.name!=="dubhe"&&await Et(n,t),e.name!=="dubhe"&&await se(`${i}/Move.toml`,t),await Dt(n,e,t,i,o)}import{Dubhe as It}from"@0xobelisk/sui-client";import*as ie from"fs";function At(){console.log(x.yellow("\u{1F514} Stopping existing Local Node..."));let e=!1;if(process.platform==="win32")try{B("taskkill /F /IM sui.exe",{stdio:"ignore"}),e=!0}catch{}else{let t=["sui start","sui.*start","^sui","sui.*--with-faucet"];for(let o of t)try{let n=B(`pgrep -f "${o}"`,{stdio:"pipe"}).toString().trim();if(n){let s=n.split(`
40
+ `).filter(i=>i);console.log(x.cyan(` \u251C\u2500 Found ${s.length} process(es) matching "${o}"`)),s.forEach(i=>{try{B(`kill -TERM ${i}`,{stdio:"ignore"}),console.log(x.cyan(` \u251C\u2500 Sent SIGTERM to process ${i}`))}catch{try{B(`kill -KILL ${i}`,{stdio:"ignore"}),console.log(x.cyan(` \u251C\u2500 Force killed process ${i}`))}catch{console.log(x.gray(` \u251C\u2500 Process ${i} already terminated`))}}}),e=!0;break}}catch{continue}}console.log(e?x.green(" \u2514\u2500 Local Node stopped successfully"):x.gray(" \u2514\u2500 No running Local Node found"))}function Nt(e){try{ie.existsSync(e)?(console.log(x.yellow(`\u{1F5D1}\uFE0F Removing directory: ${e}`)),ie.rmSync(e,{recursive:!0,force:!0}),console.log(x.green(" \u2514\u2500 Directory removed successfully"))):console.log(x.gray(` \u2514\u2500 Directory ${e} does not exist`))}catch(t){console.error(x.red(` \u2514\u2500 Error removing directory: ${t.message}`))}}function Rt(){try{if(process.platform==="win32")return B('tasklist /FI "IMAGENAME eq sui.exe" /FO CSV /NH').toString().trim().toLowerCase().includes("sui.exe");{let e=["sui start","sui.*start","^sui","sui.*--with-faucet"];for(let t of e)try{let o=B(`pgrep -f "${t}"`,{stdio:"pipe"}).toString().trim();if(o&&o.length>0)return!0}catch{continue}return!1}}catch{return!1}}async function Mt(){let e=["suiprivkey1qq3ez3dje66l8pypgxynr7yymwps6uhn7vyczespj84974j3zya0wdpu76v","suiprivkey1qp6vcyg8r2x88fllmjmxtpzjl95gd9dugqrgz7xxf50w6rqdqzetg7x4d7s","suiprivkey1qpy3a696eh3m55fwa8h38ss063459u4n2dm9t24w2hlxxzjp2x34q8sdsnc","suiprivkey1qzxwp29favhzrjd95f6uj9nskjwal6nh9g509jpun395y6g72d6jqlmps4c","suiprivkey1qzhq4lv38sesah4uzsqkkmeyjx860xqjdz8qgw36tmrdd5tnle3evxpng57","suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c"];console.log("\u{1F4DD}Accounts"),console.log("=========="),e.forEach((t,o)=>{let s=new It({secretKey:t}).getSigner();Ie("curl",["--location","--request","POST","http://127.0.0.1:9123/gas","--header","Content-Type: application/json","--data-raw",`{"FixedAmountRequest": {"recipient": "${s.toSuiAddress()}"}}`],{env:{...process.env},stdio:"ignore",detached:!0}),console.log(` \u250C\u2500 Account #${o}: ${s.toSuiAddress()}(1000 SUI)`),console.log(` \u2514\u2500 Private Key: ${t}`)}),console.log("=========="),console.log(x.yellow("\u2139\uFE0F WARNING: These accounts, and their private keys, are publicly known.")),console.log(x.yellow("Any funds sent to them on Mainnet or any other live network WILL BE LOST."))}function Ft(e){let t=()=>{console.log(x.yellow(`
41
+ \u{1F514} Stopping Local Node...`)),e&&e.kill("SIGINT"),process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t)}async function Ae(e,t){if(t)console.log(x.cyan(`
42
+ \u{1F504} Force mode enabled`)),At(),console.log(x.yellow(" \u251C\u2500 Waiting for processes to terminate...")),await L(3e3),Nt(e),console.log("");else if(Rt()){console.log(x.yellow(`
43
+ \u26A0\uFE0F Warning: Local Node Already Running`)),console.log(x.yellow(" \u251C\u2500 Cannot start a new instance")),console.log(x.yellow(" \u2514\u2500 Please stop the existing process first"));return}te(),console.log("\u{1F680} Starting Local Node...");let o=null;try{let n=["start","--with-faucet"];if(t&&n.push("--force-regenesis"),n.push("--data-ingestion-dir",e),o=Ie("sui",n,{env:{...process.env,RUST_LOG:"off,sui_node=info"},stdio:"ignore"}),o.on("error",i=>{console.error(x.red(`
44
+ \u274C Failed to Start Local Node`)),console.error(x.red(` \u2514\u2500 Error: ${i.message}`))}),await L(5e3),console.log(" \u251C\u2500 Faucet: Enabled"),console.log(` \u251C\u2500 Force Regenesis: ${t?"Yes":"No"}`),console.log(" \u251C\u2500 RPC server: http://127.0.0.1:9000/"),console.log(" \u2514\u2500 Faucet server: http://127.0.0.1:9123/"),await Mt(),await L(2e3),pe("suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c")===!1)throw new A("Please check your privateKey.");console.log(x.green("\u{1F389} Local environment is ready!")),Ft(o),await new Promise(i=>{o?.on("exit",()=>i())})}catch(n){console.error(x.red(`
45
+ \u274C Failed to Start Local Node`)),console.error(x.red(` \u2514\u2500 Error: ${n.message}`)),o&&o.kill("SIGINT"),process.exit(1)}}var jt={command:"node",describe:"Manage local Sui node",builder:{"data-dir":{type:"string",default:".chk",desc:"Path to the data directory"},force:{type:"boolean",default:!1,desc:"Force restart: stop existing node and remove data directory"}},async handler({"data-dir":e,force:t}){try{await Ae(e,t)}catch(o){console.error("Error executing command:",o),process.exit(1)}}},Ne=jt;import{requestSuiFromFaucetV0 as Ot,getFaucetHost as Ht}from"@mysten/sui/faucet";import{SuiClient as Vt,getFullnodeUrl as Lt}from"@mysten/sui/client";var he=60,Ut=1e3,Re=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],zt={command:"faucet",describe:"Interact with a Dubhe faucet",builder(e){return e.options({network:{type:"string",desc:"URL of the Dubhe faucet",choices:["testnet","devnet","localnet"],default:"localnet"},recipient:{type:"string",desc:"Sui address to fund"}})},async handler({network:e,recipient:t}){let o="";t===void 0?o=V(e).getAddress():o=t,console.log(`
46
46
  \u{1F30A} Starting Faucet Operation...`),console.log(` \u251C\u2500 Network: ${e}`),t===void 0?(console.log(" \u251C\u2500 Using Environment PrivateKey"),console.log(` \u251C\u2500 Generated Address: ${o}`)):console.log(` \u251C\u2500 Using Provided Address: ${o}`),console.log(" \u251C\u2500 Requesting funds from faucet...");let n=0,s=!1,i=0,a=Date.now(),u=!1,d=()=>{u=!0,process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(`
47
- \u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",d);try{for(;n<he&&!s&&!u;)try{await Rt({host:jt(e),recipient:o}),s=!0}catch{if(u)break;n++,n===he&&(console.log(` \u2514\u2500 Failed to request funds after ${he} attempts.`),console.log(" \u2514\u2500 Please check your network connection and try again later."),process.exit(1));let y=Math.floor((Date.now()-a)/1e3),C=Ne[i%Ne.length];i++,process.stdout.write(`\r \u251C\u2500 ${C} Retrying... (${y}s)`),await new Promise(D=>setTimeout(D,Vt))}}finally{process.removeListener("SIGINT",d)}u&&process.exit(0),process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(" \u2514\u2500 Checking balance...");let c=new Ot({url:Ht(e)}),m={owner:o},f=await c.getBalance(m);console.log(`
47
+ \u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",d);try{for(;n<he&&!s&&!u;)try{await Ot({host:Ht(e),recipient:o}),s=!0}catch{if(u)break;n++,n===he&&(console.log(` \u2514\u2500 Failed to request funds after ${he} attempts.`),console.log(" \u2514\u2500 Please check your network connection and try again later."),process.exit(1));let y=Math.floor((Date.now()-a)/1e3),C=Re[i%Re.length];i++,process.stdout.write(`\r \u251C\u2500 ${C} Retrying... (${y}s)`),await new Promise(D=>setTimeout(D,Ut))}}finally{process.removeListener("SIGINT",d)}u&&process.exit(0),process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(" \u2514\u2500 Checking balance...");let c=new Vt({url:Lt(e)}),m={owner:o},f=await c.getBalance(m);console.log(`
48
48
  \u{1F4B0} Account Summary`),console.log(` \u251C\u2500 Address: ${o}`),console.log(` \u2514\u2500 Balance: ${(Number(f.totalBalance)/1e9).toFixed(4)} SUI`),console.log(`
49
49
  \u2705 Faucet Operation Complete
50
- `),process.exit(0)}},Me=Lt;import{schemaGen as Ut,loadConfig as zt}from"@0xobelisk/sui-common";import Wt from"chalk";import qt from"node:path";var Bt={command:"schemagen",describe:"Autogenerate Dubhe schemas based on the config file",builder:{"config-path":{type:"string",default:"dubhe.config.ts",desc:"Path to the config file"},network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Node network (mainnet/testnet/devnet/localnet)"}},async handler({"config-path":e,network:t}){try{if(!e)throw new Error("Config path is required");let o=await zt(e),n=qt.dirname(e);await Ut(n,o,t),process.exit(0)}catch(o){console.log(Wt.red("Schemagen failed!")),console.error(o.message)}}},Fe=Bt;import{loadConfig as Kt}from"@0xobelisk/sui-common";import{execSync as Gt}from"child_process";var Yt={command:"publish",describe:"Publish dubhe move contract",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Node network (mainnet/testnet/devnet/localnet)"},"config-path":{type:"string",default:"dubhe.config.ts",desc:"Configuration file path"},"gas-budget":{type:"number",desc:"Optional gas budget for the transaction",optional:!0}})},async handler({network:e,"config-path":t,"gas-budget":o}){try{let n=await Kt(t);Gt(`pnpm dubhe convert-json --config-path ${t}`,{encoding:"utf-8"}),await Te(n,e,o)}catch(n){H(n),process.exit(1)}process.exit(0)}},Re=Yt;import{execSync as Jt}from"child_process";import{loadConfig as Qt}from"@0xobelisk/sui-common";var Xt={command:"test",describe:"Run tests in Dubhe contracts",builder(e){return e.options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Options to pass to forge test"},test:{type:"string",desc:"Run a specific test"},"gas-limit":{type:"string",desc:"Set the gas limit for the test",default:"100000000"}})},async handler({"config-path":e,test:t,"gas-limit":o}){try{console.log("\u{1F680} Running move test");let n=await Qt(e),a=`sui move test --path ${`${process.cwd()}/src/${n.name}`} ${t?` --test ${t}`:""} --gas-limit ${o}`;Jt(a,{stdio:"inherit",encoding:"utf-8"})}catch{process.exit(0)}}},je=Xt;import{execSync as Zt,exec as eo}from"child_process";import to from"chalk";import{loadConfig as oo}from"@0xobelisk/sui-common";var no={command:"build",describe:"Run tests in Dubhe contracts",builder(e){return e.options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Options to pass to forge test"},network:{type:"string",default:"localnet",choices:["mainnet","testnet","devnet","localnet"],desc:"Node network (mainnet/testnet/devnet/localnet)"},"dump-bytecode-as-base64":{type:"boolean",default:!1,desc:"Dump bytecode as base64"}})},async handler({"config-path":e,network:t,"dump-bytecode-as-base64":o}){try{console.log("\u{1F680} Running move build");let n=await oo(e),i=`${process.cwd()}/src/${n.name}`;await q(t),await se(i+"/Move.toml",t);let a=`sui move build --path ${i} ${o?" --dump-bytecode-as-base64":""}`,u=Zt(a,{encoding:"utf-8"});console.log(u),eo(`pnpm dubhe convert-json --config-path ${e}`)}catch(n){console.error(to.red("Error executing sui move build:")),console.log(n.stdout),process.exit(0)}}},Oe=no;var so={command:"hello",describe:"hello, dubhe",builder(e){return e},async handler(){te()}},He=so;import{Dubhe as Ve}from"@0xobelisk/sui-client";import*as Q from"fs";import J from"chalk";async function Le(e=!1,t=!1){t&&(console.log(J.gray("Note: The generated account will be stored in the .env file with NEXT_PUBLIC_ prefix for client-side usage.")),console.log(J.yellow(`Warning: Do not expose the .env file, it is intended for local testing only.
51
- `)));let o=process.cwd(),n,s="";try{s=Q.readFileSync(`${o}/.env`,"utf8");let i=process.env.PRIVATE_KEY||process.env.NEXT_PUBLIC_PRIVATE_KEY;if(t&&(i=process.env.NEXT_PUBLIC_PRIVATE_KEY||process.env.PRIVATE_KEY),i){let a=t?"NEXT_PUBLIC_PRIVATE_KEY":"PRIVATE_KEY",u=s.split(`
50
+ `),process.exit(0)}},Me=zt;import{schemaGen as Wt,loadConfig as qt}from"@0xobelisk/sui-common";import Bt from"chalk";import Kt from"node:path";var Gt={command:"schemagen",describe:"Autogenerate Dubhe schemas based on the config file",builder:{"config-path":{type:"string",default:"dubhe.config.ts",desc:"Path to the config file"},network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Node network (mainnet/testnet/devnet/localnet)"}},async handler({"config-path":e,network:t}){try{if(!e)throw new Error("Config path is required");let o=await qt(e),n=Kt.dirname(e);await Wt(n,o,t),process.exit(0)}catch(o){console.log(Bt.red("Schemagen failed!")),console.error(o.message)}}},Fe=Gt;import{loadConfig as Yt}from"@0xobelisk/sui-common";import{execSync as Jt}from"child_process";var Xt={command:"publish",describe:"Publish dubhe move contract",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Node network (mainnet/testnet/devnet/localnet)"},"config-path":{type:"string",default:"dubhe.config.ts",desc:"Configuration file path"},"gas-budget":{type:"number",desc:"Optional gas budget for the transaction",optional:!0}})},async handler({network:e,"config-path":t,"gas-budget":o}){try{let n=await Yt(t);Jt(`pnpm dubhe convert-json --config-path ${t}`,{encoding:"utf-8"}),await Ee(n,e,o)}catch(n){H(n),process.exit(1)}process.exit(0)}},je=Xt;import{execSync as Qt}from"child_process";import{loadConfig as Zt}from"@0xobelisk/sui-common";var eo={command:"test",describe:"Run tests in Dubhe contracts",builder(e){return e.options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Options to pass to forge test"},test:{type:"string",desc:"Run a specific test"},"gas-limit":{type:"string",desc:"Set the gas limit for the test",default:"100000000"}})},async handler({"config-path":e,test:t,"gas-limit":o}){try{console.log("\u{1F680} Running move test");let n=await Zt(e),a=`sui move test --path ${`${process.cwd()}/src/${n.name}`} ${t?` --test ${t}`:""} --gas-limit ${o}`;Qt(a,{stdio:"inherit",encoding:"utf-8"})}catch{process.exit(0)}}},Oe=eo;import{execSync as to,exec as oo}from"child_process";import no from"chalk";import{loadConfig as so}from"@0xobelisk/sui-common";var ro={command:"build",describe:"Run tests in Dubhe contracts",builder(e){return e.options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Options to pass to forge test"},network:{type:"string",default:"localnet",choices:["mainnet","testnet","devnet","localnet"],desc:"Node network (mainnet/testnet/devnet/localnet)"},"dump-bytecode-as-base64":{type:"boolean",default:!1,desc:"Dump bytecode as base64"}})},async handler({"config-path":e,network:t,"dump-bytecode-as-base64":o}){try{console.log("\u{1F680} Running move build");let n=await so(e),i=`${process.cwd()}/src/${n.name}`;await q(t),await se(i+"/Move.toml",t);let a=`sui move build --path ${i} ${o?" --dump-bytecode-as-base64":""}`,u=to(a,{encoding:"utf-8"});console.log(u),oo(`pnpm dubhe convert-json --config-path ${e}`)}catch(n){console.error(no.red("Error executing sui move build:")),console.log(n.stdout),process.exit(0)}}},He=ro;var io={command:"hello",describe:"hello, dubhe",builder(e){return e},async handler(){te()}},Ve=io;import{Dubhe as Le}from"@0xobelisk/sui-client";import*as X from"fs";import J from"chalk";async function Ue(e=!1,t=!1){t&&(console.log(J.gray("Note: The generated account will be stored in the .env file with NEXT_PUBLIC_ prefix for client-side usage.")),console.log(J.yellow(`Warning: Do not expose the .env file, it is intended for local testing only.
51
+ `)));let o=process.cwd(),n,s="";try{s=X.readFileSync(`${o}/.env`,"utf8");let i=process.env.PRIVATE_KEY||process.env.NEXT_PUBLIC_PRIVATE_KEY;if(t&&(i=process.env.NEXT_PUBLIC_PRIVATE_KEY||process.env.PRIVATE_KEY),i){let a=t?"NEXT_PUBLIC_PRIVATE_KEY":"PRIVATE_KEY",u=s.split(`
52
52
  `),d=!1;for(let f=u.length-1;f>=0;f--){let h=u[f];if(h.endsWith(i)){let[y]=h.split("=");t?d=y==="PRIVATE_KEY":d=y==="NEXT_PUBLIC_PRIVATE_KEY";break}}if(d){for(let f=u.length-1;f>=0;f--)if(u[f].endsWith(i)){let y=`${a}=${i}`;u[f]=y,s=u.join(`
53
- `),Q.writeFileSync(`${o}/.env`,s);break}}let m=new Ve({secretKey:i}).getSigner();console.log(J.blue(`Using existing account: ${m.toSuiAddress()}`));return}}catch{}if(e||!n){let a=new Ve().getSigner();n=a.getSecretKey();let d=`${t?"NEXT_PUBLIC_PRIVATE_KEY":"PRIVATE_KEY"}=${n}`;s?s=s.trim()+`
54
- `+d:s=d,Q.writeFileSync(`${o}/.env`,s),console.log(J.green(`File created/updated at: ${o}/.env`)),console.log(J.blue(`New account generated: ${a.toSuiAddress()}`))}}var ro={command:"generate-key",describe:"Generate a new account keypair and save it to a .env file",builder:{force:{type:"boolean",default:!1,desc:"Force generate a new keypair"},"use-next-public":{type:"boolean",default:!1,desc:"Use the NEXT_PUBLIC_ prefix for client-side usage"}},async handler({force:e,"use-next-public":t}){try{await Le(e,t)}catch(o){console.error("Error generating account:",o),process.exit(1)}process.exit(0)}},Ue=ro;import io from"chalk";import ao from"dotenv";ao.config();async function ze(e){try{let o=await V({network:e}).getBalance(),n=Number(o.totalBalance)/1e9;if(n===0)throw new N("Your account balance is 0 SUI. Please get some SUI to proceed.");console.log(io.green(`Current account balance: ${n.toFixed(4)} SUI`))}catch(t){throw new N("Failed to check balance: "+t)}}var lo={command:"check-balance",describe:"Check the balance of the account",builder:{network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Network to check balance on",default:"localnet"}},async handler({network:e}){try{await ze(e)}catch(t){console.error("Error checking balance:",t),process.exit(1)}process.exit(0)}},We=lo;import{mkdirSync as co,writeFileSync as uo}from"fs";import{dirname as po}from"path";async function go(e,t,o){let n=await ne(e),s=`type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
53
+ `),X.writeFileSync(`${o}/.env`,s);break}}let m=new Le({secretKey:i}).getSigner();console.log(J.blue(`Using existing account: ${m.toSuiAddress()}`));return}}catch{}if(e||!n){let a=new Le().getSigner();n=a.getSecretKey();let d=`${t?"NEXT_PUBLIC_PRIVATE_KEY":"PRIVATE_KEY"}=${n}`;s?s=s.trim()+`
54
+ `+d:s=d,X.writeFileSync(`${o}/.env`,s),console.log(J.green(`File created/updated at: ${o}/.env`)),console.log(J.blue(`New account generated: ${a.toSuiAddress()}`))}}var ao={command:"generate-key",describe:"Generate a new account keypair and save it to a .env file",builder:{force:{type:"boolean",default:!1,desc:"Force generate a new keypair"},"use-next-public":{type:"boolean",default:!1,desc:"Use the NEXT_PUBLIC_ prefix for client-side usage"}},async handler({force:e,"use-next-public":t}){try{await Ue(e,t)}catch(o){console.error("Error generating account:",o),process.exit(1)}process.exit(0)}},ze=ao;import lo from"chalk";import co from"dotenv";co.config();async function We(e){try{let o=await V({network:e}).getBalance(),n=Number(o.totalBalance)/1e9;if(n===0)throw new A("Your account balance is 0 SUI. Please get some SUI to proceed.");console.log(lo.green(`Current account balance: ${n.toFixed(4)} SUI`))}catch(t){throw new A("Failed to check balance: "+t)}}var uo={command:"check-balance",describe:"Check the balance of the account",builder:{network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Network to check balance on",default:"localnet"}},async handler({network:e}){try{await We(e)}catch(t){console.error("Error checking balance:",t),process.exit(1)}process.exit(0)}},qe=uo;import{mkdirSync as po,writeFileSync as go}from"fs";import{dirname as mo}from"path";async function fo(e,t,o){let n=await ne(e),s=`type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
55
55
 
56
56
  export const NETWORK: NetworkType = '${e}';
57
57
  export const PACKAGE_ID = '${t}';
58
58
  export const DUBHE_SCHEMA_ID = '${n}';
59
- `;mo(s,o,"storeConfig")}async function mo(e,t,o){co(po(t),{recursive:!0}),uo(t,e),o!==void 0&&console.log(`${o}: ${t}`)}async function qe(e,t,o){let s=`${process.cwd()}/src/${e.name}`,i=await ge(s,t);await go(i.network,i.packageId,o)}import{loadConfig as fo}from"@0xobelisk/sui-common";var ho={command:"config-store",describe:"Store configuration for the Dubhe project",builder:{"config-path":{type:"string",default:"dubhe.config.ts",desc:"Path to the config file"},network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Network to store config for"},"output-ts-path":{type:"string",desc:"Specify the output path for the generated TypeScript configuration file (e.g., ./src/config/generated.ts)"}},async handler({"config-path":e,network:t,"output-ts-path":o}){try{let n=await fo(e);await qe(n,t,o)}catch(n){console.error("Error storing config:",n),process.exit(1)}process.exit(0)}},Be=ho;import yo from"chokidar";import{exec as bo}from"child_process";var wo={command:"watch",describe:"Watch dubhe config",builder(e){return e},async handler(){let e="dubhe.config.ts",t=()=>{bo("pnpm dubhe schemagen",(n,s,i)=>{if(n){console.error(`Error executing schemagen: ${n.message}`);return}if(i){console.error(`schemagen stderr: ${i}`);return}console.log(`schemagen stdout: ${s}`)})},o=yo.watch(e,{persistent:!0});o.on("change",n=>{console.log(`${n} has been changed. Running schemagen...`),t()}),console.log(`Watching for changes in ${e}...`),process.on("SIGINT",()=>{o.close(),console.log(`
60
- Watch stopped.`),process.exit()})}},Ke=wo;import vo from"wait-on";import xo from"ora";import I from"chalk";var ko={command:"wait",describe:"Wait for service(s) to be ready",builder(e){return e.option("url",{type:"string",description:"URL to wait for (single service)"}).option("localnet",{type:"boolean",description:"Wait for all dubhe localnet services (sui localnode:9000&9123, postgres:5432, graphql:4000)",default:!1}).option("timeout",{type:"number",description:"Timeout (in milliseconds)",default:18e4}).option("interval",{type:"number",description:"Check interval (in milliseconds)",default:1e3}).check(t=>{if(!t.url&&!t.localnet)throw new Error("Please provide either --url or --localnet option");if(t.url&&t.localnet)throw new Error("Cannot use both --url and --localnet options together");return!0})},async handler(e){let t=e,o,n;t.localnet?(o=["http://localhost:9000","http://localhost:9123","tcp:localhost:5432","http://localhost:4000"],n="dubhe localnet services"):(o=[t.url],n=t.url);let s=xo({text:`Waiting for ${n}...`,color:"cyan"});s.start();try{await vo({resources:o,timeout:t.timeout,interval:t.interval,validateStatus:i=>i===200}),s.succeed(I.green(t.localnet?"All dubhe localnet services are ready!":"Service is ready!")),t.localnet&&(console.log(I.gray("\u2713 Sui localnode (9000)")),console.log(I.gray("\u2713 Sui faucet (9123)")),console.log(I.gray("\u2713 PostgreSQL database (5432)")),console.log(I.gray("\u2713 Dubhe GraphQL server (4000)"))),process.exit(0)}catch{s.fail(I.red(t.localnet?"Timeout waiting for dubhe localnet services":"Timeout waiting for service")),t.localnet?(console.error(I.yellow("Please make sure all required services are running:")),console.error(I.yellow("- Sui localnode on port 9000")),console.error(I.yellow("- Sui faucet on port 9123")),console.error(I.yellow("- PostgreSQL database on port 5432")),console.error(I.yellow("- Dubhe GraphQL server on port 4000"))):console.error(I.yellow("Please make sure the service is running...")),process.exit(1)}}},Ge=ko;var Co={command:"switch-env",describe:"Switch environment",builder(e){return e.option("network",{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Switch to node network (mainnet/testnet/devnet/localnet)"})},async handler(e){await q(e.network)}},Ye=Co;import $o from"dotenv";import K from"chalk";$o.config();var So={command:"info",describe:"Get information about the current Sui node",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Node network (mainnet/testnet/devnet/localnet)"}})},handler:async({network:e})=>{try{let t=V({network:e}),o=t.getSigner();console.log(K.blue("Account Information:")),console.log(` Network: ${K.green(e)}`),console.log(` Address: ${K.green(o.toSuiAddress())}`);try{let n=await t.getBalance("0x2::sui::SUI"),s=(Number(n.totalBalance)/10**9).toFixed(4);console.log(` Balance: ${K.green(s)} SUI`)}catch{console.log(` Balance: ${K.red("Failed to fetch balance")} ${K.gray("(Network error)")}`)}}catch(t){H(t),process.exit(1)}}},Je=So;import{loadConfig as _o}from"@0xobelisk/sui-common";async function Qe(e,t,o){if(o)await Y(e.name,t,o);else{let n=`${process.cwd()}/src/${e.name}`,s=await ke(n,t);await Y(e.name,t,s)}}var Po={command:"load-metadata",describe:"Load metadata for a package",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Node network (mainnet/testnet/devnet/localnet)"},"config-path":{type:"string",desc:"Configuration file path",default:"dubhe.config.ts"},"package-id":{type:"string",desc:"Package ID to load metadata for",optional:!0}})},async handler({network:e,"config-path":t,"package-id":o}){try{let n=await _o(t);await Qe(n,e,o)}catch(n){H(n),process.exit(1)}process.exit(0)}},Xe=Po;import r from"chalk";import{spawn as Do}from"child_process";import Ze from"cli-table3";import ae from"inquirer";import*as ot from"cli-progress";import*as w from"fs";import*as P from"path";import*as U from"os";import*as nt from"net";import{HttpsProxyAgent as et}from"https-proxy-agent";import{HttpProxyAgent as To}from"http-proxy-agent";function be(){let e=process.platform,t=process.arch,o,n;switch(e){case"darwin":o="macos";break;case"win32":o="windows";break;case"linux":o="ubuntu";break;default:o=e}switch(t){case"x64":n="x86_64";break;case"arm64":n="aarch64";break;default:n=t}return{platform:e,arch:t,platformForAsset:o,archForAsset:n}}var A={sui:{name:"sui",repo:"MystenLabs/sui",binaryName:"sui",installDir:P.join(U.homedir(),".dubhe","bin")},"dubhe-indexer":{name:"dubhe-indexer",repo:"0xobelisk/dubhe-wip",binaryName:"dubhe-indexer",installDir:P.join(U.homedir(),".dubhe","bin")}};async function O(e,t=[]){return new Promise(o=>{let n=Do(e,t,{shell:!0}),s="",i="";n.stdout?.on("data",a=>{s+=a.toString()}),n.stderr?.on("data",a=>{i+=a.toString()}),n.on("close",a=>{o({code:a||0,stdout:s,stderr:i})}),n.on("error",()=>{o({code:-1,stdout:s,stderr:i})})})}async function Eo(e,t){let o=await we(e,{headers:{"User-Agent":"dubhe-cli"}});if(!o.ok)throw new Error(`HTTP ${o.status}: ${o.statusText}`);let n=o.headers.get("content-length"),s=n?parseInt(n):0,i=new ot.SingleBar({format:r.cyan("Download Progress")+" |{bar}| {percentage}% | {value}/{total} MB | Speed: {speed} MB/s | ETA: {eta}s",barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0,barsize:30,forceRedraw:!0});s>0?i.start(Math.round(s/1024/1024*100)/100,0,{speed:"0.00"}):console.log(r.blue("\u{1F4E5} Downloading... (unable to get file size)"));let a=o.body?.getReader();if(!a)throw new Error("Unable to get response stream");let u=[],d=0,c=Date.now();try{for(;;){let{done:l,value:$}=await a.read();if(l)break;if(u.push($),d+=$.length,s>0){let p=Math.round(d/1024/1024*100)/100,b=(Date.now()-c)/1e3,k=b>0?Math.round(p/b*100)/100:0;i.update(p,{speed:k.toFixed(2)})}}let m=u.reduce((l,$)=>l+$.length,0),f=new Uint8Array(m),h=0;for(let l of u)f.set(l,h),h+=l.length;w.writeFileSync(t,f),s>0&&i.stop();let y=Math.round(d/1024/1024*100)/100,C=(Date.now()-c)/1e3,D=C>0?Math.round(y/C*100)/100:0;console.log(r.green(`\u2713 Download completed! ${y} MB, average speed: ${D} MB/s`))}catch(m){throw s>0&&i.stop(),m}}async function we(e,t={}){let o=process.env.HTTP_PROXY||process.env.http_proxy,n=process.env.HTTPS_PROXY||process.env.https_proxy,s=process.env.NO_PROXY||process.env.no_proxy;if(s){let u=s.split(",").map(c=>c.trim()),d=new URL(e).hostname;for(let c of u)if(c==="*"||d===c||d.endsWith("."+c)||c.startsWith(".")&&d.endsWith(c))return fetch(e,t)}let i=new URL(e).protocol,a;if(i==="https:"&&n?a=new et(n):i==="http:"&&o?a=new To(o):n&&i==="https:"&&(a=new et(n)),a)try{let u={...t,dispatcher:a};return await fetch(e,u)}catch{try{let d={...t,agent:a};return await fetch(e,d)}catch{return console.log(r.yellow(" \u26A0\uFE0F Warning: Could not use proxy, falling back to direct connection")),fetch(e,t)}}return fetch(e,t)}async function ve(e,t=10,o=3){let n=`https://api.github.com/repos/${e}/releases?per_page=${t}`;for(let s=1;s<=o;s++)try{s>1&&console.log(r.gray(` Retry ${s}/${o}...`));let i=await we(n,{headers:{"User-Agent":"dubhe-cli",Accept:"application/vnd.github.v3+json"}});if(!i.ok)throw i.status===403?new Error(`GitHub API rate limit: ${i.status}. Please retry later or set GITHUB_TOKEN environment variable`):new Error(`GitHub API request failed: ${i.status} ${i.statusText}`);return await i.json()}catch(i){if(s>1&&console.log(r.yellow(` \u26A0\uFE0F Attempt ${s} failed: ${i instanceof Error?i.message:String(i)}`)),s===o)return console.error(r.red(` \u274C Failed to fetch releases after ${o} attempts`)),[];await new Promise(a=>setTimeout(a,1e3*s))}return[]}function Z(e,t){return e.assets.filter(n=>{let s=n.name.toLowerCase(),i=[t.platformForAsset.toLowerCase(),...t.platformForAsset==="macos"?["darwin","apple"]:[],...t.platformForAsset==="windows"?["win","win32","windows"]:[],...t.platformForAsset==="ubuntu"?["linux","gnu"]:[]],a=[t.archForAsset.toLowerCase(),...t.archForAsset==="x86_64"?["amd64","x64"]:[],...t.archForAsset==="aarch64"?["arm64"]:[]],u=i.some(m=>s.includes(m)),d=a.some(m=>s.includes(m)),c=s.endsWith(".tar.gz")||s.endsWith(".zip")||s.endsWith(".tgz")||s.endsWith(".tar.bz2")||s.endsWith(".tar.xz");return u&&d&&c}).map(n=>n.name)}async function Io(e,t){let o=A[e];return o?(await ve(o.repo,10)).map(s=>({version:s.tag_name,hasCompatibleAsset:Z(s,t).length>0})):[]}async function Ao(e){try{let t=ee();if(!t){console.log(r.gray(`Please add to PATH: export PATH="$PATH:${e}"`));return}let{shellName:o,configFile:n}=t,s=o==="fish"?`set -gx PATH $PATH ${e}`:`export PATH="$PATH:${e}"`;if(w.existsSync(n)&&w.readFileSync(n,"utf8").includes(e)){console.log(r.green(` \u2713 PATH already configured in ${n}`));return}let a=`# Added by dubhe doctor
59
+ `;ho(s,o,"storeConfig")}async function ho(e,t,o){po(mo(t),{recursive:!0}),go(t,e),o!==void 0&&console.log(`${o}: ${t}`)}async function Be(e,t,o){let s=`${process.cwd()}/src/${e.name}`,i=await ge(s,t);await fo(i.network,i.packageId,o)}import{loadConfig as yo}from"@0xobelisk/sui-common";var bo={command:"config-store",describe:"Store configuration for the Dubhe project",builder:{"config-path":{type:"string",default:"dubhe.config.ts",desc:"Path to the config file"},network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Network to store config for"},"output-ts-path":{type:"string",desc:"Specify the output path for the generated TypeScript configuration file (e.g., ./src/config/generated.ts)"}},async handler({"config-path":e,network:t,"output-ts-path":o}){try{let n=await yo(e);await Be(n,t,o)}catch(n){console.error("Error storing config:",n),process.exit(1)}process.exit(0)}},Ke=bo;import wo from"chokidar";import{exec as vo}from"child_process";var xo={command:"watch",describe:"Watch dubhe config",builder(e){return e},async handler(){let e="dubhe.config.ts",t=()=>{vo("pnpm dubhe schemagen",(n,s,i)=>{if(n){console.error(`Error executing schemagen: ${n.message}`);return}if(i){console.error(`schemagen stderr: ${i}`);return}console.log(`schemagen stdout: ${s}`)})},o=wo.watch(e,{persistent:!0});o.on("change",n=>{console.log(`${n} has been changed. Running schemagen...`),t()}),console.log(`Watching for changes in ${e}...`),process.on("SIGINT",()=>{o.close(),console.log(`
60
+ Watch stopped.`),process.exit()})}},Ge=xo;import Ye from"wait-on";import ye from"ora";import j from"chalk";import ko from"net";async function Co(){return new Promise(e=>{let t=new ko.Socket,o=!1,n=setTimeout(()=>{t.destroy(),o||e(!1)},2e3);t.connect(5432,"127.0.0.1",()=>{o=!0,clearTimeout(n),t.destroy(),e(!0)}),t.on("error",()=>{clearTimeout(n),o||e(!1)})})}async function $o(e){let t=ye({text:"Waiting for dubhe localnet services...",color:"cyan"});t.start();let o=Date.now();for(;Date.now()-o<e.timeout;){try{if(await Ye({resources:["http://127.0.0.1:9123","http://127.0.0.1:4000"],timeout:e.interval,interval:500,validateStatus:s=>s===200}),await Co()){t.succeed(j.green("All dubhe localnet services are ready!"));return}}catch{}await new Promise(n=>setTimeout(n,e.interval))}throw new Error("Timeout waiting for services")}var So={command:"wait",describe:"Wait for service(s) to be ready",builder(e){return e.option("url",{type:"string",description:"URL to wait for (single service)"}).option("localnet",{type:"boolean",description:"Wait for all dubhe localnet services (sui localnode:9000&9123, postgres:5432, graphql:4000)",default:!1}).option("timeout",{type:"number",description:"Timeout (in milliseconds)",default:18e4}).option("interval",{type:"number",description:"Check interval (in milliseconds)",default:1e3}).check(t=>{if(!t.url&&!t.localnet)throw new Error("Please provide either --url or --localnet option");if(t.url&&t.localnet)throw new Error("Cannot use both --url and --localnet options together");return!0})},async handler(e){let t=e;try{if(t.localnet)await $o(t);else{let o=ye({text:`Waiting for ${t.url}...`,color:"cyan"});o.start(),await Ye({resources:[t.url],timeout:t.timeout,interval:t.interval,validateStatus:n=>n===200}),o.succeed(j.green("Service is ready!"))}process.exit(0)}catch{ye().fail(j.red(t.localnet?"Timeout waiting for dubhe localnet services":"Timeout waiting for service")),t.localnet?(console.error(j.yellow("Please make sure all required services are running:")),console.error(j.yellow("- Sui localnode on port 9000")),console.error(j.yellow("- Sui faucet on port 9123")),console.error(j.yellow("- PostgreSQL database on port 5432")),console.error(j.yellow("- Dubhe GraphQL server on port 4000"))):console.error(j.yellow("Please make sure the service is running...")),process.exit(1)}}},Je=So;var Po={command:"switch-env",describe:"Switch environment",builder(e){return e.option("network",{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Switch to node network (mainnet/testnet/devnet/localnet)"})},async handler(e){await q(e.network)}},Xe=Po;import _o from"dotenv";import K from"chalk";_o.config();var Do={command:"info",describe:"Get information about the current Sui node",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Node network (mainnet/testnet/devnet/localnet)"}})},handler:async({network:e})=>{try{let t=V({network:e}),o=t.getSigner();console.log(K.blue("Account Information:")),console.log(` Network: ${K.green(e)}`),console.log(` Address: ${K.green(o.toSuiAddress())}`);try{let n=await t.getBalance("0x2::sui::SUI"),s=(Number(n.totalBalance)/10**9).toFixed(4);console.log(` Balance: ${K.green(s)} SUI`)}catch{console.log(` Balance: ${K.red("Failed to fetch balance")} ${K.gray("(Network error)")}`)}}catch(t){H(t),process.exit(1)}}},Qe=Do;import{loadConfig as To}from"@0xobelisk/sui-common";async function Ze(e,t,o){if(o)await Y(e.name,t,o);else{let n=`${process.cwd()}/src/${e.name}`,s=await Ce(n,t);await Y(e.name,t,s)}}var Eo={command:"load-metadata",describe:"Load metadata for a package",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Node network (mainnet/testnet/devnet/localnet)"},"config-path":{type:"string",desc:"Configuration file path",default:"dubhe.config.ts"},"package-id":{type:"string",desc:"Package ID to load metadata for",optional:!0}})},async handler({network:e,"config-path":t,"package-id":o}){try{let n=await To(t);await Ze(n,e,o)}catch(n){H(n),process.exit(1)}process.exit(0)}},et=Eo;import r from"chalk";import{spawn as Io}from"child_process";import tt from"cli-table3";import ae from"inquirer";import*as st from"cli-progress";import*as w from"fs";import*as _ from"path";import*as U from"os";import*as rt from"net";import{HttpsProxyAgent as ot}from"https-proxy-agent";import{HttpProxyAgent as Ao}from"http-proxy-agent";function we(){let e=process.platform,t=process.arch,o,n;switch(e){case"darwin":o="macos";break;case"win32":o="windows";break;case"linux":o="ubuntu";break;default:o=e}switch(t){case"x64":n="x86_64";break;case"arm64":n="aarch64";break;default:n=t}return{platform:e,arch:t,platformForAsset:o,archForAsset:n}}var I={sui:{name:"sui",repo:"MystenLabs/sui",binaryName:"sui",installDir:_.join(U.homedir(),".dubhe","bin")},"dubhe-indexer":{name:"dubhe-indexer",repo:"0xobelisk/dubhe-wip",binaryName:"dubhe-indexer",installDir:_.join(U.homedir(),".dubhe","bin")}};async function O(e,t=[]){return new Promise(o=>{let n=Io(e,t,{shell:!0}),s="",i="";n.stdout?.on("data",a=>{s+=a.toString()}),n.stderr?.on("data",a=>{i+=a.toString()}),n.on("close",a=>{o({code:a||0,stdout:s,stderr:i})}),n.on("error",()=>{o({code:-1,stdout:s,stderr:i})})})}async function No(e,t){let o=await ve(e,{headers:{"User-Agent":"dubhe-cli"}});if(!o.ok)throw new Error(`HTTP ${o.status}: ${o.statusText}`);let n=o.headers.get("content-length"),s=n?parseInt(n):0,i=new st.SingleBar({format:r.cyan("Download Progress")+" |{bar}| {percentage}% | {value}/{total} MB | Speed: {speed} MB/s | ETA: {eta}s",barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0,barsize:30,forceRedraw:!0});s>0?i.start(Math.round(s/1024/1024*100)/100,0,{speed:"0.00"}):console.log(r.blue("\u{1F4E5} Downloading... (unable to get file size)"));let a=o.body?.getReader();if(!a)throw new Error("Unable to get response stream");let u=[],d=0,c=Date.now();try{for(;;){let{done:l,value:$}=await a.read();if(l)break;if(u.push($),d+=$.length,s>0){let p=Math.round(d/1024/1024*100)/100,b=(Date.now()-c)/1e3,k=b>0?Math.round(p/b*100)/100:0;i.update(p,{speed:k.toFixed(2)})}}let m=u.reduce((l,$)=>l+$.length,0),f=new Uint8Array(m),h=0;for(let l of u)f.set(l,h),h+=l.length;w.writeFileSync(t,f),s>0&&i.stop();let y=Math.round(d/1024/1024*100)/100,C=(Date.now()-c)/1e3,D=C>0?Math.round(y/C*100)/100:0;console.log(r.green(`\u2713 Download completed! ${y} MB, average speed: ${D} MB/s`))}catch(m){throw s>0&&i.stop(),m}}async function ve(e,t={}){let o=process.env.HTTP_PROXY||process.env.http_proxy,n=process.env.HTTPS_PROXY||process.env.https_proxy,s=process.env.NO_PROXY||process.env.no_proxy;if(s){let u=s.split(",").map(c=>c.trim()),d=new URL(e).hostname;for(let c of u)if(c==="*"||d===c||d.endsWith("."+c)||c.startsWith(".")&&d.endsWith(c))return fetch(e,t)}let i=new URL(e).protocol,a;if(i==="https:"&&n?a=new ot(n):i==="http:"&&o?a=new Ao(o):n&&i==="https:"&&(a=new ot(n)),a)try{let u={...t,dispatcher:a};return await fetch(e,u)}catch{try{let d={...t,agent:a};return await fetch(e,d)}catch{return console.log(r.yellow(" \u26A0\uFE0F Warning: Could not use proxy, falling back to direct connection")),fetch(e,t)}}return fetch(e,t)}async function xe(e,t=10,o=3){let n=`https://api.github.com/repos/${e}/releases?per_page=${t}`;for(let s=1;s<=o;s++)try{s>1&&console.log(r.gray(` Retry ${s}/${o}...`));let i=await ve(n,{headers:{"User-Agent":"dubhe-cli",Accept:"application/vnd.github.v3+json"}});if(!i.ok)throw i.status===403?new Error(`GitHub API rate limit: ${i.status}. Please retry later or set GITHUB_TOKEN environment variable`):new Error(`GitHub API request failed: ${i.status} ${i.statusText}`);return await i.json()}catch(i){if(s>1&&console.log(r.yellow(` \u26A0\uFE0F Attempt ${s} failed: ${i instanceof Error?i.message:String(i)}`)),s===o)return console.error(r.red(` \u274C Failed to fetch releases after ${o} attempts`)),[];await new Promise(a=>setTimeout(a,1e3*s))}return[]}function Z(e,t){return e.assets.filter(n=>{let s=n.name.toLowerCase(),i=[t.platformForAsset.toLowerCase(),...t.platformForAsset==="macos"?["darwin","apple"]:[],...t.platformForAsset==="windows"?["win","win32","windows"]:[],...t.platformForAsset==="ubuntu"?["linux","gnu"]:[]],a=[t.archForAsset.toLowerCase(),...t.archForAsset==="x86_64"?["amd64","x64"]:[],...t.archForAsset==="aarch64"?["arm64"]:[]],u=i.some(m=>s.includes(m)),d=a.some(m=>s.includes(m)),c=s.endsWith(".tar.gz")||s.endsWith(".zip")||s.endsWith(".tgz")||s.endsWith(".tar.bz2")||s.endsWith(".tar.xz");return u&&d&&c}).map(n=>n.name)}async function Ro(e,t){let o=I[e];return o?(await xe(o.repo,10)).map(s=>({version:s.tag_name,hasCompatibleAsset:Z(s,t).length>0})):[]}async function Mo(e){try{let t=ee();if(!t){console.log(r.gray(`Please add to PATH: export PATH="$PATH:${e}"`));return}let{shellName:o,configFile:n}=t,s=o==="fish"?`set -gx PATH $PATH ${e}`:`export PATH="$PATH:${e}"`;if(w.existsSync(n)&&w.readFileSync(n,"utf8").includes(e)){console.log(r.green(` \u2713 PATH already configured in ${n}`));return}let a=`# Added by dubhe doctor
61
61
  ${s}`;w.appendFileSync(n,`
62
62
  ${a}
63
- `),console.log(r.green(` \u2713 Automatically added to PATH in ${n}`)),console.log(r.blue(` \u{1F4DD} To apply changes: source ${n} or restart terminal`))}catch(t){console.log(r.yellow(` \u26A0\uFE0F Could not auto-configure PATH: ${t instanceof Error?t.message:String(t)}`)),console.log(r.gray(` Please manually add to PATH: export PATH="$PATH:${e}"`))}}function ee(){let e=U.homedir(),t=process.env.SHELL;if(t){if(t.includes("zsh"))return{shellName:"zsh",configFile:P.join(e,".zshrc")};if(t.includes("bash")){let n=P.join(e,".bash_profile"),s=P.join(e,".bashrc");return{shellName:"bash",configFile:process.platform==="darwin"&&w.existsSync(n)?n:s}}else if(t.includes("fish")){let n=P.join(e,".config","fish");return w.existsSync(n)||w.mkdirSync(n,{recursive:!0}),{shellName:"fish",configFile:P.join(n,"config.fish")}}}let o=[{name:"zsh",file:P.join(e,".zshrc")},{name:"bash",file:process.platform==="darwin"?P.join(e,".bash_profile"):P.join(e,".bashrc")},{name:"bash",file:P.join(e,".bashrc")}];for(let n of o)if(w.existsSync(n.file))return{shellName:n.name,configFile:n.file};return process.env.ZSH||w.existsSync("/bin/zsh")?{shellName:"zsh",configFile:P.join(e,".zshrc")}:null}async function ye(e,t){let o=A[e];if(!o)return console.error(`Unknown tool: ${e}`),!1;let n=be();console.log(r.gray(` System: ${n.platform}/${n.arch}`));try{console.log(r.gray(" Fetching release information..."));let s=await ve(o.repo,10);if(s.length===0)return console.error(r.red(` \u274C Unable to fetch releases for ${o.name}`)),!1;let i=null;if(t){if(t.startsWith("v")||(t=`v${t}`),i=s.find(l=>l.tag_name===t)||null,!i)return console.error(`Version ${t} not found`),!1}else for(let l of s)if(Z(l,n).length>0){i=l;break}if(!i)return console.error("No compatible version found"),!1;let a=Z(i,n);if(a.length===0)return console.error(`Version ${i.tag_name} has no compatible binaries`),!1;let u=a[0],d=i.assets.find(l=>l.name===u);if(!d)return console.error(`Asset file not found: ${u}`),!1;console.log(r.green(` \u2713 Found compatible version: ${i.tag_name}`)),console.log(r.gray(` Download file: ${d.name}`));try{let l=await we(d.browser_download_url,{method:"HEAD",headers:{"User-Agent":"dubhe-cli"}});if(!l.ok)console.log(r.yellow(` \u26A0\uFE0F Warning: Unable to access download file (${l.status})`));else{let $=l.headers.get("content-length");$&&console.log(r.gray(` File size: ${Math.round(parseInt($)/1024/1024*100)/100} MB`))}}catch{console.log(r.yellow(" \u26A0\uFE0F Warning: Unable to verify download file"))}w.existsSync(o.installDir)||(w.mkdirSync(o.installDir,{recursive:!0}),console.log(r.gray(` Created install directory: ${o.installDir}`))),console.log(r.blue(" \u{1F4E5} Downloading..."));let c=P.join(U.tmpdir(),d.name),m=3;for(let l=1;l<=m;l++)try{l>1&&console.log(r.gray(` Attempt ${l} to download...`)),await Eo(d.browser_download_url,c);break}catch($){let p=$ instanceof Error?$.message:String($);if(console.log(r.yellow(` \u26A0\uFE0F Download failed (attempt ${l}): ${p}`)),l===m)throw new Error(`Download failed after ${m} attempts: ${p}`);console.log(r.gray(` Waiting ${l*2} seconds before retry...`)),await new Promise(b=>setTimeout(b,l*2e3))}console.log(r.blue(" \u{1F4E6} Extracting and installing..."));let f=P.join(U.tmpdir(),`extract_${Date.now()}`);if(w.mkdirSync(f,{recursive:!0}),d.name.endsWith(".tar.gz")||d.name.endsWith(".tgz")){let l=await O("tar",["-xzf",c,"-C",f]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else if(d.name.endsWith(".tar.bz2")){let l=await O("tar",["-xjf",c,"-C",f]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else if(d.name.endsWith(".tar.xz")){let l=await O("tar",["-xJf",c,"-C",f]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else if(d.name.endsWith(".zip")){let l=await O("unzip",["-q",c,"-d",f]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else throw new Error(`Unsupported compression format: ${d.name}`);let h=l=>{let $=w.readdirSync(l,{withFileTypes:!0});for(let p of $){let b=P.join(l,p.name);if(p.isDirectory()){let k=h(b);if(k)return k}else if(p.name===o.binaryName||p.name===`${o.binaryName}.exe`)return b}return null},y=h(f);if(!y)throw new Error(`Cannot find ${o.binaryName} binary in extracted files`);let C=P.join(o.installDir,o.binaryName+(process.platform==="win32"?".exe":""));return w.copyFileSync(y,C),process.platform!=="win32"&&w.chmodSync(C,493),w.rmSync(c,{force:!0}),w.rmSync(f,{recursive:!0,force:!0}),console.log(r.green(" \u2705 Installation completed!")),console.log(r.gray(` Location: ${C}`)),console.log(r.gray(` Version: ${i.tag_name}`)),(process.env.PATH||"").includes(o.installDir)||(console.log(r.yellow(" \u26A0\uFE0F Warning: Install directory is not in PATH environment variable")),process.platform==="win32"?console.log(r.gray(` Please add to PATH: set PATH=%PATH%;${o.installDir}`)):await Ao(o.installDir)),!0}catch(s){return console.error(r.red(`\u274C Installation failed: ${s}`)),!1}}async function No(e){let t=be(),o=await Io(e,t);if(o.length===0)return console.log(r.red(`Unable to get version information for ${e}`)),null;let n=o.filter(i=>i.hasCompatibleAsset).slice(0,5);if(n.length===0)return console.log(r.red("No compatible versions found for current system")),null;console.log(r.blue(`
63
+ `),console.log(r.green(` \u2713 Automatically added to PATH in ${n}`)),console.log(r.blue(` \u{1F4DD} To apply changes: source ${n} or restart terminal`))}catch(t){console.log(r.yellow(` \u26A0\uFE0F Could not auto-configure PATH: ${t instanceof Error?t.message:String(t)}`)),console.log(r.gray(` Please manually add to PATH: export PATH="$PATH:${e}"`))}}function ee(){let e=U.homedir(),t=process.env.SHELL;if(t){if(t.includes("zsh"))return{shellName:"zsh",configFile:_.join(e,".zshrc")};if(t.includes("bash")){let n=_.join(e,".bash_profile"),s=_.join(e,".bashrc");return{shellName:"bash",configFile:process.platform==="darwin"&&w.existsSync(n)?n:s}}else if(t.includes("fish")){let n=_.join(e,".config","fish");return w.existsSync(n)||w.mkdirSync(n,{recursive:!0}),{shellName:"fish",configFile:_.join(n,"config.fish")}}}let o=[{name:"zsh",file:_.join(e,".zshrc")},{name:"bash",file:process.platform==="darwin"?_.join(e,".bash_profile"):_.join(e,".bashrc")},{name:"bash",file:_.join(e,".bashrc")}];for(let n of o)if(w.existsSync(n.file))return{shellName:n.name,configFile:n.file};return process.env.ZSH||w.existsSync("/bin/zsh")?{shellName:"zsh",configFile:_.join(e,".zshrc")}:null}async function be(e,t){let o=I[e];if(!o)return console.error(`Unknown tool: ${e}`),!1;let n=we();console.log(r.gray(` System: ${n.platform}/${n.arch}`));try{console.log(r.gray(" Fetching release information..."));let s=await xe(o.repo,10);if(s.length===0)return console.error(r.red(` \u274C Unable to fetch releases for ${o.name}`)),!1;let i=null;if(t){if(t.startsWith("v")||(t=`v${t}`),i=s.find(l=>l.tag_name===t)||null,!i)return console.error(`Version ${t} not found`),!1}else for(let l of s)if(Z(l,n).length>0){i=l;break}if(!i)return console.error("No compatible version found"),!1;let a=Z(i,n);if(a.length===0)return console.error(`Version ${i.tag_name} has no compatible binaries`),!1;let u=a[0],d=i.assets.find(l=>l.name===u);if(!d)return console.error(`Asset file not found: ${u}`),!1;console.log(r.green(` \u2713 Found compatible version: ${i.tag_name}`)),console.log(r.gray(` Download file: ${d.name}`));try{let l=await ve(d.browser_download_url,{method:"HEAD",headers:{"User-Agent":"dubhe-cli"}});if(!l.ok)console.log(r.yellow(` \u26A0\uFE0F Warning: Unable to access download file (${l.status})`));else{let $=l.headers.get("content-length");$&&console.log(r.gray(` File size: ${Math.round(parseInt($)/1024/1024*100)/100} MB`))}}catch{console.log(r.yellow(" \u26A0\uFE0F Warning: Unable to verify download file"))}w.existsSync(o.installDir)||(w.mkdirSync(o.installDir,{recursive:!0}),console.log(r.gray(` Created install directory: ${o.installDir}`))),console.log(r.blue(" \u{1F4E5} Downloading..."));let c=_.join(U.tmpdir(),d.name),m=3;for(let l=1;l<=m;l++)try{l>1&&console.log(r.gray(` Attempt ${l} to download...`)),await No(d.browser_download_url,c);break}catch($){let p=$ instanceof Error?$.message:String($);if(console.log(r.yellow(` \u26A0\uFE0F Download failed (attempt ${l}): ${p}`)),l===m)throw new Error(`Download failed after ${m} attempts: ${p}`);console.log(r.gray(` Waiting ${l*2} seconds before retry...`)),await new Promise(b=>setTimeout(b,l*2e3))}console.log(r.blue(" \u{1F4E6} Extracting and installing..."));let f=_.join(U.tmpdir(),`extract_${Date.now()}`);if(w.mkdirSync(f,{recursive:!0}),d.name.endsWith(".tar.gz")||d.name.endsWith(".tgz")){let l=await O("tar",["-xzf",c,"-C",f]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else if(d.name.endsWith(".tar.bz2")){let l=await O("tar",["-xjf",c,"-C",f]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else if(d.name.endsWith(".tar.xz")){let l=await O("tar",["-xJf",c,"-C",f]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else if(d.name.endsWith(".zip")){let l=await O("unzip",["-q",c,"-d",f]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else throw new Error(`Unsupported compression format: ${d.name}`);let h=l=>{let $=w.readdirSync(l,{withFileTypes:!0});for(let p of $){let b=_.join(l,p.name);if(p.isDirectory()){let k=h(b);if(k)return k}else if(p.name===o.binaryName||p.name===`${o.binaryName}.exe`)return b}return null},y=h(f);if(!y)throw new Error(`Cannot find ${o.binaryName} binary in extracted files`);let C=_.join(o.installDir,o.binaryName+(process.platform==="win32"?".exe":""));return w.copyFileSync(y,C),process.platform!=="win32"&&w.chmodSync(C,493),w.rmSync(c,{force:!0}),w.rmSync(f,{recursive:!0,force:!0}),console.log(r.green(" \u2705 Installation completed!")),console.log(r.gray(` Location: ${C}`)),console.log(r.gray(` Version: ${i.tag_name}`)),(process.env.PATH||"").includes(o.installDir)||(console.log(r.yellow(" \u26A0\uFE0F Warning: Install directory is not in PATH environment variable")),process.platform==="win32"?console.log(r.gray(` Please add to PATH: set PATH=%PATH%;${o.installDir}`)):await Mo(o.installDir)),!0}catch(s){return console.error(r.red(`\u274C Installation failed: ${s}`)),!1}}async function Fo(e){let t=we(),o=await Ro(e,t);if(o.length===0)return console.log(r.red(`Unable to get version information for ${e}`)),null;let n=o.filter(i=>i.hasCompatibleAsset).slice(0,5);if(n.length===0)return console.log(r.red("No compatible versions found for current system")),null;console.log(r.blue(`
64
64
  \u{1F4CB} Select version for ${e}`)),console.log(r.gray(`System: ${t.platform}/${t.arch}`)),console.log(r.gray(`Compatible versions (latest 5):
65
65
  `));let s=n.map((i,a)=>({name:`${i.version} ${a===0?r.green("(latest)"):r.gray("(available)")}`,value:i.version,short:i.version}));try{let i=await ae.prompt([{type:"list",name:"version",message:"Please select a version to install:",choices:[...s,new ae.Separator,{name:r.gray("Cancel installation"),value:"cancel"}],default:s[0].value}]);return i.version==="cancel"?(console.log(r.gray("Installation cancelled")),null):i.version}catch{return console.log(r.gray(`
66
- Installation cancelled`)),null}}function le(e){let t=A[e];if(!t)return!1;let o=P.join(t.installDir,t.binaryName+(process.platform==="win32"?".exe":""));return w.existsSync(o)}async function Mo(){try{let e=R.version,t=await O("dubhe-indexer",["--version"]);if(t.code!==0)return{name:"Dubhe-indexer Version Consistency",status:"warning",message:"Cannot get dubhe-indexer version",fixSuggestion:"Unable to verify version consistency"};let o=t.stdout.trim().match(/dubhe-indexer\s+(\S+)/);if(!o)return{name:"Dubhe-indexer Version Consistency",status:"warning",message:"Cannot parse dubhe-indexer version",fixSuggestion:"Unable to verify version consistency"};let n=o[1];return e===n?{name:"Dubhe-indexer Version Consistency",status:"success",message:`Versions match (${e})`}:{name:"Dubhe-indexer Version Consistency",status:"warning",message:`Version mismatch: sui-cli ${e}, dubhe-indexer ${n}`,fixSuggestion:`Consider reinstalling dubhe-indexer to match sui-cli version ${e}`}}catch{return{name:"Dubhe-indexer Version Consistency",status:"warning",message:"Version check failed",fixSuggestion:"Unable to verify version consistency"}}}async function X(e,t="--version"){try{let o=await O(e,[t]);if(o.code===0){let n=o.stdout.trim().split(`
67
- `)[0];return{name:e,status:"success",message:`Installed ${n}`}}else{if(le(e)){let n=ee(),s=n?n.configFile:"~/.zshrc (or ~/.bashrc)";return{name:e,status:"warning",message:"Installed but not in PATH",fixSuggestion:`Binary exists in install directory. Please apply PATH changes: source ${s} (or restart terminal), then run dubhe doctor again`}}return{name:e,status:"error",message:"Not installed",fixSuggestion:tt(e)}}}catch{if(le(e)){let n=ee(),s=n?n.configFile:"~/.zshrc (or ~/.bashrc)";return{name:e,status:"warning",message:"Installed but not in PATH",fixSuggestion:`Binary exists in install directory. Please apply PATH changes: source ${s} (or restart terminal), then run dubhe doctor again`}}return{name:e,status:"error",message:"Not installed",fixSuggestion:tt(e)}}}function tt(e){return{docker:"Visit https://docs.docker.com/get-docker/ to install Docker","docker-compose":"Visit https://docs.docker.com/compose/install/ to install Docker Compose",sui:"Run `dubhe doctor --install sui` to auto-install, or visit https://docs.sui.io/guides/developer/getting-started/sui-install","dubhe-indexer":"Run `dubhe doctor --install dubhe-indexer` to auto-install, or download from https://github.com/0xobelisk/dubhe-wip/releases",pnpm:"Run: npm install -g pnpm",node:"Visit https://nodejs.org/ to download and install Node.js"}[e]||`Please install ${e}`}async function Fo(){try{let e=await O("node",["--version"]);if(e.code===0){let t=e.stdout.trim();return parseFloat(t.replace("v",""))>=18?{name:"Node.js Version",status:"success",message:`${t} (meets requirement >=18.0)`}:{name:"Node.js Version",status:"warning",message:`${t} (recommend upgrade to >=18.0)`,fixSuggestion:"Please upgrade Node.js to 18.0 or higher"}}else return{name:"Node.js Version",status:"error",message:"Not installed",fixSuggestion:"Please install Node.js 18.0 or higher"}}catch{return{name:"Node.js Version",status:"error",message:"Check failed",fixSuggestion:"Please install Node.js"}}}async function Ro(){try{return(await O("docker",["info"])).code===0?{name:"Docker Service",status:"success",message:"Running"}:{name:"Docker Service",status:"warning",message:"Not running",fixSuggestion:"Please start Docker service"}}catch{return{name:"Docker Service",status:"error",message:"Check failed",fixSuggestion:"Please install and start Docker"}}}async function jo(){try{let e=await O("npm",["config","get","registry"]);return e.code===0?{name:"NPM Configuration",status:"success",message:`Configured (${e.stdout.trim()})`}:{name:"NPM Configuration",status:"warning",message:"Configuration issue",fixSuggestion:"Check NPM configuration: npm config list"}}catch{return{name:"NPM Configuration",status:"warning",message:"Check failed",fixSuggestion:"Please install Node.js and NPM"}}}async function st(e){let t=["127.0.0.1","0.0.0.0"];for(let o of t)if(!await Oo(e,o))return!1;return!0}async function Oo(e,t){return new Promise(o=>{let n=nt.createServer(),s=setTimeout(()=>{n.close(),o(!1)},2e3);n.listen(e,t,()=>{clearTimeout(s),n.close(()=>{o(!0)})}),n.on("error",i=>{clearTimeout(s),n.close(),i.code,o(!1)})})}async function Ho(){try{return await st(5432)?{name:"PostgreSQL Port (5432)",status:"success",message:"Available"}:{name:"PostgreSQL Port (5432)",status:"warning",message:"Port is occupied",fixSuggestion:"Port 5432 is in use. Check if PostgreSQL is already running or stop the service using this port. This may cause template startup failure."}}catch{return{name:"PostgreSQL Port (5432)",status:"warning",message:"Check failed",fixSuggestion:"Unable to check port status"}}}async function Vo(){try{return await st(4e3)?{name:"GraphQL Server Port (4000)",status:"success",message:"Available"}:{name:"GraphQL Server Port (4000)",status:"warning",message:"Port is occupied",fixSuggestion:"Port 4000 is in use. Check if GraphQL server is already running or stop the service using this port. This may cause template startup failure."}}catch{return{name:"GraphQL Server Port (4000)",status:"warning",message:"Check failed",fixSuggestion:"Unable to check port status"}}}function Lo(e){let t={success:r.green("\u2713"),warning:r.yellow("!"),error:r.red("\u2717")},o={success:r.green("Pass"),warning:r.yellow("Warning"),error:r.red("Fail")},n="";return e.status==="success"?n=e.message:n=e.fixSuggestion||e.message,[e.name,`${t[e.status]} ${o[e.status]}`,n]}async function Uo(e){if(console.log(r.bold.blue(`
66
+ Installation cancelled`)),null}}function le(e){let t=I[e];if(!t)return!1;let o=_.join(t.installDir,t.binaryName+(process.platform==="win32"?".exe":""));return w.existsSync(o)}async function jo(){try{let e=M.version,t=await O("dubhe-indexer",["--version"]);if(t.code!==0)return{name:"Dubhe-indexer Version Consistency",status:"warning",message:"Cannot get dubhe-indexer version",fixSuggestion:"Unable to verify version consistency"};let o=t.stdout.trim().match(/dubhe-indexer\s+(\S+)/);if(!o)return{name:"Dubhe-indexer Version Consistency",status:"warning",message:"Cannot parse dubhe-indexer version",fixSuggestion:"Unable to verify version consistency"};let n=o[1];return e===n?{name:"Dubhe-indexer Version Consistency",status:"success",message:`Versions match (${e})`}:{name:"Dubhe-indexer Version Consistency",status:"warning",message:`Version mismatch: sui-cli ${e}, dubhe-indexer ${n}`,fixSuggestion:`Consider reinstalling dubhe-indexer to match sui-cli version ${e}`}}catch{return{name:"Dubhe-indexer Version Consistency",status:"warning",message:"Version check failed",fixSuggestion:"Unable to verify version consistency"}}}async function Q(e,t="--version"){try{let o=await O(e,[t]);if(o.code===0){let n=o.stdout.trim().split(`
67
+ `)[0];return{name:e,status:"success",message:`Installed ${n}`}}else{if(le(e)){let n=ee(),s=n?n.configFile:"~/.zshrc (or ~/.bashrc)";return{name:e,status:"warning",message:"Installed but not in PATH",fixSuggestion:`Binary exists in install directory. Please apply PATH changes: source ${s} (or restart terminal), then run dubhe doctor again`}}return{name:e,status:"error",message:"Not installed",fixSuggestion:nt(e)}}}catch{if(le(e)){let n=ee(),s=n?n.configFile:"~/.zshrc (or ~/.bashrc)";return{name:e,status:"warning",message:"Installed but not in PATH",fixSuggestion:`Binary exists in install directory. Please apply PATH changes: source ${s} (or restart terminal), then run dubhe doctor again`}}return{name:e,status:"error",message:"Not installed",fixSuggestion:nt(e)}}}function nt(e){return{docker:"Visit https://docs.docker.com/get-docker/ to install Docker","docker-compose":"Visit https://docs.docker.com/compose/install/ to install Docker Compose",sui:"Run `dubhe doctor --install sui` to auto-install, or visit https://docs.sui.io/guides/developer/getting-started/sui-install","dubhe-indexer":"Run `dubhe doctor --install dubhe-indexer` to auto-install, or download from https://github.com/0xobelisk/dubhe-wip/releases",pnpm:"Run: npm install -g pnpm",node:"Visit https://nodejs.org/ to download and install Node.js"}[e]||`Please install ${e}`}async function Oo(){try{let e=await O("node",["--version"]);if(e.code===0){let t=e.stdout.trim();return parseFloat(t.replace("v",""))>=18?{name:"Node.js Version",status:"success",message:`${t} (meets requirement >=18.0)`}:{name:"Node.js Version",status:"warning",message:`${t} (recommend upgrade to >=18.0)`,fixSuggestion:"Please upgrade Node.js to 18.0 or higher"}}else return{name:"Node.js Version",status:"error",message:"Not installed",fixSuggestion:"Please install Node.js 18.0 or higher"}}catch{return{name:"Node.js Version",status:"error",message:"Check failed",fixSuggestion:"Please install Node.js"}}}async function Ho(){try{return(await O("docker",["info"])).code===0?{name:"Docker Service",status:"success",message:"Running"}:{name:"Docker Service",status:"warning",message:"Not running",fixSuggestion:"Please start Docker service"}}catch{return{name:"Docker Service",status:"error",message:"Check failed",fixSuggestion:"Please install and start Docker"}}}async function Vo(){try{let e=await O("npm",["config","get","registry"]);return e.code===0?{name:"NPM Configuration",status:"success",message:`Configured (${e.stdout.trim()})`}:{name:"NPM Configuration",status:"warning",message:"Configuration issue",fixSuggestion:"Check NPM configuration: npm config list"}}catch{return{name:"NPM Configuration",status:"warning",message:"Check failed",fixSuggestion:"Please install Node.js and NPM"}}}async function it(e){let t=["127.0.0.1","0.0.0.0"];for(let o of t)if(!await Lo(e,o))return!1;return!0}async function Lo(e,t){return new Promise(o=>{let n=rt.createServer(),s=setTimeout(()=>{n.close(),o(!1)},2e3);n.listen(e,t,()=>{clearTimeout(s),n.close(()=>{o(!0)})}),n.on("error",i=>{clearTimeout(s),n.close(),i.code,o(!1)})})}async function Uo(){try{return await it(5432)?{name:"PostgreSQL Port (5432)",status:"success",message:"Available"}:{name:"PostgreSQL Port (5432)",status:"warning",message:"Port is occupied",fixSuggestion:"Port 5432 is in use. Check if PostgreSQL is already running or stop the service using this port. This may cause template startup failure."}}catch{return{name:"PostgreSQL Port (5432)",status:"warning",message:"Check failed",fixSuggestion:"Unable to check port status"}}}async function zo(){try{return await it(4e3)?{name:"GraphQL Server Port (4000)",status:"success",message:"Available"}:{name:"GraphQL Server Port (4000)",status:"warning",message:"Port is occupied",fixSuggestion:"Port 4000 is in use. Check if GraphQL server is already running or stop the service using this port. This may cause template startup failure."}}catch{return{name:"GraphQL Server Port (4000)",status:"warning",message:"Check failed",fixSuggestion:"Unable to check port status"}}}function Wo(e){let t={success:r.green("\u2713"),warning:r.yellow("!"),error:r.red("\u2717")},o={success:r.green("Pass"),warning:r.yellow("Warning"),error:r.red("Fail")},n="";return e.status==="success"?n=e.message:n=e.fixSuggestion||e.message,[e.name,`${t[e.status]} ${o[e.status]}`,n]}async function qo(e){if(console.log(r.bold.blue(`
68
68
  \u{1F50D} Dubhe Doctor - Development Environment Checker
69
- `)),e.listVersions){let p=e.listVersions;A[p]||(console.error(r.red(`\u274C Unsupported tool: ${p}`)),process.exit(1)),console.log(r.blue(`\u{1F4CB} Available versions for ${p}:`));let b=be();console.log(r.gray(`System: ${b.platform}/${b.arch}
70
- `));let k=A[p],T=await ve(k.repo,10);T.length===0&&(console.log(r.red("Unable to get version information")),process.exit(1));let S=T.map(g=>({version:g.tag_name,hasCompatibleAsset:Z(g,b).length>0,publishDate:new Date(g.published_at).toLocaleDateString("en-US")})),E=new Ze({head:[r.bold.cyan("Version"),r.bold.cyan("Compatibility"),r.bold.cyan("Release Date")],colWidths:[30,15,25]});if(S.forEach(g=>{E.push([g.version,g.hasCompatibleAsset?r.green("\u2713 Compatible"):r.red("\u2717 Incompatible"),g.publishDate])}),console.log(E.toString()),e.debug&&S.length>0){console.log(r.blue(`
71
- \u{1F50D} Debug Information:`));let g=S.find(v=>v.hasCompatibleAsset);if(g){let v=T.find(F=>F.tag_name===g.version);if(v){console.log(r.gray(`Latest compatible version: ${g.version}`)),console.log(r.gray("Available asset files:")),v.assets.forEach(z=>{console.log(r.gray(` - ${z.name}`))});let F=Z(v,b);console.log(r.gray("Compatible asset files:")),F.forEach(z=>{console.log(r.green(` \u2713 ${z}`))})}}}process.exit(0)}if(console.log(r.gray(`Checking your development environment...
72
- `)),e.install){let p=e.install;A[p]||(console.error(r.red(`\u274C Unsupported tool: ${p}`)),console.log(r.gray(`Supported tools: ${Object.keys(A).join(", ")}`)),process.exit(1));let b=null;e.selectVersion?(b=await No(p),b||process.exit(1)):p==="dubhe-indexer"&&(b=R.version,console.log(r.blue(`\u{1F4E6} Installing dubhe-indexer version ${b} (matching sui-cli version)`)));let k=await ye(p,b||void 0);process.exit(k?0:1)}let t=[];console.log(`Running checks...
73
- `);let o=await Fo();t.push(o);let n=await X("pnpm");t.push(n);let s=await jo();s.status==="error"&&(s.status="warning"),t.push(s);let i=await X("docker");t.push(i);let a=null;i.status==="success"&&(a=await Ro(),t.push(a));let u=await X("docker-compose");t.push(u);let d=await X("sui");t.push(d);let c=await X("dubhe-indexer");if(t.push(c),c.status==="success"){let p=await Mo();t.push(p)}let m=await Ho();t.push(m);let f=await Vo();t.push(f);let h=new Ze({head:[r.bold.cyan("Check Item"),r.bold.cyan("Result"),r.bold.cyan("Description/Fix Suggestion")],colWidths:[25,15,60],style:{head:["cyan"],border:["grey"]},wordWrap:!0});t.forEach(p=>{h.push(Lo(p))}),console.log(h.toString());let y={success:t.filter(p=>p.status==="success").length,warning:t.filter(p=>p.status==="warning").length,error:t.filter(p=>p.status==="error").length};console.log(`
69
+ `)),e.listVersions){let p=e.listVersions;I[p]||(console.error(r.red(`\u274C Unsupported tool: ${p}`)),process.exit(1)),console.log(r.blue(`\u{1F4CB} Available versions for ${p}:`));let b=we();console.log(r.gray(`System: ${b.platform}/${b.arch}
70
+ `));let k=I[p],T=await xe(k.repo,10);T.length===0&&(console.log(r.red("Unable to get version information")),process.exit(1));let S=T.map(g=>({version:g.tag_name,hasCompatibleAsset:Z(g,b).length>0,publishDate:new Date(g.published_at).toLocaleDateString("en-US")})),E=new tt({head:[r.bold.cyan("Version"),r.bold.cyan("Compatibility"),r.bold.cyan("Release Date")],colWidths:[30,15,25]});if(S.forEach(g=>{E.push([g.version,g.hasCompatibleAsset?r.green("\u2713 Compatible"):r.red("\u2717 Incompatible"),g.publishDate])}),console.log(E.toString()),e.debug&&S.length>0){console.log(r.blue(`
71
+ \u{1F50D} Debug Information:`));let g=S.find(v=>v.hasCompatibleAsset);if(g){let v=T.find(R=>R.tag_name===g.version);if(v){console.log(r.gray(`Latest compatible version: ${g.version}`)),console.log(r.gray("Available asset files:")),v.assets.forEach(z=>{console.log(r.gray(` - ${z.name}`))});let R=Z(v,b);console.log(r.gray("Compatible asset files:")),R.forEach(z=>{console.log(r.green(` \u2713 ${z}`))})}}}process.exit(0)}if(console.log(r.gray(`Checking your development environment...
72
+ `)),e.install){let p=e.install;I[p]||(console.error(r.red(`\u274C Unsupported tool: ${p}`)),console.log(r.gray(`Supported tools: ${Object.keys(I).join(", ")}`)),process.exit(1));let b=null;e.selectVersion?(b=await Fo(p),b||process.exit(1)):p==="dubhe-indexer"&&(b=M.version,console.log(r.blue(`\u{1F4E6} Installing dubhe-indexer version ${b} (matching sui-cli version)`)));let k=await be(p,b||void 0);process.exit(k?0:1)}let t=[];console.log(`Running checks...
73
+ `);let o=await Oo();t.push(o);let n=await Q("pnpm");t.push(n);let s=await Vo();s.status==="error"&&(s.status="warning"),t.push(s);let i=await Q("docker");t.push(i);let a=null;i.status==="success"&&(a=await Ho(),t.push(a));let u=await Q("docker-compose");t.push(u);let d=await Q("sui");t.push(d);let c=await Q("dubhe-indexer");if(t.push(c),c.status==="success"){let p=await jo();t.push(p)}let m=await Uo();t.push(m);let f=await zo();t.push(f);let h=new tt({head:[r.bold.cyan("Check Item"),r.bold.cyan("Result"),r.bold.cyan("Description/Fix Suggestion")],colWidths:[25,15,60],style:{head:["cyan"],border:["grey"]},wordWrap:!0});t.forEach(p=>{h.push(Wo(p))}),console.log(h.toString());let y={success:t.filter(p=>p.status==="success").length,warning:t.filter(p=>p.status==="warning").length,error:t.filter(p=>p.status==="error").length};console.log(`
74
74
  `+r.bold("\u{1F4CA} Check Summary:")),console.log(` ${r.green("\u2713 Passed:")} ${y.success} items`),console.log(` ${r.yellow("! Warning:")} ${y.warning} items`),console.log(` ${r.red("\u2717 Failed:")} ${y.error} items`);let C=t.find(p=>p.name==="Dubhe-indexer Version Consistency"&&p.status==="warning"&&p.message.includes("Version mismatch"));if(C){console.log(r.yellow(`
75
75
  \u26A0\uFE0F Dubhe-indexer version inconsistency detected!`)),console.log(r.gray(` ${C.message}`));try{(await ae.prompt([{type:"confirm",name:"reinstallDubheIndexer",message:"Would you like to reinstall dubhe-indexer to match the sui-cli version?",default:!0}])).reinstallDubheIndexer?(console.log(r.blue(`
76
76
  \u{1F4E6} Reinstalling dubhe-indexer...
77
- `)),console.log(r.blue(`${"=".repeat(60)}`)),console.log(r.blue("\u{1F4E6} Installing dubhe-indexer...")),console.log(r.blue(`${"=".repeat(60)}`)),await ye("dubhe-indexer",R.version)?(console.log(r.green(`
77
+ `)),console.log(r.blue(`${"=".repeat(60)}`)),console.log(r.blue("\u{1F4E6} Installing dubhe-indexer...")),console.log(r.blue(`${"=".repeat(60)}`)),await be("dubhe-indexer",M.version)?(console.log(r.green(`
78
78
  \u2705 Dubhe-indexer reinstallation completed successfully!`)),console.log(r.blue(" Please restart your terminal or run: source ~/.zshrc (or ~/.bashrc)")),console.log(r.blue(" Then run: dubhe doctor to verify the installation"))):(console.log(r.red(`
79
79
  \u274C Dubhe-indexer reinstallation failed`)),console.log(r.gray(" You can try manual installation: dubhe doctor --install dubhe-indexer")))):(console.log(r.gray(`
80
80
  Version inconsistency ignored. You can reinstall later with:`)),console.log(r.gray(" dubhe doctor --install dubhe-indexer")))}catch{console.log(r.gray(`
81
- Version inconsistency check cancelled.`))}}let D=t.filter(p=>p.status==="error"),l=D.filter(p=>A[p.name]),$=D.filter(p=>!A[p.name]);if($.length>0&&(console.log(r.blue(`
82
- \u{1F527} Missing tools that require manual installation:`)),$.forEach(p=>{console.log(` ${r.red("\u2717")} ${p.name}: ${p.fixSuggestion||p.message}`)})),l.length>0){let p=l.filter(k=>le(k.name)),b=l.filter(k=>!le(k.name));if(p.length>0){let k=p.map(g=>g.name).join(", "),T=A[p[0].name]?.installDir||"~/.dubhe/bin",S=ee(),E=S?S.configFile:"~/.zshrc (or ~/.bashrc)";console.log(r.yellow(`
81
+ Version inconsistency check cancelled.`))}}let D=t.filter(p=>p.status==="error"),l=D.filter(p=>I[p.name]),$=D.filter(p=>!I[p.name]);if($.length>0&&(console.log(r.blue(`
82
+ \u{1F527} Missing tools that require manual installation:`)),$.forEach(p=>{console.log(` ${r.red("\u2717")} ${p.name}: ${p.fixSuggestion||p.message}`)})),l.length>0){let p=l.filter(k=>le(k.name)),b=l.filter(k=>!le(k.name));if(p.length>0){let k=p.map(g=>g.name).join(", "),T=I[p[0].name]?.installDir||"~/.dubhe/bin",S=ee(),E=S?S.configFile:"~/.zshrc (or ~/.bashrc)";console.log(r.yellow(`
83
83
  \u26A0\uFE0F Tools already installed but not in PATH: ${k}`)),console.log(r.gray(` Location: ${T}`)),console.log(r.blue(" To fix this, apply PATH changes:")),console.log(r.green(` source ${E}`)),console.log(r.blue(" Or restart your terminal, then run: dubhe doctor")),console.log(r.gray(` If you want to reinstall, remove the files from ${T} and run dubhe doctor again`))}if(b.length>0){let k=b.map(T=>T.name).join(", ");console.log(r.blue(`
84
84
  \u{1F680} Auto-installable tools detected: ${k}`));try{if((await ae.prompt([{type:"confirm",name:"installAll",message:`Would you like to automatically install these tools? (${k})`,default:!0}])).installAll){console.log(r.blue(`
85
85
  \u{1F4E6} Starting installation of auto-installable tools...
86
- `));let S=[];for(let v of b){console.log(r.blue(`${"=".repeat(60)}`)),console.log(r.blue(`\u{1F4E6} Installing ${v.name}...`)),console.log(r.blue(`${"=".repeat(60)}`));let F=v.name==="dubhe-indexer"?R.version:void 0;v.name==="dubhe-indexer"&&console.log(r.blue(` Using version ${F} (matching sui-cli version)`));let z=await ye(v.name,F);S.push({name:v.name,success:z}),z?console.log(r.green(`
86
+ `));let S=[];for(let v of b){console.log(r.blue(`${"=".repeat(60)}`)),console.log(r.blue(`\u{1F4E6} Installing ${v.name}...`)),console.log(r.blue(`${"=".repeat(60)}`));let R=v.name==="dubhe-indexer"?M.version:void 0;v.name==="dubhe-indexer"&&console.log(r.blue(` Using version ${R} (matching sui-cli version)`));let z=await be(v.name,R);S.push({name:v.name,success:z}),z?console.log(r.green(`
87
87
  \u2705 ${v.name} installation completed successfully!`)):(console.log(r.red(`
88
- \u274C ${v.name} installation failed`)),console.log(r.gray(` Manual installation: dubhe doctor --install ${v.name}`))),console.log("")}console.log(r.blue(`${"=".repeat(60)}`)),console.log(r.bold("\u{1F4CB} Installation Summary:")),console.log(r.blue(`${"=".repeat(60)}`)),S.forEach(v=>{let F=v.success?r.green("\u2705 Success"):r.red("\u274C Failed");console.log(` ${v.name}: ${F}`)});let E=S.filter(v=>v.success).length,g=S.length-E;if(console.log(`
89
- ${r.green("Successful:")} ${E}/${S.length}`),g>0&&console.log(` ${r.red("Failed:")} ${g}/${S.length}`),E>0){let v=ee(),F=v?v.configFile:"~/.zshrc (or ~/.bashrc)";console.log(r.blue(`
90
- \u{1F504} Next Steps:`)),console.log(r.yellow(" 1. Apply PATH changes by running:")),console.log(r.green(` source ${F}`)),console.log(r.yellow(" 2. Or restart your terminal")),console.log(r.yellow(" 3. Then run the doctor check again:")),console.log(r.green(" dubhe doctor")),console.log(r.gray(`
88
+ \u274C ${v.name} installation failed`)),console.log(r.gray(` Manual installation: dubhe doctor --install ${v.name}`))),console.log("")}console.log(r.blue(`${"=".repeat(60)}`)),console.log(r.bold("\u{1F4CB} Installation Summary:")),console.log(r.blue(`${"=".repeat(60)}`)),S.forEach(v=>{let R=v.success?r.green("\u2705 Success"):r.red("\u274C Failed");console.log(` ${v.name}: ${R}`)});let E=S.filter(v=>v.success).length,g=S.length-E;if(console.log(`
89
+ ${r.green("Successful:")} ${E}/${S.length}`),g>0&&console.log(` ${r.red("Failed:")} ${g}/${S.length}`),E>0){let v=ee(),R=v?v.configFile:"~/.zshrc (or ~/.bashrc)";console.log(r.blue(`
90
+ \u{1F504} Next Steps:`)),console.log(r.yellow(" 1. Apply PATH changes by running:")),console.log(r.green(` source ${R}`)),console.log(r.yellow(" 2. Or restart your terminal")),console.log(r.yellow(" 3. Then run the doctor check again:")),console.log(r.green(" dubhe doctor")),console.log(r.gray(`
91
91
  This will verify that all tools are properly configured.`))}else console.log(r.red(`
92
92
  \u274C All installations failed. Please check the error messages above.`))}else console.log(r.gray(`
93
93
  Auto-installation skipped. You can install them manually later:`)),b.forEach(S=>{console.log(r.gray(` dubhe doctor --install ${S.name}`))})}catch{console.log(r.gray(`
@@ -95,5 +95,5 @@ Installation cancelled. You can install them manually later:`)),b.forEach(S=>{co
95
95
  \u274C Your environment has some issues. Please fix them according to the suggestions above.`)),process.exit(1)):y.warning>0?console.log(r.yellow(`
96
96
  \u26A0\uFE0F Your environment is basically ready, but we recommend fixing the warnings for better development experience.`)):console.log(r.green(`
97
97
  \u2705 Congratulations! Your development environment is fully ready!`))),console.log(r.gray(`
98
- \u{1F4A1} Tip: For more help, visit https://docs.sui.io/ or https://github.com/0xobelisk/dubhe`))}var zo={command:"doctor",describe:"Check if local development environment is ready",builder(e){return e.option("install",{type:"string",describe:"Auto-install specified tool (sui, dubhe-indexer)",choices:Object.keys(A)}).option("select-version",{type:"boolean",default:!1,describe:"Select specific version for installation"}).option("list-versions",{type:"string",describe:"List available versions for specified tool",choices:Object.keys(A)}).option("debug",{type:"boolean",default:!1,describe:"Show detailed debug information"})},async handler(e){try{await Uo({install:e.install,selectVersion:e["select-version"],listVersions:e["list-versions"],debug:e.debug})}catch(t){console.error(r.red("Error occurred during check:"),t),process.exit(1)}}},rt=zo;import Wo from"chalk";import{loadConfig as qo}from"@0xobelisk/sui-common";import Bo from"fs";var Ko={command:"convert-json",describe:"Convert JSON from Dubhe config to config.json",builder(e){return e.options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Options to pass to forge test"},"output-path":{type:"string",default:"dubhe.config.json",description:"Output path for the config.json file"}})},async handler({"config-path":e,"output-path":t}){try{console.log("\u{1F680} Running convert json");let o=await qo(e),n=Ce(o);Bo.writeFileSync(t,n)}catch(o){console.error(Wo.red("Error executing convert json:")),console.log(o.stdout),process.exit(0)}}},it=Ko;var at=[Ae,Re,Me,Fe,je,Oe,He,Ue,We,Be,Ke,Ge,Ye,Je,Xe,rt,it];import*as ct from"dotenv";ct.config();Go(Yo(process.argv)).scriptName("dubhe").command(at).version(R.version).demandCommand(1,"Please provide a command").recommendCommands().strict().fail((e,t)=>{console.error(lt.red(e)),e.includes("Missing required argument")&&console.log(lt.yellow(`Run 'pnpm dubhe ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),t!=null&&(H(t),console.log("")),process.exit(1)}).alias({h:"help"}).argv;
98
+ \u{1F4A1} Tip: For more help, visit https://docs.sui.io/ or https://github.com/0xobelisk/dubhe`))}var Bo={command:"doctor",describe:"Check if local development environment is ready",builder(e){return e.option("install",{type:"string",describe:"Auto-install specified tool (sui, dubhe-indexer)",choices:Object.keys(I)}).option("select-version",{type:"boolean",default:!1,describe:"Select specific version for installation"}).option("list-versions",{type:"string",describe:"List available versions for specified tool",choices:Object.keys(I)}).option("debug",{type:"boolean",default:!1,describe:"Show detailed debug information"})},async handler(e){try{await qo({install:e.install,selectVersion:e["select-version"],listVersions:e["list-versions"],debug:e.debug})}catch(t){console.error(r.red("Error occurred during check:"),t),process.exit(1)}}},at=Bo;import Ko from"chalk";import{loadConfig as Go}from"@0xobelisk/sui-common";import Yo from"fs";var Jo={command:"convert-json",describe:"Convert JSON from Dubhe config to config.json",builder(e){return e.options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Options to pass to forge test"},"output-path":{type:"string",default:"dubhe.config.json",description:"Output path for the config.json file"}})},async handler({"config-path":e,"output-path":t}){try{console.log("\u{1F680} Running convert json");let o=await Go(e),n=$e(o);Yo.writeFileSync(t,n)}catch(o){console.error(Ko.red("Error executing convert json:")),console.log(o.stdout),process.exit(0)}}},lt=Jo;var ct=[Ne,je,Me,Fe,Oe,He,Ve,ze,qe,Ke,Ge,Je,Xe,Qe,et,at,lt];import*as ut from"dotenv";ut.config();Xo(Qo(process.argv)).scriptName("dubhe").command(ct).version(M.version).demandCommand(1,"Please provide a command").recommendCommands().strict().fail((e,t)=>{console.error(dt.red(e)),e.includes("Missing required argument")&&console.log(dt.yellow(`Run 'pnpm dubhe ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),t!=null&&(H(t),console.log("")),process.exit(1)}).alias({h:"help"}).argv;
99
99
  //# sourceMappingURL=dubhe.js.map