Skip to content

Commit 9dff517

Browse files
committed
feat: Initial commit
0 parents  commit 9dff517

File tree

6 files changed

+265
-0
lines changed

6 files changed

+265
-0
lines changed

.vscode/settings.json

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"deno.enable": true,
3+
"deno.lint": true,
4+
"deno.unstable": false
5+
}

LICENSE.md

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
Copyright 2022 AshCorr
2+
3+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4+
5+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6+
7+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

README.md

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# byond_client
2+
3+
> **byond_client** is a Deno implementation of the byond topic protocol used for communicating between byond servers.
4+
5+
### Import
6+
7+
Replace `LATEST_VERSION` with
8+
[current latest version](https://deno.land/x/byond_client)
9+
10+
```ts
11+
import {
12+
ByondClient
13+
} from "https://deno.land/x/byond_client@LATEST_VERSION/mod.ts";
14+
```
15+
16+
### Usage
17+
18+
```ts
19+
const client = new ByondClient();
20+
21+
await client.connect({
22+
hostname: "game.yogstation.net",
23+
port: "4133"
24+
});
25+
26+
// Basic Example: ?ping
27+
const playersOnline = client.send("ping");
28+
console.log(`Players Online: ${playersOnline}`);
29+
/// Players Online: 47
30+
31+
// Using parameters and parsing Byond response: ?status&comms_key=SuperSecretPassword
32+
const info = new URLSearchParams(await client.send("status", {
33+
comms_key: "SuperSecretPassword"
34+
}));
35+
console.log(`Current Gamemode: ${info.gamemode}`)
36+
/// Current Gamemode: Shadowlings
37+
38+
client.close();
39+
```
40+
41+
### Todo
42+
1. Locking or Queuing topic requests for thread safety
43+
2. Connecting pooling
44+
3. Documentation

deps.ts

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export { varnum } from "https://deno.land/[email protected]/encoding/binary.ts";
2+
3+
export { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";

mod.ts

+126
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
import { varnum } from "./deps.ts";
2+
3+
const BYOND_RESPONSE_HEADER_SIZE = 5;
4+
5+
const BYOND_FLOAT_TYPE = 0x2a;
6+
const BYOND_TEXT_TYPE = 0x06;
7+
8+
export class ByondClient {
9+
#connection?: Deno.TcpConn;
10+
11+
constructor() {}
12+
13+
async connect(connectionOptions: Deno.ConnectTlsOptions) {
14+
this.#connection = await Deno.connect(connectionOptions);
15+
}
16+
17+
#urlEncode(topic: string, parameters?: { [key: string]: string }) {
18+
if (topic[0] !== "?") topic = "?" + topic;
19+
20+
if (parameters === undefined) return topic;
21+
22+
Object.keys(parameters).forEach((parameter) => {
23+
const value = parameters[parameter];
24+
25+
if (value === undefined) {
26+
topic = topic += `&${parameter}`;
27+
} else {
28+
topic = topic += `&${parameter}=${encodeURIComponent(
29+
parameters[parameter]
30+
)}`;
31+
}
32+
});
33+
34+
return topic;
35+
}
36+
37+
#createByondPacket(topic: string) {
38+
const size = 2 + 2 + 5 + topic.length + 1;
39+
const dataBuffer = new Uint8Array(2 + 2 + 5 + topic.length + 1);
40+
dataBuffer[0] = 0x00;
41+
dataBuffer[1] = 0x83;
42+
dataBuffer[2] = 0x00;
43+
dataBuffer[3] = 5 + topic.length + 1;
44+
dataBuffer[4] = 0x00;
45+
dataBuffer[5] = 0x00;
46+
dataBuffer[6] = 0x00;
47+
dataBuffer[7] = 0x00;
48+
dataBuffer[8] = 0x00;
49+
50+
const utfEncoded = new TextEncoder().encode(topic);
51+
dataBuffer.set(utfEncoded, 9);
52+
53+
dataBuffer[size] = 0x00;
54+
55+
return dataBuffer;
56+
}
57+
58+
#decodeByondRespose(
59+
headerBuffer: Uint8Array,
60+
dataBuffer: Uint8Array
61+
): number | string {
62+
const dataType = headerBuffer[4];
63+
64+
switch (dataType) {
65+
case BYOND_FLOAT_TYPE: {
66+
const number = varnum(dataBuffer, {
67+
dataType: "float32",
68+
endian: "little",
69+
});
70+
71+
if (number === null) {
72+
throw new Error(
73+
`Unexpected data from server, was expecting 4 bytes but received ${dataBuffer}`
74+
);
75+
}
76+
77+
return number;
78+
}
79+
case BYOND_TEXT_TYPE:
80+
return new TextDecoder().decode(dataBuffer);
81+
default:
82+
throw new Error(
83+
`Unexpected type header returned by server: ${dataType}`
84+
);
85+
}
86+
}
87+
88+
#decodeByondResponseSize(headerBuffer: Uint8Array) {
89+
const responseSize = varnum(headerBuffer.slice(2, 4), {
90+
dataType: "uint16",
91+
});
92+
93+
if (responseSize === null) {
94+
throw new Error(`Unexpected header returned by server ${headerBuffer}`);
95+
}
96+
97+
return responseSize;
98+
}
99+
100+
async send(
101+
topic: string,
102+
parameters?: { [key: string]: string }
103+
): Promise<string | number> {
104+
if (this.#connection === undefined)
105+
throw new Error("Tried using send() without open()ing first.");
106+
107+
const byondPacket = this.#createByondPacket(
108+
this.#urlEncode(topic, parameters)
109+
);
110+
await this.#connection.write(byondPacket);
111+
112+
const headerBuffer = new Uint8Array(BYOND_RESPONSE_HEADER_SIZE);
113+
await this.#connection.read(headerBuffer);
114+
115+
const responseSize = this.#decodeByondResponseSize(headerBuffer);
116+
117+
const dataBuffer = new Uint8Array(responseSize);
118+
await this.#connection.read(dataBuffer);
119+
120+
return this.#decodeByondRespose(headerBuffer, dataBuffer);
121+
}
122+
123+
close() {
124+
this.#connection?.close();
125+
}
126+
}

mod_test.ts

+80
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import { assertEquals } from "./deps.ts";
2+
import { ByondClient } from "./mod.ts";
3+
4+
const TEST_HOSTNAME = "localhost";
5+
const TEST_PORT = 5613;
6+
7+
let listener: Deno.Listener;
8+
let connection: Deno.Conn;
9+
10+
async function mockByondServer(
11+
expectedPayload: Uint8Array,
12+
response: Uint8Array
13+
) {
14+
listener = Deno.listen({
15+
hostname: TEST_HOSTNAME,
16+
port: TEST_PORT,
17+
});
18+
connection = await listener.accept();
19+
20+
const payload = new Uint8Array(expectedPayload.length);
21+
await connection.read(payload);
22+
assertEquals(payload, expectedPayload);
23+
24+
await connection.write(response);
25+
26+
connection.close();
27+
listener.close();
28+
}
29+
30+
Deno.test("?ping", async () => {
31+
mockByondServer(
32+
// ?ping
33+
Uint8Array.from([0, 131, 0, 11, 0, 0, 0, 0, 0, 63, 112, 105, 110, 103, 0]),
34+
Uint8Array.from([0, 131, 0, 5, 42, 0, 0, 60, 66])
35+
);
36+
37+
const connector = new ByondClient();
38+
await connector.connect({ hostname: TEST_HOSTNAME, port: TEST_PORT });
39+
const response = await connector.send("?ping");
40+
connector.close();
41+
42+
assertEquals(47, response);
43+
});
44+
45+
Deno.test("ping", async () => {
46+
// ?ping
47+
mockByondServer(
48+
Uint8Array.from([0, 131, 0, 11, 0, 0, 0, 0, 0, 63, 112, 105, 110, 103, 0]),
49+
Uint8Array.from([0, 131, 0, 5, 42, 0, 0, 60, 66])
50+
);
51+
52+
const connector = new ByondClient();
53+
await connector.connect({ hostname: TEST_HOSTNAME, port: TEST_PORT });
54+
const response = await connector.send("ping");
55+
connector.close();
56+
57+
assertEquals(47, response);
58+
});
59+
60+
Deno.test("?status&comms_key=SuperSecretPassword", async () => {
61+
mockByondServer(
62+
// ?ping&comms_key=Super%26Secret%3FPassword
63+
Uint8Array.from([
64+
0, 131, 0, 47, 0, 0, 0, 0, 0, 63, 112, 105, 110, 103, 38, 99, 111, 109,
65+
109, 115, 95, 107, 101, 121, 61, 83, 117, 112, 101, 114, 37, 50, 54, 83,
66+
101, 99, 114, 101, 116, 37, 51, 70, 80, 97, 115, 115, 119, 111, 114, 100,
67+
0,
68+
]),
69+
Uint8Array.from([0, 131, 0, 5, 42, 0, 0, 60, 66])
70+
);
71+
72+
const connector = new ByondClient();
73+
await connector.connect({ hostname: TEST_HOSTNAME, port: TEST_PORT });
74+
const response = await connector.send("?ping", {
75+
comms_key: "Super&Secret?Password",
76+
});
77+
connector.close();
78+
79+
assertEquals(47, response);
80+
});

0 commit comments

Comments
 (0)