@minecraftbot-com/plugin 0.0.0-stage → 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.
Files changed (137) hide show
  1. package/AGENTS.md +188 -0
  2. package/README.md +47 -3
  3. package/dist/api.d.ts +354 -0
  4. package/dist/api.js +2 -0
  5. package/dist/cli/api.d.ts +49 -0
  6. package/dist/cli/api.js +69 -0
  7. package/dist/cli/build.d.ts +24 -0
  8. package/dist/cli/build.js +72 -0
  9. package/dist/cli/check.d.ts +17 -0
  10. package/dist/cli/check.js +99 -0
  11. package/dist/cli/config.d.ts +11 -0
  12. package/dist/cli/config.js +38 -0
  13. package/dist/cli/create.d.ts +2 -0
  14. package/dist/cli/create.js +39 -0
  15. package/dist/cli/deploy.d.ts +13 -0
  16. package/dist/cli/deploy.js +51 -0
  17. package/dist/cli/dev-mcp.d.ts +36 -0
  18. package/dist/cli/dev-mcp.js +101 -0
  19. package/dist/cli/dev.d.ts +15 -0
  20. package/dist/cli/dev.js +261 -0
  21. package/dist/cli/fetch-guard.d.ts +7 -0
  22. package/dist/cli/fetch-guard.js +66 -0
  23. package/dist/cli/main.d.ts +2 -0
  24. package/dist/cli/main.js +119 -0
  25. package/dist/cli/mcp.d.ts +24 -0
  26. package/dist/cli/mcp.js +136 -0
  27. package/dist/cli/output.d.ts +11 -0
  28. package/dist/cli/output.js +25 -0
  29. package/dist/cli/test.d.ts +2 -0
  30. package/dist/cli/test.js +39 -0
  31. package/dist/errors.d.ts +22 -0
  32. package/dist/errors.js +35 -0
  33. package/dist/generated/block-states.d.ts +4087 -0
  34. package/dist/generated/block-states.js +2 -0
  35. package/dist/generated/blocks.d.ts +1289 -0
  36. package/dist/generated/blocks.js +1291 -0
  37. package/dist/generated/contracts.d.ts +304 -0
  38. package/dist/generated/contracts.js +327 -0
  39. package/dist/generated/effects.d.ts +43 -0
  40. package/dist/generated/effects.js +45 -0
  41. package/dist/generated/entities.d.ts +164 -0
  42. package/dist/generated/entities.js +166 -0
  43. package/dist/generated/items.d.ts +1661 -0
  44. package/dist/generated/items.js +1663 -0
  45. package/dist/generated/operations.d.ts +7 -0
  46. package/dist/generated/operations.js +65 -0
  47. package/dist/generated/permission-labels.d.ts +3 -0
  48. package/dist/generated/permission-labels.js +17 -0
  49. package/dist/generated/version.d.ts +2 -0
  50. package/dist/generated/version.js +3 -0
  51. package/dist/host/index.d.ts +7 -0
  52. package/dist/host/index.js +5 -0
  53. package/dist/hosted/fetch.d.ts +53 -0
  54. package/dist/hosted/fetch.js +216 -0
  55. package/dist/hosted/index.d.ts +3 -0
  56. package/dist/hosted/index.js +81 -0
  57. package/dist/index.d.ts +19 -0
  58. package/dist/index.js +13 -0
  59. package/dist/permissions.d.ts +11 -0
  60. package/dist/permissions.js +18 -0
  61. package/dist/plugin.d.ts +86 -0
  62. package/dist/plugin.js +26 -0
  63. package/dist/protocol.d.ts +167 -0
  64. package/dist/protocol.js +4 -0
  65. package/dist/runtime/connection.d.ts +52 -0
  66. package/dist/runtime/connection.js +132 -0
  67. package/dist/runtime/handles.d.ts +95 -0
  68. package/dist/runtime/handles.js +289 -0
  69. package/dist/runtime/memory-transport.d.ts +6 -0
  70. package/dist/runtime/memory-transport.js +39 -0
  71. package/dist/runtime/runtime.d.ts +57 -0
  72. package/dist/runtime/runtime.js +265 -0
  73. package/dist/runtime/scope.d.ts +25 -0
  74. package/dist/runtime/scope.js +94 -0
  75. package/dist/runtime/storage-runtime.d.ts +10 -0
  76. package/dist/runtime/storage-runtime.js +131 -0
  77. package/dist/settings.d.ts +111 -0
  78. package/dist/settings.js +78 -0
  79. package/dist/storage.d.ts +78 -0
  80. package/dist/storage.js +24 -0
  81. package/dist/testing/fake-container.d.ts +175 -0
  82. package/dist/testing/fake-container.js +483 -0
  83. package/dist/testing/index.d.ts +37 -0
  84. package/dist/testing/index.js +54 -0
  85. package/dist/types.d.ts +65 -0
  86. package/dist/types.js +54 -0
  87. package/llms.txt +11 -0
  88. package/package.json +60 -4
  89. package/src/api.ts +337 -0
  90. package/src/cli/api.ts +105 -0
  91. package/src/cli/build.ts +83 -0
  92. package/src/cli/check.ts +104 -0
  93. package/src/cli/config.ts +48 -0
  94. package/src/cli/create.ts +38 -0
  95. package/src/cli/deploy.ts +60 -0
  96. package/src/cli/dev-mcp.ts +131 -0
  97. package/src/cli/dev.ts +272 -0
  98. package/src/cli/fetch-guard.ts +61 -0
  99. package/src/cli/main.ts +120 -0
  100. package/src/cli/mcp.ts +168 -0
  101. package/src/cli/output.ts +30 -0
  102. package/src/cli/test.ts +38 -0
  103. package/src/errors.ts +34 -0
  104. package/src/generated/block-states.ts +892 -0
  105. package/src/generated/blocks.ts +1291 -0
  106. package/src/generated/contracts.ts +329 -0
  107. package/src/generated/effects.ts +45 -0
  108. package/src/generated/entities.ts +166 -0
  109. package/src/generated/items.ts +1663 -0
  110. package/src/generated/operations.ts +69 -0
  111. package/src/generated/permission-labels.ts +19 -0
  112. package/src/generated/version.ts +3 -0
  113. package/src/host/index.ts +9 -0
  114. package/src/hosted/fetch.ts +224 -0
  115. package/src/hosted/index.ts +121 -0
  116. package/src/index.ts +34 -0
  117. package/src/permissions.ts +23 -0
  118. package/src/plugin.ts +105 -0
  119. package/src/protocol.ts +107 -0
  120. package/src/runtime/connection.ts +167 -0
  121. package/src/runtime/handles.ts +337 -0
  122. package/src/runtime/memory-transport.ts +41 -0
  123. package/src/runtime/runtime.ts +281 -0
  124. package/src/runtime/scope.ts +101 -0
  125. package/src/runtime/storage-runtime.ts +138 -0
  126. package/src/settings.ts +118 -0
  127. package/src/storage.ts +82 -0
  128. package/src/testing/fake-container.ts +571 -0
  129. package/src/testing/index.ts +70 -0
  130. package/src/types.ts +88 -0
  131. package/templates/basic/AGENTS.md +32 -0
  132. package/templates/basic/README.md +14 -0
  133. package/templates/basic/gitignore +3 -0
  134. package/templates/basic/package.json +19 -0
  135. package/templates/basic/src/index.ts +20 -0
  136. package/templates/basic/test/plugin.test.ts +14 -0
  137. package/templates/basic/tsconfig.json +14 -0
@@ -0,0 +1,281 @@
1
+ import { isStopped, PluginError } from "../errors.js";
2
+ import type { Logger, Stats, Warnings, DefinedPlugin } from "../plugin.js";
3
+ import type { BotInfo, DevOptions, Manifest, SettingSchema, WelcomeFrame } from "../protocol.js";
4
+ import { toPosition } from "../types.js";
5
+ import type { ProfileBot } from "../api.js";
6
+ import { Connection, type CallOutcome, type Transport } from "./connection.js";
7
+ import { BotHandle, ProfileBotHandle, ProfileHandle, type HandleHost } from "./handles.js";
8
+ import { Scope } from "./scope.js";
9
+ import { createStorage } from "./storage-runtime.js";
10
+
11
+ export const SDK_VERSION = "0.2.0";
12
+
13
+ export type LogLevel = "debug" | "info" | "warn" | "error";
14
+
15
+ export interface RuntimeOptions {
16
+ /** Called for every log line, warning and statistic, e.g. to print them under `minebot dev`. */
17
+ onLog?(level: LogLevel, message: string, bot: BotInfo | null): void;
18
+ /** Called once the connection ends. */
19
+ onClosed?(code: number, reason: string): void;
20
+ }
21
+
22
+ /** Builds the manifest the container checks, from the plugin's definition. */
23
+ export function buildManifest(plugin: DefinedPlugin, version: string): Manifest {
24
+ const d = plugin.definition;
25
+ const settings: Record<string, SettingSchema> = {};
26
+ for (const [key, setting] of Object.entries(d.settings ?? {})) settings[key] = setting.schema;
27
+ const storage: Manifest["storage"] = {};
28
+ for (const [key, entry] of Object.entries(d.storage ?? {})) storage[key] = entry.schema;
29
+ return {
30
+ name: d.name,
31
+ version,
32
+ permissions: [...new Set(d.permissions as readonly string[])],
33
+ exclusive: [...new Set((d.exclusive ?? []) as readonly string[])],
34
+ settings,
35
+ storage,
36
+ profile: typeof d.runProfile === "function",
37
+ };
38
+ }
39
+
40
+ function applyDefaults(manifest: Manifest, values: Record<string, unknown>): Record<string, unknown> {
41
+ const out: Record<string, unknown> = {};
42
+ for (const [key, schema] of Object.entries(manifest.settings)) {
43
+ const v = values[key];
44
+ out[key] = v === undefined || v === null ? schema.default : v;
45
+ if (schema.type === "position" && out[key]) out[key] = toPosition(out[key]);
46
+ }
47
+ return Object.freeze(out);
48
+ }
49
+
50
+ function describe(error: unknown): string {
51
+ if (error instanceof Error) return error.stack && !(error instanceof PluginError) ? error.stack : error.message;
52
+ return String(error);
53
+ }
54
+
55
+ /**
56
+ * Runs one plugin instance over a connection: starts `runProfile` and `run(bot)` when the container says so,
57
+ * stops them when it says so, and routes events to listeners.
58
+ */
59
+ export class PluginRuntime implements HandleHost {
60
+ private readonly root = new Scope();
61
+ private readonly botScopes = new Map<string, Scope>();
62
+ private profileScope: Scope | null = null;
63
+ private readonly bots = new Map<string, BotInfo>();
64
+ private readonly listeners = new Map<string, Set<(data: unknown) => unknown>>();
65
+ private readonly profileBots = new Map<string, ProfileBotHandle>();
66
+ private readonly stats = new Map<string, number>();
67
+
68
+ constructor(
69
+ private readonly plugin: DefinedPlugin,
70
+ private readonly manifest: Manifest,
71
+ private readonly connection: Connection,
72
+ readonly welcome: WelcomeFrame,
73
+ private readonly options: RuntimeOptions = {},
74
+ ) {
75
+ for (const bot of welcome.bots) this.bots.set(bot.id, bot);
76
+ connection.attach({
77
+ start: (bot, settings, version) => this.start(bot, settings, version),
78
+ stop: (bot, reason) => this.stop(bot, reason),
79
+ event: (bot, event, data) => this.dispatch(bot, event, data),
80
+ bots: frame => {
81
+ this.bots.clear();
82
+ for (const bot of frame.bots) this.bots.set(bot.id, bot);
83
+ },
84
+ dropped: count => this.emitLog("warn", `${count} events were dropped because the plugin didn't keep up`, null),
85
+ closed: (code, reason) => {
86
+ this.root.stop("Disconnected");
87
+ this.options.onClosed?.(code, reason);
88
+ },
89
+ });
90
+ }
91
+
92
+ /** Connects, sends hello and starts running once welcomed. Rejects if the container refuses. */
93
+ static async connect(plugin: DefinedPlugin, transport: Transport, token: string, version: string, options: RuntimeOptions = {}, dev?: DevOptions): Promise<PluginRuntime> {
94
+ const manifest = buildManifest(plugin, version);
95
+ const connection = new Connection(transport);
96
+ const welcome = await connection.open(token, manifest, SDK_VERSION, dev);
97
+ return new PluginRuntime(plugin, manifest, connection, welcome, options);
98
+ }
99
+
100
+ /** The profile's bots as the container last reported them. */
101
+ get currentBots(): BotInfo[] {
102
+ return [...this.bots.values()];
103
+ }
104
+
105
+ /** The bots `run(bot)` is currently running on. */
106
+ get runningBots(): string[] {
107
+ return [...this.botScopes.keys()];
108
+ }
109
+
110
+ /** Stops everything and closes the connection. */
111
+ close(): void {
112
+ this.root.stop("Disconnected");
113
+ this.connection.close();
114
+ }
115
+
116
+ // ---- HandleHost ----
117
+
118
+ call(scope: Scope, bot: string | null, op: string, args: Record<string, unknown> = {}): Promise<CallOutcome> {
119
+ return this.connection.call(scope, bot, op, args);
120
+ }
121
+
122
+ subscribe(scope: Scope, bot: string | null, event: string, listener: (data: unknown) => unknown): () => void {
123
+ scope.check();
124
+ const key = `${bot ?? ""}|${event}`;
125
+ let set = this.listeners.get(key);
126
+ if (!set) {
127
+ set = new Set();
128
+ this.listeners.set(key, set);
129
+ this.connection.send({ type: "subscribe", bot, event });
130
+ }
131
+ set.add(listener);
132
+ return scope.onStop(() => {
133
+ const current = this.listeners.get(key);
134
+ if (!current) return;
135
+ current.delete(listener);
136
+ if (current.size === 0) {
137
+ this.listeners.delete(key);
138
+ if (!this.root.stopped) this.connection.send({ type: "unsubscribe", bot, event });
139
+ }
140
+ });
141
+ }
142
+
143
+ botInfo(id: string): BotInfo | undefined {
144
+ return this.bots.get(id);
145
+ }
146
+
147
+ profileBot(id: string): ProfileBot {
148
+ let handle = this.profileBots.get(id);
149
+ if (!handle) {
150
+ handle = new ProfileBotHandle(this.profileScope ?? this.root, this, id);
151
+ this.profileBots.set(id, handle);
152
+ }
153
+ return handle;
154
+ }
155
+
156
+ logError(bot: string | null, error: unknown): void {
157
+ this.emitLog("error", describe(error), bot);
158
+ }
159
+
160
+ // ---- lifecycle ----
161
+
162
+ private start(bot: string | null, settingsFrame: Record<string, unknown>, version: string): void {
163
+ const settings = applyDefaults(this.manifest, settingsFrame);
164
+ const d = this.plugin.definition;
165
+
166
+ if (bot === null) {
167
+ if (!d.runProfile || this.profileScope) return;
168
+ const scope = this.root.child();
169
+ this.profileScope = scope;
170
+ this.profileBots.clear();
171
+ const profile = new ProfileHandle(scope, this, this.welcome.profile.id, this.welcome.profile.name, () => [...this.bots.values()]);
172
+ const context = this.context(scope, null, settings);
173
+ this.supervise(null, () => d.runProfile!(profile, context as any), scope);
174
+ return;
175
+ }
176
+
177
+ if (!d.run) return;
178
+ this.botScopes.get(bot)?.stop("Replaced");
179
+ const scope = this.root.child();
180
+ this.botScopes.set(bot, scope);
181
+ const handle = new BotHandle(scope, this, bot, version);
182
+ const context = this.context(scope, bot, settings);
183
+ this.supervise(bot, () => d.run!(handle, context as any), scope);
184
+ }
185
+
186
+ private stop(bot: string | null, reason: string): void {
187
+ if (bot === null) {
188
+ this.profileScope?.stop(reason);
189
+ this.profileScope = null;
190
+ this.profileBots.clear();
191
+ return;
192
+ }
193
+ this.botScopes.get(bot)?.stop(reason);
194
+ this.botScopes.delete(bot);
195
+ }
196
+
197
+ /** Runs `run`/`runProfile`. Returning keeps listeners alive until stopped; throwing ends the run and is reported. */
198
+ private supervise(bot: string | null, body: () => Promise<void>, scope: Scope): void {
199
+ Promise.resolve()
200
+ .then(body)
201
+ .catch(error => {
202
+ if (isStopped(error) || scope.stopped) return;
203
+ this.emitLog("error", describe(error), bot);
204
+ this.connection.send({ type: "done", bot, error: error instanceof Error ? error.message : String(error) });
205
+ scope.stop("Failed");
206
+ if (bot === null) this.profileScope = null;
207
+ else if (this.botScopes.get(bot) === scope) this.botScopes.delete(bot);
208
+ });
209
+ }
210
+
211
+ private context(scope: Scope, bot: string | null, settings: Record<string, unknown>) {
212
+ const log: Logger = {
213
+ debug: m => this.emitLog("debug", String(m), bot),
214
+ info: m => this.emitLog("info", String(m), bot),
215
+ warn: m => this.emitLog("warn", String(m), bot),
216
+ error: m => this.emitLog("error", m instanceof Error ? describe(m) : String(m), bot),
217
+ };
218
+ const statKey = (name: string) => `${bot ?? ""}|${name}`;
219
+ const stats: Stats = {
220
+ set: (name, value) => {
221
+ this.stats.set(statKey(name), value);
222
+ this.connection.send({ type: "stat", bot, key: name, value });
223
+ },
224
+ add: (name, amount = 1) => {
225
+ const value = (this.stats.get(statKey(name)) ?? 0) + amount;
226
+ this.stats.set(statKey(name), value);
227
+ this.connection.send({ type: "stat", bot, key: name, value });
228
+ },
229
+ };
230
+ const warnings: Warnings = {
231
+ set: (key, message) => this.connection.send({ type: "warning", bot, key, message }),
232
+ clear: key => this.connection.send({ type: "warning", bot, key, message: null }),
233
+ };
234
+ const botUuid = bot === null ? null : this.bots.get(bot)?.uuid ?? null;
235
+ const storage = createStorage(this.manifest.storage, (s, op, args) => this.connection.call(s, bot, op, args), scope, bot === null ? null : botUuid ?? bot);
236
+ return { settings, storage, log, stats, warnings };
237
+ }
238
+
239
+ private emitLog(level: LogLevel, message: string, bot: string | null): void {
240
+ const trimmed = message.length > 4000 ? `${message.slice(0, 4000)}…` : message;
241
+ this.connection.send({ type: "log", bot, level, message: trimmed });
242
+ this.options.onLog?.(level, trimmed, bot === null ? null : this.bots.get(bot) ?? null);
243
+ }
244
+
245
+ // ---- events ----
246
+
247
+ private dispatch(bot: string | null, event: string, data: unknown): void {
248
+ if (event === "__error") {
249
+ const e = data as { code: string; message: string };
250
+ this.emitLog("error", `${e.code}: ${e.message}`, null);
251
+ return;
252
+ }
253
+ const set = this.listeners.get(`${bot ?? ""}|${event}`);
254
+ if (!set) return;
255
+ const payload = this.decorate(data);
256
+ for (const listener of [...set]) {
257
+ try {
258
+ const r = listener(payload);
259
+ if (r && typeof (r as Promise<unknown>).then === "function") {
260
+ (r as Promise<unknown>).catch(error => {
261
+ if (!isStopped(error)) this.emitLog("error", describe(error), bot);
262
+ });
263
+ }
264
+ } catch (error) {
265
+ if (!isStopped(error)) this.emitLog("error", describe(error), bot);
266
+ }
267
+ }
268
+ }
269
+
270
+ /** Turns bot ids in event data into ProfileBot handles, and positions into Positions. */
271
+ private decorate(data: unknown): unknown {
272
+ if (!data || typeof data !== "object") return data;
273
+ const out: Record<string, unknown> = { ...(data as Record<string, unknown>) };
274
+ if (typeof out.botId === "string") {
275
+ out.bot = this.profileBot(out.botId);
276
+ delete out.botId;
277
+ }
278
+ if (out.position && typeof out.position === "object") out.position = toPosition(out.position);
279
+ return Object.freeze(out);
280
+ }
281
+ }
@@ -0,0 +1,101 @@
1
+ import { StoppedError } from "../errors.js";
2
+
3
+ /**
4
+ * A lifetime: one run(bot), one runProfile, or the whole plugin. Everything started inside it (calls,
5
+ * listeners, timers, child scopes) ends when it stops, so plugin code never needs cancellation plumbing.
6
+ */
7
+ export class Scope {
8
+ private readonly cleanups = new Set<() => void>();
9
+ private readonly children = new Set<Scope>();
10
+ private stoppedReason: string | null = null;
11
+
12
+ constructor(private readonly parent: Scope | null = null) {
13
+ parent?.children.add(this);
14
+ }
15
+
16
+ get stopped(): boolean {
17
+ return this.stoppedReason !== null;
18
+ }
19
+
20
+ get reason(): string | null {
21
+ return this.stoppedReason;
22
+ }
23
+
24
+ /** Throws StoppedError if this scope has stopped. */
25
+ check(): void {
26
+ if (this.stoppedReason !== null) throw new StoppedError(this.stoppedReason);
27
+ }
28
+
29
+ child(): Scope {
30
+ this.check();
31
+ return new Scope(this);
32
+ }
33
+
34
+ /** Runs `cleanup` when the scope stops. Returns a function that runs it early and forgets it. */
35
+ onStop(cleanup: () => void): () => void {
36
+ if (this.stoppedReason !== null) {
37
+ cleanup();
38
+ return () => {};
39
+ }
40
+ this.cleanups.add(cleanup);
41
+ return () => {
42
+ if (this.cleanups.delete(cleanup)) cleanup();
43
+ };
44
+ }
45
+
46
+ /** Forgets a cleanup without running it. */
47
+ forget(cleanup: () => void): void {
48
+ this.cleanups.delete(cleanup);
49
+ }
50
+
51
+ stop(reason: string): void {
52
+ if (this.stoppedReason !== null) return;
53
+ this.stoppedReason = reason;
54
+ for (const child of [...this.children]) child.stop(reason);
55
+ this.children.clear();
56
+ for (const cleanup of [...this.cleanups]) {
57
+ try {
58
+ cleanup();
59
+ } catch {
60
+ // A cleanup must not keep the others from running.
61
+ }
62
+ }
63
+ this.cleanups.clear();
64
+ this.parent?.children.delete(this);
65
+ }
66
+
67
+ /** A promise that settles like `promise` but rejects with StoppedError as soon as the scope stops. */
68
+ guard<T>(promise: Promise<T>): Promise<T> {
69
+ this.check();
70
+ return new Promise<T>((resolve, reject) => {
71
+ const cancel = () => reject(new StoppedError(this.stoppedReason ?? "Stopped"));
72
+ this.cleanups.add(cancel);
73
+ promise.then(
74
+ value => {
75
+ this.cleanups.delete(cancel);
76
+ resolve(value);
77
+ },
78
+ error => {
79
+ this.cleanups.delete(cancel);
80
+ reject(error);
81
+ },
82
+ );
83
+ });
84
+ }
85
+
86
+ /** Waits `ms`, or rejects with StoppedError when the scope stops first. */
87
+ sleep(ms: number): Promise<void> {
88
+ this.check();
89
+ return new Promise<void>((resolve, reject) => {
90
+ const timer = setTimeout(() => {
91
+ this.cleanups.delete(cancel);
92
+ resolve();
93
+ }, ms);
94
+ const cancel = () => {
95
+ clearTimeout(timer);
96
+ reject(new StoppedError(this.stoppedReason ?? "Stopped"));
97
+ };
98
+ this.cleanups.add(cancel);
99
+ });
100
+ }
101
+ }
@@ -0,0 +1,138 @@
1
+ import { PluginError } from "../errors.js";
2
+ import { StorageScope } from "../generated/contracts.js";
3
+ import type { StorageSchema } from "../protocol.js";
4
+ import type { PerBot, StoredMap, StoredValue } from "../storage.js";
5
+ import type { CallOutcome } from "./connection.js";
6
+ import type { Scope } from "./scope.js";
7
+
8
+ type Call = (scope: Scope, op: string, args: Record<string, unknown>) => Promise<CallOutcome>;
9
+
10
+ const MAX_UPDATE_ATTEMPTS = 16;
11
+
12
+ interface Address {
13
+ name: string;
14
+ scope: string;
15
+ /** The bot's uuid for bot-scoped entries. */
16
+ bot: string | null;
17
+ }
18
+
19
+ function ok<T>(outcome: CallOutcome): T {
20
+ if (!outcome.ok) throw new PluginError(outcome.failure, outcome.message);
21
+ return outcome.value as T;
22
+ }
23
+
24
+ function clone<T>(value: T): T {
25
+ return value === undefined ? value : (JSON.parse(JSON.stringify(value)) as T);
26
+ }
27
+
28
+ class Value<T> implements StoredValue<T> {
29
+ constructor(private readonly call: Call, private readonly scope: Scope, private readonly at: Address, private readonly fallback: T) {}
30
+
31
+ private async read(): Promise<{ value: T; version: number }> {
32
+ const r = ok<{ value: T | null; version: number }>(await this.call(this.scope, "storage.get", { ...this.at, key: null }));
33
+ return { value: r.value === null || r.value === undefined ? clone(this.fallback) : r.value, version: r.version };
34
+ }
35
+
36
+ async get(): Promise<T> {
37
+ return (await this.read()).value;
38
+ }
39
+
40
+ async set(value: T): Promise<void> {
41
+ ok(await this.call(this.scope, "storage.set", { ...this.at, key: null, value, ifVersion: null }));
42
+ }
43
+
44
+ async delete(): Promise<void> {
45
+ ok(await this.call(this.scope, "storage.delete", { ...this.at, key: null, ifVersion: null }));
46
+ }
47
+
48
+ async update(fn: (current: T) => T): Promise<T> {
49
+ for (let attempt = 0; attempt < MAX_UPDATE_ATTEMPTS; attempt++) {
50
+ const { value, version } = await this.read();
51
+ const next = fn(value);
52
+ const outcome = await this.call(this.scope, "storage.set", { ...this.at, key: null, value: next, ifVersion: version });
53
+ if (outcome.ok) return next;
54
+ if (outcome.failure !== "Conflict") throw new PluginError(outcome.failure, outcome.message);
55
+ }
56
+ throw new PluginError("Conflict", `storage.${this.at.name}.update: gave up after ${MAX_UPDATE_ATTEMPTS} conflicting writes`);
57
+ }
58
+ }
59
+
60
+ class Map_<T> implements StoredMap<T> {
61
+ constructor(private readonly call: Call, private readonly scope: Scope, private readonly at: Address) {}
62
+
63
+ private checkKey(key: string): void {
64
+ if (typeof key !== "string" || key.length === 0 || key.length > 128) throw new TypeError(`storage.${this.at.name}: keys are strings of 1 to 128 characters`);
65
+ }
66
+
67
+ private async read(key: string): Promise<{ value: T | undefined; version: number }> {
68
+ this.checkKey(key);
69
+ const r = ok<{ value: T | null; version: number }>(await this.call(this.scope, "storage.get", { ...this.at, key }));
70
+ return { value: r.value === null ? undefined : r.value, version: r.version };
71
+ }
72
+
73
+ async get(key: string): Promise<T | undefined> {
74
+ return (await this.read(key)).value;
75
+ }
76
+
77
+ async set(key: string, value: T): Promise<void> {
78
+ this.checkKey(key);
79
+ ok(await this.call(this.scope, "storage.set", { ...this.at, key, value, ifVersion: null }));
80
+ }
81
+
82
+ async delete(key: string): Promise<void> {
83
+ this.checkKey(key);
84
+ ok(await this.call(this.scope, "storage.delete", { ...this.at, key, ifVersion: null }));
85
+ }
86
+
87
+ async update(key: string, fn: (current: T | undefined) => T): Promise<T> {
88
+ for (let attempt = 0; attempt < MAX_UPDATE_ATTEMPTS; attempt++) {
89
+ const { value, version } = await this.read(key);
90
+ const next = fn(value);
91
+ const outcome = await this.call(this.scope, "storage.set", { ...this.at, key, value: next, ifVersion: version });
92
+ if (outcome.ok) return next;
93
+ if (outcome.failure !== "Conflict") throw new PluginError(outcome.failure, outcome.message);
94
+ }
95
+ throw new PluginError("Conflict", `storage.${this.at.name}.update: gave up after ${MAX_UPDATE_ATTEMPTS} conflicting writes`);
96
+ }
97
+
98
+ async keys(): Promise<string[]> {
99
+ return (await this.entries()).map(([k]) => k);
100
+ }
101
+
102
+ async entries(): Promise<[string, T][]> {
103
+ const all: [string, T][] = [];
104
+ let after: string | null = null;
105
+ for (;;) {
106
+ const page: { entries: [string, T][]; next: string | null } = ok(await this.call(this.scope, "storage.entries", { ...this.at, after, limit: 100 }));
107
+ all.push(...page.entries);
108
+ if (!page.next) return all;
109
+ after = page.next;
110
+ }
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Builds the `storage` object for a scope from the manifest's declarations. In run(bot) `bot` is that bot's
116
+ * uuid and bot-scoped entries bind to it; in runProfile `bot` is null and bot-scoped entries need `.for(bot)`.
117
+ */
118
+ export function createStorage(declared: Record<string, StorageSchema>, call: Call, scope: Scope, bot: string | null): Record<string, unknown> {
119
+ const storage: Record<string, unknown> = {};
120
+ for (const [name, schema] of Object.entries(declared)) {
121
+ const make = (botUuid: string | null) => {
122
+ const at: Address = { name, scope: schema.scope, bot: schema.scope === StorageScope.Bot ? botUuid : null };
123
+ return schema.kind === "map" ? new Map_(call, scope, at) : new Value(call, scope, at, schema.default);
124
+ };
125
+ if (schema.scope === StorageScope.Bot && bot === null) {
126
+ const perBot: PerBot<unknown> = {
127
+ for: target => {
128
+ if (!target?.uuid) throw new TypeError(`storage.${name}.for(bot): pass a bot from profile.bots()`);
129
+ return make(target.uuid);
130
+ },
131
+ };
132
+ storage[name] = perBot;
133
+ } else {
134
+ storage[name] = make(bot);
135
+ }
136
+ }
137
+ return storage;
138
+ }
@@ -0,0 +1,118 @@
1
+ import type { SettingSchema } from "./protocol.js";
2
+ import type { Block } from "./generated/blocks.js";
3
+ import type { Item } from "./generated/items.js";
4
+ import type { Entity } from "./generated/entities.js";
5
+ import type { Vec3 } from "./types.js";
6
+
7
+ /**
8
+ * One setting the user fills in on the dashboard. Build it with `Setting.*`; the type parameter is the
9
+ * value your plugin receives in `settings`.
10
+ */
11
+ export interface SettingDefinition<T> {
12
+ readonly schema: SettingSchema;
13
+ /** Type only, never set: carries the value type to `settings`. */
14
+ readonly __value?: T;
15
+ }
16
+
17
+ interface Common<T> {
18
+ /** Shown next to the field. */
19
+ label: string;
20
+ /** Shown under the field. */
21
+ description?: string;
22
+ default?: T;
23
+ }
24
+
25
+ type Optional<T, O> = O extends { optional: true } ? T | undefined : T;
26
+
27
+ function define<T>(schema: SettingSchema): SettingDefinition<T> {
28
+ return { schema };
29
+ }
30
+
31
+ function clean(schema: Record<string, unknown>): SettingSchema {
32
+ for (const key of Object.keys(schema)) if (schema[key] === undefined) delete schema[key];
33
+ return schema as unknown as SettingSchema;
34
+ }
35
+
36
+ /**
37
+ * Settings the user configures on the dashboard, per bot.
38
+ *
39
+ * @example
40
+ * settings: {
41
+ * crop: Setting.block({ label: "Crop", options: [Block.Wheat, Block.Carrots], default: Block.Wheat }),
42
+ * radius: Setting.radius({ label: "Search radius", default: 16, max: 48 }),
43
+ * greeting: Setting.text({ label: "Greeting", default: "Hello!" }),
44
+ * }
45
+ */
46
+ export const Setting = {
47
+ /** Free text. `max` limits the length (default 256). */
48
+ text<O extends Common<string> & { optional?: boolean; max?: number }>(o: O): SettingDefinition<Optional<string, O>> {
49
+ return define(clean({ type: "text", label: o.label, description: o.description, default: o.default, optional: o.optional, max: o.max ?? 256 }));
50
+ },
51
+
52
+ /** A number between `min` and `max`. */
53
+ number<O extends Common<number> & { optional?: boolean; min?: number; max?: number }>(o: O): SettingDefinition<Optional<number, O>> {
54
+ return define(clean({ type: "number", label: o.label, description: o.description, default: o.default, optional: o.optional, min: o.min, max: o.max }));
55
+ },
56
+
57
+ /** A distance in blocks, 1 to `max` (at most 64). */
58
+ radius(o: Common<number> & { max?: number }): SettingDefinition<number> {
59
+ return define(clean({ type: "radius", label: o.label, description: o.description, default: o.default ?? 16, min: 1, max: Math.min(o.max ?? 32, 64) }));
60
+ },
61
+
62
+ /** On or off. */
63
+ boolean(o: Common<boolean>): SettingDefinition<boolean> {
64
+ return define(clean({ type: "boolean", label: o.label, description: o.description, default: o.default ?? false }));
65
+ },
66
+
67
+ /** One of a fixed list of values, e.g. an enum's members. */
68
+ select<const V extends string | number, O extends Common<V> & { options: readonly V[]; optional?: boolean }>(o: O): SettingDefinition<Optional<V, O>> {
69
+ return define(clean({ type: "select", label: o.label, description: o.description, default: o.default, optional: o.optional, options: [...o.options] }));
70
+ },
71
+
72
+ /** A block type. `options` limits the choice; without it any block can be picked. */
73
+ block<O extends Common<Block> & { options?: readonly Block[]; optional?: boolean }>(o: O): SettingDefinition<Optional<Block, O>> {
74
+ return define(clean({ type: "block", label: o.label, description: o.description, default: o.default, optional: o.optional, options: o.options ? [...o.options] : undefined }));
75
+ },
76
+
77
+ /** An item type. */
78
+ item<O extends Common<Item> & { options?: readonly Item[]; optional?: boolean }>(o: O): SettingDefinition<Optional<Item, O>> {
79
+ return define(clean({ type: "item", label: o.label, description: o.description, default: o.default, optional: o.optional, options: o.options ? [...o.options] : undefined }));
80
+ },
81
+
82
+ /** An entity type (mob, animal, player...). */
83
+ entity<O extends Common<Entity> & { options?: readonly Entity[]; optional?: boolean }>(o: O): SettingDefinition<Optional<Entity, O>> {
84
+ return define(clean({ type: "entity", label: o.label, description: o.description, default: o.default, optional: o.optional, options: o.options ? [...o.options] : undefined }));
85
+ },
86
+
87
+ /** A position in the world (x, y, z). */
88
+ position<O extends Common<Vec3> & { optional?: boolean }>(o: O): SettingDefinition<Optional<Vec3, O>> {
89
+ return define(clean({ type: "position", label: o.label, description: o.description, default: o.default, optional: o.optional }));
90
+ },
91
+
92
+ /**
93
+ * An HTTPS address the user enters, such as a webhook. Your plugin may `fetch` exactly this origin
94
+ * without declaring a network permission. `hosts` limits which hosts are accepted.
95
+ *
96
+ * @example
97
+ * webhook: Setting.url({ label: "Discord webhook", hosts: ["discord.com"], secret: true, optional: true })
98
+ */
99
+ url<O extends Common<string> & { hosts?: readonly string[]; secret?: boolean; optional?: boolean }>(o: O): SettingDefinition<Optional<string, O>> {
100
+ return define(clean({ type: "url", label: o.label, description: o.description, default: o.secret ? undefined : o.default, optional: o.optional, hosts: o.hosts ? [...o.hosts] : undefined, secret: o.secret || undefined }));
101
+ },
102
+
103
+ /**
104
+ * A secret such as an API key: stored encrypted, never shown again on the dashboard, sent only to the
105
+ * running plugin and never to its author.
106
+ */
107
+ secret<O extends { label: string; description?: string; optional?: boolean }>(o: O): SettingDefinition<Optional<string, O>> {
108
+ return define(clean({ type: "secret", label: o.label, description: o.description, optional: o.optional, secret: true }));
109
+ },
110
+
111
+ /** A list of values of one kind, e.g. `Setting.list({ label: "Owners", of: Setting.text({ label: "Name" }) })`. */
112
+ list<T>(o: { label: string; description?: string; of: SettingDefinition<T>; max?: number; default?: T[] }): SettingDefinition<T[]> {
113
+ return define(clean({ type: "list", label: o.label, description: o.description, of: o.of.schema, max: o.max ?? 32, default: o.default ?? [] }));
114
+ },
115
+ };
116
+
117
+ /** The values your plugin receives for a settings declaration. */
118
+ export type SettingValues<S> = { readonly [K in keyof S]: S[K] extends SettingDefinition<infer T> ? T : never };