├── example ├── example_behavior_pack │ ├── pack_icon.png │ ├── structures │ │ └── gametest │ │ │ └── remote.mcstructure │ ├── scripts │ │ └── main.js │ ├── manifest.json │ └── .vscode │ │ └── launch.json ├── tsconfig.json ├── dumpScope.ts ├── evaluate.ts └── breakpoint.ts ├── tsconfig.json ├── src ├── tsconfig.json ├── index.ts ├── lib │ ├── connection.ts │ ├── minecraft.ts │ └── session.ts └── repl.ts ├── README.md ├── tsconfig-base.json ├── biome.json ├── LICENSE ├── .gitignore └── package.json /example/example_behavior_pack/pack_icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XeroAlpha/quickjs-debugger/HEAD/example/example_behavior_pack/pack_icon.png -------------------------------------------------------------------------------- /example/example_behavior_pack/structures/gametest/remote.mcstructure: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XeroAlpha/quickjs-debugger/HEAD/example/example_behavior_pack/structures/gametest/remote.mcstructure -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "references": [ 3 | { 4 | "path": "./src" 5 | }, 6 | { 7 | "path": "./example" 8 | } 9 | ], 10 | "files": [] 11 | } 12 | -------------------------------------------------------------------------------- /src/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig-base.json", 3 | "compilerOptions": { 4 | "composite": true, 5 | "rootDir": ".", 6 | "outDir": "../dist", 7 | "declarationDir": "../dist" 8 | }, 9 | "include": ["**/*"] 10 | } 11 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export { DebugConnection, QuickJSDebugConnection } from './lib/connection.js'; 2 | export { MinecraftDebugSession } from './lib/minecraft.js'; 3 | export { 4 | InspectOptions, 5 | QuickJSDebugSession, 6 | QuickJSHandle, 7 | QuickJSScope, 8 | QuickJSStackFrame, 9 | QuickJSVariable, 10 | } from './lib/session.js'; 11 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # QuickJS Debugger 2 | 3 | A library that supports [QuickJS Debugging Protocol](https://github.com/koush/vscode-quickjs-debug). 4 | 5 | You can also use it to debug [Minecraft GameTest](https://docs.microsoft.com/minecraft/creator/documents/gametestgettingstarted). 6 | 7 | See [examples](https://github.com/XeroAlpha/quickjs-debugger/tree/master/example) for examples. 8 | 9 | ## REPL 10 | 11 | ``` 12 | qjs-debugger 13 | ``` 14 | -------------------------------------------------------------------------------- /example/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig-base.json", 3 | "compilerOptions": { 4 | "composite": true, 5 | "noEmit": true, 6 | "rootDir": ".", 7 | "outDir": "../dist/example", 8 | "declarationDir": "../dist/example" 9 | }, 10 | "include": ["**/*"], 11 | "exclude": ["example_behavior_pack"], 12 | "references": [ 13 | { 14 | "path": "../src" 15 | } 16 | ] 17 | } 18 | -------------------------------------------------------------------------------- /example/example_behavior_pack/scripts/main.js: -------------------------------------------------------------------------------- 1 | import * as Minecraft from '@minecraft/server'; 2 | import * as GameTest from '@minecraft/server-gametest'; 3 | 4 | globalThis.totalTicks = 0; 5 | Minecraft.system.run(function handler() { 6 | globalThis.totalTicks += 1; // trigger debugger to response since quickjs does not provide a message loop 7 | Minecraft.system.run(handler); 8 | }); 9 | 10 | GameTest.register('gametest', 'remote', (test) => { 11 | test.succeed(); 12 | /* BREAKPOINT HERE */ console.error(`Current tick: ${globalThis.totalTicks}`); 13 | }); 14 | -------------------------------------------------------------------------------- /tsconfig-base.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "moduleResolution": "NodeNext", 4 | "module": "NodeNext", 5 | "target": "ESNext", 6 | "lib": ["ESNext"], 7 | "skipLibCheck": true, 8 | "allowJs": true, 9 | "declaration": true, 10 | "sourceMap": true, 11 | "strict": true, 12 | "noImplicitAny": true, 13 | "strictNullChecks": true, 14 | "strictFunctionTypes": true, 15 | "strictBindCallApply": true, 16 | "strictPropertyInitialization": true, 17 | "esModuleInterop": true, 18 | "outDir": "./dist", 19 | "declarationDir": "./dist" 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /example/example_behavior_pack/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "format_version": 2, 3 | "header": { 4 | "description": "", 5 | "name": "GameTest Remote", 6 | "uuid": "8104db82-a292-47a0-bc79-34bbbc4df35f", 7 | "version": [0, 0, 1], 8 | "min_engine_version": [1, 21, 10] 9 | }, 10 | "modules": [ 11 | { 12 | "description": "", 13 | "uuid": "3c80b6d8-7ad8-474f-a97a-95d4835ab217", 14 | "version": [0, 0, 1], 15 | "type": "script", 16 | "lang": "javascript", 17 | "entry": "scripts/main.js" 18 | } 19 | ], 20 | "dependencies": [ 21 | { 22 | "module_name": "@minecraft/server", 23 | "version": "beta" 24 | } 25 | ] 26 | } 27 | -------------------------------------------------------------------------------- /example/example_behavior_pack/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // 使用 IntelliSense 了解相关属性。 3 | // 悬停以查看现有属性的描述。 4 | // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "type": "minecraft-js", 9 | "request": "attach", 10 | "name": "Start Debug Minecraft (Server)", 11 | "mode": "listen", 12 | "localRoot": "${workspaceFolder}/", 13 | "host": "localhost", 14 | "port": 19144 15 | }, 16 | { 17 | "type": "minecraft-js", 18 | "request": "attach", 19 | "name": "Start Debug Minecraft (Client)", 20 | "mode": "connect", 21 | "localRoot": "${workspaceFolder}/", 22 | "host": "localhost", 23 | "port": 19145 24 | } 25 | ] 26 | } -------------------------------------------------------------------------------- /biome.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://biomejs.dev/schemas/2.3.6/schema.json", 3 | "vcs": { 4 | "enabled": true, 5 | "clientKind": "git", 6 | "useIgnoreFile": true 7 | }, 8 | "files": { 9 | "includes": ["**", "!!**/dist", "!!example/example_behavior_pack", "!!test/quickjs"] 10 | }, 11 | "formatter": { 12 | "enabled": true, 13 | "indentStyle": "space", 14 | "indentWidth": 4, 15 | "lineWidth": 120 16 | }, 17 | "linter": { 18 | "enabled": true, 19 | "rules": { 20 | "recommended": true 21 | } 22 | }, 23 | "javascript": { 24 | "formatter": { 25 | "quoteStyle": "single", 26 | "indentStyle": "space", 27 | "indentWidth": 4, 28 | "lineWidth": 120 29 | } 30 | }, 31 | "assist": { 32 | "enabled": true, 33 | "actions": { 34 | "source": { 35 | "organizeImports": "on" 36 | } 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 ProjectXero 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /example/dumpScope.ts: -------------------------------------------------------------------------------- 1 | import { strict as assert } from 'node:assert'; 2 | import { type AddressInfo, createServer, type Socket } from 'node:net'; 3 | import { inspect } from 'node:util'; 4 | import { QuickJSDebugConnection, QuickJSDebugSession } from '../src/index.js'; 5 | 6 | type QuickJSGlobal = { Global: QuickJSGlobal } & { 7 | -readonly [K in keyof typeof globalThis]: (typeof globalThis)[K]; 8 | }; 9 | 10 | async function test(socket: Socket) { 11 | const conn = new QuickJSDebugConnection(socket); 12 | const session = new QuickJSDebugSession(conn); 13 | const topStack = await session.getTopStack(); 14 | const target = {} as QuickJSGlobal; 15 | const scopes = await topStack.getScopes(); 16 | await Promise.all( 17 | scopes.map(async (scope) => { 18 | (target as Record)[scope.name] = await scope.inspect({ inspectProto: true }); 19 | }), 20 | ); 21 | process.stdout.write(`${inspect(target)}\n`); 22 | assert.equal(target.Global.JSON, target.Global.globalThis.JSON); 23 | session.resume(); 24 | conn.close(); 25 | } 26 | 27 | function main([port]: string[]) { 28 | const server = createServer((socket) => { 29 | test(socket).catch((err) => { 30 | console.error(err); 31 | }); 32 | }); 33 | server.listen(port); 34 | const addr = server.address() as AddressInfo; 35 | process.stdout.write(`Please connect to :${addr.port}\n`); 36 | } 37 | 38 | main(process.argv.slice(2)); 39 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | .env.test 60 | 61 | # parcel-bundler cache (https://parceljs.org/) 62 | .cache 63 | 64 | # next.js build output 65 | .next 66 | 67 | # nuxt.js build output 68 | .nuxt 69 | 70 | # vuepress build output 71 | .vuepress/dist 72 | 73 | # Serverless directories 74 | .serverless/ 75 | 76 | # FuseBox cache 77 | .fusebox/ 78 | 79 | # DynamoDB Local files 80 | .dynamodb/ 81 | 82 | # dist 83 | dist/ 84 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "quickjs-debugger", 3 | "version": "2.3.0", 4 | "description": "A debug library for quickjs", 5 | "type": "module", 6 | "main": "./dist/index.js", 7 | "types": "./dist/index.d.ts", 8 | "bin": { 9 | "qjs-debugger": "./dist/repl.js" 10 | }, 11 | "files": [ 12 | "dist/*.js", 13 | "dist/*.d.ts", 14 | "dist/lib/*.js", 15 | "dist/lib/*.d.ts" 16 | ], 17 | "scripts": { 18 | "clean": "rimraf ./dist", 19 | "build": "tsc --build", 20 | "lint": "biome check --write", 21 | "watch": "tsc --build --watch --preserveWatchOutput" 22 | }, 23 | "repository": { 24 | "type": "git", 25 | "url": "git+https://github.com/XeroAlpha/quickjs-debugger.git" 26 | }, 27 | "keywords": [ 28 | "quickjs", 29 | "debugger", 30 | "gametest" 31 | ], 32 | "author": "ProjectXero", 33 | "license": "MIT", 34 | "bugs": { 35 | "url": "https://github.com/XeroAlpha/quickjs-debugger/issues" 36 | }, 37 | "homepage": "https://github.com/XeroAlpha/quickjs-debugger", 38 | "devDependencies": { 39 | "@biomejs/biome": "2.3.6", 40 | "@minecraft/server": "^2.5.0-beta.1.21.130-preview.25", 41 | "@minecraft/server-gametest": "^1.0.0-beta.1.21.130-preview.25", 42 | "@types/node": "^24.10.1", 43 | "rimraf": "^6.1.2", 44 | "typescript": "^5.9.3" 45 | }, 46 | "dependencies": { 47 | "@vscode/debugprotocol": "^1.68.0" 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /example/evaluate.ts: -------------------------------------------------------------------------------- 1 | import { strict as assert } from 'node:assert'; 2 | import { type AddressInfo, createServer, type Socket } from 'node:net'; 3 | import { QuickJSDebugConnection, QuickJSDebugSession } from '../src/index.js'; 4 | 5 | async function test(socket: Socket) { 6 | const conn = new QuickJSDebugConnection(socket); 7 | const session = new QuickJSDebugSession(conn); 8 | const topStack = await session.getTopStack(); 9 | const expected = { 10 | number: 1, 11 | float: 0.125, 12 | string: 'Hello world', 13 | boolean: false, 14 | null: null, 15 | undefined, 16 | object: { array: [1, 2, 3] }, 17 | }; 18 | const resultRef = await topStack.evaluateExpression(`({ 19 | number: 1, 20 | float: 0.125, 21 | string: "Hello world", 22 | boolean: false, 23 | null: null, 24 | undefined, 25 | object: { array: [1, 2, 3] } 26 | })`); 27 | const result = await resultRef.inspect(); 28 | assert.deepEqual(result, expected); 29 | process.stdout.write('Local scope\n'); 30 | process.stdout.write( 31 | await topStack.evaluate(() => { 32 | const error = new Error(); 33 | return error.stack ?? ''; 34 | }), 35 | ); 36 | process.stdout.write('Global scope\n'); 37 | process.stdout.write( 38 | await topStack.evaluateGlobal(() => { 39 | const error = new Error(); 40 | return error.stack ?? ''; 41 | }), 42 | ); 43 | session.resume(); 44 | conn.close(); 45 | } 46 | 47 | function main([port]: string[]) { 48 | const server = createServer((socket) => { 49 | test(socket).catch((err) => { 50 | console.error(err); 51 | }); 52 | }); 53 | server.listen(port); 54 | const addr = server.address() as AddressInfo; 55 | process.stdout.write(`Please connect to :${addr.port}\n`); 56 | } 57 | 58 | main(process.argv.slice(2)); 59 | -------------------------------------------------------------------------------- /example/breakpoint.ts: -------------------------------------------------------------------------------- 1 | import { strict as assert } from 'node:assert'; 2 | import { type AddressInfo, createServer } from 'node:net'; 3 | import { MinecraftDebugSession, QuickJSDebugConnection } from '../src/index.js'; 4 | 5 | const Minecraft = {} as typeof import('@minecraft/server'); 6 | 7 | async function test(session: MinecraftDebugSession) { 8 | const topStack = await session.getTopStack(); 9 | assert.equal(topStack.fileName, 'main.js'); 10 | assert.equal(topStack.lineNumber, 12); 11 | const result = await topStack.evaluate( 12 | ({ blockId }) => { 13 | const permutation = Minecraft.BlockPermutation.resolve(blockId); 14 | return permutation.getTags(); 15 | }, 16 | { blockId: 'cobblestone' }, 17 | ); 18 | assert.deepEqual(result, ['stone']); 19 | process.stdout.write( 20 | await topStack.evaluate(() => { 21 | const player = [...Minecraft.world.getPlayers()][0]; 22 | const { location } = player; 23 | return `${player.name}(${location.x},${location.y},${location.z})`; 24 | }), 25 | ); 26 | process.stdout.write('\n'); 27 | await session.continue(); 28 | } 29 | 30 | function main([port]: string[]) { 31 | const server = createServer((socket) => { 32 | const conn = new QuickJSDebugConnection(socket); 33 | const session = new MinecraftDebugSession(conn); 34 | session.setBreakpoints('main.js', [{ line: 12 }]); 35 | session.resume(); 36 | session.on('stopped', (ev) => { 37 | if (ev.reason === 'breakpoint') { 38 | test(session) 39 | .catch((err) => { 40 | console.error(err); 41 | }) 42 | .finally(() => { 43 | conn.close(); 44 | }); 45 | } 46 | }); 47 | }); 48 | server.listen(port); 49 | const addr = server.address() as AddressInfo; 50 | process.stdout.write(`Please type '/script debugger connect :${addr.port}' in Minecraft\n`); 51 | } 52 | 53 | main(process.argv.slice(2)); 54 | -------------------------------------------------------------------------------- /src/lib/connection.ts: -------------------------------------------------------------------------------- 1 | import { Buffer } from 'node:buffer'; 2 | import EventEmitter from 'node:events'; 3 | import type { Socket } from 'node:net'; 4 | 5 | function addMessageListener(socket: Socket, onMessage: (buffer: Buffer) => void) { 6 | const chunks: Buffer[] = []; 7 | let bufferLength = 0; 8 | let state: 'content' | 'length' = 'length'; 9 | let triggerLength = 9; 10 | socket.on('data', (chunk) => { 11 | bufferLength += chunk.length; 12 | chunks.push(chunk); 13 | while (bufferLength >= triggerLength) { 14 | const bufferedChunk = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks); 15 | const triggerChunk = bufferedChunk.subarray(0, triggerLength); 16 | bufferLength -= triggerLength; 17 | chunks.splice(0, chunks.length, bufferedChunk.subarray(triggerLength)); 18 | switch (state) { 19 | case 'length': 20 | state = 'content'; 21 | triggerLength = parseInt(triggerChunk.toString(), 16); 22 | break; 23 | case 'content': 24 | onMessage(triggerChunk); 25 | state = 'length'; 26 | triggerLength = 9; 27 | break; 28 | } 29 | } 30 | }); 31 | } 32 | 33 | export interface DebugConnectionEvents { 34 | end: []; 35 | error: [error: unknown]; 36 | [key: `event:${string}`]: [DebuggeeEvent]; 37 | } 38 | 39 | export interface DebugConnection extends EventEmitter { 40 | close(): void; 41 | sendEnvelope(type: string, data?: object): void; 42 | sendRequest(command: string, args?: T): Promise; 43 | } 44 | 45 | export interface DebugEnvelope { 46 | version: number; 47 | type: string; 48 | } 49 | 50 | export interface DebuggerRequest { 51 | request_seq: number; 52 | command: string; 53 | args: unknown; 54 | } 55 | 56 | export interface DebuggeeEventEnvelope extends DebugEnvelope { 57 | type: 'event'; 58 | event: DebuggeeEvent; 59 | } 60 | 61 | export interface DebuggeeEvent { 62 | type: string; 63 | } 64 | 65 | export interface DebuggeeResponse extends DebugEnvelope { 66 | type: 'response'; 67 | request_seq: number; 68 | error?: string; 69 | body?: unknown; 70 | } 71 | 72 | export class QuickJSDebugConnection extends EventEmitter implements DebugConnection { 73 | socket: Socket; 74 | requestTimeout: number; 75 | requestVersion: number; 76 | requestSeq: number; 77 | requestReactions: Map void; reject: (error?: unknown) => void }>; 78 | constructor(socket: Socket) { 79 | super(); 80 | this.socket = socket; 81 | this.requestTimeout = 10000; 82 | this.requestVersion = 1; 83 | this.requestSeq = 1; 84 | this.requestReactions = new Map(); 85 | addMessageListener(socket, (message) => { 86 | this.handleMessage(message); 87 | }); 88 | socket.on('end', () => { 89 | this.emit('end'); 90 | const reactions = [...this.requestReactions.values()]; 91 | this.requestReactions.clear(); 92 | for (const { reject } of reactions) { 93 | reject(new Error('Protocol is closed')); 94 | } 95 | }); 96 | socket.on('error', (err) => this.emit('error', err)); 97 | } 98 | 99 | close() { 100 | this.socket.end(); 101 | } 102 | 103 | sendMessage(message: T) { 104 | const buffer = Buffer.from(`${JSON.stringify(message)}\n`); 105 | const lf = Buffer.from('\n'); 106 | const packet = Buffer.concat([Buffer.from(buffer.length.toString(16).padStart(8, '0')), lf, buffer]); 107 | this.socket.write(packet); 108 | } 109 | 110 | sendEnvelope(type: string, data?: object) { 111 | this.sendMessage({ 112 | version: this.requestVersion, 113 | type, 114 | ...data, 115 | } as DebugEnvelope); 116 | } 117 | 118 | sendRequestRaw(command: string, args?: object) { 119 | const { requestSeq } = this; 120 | this.requestSeq += 1; 121 | this.sendEnvelope('request', { 122 | request: { 123 | request_seq: requestSeq, 124 | command, 125 | args, 126 | } as DebuggerRequest, 127 | }); 128 | return requestSeq; 129 | } 130 | 131 | sendRequest(command: string, args?: T) { 132 | const requestSeq = this.sendRequestRaw(command, args); 133 | const timeoutError = new Error(`Request timeout ${this.requestTimeout}ms exceed.`); 134 | const { promise, resolve, reject } = Promise.withResolvers(); 135 | this.requestReactions.set(requestSeq, { resolve: resolve as (value: unknown) => void, reject }); 136 | const timeout = setTimeout(() => { 137 | reject(timeoutError); 138 | }, this.requestTimeout); 139 | return promise.finally(() => { 140 | clearTimeout(timeout); 141 | this.requestReactions.delete(requestSeq); 142 | }); 143 | } 144 | 145 | handleMessage(message: Buffer) { 146 | const json = JSON.parse(message.toString()) as DebugEnvelope; 147 | if (json.type === 'event') { 148 | const event = (json as DebuggeeEventEnvelope).event; 149 | this.emit(`event:${event.type}`, event); 150 | } else if (json.type === 'response') { 151 | const response = json as DebuggeeResponse; 152 | const reaction = this.requestReactions.get(response.request_seq); 153 | if (reaction) { 154 | this.requestReactions.delete(response.request_seq); 155 | if (response.error) { 156 | reaction.reject(new Error(response.error)); 157 | } else { 158 | reaction.resolve(response.body); 159 | } 160 | } 161 | } 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /src/lib/minecraft.ts: -------------------------------------------------------------------------------- 1 | import type EventEmitter from 'node:events'; 2 | import type { DebugConnection, DebuggeeEvent } from './connection.js'; 3 | import { 4 | type BreakpointInfo, 5 | type BreakpointStatus, 6 | QuickJSDebugSession, 7 | type QuickJSDebugSessionEvents, 8 | } from './session.js'; 9 | 10 | export enum ProtocolVersion { 11 | Unknown = 0, 12 | /** 13 | * Initial version 14 | */ 15 | Initial = 1, 16 | /** 17 | * Add targetModuleUuid to protocol event 18 | * @since Minecraft 1.21.10 19 | */ 20 | SupportTargetModuleUuid = 2, 21 | /** 22 | * Add array of plugins and target module ids to incoming protocol event 23 | * @since Minecraft 1.21.40 24 | */ 25 | SupportTargetSelection = 3, 26 | /** 27 | * MC can require a passcode to connect 28 | * @since Minecraft 1.21.50 29 | */ 30 | SupportPasscode = 4, 31 | /** 32 | * Debugger can take MC script profiler captures 33 | * @since Minecraft 1.21.50.25 34 | */ 35 | SupportProfilerCaptures = 5, 36 | /** 37 | * Breakpoints as request, MC can reject 38 | * @since Minecraft 1.21.130.24 39 | */ 40 | SupportBreakpointsAsRequest = 6, 41 | } 42 | 43 | export interface ProtocolInfo { 44 | version: number; 45 | targetModuleUuid?: string; 46 | passcode?: string; 47 | } 48 | 49 | export enum LogLevel { 50 | Verbose = 0, 51 | Info = 1, 52 | Warn = 2, 53 | Error = 3, 54 | Fatal = 4, 55 | } 56 | 57 | export interface LogEvent extends DebuggeeEvent { 58 | type: 'PrintEvent'; 59 | message: string; 60 | logLevel: LogLevel; 61 | } 62 | 63 | export interface ProtocolEvent extends DebuggeeEvent { 64 | type: 'ProtocolEvent'; 65 | version: number; 66 | } 67 | 68 | export interface ProtocolEventV3 extends ProtocolEvent { 69 | plugins: { 70 | name: string; 71 | module_uuid: string; 72 | }[]; 73 | } 74 | 75 | export interface ProtocolEventV4 extends ProtocolEventV3 { 76 | require_passcode?: boolean; 77 | } 78 | 79 | export interface ProfilerCaptureEvent { 80 | type: string; 81 | capture_base_path: string; 82 | capture_data: string; 83 | } 84 | 85 | export interface StatDataV1 { 86 | id: string; 87 | parent_id?: string; 88 | type?: string; 89 | label?: string; 90 | value?: string | number; 91 | } 92 | 93 | export interface StatDataModel { 94 | name: string; 95 | should_aggregate?: boolean; 96 | children?: StatDataModel[]; 97 | values?: number[]; 98 | } 99 | 100 | export interface StatMessageV1Event extends DebuggeeEvent { 101 | type: 'StatEvent'; 102 | stats: StatDataV1[]; 103 | } 104 | 105 | export interface StatMessageV2Event extends DebuggeeEvent { 106 | type: 'StatEvent2'; 107 | tick: number; 108 | stats: StatDataModel[]; 109 | } 110 | 111 | export interface StatTreeNode { 112 | name: string; 113 | label?: string; 114 | type?: string; 115 | updateTick?: number; 116 | aggregated?: boolean; 117 | values?: (string | number)[]; 118 | children?: StatTree; 119 | } 120 | 121 | export type StatTree = Record; 122 | 123 | export interface StatEvent { 124 | stat: StatTree; 125 | tick: number; 126 | } 127 | 128 | function mergeStatTreeNodeV1(target: StatTree, updated: StatDataV1[], pathCache: Map) { 129 | for (const statData of updated) { 130 | const path: string[] = []; 131 | if (statData.parent_id) { 132 | const cachedPath = pathCache.get(statData.parent_id); 133 | if (cachedPath) { 134 | path.push(...cachedPath); 135 | } else { 136 | continue; 137 | } 138 | } 139 | let currentTarget = target; 140 | for (const part of path) { 141 | const newTargetOwner = currentTarget[part]; 142 | if (!newTargetOwner) { 143 | throw new Error(`Cannot find node in stat tree: ${path.join('->')}`); 144 | } 145 | if (!newTargetOwner.children) { 146 | newTargetOwner.children = {}; 147 | } 148 | currentTarget = newTargetOwner.children; 149 | } 150 | if (!pathCache.has(statData.id)) { 151 | pathCache.set(statData.id, [...path, statData.id]); 152 | } 153 | let existed = currentTarget[statData.id]; 154 | if (!existed) { 155 | existed = currentTarget[statData.id] = { name: statData.id }; 156 | } 157 | existed.label = statData.label; 158 | existed.type = statData.type; 159 | if (statData.value !== undefined) { 160 | existed.values = [statData.value]; 161 | } 162 | } 163 | return target; 164 | } 165 | 166 | function mergeStatTreeNodeV2(target: StatTree, updated: StatDataModel[], tick: number) { 167 | for (const statData of updated) { 168 | let existed = target[statData.name]; 169 | if (!existed) { 170 | existed = target[statData.name] = { name: statData.name }; 171 | } 172 | existed.updateTick = tick; 173 | if (statData.values !== undefined) { 174 | existed.values = statData.values; 175 | } 176 | if (statData.values !== undefined) { 177 | existed.aggregated = statData.should_aggregate; 178 | } 179 | if (statData.children) { 180 | let children = existed.children; 181 | if (!children) { 182 | children = existed.children = {}; 183 | } 184 | if (statData.should_aggregate === true) { 185 | const newKeys = new Set(statData.children.map((e) => e.name)); 186 | const removingKeys = Object.keys(children).filter((e) => !newKeys.has(e)); 187 | for (const key of removingKeys) { 188 | delete children[key]; 189 | } 190 | } 191 | mergeStatTreeNodeV2(children, statData.children, tick); 192 | } 193 | } 194 | return target; 195 | } 196 | 197 | export interface MinecraftDebugSessionEvents extends QuickJSDebugSessionEvents { 198 | log: [event: LogEvent]; 199 | protocol: [event: ProtocolEvent]; 200 | stat: [event: StatEvent]; 201 | profilerCapture: [event: ProfilerCaptureEvent]; 202 | } 203 | 204 | type ExtendEventMap> = C extends { 205 | new (...args: infer Args): infer Inst; 206 | } 207 | ? Inst extends EventEmitter 208 | ? { new (...args: Args): Inst & EventEmitter } 209 | : C 210 | : C; 211 | 212 | export class MinecraftDebugSession extends (QuickJSDebugSession as ExtendEventMap< 213 | typeof QuickJSDebugSession, 214 | MinecraftDebugSessionEvents 215 | >) { 216 | protocolVersion = ProtocolVersion.Unknown; 217 | protocolInfo?: ProtocolInfo; 218 | currentStat?: StatTree; 219 | currentTick = 0; 220 | constructor(connection: DebugConnection, protocolInfo?: ProtocolInfo) { 221 | super(connection); 222 | if (protocolInfo) { 223 | this.setProtocolInfo(protocolInfo); 224 | } 225 | connection.on('event:PrintEvent', (ev) => { 226 | this.emit('log', ev as LogEvent); 227 | }); 228 | connection.on('event:ProtocolEvent', (ev) => { 229 | const protocolEvent = ev as ProtocolEvent; 230 | this.protocolVersion = protocolEvent.version; 231 | this.emit('protocol', protocolEvent); 232 | if (this.protocolInfo) { 233 | const protocolInfo = this.protocolInfo; 234 | this.connection.sendEnvelope('protocol', { 235 | version: protocolInfo.version, 236 | target_module_uuid: protocolInfo.targetModuleUuid, 237 | passcode: protocolInfo.passcode, 238 | }); 239 | } 240 | }); 241 | const v1PathCache = new Map(); 242 | connection.on('event:StatEvent', (ev) => { 243 | const statEvent = ev as StatMessageV1Event; 244 | if (!this.currentStat) this.currentStat = {}; 245 | const stat = mergeStatTreeNodeV1(this.currentStat, statEvent.stats, v1PathCache); 246 | this.emit('stat', { stat, tick: this.currentTick }); 247 | }); 248 | connection.on('event:StatEvent2', (ev) => { 249 | const statEvent = ev as StatMessageV2Event; 250 | if (!this.currentStat) this.currentStat = {}; 251 | const stat = mergeStatTreeNodeV2(this.currentStat, statEvent.stats, statEvent.tick); 252 | this.currentTick = statEvent.tick; 253 | this.emit('stat', { stat, tick: statEvent.tick }); 254 | }); 255 | connection.on('event:ProfilerCapture', (ev) => { 256 | this.emit('profilerCapture', ev as ProfilerCaptureEvent); 257 | }); 258 | } 259 | 260 | setProtocolInfo(protocolInfo: ProtocolInfo) { 261 | this.protocolInfo = protocolInfo; 262 | } 263 | 264 | setBreakpoints(fileName: string, breakpoints: BreakpointInfo[]) { 265 | if (this.protocolVersion >= ProtocolVersion.SupportBreakpointsAsRequest) { 266 | const breakpointLines = breakpoints.map((e) => e.line); 267 | return this.setBreakpointLines(fileName, breakpointLines); 268 | } else { 269 | super.setBreakpoints(fileName, breakpoints); 270 | const status: BreakpointStatus[] = breakpoints.map(() => ({ verified: true })); 271 | return status; 272 | } 273 | } 274 | 275 | sendMinecraftCommand(command: string, dimensionType?: string) { 276 | if (this.protocolVersion >= ProtocolVersion.SupportProfilerCaptures) { 277 | this.connection.sendEnvelope('minecraftCommand', { 278 | command: { 279 | command, 280 | dimension_type: dimensionType ?? 'overworld', 281 | }, 282 | }); 283 | } else if (this.protocolVersion >= ProtocolVersion.SupportPasscode) { 284 | this.connection.sendEnvelope('minecraftCommand', { 285 | command, 286 | dimension_type: dimensionType ?? 'overworld', 287 | }); 288 | } else { 289 | throw new Error(`Client not supported`); 290 | } 291 | } 292 | 293 | sendStartProfiler(targetModuleUuid?: string) { 294 | if (this.protocolVersion < ProtocolVersion.SupportProfilerCaptures) { 295 | throw new Error(`Client not supported`); 296 | } 297 | const argTargetModuleUuid = targetModuleUuid ?? this.protocolInfo?.targetModuleUuid; 298 | if (!argTargetModuleUuid) { 299 | throw new Error(`Expect target module uuid`); 300 | } 301 | this.connection.sendEnvelope('startProfiler', { 302 | profiler: { 303 | target_module_uuid: argTargetModuleUuid, 304 | }, 305 | }); 306 | } 307 | 308 | sendStopProfiler(capturesPath: string, targetModuleUuid?: string) { 309 | if (this.protocolVersion < ProtocolVersion.SupportProfilerCaptures) { 310 | throw new Error(`Client not supported`); 311 | } 312 | const argTargetModuleUuid = targetModuleUuid ?? this.protocolInfo?.targetModuleUuid; 313 | if (!argTargetModuleUuid) { 314 | throw new Error(`Expect target module uuid`); 315 | } 316 | this.connection.sendEnvelope('stopProfiler', { 317 | profiler: { 318 | captures_path: capturesPath, 319 | target_module_uuid: argTargetModuleUuid, 320 | }, 321 | }); 322 | } 323 | } 324 | -------------------------------------------------------------------------------- /src/lib/session.ts: -------------------------------------------------------------------------------- 1 | import EventEmitter from 'node:events'; 2 | import type { DebugProtocol } from '@vscode/debugprotocol'; 3 | import type { DebugConnection, DebuggeeEvent } from './connection.js'; 4 | 5 | function generateFunctionCode( 6 | f: ((args: T) => unknown) | string, 7 | args: T | undefined, 8 | type: 'eval' | 'function', 9 | ) { 10 | if (typeof f === 'function') { 11 | const serializedArgs = JSON.stringify(args); 12 | if (type === 'eval') { 13 | return `(${String(f)})(${serializedArgs})`; 14 | } else { 15 | const serializedCode = JSON.stringify(`return (${String(f)})(arguments[0])`); 16 | return `(new Function(${serializedCode}))(${serializedArgs})`; 17 | } 18 | } 19 | return String(f); 20 | } 21 | 22 | export interface StackFrameInfo { 23 | id: number; 24 | name: string; 25 | filename: string; 26 | line: number; 27 | column: number; 28 | } 29 | 30 | export class QuickJSStackFrame { 31 | session: QuickJSDebugSession; 32 | id: number; 33 | name: string; 34 | fileName: string; 35 | lineNumber: number; 36 | constructor(session: QuickJSDebugSession, frameInfo: StackFrameInfo) { 37 | this.session = session; 38 | this.id = frameInfo.id; 39 | this.name = frameInfo.name; 40 | this.fileName = frameInfo.filename; 41 | this.lineNumber = frameInfo.line; 42 | } 43 | 44 | async evaluateExpression(expression: string) { 45 | return this.session.evaluate(this.id, expression); 46 | } 47 | 48 | async evaluateHandle(f: (args: T) => R, args?: T): Promise> { 49 | return this.evaluateExpression(generateFunctionCode(f, args, 'eval')); 50 | } 51 | 52 | async evaluateHandleGlobal(f: (args: T) => R, args?: T): Promise> { 53 | return this.evaluateExpression(generateFunctionCode(f, args, 'function')); 54 | } 55 | 56 | async evaluate(f: (args: T) => R, args?: T): Promise { 57 | return (await this.evaluateHandle(f, args)).inspect(); 58 | } 59 | 60 | async evaluateGlobal(f: (args: T) => R, args?: T): Promise { 61 | return (await this.evaluateHandleGlobal(f, args)).inspect(); 62 | } 63 | 64 | async getScopes() { 65 | return this.session.getScopes(this.id); 66 | } 67 | } 68 | 69 | export interface InspectOptions { 70 | maxDepth?: number; 71 | inspectProto?: boolean; 72 | } 73 | 74 | interface InspectInternalOptions { 75 | inspectProto?: boolean; 76 | referenceMap: Map; 77 | } 78 | 79 | const QuickJSRef = Symbol('QuickJSRef'); 80 | interface WithQuickJSRef { 81 | [QuickJSRef]: number; 82 | } 83 | 84 | export class QuickJSHandle { 85 | session: QuickJSDebugSession; 86 | name: string; 87 | ref: number; 88 | primitive?: boolean; 89 | primitiveValue?: unknown; 90 | type?: string; 91 | isArray?: boolean; 92 | indexedCount?: number; 93 | valueAsString?: string; 94 | constructor(session: QuickJSDebugSession, reference: number) { 95 | this.session = session; 96 | this.ref = reference; 97 | this.name = `#${reference}`; 98 | } 99 | 100 | async getProperties(options?: Omit) { 101 | return this.session.inspectVariable(this.ref, options); 102 | } 103 | 104 | async inspect(options?: InspectOptions) { 105 | const referenceMap = new Map(); 106 | const { maxDepth, inspectProto } = options ?? {}; 107 | return this.inspectInternal(maxDepth ?? 16, { 108 | referenceMap, 109 | inspectProto, 110 | }) as Promise; 111 | } 112 | 113 | private async inspectInternal(depth: number, options: InspectInternalOptions) { 114 | const { referenceMap, inspectProto } = options; 115 | if (this.primitive) { 116 | return this.primitiveValue; 117 | } 118 | if (referenceMap.has(this.ref)) { 119 | return referenceMap.get(this.ref); 120 | } 121 | if (this.type === 'object') { 122 | if (depth > 0) { 123 | let result: object; 124 | let getPropOptions: Omit | undefined; 125 | let properties: QuickJSVariable[]; 126 | if (this.isArray) { 127 | result = []; 128 | getPropOptions = { 129 | filter: 'indexed', 130 | start: 0, 131 | count: this.indexedCount, 132 | }; 133 | } else { 134 | result = {}; 135 | } 136 | referenceMap.set(this.ref, result); 137 | try { 138 | properties = await this.getProperties(getPropOptions); 139 | } catch (_) { 140 | properties = []; 141 | } 142 | await Promise.all( 143 | properties.map(async (property) => { 144 | if (property.name === '__proto__') { 145 | if (inspectProto) { 146 | const proto = await property.inspectInternal(depth - 1, options); 147 | if (typeof proto === 'object') { 148 | Object.setPrototypeOf(result, proto); 149 | } 150 | } 151 | } else { 152 | (result as Record)[property.name] = await property.inspectInternal( 153 | depth - 1, 154 | options, 155 | ); 156 | } 157 | }), 158 | ); 159 | (result as WithQuickJSRef)[QuickJSRef] = this.ref; 160 | return result; 161 | } 162 | } 163 | return String(this); 164 | } 165 | 166 | toString() { 167 | return this.valueAsString ?? String(this.primitiveValue); 168 | } 169 | 170 | valueOf() { 171 | return this.primitiveValue ?? this.valueAsString; 172 | } 173 | 174 | equals(x: QuickJSHandle | null | undefined) { 175 | if (!x) return false; 176 | return this.ref === x.ref; 177 | } 178 | } 179 | 180 | export interface ScopeInfo { 181 | name: string; 182 | reference: number; 183 | expensive: boolean; 184 | } 185 | 186 | export class QuickJSScope extends QuickJSHandle> { 187 | expensive: boolean; 188 | constructor(session: QuickJSDebugSession, scopeInfo: ScopeInfo) { 189 | super(session, scopeInfo.reference); 190 | this.name = scopeInfo.name; 191 | this.type = 'object'; 192 | this.primitive = false; 193 | this.isArray = false; 194 | this.expensive = scopeInfo.expensive; 195 | } 196 | 197 | toString() { 198 | return `[scope ${this.name}]`; 199 | } 200 | } 201 | 202 | export interface VariableInfo { 203 | name: string; 204 | value: string; 205 | type?: string; 206 | variablesReference: number; 207 | indexedVariables?: number; 208 | } 209 | 210 | export class QuickJSVariable extends QuickJSHandle { 211 | constructor(session: QuickJSDebugSession, variableInfo: VariableInfo) { 212 | super(session, variableInfo.variablesReference); 213 | this.name = variableInfo.name; 214 | this.type = variableInfo.type; 215 | this.primitive = true; 216 | this.isArray = false; 217 | switch (this.type) { 218 | case 'string': 219 | this.primitiveValue = variableInfo.value; 220 | break; 221 | case 'integer': 222 | this.primitiveValue = parseInt(variableInfo.value, 10); 223 | break; 224 | case 'float': 225 | this.primitiveValue = parseFloat(variableInfo.value); 226 | break; 227 | case 'boolean': 228 | this.primitiveValue = variableInfo.value === 'true'; 229 | break; 230 | case 'null': 231 | this.primitiveValue = null; 232 | break; 233 | case 'undefined': 234 | this.primitiveValue = undefined; 235 | break; 236 | case 'object': 237 | case 'function': 238 | this.primitive = false; 239 | this.valueAsString = variableInfo.value; 240 | this.isArray = variableInfo.indexedVariables !== undefined; 241 | this.indexedCount = variableInfo.indexedVariables; 242 | break; 243 | default: 244 | this.primitive = false; 245 | this.valueAsString = variableInfo.value; 246 | break; 247 | } 248 | } 249 | } 250 | 251 | export interface BreakpointInfo { 252 | line: number; 253 | column?: number; 254 | } 255 | 256 | export interface BreakpointStatus { 257 | verified: boolean; 258 | } 259 | 260 | export interface StoppedEvent extends DebuggeeEvent { 261 | type: 'StoppedEvent'; 262 | thread: number; 263 | reason: 'entry' | 'exception' | 'breakpoint' | 'pause' | 'step' | 'stepIn' | 'stepOut'; 264 | } 265 | 266 | export interface ContextEvent { 267 | type: 'ThreadEvent'; 268 | thread: number; 269 | reason: 'new' | 'exited'; 270 | } 271 | 272 | export type EvaluateContext = 'watch' | 'repl' | 'hover' | 'clipboard' | 'variables'; 273 | 274 | export interface QuickJSDebugSessionEvents { 275 | stopped: [event: StoppedEvent]; 276 | context: [event: ContextEvent]; 277 | end: []; 278 | } 279 | 280 | export class QuickJSDebugSession extends EventEmitter { 281 | connection: DebugConnection; 282 | constructor(connection: DebugConnection) { 283 | super(); 284 | this.connection = connection; 285 | connection.on('event:StoppedEvent', (ev) => { 286 | this.emit('stopped', ev as StoppedEvent); 287 | }); 288 | connection.on('event:ThreadEvent', (ev) => { 289 | this.emit('context', ev as ContextEvent); 290 | }); 291 | connection.on('event:terminated', () => { 292 | this.emit('end'); 293 | }); 294 | } 295 | 296 | async continue() { 297 | return this.connection.sendRequest('continue'); 298 | } 299 | 300 | async pause() { 301 | return this.connection.sendRequest('pause'); 302 | } 303 | 304 | async stepNext() { 305 | return this.connection.sendRequest('next'); 306 | } 307 | 308 | async stepIn() { 309 | return this.connection.sendRequest('stepIn'); 310 | } 311 | 312 | async stepOut() { 313 | return this.connection.sendRequest('stepOut'); 314 | } 315 | 316 | async evaluate(frameId: number, expression: string, context?: EvaluateContext) { 317 | const res = await this.connection.sendRequest('evaluate', { 318 | frameId, 319 | context: context ?? 'watch', 320 | expression, 321 | } as DebugProtocol.EvaluateArguments); 322 | return new QuickJSVariable(this, { ...res, name: 'result', value: res.result }); 323 | } 324 | 325 | async traceStack() { 326 | const res = await this.connection.sendRequest('stackTrace'); 327 | return res.map((e) => new QuickJSStackFrame(this, e)); 328 | } 329 | 330 | async getTopStack() { 331 | return (await this.traceStack())[0]; 332 | } 333 | 334 | async getScopes(frameId: number) { 335 | const res = await this.connection.sendRequest('scopes', { 336 | frameId, 337 | } as DebugProtocol.ScopesArguments); 338 | return res.map((e) => new QuickJSScope(this, e)); 339 | } 340 | 341 | async inspectVariable( 342 | reference: number, 343 | options?: Omit, 344 | ) { 345 | const res = await this.connection.sendRequest('variables', { 346 | variablesReference: reference, 347 | ...options, 348 | } as DebugProtocol.VariablesArguments); 349 | return res.map((e) => new QuickJSVariable(this, e)); 350 | } 351 | 352 | resume() { 353 | this.connection.sendEnvelope('resume'); 354 | } 355 | 356 | setBreakpoints(fileName: string, breakpoints: BreakpointInfo[]) { 357 | this.connection.sendEnvelope('breakpoints', { 358 | breakpoints: { 359 | path: fileName, 360 | breakpoints: breakpoints.length ? breakpoints : undefined, 361 | }, 362 | }); 363 | } 364 | 365 | async setBreakpointLines(fileName: string, breakpointsLines: number[]) { 366 | const status = await this.connection.sendRequest<{ 367 | breakpoints: BreakpointStatus[]; 368 | }>('setBreakpoints', { 369 | path: fileName, 370 | breakpoints: breakpointsLines, 371 | }); 372 | return status.breakpoints; 373 | } 374 | 375 | setStopOnException(enabled: boolean) { 376 | this.connection.sendEnvelope('stopOnException', { 377 | stopOnException: enabled, 378 | }); 379 | } 380 | } 381 | -------------------------------------------------------------------------------- /src/repl.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | import EventEmitter from 'node:events'; 4 | import { type AddressInfo, createServer, type Server, type Socket } from 'node:net'; 5 | import { clearLine, cursorTo } from 'node:readline'; 6 | import { type REPLServer, start as startRepl } from 'node:repl'; 7 | import { format, inspect } from 'node:util'; 8 | import type { Context } from 'node:vm'; 9 | import { 10 | MinecraftDebugSession, 11 | QuickJSDebugConnection, 12 | type QuickJSHandle, 13 | type QuickJSScope, 14 | type QuickJSStackFrame, 15 | } from './index.js'; 16 | import type { ProtocolInfo, StatTree } from './lib/minecraft.js'; 17 | 18 | function dumpStatTree(tree: StatTree) { 19 | const ret: string[] = []; 20 | for (const node of Object.values(tree)) { 21 | if (!node) continue; 22 | if (node.values) { 23 | ret.push(`- ${node.name}: ${node.values.join(', ')}`); 24 | } else { 25 | ret.push(`- ${node.name}`); 26 | } 27 | if (node.children) { 28 | const childDump = dumpStatTree(node.children).map((l) => ` ${l}`); 29 | ret.push(...childDump); 30 | } 31 | } 32 | return ret; 33 | } 34 | 35 | class MCQuickJSDebugServer extends EventEmitter { 36 | server: Server; 37 | connection: QuickJSDebugConnection | null = null; 38 | breakpointMap = new Map(); 39 | logLevel = 0; 40 | socket: Socket | null = null; 41 | session: MinecraftDebugSession | null = null; 42 | paused = false; 43 | stacks: QuickJSStackFrame[] = []; 44 | stackIndex = 0; 45 | currentStack: QuickJSStackFrame | null = null; 46 | protocolInfo: ProtocolInfo = { version: 1 }; 47 | constructor(port: number) { 48 | super(); 49 | this.server = createServer((socket) => { 50 | this.onConnection(socket); 51 | }); 52 | this.server.listen(port); 53 | } 54 | 55 | reset() { 56 | if (this.connection) { 57 | this.connection.close(); 58 | } 59 | this.socket = null; 60 | this.connection = null; 61 | this.session = null; 62 | this.paused = false; 63 | this.stacks = []; 64 | this.stackIndex = 0; 65 | this.currentStack = null; 66 | } 67 | 68 | onConnection(socket: Socket) { 69 | if (this.connection != null) { 70 | socket.end(); 71 | return; 72 | } 73 | const addressInfo = socket.address() as AddressInfo; 74 | const address = `${addressInfo.address}:${addressInfo.port}`; 75 | this.socket = socket; 76 | this.connection = new QuickJSDebugConnection(socket); 77 | this.session = new MinecraftDebugSession(this.connection, this.protocolInfo); 78 | this.paused = false; 79 | this.emit('online', address); 80 | this.syncBreakpoints(); 81 | this.session.resume(); 82 | this.session.on('stopped', (ev) => { 83 | this.paused = true; 84 | this.emit('stopped', ev); 85 | if (ev.reason === 'breakpoint') { 86 | this.emit('breakpointHit'); 87 | } 88 | this.updateStateAsync(); 89 | }); 90 | this.session.on('log', (ev) => { 91 | if ((ev.logLevel as number) < this.logLevel) return; 92 | this.emit('log', ev); 93 | }); 94 | this.session.on('end', () => { 95 | this.connection?.close(); 96 | }); 97 | this.connection.on('end', () => { 98 | this.connection = null; 99 | this.emit('offline', address); 100 | this.reset(); 101 | this.emit('update'); 102 | }); 103 | } 104 | 105 | get port() { 106 | return (this.server.address() as AddressInfo).port; 107 | } 108 | 109 | wrapAsync

(asyncFunc: (...args: P) => Promise) { 110 | return (...args: P) => { 111 | asyncFunc(...args).catch((err) => this.emit('error', err)); 112 | }; 113 | } 114 | 115 | updateStateAsync() { 116 | this.updateState().catch((err) => this.emit('error', err)); 117 | } 118 | 119 | async updateState() { 120 | if (this.session) { 121 | this.stacks = await this.session.traceStack(); 122 | const stackIndex = this.stackIndex >= 0 ? this.stackIndex : this.stacks.length + this.stackIndex; 123 | this.currentStack = this.stacks[Math.max(Math.min(stackIndex, this.stacks.length - 1), 0)]; 124 | this.emit('update'); 125 | return; 126 | } 127 | throw new Error('Debuggee is offline'); 128 | } 129 | 130 | async evaluate(expression: string) { 131 | if (this.currentStack) { 132 | const ref = await this.currentStack.evaluateExpression(expression); 133 | await this.updateState(); 134 | return ref; 135 | } 136 | throw new Error('Debuggee is offline'); 137 | } 138 | 139 | async dumpScope() { 140 | if (this.currentStack) { 141 | return this.currentStack.getScopes(); 142 | } 143 | throw new Error('Debuggee is offline'); 144 | } 145 | 146 | async dumpReference(ref: number, range?: readonly [number, number]) { 147 | if (this.session) { 148 | if (range) { 149 | return await this.session.inspectVariable(ref, { 150 | filter: 'indexed', 151 | start: range[0], 152 | count: range[1] - range[0] + 1, 153 | }); 154 | } 155 | return await this.session.inspectVariable(ref); 156 | } 157 | throw new Error('Debuggee is offline'); 158 | } 159 | 160 | syncBreakpoints() { 161 | if (this.session) { 162 | const session = this.session; 163 | for (const [fileName, breakpoints] of this.breakpointMap) { 164 | session.setBreakpoints(fileName, breakpoints); 165 | } 166 | } 167 | } 168 | 169 | addBreakpoint(lineNumber: number, fileName?: string) { 170 | const fn = fileName ?? this.currentStack?.fileName ?? ''; 171 | if (!fn) { 172 | throw new Error('Invalid file name or not specified'); 173 | } 174 | const breakpoints = this.breakpointMap.get(fn); 175 | if (breakpoints) { 176 | breakpoints.push({ line: lineNumber }); 177 | breakpoints.sort(); 178 | } else { 179 | this.breakpointMap.set(fn, [{ line: lineNumber }]); 180 | } 181 | this.syncBreakpoints(); 182 | return true; 183 | } 184 | 185 | removeBreakpoint(lineNumber: number, fileName?: string) { 186 | const fn = fileName ?? this.currentStack?.fileName ?? ''; 187 | if (!fn) { 188 | throw new Error('Invalid file name or not specified'); 189 | } 190 | const breakpoints = this.breakpointMap.get(fn); 191 | if (breakpoints) { 192 | const index = breakpoints.findIndex((e) => e.line === lineNumber); 193 | if (index >= 0) { 194 | breakpoints.splice(index, 1); 195 | this.syncBreakpoints(); 196 | return true; 197 | } 198 | } 199 | return false; 200 | } 201 | 202 | async executeCommand(command: string) { 203 | if (this.connection && this.session) { 204 | this.paused = false; 205 | this.emit('update'); 206 | switch (command.toLowerCase()) { 207 | case 'resume': 208 | this.session.resume(); 209 | break; 210 | case 'pause': 211 | await this.session.pause(); 212 | break; 213 | case 'continue': 214 | await this.session.continue(); 215 | break; 216 | case 'stepin': 217 | case 'step in': 218 | await this.session.stepIn(); 219 | break; 220 | case 'stepout': 221 | case 'step out': 222 | await this.session.stepOut(); 223 | break; 224 | case 'step': 225 | case 'next': 226 | case 'stepnext': 227 | case 'step next': 228 | await this.session.stepNext(); 229 | break; 230 | default: 231 | throw new Error(`Unknown command: ${command}`); 232 | } 233 | return; 234 | } 235 | throw new Error('Debuggee is offline'); 236 | } 237 | 238 | async import(useRequire: boolean, module: string, alias?: string) { 239 | if (this.session) { 240 | const moduleCode = JSON.stringify(module); 241 | const aliasCode = JSON.stringify(alias ?? module); 242 | const stacks = await this.session.traceStack(); 243 | const rootStack = stacks[stacks.length - 1]; 244 | if (useRequire) { 245 | await rootStack.evaluateExpression(`((m)=>globalThis[${aliasCode}]=m)(require(${moduleCode}))`); 246 | } else { 247 | await rootStack.evaluateExpression(`import(${moduleCode}).then((m)=>globalThis[${aliasCode}]=m)`); 248 | } 249 | return; 250 | } 251 | throw new Error('Debuggee is offline'); 252 | } 253 | 254 | dumpStatMessage() { 255 | const stat = this.session?.currentStat; 256 | if (stat) { 257 | return dumpStatTree(stat).join('\n'); 258 | } 259 | return null; 260 | } 261 | } 262 | 263 | function inspectHandle(handle: QuickJSHandle) { 264 | let refStr = 'ref'; 265 | if (handle.isArray && handle.indexedCount !== undefined) { 266 | refStr = `indexed 0..${handle.indexedCount - 1}`; 267 | } 268 | return `${handle.type} ${handle.name} <${refStr} *${handle.ref}> ${String(handle).replace(/\n/g, ' ')}`; 269 | } 270 | 271 | const LOG_LEVEL = ['debug', 'info', 'warn', 'error', 'silent']; 272 | 273 | const integerRegex = /^\d+$/; 274 | const breakpointRegex = /^(?:(.+)\s+)?([+-])?(\d+)$/; 275 | const referenceLocatorRegex = /^(\d+)(?:\s+(\d+)\.\.(\d+))?$/; 276 | const importRegex = /^(\S+?)(?:\s+as\s+(\w+))?$/; 277 | const inspectMethods = [ 278 | ['js', '[Default] Inspect recursively but cost more time'], 279 | ['handle', 'Only show references of properties'], 280 | ]; 281 | class DebuggerReplServer { 282 | repl: REPLServer; 283 | server: MCQuickJSDebugServer; 284 | acceptUserInput: boolean; 285 | recentCommand: string; 286 | inspectMethod: string; 287 | constructor(port: number) { 288 | this.repl = startRepl({ 289 | eval: (cmd, context, file, callback) => { 290 | this.doEval(cmd, context, file, callback); 291 | }, 292 | }); 293 | this.server = new MCQuickJSDebugServer(port); 294 | this.acceptUserInput = true; 295 | this.recentCommand = ''; 296 | this.inspectMethod = 'js'; 297 | this.defineDefaultCommands(); 298 | this.repl.on('exit', () => { 299 | this.server.reset(); 300 | }); 301 | this.server 302 | .on('online', (address) => { 303 | this.printLine(`Connection established: ${address}.\nType ".help" for more information.`, true); 304 | this.updatePrompt(); 305 | if (this.acceptUserInput) { 306 | this.repl.displayPrompt(true); 307 | } 308 | }) 309 | .on('offline', (address) => { 310 | this.printLine(`Connection disconnected: ${address}.`, true); 311 | this.showOfflinePrompt(); 312 | this.updatePrompt(); 313 | if (this.acceptUserInput) { 314 | this.repl.displayPrompt(true); 315 | } 316 | }) 317 | .on('update', () => { 318 | this.updatePrompt(); 319 | if (this.acceptUserInput) { 320 | this.repl.displayPrompt(true); 321 | } 322 | }) 323 | .on('log', ({ message, logLevel }) => { 324 | if (this.repl.editorMode) return; 325 | const levelStr = LOG_LEVEL[logLevel as number]; 326 | this.printLine(`[${levelStr}] ${message}`, true); 327 | }) 328 | .on('error', (err) => { 329 | if (this.repl.editorMode) return; 330 | this.printLine(format('[Debugger] %s', err), true); 331 | }); 332 | this.updatePrompt(); 333 | this.showOfflinePrompt(); 334 | } 335 | 336 | printLine(str: string, rewriteLine?: boolean) { 337 | if (rewriteLine) { 338 | cursorTo(this.repl.output, 0); 339 | clearLine(this.repl.output, 0); 340 | } 341 | this.repl.output.write(`${str}\n`); 342 | if (this.acceptUserInput) { 343 | this.repl.displayPrompt(true); 344 | } 345 | } 346 | 347 | showOfflinePrompt() { 348 | this.printLine(`Waiting for Debuggee to connect..... port:${this.server.port}`, true); 349 | } 350 | 351 | updatePrompt() { 352 | let prompt = '> '; 353 | if (this.server.session) { 354 | if (this.server.paused) { 355 | const stack = this.server.currentStack; 356 | if (this.recentCommand) { 357 | prompt = `${this.recentCommand} ${prompt}`; 358 | } 359 | if (stack) { 360 | const fileName = stack.fileName.slice(-16); 361 | prompt = `[${fileName}:${stack.lineNumber}] ${prompt}`; 362 | } 363 | } else { 364 | prompt = `[Running] Pause ${prompt}`; 365 | } 366 | } else { 367 | prompt = `[Offline] ${prompt}`; 368 | } 369 | this.repl.setPrompt(prompt); 370 | } 371 | 372 | printStack() { 373 | if (this.server.currentStack) { 374 | const lines = this.server.stacks.map((stack, index, arr) => { 375 | const currectFlag = stack === this.server.currentStack; 376 | return `${currectFlag ? '*' : ' '} ${arr.length - index} ${stack.fileName}:${stack.lineNumber}`; 377 | }); 378 | this.printLine(lines.join('\n'), true); 379 | } 380 | } 381 | 382 | printBreakpoints() { 383 | const lines = []; 384 | for (const [fileName, breakpoints] of this.server.breakpointMap) { 385 | for (const { line } of breakpoints) { 386 | lines.push(`${fileName}:${line}`); 387 | } 388 | } 389 | if (!lines.length) { 390 | lines.push('Empty'); 391 | } 392 | this.printLine(lines.join('\n'), true); 393 | } 394 | 395 | parseBreakpoint(str: string) { 396 | const match = breakpointRegex.exec(str); 397 | if (match) { 398 | const { currentStack } = this.server; 399 | if (currentStack) { 400 | let fileName = match[1]; 401 | const offset = match[2]; 402 | let lineNumber = Number(match[3]); 403 | if (offset === '+') { 404 | lineNumber += currentStack.lineNumber; 405 | } else if (offset === '-') { 406 | lineNumber -= currentStack.lineNumber; 407 | } 408 | if (!fileName) { 409 | fileName = currentStack.fileName; 410 | } 411 | return { fileName, lineNumber }; 412 | } 413 | } 414 | return null; 415 | } 416 | 417 | async inspect(handle: QuickJSHandle) { 418 | if (this.inspectMethod === 'handle') { 419 | return inspectHandle(handle); 420 | } 421 | return inspect(await handle.inspect(), { colors: true }); 422 | } 423 | 424 | defineDefaultCommands() { 425 | const executeServerQuickCommand = async (command: string) => { 426 | this.recentCommand = command; 427 | await this.server.executeCommand(command); 428 | }; 429 | this.repl.defineCommand('disconnect', { 430 | help: 'Disconnect from Debuggee', 431 | action: () => { 432 | this.server.reset(); 433 | this.repl.displayPrompt(true); 434 | }, 435 | }); 436 | this.repl.defineCommand('stack', { 437 | help: 'Print stacks or switch current stack frame', 438 | action: this.server.wrapAsync(async (args) => { 439 | if (integerRegex.test(args)) { 440 | this.server.stackIndex = -Number.parseInt(args, 10); 441 | await this.server.updateState(); 442 | } 443 | this.printStack(); 444 | }), 445 | }); 446 | this.repl.defineCommand('breakpoints', { 447 | help: 'Show breakpoints', 448 | action: () => { 449 | this.printBreakpoints(); 450 | }, 451 | }); 452 | this.repl.defineCommand('on', { 453 | help: 'Add breakpoint', 454 | action: (args) => { 455 | const parsed = this.parseBreakpoint(args); 456 | if (parsed) { 457 | this.server.addBreakpoint(parsed.lineNumber, parsed.fileName); 458 | this.printLine(`Breakpoint ${parsed.fileName}:${parsed.lineNumber} added`); 459 | } else { 460 | this.printLine(`Invalid breakpoint: ${args}`); 461 | } 462 | }, 463 | }); 464 | this.repl.defineCommand('off', { 465 | help: 'Remove breakpoint', 466 | action: (args) => { 467 | const parsed = this.parseBreakpoint(args); 468 | if (parsed) { 469 | this.server.removeBreakpoint(parsed.lineNumber, parsed.fileName); 470 | this.printLine(`Breakpoint ${parsed.fileName}:${parsed.lineNumber} removed`); 471 | } else { 472 | this.printLine(`Invalid breakpoint: ${args}`); 473 | } 474 | }, 475 | }); 476 | this.repl.defineCommand('scope', { 477 | help: 'Dump scope', 478 | action: this.server.wrapAsync(async (args) => { 479 | const scopes = await this.server.dumpScope(); 480 | if (integerRegex.test(args)) { 481 | const scope = scopes[Number.parseInt(args, 10)] as QuickJSScope | undefined; 482 | if (scope) { 483 | this.printLine(await this.inspect(scope)); 484 | return; 485 | } 486 | this.printLine(`Invalid scope: ${args}`); 487 | } 488 | this.printLine(scopes.map((scope, i) => `${i} ${inspectHandle(scope)}`).join('\n')); 489 | }), 490 | }); 491 | this.repl.defineCommand('ref', { 492 | help: 'Dump reference', 493 | action: this.server.wrapAsync(async (args) => { 494 | const match = referenceLocatorRegex.exec(args); 495 | if (match) { 496 | const ref = Number.parseInt(match[1], 10); 497 | const range = [Number.parseInt(match[2], 10), Number.parseInt(match[3], 10)] as const; 498 | const properties = await this.server.dumpReference(ref, Number.isNaN(range[0]) ? undefined : range); 499 | const lines = properties.map(inspectHandle); 500 | if (!lines.length) { 501 | lines.push('None'); 502 | } 503 | this.printLine(lines.join('\n')); 504 | } else { 505 | this.printLine(`Invalid reference: ${args}`); 506 | } 507 | }), 508 | }); 509 | this.repl.defineCommand('setinspect', { 510 | help: 'Set inspect method', 511 | action: (args) => { 512 | const found = inspectMethods.find((e) => args === e[0]); 513 | if (found) { 514 | [this.inspectMethod] = found; 515 | this.printLine(`Inspect method has changed to ${this.inspectMethod}`); 516 | return; 517 | } 518 | const lines = inspectMethods.map((e) => `${e[0]} - ${e[1]}`); 519 | if (args) { 520 | lines.unshift(`Invalid inspect method: ${args}`); 521 | } 522 | this.printLine(lines.join('\n')); 523 | }, 524 | }); 525 | this.repl.defineCommand('loglevel', { 526 | help: 'Show or change log level', 527 | action: (args) => { 528 | const argsTrimmed = args.trim().toLowerCase(); 529 | const index = LOG_LEVEL.indexOf(argsTrimmed); 530 | if (index >= 0) { 531 | this.server.logLevel = index; 532 | this.printLine(`Log level has changed to ${LOG_LEVEL[index]}`); 533 | } else { 534 | this.printLine( 535 | [ 536 | `Log level is ${LOG_LEVEL[this.server.logLevel]}`, 537 | `Accept values: ${LOG_LEVEL.join(', ')}`, 538 | ].join('\n'), 539 | ); 540 | } 541 | }, 542 | }); 543 | this.repl.defineCommand('require', { 544 | help: 'Require module to global scope', 545 | action: this.server.wrapAsync(async (args) => { 546 | const match = importRegex.exec(args); 547 | if (match) { 548 | if (this.server.paused) { 549 | await this.server.import(true, match[1], match[2]); 550 | this.printLine(`Trying to require ${match[1]}`); 551 | } else { 552 | this.printLine('Dynamic require is not allowed when running'); 553 | } 554 | } else { 555 | this.printLine(`Invalid import statement: ${args}`); 556 | } 557 | }), 558 | }); 559 | this.repl.defineCommand('import', { 560 | help: 'Import module to global scope', 561 | action: this.server.wrapAsync(async (args) => { 562 | const match = importRegex.exec(args); 563 | if (match) { 564 | if (this.server.paused) { 565 | await this.server.import(false, match[1], match[2]); 566 | this.printLine(`Trying to import ${match[1]} (Continuation is required)`); 567 | } else { 568 | this.printLine('Dynamic import is not allowed when running'); 569 | } 570 | } else { 571 | this.printLine(`Invalid import statement: ${args}`); 572 | } 573 | }), 574 | }); 575 | this.repl.defineCommand('resume', { 576 | help: 'Resume control', 577 | action: this.server.wrapAsync(async () => { 578 | await this.server.executeCommand('Resume'); 579 | this.repl.displayPrompt(true); 580 | }), 581 | }); 582 | this.repl.defineCommand('pause', { 583 | help: 'Pause execution', 584 | action: this.server.wrapAsync(async () => { 585 | await executeServerQuickCommand('Pause'); 586 | this.repl.displayPrompt(true); 587 | }), 588 | }); 589 | this.repl.defineCommand('continue', { 590 | help: 'Continue current line', 591 | action: this.server.wrapAsync(async () => { 592 | await executeServerQuickCommand('Continue'); 593 | this.repl.displayPrompt(true); 594 | }), 595 | }); 596 | this.repl.defineCommand('until', { 597 | help: 'Continue execution until specified breakpoint hit', 598 | action: this.server.wrapAsync(async (args) => { 599 | const parsed = this.parseBreakpoint(args); 600 | if (parsed) { 601 | this.server.addBreakpoint(parsed.lineNumber, parsed.fileName); 602 | const breakpointHitListener = () => { 603 | this.server.removeBreakpoint(parsed.lineNumber, parsed.fileName); 604 | this.server.off('breakpointHit', breakpointHitListener); 605 | }; 606 | this.server.on('breakpointHit', breakpointHitListener); 607 | await executeServerQuickCommand('Continue'); 608 | this.repl.displayPrompt(true); 609 | } else { 610 | this.printLine(`Invalid breakpoint: ${args}`); 611 | } 612 | }), 613 | }); 614 | this.repl.defineCommand('step', { 615 | help: 'Step current line', 616 | action: this.server.wrapAsync(async (type) => { 617 | if (type === 'in') { 618 | await executeServerQuickCommand('StepIn'); 619 | } else if (type === 'out') { 620 | await executeServerQuickCommand('StepOut'); 621 | } else { 622 | await executeServerQuickCommand('Step'); 623 | } 624 | this.repl.displayPrompt(true); 625 | }), 626 | }); 627 | this.repl.defineCommand('stat', { 628 | help: '[Minecraft only] Show running statistics', 629 | action: () => { 630 | const stat = this.server.dumpStatMessage(); 631 | if (stat) { 632 | this.printLine(stat); 633 | } else { 634 | this.printLine('Statistics is not available'); 635 | } 636 | }, 637 | }); 638 | this.repl.defineCommand('creator', { 639 | help: '[Minecraft only] Edit creator settings', 640 | action: (args) => { 641 | const protocolInfo = this.server.protocolInfo as unknown as Record; 642 | const argParts = args.split(/\s+/); 643 | if (argParts.length === 0) { 644 | this.printLine(`Current creator config: ${JSON.stringify(protocolInfo, null, 4)}`); 645 | } else if (argParts.length === 1) { 646 | const [name] = argParts; 647 | this.printLine(`${name}: ${JSON.stringify(protocolInfo[name], null, 4)}`); 648 | } else if (argParts.length === 2) { 649 | const [name, value] = argParts; 650 | const newValue: unknown = JSON.parse(value); 651 | protocolInfo[name] = newValue; 652 | this.printLine(`${name}: ${JSON.stringify(newValue, null, 4)}`); 653 | } else { 654 | this.printLine('Invalid syntax'); 655 | } 656 | }, 657 | }); 658 | } 659 | 660 | doEval(cmd: string, _context: Context, _file: string, callback: (err: Error | null, result?: unknown) => void) { 661 | this.acceptUserInput = false; 662 | try { 663 | if (this.server.session) { 664 | const trimmedCmd = cmd.trim(); 665 | let result = null; 666 | if (this.server.paused) { 667 | if (trimmedCmd.length > 0) { 668 | result = this.server.evaluate(cmd); 669 | result = result.then(async (res) => { 670 | this.printLine(await this.inspect(res), true); 671 | }); 672 | } else if (this.recentCommand) { 673 | result = this.server.executeCommand(this.recentCommand); 674 | } else { 675 | callback(null); 676 | return; 677 | } 678 | } else { 679 | result = this.server.executeCommand('Pause'); 680 | } 681 | result 682 | .then(() => { 683 | callback(null); 684 | }) 685 | .catch((err) => { 686 | callback(err as Error); 687 | }) 688 | .finally(() => { 689 | this.acceptUserInput = true; 690 | }); 691 | } else { 692 | this.showOfflinePrompt(); 693 | callback(null); 694 | } 695 | } catch (err) { 696 | callback(err as Error); 697 | this.acceptUserInput = true; 698 | } 699 | } 700 | } 701 | 702 | function main(port: number) { 703 | const replServer = new DebuggerReplServer(port); 704 | replServer.repl.on('exit', () => { 705 | process.exit(0); 706 | }); 707 | } 708 | 709 | main(Number(process.argv[2]) || 19144); 710 | --------------------------------------------------------------------------------