@minecraftbot-com/plugin 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +188 -177
- package/README.md +47 -46
- package/dist/api.d.ts +4 -1
- package/dist/cli/api.d.ts +23 -0
- package/dist/cli/api.js +8 -0
- package/dist/cli/build.d.ts +1 -0
- package/dist/cli/build.js +9 -2
- package/dist/cli/check.d.ts +7 -0
- package/dist/cli/check.js +2 -1
- package/dist/cli/deploy.d.ts +13 -0
- package/dist/cli/deploy.js +51 -0
- package/dist/cli/main.js +7 -0
- package/dist/hosted/fetch.d.ts +53 -0
- package/dist/hosted/fetch.js +216 -0
- package/dist/hosted/index.d.ts +3 -0
- package/dist/hosted/index.js +81 -0
- package/dist/runtime/runtime.d.ts +1 -1
- package/dist/runtime/runtime.js +1 -1
- package/package.json +6 -1
- package/src/api.ts +4 -1
- package/src/cli/api.ts +105 -79
- package/src/cli/build.ts +9 -2
- package/src/cli/check.ts +104 -103
- package/src/cli/deploy.ts +60 -0
- package/src/cli/main.ts +7 -0
- package/src/hosted/fetch.ts +224 -0
- package/src/hosted/index.ts +121 -0
- package/src/runtime/runtime.ts +281 -281
- package/templates/basic/AGENTS.md +32 -31
- package/templates/basic/README.md +14 -13
- package/templates/basic/package.json +1 -0
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { SDK_VERSION } from "../runtime/runtime.js";
|
|
4
|
+
import { deployBundle } from "./api.js";
|
|
5
|
+
import { findProject } from "./build.js";
|
|
6
|
+
import { buildAll, review } from "./check.js";
|
|
7
|
+
import { bold, cyan, dim, fail, green, info, warn } from "./output.js";
|
|
8
|
+
/**
|
|
9
|
+
* `minebot deploy`: builds the hosted bundle and uploads it as the plugin's new version, so it runs on MineBot's
|
|
10
|
+
* servers instead of your machine. Profiles it runs on move to the new version; `--profile` adds one.
|
|
11
|
+
*/
|
|
12
|
+
export async function deploy(args) {
|
|
13
|
+
const project = findProject();
|
|
14
|
+
const { manifest, bundle, bytes } = await buildAll(join(project.root, ".minebot", "deploy"));
|
|
15
|
+
const { problems } = review(manifest, bytes);
|
|
16
|
+
if (problems.length) {
|
|
17
|
+
for (const p of problems)
|
|
18
|
+
warn(p);
|
|
19
|
+
fail("Fix these before deploying.", "`minebot check` shows the same list.");
|
|
20
|
+
}
|
|
21
|
+
if ((args.bots.length || args.settingsFile) && !args.profile)
|
|
22
|
+
fail("--bot and --settings need --profile.");
|
|
23
|
+
let settings;
|
|
24
|
+
if (args.settingsFile) {
|
|
25
|
+
try {
|
|
26
|
+
settings = JSON.parse(readFileSync(args.settingsFile, "utf8"));
|
|
27
|
+
}
|
|
28
|
+
catch (e) {
|
|
29
|
+
fail(`Couldn't read ${args.settingsFile}: ${e.message}`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
info(`Deploying ${bold(manifest.name)} ${dim(manifest.version)} (${(bytes / 1024).toFixed(1)} KB)…`);
|
|
33
|
+
const result = await deployBundle({
|
|
34
|
+
manifest,
|
|
35
|
+
bundle: readFileSync(bundle, "utf8"),
|
|
36
|
+
sdk: SDK_VERSION,
|
|
37
|
+
profile: args.profile,
|
|
38
|
+
settings,
|
|
39
|
+
bots: args.bots.length ? args.bots : undefined,
|
|
40
|
+
});
|
|
41
|
+
info(result.newVersion ? green(`Deployed ${result.name} ${result.version}.`) : `${result.name} ${result.version} is already deployed; nothing to upload.`);
|
|
42
|
+
const enabled = result.installations.filter(i => i.enabled);
|
|
43
|
+
if (enabled.length === 0) {
|
|
44
|
+
info(`\nIt doesn't run anywhere yet: ${cyan("minebot deploy --profile <name>")}, or Plugins → Custom Plugins on the dashboard.`);
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
info("\nRuns on MineBot's servers whenever these profiles run:");
|
|
48
|
+
for (const i of enabled)
|
|
49
|
+
info(` • ${bold(i.profileName)}`);
|
|
50
|
+
info(dim(`\nIts console and status are on the dashboard: ${result.dashboard}`));
|
|
51
|
+
}
|
package/dist/cli/main.js
CHANGED
|
@@ -3,6 +3,7 @@ import { pollDevice, startDevice } from "./api.js";
|
|
|
3
3
|
import { build, check } from "./check.js";
|
|
4
4
|
import { apiUrl, deleteCredentials, readCredentials, saveCredentials } from "./config.js";
|
|
5
5
|
import { create } from "./create.js";
|
|
6
|
+
import { deploy } from "./deploy.js";
|
|
6
7
|
import { dev } from "./dev.js";
|
|
7
8
|
import { bold, cyan, dim, fail, green, info } from "./output.js";
|
|
8
9
|
import { test } from "./test.js";
|
|
@@ -22,6 +23,10 @@ const HELP = `minebot ${SDK_VERSION}: write and run MineBot plugins
|
|
|
22
23
|
minebot test run test/*.test.ts against a fake bot
|
|
23
24
|
minebot check what users will be asked to allow, bundle size, problems
|
|
24
25
|
minebot build write dist/plugin.js and dist/manifest.json
|
|
26
|
+
minebot deploy [options] upload the plugin so it runs on MineBot's servers, not your machine
|
|
27
|
+
--profile <name|id> run it on this profile from now on (it already runs where it did)
|
|
28
|
+
--bot <name> on this bot only (repeat for more; default: every bot)
|
|
29
|
+
--settings <file.json> setting values for that profile
|
|
25
30
|
|
|
26
31
|
Environment: MINEBOT_API_URL overrides the API (default ${apiUrl()}).`;
|
|
27
32
|
function option(args, name) {
|
|
@@ -95,6 +100,8 @@ async function main(argv) {
|
|
|
95
100
|
return check();
|
|
96
101
|
case "build":
|
|
97
102
|
return build();
|
|
103
|
+
case "deploy":
|
|
104
|
+
return deploy({ profile: option(args, "--profile"), bots: options(args, "--bot"), settingsFile: option(args, "--settings") });
|
|
98
105
|
case undefined:
|
|
99
106
|
case "help":
|
|
100
107
|
case "--help":
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
interface WireResponse {
|
|
2
|
+
status: number;
|
|
3
|
+
statusText: string;
|
|
4
|
+
url: string;
|
|
5
|
+
redirected: boolean;
|
|
6
|
+
headers: [string, string][];
|
|
7
|
+
body: string;
|
|
8
|
+
bodyBase64: boolean;
|
|
9
|
+
}
|
|
10
|
+
type HeadersInit = Record<string, string> | [string, string][] | HostedHeaders;
|
|
11
|
+
/** Case-insensitive header names, as in browsers and Node. */
|
|
12
|
+
export declare class HostedHeaders {
|
|
13
|
+
private readonly map;
|
|
14
|
+
constructor(init?: HeadersInit);
|
|
15
|
+
append(name: string, value: string): void;
|
|
16
|
+
set(name: string, value: string): void;
|
|
17
|
+
get(name: string): string | null;
|
|
18
|
+
has(name: string): boolean;
|
|
19
|
+
delete(name: string): void;
|
|
20
|
+
forEach(callback: (value: string, name: string) => void): void;
|
|
21
|
+
entries(): IterableIterator<[string, string]>;
|
|
22
|
+
keys(): IterableIterator<string>;
|
|
23
|
+
values(): IterableIterator<string>;
|
|
24
|
+
[Symbol.iterator](): IterableIterator<[string, string]>;
|
|
25
|
+
}
|
|
26
|
+
/** The parts of a Response plugins use: status, headers and the body as text, JSON or bytes (once). */
|
|
27
|
+
export declare class HostedResponse {
|
|
28
|
+
private readonly wire;
|
|
29
|
+
readonly status: number;
|
|
30
|
+
readonly statusText: string;
|
|
31
|
+
readonly ok: boolean;
|
|
32
|
+
readonly url: string;
|
|
33
|
+
readonly redirected: boolean;
|
|
34
|
+
readonly headers: HostedHeaders;
|
|
35
|
+
readonly type = "basic";
|
|
36
|
+
private used;
|
|
37
|
+
constructor(wire: WireResponse);
|
|
38
|
+
get bodyUsed(): boolean;
|
|
39
|
+
private take;
|
|
40
|
+
text(): Promise<string>;
|
|
41
|
+
json(): Promise<unknown>;
|
|
42
|
+
bytes(): Promise<Uint8Array>;
|
|
43
|
+
arrayBuffer(): Promise<ArrayBuffer>;
|
|
44
|
+
clone(): HostedResponse;
|
|
45
|
+
}
|
|
46
|
+
/** Installs fetch, Headers and Response; returns what the runner calls with each outcome. */
|
|
47
|
+
export declare function installFetch(g: Record<string, unknown>): (id: number, outcome: string) => void;
|
|
48
|
+
export declare function base64Encode(bytes: Uint8Array): string;
|
|
49
|
+
export declare function base64Decode(text: string): Uint8Array;
|
|
50
|
+
export declare function utf8Encode(text: string): Uint8Array;
|
|
51
|
+
/** UTF-8 to text; malformed sequences become U+FFFD. */
|
|
52
|
+
export declare function utf8Decode(bytes: Uint8Array): string;
|
|
53
|
+
export {};
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
// fetch() for hosted plugins: the standard API on top of the runner's __host_fetch. The runner checks and makes
|
|
2
|
+
// every request (allowed hosts and URL settings, HTTPS, public addresses, sizes, rates) and logs it in the plugin
|
|
3
|
+
// console; this side only shapes the request and gives back a Response. QuickJS has no fetch, Headers or
|
|
4
|
+
// Response of its own, so minimal ones are defined here.
|
|
5
|
+
import { PluginError } from "../errors.js";
|
|
6
|
+
/** Case-insensitive header names, as in browsers and Node. */
|
|
7
|
+
export class HostedHeaders {
|
|
8
|
+
map = new Map();
|
|
9
|
+
constructor(init) {
|
|
10
|
+
if (!init)
|
|
11
|
+
return;
|
|
12
|
+
if (init instanceof HostedHeaders)
|
|
13
|
+
init.forEach((value, name) => this.append(name, value));
|
|
14
|
+
else if (Array.isArray(init))
|
|
15
|
+
for (const [name, value] of init)
|
|
16
|
+
this.append(name, value);
|
|
17
|
+
else
|
|
18
|
+
for (const name of Object.keys(init))
|
|
19
|
+
this.append(name, init[name]);
|
|
20
|
+
}
|
|
21
|
+
append(name, value) {
|
|
22
|
+
const key = String(name).toLowerCase();
|
|
23
|
+
const list = this.map.get(key);
|
|
24
|
+
if (list)
|
|
25
|
+
list.push(String(value));
|
|
26
|
+
else
|
|
27
|
+
this.map.set(key, [String(value)]);
|
|
28
|
+
}
|
|
29
|
+
set(name, value) {
|
|
30
|
+
this.map.set(String(name).toLowerCase(), [String(value)]);
|
|
31
|
+
}
|
|
32
|
+
get(name) {
|
|
33
|
+
return this.map.get(String(name).toLowerCase())?.join(", ") ?? null;
|
|
34
|
+
}
|
|
35
|
+
has(name) {
|
|
36
|
+
return this.map.has(String(name).toLowerCase());
|
|
37
|
+
}
|
|
38
|
+
delete(name) {
|
|
39
|
+
this.map.delete(String(name).toLowerCase());
|
|
40
|
+
}
|
|
41
|
+
forEach(callback) {
|
|
42
|
+
for (const [name, values] of this.map)
|
|
43
|
+
callback(values.join(", "), name);
|
|
44
|
+
}
|
|
45
|
+
*entries() {
|
|
46
|
+
for (const [name, values] of this.map)
|
|
47
|
+
yield [name, values.join(", ")];
|
|
48
|
+
}
|
|
49
|
+
keys() {
|
|
50
|
+
return this.map.keys();
|
|
51
|
+
}
|
|
52
|
+
*values() {
|
|
53
|
+
for (const values of this.map.values())
|
|
54
|
+
yield values.join(", ");
|
|
55
|
+
}
|
|
56
|
+
[Symbol.iterator]() {
|
|
57
|
+
return this.entries();
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/** The parts of a Response plugins use: status, headers and the body as text, JSON or bytes (once). */
|
|
61
|
+
export class HostedResponse {
|
|
62
|
+
wire;
|
|
63
|
+
status;
|
|
64
|
+
statusText;
|
|
65
|
+
ok;
|
|
66
|
+
url;
|
|
67
|
+
redirected;
|
|
68
|
+
headers;
|
|
69
|
+
type = "basic";
|
|
70
|
+
used = false;
|
|
71
|
+
constructor(wire) {
|
|
72
|
+
this.wire = wire;
|
|
73
|
+
this.status = wire.status;
|
|
74
|
+
this.statusText = wire.statusText;
|
|
75
|
+
this.ok = wire.status >= 200 && wire.status < 300;
|
|
76
|
+
this.url = wire.url;
|
|
77
|
+
this.redirected = wire.redirected;
|
|
78
|
+
this.headers = new HostedHeaders(wire.headers);
|
|
79
|
+
}
|
|
80
|
+
get bodyUsed() {
|
|
81
|
+
return this.used;
|
|
82
|
+
}
|
|
83
|
+
take() {
|
|
84
|
+
if (this.used)
|
|
85
|
+
throw new TypeError("The response body was already read");
|
|
86
|
+
this.used = true;
|
|
87
|
+
return this.wire;
|
|
88
|
+
}
|
|
89
|
+
async text() {
|
|
90
|
+
const w = this.take();
|
|
91
|
+
return w.bodyBase64 ? utf8Decode(base64Decode(w.body)) : w.body;
|
|
92
|
+
}
|
|
93
|
+
async json() {
|
|
94
|
+
return JSON.parse(await this.text());
|
|
95
|
+
}
|
|
96
|
+
async bytes() {
|
|
97
|
+
const w = this.take();
|
|
98
|
+
return w.bodyBase64 ? base64Decode(w.body) : utf8Encode(w.body);
|
|
99
|
+
}
|
|
100
|
+
async arrayBuffer() {
|
|
101
|
+
const b = await this.bytes();
|
|
102
|
+
return b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength);
|
|
103
|
+
}
|
|
104
|
+
clone() {
|
|
105
|
+
if (this.used)
|
|
106
|
+
throw new TypeError("The response body was already read");
|
|
107
|
+
return new HostedResponse(this.wire);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/** Installs fetch, Headers and Response; returns what the runner calls with each outcome. */
|
|
111
|
+
export function installFetch(g) {
|
|
112
|
+
const pending = new Map();
|
|
113
|
+
let next = 1;
|
|
114
|
+
g.Headers ??= HostedHeaders;
|
|
115
|
+
g.Response ??= HostedResponse;
|
|
116
|
+
g.fetch = (input, init = {}) => {
|
|
117
|
+
const url = typeof input === "string" ? input : (input?.href ?? input?.url ?? String(input));
|
|
118
|
+
const method = (init.method ?? (typeof input === "object" ? input?.method : undefined) ?? "GET").toUpperCase();
|
|
119
|
+
const headers = [...new HostedHeaders(init.headers ?? (typeof input === "object" ? input?.headers : undefined))];
|
|
120
|
+
let body = null;
|
|
121
|
+
let bodyBase64 = false;
|
|
122
|
+
if (init.body !== undefined && init.body !== null) {
|
|
123
|
+
if (typeof init.body === "string")
|
|
124
|
+
body = init.body;
|
|
125
|
+
else if (init.body instanceof Uint8Array)
|
|
126
|
+
[body, bodyBase64] = [base64Encode(init.body), true];
|
|
127
|
+
else if (init.body instanceof ArrayBuffer)
|
|
128
|
+
[body, bodyBase64] = [base64Encode(new Uint8Array(init.body)), true];
|
|
129
|
+
else
|
|
130
|
+
return Promise.reject(new TypeError("fetch: the body must be a string (e.g. JSON.stringify(...)) or bytes"));
|
|
131
|
+
}
|
|
132
|
+
const id = next++;
|
|
133
|
+
return new Promise((resolve, reject) => {
|
|
134
|
+
pending.set(id, { resolve, reject });
|
|
135
|
+
__host_fetch(id, JSON.stringify({ url, method, headers, body, bodyBase64 }));
|
|
136
|
+
});
|
|
137
|
+
};
|
|
138
|
+
return (id, text) => {
|
|
139
|
+
const p = pending.get(id);
|
|
140
|
+
if (!p)
|
|
141
|
+
return;
|
|
142
|
+
pending.delete(id);
|
|
143
|
+
const outcome = JSON.parse(text);
|
|
144
|
+
if (outcome.ok)
|
|
145
|
+
p.resolve(new HostedResponse(outcome.response));
|
|
146
|
+
else if (outcome.code === "NetworkDenied")
|
|
147
|
+
p.reject(new PluginError("NetworkDenied", outcome.message));
|
|
148
|
+
else
|
|
149
|
+
p.reject(new TypeError(outcome.message));
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
// ---- bytes, without TextEncoder or atob (QuickJS has neither) ----
|
|
153
|
+
const B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
154
|
+
export function base64Encode(bytes) {
|
|
155
|
+
let out = "";
|
|
156
|
+
for (let i = 0; i < bytes.length; i += 3) {
|
|
157
|
+
const n = (bytes[i] << 16) | ((bytes[i + 1] ?? 0) << 8) | (bytes[i + 2] ?? 0);
|
|
158
|
+
out += B64[(n >> 18) & 63] + B64[(n >> 12) & 63] + (i + 1 < bytes.length ? B64[(n >> 6) & 63] : "=") + (i + 2 < bytes.length ? B64[n & 63] : "=");
|
|
159
|
+
}
|
|
160
|
+
return out;
|
|
161
|
+
}
|
|
162
|
+
export function base64Decode(text) {
|
|
163
|
+
const clean = text.replace(/[^A-Za-z0-9+/]/g, "");
|
|
164
|
+
const out = new Uint8Array(Math.floor((clean.length * 3) / 4));
|
|
165
|
+
let o = 0;
|
|
166
|
+
for (let i = 0; i < clean.length; i += 4) {
|
|
167
|
+
const n = (B64.indexOf(clean[i]) << 18) | (B64.indexOf(clean[i + 1]) << 12) | ((B64.indexOf(clean[i + 2] ?? "A") & 63) << 6) | (B64.indexOf(clean[i + 3] ?? "A") & 63);
|
|
168
|
+
out[o++] = (n >> 16) & 255;
|
|
169
|
+
if (i + 2 < clean.length)
|
|
170
|
+
out[o++] = (n >> 8) & 255;
|
|
171
|
+
if (i + 3 < clean.length)
|
|
172
|
+
out[o++] = n & 255;
|
|
173
|
+
}
|
|
174
|
+
return out.subarray(0, o);
|
|
175
|
+
}
|
|
176
|
+
export function utf8Encode(text) {
|
|
177
|
+
const out = [];
|
|
178
|
+
for (const ch of text) {
|
|
179
|
+
const c = ch.codePointAt(0);
|
|
180
|
+
if (c < 0x80)
|
|
181
|
+
out.push(c);
|
|
182
|
+
else if (c < 0x800)
|
|
183
|
+
out.push(0xc0 | (c >> 6), 0x80 | (c & 63));
|
|
184
|
+
else if (c < 0x10000)
|
|
185
|
+
out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));
|
|
186
|
+
else
|
|
187
|
+
out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 63), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));
|
|
188
|
+
}
|
|
189
|
+
return new Uint8Array(out);
|
|
190
|
+
}
|
|
191
|
+
/** UTF-8 to text; malformed sequences become U+FFFD. */
|
|
192
|
+
export function utf8Decode(bytes) {
|
|
193
|
+
let out = "";
|
|
194
|
+
let i = 0;
|
|
195
|
+
while (i < bytes.length) {
|
|
196
|
+
const b = bytes[i];
|
|
197
|
+
const need = b < 0x80 ? 0 : (b & 0xe0) === 0xc0 ? 1 : (b & 0xf0) === 0xe0 ? 2 : (b & 0xf8) === 0xf0 ? 3 : -1;
|
|
198
|
+
let c = need <= 0 ? b : b & (0xff >> (need + 2));
|
|
199
|
+
let ok = need >= 0 && i + need < bytes.length;
|
|
200
|
+
for (let k = 1; ok && k <= need; k++) {
|
|
201
|
+
const n = bytes[i + k];
|
|
202
|
+
if ((n & 0xc0) !== 0x80)
|
|
203
|
+
ok = false;
|
|
204
|
+
else
|
|
205
|
+
c = (c << 6) | (n & 63);
|
|
206
|
+
}
|
|
207
|
+
if (!ok || c > 0x10ffff) {
|
|
208
|
+
out += "\uFFFD";
|
|
209
|
+
i++;
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
out += String.fromCodePoint(c);
|
|
213
|
+
i += need + 1;
|
|
214
|
+
}
|
|
215
|
+
return out;
|
|
216
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { PluginRuntime } from "../runtime/runtime.js";
|
|
2
|
+
import { installFetch } from "./fetch.js";
|
|
3
|
+
function describe(error) {
|
|
4
|
+
return error instanceof Error ? (error.stack ?? error.message) : String(error);
|
|
5
|
+
}
|
|
6
|
+
/** Installs the hosted environment and waits for the runner to start the plugin. */
|
|
7
|
+
export function serveHosted(plugin) {
|
|
8
|
+
const g = globalThis;
|
|
9
|
+
const timers = new Map();
|
|
10
|
+
let nextTimer = 1;
|
|
11
|
+
g.setTimeout = (fn, ms) => {
|
|
12
|
+
const id = nextTimer++;
|
|
13
|
+
timers.set(id, fn);
|
|
14
|
+
__host_timer_set(id, Math.max(0, Math.floor(Number(ms) || 0)));
|
|
15
|
+
return id;
|
|
16
|
+
};
|
|
17
|
+
g.clearTimeout = (id) => {
|
|
18
|
+
if (timers.delete(id))
|
|
19
|
+
__host_timer_clear(id);
|
|
20
|
+
};
|
|
21
|
+
const fetchDone = installFetch(g);
|
|
22
|
+
const transport = {
|
|
23
|
+
send: text => __host_send(text),
|
|
24
|
+
close: (code, reason) => __host_close(code ?? 1000, reason ?? ""),
|
|
25
|
+
onmessage: null,
|
|
26
|
+
onclose: null,
|
|
27
|
+
};
|
|
28
|
+
// console.* goes to the plugin console once connected (before that, to the runner's log), as it would show
|
|
29
|
+
// in the terminal under `minebot dev`.
|
|
30
|
+
let connected = false;
|
|
31
|
+
const write = (level, args) => {
|
|
32
|
+
const message = args.map(a => (typeof a === "string" ? a : a instanceof Error ? describe(a) : safeJson(a))).join(" ");
|
|
33
|
+
const trimmed = message.length > 4000 ? `${message.slice(0, 4000)}…` : message;
|
|
34
|
+
if (connected)
|
|
35
|
+
__host_send(JSON.stringify({ type: "log", bot: null, level, message: trimmed }));
|
|
36
|
+
else
|
|
37
|
+
__host_log(level === "error" ? 2 : level === "warn" ? 1 : 0, trimmed);
|
|
38
|
+
};
|
|
39
|
+
g.console = {
|
|
40
|
+
log: (...a) => write("info", a),
|
|
41
|
+
info: (...a) => write("info", a),
|
|
42
|
+
debug: (...a) => write("debug", a),
|
|
43
|
+
warn: (...a) => write("warn", a),
|
|
44
|
+
error: (...a) => write("error", a),
|
|
45
|
+
};
|
|
46
|
+
const entry = {
|
|
47
|
+
start(text) {
|
|
48
|
+
const config = JSON.parse(text);
|
|
49
|
+
PluginRuntime.connect(plugin, transport, config.token, config.version).then(() => (connected = true), error => {
|
|
50
|
+
__host_log(2, `Couldn't start: ${describe(error)}`);
|
|
51
|
+
transport.close(1000, "Rejected");
|
|
52
|
+
});
|
|
53
|
+
},
|
|
54
|
+
receive(frame) {
|
|
55
|
+
transport.onmessage?.(frame);
|
|
56
|
+
},
|
|
57
|
+
timer(id) {
|
|
58
|
+
const fn = timers.get(id);
|
|
59
|
+
if (!fn)
|
|
60
|
+
return;
|
|
61
|
+
timers.delete(id);
|
|
62
|
+
fn();
|
|
63
|
+
},
|
|
64
|
+
closed(code, reason) {
|
|
65
|
+
connected = false;
|
|
66
|
+
transport.onclose?.(code, reason);
|
|
67
|
+
},
|
|
68
|
+
fetchDone(id, outcome) {
|
|
69
|
+
fetchDone(id, outcome);
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
g.__minebot = entry;
|
|
73
|
+
}
|
|
74
|
+
function safeJson(value) {
|
|
75
|
+
try {
|
|
76
|
+
return JSON.stringify(value) ?? String(value);
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
return String(value);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
@@ -4,7 +4,7 @@ import type { ProfileBot } from "../api.js";
|
|
|
4
4
|
import { Connection, type CallOutcome, type Transport } from "./connection.js";
|
|
5
5
|
import { type HandleHost } from "./handles.js";
|
|
6
6
|
import { Scope } from "./scope.js";
|
|
7
|
-
export declare const SDK_VERSION = "0.
|
|
7
|
+
export declare const SDK_VERSION = "0.2.0";
|
|
8
8
|
export type LogLevel = "debug" | "info" | "warn" | "error";
|
|
9
9
|
export interface RuntimeOptions {
|
|
10
10
|
/** Called for every log line, warning and statistic, e.g. to print them under `minebot dev`. */
|
package/dist/runtime/runtime.js
CHANGED
|
@@ -4,7 +4,7 @@ import { Connection } from "./connection.js";
|
|
|
4
4
|
import { BotHandle, ProfileBotHandle, ProfileHandle } from "./handles.js";
|
|
5
5
|
import { Scope } from "./scope.js";
|
|
6
6
|
import { createStorage } from "./storage-runtime.js";
|
|
7
|
-
export const SDK_VERSION = "0.
|
|
7
|
+
export const SDK_VERSION = "0.2.0";
|
|
8
8
|
/** Builds the manifest the container checks, from the plugin's definition. */
|
|
9
9
|
export function buildManifest(plugin, version) {
|
|
10
10
|
const d = plugin.definition;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@minecraftbot-com/plugin",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Write MineBot plugins in TypeScript: typed bot API, enums for every block, item and event, and the minebot CLI.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"publishConfig": {
|
|
@@ -25,6 +25,11 @@
|
|
|
25
25
|
"types": "./dist/host/index.d.ts",
|
|
26
26
|
"minebot-source": "./src/host/index.ts",
|
|
27
27
|
"default": "./dist/host/index.js"
|
|
28
|
+
},
|
|
29
|
+
"./hosted": {
|
|
30
|
+
"types": "./dist/hosted/index.d.ts",
|
|
31
|
+
"minebot-source": "./src/hosted/index.ts",
|
|
32
|
+
"default": "./dist/hosted/index.js"
|
|
28
33
|
}
|
|
29
34
|
},
|
|
30
35
|
"bin": {
|
package/src/api.ts
CHANGED
|
@@ -47,7 +47,10 @@ export interface PlayerInfo {
|
|
|
47
47
|
export interface ItemStack {
|
|
48
48
|
readonly item: Item;
|
|
49
49
|
readonly count: number;
|
|
50
|
-
/**
|
|
50
|
+
/**
|
|
51
|
+
* Where the stack is, numbered as Minecraft's commands do (`/item replace entity <bot> container.N`): the hotbar
|
|
52
|
+
* 0-8, the inventory 9-35, armor 100 (feet) to 103 (head), the offhand 98. A container's items: its own slot from 0.
|
|
53
|
+
*/
|
|
51
54
|
readonly slot: number;
|
|
52
55
|
/** The custom name, if renamed in an anvil. */
|
|
53
56
|
readonly name: string | null;
|
package/src/cli/api.ts
CHANGED
|
@@ -1,79 +1,105 @@
|
|
|
1
|
-
import { hostname } from "node:os";
|
|
2
|
-
import { apiUrl, readCredentials } from "./config.js";
|
|
3
|
-
import { fail } from "./output.js";
|
|
4
|
-
|
|
5
|
-
export interface DeviceStart {
|
|
6
|
-
deviceCode: string;
|
|
7
|
-
userCode: string;
|
|
8
|
-
verificationUrl: string;
|
|
9
|
-
interval: number;
|
|
10
|
-
expiresIn: number;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
export interface ProfileEntry {
|
|
14
|
-
id: string;
|
|
15
|
-
name: string;
|
|
16
|
-
running: boolean;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
export interface DevToken {
|
|
20
|
-
token: string;
|
|
21
|
-
address: string;
|
|
22
|
-
profileId: string;
|
|
23
|
-
profileName: string;
|
|
24
|
-
expiresAt: string;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
async function request<T>(method: string, path: string, body?: unknown, auth = false): Promise<{ status: number; data: T | { message?: string } }> {
|
|
28
|
-
const headers: Record<string, string> = { "content-type": "application/json", "user-agent": "minebot-cli" };
|
|
29
|
-
if (auth) {
|
|
30
|
-
const credentials = readCredentials();
|
|
31
|
-
if (!credentials) fail("You're not signed in.", "Run `minebot login` first.");
|
|
32
|
-
headers.authorization = `Bearer ${credentials.token}`;
|
|
33
|
-
}
|
|
34
|
-
let response: Response;
|
|
35
|
-
try {
|
|
36
|
-
response = await fetch(`${apiUrl()}${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
|
|
37
|
-
} catch (e) {
|
|
38
|
-
fail(`Couldn't reach ${apiUrl()}: ${(e as Error).message}`, "Check your internet connection, or MINEBOT_API_URL if you set it.");
|
|
39
|
-
}
|
|
40
|
-
const text = await response.text();
|
|
41
|
-
let data: unknown = {};
|
|
42
|
-
try {
|
|
43
|
-
data = text ? JSON.parse(text) : {};
|
|
44
|
-
} catch {
|
|
45
|
-
data = { message: text.slice(0, 200) };
|
|
46
|
-
}
|
|
47
|
-
return { status: response.status, data: data as T };
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
function message(data: unknown, fallback: string): string {
|
|
51
|
-
return (data as { message?: string })?.message ?? fallback;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
export async function startDevice(): Promise<DeviceStart> {
|
|
55
|
-
const r = await request<DeviceStart>("POST", "/plugins/cli/device", { clientName: `minebot CLI on ${hostname()}` });
|
|
56
|
-
if (r.status !== 200) fail(message(r.data, `Sign-in failed (HTTP ${r.status})`));
|
|
57
|
-
return r.data as DeviceStart;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
export async function pollDevice(deviceCode: string): Promise<{ status: string; token: string | null }> {
|
|
61
|
-
const r = await request<{ status: string; token: string | null }>("POST", "/plugins/cli/token", { deviceCode });
|
|
62
|
-
if (r.status !== 200) return { status: "pending", token: null };
|
|
63
|
-
return r.data as { status: string; token: string | null };
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
export async function listProfiles(): Promise<ProfileEntry[]> {
|
|
67
|
-
const r = await request<ProfileEntry[]>("GET", "/plugins/cli/profiles", undefined, true);
|
|
68
|
-
if (r.status === 401) fail(message(r.data, "Your sign-in expired."), "Run `minebot login` again.");
|
|
69
|
-
if (r.status !== 200) fail(message(r.data, `Couldn't list your profiles (HTTP ${r.status})`));
|
|
70
|
-
return r.data as ProfileEntry[];
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
export
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
1
|
+
import { hostname } from "node:os";
|
|
2
|
+
import { apiUrl, readCredentials } from "./config.js";
|
|
3
|
+
import { fail } from "./output.js";
|
|
4
|
+
|
|
5
|
+
export interface DeviceStart {
|
|
6
|
+
deviceCode: string;
|
|
7
|
+
userCode: string;
|
|
8
|
+
verificationUrl: string;
|
|
9
|
+
interval: number;
|
|
10
|
+
expiresIn: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface ProfileEntry {
|
|
14
|
+
id: string;
|
|
15
|
+
name: string;
|
|
16
|
+
running: boolean;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface DevToken {
|
|
20
|
+
token: string;
|
|
21
|
+
address: string;
|
|
22
|
+
profileId: string;
|
|
23
|
+
profileName: string;
|
|
24
|
+
expiresAt: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function request<T>(method: string, path: string, body?: unknown, auth = false): Promise<{ status: number; data: T | { message?: string } }> {
|
|
28
|
+
const headers: Record<string, string> = { "content-type": "application/json", "user-agent": "minebot-cli" };
|
|
29
|
+
if (auth) {
|
|
30
|
+
const credentials = readCredentials();
|
|
31
|
+
if (!credentials) fail("You're not signed in.", "Run `minebot login` first.");
|
|
32
|
+
headers.authorization = `Bearer ${credentials.token}`;
|
|
33
|
+
}
|
|
34
|
+
let response: Response;
|
|
35
|
+
try {
|
|
36
|
+
response = await fetch(`${apiUrl()}${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
|
|
37
|
+
} catch (e) {
|
|
38
|
+
fail(`Couldn't reach ${apiUrl()}: ${(e as Error).message}`, "Check your internet connection, or MINEBOT_API_URL if you set it.");
|
|
39
|
+
}
|
|
40
|
+
const text = await response.text();
|
|
41
|
+
let data: unknown = {};
|
|
42
|
+
try {
|
|
43
|
+
data = text ? JSON.parse(text) : {};
|
|
44
|
+
} catch {
|
|
45
|
+
data = { message: text.slice(0, 200) };
|
|
46
|
+
}
|
|
47
|
+
return { status: response.status, data: data as T };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function message(data: unknown, fallback: string): string {
|
|
51
|
+
return (data as { message?: string })?.message ?? fallback;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export async function startDevice(): Promise<DeviceStart> {
|
|
55
|
+
const r = await request<DeviceStart>("POST", "/plugins/cli/device", { clientName: `minebot CLI on ${hostname()}` });
|
|
56
|
+
if (r.status !== 200) fail(message(r.data, `Sign-in failed (HTTP ${r.status})`));
|
|
57
|
+
return r.data as DeviceStart;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function pollDevice(deviceCode: string): Promise<{ status: string; token: string | null }> {
|
|
61
|
+
const r = await request<{ status: string; token: string | null }>("POST", "/plugins/cli/token", { deviceCode });
|
|
62
|
+
if (r.status !== 200) return { status: "pending", token: null };
|
|
63
|
+
return r.data as { status: string; token: string | null };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function listProfiles(): Promise<ProfileEntry[]> {
|
|
67
|
+
const r = await request<ProfileEntry[]>("GET", "/plugins/cli/profiles", undefined, true);
|
|
68
|
+
if (r.status === 401) fail(message(r.data, "Your sign-in expired."), "Run `minebot login` again.");
|
|
69
|
+
if (r.status !== 200) fail(message(r.data, `Couldn't list your profiles (HTTP ${r.status})`));
|
|
70
|
+
return r.data as ProfileEntry[];
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export interface DeployRequest {
|
|
74
|
+
manifest: unknown;
|
|
75
|
+
bundle: string;
|
|
76
|
+
sdk: string;
|
|
77
|
+
profile?: string;
|
|
78
|
+
settings?: Record<string, unknown>;
|
|
79
|
+
bots?: string[];
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface DeployResult {
|
|
83
|
+
pluginId: string;
|
|
84
|
+
name: string;
|
|
85
|
+
version: string;
|
|
86
|
+
bundleHash: string;
|
|
87
|
+
newVersion: boolean;
|
|
88
|
+
installations: { id: string; profileId: string; profileName: string; enabled: boolean }[];
|
|
89
|
+
dashboard: string;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export async function deployBundle(body: DeployRequest): Promise<DeployResult> {
|
|
93
|
+
const r = await request<DeployResult>("POST", "/plugins/cli/deploy", body, true);
|
|
94
|
+
if (r.status === 401) fail(message(r.data, "Your sign-in expired."), "Run `minebot login` again.");
|
|
95
|
+
if (r.status !== 200) fail(message(r.data, `The deploy failed (HTTP ${r.status})`));
|
|
96
|
+
return r.data as DeployResult;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export async function devToken(profileId: string): Promise<DevToken> {
|
|
100
|
+
const r = await request<DevToken>("POST", "/plugins/cli/dev-token", { profileId }, true);
|
|
101
|
+
if (r.status === 401) fail(message(r.data, "Your sign-in expired."), "Run `minebot login` again.");
|
|
102
|
+
if (r.status === 409) fail(message(r.data, "The profile isn't running."), "Start it on the dashboard, then run `minebot dev` again.");
|
|
103
|
+
if (r.status !== 200) fail(message(r.data, `Couldn't get a dev token (HTTP ${r.status})`));
|
|
104
|
+
return r.data as DevToken;
|
|
105
|
+
}
|