@mincraft/cli 1.3.0 → 1.4.0

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/index.mjs CHANGED
@@ -1,8 +1,9 @@
1
1
  #!/usr/bin/env node
2
- import{Option as I,program as l}from"commander";import*as C from"readline";import{createBot as M}from"mineflayer";import{SocksClient as O}from"socks";var d=class{proxy;client;server;options;logger;isLoggedIn;bot;constructor({proxy:t,client:e,server:i,options:r},s){this.proxy=t,this.client=e,this.server=i,this.options=r,this.logger=s,this.isLoggedIn=!1}async registerAndLogIn(){let t={host:this.server.host,port:this.server.port,username:this.client.account.email,auth:this.client.account.auth,version:this.client.version,hideErrors:!0};this.proxy&&(t.connect=e=>{this.connectViaProxy(e)}),this.bot=M(t),this.options.verboseLogging&&this.registerClientEvents(),this.registerBotEvents()}connectViaProxy(t){this.logger.log("connecting via proxy");let{host:e,port:i,user:r,pass:s,type:n}=this.proxy,a=this.server;O.createConnection({proxy:{host:e,port:i,type:n,userId:r,password:s},command:"connect",destination:{host:a.host,port:a.port},timeout:3e4}).then(c=>{t.setSocket(c.socket),t.emit("connect")}).catch(c=>{this.logger.error(`proxy connection failed: ${c.message}`),t.emit("error",c)})}registerClientEvents(){this.bot._client.on("connect",()=>{this.logger.log("TCP connection established")}),this.bot._client.on("login",()=>{this.logger.log("login packet received")}),this.bot._client.on("error",t=>{this.logger.error(`client error: ${t.message}`)}),this.bot._client.on("end",t=>{this.logger.warn(`client ended: ${t}`)})}registerBotEvents(){this.bot.once("spawn",()=>{let{ign:t,uuid:e}=this.client.account;this.logger.log(`logged in as ${t} (${e})`),this.isLoggedIn=!0}),this.bot.once("kicked",t=>{this.logger.warn(`kicked: ${JSON.stringify(t)}`),this.disconnect()}),this.bot.once("error",t=>{this.logger.error(`bot error: ${t.message}`),this.isLoggedIn=!1}),this.bot.once("end",t=>{this.logger.warn(`disconnected by server: ${JSON.stringify(t)}`),this.disconnect()}),this.options.logMessages&&this.bot.on("messagestr",t=>{let e=t.split(`
3
- `);if(e.length===1)this.logger.log(t,"chat");else{this.logger.log(e[0],"chat");for(let i=1;i<e.length;i++)this.logger.raw(` ${e[i]}`)}})}disconnect(){this.bot&&(this.proxy?this.bot._client.socket?.destroy():this.bot.quit(),this.isLoggedIn=!1)}sendMessage(t){this.bot.chat(t)}};import*as f from"readline";var S="\x1B[90m",F="\x1B[34m",x="\x1B[0m";function D(o){return o?`/${o.split("/").map((i,r)=>r===0?`${S}${i}${x}`:`${F}${i}${x}`).join("/")}`:""}function g(o,t){let e=(r,s="")=>{let n=t?s?`${t}/${s}`:t:s;return`[mc${D(n)}] ${r}`},i=r=>{o?(f.clearLine(process.stdout,0),f.cursorTo(process.stdout,0),console.log(r),o.prompt(!0)):console.log(r)};return{log:(r,s)=>i(e(r,s)),warn:(r,s="warn")=>i(e(r,s)),error:(r,s="err")=>i(e(r,s)),raw:i}}import*as p from"fs/promises";import*as m from"path";import*as b from"esbuild";async function T(o){let e=(await b.build({entryPoints:[o],bundle:!0,write:!1,platform:"node",format:"esm",target:"es2022",loader:{". ts":"ts"},external:["mineflayer"],logLevel:"silent"})).outputFiles[0].text,i=o.replace(/\.ts$/,". macro.mjs");return await p.writeFile(i,e),i}async function k(o){try{await p.unlink(o)}catch{}}function A(o){return m.isAbsolute(o)?o:m.resolve(process.cwd(),o)}async function U(o){try{return await p.access(o),!0}catch{return!1}}function j(o){return m.basename(o).replace(/\.(ts|js|mjs)$/,"")}async function w(o,t,e){let i=A(o),r=i,s=null,n=g(e,`macro/${j(o)}`);try{if(!await U(i))return n.error(`file not found: ${i}`),!1;i.endsWith(".ts")&&(n.log("compiling macro to js"),s=await T(i),r=s);let u=await import(`file://${r}?t=${Date.now()}`);return typeof u.default!="function"?(n.error("macro file must export a default function"),!1):(n.log("running"),await u.default({bot:t,logger:n}),n.log("finished"),!0)}catch(a){return n.error(`failed: ${a.message}`),!1}finally{s&&await k(s)}}var $=(r=>(r.Exit=".exit",r.Logout=".lo",r.Login=".li",r.Macro=".macro",r))($||{});function v(o){return Object.values($).some(t=>o.startsWith(t))}async function L(o,t){let e=null,i=C.createInterface({input:process.stdin,output:process.stdout}),r=g(i);i.setPrompt("> ");let s=async n=>{if(n=n.trim(),!n)return!1;if(!v(n)&&!e?.isLoggedIn)return r.raw("log in using .li before sending messages"),!1;if(v(n)){let[a,...c]=n.split(" ");switch(a){case".exit":return e?.disconnect(),i.close(),!0;case".li":{e?.isLoggedIn?r.error("client is already logged in"):(e=new d(o,r),e.registerAndLogIn());break}case".lo":{e?.isLoggedIn?e?.disconnect():r.error("client isn't logged in");break}case".macro":{if(!e?.isLoggedIn){r.error("client must be logged in to run macros");break}let u=c.join(" ");if(!u){r.error("usage: .macro <filepath>");break}let y=e.bot;y&&await w(u,y,i);break}}}else e?.sendMessage(n);return!1};if(i.on("line",async n=>{await s(n)&&process.exit(0),i.prompt()}),console.log("=== mincraft REPL ==="),console.log("input plain text to send a message to the server"),console.log(`input .li to log in to ${o.server.host}`),console.log(`input .lo to log out from ${o.server.host}`),console.log("input .macro <filepath> to run a macro"),console.log("input .exit to exit the REPL"),t&&t.length>0)for(let{command:n,delay:a}of t)n&&(r.raw(`> ${n}`),await s(n)&&process.exit(0)),a>0&&await new Promise(c=>setTimeout(c,a));i.prompt()}l.name("mincraft").description("Mineflayer CLI tool with supports for macros and proxies.").version("1.0.0").addHelpText("after",`
2
+ import{Option as O,program as l}from"commander";function F(t){let o=[],e="",r=0;for(;r<t.length;)t[r]==="\\"&&r+1<t.length?(e+=t[r]+t[r+1],r+=2):t[r]===","?(o.push(e),e="",r++):(e+=t[r],r++);return o.push(e),o}function T(t){let o="",e=0;for(;e<t.length;)if(t[e]==="\\"&&e+1<t.length){let r=t[e+1];r===","||r==="{"||r==="}"?(o+=r,e+=2):(o+=t[e],e++)}else o+=t[e],e++;return o}function v(t){let o=[],e=F(t),r=/^\{\{(\d+(?:\.\d+)?)\}\}$/;for(let n of e){let s=n.trim();if(!s)continue;let a=s.match(r);if(a){let i=parseFloat(a[1]),c=Math.round(i*1e3);o.push({command:"",delay:c})}else{let i=T(s);o.push({command:i,delay:0})}}return o}import*as I from"readline";import p from"chalk";import{createBot as A}from"mineflayer";import{SocksClient as D}from"socks";var u=class{proxy;client;server;options;logger;isLoggedIn;bot;constructor({proxy:o,client:e,server:r,options:n},s){this.proxy=o,this.client=e,this.server=r,this.options=n,this.logger=s,this.isLoggedIn=!1}async registerAndLogIn(){let o={host:this.server.host,port:this.server.port,username:this.client.account.email,auth:this.client.account.auth,version:this.client.version,hideErrors:!0};this.proxy&&(o.connect=e=>{this.connectViaProxy(e)}),this.bot=A(o),this.options.verboseLogging&&this.registerClientEvents(),this.registerBotEvents()}connectViaProxy(o){this.logger.log("connecting via proxy");let{host:e,port:r,user:n,pass:s,type:a}=this.proxy,i=this.server;D.createConnection({proxy:{host:e,port:r,type:a,userId:n,password:s},command:"connect",destination:{host:i.host,port:i.port},timeout:3e4}).then(c=>{o.setSocket(c.socket),o.emit("connect")}).catch(c=>{this.logger.error(`proxy connection failed: ${c.message}`),o.emit("error",c)})}registerClientEvents(){this.bot._client.on("connect",()=>{this.logger.log("TCP connection established")}),this.bot._client.on("login",()=>{this.logger.log("login packet received")}),this.bot._client.on("error",o=>{this.logger.error(`client error: ${o.message}`)}),this.bot._client.on("end",o=>{this.logger.warn(`client ended: ${o}`)})}registerBotEvents(){this.bot.once("spawn",()=>{let{ign:o,uuid:e}=this.client.account;this.logger.log(`logged in as ${o} (${e})`),this.isLoggedIn=!0}),this.bot.once("kicked",o=>{this.logger.warn(`kicked: ${JSON.stringify(o)}`),this.disconnect()}),this.bot.once("error",o=>{this.logger.error(`bot error: ${o.message}`),this.isLoggedIn=!1}),this.bot.once("end",o=>{this.logger.warn(`disconnected by server: ${JSON.stringify(o)}`),this.disconnect()}),this.options.logMessages&&this.bot.on("messagestr",o=>{let e=o.split(`
3
+ `);if(e.length===1)this.logger.log(o,"chat");else{this.logger.log(e[0],"chat");for(let r=1;r<e.length;r++)this.logger.raw(` ${e[r]}`)}})}disconnect(){this.bot&&(this.proxy?this.bot._client.socket?.destroy():this.bot.quit(),this.isLoggedIn=!1)}sendMessage(o){this.bot.chat(o)}};import*as y from"readline";import h from"chalk";function U(t){return t?`/${t.split("/").map((r,n)=>n===0?r==="err"?h.red(r):r==="warn"?h.yellow(r):h.gray(r):h.blue(r)).join("/")}`:""}function m(t,o){let e=(n,s="")=>{let a=o?s?`${o}/${s}`:o:s;return`[mc${U(a)}] ${n}`},r=n=>{t?(y.clearLine(process.stdout,0),y.cursorTo(process.stdout,0),console.log(n),t.prompt(!0)):console.log(n)};return{log:(n,s)=>r(e(n,s)),warn:(n,s="warn")=>r(e(n,s)),error:(n,s="err")=>r(e(n,s)),raw:r}}import*as f from"fs/promises";import*as d from"path";import*as C from"esbuild";async function j(t){let e=(await C.build({entryPoints:[t],bundle:!0,write:!1,platform:"node",format:"esm",target:"es2022",loader:{". ts":"ts"},external:["mineflayer"],logLevel:"silent"})).outputFiles[0].text,r=t.replace(/\.ts$/,". macro.mjs");return await f.writeFile(r,e),r}async function B(t){try{await f.unlink(t)}catch{}}function N(t){return d.isAbsolute(t)?t:d.resolve(process.cwd(),t)}async function R(t){try{return await f.access(t),!0}catch{return!1}}function _(t){return d.basename(t).replace(/\.(ts|js|mjs)$/,"")}async function $(t,o,e){let r=N(t),n=r,s=null,a=m(e,`macro/${_(t)}`);try{if(!await R(r))return a.error(`file not found: ${r}`),!1;r.endsWith(".ts")&&(a.log("compiling macro to js"),s=await j(r),n=s);let g=await import(`file://${n}?t=${Date.now()}`);return typeof g.default!="function"?(a.error("macro file must export a default function"),!1):(a.log("running"),await g.default({bot:o,logger:a}),a.log("finished"),!0)}catch(i){return a.error(`failed: ${i.message}`),!1}finally{s&&await B(s)}}var E=(s=>(s.Exit=".exit",s.Logout=".lo",s.Login=".li",s.Macro=".macro",s.Help=".help",s))(E||{});function L(t){return Object.values(E).some(o=>t.startsWith(o))}function H(t,o){t(`type ${p.magenta(".li")} to log in to ${o}`),t(`type ${p.magenta(".lo")} to log out from ${o}`),t(`type ${p.magenta(".macro <filepath>")} to run a macro`),t(`type ${p.magenta(".help")} to show this REPL reference`),t(`type ${p.magenta(".exit")} to exit the REPL`),t(`type ${p.bold("any other value")} to send a message to the server`)}async function P(t,o){process.stdout.write("\x1B[2J\x1B[2;0H");let e=null,r=I.createInterface({input:process.stdin,output:process.stdout}),n=m(r),s=i=>n.raw(`>> ${i}`);r.setPrompt("> ");let a=async i=>{if(i=i.trim(),!i)return!1;if(!L(i)&&!e?.isLoggedIn)return n.error("log in using .li before sending messages"),!1;if(L(i)){let[c,...g]=i.split(" ");switch(c){case".exit":return e?.disconnect(),r.close(),!0;case".li":{e?.isLoggedIn?n.error("client is already logged in"):(e=new u(t,n),e.registerAndLogIn());break}case".lo":{e?.isLoggedIn?e?.disconnect():n.error("client isn't logged in");break}case".macro":{if(!e?.isLoggedIn){n.error("client must be logged in to run macros");break}let b=g.join(" ");if(!b){n.error("usage: .macro <filepath>");break}let w=e.bot;w&&await $(b,w,r);break}case".help":{H(s,t.server.host);break}}}else e?.sendMessage(i);return!1};if(r.on("line",async i=>{await a(i)&&process.exit(0),r.prompt()}),console.log(p.green(`mincraft REPL ${M}`)),s('type ".help" for more information.'),o&&o.length>0)for(let{command:i,delay:c}of o)c>0&&await new Promise(g=>setTimeout(g,c)),i&&(n.raw(`> ${i}`),await a(i)&&process.exit(0));r.prompt()}l.name("mincraft").description("Mineflayer CLI tool with supports for macros and proxies.").version("1.0.0").addHelpText("after",`
4
4
  Examples:
5
5
  $ mincraft mc.hypixel.net 1.21.4 --ign FuriousDestroyer --email you@example.com
6
6
  $ mincraft mythic.gg 1.7.10 -p 58585 --ign MangoSyrup --email you@example.com --prox proxy.com:1234:mango:secret
7
- $ mincraft mc.hypixel.net 1.21.4 --ign Player --email you@example.com --exec "{{1000}}.li{{2000}}\\nhello{{500}}\\n.lo"
8
- `);l.argument("<host>","Server hostname").option("-p, --port <PORT>","Server port",o=>parseInt(o,10),25565);l.argument("<version>","Client version, e.g. 1.21.4");var E=["host","port","user","pass"],P=":";l.option("--prox <HOST:PORT:USER:PASS>","Connect to the server with a proxy").option("--prox-field-order <FORMAT>",'The order of the proxy credential fields, e.g. "user,pass,host,port".').option("--prox-field-sep <SEP>","The separator of the proxy credential fields").option("--prox-type <4|5>","The SOCKS proxy type",o=>parseInt(o,10),5);var B="microsoft";l.addOption(new I("--ign <IN-GAME NAME>","Player username").conflicts("uuid")).addOption(new I("--uuid <UUID>","Player UUID").conflicts("ign")).requiredOption("--email <EMAIL>","Account email").option("--auth <AUTH>","Account authentication method",B);l.option("--no-log-messages","Do not log messages your client receives").option("--verbose","Enable additional logging messages").option("--exec <COMMANDS>",'Execute REPL commands on startup with optional millisecond-based delays, e.g. "{{1000}}.li{{2000}}\\nhello{{500}}\\n.lo".',(o,t)=>t.concat(o),[]);l.action(async(o,t,e)=>{if(!e.ign&&!e.uuid&&l.error("error: must specify either --ign or --uuid"),e.proxFieldOrder){let s=e.proxyFieldSep??P;e.proxFieldOrder.split(s).every(a=>E.includes(a))||l.error("error: --prox-field-order includes invalid fields")}let i=await H(l),r=[];for(let s of e.exec){let n=N(s);r.push(...n)}await L(i,r.length>0?r:void 0)});function N(o){let t=[],e=o.split("\\n").filter(Boolean);for(let i of e){let r=i.match(/^\{\{(\d+)\}\}/);if(r){let n=parseInt(r[1],10);t.push({command:"",delay:n})}let s=i.replace(/^\{\{\d+\}\}/,"");if(s){let n=s.match(/\{\{(\d+)\}\}$/);if(n){let a=parseInt(n[1],10),c=s.replace(/\{\{\d+\}\}$/,"");t.push({command:c,delay:a})}else t.push({command:s,delay:0})}}return t}async function R(o){let e=await(await fetch(`https://sessionserver.mojang.com/session/minecraft/profile/${o}`)).json();if(!e?.name)throw new Error("Could not fetch IGN from UUID");return e.name}async function _(o){let e=await(await fetch(`https://api.mojang.com/users/profiles/minecraft/${o}`)).json();if(!e?.id)throw new Error("Could not fetch UUID from IGN");return e.id}function G(o,t,e){let i=o.split(e),r=Object.fromEntries(t.map((s,n)=>[s,i[n]]));return r.port=+r.port,r}async function H(o){let t=o.args,e=o.opts();return{server:{host:t[0],port:e.port},client:{version:t[1],account:{auth:e.auth,uuid:e.uuid??await _(e.ign),ign:e.ign??await R(e.uuid),email:e.email}},...e.prox?{proxy:{...G(e.prox,e.proxFieldOrder??E,e.proxFieldSep??P),type:e.proxType}}:{},options:{logMessages:e.noLogMessages??!0,verboseLogging:e.verbose??!1}}}var h=g(),ne=h.log,se=h.warn,ae=h.error;l.parse();export{h as defaultLogger,ae as error,ne as log,se as warn};
7
+ $ mincraft mc.hypixel.net 1.21.4 --ign Player --email you@example.com --exec "{{1}},.li,{{2.5}},hello,{{0.5}},.lo"
8
+ $ mincraft mc.hypixel.net 1.21.4 --ign Player --email you@example.com --exec "{{1.5}},.li,{{5}},hello\\,world,{{0.5}},.lo"
9
+ `);l.argument("<host>","Server hostname").option("-p, --port <PORT>","Server port",t=>parseInt(t,10),25565);l.argument("<version>","Client version, e.g. 1.21.4");var S=["host","port","user","pass"],k=":";l.option("--prox <HOST:PORT:USER:PASS>","Connect to the server with a proxy").option("--prox-field-order <FORMAT>",'The order of the proxy credential fields, e.g. "user,pass,host,port".').option("--prox-field-sep <SEP>","The separator of the proxy credential fields").option("--prox-type <4|5>","The SOCKS proxy type",t=>parseInt(t,10),5);var G="microsoft";l.addOption(new O("--ign <IN-GAME NAME>","Player username").conflicts("uuid")).addOption(new O("--uuid <UUID>","Player UUID").conflicts("ign")).requiredOption("--email <EMAIL>","Account email").option("--auth <AUTH>","Account authentication method",G);l.option("--no-log-messages","Do not log messages your client receives").option("--verbose","Enable additional logging messages").option("--exec <COMMANDS>",'Execute REPL commands on startup with optional delays, e.g. "{{1}},.li,{{2.5}},hello,{{0.5}},.lo", where {{N}} represents a delay. You can escape curly braces and commas to include them in commands/messages.',(t,o)=>o.concat(t),[]);l.action(async(t,o,e)=>{if(!e.ign&&!e.uuid&&l.error("error: must specify either --ign or --uuid"),e.proxFieldOrder){let s=e.proxyFieldSep??k;e.proxFieldOrder.split(s).every(i=>S.includes(i))||l.error("error: --prox-field-order includes invalid fields")}let r=await W(l),n=[];for(let s of e.exec){let a=v(s);n.push(...a)}await P(r,n.length>0?n:void 0)});async function J(t){let e=await(await fetch(`https://sessionserver.mojang.com/session/minecraft/profile/${t}`)).json();if(!e?.name)throw new Error("Could not fetch IGN from UUID");return e.name}async function q(t){let e=await(await fetch(`https://api.mojang.com/users/profiles/minecraft/${t}`)).json();if(!e?.id)throw new Error("Could not fetch UUID from IGN");return e.id}function V(t,o,e){let r=t.split(e),n=Object.fromEntries(o.map((s,a)=>[s,r[a]]));return n.port=+n.port,n}async function W(t){let o=t.args,e=t.opts();return{server:{host:o[0],port:e.port},client:{version:o[1],account:{auth:e.auth,uuid:e.uuid??await q(e.ign),ign:e.ign??await J(e.uuid),email:e.email}},...e.prox?{proxy:{...V(e.prox,e.proxFieldOrder??S,e.proxFieldSep??k),type:e.proxType}}:{},options:{logMessages:e.noLogMessages??!0,verboseLogging:e.verbose??!1}}}var x=m(),de=x.log,ue=x.warn,he=x.error,M="v1.4.0";l.parse();export{x as defaultLogger,he as error,de as log,M as version,ue as warn};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mincraft/cli",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "Mineflayer CLI tool with support for macros and proxies",
5
5
  "bin": {
6
6
  "mincraft": "./dist/index.mjs"
@@ -13,11 +13,12 @@
13
13
  ],
14
14
  "dependencies": {
15
15
  "@inquirer/prompts": "^8.1.0",
16
+ "chalk": "^5.6.2",
16
17
  "commander": "^14.0.2",
17
18
  "esbuild": "^0.27.2",
18
19
  "mineflayer": "^4.33.0",
19
20
  "socks": "^2.8.7",
20
- "@mincraft/types": "1.3.0"
21
+ "@mincraft/types": "1.4.0"
21
22
  },
22
23
  "devDependencies": {
23
24
  "@types/debug": "^4.1.12",
package/src/cli.ts CHANGED
@@ -4,6 +4,7 @@ import type {
4
4
  ProxyCredentials,
5
5
  } from "@mincraft/types";
6
6
  import { type Command, Option, program } from "commander";
7
+ import { parseExecCommands } from "./exec";
7
8
  import { run } from "./repl";
8
9
 
9
10
  // meta
@@ -17,7 +18,8 @@ program
17
18
  Examples:
18
19
  $ mincraft mc.hypixel.net 1.21.4 --ign FuriousDestroyer --email you@example.com
19
20
  $ mincraft mythic.gg 1.7.10 -p 58585 --ign MangoSyrup --email you@example.com --prox proxy.com:1234:mango:secret
20
- $ mincraft mc.hypixel.net 1.21.4 --ign Player --email you@example.com --exec "{{1000}}.li{{2000}}\\nhello{{500}}\\n.lo"
21
+ $ mincraft mc.hypixel.net 1.21.4 --ign Player --email you@example.com --exec "{{1}},.li,{{2.5}},hello,{{0.5}},.lo"
22
+ $ mincraft mc.hypixel.net 1.21.4 --ign Player --email you@example.com --exec "{{1.5}},.li,{{5}},hello\\,world,{{0.5}},.lo"
21
23
  `,
22
24
  );
23
25
 
@@ -74,7 +76,8 @@ program
74
76
  .option("--verbose", "Enable additional logging messages")
75
77
  .option(
76
78
  "--exec <COMMANDS>",
77
- 'Execute REPL commands on startup with optional millisecond-based delays, e.g. "{{1000}}.li{{2000}}\\nhello{{500}}\\n.lo".',
79
+ 'Execute REPL commands on startup with optional delays, e.g. "{{1}},.li,{{2.5}},hello,{{0.5}},.lo", where {{N}} represents a delay.' +
80
+ " You can escape curly braces and commas to include them in commands/messages.",
78
81
  (val: string, prev: string[]) => prev.concat(val),
79
82
  [],
80
83
  );
@@ -103,33 +106,6 @@ program.action(async (_host, _version, options) => {
103
106
  await run(config, commands.length > 0 ? commands : undefined);
104
107
  });
105
108
 
106
- function parseExecCommands(input: string) {
107
- const result: DelayableCommands = [];
108
- const lines = input.split("\\n").filter(Boolean);
109
-
110
- for (const line of lines) {
111
- const initialDelayMatch = line.match(/^\{\{(\d+)\}\}/);
112
- if (initialDelayMatch) {
113
- const initialDelay = parseInt(initialDelayMatch[1], 10);
114
- result.push({ command: "", delay: initialDelay });
115
- }
116
-
117
- const lineWithoutInitial = line.replace(/^\{\{\d+\}\}/, "");
118
- if (lineWithoutInitial) {
119
- const trailingDelayMatch = lineWithoutInitial.match(/\{\{(\d+)\}\}$/);
120
- if (trailingDelayMatch) {
121
- const delay = parseInt(trailingDelayMatch[1], 10);
122
- const command = lineWithoutInitial.replace(/\{\{\d+\}\}$/, "");
123
- result.push({ command, delay });
124
- } else {
125
- result.push({ command: lineWithoutInitial, delay: 0 });
126
- }
127
- }
128
- }
129
-
130
- return result;
131
- }
132
-
133
109
  async function getIGN(uuid: string) {
134
110
  const res = await fetch(
135
111
  `https://sessionserver.mojang.com/session/minecraft/profile/${uuid}`,
package/src/exec.ts ADDED
@@ -0,0 +1,73 @@
1
+ import type { DelayableCommands } from "@mincraft/types";
2
+
3
+ function splitByUnescapedCommas(input: string) {
4
+ const parts: string[] = [];
5
+ let current = "";
6
+ let i = 0;
7
+
8
+ while (i < input.length) {
9
+ if (input[i] === "\\" && i + 1 < input.length) {
10
+ current += input[i] + input[i + 1];
11
+ i += 2;
12
+ } else if (input[i] === ",") {
13
+ parts.push(current);
14
+ current = "";
15
+ i++;
16
+ } else {
17
+ current += input[i];
18
+ i++;
19
+ }
20
+ }
21
+ parts.push(current);
22
+
23
+ return parts;
24
+ }
25
+
26
+ function unescapeString(input: string) {
27
+ let result = "";
28
+ let i = 0;
29
+
30
+ while (i < input.length) {
31
+ if (input[i] === "\\" && i + 1 < input.length) {
32
+ const nextChar = input[i + 1];
33
+ if (nextChar === "," || nextChar === "{" || nextChar === "}") {
34
+ result += nextChar;
35
+ i += 2;
36
+ } else {
37
+ result += input[i];
38
+ i++;
39
+ }
40
+ } else {
41
+ result += input[i];
42
+ i++;
43
+ }
44
+ }
45
+
46
+ return result;
47
+ }
48
+
49
+ export function parseExecCommands(input: string) {
50
+ const result: DelayableCommands = [];
51
+ const parts = splitByUnescapedCommas(input);
52
+
53
+ const delayPattern = /^\{\{(\d+(?:\.\d+)?)\}\}$/;
54
+
55
+ for (const part of parts) {
56
+ const trimmed = part.trim();
57
+ if (!trimmed) {
58
+ continue;
59
+ }
60
+
61
+ const delayMatch = trimmed.match(delayPattern);
62
+ if (delayMatch) {
63
+ const delaySeconds = parseFloat(delayMatch[1]);
64
+ const delayMs = Math.round(delaySeconds * 1000);
65
+ result.push({ command: "", delay: delayMs });
66
+ } else {
67
+ const command = unescapeString(trimmed);
68
+ result.push({ command, delay: 0 });
69
+ }
70
+ }
71
+
72
+ return result;
73
+ }
package/src/index.ts CHANGED
@@ -6,4 +6,6 @@ export const log = defaultLogger.log;
6
6
  export const warn = defaultLogger.warn;
7
7
  export const error = defaultLogger.error;
8
8
 
9
+ export const version = "v1.4.0";
10
+
9
11
  program.parse();
package/src/logger.ts CHANGED
@@ -1,17 +1,18 @@
1
1
  import * as readline from "node:readline";
2
2
  import type { Logger } from "@mincraft/types";
3
-
4
- const GRAY = "\x1b[90m";
5
- const BLUE = "\x1b[34m";
6
- const RESET = "\x1b[0m";
3
+ import chalk from "chalk";
7
4
 
8
5
  function formatScope(fullScope: string) {
9
6
  if (!fullScope) return "";
10
7
 
11
8
  const parts = fullScope.split("/");
12
9
  const colored = parts.map((part, i) => {
13
- if (i === 0) return `${GRAY}${part}${RESET}`;
14
- return `${BLUE}${part}${RESET}`;
10
+ if (i === 0) {
11
+ if (part === "err") return chalk.red(part);
12
+ if (part === "warn") return chalk.yellow(part);
13
+ return chalk.gray(part);
14
+ }
15
+ return chalk.blue(part);
15
16
  });
16
17
 
17
18
  return `/${colored.join("/")}`;
package/src/repl.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import * as readline from "node:readline";
2
2
  import type { Config, DelayableCommands } from "@mincraft/types";
3
+ import chalk from "chalk";
4
+ import { version } from ".";
3
5
  import { BotClient } from "./bot";
4
6
  import { createLogger } from "./logger";
5
7
  import { loadAndRunMacro } from "./macro";
@@ -9,13 +11,24 @@ export enum BotCommand {
9
11
  Logout = ".lo",
10
12
  Login = ".li",
11
13
  Macro = ".macro",
14
+ Help = ".help",
12
15
  }
13
16
 
14
17
  function isCommand(value: string) {
15
18
  return Object.values(BotCommand).some((cmd) => value.startsWith(cmd));
16
19
  }
17
20
 
21
+ function showReplHelp(log: (msg: string) => void, serverHost: string) {
22
+ log(`type ${chalk.magenta(".li")} to log in to ${serverHost}`);
23
+ log(`type ${chalk.magenta(".lo")} to log out from ${serverHost}`);
24
+ log(`type ${chalk.magenta(".macro <filepath>")} to run a macro`);
25
+ log(`type ${chalk.magenta(".help")} to show this REPL reference`);
26
+ log(`type ${chalk.magenta(".exit")} to exit the REPL`);
27
+ log(`type ${chalk.bold("any other value")} to send a message to the server`);
28
+ }
29
+
18
30
  export async function run(config: Config, commands?: DelayableCommands) {
31
+ process.stdout.write("\u001b[2J\u001b[2;0H");
19
32
  let bot: BotClient = null;
20
33
 
21
34
  const rl = readline.createInterface({
@@ -24,6 +37,7 @@ export async function run(config: Config, commands?: DelayableCommands) {
24
37
  });
25
38
 
26
39
  const logger = createLogger(rl);
40
+ const helpLogger = (msg: string) => logger.raw(`>> ${msg}`);
27
41
 
28
42
  rl.setPrompt("> ");
29
43
 
@@ -35,7 +49,7 @@ export async function run(config: Config, commands?: DelayableCommands) {
35
49
  }
36
50
 
37
51
  if (!isCommand(input) && !bot?.isLoggedIn) {
38
- logger.raw("log in using .li before sending messages");
52
+ logger.error("log in using .li before sending messages");
39
53
  return false;
40
54
  }
41
55
 
@@ -81,6 +95,10 @@ export async function run(config: Config, commands?: DelayableCommands) {
81
95
  }
82
96
  break;
83
97
  }
98
+ case BotCommand.Help: {
99
+ showReplHelp(helpLogger, config.server.host);
100
+ break;
101
+ }
84
102
  }
85
103
  } else {
86
104
  bot?.sendMessage(input);
@@ -97,15 +115,14 @@ export async function run(config: Config, commands?: DelayableCommands) {
97
115
  rl.prompt();
98
116
  });
99
117
 
100
- console.log("=== mincraft REPL ===");
101
- console.log("input plain text to send a message to the server");
102
- console.log(`input .li to log in to ${config.server.host}`);
103
- console.log(`input .lo to log out from ${config.server.host}`);
104
- console.log("input .macro <filepath> to run a macro");
105
- console.log("input .exit to exit the REPL");
118
+ console.log(chalk.green(`mincraft REPL ${version}`));
119
+ helpLogger('type ".help" for more information.');
106
120
 
107
121
  if (commands && commands.length > 0) {
108
122
  for (const { command, delay } of commands) {
123
+ if (delay > 0) {
124
+ await new Promise((resolve) => setTimeout(resolve, delay));
125
+ }
109
126
  if (command) {
110
127
  logger.raw(`> ${command}`);
111
128
  const shouldExit = await handleInput(command);
@@ -113,9 +130,6 @@ export async function run(config: Config, commands?: DelayableCommands) {
113
130
  process.exit(0);
114
131
  }
115
132
  }
116
- if (delay > 0) {
117
- await new Promise((resolve) => setTimeout(resolve, delay));
118
- }
119
133
  }
120
134
  }
121
135