@minecraftbot-com/plugin 0.0.0-stage → 0.1.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 (128) hide show
  1. package/AGENTS.md +177 -0
  2. package/README.md +45 -2
  3. package/dist/api.d.ts +351 -0
  4. package/dist/api.js +2 -0
  5. package/dist/cli/api.d.ts +26 -0
  6. package/dist/cli/api.js +61 -0
  7. package/dist/cli/build.d.ts +23 -0
  8. package/dist/cli/build.js +65 -0
  9. package/dist/cli/check.d.ts +10 -0
  10. package/dist/cli/check.js +98 -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/dev-mcp.d.ts +36 -0
  16. package/dist/cli/dev-mcp.js +101 -0
  17. package/dist/cli/dev.d.ts +15 -0
  18. package/dist/cli/dev.js +261 -0
  19. package/dist/cli/fetch-guard.d.ts +7 -0
  20. package/dist/cli/fetch-guard.js +66 -0
  21. package/dist/cli/main.d.ts +2 -0
  22. package/dist/cli/main.js +112 -0
  23. package/dist/cli/mcp.d.ts +24 -0
  24. package/dist/cli/mcp.js +136 -0
  25. package/dist/cli/output.d.ts +11 -0
  26. package/dist/cli/output.js +25 -0
  27. package/dist/cli/test.d.ts +2 -0
  28. package/dist/cli/test.js +39 -0
  29. package/dist/errors.d.ts +22 -0
  30. package/dist/errors.js +35 -0
  31. package/dist/generated/block-states.d.ts +4087 -0
  32. package/dist/generated/block-states.js +2 -0
  33. package/dist/generated/blocks.d.ts +1289 -0
  34. package/dist/generated/blocks.js +1291 -0
  35. package/dist/generated/contracts.d.ts +304 -0
  36. package/dist/generated/contracts.js +327 -0
  37. package/dist/generated/effects.d.ts +43 -0
  38. package/dist/generated/effects.js +45 -0
  39. package/dist/generated/entities.d.ts +164 -0
  40. package/dist/generated/entities.js +166 -0
  41. package/dist/generated/items.d.ts +1661 -0
  42. package/dist/generated/items.js +1663 -0
  43. package/dist/generated/operations.d.ts +7 -0
  44. package/dist/generated/operations.js +65 -0
  45. package/dist/generated/permission-labels.d.ts +3 -0
  46. package/dist/generated/permission-labels.js +17 -0
  47. package/dist/generated/version.d.ts +2 -0
  48. package/dist/generated/version.js +3 -0
  49. package/dist/host/index.d.ts +7 -0
  50. package/dist/host/index.js +5 -0
  51. package/dist/index.d.ts +19 -0
  52. package/dist/index.js +13 -0
  53. package/dist/permissions.d.ts +11 -0
  54. package/dist/permissions.js +18 -0
  55. package/dist/plugin.d.ts +86 -0
  56. package/dist/plugin.js +26 -0
  57. package/dist/protocol.d.ts +167 -0
  58. package/dist/protocol.js +4 -0
  59. package/dist/runtime/connection.d.ts +52 -0
  60. package/dist/runtime/connection.js +132 -0
  61. package/dist/runtime/handles.d.ts +95 -0
  62. package/dist/runtime/handles.js +289 -0
  63. package/dist/runtime/memory-transport.d.ts +6 -0
  64. package/dist/runtime/memory-transport.js +39 -0
  65. package/dist/runtime/runtime.d.ts +57 -0
  66. package/dist/runtime/runtime.js +265 -0
  67. package/dist/runtime/scope.d.ts +25 -0
  68. package/dist/runtime/scope.js +94 -0
  69. package/dist/runtime/storage-runtime.d.ts +10 -0
  70. package/dist/runtime/storage-runtime.js +131 -0
  71. package/dist/settings.d.ts +111 -0
  72. package/dist/settings.js +78 -0
  73. package/dist/storage.d.ts +78 -0
  74. package/dist/storage.js +24 -0
  75. package/dist/testing/fake-container.d.ts +175 -0
  76. package/dist/testing/fake-container.js +483 -0
  77. package/dist/testing/index.d.ts +37 -0
  78. package/dist/testing/index.js +54 -0
  79. package/dist/types.d.ts +65 -0
  80. package/dist/types.js +54 -0
  81. package/llms.txt +11 -0
  82. package/package.json +55 -4
  83. package/src/api.ts +334 -0
  84. package/src/cli/api.ts +79 -0
  85. package/src/cli/build.ts +76 -0
  86. package/src/cli/check.ts +103 -0
  87. package/src/cli/config.ts +48 -0
  88. package/src/cli/create.ts +38 -0
  89. package/src/cli/dev-mcp.ts +131 -0
  90. package/src/cli/dev.ts +272 -0
  91. package/src/cli/fetch-guard.ts +61 -0
  92. package/src/cli/main.ts +113 -0
  93. package/src/cli/mcp.ts +168 -0
  94. package/src/cli/output.ts +30 -0
  95. package/src/cli/test.ts +38 -0
  96. package/src/errors.ts +34 -0
  97. package/src/generated/block-states.ts +892 -0
  98. package/src/generated/blocks.ts +1291 -0
  99. package/src/generated/contracts.ts +329 -0
  100. package/src/generated/effects.ts +45 -0
  101. package/src/generated/entities.ts +166 -0
  102. package/src/generated/items.ts +1663 -0
  103. package/src/generated/operations.ts +69 -0
  104. package/src/generated/permission-labels.ts +19 -0
  105. package/src/generated/version.ts +3 -0
  106. package/src/host/index.ts +9 -0
  107. package/src/index.ts +34 -0
  108. package/src/permissions.ts +23 -0
  109. package/src/plugin.ts +105 -0
  110. package/src/protocol.ts +107 -0
  111. package/src/runtime/connection.ts +167 -0
  112. package/src/runtime/handles.ts +337 -0
  113. package/src/runtime/memory-transport.ts +41 -0
  114. package/src/runtime/runtime.ts +281 -0
  115. package/src/runtime/scope.ts +101 -0
  116. package/src/runtime/storage-runtime.ts +138 -0
  117. package/src/settings.ts +118 -0
  118. package/src/storage.ts +82 -0
  119. package/src/testing/fake-container.ts +571 -0
  120. package/src/testing/index.ts +70 -0
  121. package/src/types.ts +88 -0
  122. package/templates/basic/AGENTS.md +31 -0
  123. package/templates/basic/README.md +13 -0
  124. package/templates/basic/gitignore +3 -0
  125. package/templates/basic/package.json +18 -0
  126. package/templates/basic/src/index.ts +20 -0
  127. package/templates/basic/test/plugin.test.ts +14 -0
  128. package/templates/basic/tsconfig.json +14 -0
@@ -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 };
package/src/storage.ts ADDED
@@ -0,0 +1,82 @@
1
+ import type { StorageSchema } from "./protocol.js";
2
+ import { StorageScope } from "./generated/contracts.js";
3
+ import type { JsonValue } from "./types.js";
4
+
5
+ /** Declares one stored value. Build it with `Storage.value` or `Storage.map`. */
6
+ export interface StorageDefinition<T, K extends "value" | "map", S extends StorageScope> {
7
+ readonly schema: StorageSchema;
8
+ readonly __value?: T;
9
+ readonly __kind?: K;
10
+ readonly __scope?: S;
11
+ }
12
+
13
+ /**
14
+ * Data your plugin keeps between runs. It belongs to the user who installed the plugin, is limited to
15
+ * 1 MB per scope and 64 KB per value, and holds JSON values only.
16
+ *
17
+ * Scopes: `StorageScope.Profile` (default, shared by every bot of the profile), `StorageScope.Bot` (one per
18
+ * account, survives renames), `StorageScope.User` (shared by all of the user's profiles).
19
+ *
20
+ * @example
21
+ * storage: {
22
+ * harvested: Storage.value({ scope: StorageScope.Bot, default: 0 }),
23
+ * homes: Storage.map<Vec3>(),
24
+ * }
25
+ */
26
+ export const Storage = {
27
+ /** A single value. `get()` returns `default` until something is set. */
28
+ value<T, S extends StorageScope = StorageScope.Profile>(o: { scope?: S; default: T & JsonValue }): StorageDefinition<T, "value", NoInfer<S>> {
29
+ return { schema: { kind: "value", scope: o.scope ?? StorageScope.Profile, default: o.default } };
30
+ },
31
+
32
+ /** Keys (strings, up to 128 characters) to values. */
33
+ map<T extends JsonValue, S extends StorageScope = StorageScope.Profile>(o: { scope?: S } = {}): StorageDefinition<T, "map", NoInfer<S>> {
34
+ return { schema: { kind: "map", scope: o.scope ?? StorageScope.Profile } };
35
+ },
36
+ };
37
+
38
+ /** A stored value. */
39
+ export interface StoredValue<T> {
40
+ /** The current value, or the declared default. */
41
+ get(): Promise<T>;
42
+ set(value: T): Promise<void>;
43
+ /** Back to the default. */
44
+ delete(): Promise<void>;
45
+ /**
46
+ * Read, change and write in one step. If another bot wrote in between, `fn` runs again on the newer
47
+ * value, so concurrent updates are never lost.
48
+ *
49
+ * @example await storage.harvested.update(n => n + 1);
50
+ */
51
+ update(fn: (current: T) => T): Promise<T>;
52
+ }
53
+
54
+ /** A stored map from string keys to values. */
55
+ export interface StoredMap<T> {
56
+ get(key: string): Promise<T | undefined>;
57
+ set(key: string, value: T): Promise<void>;
58
+ delete(key: string): Promise<void>;
59
+ /** Change one entry in one step; `fn` gets `undefined` for a missing key. */
60
+ update(key: string, fn: (current: T | undefined) => T): Promise<T>;
61
+ /** Every key, in order. */
62
+ keys(): Promise<string[]>;
63
+ /** Every entry, in key order. */
64
+ entries(): Promise<[string, T][]>;
65
+ }
66
+
67
+ /** A bot-scoped value seen from `runProfile`: pick the bot first. */
68
+ export interface PerBot<S> {
69
+ for(bot: { readonly uuid: string }): S;
70
+ }
71
+
72
+ type Stored<T, K> = K extends "map" ? StoredMap<T> : StoredValue<T>;
73
+
74
+ type Accessor<D, InRun extends boolean> =
75
+ D extends StorageDefinition<infer T, infer K, infer S>
76
+ ? InRun extends true ? Stored<T, K> : S extends StorageScope.Bot ? PerBot<Stored<T, K>> : Stored<T, K>
77
+ : never;
78
+
79
+ /** `storage` inside `run(bot)`: bot-scoped entries are already bound to that bot. */
80
+ export type BotStorage<S> = { readonly [K in keyof S]: Accessor<S[K], true> };
81
+ /** `storage` inside `runProfile`: bot-scoped entries need `.for(bot)`. */
82
+ export type ProfileStorage<S> = { readonly [K in keyof S]: Accessor<S[K], false> };