PaperTS
PaperTS 是一个 Paper Minecraft 插件,允许你使用 TypeScript 编写 Minecraft 服务器插件,并通过 Javet 在 Node.js JavaScript 引擎上运行。它为 TypeScript 模块提供了运行时环境,让你能够利用 JavaScript/TypeScript 的强大功能和灵活性进行 Minecraft 服务器开发。Node.JS 运行时是在运行时下载的,插件会从 Javet 官方依赖项 安装它,你可以验证你的平台是否受支持。
功能
- TypeScript/JavaScript 插件支持:使用 TypeScript 或 JavaScript 编写 Minecraft 插件,并直接在 Paper 服务器上运行它们。
- 自动模块加载:扫描插件的数据文件夹以查找模块(包含
package.json 的目录),初始化并自动启动它们。
- Node.js 环境:使用 Javet 的 NodeRuntime 提供类似 Node.js 的环境。
- 事件和命令注册:暴露 API,用于从 TypeScript 注册/注销 Bukkit 事件和命令。
- 热重载:模块可以在不重启服务器的情况下释放和重新加载。
工作原理
- 服务器启动时,PaperTS 扫描其数据文件夹中子目录,查找包含
package.json 文件的目录。
- 对于每个模块,它会读取
package.json 中的 main 字段以找到入口脚本。
- 入口脚本在 Node.js 运行时中执行,可以访问 PaperTS API 与服务器交互。
- 模块可以使用提供的全局
PaperTS 对象注册事件处理程序和命令。
入门指南
-
安装 PaperTS:将 PaperTS 插件 JAR 文件放入服务器的 plugins 文件夹中。
-
创建模块:
- 在
plugins/PaperTS 文件夹中,为你的模块创建一个新目录(例如 my-plugin)。
- 添加一个
package.json 文件,其中 main 字段指向你的入口脚本(例如 index.js)。
- 编写你的 TypeScript/JavaScript 代码,并在需要时将其编译为 JavaScript。
-
示例 package.json:
{
"name": "my-plugin",
"main": "index.js"
}
-
示例 index.js:
class ServerModule {
constructor() {
console.log("My plugin has been loaded!");
}
public handlePlayerJoin(event) {
// Handle player join event
event.player.sendMessage(event.player.name, "Welcome to the server!");
}
public helloCommand(sender, args) {
sender.sendMessage("Hello from PaperTS!");
}
}
const server = new ServerModule();
PaperTS.registerEvent(
org.bukkit.event.player.PlayerJoinEvent,
server.handlePlayerJoin.bind(server),
);
PaperTS.registerCommand(
"hello",
"Says hello to the player",
"/hello",
"",
[],
server.helloCommand.bind(server),
);
-
启动你的 Paper 服务器。PaperTS 将自动加载你的模块。你可以随时使用 /paperts reload 命令重新加载模块。
注意
导入 Node 模块
Node 模块导入的根目录是工作目录的根目录,因此如果你的目录结构如下所示:
my-plugin/
├── package.json
├── src/
│ └── index.ts
├── dist/
│ └── index.js
└── node_modules/
└── some-node-module/
PaperTS 将在 my-plugin 目录中查找模块,如果你想要从不同于模块根目录的路径导入脚本,可能需要调整 require 函数。所需的函数已经通过以下代码进行了修改,以允许导入 Java 类:
const Module = require("module");
const originalRequire = Module.prototype.require;
Module.prototype.require = function () {
if (arguments.length === 1 && typeof arguments[0] === "string" && (arguments[0].startsWith("org.") || arguments[0].startsWith("java.") || arguments[0].startsWith("net.") || arguments[0].startsWith("com."))) {
return javet.package[arguments[0]];
}
return originalRequire.apply(this, arguments);
};
Get 和 Set 方法
根据 Javet 维基,Javet 会猜测 get 和 set 方法。例如,getName() 变成 name,而 setName(value) 变成 name = value。因此,在使用这些方法时,你应该使用类似属性的语法。例如,与其调用 player.getName(),不如使用 player.name。同样,要设置值,请使用赋值语法,如 player.name = "NewName"。
PaperTS 全局 API
以下全局 API 在你的 TypeScript/JavaScript 代码中可用:
import { Event } from "org.bukkit.event";
import { CommandSender } from "org.bukkit.command";
import { PersistentDataContainer } from "org.bukkit.persistence";
import { List } from "java.util";
import { Runnable } from "java.lang";
import { JavaPlugin } from "org.bukkit.plugin.java";
declare namespace PaperTS {
export function registerEvent<T extends Event>(
eventClass: { new (...args: any[]): T },
listener: (event: T) => void,
): void;
export function registerCommand(
name: string,
description: string,
usageMessage: string,
permission: string,
aliases: string[],
executor: (sender: CommandSender, args: string[]) => void,
): void;
export function getPersistentContainerString(
key: string,
container: PersistentDataContainer
): string;
export function hasKeyPersistentContainer(
key: string,
container: PersistentDataContainer
): boolean;
export function setPersistentContainerString(
key: string,
value: string,
container: PersistentDataContainer
): void;
export function getJavaPlugin(): JavaPlugin;
export function createRunnable(runnable: () => void): Runnable;
}
注册事件
要注册事件,请使用 PaperTS.registerEvent 方法。你可以传递事件类和回调函数,当事件触发时将执行该回调函数。
export class ServerModule {
public handlePlayerJoin(event) {
console.log(`玩家 ${event.player.name} 已加入服务器!`);
}
}
const server = new ServerModule();
PaperTS.registerEvent(
org.bukkit.event.PlayerJoinEvent,
server.handlePlayerJoin.bind(server),
);
注册命令
要注册命令,请使用 PaperTS.registerCommand 方法。你可以指定命令名称、描述、用法提示、权限、别名以及一个用于处理命令执行的执行器函数。
class ServerModule {
public command(sender, args) {
console.log(`Command executed by ${sender.displayName()} with args: ${args.join(", ")}`);
}
}
const server = new ServerModule();
PaperTS.registerCommand(
"commandname",
"Command description",
"/commandname <args>",
"command.permission",
["alias1", "alias2"],
server.command.bind(server),
);
注意
在将方法作为回调传递时,使用 bind 是必要的,以确保保持正确的上下文(this)。
使用 TypeScript
要使用 TypeScript,你可以在模块目录中设置一个 tsconfig.json:
{
"compilerOptions": {
"incremental": true,
"module": "commonjs",
"esModuleInterop": true,
"strict": true,
"outDir": "./dist",
"forceConsistentCasingInFileNames": true,
"skipLibCheck": true,
"typeRoots": [
"node_modules/paperts-java-ts-bind",
"node_modules/@types"
]
},
"include": [
"src/**/*"
]
}
在模块目录中安装必要的依赖项:
npm install --save github:MetlHedd/java-ts-bind#1.20-R0.1-SNAPSHOT
如果您想使用其他版本,可以替换 paperts-java-ts-bind 包的版本。您也可以通过在此仓库中提交 issue 来请求其他版本。
然后,您可以在 src 目录中编写 TypeScript 代码,并将其编译为 dist 目录中的 JavaScript 文件。
您的 package.json 应如下所示:
{
"main": "dist/index.js",
"scripts": {
"build": "bun build ./src/index.ts --outdir=./dist --target=node --format=cjs --external=org.* --external=com.* --external=net.* --external=io.* --external=java.* --external=javet.* --watch"
},
"dependencies": {
"bun": "^1.2.19",
"paperts-java-ts-bind": "github:MetlHedd/java-ts-bind#1.21.4-R0.1-SNAPSHOT",
"typescript": "^5.8.3",
"@types/node": "^24.0.15"
}
}
然后,您可以使用 npm run build 将 TypeScript 代码打包成单个 JavaScript 文件,该文件可由 PaperTS 运行。
示例 index.ts:
import { Event } from "org.bukkit.event";
import { PlayerJoinEvent } from "org.bukkit.event.player";
import { CommandSender } from "org.bukkit.command";
declare namespace PaperTS {
export function registerEvent<T extends Event>(
eventClass: { new (...args: any[]): T },
listener: (event: T) => void,
): void;
```typescript
export function registerCommand(
name: string,
description: string,
usageMessage: string,
permission: string,
aliases: string[],
executor: (sender: CommandSender, args: string[]) => void,
): void;
}
export class ServerModule {
constructor() {
// 模块加载时会调用此构造函数
console.log("My plugin has been loaded!");
}
public handlePlayerJoin(event: PlayerJoinEvent) {
// 处理玩家加入事件
event.player.sendMessage(event.player.name, "Welcome to the server!");
}
public helloCommand(sender: CommandSender, args: string[]) {
sender.sendMessage("Hello from PaperTS!");
}
}
const server = new ServerModule();
PaperTS.registerEvent(
PlayerJoinEvent,
server.handlePlayerJoin.bind(server),
);
PaperTS.registerCommand(
"hello",
"Says hello to the player",
"/hello",
"",
[],
server.helloCommand.bind(server),
);
国际化 (i18n)
PaperTS 通过 Node.js 运行时支持国际化 (i18n),启用后可能会使某些 Node.js 模块的行为更加兼容。要启用 i18n,请在插件的数据文件夹中创建一个名为 node-icu 的文件夹(通常为 plugins/PaperTS/node-icu),并将 ICU 数据文件放置其中。您可以从 Javet 仓库 的任何 Actions 运行中下载 ICU 数据文件。插件会自动检测 node-icu 文件夹的存在并启用 i18n 支持。
设置运行类型
您可以通过在模块的 package.json 中指定 runType 字段来配置脚本的运行方式。这决定了脚本是同步还是异步执行,以及在哪个线程上运行。以下是一个示例配置:
{
"runType": "SynchronousOnNextTick"
}
runType 的可用选项包括:
SynchronousOnNextTick:在下一次服务器刻时同步执行脚本。
AsynchronousOnNextTick:在下一次服务器刻时异步执行脚本。
NewThread:在单独的线程上异步执行脚本。
资源清理
当卸载或重新加载模块时,如果模块的主脚本中存在 cleanup 函数,PaperTS 会尝试通过调用该函数来清理资源。此函数应处理任何必要的清理任务,例如关闭数据库连接、关闭 HTTP 服务器或释放内存。
插件命令
您可以使用以下命令来管理您的 PaperTS 模块:
/paperts reload:重新加载所有模块。
/paperts reload <module>:重新加载特定模块。
/paperts list:列出所有已加载的模块。
/paperts unload <module>:卸载特定模块。
/paperts load <module>:加载特定模块。
开发
PaperTS 使用 Javet 嵌入 V8 引擎和 Node.js 运行时。该插件管理引擎池和工作目录,并暴露一个 Globals API 用于事件和命令管理。
构建
使用 Gradle 进行构建:
./gradlew build
输出的 JAR 文件将位于 app/build/libs/ 中。
贡献指南
欢迎贡献!请提交 Issue 或 Pull Request,用于修复 bug、添加新功能或改进文档。
灵感来源
以下是一些启发 PaperTS 的项目:
PaperTS
PaperTS is a Paper Minecraft plugin that enables you to write Minecraft server plugins in TypeScript, running on the Node.js JavaScript engine via Javet. It provides a runtime environment for TypeScript modules, allowing you to leverage the power and flexibility of JavaScript/TypeScript for Minecraft server development. Node.JS runtime is downloaded at runtime, the plugins install it from Javet Official Depedencies, you may verify if your platform is supported.
Features
- TypeScript/JavaScript Plugin Support: Write Minecraft plugins in TypeScript or JavaScript and run them directly on your Paper server.
- Automatic Module Loading: Scans the plugin's data folder for modules (directories with a
package.json), initializes, and starts them automatically.
- Node.js Environment: Provides a Node.js-like environment using Javet's NodeRuntime.
- Event and Command Registration: Exposes APIs for registering/unregistering Bukkit events and commands from TypeScript.
- Hot Reloading: Modules can be released and reloaded without restarting the server.
How It Works
- On server start, PaperTS scans its data folder for subdirectories containing a
package.json file.
- For each module, it reads the
main field in package.json to find the entry script.
- The entry script is executed in a Node.js runtime, with access to PaperTS APIs for interacting with the server.
- Modules can register event handlers and commands using the provided global
PaperTS object.
Getting Started
-
Install PaperTS: Place the PaperTS plugin JAR in your server's plugins folder.
-
Create a Module:
- In the
plugins/PaperTS folder, create a new directory for your module (e.g., my-plugin).
- Add a
package.json file with a main field pointing to your entry script (e.g., index.js).
- Write your TypeScript/JavaScript code and compile it to JavaScript if needed.
-
Example package.json:
{
"name": "my-plugin",
"main": "index.js"
}
-
Example index.js:
class ServerModule {
constructor() {
console.log("My plugin has been loaded!");
}
public handlePlayerJoin(event) {
// Handle player join event
event.player.sendMessage(event.player.name, "Welcome to the server!");
}
public helloCommand(sender, args) {
sender.sendMessage("Hello from PaperTS!");
}
}
const server = new ServerModule();
PaperTS.registerEvent(
org.bukkit.event.player.PlayerJoinEvent,
server.handlePlayerJoin.bind(server),
);
PaperTS.registerCommand(
"hello",
"Says hello to the player",
"/hello",
"",
[],
server.helloCommand.bind(server),
);
-
Start your Paper server. PaperTS will automatically load your module. You can reload the modules any time using the /paperts reload command.
Note
Importing Node Modules
The root for the imports of node modules is the root of the working directory, so if your directory structure is like this:
my-plugin/
├── package.json
├── src/
│ └── index.ts
├── dist/
│ └── index.js
└── node_modules/
└── some-node-module/
PaperTS will look for modules in my-plugin directory, you may need to adjust the require functiion if you want to import scripts from diferents paths that the root of the module. The required function is already modified with the following code to allow importing the java classes:
const Module = require("module");
const originalRequire = Module.prototype.require;
Module.prototype.require = function () {
if (arguments.length === 1 && typeof arguments[0] === "string" && (arguments[0].startsWith("org.") || arguments[0].startsWith("java.") || arguments[0].startsWith("net.") || arguments[0].startsWith("com."))) {
return javet.package[arguments[0]];
}
return originalRequire.apply(this, arguments);
};
Get and Set methods
According to the Javet wiki, Javet guesses the get and set methods. For example, getName() turns into name, and setName(value) becomes name = value. So, when using these methods, you should use the property-like syntax. For example, instead of calling player.getName(), you should use player.name. Similarly, to set a value, use the assignment syntax like player.name = "NewName".
PaperTS Global API
The following global API is available in your TypeScript/JavaScript code:
import { Event } from "org.bukkit.event";
import { CommandSender } from "org.bukkit.command";
import { PersistentDataContainer } from "org.bukkit.persistence";
import { List } from "java.util";
import { Runnable } from "java.lang";
import { JavaPlugin } from "org.bukkit.plugin.java";
declare namespace PaperTS {
export function registerEvent<T extends Event>(
eventClass: { new (...args: any[]): T },
listener: (event: T) => void,
): void;
export function registerCommand(
name: string,
description: string,
usageMessage: string,
permission: string,
aliases: string[],
executor: (sender: CommandSender, args: string[]) => void,
): void;
export function getPersistentContainerString(
key: string,
container: PersistentDataContainer
): string;
export function hasKeyPersistentContainer(
key: string,
container: PersistentDataContainer
): boolean;
export function setPersistentContainerString(
key: string,
value: string,
container: PersistentDataContainer
): void;
export function getJavaPlugin(): JavaPlugin;
export function createRunnable(runnable: () => void): Runnable;
}
Registering Events
To register events, use the PaperTS.registerEvent method. You can pass the event class and a callback function that will be executed when the event is triggered.
export class ServerModule {
public handlePlayerJoin(event) {
console.log(`Player ${event.player.name} has joined the server!`);
}
}
const server = new ServerModule();
PaperTS.registerEvent(
org.bukkit.event.PlayerJoinEvent,
server.handlePlayerJoin.bind(server),
);
Registering Commands
To register commands, use the PaperTS.registerCommand method. You can specify the command name, description, usage message, permission, aliases, and an executor function that will handle the command execution.
class ServerModule {
public command(sender, args) {
console.log(`Command executed by ${sender.displayName()} with args: ${args.join(", ")}`);
}
}
const server = new ServerModule();
PaperTS.registerCommand(
"commandname",
"Command description",
"/commandname <args>",
"command.permission",
["alias1", "alias2"],
server.command.bind(server),
);
Note
Using bind is necessary when passing methods as callbacks to ensure the correct context (this) is maintained.
Using typescript
To use TypeScript, you can set up a tsconfig.json in your module directory:
{
"compilerOptions": {
"incremental": true,
"module": "commonjs",
"esModuleInterop": true,
"strict": true,
"outDir": "./dist",
"forceConsistentCasingInFileNames": true,
"skipLibCheck": true,
"typeRoots": [
"node_modules/paperts-java-ts-bind",
"node_modules/@types"
]
},
"include": [
"src/**/*"
]
}
Install the necessary depedencies in your module directory:
npm install --save github:MetlHedd/java-ts-bind#1.20-R0.1-SNAPSHOT
You can substitute the version, with another version of the paperts-java-ts-bind package, if you want to use a different version. You can also request another version by opening an issue on this repository.
Then, you can write your TypeScript code in the src directory and compile it to JavaScript in the dist directory.
Your package.json should look like this:
{
"main": "dist/index.js",
"scripts": {
"build": "bun build ./src/index.ts --outdir=./dist --target=node --format=cjs --external=org.* --external=com.* --external=net.* --external=io.* --external=java.* --external=javet.* --watch"
},
"dependencies": {
"bun": "^1.2.19",
"paperts-java-ts-bind": "github:MetlHedd/java-ts-bind#1.21.4-R0.1-SNAPSHOT",
"typescript": "^5.8.3",
"@types/node": "^24.0.15"
}
}
Then you can use npm run build to bundle your TypeScript code into a single JavaScript file that can be run by PaperTS.
Example index.ts:
import { Event } from "org.bukkit.event";
import { PlayerJoinEvent } from "org.bukkit.event.player";
import { CommandSender } from "org.bukkit.command";
declare namespace PaperTS {
export function registerEvent<T extends Event>(
eventClass: { new (...args: any[]): T },
listener: (event: T) => void,
): void;
export function registerCommand(
name: string,
description: string,
usageMessage: string,
permission: string,
aliases: string[],
executor: (sender: CommandSender, args: string[]) => void,
): void;
}
export class ServerModule {
constructor() {
// This constructor is called when the module is loaded
console.log("My plugin has been loaded!");
}
public handlePlayerJoin(event: PlayerJoinEvent) {
// Handle player join event
event.player.sendMessage(event.player.name, "Welcome to the server!");
}
public helloCommand(sender: CommandSender, args: string[]) {
sender.sendMessage("Hello from PaperTS!");
}
}
const server = new ServerModule();
PaperTS.registerEvent(
PlayerJoinEvent,
server.handlePlayerJoin.bind(server),
);
PaperTS.registerCommand(
"hello",
"Says hello to the player",
"/hello",
"",
[],
server.helloCommand.bind(server),
);
Internationalization (i18n)
PaperTS supports internationalization (i18n) through the Node.js runtime, enabling it may lead to more compatible behavior with some Node.js modules. To enable i18n, create a folder name node-icu in the data folder of the plugin (normally plugins/PaperTS/node-icu) and place the ICU data files there. You can download the ICU data files from any actions run of the Javet repository. The plugin will automatically detect the presence of the node-icu folder and enable i18n support.
Setting up the Run Type
You can configure how the script runs by specifying the runType field in the package.json of your module. This determines whether the script executes synchronously or asynchronously, and on which thread. Below is an example configuration:
{
"runType": "SynchronousOnNextTick"
}
The available options for runType are:
SynchronousOnNextTick: Executes the script synchronously on the next server tick.
AsynchronousOnNextTick: Executes the script asynchronously on the next server tick.
NewThread: Executes the script asynchronously on a separate thread.
Resource Cleanup
When unloading or reloading a module, PaperTS attempts to clean up resources by calling a cleanup function if it exists in the module's main script. This function should handle any necessary cleanup tasks, such as closing database connections, closing a http server, or freeing up memory.
Plugin Commands
You can use the following commands to manage your PaperTS modules:
/paperts reload: Reloads all modules.
/paperts reload <module>: Reloads a specific module.
/paperts list: Lists all loaded modules.
/paperts unload <module>: Unloads a specific module.
/paperts load <module>: Loads a specific module.
Development
PaperTS uses Javet to embed the V8 engine and Node.js runtime. The plugin manages engine pools, working directories, and exposes a Globals API for event and command management.
Building
Build with Gradle:
./gradlew build
The output JAR will be in app/build/libs/.
Contributing
Contributions are welcome! Please open issues or pull requests for bug fixes, features, or documentation improvements.
Inspiration
Some projects that inspired PaperTS:
评论 0
登录后参与评分
还没有评论,来抢沙发吧