@jsprismarine/management-protocol 0.0.0 → 0.27.0-unstable-20261128211340
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/CHANGELOG.md +12 -0
- package/LICENSE +21 -0
- package/README.md +48 -0
- package/dist/ManagementServer.d.ts +101 -0
- package/dist/ManagementServer.d.ts.map +1 -0
- package/dist/ManagementServer.js +190 -0
- package/dist/ManagementServer.js.map +1 -0
- package/dist/isRecord.d.ts +3 -0
- package/dist/isRecord.d.ts.map +1 -0
- package/dist/isRecord.js +6 -0
- package/dist/isRecord.js.map +1 -0
- package/dist/jsonRpc.d.ts +106 -0
- package/dist/jsonRpc.d.ts.map +1 -0
- package/dist/jsonRpc.js +153 -0
- package/dist/jsonRpc.js.map +1 -0
- package/dist/mojangApi.d.ts +893 -0
- package/dist/mojangApi.d.ts.map +1 -0
- package/dist/mojangApi.js +14 -0
- package/dist/mojangApi.js.map +1 -0
- package/dist/mojangApi.json.d.ts +2 -0
- package/dist/mojangApi.json.js +1170 -0
- package/dist/mojangApi.json.js.map +1 -0
- package/dist/schemaCheck.d.ts +13 -0
- package/dist/schemaCheck.d.ts.map +1 -0
- package/dist/schemaCheck.js +55 -0
- package/dist/schemaCheck.js.map +1 -0
- package/dist/secret.d.ts +12 -0
- package/dist/secret.d.ts.map +1 -0
- package/dist/secret.js +27 -0
- package/dist/secret.js.map +1 -0
- package/package.json +77 -12
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# @jsprismarine/management-protocol
|
|
2
|
+
|
|
3
|
+
## 0.27.0-unstable-20261128211340
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#3921](https://github.com/JSPrismarine/JSPrismarine/pull/3921) [`edb0aca`](https://github.com/JSPrismarine/JSPrismarine/commit/edb0aca4ea9cf705456e84948490819691f2da5a) Thanks [@filiphsps](https://github.com/filiphsps)! - Serve Java Edition's Server Management Protocol. With `management-server-enabled` on, the server answers JSON-RPC over a WebSocket for the players, allow list, bans, operators, game rules and some server settings, and sends their notifications. The new `@jsprismarine/management-protocol` package holds the listener and Mojang's method catalog.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- Updated dependencies [[`44c0251`](https://github.com/JSPrismarine/JSPrismarine/commit/44c02515fa4810e75de3185001a8490aa7766ebd), [`c836dac`](https://github.com/JSPrismarine/JSPrismarine/commit/c836dac76a41e697fb7c8d1594224cdaf5cdbece), [`edb1160`](https://github.com/JSPrismarine/JSPrismarine/commit/edb116075c62fa251747acaf9d6db80bf1b448c4), [`3a7e94b`](https://github.com/JSPrismarine/JSPrismarine/commit/3a7e94b89acda05d76e99409711ea15afd122c0f), [`88fc786`](https://github.com/JSPrismarine/JSPrismarine/commit/88fc78645d05b732a620dbfcc6ee2a106950c093), [`ddbf63c`](https://github.com/JSPrismarine/JSPrismarine/commit/ddbf63cd7d5c971e4ef224f11c72f5227acc5816), [`f71822e`](https://github.com/JSPrismarine/JSPrismarine/commit/f71822e9a631edf44c55b8fbe70dfc9a728e78cc), [`ffb86ad`](https://github.com/JSPrismarine/JSPrismarine/commit/ffb86ad9e67431eeb9f1568ea66758a5cbffd050), [`cf7fe3c`](https://github.com/JSPrismarine/JSPrismarine/commit/cf7fe3c485a52482dcdbda6da2f822749b256f36), [`7756f1c`](https://github.com/JSPrismarine/JSPrismarine/commit/7756f1c349bb40b381252a231d6fd4b6518ae997), [`ce0f038`](https://github.com/JSPrismarine/JSPrismarine/commit/ce0f038e31a3976859d62295b8f04786cdbb0eb3), [`6580502`](https://github.com/JSPrismarine/JSPrismarine/commit/6580502b8aa1bab3091d98d581fd3501d5049b36), [`832bd7b`](https://github.com/JSPrismarine/JSPrismarine/commit/832bd7b2e1237f1cc98622cdcb1c21a3a6d37503), [`68a0e1b`](https://github.com/JSPrismarine/JSPrismarine/commit/68a0e1b820981bab5d69830066d824ca937e1021), [`14aeb2c`](https://github.com/JSPrismarine/JSPrismarine/commit/14aeb2cf0b75913f02907de47112af392f517d53), [`c35144a`](https://github.com/JSPrismarine/JSPrismarine/commit/c35144acb33d5b1a6237c523595df8674e349a0f), [`edb0aca`](https://github.com/JSPrismarine/JSPrismarine/commit/edb0aca4ea9cf705456e84948490819691f2da5a), [`0cd4ddb`](https://github.com/JSPrismarine/JSPrismarine/commit/0cd4ddb62d4a05f212368dbca7f217a8bb3a7f08), [`37722e2`](https://github.com/JSPrismarine/JSPrismarine/commit/37722e2d12c913328b9dfa9776e70b6300868d5e), [`dfe4b85`](https://github.com/JSPrismarine/JSPrismarine/commit/dfe4b85f7b9c075988d0231f4fb48e572e332ce1)]:
|
|
12
|
+
- @jsprismarine/errors@0.27.0-unstable-20261128211340
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 JSPrismarine Contributors
|
|
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.
|
package/README.md
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# @jsprismarine/management-protocol
|
|
2
|
+
|
|
3
|
+
[](https://github.com/JSPrismarine/JSPrismarine#readme)
|
|
4
|
+
[](https://discord.gg/kZZCDyCBbW)
|
|
5
|
+
[](https://www.npmjs.com/package/@jsprismarine/management-protocol)
|
|
6
|
+
|
|
7
|
+
The server side of Java Edition's [Server Management Protocol](https://minecraft.wiki/w/Minecraft_Server_Management_Protocol):
|
|
8
|
+
JSON-RPC 2.0 over a WebSocket, answered the way Java's own management server answers it. It knows
|
|
9
|
+
nothing about a game server. You hand it a function per method, and it handles the connection,
|
|
10
|
+
the secret, the parameters and the notifications.
|
|
11
|
+
|
|
12
|
+
## Modules
|
|
13
|
+
|
|
14
|
+
| Import | What it has |
|
|
15
|
+
| --- | --- |
|
|
16
|
+
| `@jsprismarine/management-protocol/ManagementServer` | `ManagementServer.listen`, which starts the listener, and the `Handlers` type a server implements |
|
|
17
|
+
| `@jsprismarine/management-protocol/mojangApi` | Mojang's OpenRPC document for the pinned Java release, with a type per schema and the `Methods` and `Notifications` maps |
|
|
18
|
+
| `@jsprismarine/management-protocol/jsonRpc` | `answerFrame`, the dispatcher, and the JSON-RPC error codes |
|
|
19
|
+
| `@jsprismarine/management-protocol/schemaCheck` | `schemaMismatch`, which checks a value against one of the document's schemas |
|
|
20
|
+
| `@jsprismarine/management-protocol/secret` | `generateSecret` and `isValidSecret`, for the 40-character secret |
|
|
21
|
+
|
|
22
|
+
## Example
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
import { ManagementServer } from '@jsprismarine/management-protocol/ManagementServer';
|
|
26
|
+
import { generateSecret } from '@jsprismarine/management-protocol/secret';
|
|
27
|
+
|
|
28
|
+
const server = await ManagementServer.listen({
|
|
29
|
+
host: 'localhost',
|
|
30
|
+
port: 25585,
|
|
31
|
+
secret: generateSecret(),
|
|
32
|
+
allowedOrigins: [],
|
|
33
|
+
started: () => true,
|
|
34
|
+
handlers: {
|
|
35
|
+
'minecraft:players': () => [{ id: '853c80ef-3c37-49fd-aa49-938b674adae6', name: 'jeb_' }]
|
|
36
|
+
},
|
|
37
|
+
notifications: ['minecraft:notification/players/joined']
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
server.notify('minecraft:notification/players/joined', { player: { name: 'jeb_' } });
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
A client authenticates with `Authorization: Bearer <secret>`, or from a browser with the
|
|
44
|
+
subprotocol `minecraft-v1,<secret>` from one of `allowedOrigins`. `rpc.discover` answers with the
|
|
45
|
+
methods in `handlers` and the listed notifications, so a client sees what the server implements.
|
|
46
|
+
|
|
47
|
+
`mojangApi.json` is generated: `pnpm --filter @jsprismarine/bedrock-data run dump:java-management`
|
|
48
|
+
copies it from the pinned Java release's data generator report and writes `mojangApi.ts` from it.
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Server Management Protocol listener: a WebSocket server that authenticates each client with
|
|
3
|
+
* the management secret, answers its JSON-RPC requests through the handlers it was given, and
|
|
4
|
+
* sends every client the server's notifications.
|
|
5
|
+
*/
|
|
6
|
+
import type { IncomingMessage } from 'node:http';
|
|
7
|
+
import type { RpcTable } from './jsonRpc.js';
|
|
8
|
+
import type { Methods, Notifications } from './mojangApi.js';
|
|
9
|
+
import { MOJANG_API } from './mojangApi.js';
|
|
10
|
+
/** What one method's handler takes and returns, as Mojang's document types it. */
|
|
11
|
+
export type Handler<K extends keyof Methods> = (params: Methods[K]['params']) => Methods[K]['result'] | Promise<Methods[K]['result']>;
|
|
12
|
+
/** The methods a server implements, by name. A method left out is not found, and not discovered. */
|
|
13
|
+
export type Handlers = {
|
|
14
|
+
readonly [K in keyof Methods]?: Handler<K>;
|
|
15
|
+
};
|
|
16
|
+
/** The subprotocol a browser offers, with the secret after it, since it cannot set a header. */
|
|
17
|
+
export declare const SUBPROTOCOL = "minecraft-v1";
|
|
18
|
+
/** What a listener logs. */
|
|
19
|
+
export interface ManagementLogger {
|
|
20
|
+
info(message: string): void;
|
|
21
|
+
warn(message: string): void;
|
|
22
|
+
}
|
|
23
|
+
/** How to start a listener. */
|
|
24
|
+
export interface ManagementServerOptions {
|
|
25
|
+
/** The address to listen on, as `management-server-host`. */
|
|
26
|
+
readonly host: string;
|
|
27
|
+
/** The port, as `management-server-port`; 0 picks a free one. */
|
|
28
|
+
readonly port: number;
|
|
29
|
+
/** The secret every client must send. */
|
|
30
|
+
readonly secret: string;
|
|
31
|
+
/**
|
|
32
|
+
* The `Origin` values a browser may connect from, as `management-server-allowed-origins`. Java
|
|
33
|
+
* checks the origin of a client that sends the secret as a subprotocol, which is what a browser
|
|
34
|
+
* has to do, and not of one that sends a bearer token.
|
|
35
|
+
*/
|
|
36
|
+
readonly allowedOrigins: readonly string[];
|
|
37
|
+
/**
|
|
38
|
+
* Whether the server has started. Before it has, a client may only call `rpc.discover`, and
|
|
39
|
+
* the only notification sent is `server/status`, as on Java.
|
|
40
|
+
*/
|
|
41
|
+
readonly started: () => boolean;
|
|
42
|
+
/** A PKCS12 keystore and its password, to serve `wss://`; omitted, the listener serves `ws://`. */
|
|
43
|
+
readonly tls?: {
|
|
44
|
+
readonly pfx: Buffer;
|
|
45
|
+
readonly passphrase?: string;
|
|
46
|
+
};
|
|
47
|
+
readonly handlers: Handlers;
|
|
48
|
+
/** The notifications the server sends, which `rpc.discover` lists. */
|
|
49
|
+
readonly notifications: readonly (keyof Notifications)[];
|
|
50
|
+
readonly logger?: ManagementLogger;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* The `rpc.discover` result: Mojang's document cut down to the methods this server handles and the
|
|
54
|
+
* notifications it sends, with every component, so a client sees what it can use here.
|
|
55
|
+
*/
|
|
56
|
+
export declare const discoverDocument: (handlers: Handlers, notifications: readonly (keyof Notifications)[]) => typeof MOJANG_API;
|
|
57
|
+
/**
|
|
58
|
+
* The dispatcher table for a set of handlers, with `rpc.discover`.
|
|
59
|
+
* @param handlers - The methods the server implements.
|
|
60
|
+
* @param notifications - The notifications it sends.
|
|
61
|
+
* @returns The table {@link answerFrame} reads.
|
|
62
|
+
*/
|
|
63
|
+
export declare const rpcTable: (handlers: Handlers, notifications: readonly (keyof Notifications)[], started: () => boolean, onInternalError?: RpcTable['onInternalError']) => RpcTable;
|
|
64
|
+
/** Why a client is refused, in the words Java's `AuthenticationHandler` uses. */
|
|
65
|
+
type Refusal = 'Missing API key' | 'Invalid API key' | 'Origin Not Allowed';
|
|
66
|
+
/**
|
|
67
|
+
* Checks a client's handshake as Java does: a bearer token, with no origin check, or else the
|
|
68
|
+
* secret after `minecraft-v1,` in `Sec-WebSocket-Protocol`, from an allowed origin.
|
|
69
|
+
* @returns Why the client is refused, or undefined to let it in.
|
|
70
|
+
*/
|
|
71
|
+
export declare const refusalOf: (headers: IncomingMessage['headers'], secret: string, allowedOrigins: readonly string[]) => Refusal | undefined;
|
|
72
|
+
/** A running listener. */
|
|
73
|
+
export declare class ManagementServer {
|
|
74
|
+
private readonly http;
|
|
75
|
+
private readonly sockets;
|
|
76
|
+
private readonly started;
|
|
77
|
+
private readonly clients;
|
|
78
|
+
private constructor();
|
|
79
|
+
/**
|
|
80
|
+
* Starts listening.
|
|
81
|
+
* @param options - Where to listen, the secret, and what to answer with.
|
|
82
|
+
* @returns The listener, once it is bound.
|
|
83
|
+
*/
|
|
84
|
+
static listen(options: ManagementServerOptions): Promise<ManagementServer>;
|
|
85
|
+
private accept;
|
|
86
|
+
/** The port the listener is bound to, which is the chosen one when the options asked for 0. */
|
|
87
|
+
get port(): number;
|
|
88
|
+
/** How many clients are connected. */
|
|
89
|
+
get clientCount(): number;
|
|
90
|
+
/**
|
|
91
|
+
* Sends a notification to every connected client. Before the server has started, only
|
|
92
|
+
* `server/status` is sent.
|
|
93
|
+
* @param name - The notification.
|
|
94
|
+
* @param params - Its parameters by name, as Mojang's document declares them.
|
|
95
|
+
*/
|
|
96
|
+
notify<K extends keyof Notifications>(name: K, params: Notifications[K]): void;
|
|
97
|
+
/** Disconnects every client and stops listening. */
|
|
98
|
+
close(): Promise<void>;
|
|
99
|
+
}
|
|
100
|
+
export {};
|
|
101
|
+
//# sourceMappingURL=ManagementServer.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ManagementServer.d.ts","sources":["../src/ManagementServer.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,eAAe,EAAwB,MAAM,WAAW,CAAC;AASvE,OAAO,KAAK,EAAuB,QAAQ,EAAE,MAAM,WAAW,CAAC;AAE/D,OAAO,KAAK,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EAAe,UAAU,EAAE,MAAM,aAAa,CAAC;AAGtD,kFAAkF;AAClF,MAAM,MAAM,OAAO,CAAC,CAAC,SAAS,MAAM,OAAO,IAAI,CAC3C,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,KAC3B,OAAO,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;AAE1D,oGAAoG;AACpG,MAAM,MAAM,QAAQ,GAAG;IAAE,QAAQ,EAAE,CAAC,IAAI,MAAM,OAAO,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC;CAAE,CAAC;AAKtE,gGAAgG;AAChG,eAAO,MAAM,WAAW,iBAAiB,CAAC;AAE1C,4BAA4B;AAC5B,MAAM,WAAW,gBAAgB;IAC7B,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,IAAI,CAAC,OAAO,EAAE,MAAM,GA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0BAA0B;AAC1B,qBAAa,gBAAgB;IAIrB,OAAO,CAAC,QAAQ,CAAC,IAAI;IACrB,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,OAAO;IAL5B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAwB;IAEhD,OAAO,eAIH;IAEJ;;;;OAIG;IACH,OAAoB,MAAM,CAAC,OAAO,EAAE,uBAAuB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CA4CtF;IAED,OAAO,CAAC,MAAM;IAed,+FAA+F;IAC/F,IAAW,IAAI,IAAI,MAAM,CAGxB;IAED,sCAAsC;IACtC,IAAW,WAAW,IAAI,MAAM,CAE/B;IAED;;;;;OAKG;IACI,MAAM,CAAC,CAAC,SAAS,MAAM,aAAa,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,aAAa,CAAC,CAAC,CAAC,GAAG,IAAI,CAMpF;IAED,oDAAoD;IACvC,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAOlC;CACJ"}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { createServer } from "node:http";
|
|
2
|
+
import { createServer as createServer$1 } from "node:https";
|
|
3
|
+
import { WebSocketServer } from "ws";
|
|
4
|
+
import { answerFrame, notificationFrame } from "./jsonRpc.js";
|
|
5
|
+
import { API_VERSION, MOJANG_API } from "./mojangApi.js";
|
|
6
|
+
import { secretMatches } from "./secret.js";
|
|
7
|
+
// src/ManagementServer.ts
|
|
8
|
+
/** The subprotocol a browser offers, with the secret after it, since it cannot set a header. */
|
|
9
|
+
var SUBPROTOCOL = "minecraft-v1";
|
|
10
|
+
var entries = new Map(MOJANG_API.methods.map((entry) => [entry.name, entry]));
|
|
11
|
+
/** The parameter of a method, as the document declares it. No method of the protocol takes more than one. */
|
|
12
|
+
var paramOf = (name) => entries.get(name)?.params[0];
|
|
13
|
+
/** The notifications Java sends before the server has started. */
|
|
14
|
+
var BEFORE_START = /* @__PURE__ */ new Set(["minecraft:notification/server/status"]);
|
|
15
|
+
/** The largest message a client may send, as Java's frame aggregator allows. */
|
|
16
|
+
var MAX_PAYLOAD = 65536;
|
|
17
|
+
/**
|
|
18
|
+
* The `rpc.discover` result: Mojang's document cut down to the methods this server handles and the
|
|
19
|
+
* notifications it sends, with every component, so a client sees what it can use here.
|
|
20
|
+
*/
|
|
21
|
+
var discoverDocument = (handlers, notifications) => ({
|
|
22
|
+
...MOJANG_API,
|
|
23
|
+
info: {
|
|
24
|
+
...MOJANG_API.info,
|
|
25
|
+
version: API_VERSION
|
|
26
|
+
},
|
|
27
|
+
methods: MOJANG_API.methods.filter((entry) => Object.hasOwn(handlers, entry.name) || notifications.some((name) => name === entry.name))
|
|
28
|
+
});
|
|
29
|
+
/**
|
|
30
|
+
* The dispatcher table for a set of handlers, with `rpc.discover`.
|
|
31
|
+
* @param handlers - The methods the server implements.
|
|
32
|
+
* @param notifications - The notifications it sends.
|
|
33
|
+
* @returns The table {@link answerFrame} reads.
|
|
34
|
+
*/
|
|
35
|
+
var rpcTable = (handlers, notifications, started, onInternalError) => {
|
|
36
|
+
const methods = /* @__PURE__ */ new Map();
|
|
37
|
+
for (const [name, handler] of Object.entries(handlers)) {
|
|
38
|
+
if (handler === void 0) continue;
|
|
39
|
+
const call = handler;
|
|
40
|
+
const param = paramOf(name);
|
|
41
|
+
methods.set(name, {
|
|
42
|
+
...param === void 0 ? {} : { param },
|
|
43
|
+
call
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
const discovered = discoverDocument(handlers, notifications);
|
|
47
|
+
methods.set("rpc.discover", {
|
|
48
|
+
beforeStart: true,
|
|
49
|
+
call: () => discovered
|
|
50
|
+
});
|
|
51
|
+
return {
|
|
52
|
+
methods,
|
|
53
|
+
components: MOJANG_API.components.schemas,
|
|
54
|
+
started,
|
|
55
|
+
...onInternalError === void 0 ? {} : { onInternalError }
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* Checks a client's handshake as Java does: a bearer token, with no origin check, or else the
|
|
60
|
+
* secret after `minecraft-v1,` in `Sec-WebSocket-Protocol`, from an allowed origin.
|
|
61
|
+
* @returns Why the client is refused, or undefined to let it in.
|
|
62
|
+
*/
|
|
63
|
+
var refusalOf = (headers, secret, allowedOrigins) => {
|
|
64
|
+
const authorization = headers.authorization;
|
|
65
|
+
if (authorization?.startsWith("Bearer ")) {
|
|
66
|
+
const token = authorization.slice(7).trim();
|
|
67
|
+
return token !== "" && secretMatches(secret, token) ? void 0 : "Invalid API key";
|
|
68
|
+
}
|
|
69
|
+
const protocol = headers["sec-websocket-protocol"];
|
|
70
|
+
if (protocol?.startsWith(`minecraft-v1,`)) {
|
|
71
|
+
const origin = headers.origin;
|
|
72
|
+
if (origin === void 0 || origin === "" || !allowedOrigins.includes(origin)) return "Origin Not Allowed";
|
|
73
|
+
const token = protocol.slice(13).trim();
|
|
74
|
+
return token !== "" && secretMatches(secret, token) ? void 0 : "Invalid API key";
|
|
75
|
+
}
|
|
76
|
+
return "Missing API key";
|
|
77
|
+
};
|
|
78
|
+
/** The response Java refuses a client with. */
|
|
79
|
+
var unauthorized = (reason) => {
|
|
80
|
+
const body = JSON.stringify({
|
|
81
|
+
error: "Unauthorized",
|
|
82
|
+
message: reason
|
|
83
|
+
});
|
|
84
|
+
return [
|
|
85
|
+
"HTTP/1.1 401 Unauthorized",
|
|
86
|
+
"Content-Type: application/json",
|
|
87
|
+
`Content-Length: ${Buffer.byteLength(body)}`,
|
|
88
|
+
"Connection: close",
|
|
89
|
+
"",
|
|
90
|
+
body
|
|
91
|
+
].join("\r\n");
|
|
92
|
+
};
|
|
93
|
+
/** A running listener. */
|
|
94
|
+
var ManagementServer = class ManagementServer {
|
|
95
|
+
http;
|
|
96
|
+
sockets;
|
|
97
|
+
started;
|
|
98
|
+
clients = /* @__PURE__ */ new Set();
|
|
99
|
+
constructor(http, sockets, started) {
|
|
100
|
+
this.http = http;
|
|
101
|
+
this.sockets = sockets;
|
|
102
|
+
this.started = started;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Starts listening.
|
|
106
|
+
* @param options - Where to listen, the secret, and what to answer with.
|
|
107
|
+
* @returns The listener, once it is bound.
|
|
108
|
+
*/
|
|
109
|
+
static async listen(options) {
|
|
110
|
+
const table = rpcTable(options.handlers, options.notifications, options.started, (method, error) => options.logger?.warn(`Management method ${method} failed: ${error instanceof Error ? error.stack : String(error)}`));
|
|
111
|
+
const http = options.tls === void 0 ? createServer() : createServer$1(options.tls);
|
|
112
|
+
const sockets = new WebSocketServer({
|
|
113
|
+
noServer: true,
|
|
114
|
+
maxPayload: MAX_PAYLOAD,
|
|
115
|
+
handleProtocols: (protocols) => protocols.has("minecraft-v1") ? SUBPROTOCOL : false
|
|
116
|
+
});
|
|
117
|
+
const server = new ManagementServer(http, sockets, options.started);
|
|
118
|
+
http.on("request", (_request, response) => {
|
|
119
|
+
response.writeHead(426, { Upgrade: "websocket" }).end();
|
|
120
|
+
});
|
|
121
|
+
http.on("upgrade", (request, socket, head) => {
|
|
122
|
+
const refusal = refusalOf(request.headers, options.secret, options.allowedOrigins);
|
|
123
|
+
if (refusal !== void 0) {
|
|
124
|
+
options.logger?.warn(`Refused a management client from ${request.socket.remoteAddress}: ${refusal}`);
|
|
125
|
+
socket.end(unauthorized(refusal));
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
if (request.url !== "/") {
|
|
129
|
+
socket.end("HTTP/1.1 404 Not Found\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
sockets.handleUpgrade(request, socket, head, (client) => server.accept(client, table));
|
|
133
|
+
});
|
|
134
|
+
await new Promise((resolve, reject) => {
|
|
135
|
+
http.once("error", reject);
|
|
136
|
+
http.listen(options.port, options.host, () => {
|
|
137
|
+
http.off("error", reject);
|
|
138
|
+
resolve();
|
|
139
|
+
});
|
|
140
|
+
});
|
|
141
|
+
options.logger?.info(`Management server listening on ${options.tls === void 0 ? "ws" : "wss"}://${options.host}:${server.port}`);
|
|
142
|
+
return server;
|
|
143
|
+
}
|
|
144
|
+
accept(client, table) {
|
|
145
|
+
this.clients.add(client);
|
|
146
|
+
client.on("close", () => this.clients.delete(client));
|
|
147
|
+
client.on("error", () => client.terminate());
|
|
148
|
+
client.on("message", (data, isBinary) => {
|
|
149
|
+
if (isBinary) return;
|
|
150
|
+
answerFrame(data.toString(), table).then((answer) => {
|
|
151
|
+
if (client.readyState !== client.OPEN) return;
|
|
152
|
+
if (answer.kind === "reply") client.send(answer.text);
|
|
153
|
+
else if (answer.kind === "close") client.close();
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
/** The port the listener is bound to, which is the chosen one when the options asked for 0. */
|
|
158
|
+
get port() {
|
|
159
|
+
const address = this.http.address();
|
|
160
|
+
return typeof address === "object" && address !== null ? address.port : 0;
|
|
161
|
+
}
|
|
162
|
+
/** How many clients are connected. */
|
|
163
|
+
get clientCount() {
|
|
164
|
+
return this.clients.size;
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Sends a notification to every connected client. Before the server has started, only
|
|
168
|
+
* `server/status` is sent.
|
|
169
|
+
* @param name - The notification.
|
|
170
|
+
* @param params - Its parameters by name, as Mojang's document declares them.
|
|
171
|
+
*/
|
|
172
|
+
notify(name, params) {
|
|
173
|
+
if (!this.started() && !BEFORE_START.has(name)) return;
|
|
174
|
+
const param = paramOf(name);
|
|
175
|
+
const frame = notificationFrame(name, param === void 0 ? void 0 : params[param.name]);
|
|
176
|
+
for (const client of this.clients) if (client.readyState === client.OPEN) client.send(frame);
|
|
177
|
+
}
|
|
178
|
+
/** Disconnects every client and stops listening. */
|
|
179
|
+
async close() {
|
|
180
|
+
for (const client of this.clients) client.close(1001, "Server stopping");
|
|
181
|
+
this.sockets.close();
|
|
182
|
+
await new Promise((resolve) => {
|
|
183
|
+
this.http.close(() => resolve());
|
|
184
|
+
this.http.closeAllConnections();
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
export { ManagementServer, SUBPROTOCOL, discoverDocument, refusalOf, rpcTable };
|
|
189
|
+
|
|
190
|
+
//# sourceMappingURL=ManagementServer.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ManagementServer.js","names":["createHttpServer","createHttpsServer","values"],"sources":["../src/ManagementServer.ts"],"sourcesContent":["/**\n * The Server Management Protocol listener: a WebSocket server that authenticates each client with\n * the management secret, answers its JSON-RPC requests through the handlers it was given, and\n * sends every client the server's notifications.\n */\nimport type { IncomingMessage, Server as HttpServer } from 'node:http';\nimport { createServer as createHttpServer } from 'node:http';\nimport { createServer as createHttpsServer } from 'node:https';\nimport type { AddressInfo } from 'node:net';\nimport type { Duplex } from 'node:stream';\n\nimport type { WebSocket } from 'ws';\nimport { WebSocketServer } from 'ws';\n\nimport type { RpcMethod, RpcParam, RpcTable } from './jsonRpc';\nimport { answerFrame, notificationFrame } from './jsonRpc';\nimport type { Methods, Notifications } from './mojangApi';\nimport { API_VERSION, MOJANG_API } from './mojangApi';\nimport { secretMatches } from './secret';\n\n/** What one method's handler takes and returns, as Mojang's document types it. */\nexport type Handler<K extends keyof Methods> = (\n params: Methods[K]['params']\n) => Methods[K]['result'] | Promise<Methods[K]['result']>;\n\n/** The methods a server implements, by name. A method left out is not found, and not discovered. */\nexport type Handlers = { readonly [K in keyof Methods]?: Handler<K> };\n\n/** One method or notification of Mojang's document. */\ntype ApiEntry = (typeof MOJANG_API.methods)[number];\n\n/** The subprotocol a browser offers, with the secret after it, since it cannot set a header. */\nexport const SUBPROTOCOL = 'minecraft-v1';\n\n/** What a listener logs. */\nexport interface ManagementLogger {\n info(message: string): void;\n warn(message: string): void;\n}\n\n/** How to start a listener. */\nexport interface ManagementServerOptions {\n /** The address to listen on, as `management-server-host`. */\n readonly host: string;\n /** The port, as `management-server-port`; 0 picks a free one. */\n readonly port: number;\n /** The secret every client must send. */\n readonly secret: string;\n /**\n * The `Origin` values a browser may connect from, as `management-server-allowed-origins`. Java\n * checks the origin of a client that sends the secret as a subprotocol, which is what a browser\n * has to do, and not of one that sends a bearer token.\n */\n readonly allowedOrigins: readonly string[];\n /**\n * Whether the server has started. Before it has, a client may only call `rpc.discover`, and\n * the only notification sent is `server/status`, as on Java.\n */\n readonly started: () => boolean;\n /** A PKCS12 keystore and its password, to serve `wss://`; omitted, the listener serves `ws://`. */\n readonly tls?: { readonly pfx: Buffer; readonly passphrase?: string };\n readonly handlers: Handlers;\n /** The notifications the server sends, which `rpc.discover` lists. */\n readonly notifications: readonly (keyof Notifications)[];\n readonly logger?: ManagementLogger;\n}\n\nconst entries: ReadonlyMap<string, ApiEntry> = new Map(MOJANG_API.methods.map((entry) => [entry.name, entry]));\n\n/** The parameter of a method, as the document declares it. No method of the protocol takes more than one. */\nconst paramOf = (name: string): RpcParam | undefined => entries.get(name)?.params[0];\n\n/** The notifications Java sends before the server has started. */\nconst BEFORE_START: ReadonlySet<string> = new Set(['minecraft:notification/server/status']);\n\n/** The largest message a client may send, as Java's frame aggregator allows. */\nconst MAX_PAYLOAD = 65_536;\n\n/**\n * The `rpc.discover` result: Mojang's document cut down to the methods this server handles and the\n * notifications it sends, with every component, so a client sees what it can use here.\n */\nexport const discoverDocument = (\n handlers: Handlers,\n notifications: readonly (keyof Notifications)[]\n): typeof MOJANG_API => ({\n ...MOJANG_API,\n info: { ...MOJANG_API.info, version: API_VERSION },\n methods: MOJANG_API.methods.filter(\n (entry) => Object.hasOwn(handlers, entry.name) || notifications.some((name) => name === entry.name)\n )\n});\n\n/**\n * The dispatcher table for a set of handlers, with `rpc.discover`.\n * @param handlers - The methods the server implements.\n * @param notifications - The notifications it sends.\n * @returns The table {@link answerFrame} reads.\n */\nexport const rpcTable = (\n handlers: Handlers,\n notifications: readonly (keyof Notifications)[],\n started: () => boolean,\n onInternalError?: RpcTable['onInternalError']\n): RpcTable => {\n const methods = new Map<string, RpcMethod>();\n for (const [name, handler] of Object.entries(handlers)) {\n if (handler === undefined) continue;\n // The handler is typed by its name in `Handlers`; the dispatcher has checked the params\n // against that same method's schemas, which is the type the handler declares.\n const call = handler as (params: Readonly<Record<string, unknown>>) => unknown;\n const param = paramOf(name);\n methods.set(name, { ...(param === undefined ? {} : { param }), call });\n }\n const discovered = discoverDocument(handlers, notifications);\n methods.set('rpc.discover', { beforeStart: true, call: () => discovered });\n return {\n methods,\n components: MOJANG_API.components.schemas,\n started,\n ...(onInternalError === undefined ? {} : { onInternalError })\n };\n};\n\n/** Why a client is refused, in the words Java's `AuthenticationHandler` uses. */\ntype Refusal = 'Missing API key' | 'Invalid API key' | 'Origin Not Allowed';\n\n/**\n * Checks a client's handshake as Java does: a bearer token, with no origin check, or else the\n * secret after `minecraft-v1,` in `Sec-WebSocket-Protocol`, from an allowed origin.\n * @returns Why the client is refused, or undefined to let it in.\n */\nexport const refusalOf = (\n headers: IncomingMessage['headers'],\n secret: string,\n allowedOrigins: readonly string[]\n): Refusal | undefined => {\n const authorization = headers.authorization;\n if (authorization?.startsWith('Bearer ')) {\n const token = authorization.slice('Bearer '.length).trim();\n return token !== '' && secretMatches(secret, token) ? undefined : 'Invalid API key';\n }\n const protocol = headers['sec-websocket-protocol'];\n if (protocol?.startsWith(`${SUBPROTOCOL},`)) {\n const origin = headers.origin;\n if (origin === undefined || origin === '' || !allowedOrigins.includes(origin)) return 'Origin Not Allowed';\n const token = protocol.slice(SUBPROTOCOL.length + 1).trim();\n return token !== '' && secretMatches(secret, token) ? undefined : 'Invalid API key';\n }\n return 'Missing API key';\n};\n\n/** The response Java refuses a client with. */\nconst unauthorized = (reason: Refusal): string => {\n const body = JSON.stringify({ error: 'Unauthorized', message: reason });\n return [\n 'HTTP/1.1 401 Unauthorized',\n 'Content-Type: application/json',\n `Content-Length: ${Buffer.byteLength(body)}`,\n 'Connection: close',\n '',\n body\n ].join('\\r\\n');\n};\n\n/** A running listener. */\nexport class ManagementServer {\n private readonly clients = new Set<WebSocket>();\n\n private constructor(\n private readonly http: HttpServer,\n private readonly sockets: WebSocketServer,\n private readonly started: () => boolean\n ) {}\n\n /**\n * Starts listening.\n * @param options - Where to listen, the secret, and what to answer with.\n * @returns The listener, once it is bound.\n */\n public static async listen(options: ManagementServerOptions): Promise<ManagementServer> {\n const table = rpcTable(options.handlers, options.notifications, options.started, (method, error) =>\n options.logger?.warn(\n `Management method ${method} failed: ${error instanceof Error ? error.stack : String(error)}`\n )\n );\n const http = options.tls === undefined ? createHttpServer() : createHttpsServer(options.tls);\n const sockets = new WebSocketServer({\n noServer: true,\n maxPayload: MAX_PAYLOAD,\n // A browser that sent its secret as a subprotocol needs `minecraft-v1` echoed back.\n handleProtocols: (protocols) => (protocols.has(SUBPROTOCOL) ? SUBPROTOCOL : false)\n });\n const server = new ManagementServer(http, sockets, options.started);\n\n http.on('request', (_request, response) => {\n response.writeHead(426, { Upgrade: 'websocket' }).end();\n });\n http.on('upgrade', (request: IncomingMessage, socket: Duplex, head: Buffer) => {\n const refusal = refusalOf(request.headers, options.secret, options.allowedOrigins);\n if (refusal !== undefined) {\n options.logger?.warn(`Refused a management client from ${request.socket.remoteAddress}: ${refusal}`);\n socket.end(unauthorized(refusal));\n return;\n }\n // Java upgrades on `/` alone.\n if (request.url !== '/') {\n socket.end('HTTP/1.1 404 Not Found\\r\\nConnection: close\\r\\nContent-Length: 0\\r\\n\\r\\n');\n return;\n }\n sockets.handleUpgrade(request, socket, head, (client) => server.accept(client, table));\n });\n\n await new Promise<void>((resolve, reject) => {\n http.once('error', reject);\n http.listen(options.port, options.host, () => {\n http.off('error', reject);\n resolve();\n });\n });\n options.logger?.info(\n `Management server listening on ${options.tls === undefined ? 'ws' : 'wss'}://${options.host}:${server.port}`\n );\n return server;\n }\n\n private accept(client: WebSocket, table: RpcTable): void {\n this.clients.add(client);\n client.on('close', () => this.clients.delete(client));\n client.on('error', () => client.terminate());\n client.on('message', (data, isBinary) => {\n // Java reads text frames alone and drops the rest.\n if (isBinary) return;\n void answerFrame(data.toString(), table).then((answer) => {\n if (client.readyState !== client.OPEN) return;\n if (answer.kind === 'reply') client.send(answer.text);\n else if (answer.kind === 'close') client.close();\n });\n });\n }\n\n /** The port the listener is bound to, which is the chosen one when the options asked for 0. */\n public get port(): number {\n const address = this.http.address();\n return typeof address === 'object' && address !== null ? (address satisfies AddressInfo).port : 0;\n }\n\n /** How many clients are connected. */\n public get clientCount(): number {\n return this.clients.size;\n }\n\n /**\n * Sends a notification to every connected client. Before the server has started, only\n * `server/status` is sent.\n * @param name - The notification.\n * @param params - Its parameters by name, as Mojang's document declares them.\n */\n public notify<K extends keyof Notifications>(name: K, params: Notifications[K]): void {\n if (!this.started() && !BEFORE_START.has(name)) return;\n const param = paramOf(name);\n const values: Readonly<Record<string, unknown>> = params;\n const frame = notificationFrame(name, param === undefined ? undefined : values[param.name]);\n for (const client of this.clients) if (client.readyState === client.OPEN) client.send(frame);\n }\n\n /** Disconnects every client and stops listening. */\n public async close(): Promise<void> {\n for (const client of this.clients) client.close(1001, 'Server stopping');\n this.sockets.close();\n await new Promise<void>((resolve) => {\n this.http.close(() => resolve());\n this.http.closeAllConnections();\n });\n }\n}\n"],"mappings":";;;;;;;;AAgCA,IAAa,cAAc;AAmC3B,IAAM,UAAyC,IAAI,IAAI,WAAW,QAAQ,KAAK,UAAU,CAAC,MAAM,MAAM,KAAK,CAAC,CAAC;;AAG7G,IAAM,WAAW,SAAuC,QAAQ,IAAI,IAAI,CAAC,EAAE,OAAO;;AAGlF,IAAM,+BAAoC,IAAI,IAAI,CAAC,sCAAsC,CAAC;;AAG1F,IAAM,cAAc;;;;;AAMpB,IAAa,oBACT,UACA,mBACqB;CACrB,GAAG;CACH,MAAM;EAAE,GAAG,WAAW;EAAM,SAAS;CAAY;CACjD,SAAS,WAAW,QAAQ,QACvB,UAAU,OAAO,OAAO,UAAU,MAAM,IAAI,KAAK,cAAc,MAAM,SAAS,SAAS,MAAM,IAAI,CACtG;AACJ;;;;;;;AAQA,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AO,MAAM,MAAM,iBAAiB;EACvE,KAAK,QAAQ,MAAM;EACnB,MAAM,IAAI,SAAe,YAAY;GACjC,KAAK,KAAK,YAAY,QAAQ,CAAC;GAC/B,KAAK,KAAK,oBAAoB;EAClC,CAAC;CACL;AACJ"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"isRecord.d.ts","sources":["../src/isRecord.ts"],"names":[],"mappings":"AAAA,4GAA4G;AAC5G,eAAO,MAAM,QAAQ,UAAW,OAAO,KAAG,KAAK,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CACD,CAAC"}
|
package/dist/isRecord.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// src/isRecord.ts
|
|
2
|
+
/** Whether a value is a non-null object, which is what parsed JSON has to be before its fields are read. */
|
|
3
|
+
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
4
|
+
export { isRecord };
|
|
5
|
+
|
|
6
|
+
//# sourceMappingURL=isRecord.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"isRecord.js","names":[],"sources":["../src/isRecord.ts"],"sourcesContent":["/** Whether a value is a non-null object, which is what parsed JSON has to be before its fields are read. */\nexport const isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n"],"mappings":";;AACA,IAAa,YAAY,UACrB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK"}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import type { Components } from './schemaCheck.js';
|
|
2
|
+
/** A request id: what the client sent, echoed back on the response. */
|
|
3
|
+
export type RpcId = string | number | null;
|
|
4
|
+
/** The error member of a response. */
|
|
5
|
+
export interface RpcError {
|
|
6
|
+
readonly code: number;
|
|
7
|
+
readonly message: string;
|
|
8
|
+
readonly data?: string;
|
|
9
|
+
}
|
|
10
|
+
/** A response: a result or an error, for the request with the same id. */
|
|
11
|
+
export type RpcResponse = {
|
|
12
|
+
readonly jsonrpc: '2.0';
|
|
13
|
+
readonly id: RpcId;
|
|
14
|
+
readonly result: unknown;
|
|
15
|
+
} | {
|
|
16
|
+
readonly jsonrpc: '2.0';
|
|
17
|
+
readonly id: RpcId;
|
|
18
|
+
readonly error: RpcError;
|
|
19
|
+
};
|
|
20
|
+
/** A notification the server sends: a method name and its parameters, and no id. */
|
|
21
|
+
export interface RpcNotification {
|
|
22
|
+
readonly jsonrpc: '2.0';
|
|
23
|
+
readonly method: string;
|
|
24
|
+
readonly params?: readonly unknown[];
|
|
25
|
+
}
|
|
26
|
+
/** The five errors JSON-RPC 2.0 defines, by the name its specification gives them. */
|
|
27
|
+
export declare const RPC_ERRORS: {
|
|
28
|
+
readonly parseError: {
|
|
29
|
+
readonly code: -32700;
|
|
30
|
+
readonly message: 'Parse error';
|
|
31
|
+
};
|
|
32
|
+
readonly invalidRequest: {
|
|
33
|
+
readonly code: -32600;
|
|
34
|
+
readonly message: 'Invalid Request';
|
|
35
|
+
};
|
|
36
|
+
readonly methodNotFound: {
|
|
37
|
+
readonly code: -32601;
|
|
38
|
+
readonly message: 'Method not found';
|
|
39
|
+
};
|
|
40
|
+
readonly invalidParams: {
|
|
41
|
+
readonly code: -32602;
|
|
42
|
+
readonly message: 'Invalid params';
|
|
43
|
+
};
|
|
44
|
+
readonly internalError: {
|
|
45
|
+
readonly code: -32603;
|
|
46
|
+
readonly message: 'Internal error';
|
|
47
|
+
};
|
|
48
|
+
};
|
|
49
|
+
/** One parameter a method declares, as Mojang's document lists it. */
|
|
50
|
+
export interface RpcParam {
|
|
51
|
+
readonly name: string;
|
|
52
|
+
readonly schema: unknown;
|
|
53
|
+
}
|
|
54
|
+
/** A method the dispatcher can call. */
|
|
55
|
+
export interface RpcMethod {
|
|
56
|
+
/** The parameter, when the method takes one. No method of the protocol takes more. */
|
|
57
|
+
readonly param?: RpcParam;
|
|
58
|
+
/** Whether a client may call it before the server has started, as only `rpc.discover` may. */
|
|
59
|
+
readonly beforeStart?: boolean;
|
|
60
|
+
/**
|
|
61
|
+
* Runs the method.
|
|
62
|
+
* @param params - The parameter by name, checked against its schema, or nothing.
|
|
63
|
+
* @returns The result, sent as the response's `result`.
|
|
64
|
+
* @throws {ManagementProtocolErrors.InvalidParams} When the parameter is well-formed but names
|
|
65
|
+
* something the method cannot act on. Any other error becomes an internal error.
|
|
66
|
+
*/
|
|
67
|
+
readonly call: (params: Readonly<Record<string, unknown>>) => unknown;
|
|
68
|
+
}
|
|
69
|
+
/** The methods one connection can call, by name, and the components their schemas refer to. */
|
|
70
|
+
export interface RpcTable {
|
|
71
|
+
readonly methods: ReadonlyMap<string, RpcMethod>;
|
|
72
|
+
readonly components: Components;
|
|
73
|
+
/** Whether the server has started; before it has, only `beforeStart` methods are dispatched. */
|
|
74
|
+
readonly started: () => boolean;
|
|
75
|
+
/** Told about an error a method threw that is not an `InvalidParams`, which the client sees no detail of. */
|
|
76
|
+
readonly onInternalError?: (method: string, error: unknown) => void;
|
|
77
|
+
}
|
|
78
|
+
/** What a frame needs in reply. */
|
|
79
|
+
export type FrameAnswer =
|
|
80
|
+
/** A frame to send back. */
|
|
81
|
+
{
|
|
82
|
+
readonly kind: 'reply';
|
|
83
|
+
readonly text: string;
|
|
84
|
+
}
|
|
85
|
+
/** Nothing: the frame was a notification, or a stray response. */
|
|
86
|
+
| {
|
|
87
|
+
readonly kind: 'none';
|
|
88
|
+
}
|
|
89
|
+
/** A batch held something that is not a request, which Java answers by closing the connection. */
|
|
90
|
+
| {
|
|
91
|
+
readonly kind: 'close';
|
|
92
|
+
};
|
|
93
|
+
/**
|
|
94
|
+
* Answers one frame: a request, a notification, or a batch of them.
|
|
95
|
+
*
|
|
96
|
+
* @param text - The frame, as the client sent it.
|
|
97
|
+
* @param table - The methods the connection can call.
|
|
98
|
+
* @returns What to send back, if anything.
|
|
99
|
+
*/
|
|
100
|
+
export declare const answerFrame: (text: string, table: RpcTable) => Promise<FrameAnswer>;
|
|
101
|
+
/**
|
|
102
|
+
* A notification frame. MSMP sends a notification's parameter as an array of one value, and no
|
|
103
|
+
* `params` at all for a notification that has none.
|
|
104
|
+
*/
|
|
105
|
+
export declare const notificationFrame: (method: string, param?: unknown) => string;
|
|
106
|
+
//# sourceMappingURL=jsonRpc.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"jsonRpc.d.ts","sources":["../src/jsonRpc.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAGhD,uEAAuE;AACvE,MAAM,MAAM,KAAK,GAAG,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC;AAE3C,sCAAsC;AACtC,MAAM,WAAW,QAAQ;IACrB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,0EAA0E;AAC1E,MAAM,MAAM,WAAW,GACjB;IAAE,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC;IAAC,QAAQ,CAAC,EAAE,EAAE,KAAK,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAA;CAAE,GACzE;IAAE,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC;IAAC,QAAQ,CAAC,EAAE,EAAE,KAAK,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAA;CAAE,CAAC;AAEhF,oFAAoF;AACpF,MAAM,WAAW,eAAe;IAC5B,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC;IACxB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,MAAM,CAAC,EAAE,SAAS,OAAO,EAAE,CAAC;CACxC;AAED,sFAAsF;AACtF,eAAO,MAAM,UAAU;;iBACL,IAAI,EAAE,CAAC,KAAK;iBAAE,OAAO,EAAE,aAAa;;;iBAChC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