@dice-plus/sdk 0.0.0-stage → 1.3.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 MissingLinkDev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,24 @@
1
- # Temporary Holding Version
1
+ # @dice-plus/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Put the [Dice+](https://dice-plus.missinglinkdev.com) 3D physics dice tray and dice bag on your site. We run the physics, the rooms shared with Owlbear Rodeo players, the player's own dice and Patreon; you build the buttons and show the results your way.
4
+
5
+ ```bash
6
+ npm install @dice-plus/sdk
7
+ ```
8
+
9
+ ```js
10
+ import { DicePlusTray } from '@dice-plus/sdk';
11
+
12
+ const tray = new DicePlusTray({
13
+ apiKey: 'dp_your_key',
14
+ container: document.body,
15
+ identity: { name: 'Ari', color: '#e07a5f' },
16
+ });
17
+
18
+ tray.on('roll-result', ({ result }) => console.log(result.result.totalValue));
19
+ await tray.roll({ diceNotation: '2d20kh1+5' });
20
+ ```
21
+
22
+ You need an Access Key: request one at [dice-plus.missinglinkdev.com/devs](https://dice-plus.missinglinkdev.com/devs). Pages using Dice+ show "Dice powered by Dice+" with links to the site and [the Dice+ Patreon](https://patreon.com/MissingLinkDev).
23
+
24
+ Full reference: [dice-plus.missinglinkdev.com/devs/docs](https://dice-plus.missinglinkdev.com/devs/docs).
package/dist/index.js ADDED
@@ -0,0 +1,366 @@
1
+ //#region ../src/embed/protocol.ts
2
+ /** Every message carries this, so pages and frames ignore other postMessage traffic. */
3
+ var EMBED_TAG = "dice-plus-embed";
4
+ function isEmbedMessage(data) {
5
+ return !!data && typeof data === "object" && data.tag === "dice-plus-embed" && typeof data.type === "string";
6
+ }
7
+ //#endregion
8
+ //#region ../src/platform/relay/protocol.ts
9
+ var RELAY_LIMITS = {
10
+ maxSockets: 20,
11
+ /** One wire message: a 64KB broadcast payload plus its envelope. */
12
+ maxMessageBytes: 72 * 1024,
13
+ /** Token bucket per socket: sustained messages per second, and the burst a large chunked roll needs. */
14
+ messagesPerSecond: 5,
15
+ burst: 64,
16
+ keptMessages: 50,
17
+ /** A member's published metadata, as JSON. */
18
+ maxMetadataBytes: 8 * 1024,
19
+ webRoomIdleMs: 14400 * 1e3,
20
+ homeRoomIdleMs: 720 * 60 * 60 * 1e3,
21
+ /** How long a link request waits for its answer. */
22
+ linkAskMs: 60 * 1e3,
23
+ /** Before the same Guest may ask the same player again. */
24
+ linkCooldownMs: 10 * 1e3,
25
+ /** Denials from one player before that connection may not ask them again. */
26
+ linkDenials: 3,
27
+ /** Links a Room remembers. */
28
+ maxLinks: 64,
29
+ /** Wrong Passcodes from one address within a minute before it is turned away for a minute. */
30
+ passcodeTriesPerAddress: 5,
31
+ passcodeAddressWindowMs: 60 * 1e3,
32
+ passcodeAddressBlockMs: 60 * 1e3,
33
+ /** Wrong Passcodes for the room within 15 minutes before it refuses Passcode joins for 15 minutes. */
34
+ passcodeTriesPerRoom: 50,
35
+ passcodeRoomWindowMs: 900 * 1e3,
36
+ passcodeRoomLockMs: 900 * 1e3,
37
+ /** Roll Links' roll requests, per socket: the burst, then one every two seconds. */
38
+ rollRequestBurst: 5,
39
+ rollRequestsPerSecond: .5,
40
+ /** A roll request as JSON, and its notation. */
41
+ maxRollRequestBytes: 4 * 1024,
42
+ maxNotationLength: 500,
43
+ rollIdLength: 64,
44
+ /** Roll Links linked to one player at once. */
45
+ rollLinksPerPlayer: 3
46
+ };
47
+ /** A Room Code: 8 Crockford base32 characters, stored upper case without the dash. */
48
+ var ROOM_CODE = /^[0-9A-HJKMNP-TV-Z]{8}$/;
49
+ /** Room ids from before Room Codes: 16 random bytes in base64url. */
50
+ var LEGACY_ROOM_ID = /^[A-Za-z0-9_-]{16,64}$/;
51
+ new RegExp(`${ROOM_CODE.source}|${LEGACY_ROOM_ID.source}`);
52
+ /** A Passcode: six digits, leading zeros kept. */
53
+ var PASSCODE_PATTERN = /^\d{6}$/;
54
+ /**
55
+ * A room id from what a player typed: Room Codes ignore case, spaces and the
56
+ * dash, and read I and L as 1 and O as 0. Older long ids pass through exactly.
57
+ */
58
+ function normalizeRoomId(input) {
59
+ const text = input.trim();
60
+ if (LEGACY_ROOM_ID.test(text)) return text;
61
+ const code = text.replace(/[\s-]/g, "").toUpperCase().replace(/[IL]/g, "1").replace(/O/g, "0");
62
+ return ROOM_CODE.test(code) ? code : null;
63
+ }
64
+ //#endregion
65
+ //#region ../src/platform/relay/roomCode.ts
66
+ /** `K7M2-QX9P`; older long ids as they are. */
67
+ function formatRoomCode(roomId) {
68
+ return roomId.length === 8 ? `${roomId.slice(0, 4)}-${roomId.slice(4)}` : roomId;
69
+ }
70
+ //#endregion
71
+ //#region src/index.ts
72
+ var SDK_VERSION = "1.3.0";
73
+ var DEFAULT_BASE_URL = "https://dice-plus.missinglinkdev.com";
74
+ /** Room Code and Passcode helpers, so a page never has to guess our formats. */
75
+ var rooms = {
76
+ /** `K7M2-QX9P` from a stored id */
77
+ formatRoomCode,
78
+ /** The id from what a player typed (case, spaces and the dash ignored), or null if it is not a Room Code */
79
+ normalizeRoomCode: normalizeRoomId,
80
+ /** Six digits */
81
+ isPasscode: (value) => PASSCODE_PATTERN.test(value),
82
+ /** How long a player has to allow a link request */
83
+ linkAskMs: RELAY_LIMITS.linkAskMs,
84
+ /** Denials after which a player cannot be asked again on this connection */
85
+ linkDenials: RELAY_LIMITS.linkDenials
86
+ };
87
+ /** One of our iframes: the handshake, calls and events every embed shares. */
88
+ var Embed = class {
89
+ constructor(options, path, title, style) {
90
+ this.listeners = /* @__PURE__ */ new Map();
91
+ this.pending = /* @__PURE__ */ new Map();
92
+ this.queued = [];
93
+ this.lastEvents = /* @__PURE__ */ new Map();
94
+ this.nextId = 1;
95
+ this.isReady = false;
96
+ this.destroyed = false;
97
+ this.refused = null;
98
+ this.onMessage = (event) => this.receive(event);
99
+ if (!options?.container) throw new Error(`${title} needs a container element.`);
100
+ this.apiKey = options.apiKey;
101
+ this.theme = options.theme;
102
+ const base = new URL(options.baseUrl ?? "https://dice-plus.missinglinkdev.com");
103
+ this.origin = base.origin;
104
+ let settle;
105
+ this.ready = new Promise((resolve, reject) => {
106
+ settle = {
107
+ resolve,
108
+ reject
109
+ };
110
+ });
111
+ this.ready.catch(() => {});
112
+ this.once("ready", (value) => settle.resolve(value));
113
+ this.once("unauthorized", (value) => settle.reject(new Error(value.message)));
114
+ const frame = document.createElement("iframe");
115
+ frame.src = new URL(path, base).href;
116
+ frame.title = title;
117
+ Object.assign(frame.style, {
118
+ position: "absolute",
119
+ inset: "0",
120
+ width: "100%",
121
+ height: "100%",
122
+ border: "0"
123
+ }, style);
124
+ frame.addEventListener("load", () => this.hello());
125
+ if (getComputedStyle(options.container).position === "static") options.container.style.position = "relative";
126
+ window.addEventListener("message", this.onMessage);
127
+ options.container.append(frame);
128
+ this.frame = frame;
129
+ }
130
+ /** Listen for an event. Returns an unsubscribe. */
131
+ on(name, listener) {
132
+ let set = this.listeners.get(name);
133
+ if (!set) {
134
+ set = /* @__PURE__ */ new Set();
135
+ this.listeners.set(name, set);
136
+ }
137
+ set.add(listener);
138
+ return () => {
139
+ set.delete(listener);
140
+ };
141
+ }
142
+ once(name, listener) {
143
+ const off = this.on(name, (data) => {
144
+ off();
145
+ listener(data);
146
+ });
147
+ return off;
148
+ }
149
+ /** Remove the embed and stop listening. */
150
+ destroy() {
151
+ if (this.destroyed) return;
152
+ this.destroyed = true;
153
+ window.removeEventListener("message", this.onMessage);
154
+ this.frame.remove();
155
+ for (const { reject } of this.pending.values()) reject(/* @__PURE__ */ new Error("The embed was destroyed."));
156
+ this.pending.clear();
157
+ this.listeners.clear();
158
+ }
159
+ /** Your site's colors for the embed's UI; null for ours. */
160
+ setTheme(theme) {
161
+ this.theme = theme ?? void 0;
162
+ return this.call("setTheme", theme);
163
+ }
164
+ /** The latest of an event, if it has come yet. */
165
+ last(name) {
166
+ return this.lastEvents.get(name);
167
+ }
168
+ /** What else this embed's hello carries. */
169
+ helloExtras() {
170
+ return {};
171
+ }
172
+ call(method, ...args) {
173
+ if (this.destroyed) return Promise.reject(/* @__PURE__ */ new Error("The embed was destroyed."));
174
+ if (this.refused) return Promise.reject(new Error(this.refused.message));
175
+ return new Promise((resolve, reject) => {
176
+ const send = () => {
177
+ const id = this.nextId++;
178
+ this.pending.set(id, {
179
+ resolve,
180
+ reject
181
+ });
182
+ this.post({
183
+ type: "call",
184
+ id,
185
+ method,
186
+ args
187
+ });
188
+ };
189
+ if (this.isReady) send();
190
+ else this.queued.push(send);
191
+ });
192
+ }
193
+ hello() {
194
+ if (this.destroyed) return;
195
+ this.isReady = false;
196
+ for (const { reject } of this.pending.values()) reject(/* @__PURE__ */ new Error("The embed reloaded."));
197
+ this.pending.clear();
198
+ this.post({
199
+ type: "hello",
200
+ protocol: 1,
201
+ sdkVersion: SDK_VERSION,
202
+ apiKey: this.apiKey,
203
+ ...this.theme ? { theme: this.theme } : {},
204
+ ...this.helloExtras()
205
+ });
206
+ }
207
+ post(message) {
208
+ this.frame.contentWindow?.postMessage({
209
+ tag: EMBED_TAG,
210
+ ...message
211
+ }, this.origin);
212
+ }
213
+ receive(event) {
214
+ if (event.source !== this.frame.contentWindow || event.origin !== this.origin) return;
215
+ if (!isEmbedMessage(event.data)) return;
216
+ const message = event.data;
217
+ switch (message.type) {
218
+ case "ready": {
219
+ const { playerId } = message;
220
+ this.isReady = true;
221
+ this.emit("ready", { playerId });
222
+ this.queued.splice(0).forEach((send) => send());
223
+ break;
224
+ }
225
+ case "unauthorized": {
226
+ const { reason, message: text } = message;
227
+ this.refused = {
228
+ reason,
229
+ message: text
230
+ };
231
+ this.queued.splice(0);
232
+ this.emit("unauthorized", this.refused);
233
+ break;
234
+ }
235
+ case "reply": {
236
+ const reply = message;
237
+ const pending = this.pending.get(reply.id);
238
+ if (!pending) return;
239
+ this.pending.delete(reply.id);
240
+ if (reply.ok) pending.resolve(reply.value);
241
+ else pending.reject(new Error(reply.error ?? "The embed could not do that."));
242
+ break;
243
+ }
244
+ case "event": {
245
+ const { name, data } = message;
246
+ this.lastEvents.set(name, data);
247
+ this.emit(name, data);
248
+ break;
249
+ }
250
+ }
251
+ }
252
+ emit(name, data) {
253
+ for (const listener of [...this.listeners.get(name) ?? []]) try {
254
+ listener(data);
255
+ } catch (error) {
256
+ console.error(`[Dice+] ${String(name)} listener threw`, error);
257
+ }
258
+ }
259
+ };
260
+ /** The dice tray: rolls, the Room, and every result the player sees. Fills its container, see-through and click-through. */
261
+ var DicePlusTray = class extends Embed {
262
+ constructor(options) {
263
+ super(options, "/embed/tray.html", "Dice+ dice tray", {
264
+ background: "transparent",
265
+ colorScheme: "normal",
266
+ pointerEvents: "none"
267
+ });
268
+ this.settings = { ...options.settings ?? {} };
269
+ this.identity = options.identity;
270
+ this.dice = options.dice;
271
+ this.frame.setAttribute("allow", "autoplay");
272
+ this.frame.setAttribute("aria-hidden", "true");
273
+ this.frame.tabIndex = -1;
274
+ }
275
+ helloExtras() {
276
+ return {
277
+ settings: this.settings,
278
+ ...this.identity ? { identity: this.identity } : {},
279
+ ...this.dice ? { dice: this.dice } : {}
280
+ };
281
+ }
282
+ invoke(method, ...args) {
283
+ return this.call(method, ...args);
284
+ }
285
+ /** Roll dice. Resolves with the rollId once the tray has taken the roll; the result comes as a 'roll-result' event. */
286
+ roll(request) {
287
+ return this.invoke("roll", request);
288
+ }
289
+ /** Change some settings; the rest stay as they are. */
290
+ setSettings(settings) {
291
+ this.settings = {
292
+ ...this.settings,
293
+ ...settings
294
+ };
295
+ return this.invoke("setSettings", settings);
296
+ }
297
+ setIdentity(identity) {
298
+ this.identity = identity;
299
+ return this.invoke("setIdentity", identity);
300
+ }
301
+ /** Your site's look for dice the player's bag does not cover; null for ours. */
302
+ setSiteDice(dice) {
303
+ this.dice = dice ?? void 0;
304
+ return this.invoke("setSiteDice", dice);
305
+ }
306
+ getHistory() {
307
+ return this.invoke("getHistory");
308
+ }
309
+ /** A new Room with this browser as Host; in a Room already, a new Room Code and Passcode */
310
+ createRoom() {
311
+ return this.invoke("createRoom");
312
+ }
313
+ joinRoom(roomCode, passcode) {
314
+ return this.invoke("joinRoom", roomCode, passcode);
315
+ }
316
+ leaveRoom() {
317
+ return this.invoke("leaveRoom");
318
+ }
319
+ setPasscode(passcode) {
320
+ return this.invoke("setPasscode", passcode);
321
+ }
322
+ setGm(playerId, gm) {
323
+ return this.invoke("setGm", playerId, gm);
324
+ }
325
+ kick(playerId) {
326
+ return this.invoke("kick", playerId);
327
+ }
328
+ requestLink(playerId) {
329
+ return this.invoke("requestLink", playerId);
330
+ }
331
+ cancelLinkRequest() {
332
+ return this.invoke("cancelLinkRequest");
333
+ }
334
+ unlink(guestId) {
335
+ return this.invoke("unlink", guestId);
336
+ }
337
+ answerLink(guestId, allow) {
338
+ return this.invoke("answerLink", guestId, allow);
339
+ }
340
+ chooseNewPlayer() {
341
+ return this.invoke("chooseNewPlayer");
342
+ }
343
+ reconnect() {
344
+ return this.invoke("reconnect");
345
+ }
346
+ /** The latest of an event the tray repeats as state, if any yet. */
347
+ latest(name) {
348
+ return this.last(name);
349
+ }
350
+ };
351
+ /**
352
+ * The player's dice bag: their dice, collections, stats, cloud backup and
353
+ * Patreon sign-in. Fills its container; show it however suits your site.
354
+ */
355
+ var DicePlusBag = class extends Embed {
356
+ constructor(options) {
357
+ super(options, "/embed/bag.html", "Dice+ dice bag", {});
358
+ this.frame.setAttribute("allow", "clipboard-write");
359
+ }
360
+ /** Whether the player is signed in and a patron, once the bag has said. */
361
+ premium() {
362
+ return this.last("premium-changed");
363
+ }
364
+ };
365
+ //#endregion
366
+ export { DEFAULT_BASE_URL, DicePlusBag, DicePlusTray, SDK_VERSION, rooms };
@@ -0,0 +1,133 @@
1
+ import { type BagEvents, type EmbedTheme, type HelloMessage, type SiteDice, type TrayEvents, type TrayIdentity, type TrayMethods, type TraySettings, type UnauthorizedReason } from '../../src/embed/protocol';
2
+ import { normalizeRoomId } from '../../src/platform/relay/protocol';
3
+ import { formatRoomCode } from '../../src/platform/relay/roomCode';
4
+ export type * from '../../src/embed/protocol';
5
+ export declare const SDK_VERSION = "1.3.0";
6
+ export declare const DEFAULT_BASE_URL = "https://dice-plus.missinglinkdev.com";
7
+ /** Room Code and Passcode helpers, so a page never has to guess our formats. */
8
+ export declare const rooms: {
9
+ /** `K7M2-QX9P` from a stored id */
10
+ readonly formatRoomCode: typeof formatRoomCode;
11
+ /** The id from what a player typed (case, spaces and the dash ignored), or null if it is not a Room Code */
12
+ readonly normalizeRoomCode: typeof normalizeRoomId;
13
+ /** Six digits */
14
+ readonly isPasscode: (value: string) => boolean;
15
+ /** How long a player has to allow a link request */
16
+ readonly linkAskMs: number;
17
+ /** Denials after which a player cannot be asked again on this connection */
18
+ readonly linkDenials: 3;
19
+ };
20
+ interface EmbedOptions {
21
+ /** Your Access Key from dice-plus.missinglinkdev.com/devs */
22
+ apiKey: string;
23
+ /** The embed fills this element; give it a size. */
24
+ container: HTMLElement;
25
+ /** Where our embeds are served from. Leave out except to test against a development build. */
26
+ baseUrl?: string;
27
+ /** Your site's colors for the embed's UI. Dice keep their own look. */
28
+ theme?: EmbedTheme;
29
+ }
30
+ export interface DicePlusTrayOptions extends EmbedOptions {
31
+ settings?: TraySettings;
32
+ /** The player's name and color as others in the Room see them */
33
+ identity?: TrayIdentity;
34
+ /** Your site's look for dice the player's bag does not cover */
35
+ dice?: SiteDice;
36
+ }
37
+ export type DicePlusBagOptions = EmbedOptions;
38
+ export interface UnauthorizedEvent {
39
+ reason: UnauthorizedReason;
40
+ message: string;
41
+ }
42
+ /** Every embed tells you these. */
43
+ type CommonEvents = {
44
+ /** The embed is up (again, after it reloads) */
45
+ ready: {
46
+ playerId: string;
47
+ };
48
+ /** Your key or this page's origin was refused; the embed will not work */
49
+ unauthorized: UnauthorizedEvent;
50
+ };
51
+ export type DicePlusTrayEvents = TrayEvents & CommonEvents;
52
+ export type DicePlusBagEvents = BagEvents & CommonEvents;
53
+ type Listener<T> = (data: T) => void;
54
+ /** One of our iframes: the handshake, calls and events every embed shares. */
55
+ declare abstract class Embed<Events extends CommonEvents> {
56
+ /** Resolves once the embed first says it is ready; rejects if it refuses this page. */
57
+ readonly ready: Promise<{
58
+ playerId: string;
59
+ }>;
60
+ protected readonly frame: HTMLIFrameElement;
61
+ private readonly origin;
62
+ private readonly apiKey;
63
+ private readonly listeners;
64
+ private readonly pending;
65
+ private readonly queued;
66
+ private readonly lastEvents;
67
+ private nextId;
68
+ private isReady;
69
+ private destroyed;
70
+ private refused;
71
+ private theme;
72
+ private readonly onMessage;
73
+ protected constructor(options: EmbedOptions, path: string, title: string, style: Partial<CSSStyleDeclaration>);
74
+ /** Listen for an event. Returns an unsubscribe. */
75
+ on<E extends keyof Events>(name: E, listener: Listener<Events[E]>): () => void;
76
+ once<E extends keyof Events>(name: E, listener: Listener<Events[E]>): () => void;
77
+ /** Remove the embed and stop listening. */
78
+ destroy(): void;
79
+ /** Your site's colors for the embed's UI; null for ours. */
80
+ setTheme(theme: EmbedTheme | null): Promise<void>;
81
+ /** The latest of an event, if it has come yet. */
82
+ protected last<E extends keyof Events>(name: E): Events[E] | undefined;
83
+ /** What else this embed's hello carries. */
84
+ protected helloExtras(): Partial<HelloMessage>;
85
+ protected call(method: string, ...args: unknown[]): Promise<unknown>;
86
+ private hello;
87
+ private post;
88
+ private receive;
89
+ private emit;
90
+ }
91
+ /** The dice tray: rolls, the Room, and every result the player sees. Fills its container, see-through and click-through. */
92
+ export declare class DicePlusTray extends Embed<DicePlusTrayEvents> {
93
+ private settings;
94
+ private identity;
95
+ private dice;
96
+ constructor(options: DicePlusTrayOptions);
97
+ protected helloExtras(): Partial<HelloMessage>;
98
+ private invoke;
99
+ /** Roll dice. Resolves with the rollId once the tray has taken the roll; the result comes as a 'roll-result' event. */
100
+ roll(request: Parameters<TrayMethods['roll']>[0]): Promise<{
101
+ rollId: string;
102
+ }>;
103
+ /** Change some settings; the rest stay as they are. */
104
+ setSettings(settings: TraySettings): Promise<void>;
105
+ setIdentity(identity: TrayIdentity): Promise<void>;
106
+ /** Your site's look for dice the player's bag does not cover; null for ours. */
107
+ setSiteDice(dice: SiteDice | null): Promise<void>;
108
+ getHistory(): Promise<import(".").HistoryEntry[]>;
109
+ /** A new Room with this browser as Host; in a Room already, a new Room Code and Passcode */
110
+ createRoom(): Promise<void>;
111
+ joinRoom(roomCode: string, passcode: string | null): Promise<void>;
112
+ leaveRoom(): Promise<void>;
113
+ setPasscode(passcode: string | null): Promise<void>;
114
+ setGm(playerId: string, gm: boolean): Promise<void>;
115
+ kick(playerId: string): Promise<void>;
116
+ requestLink(playerId: string): Promise<void>;
117
+ cancelLinkRequest(): Promise<void>;
118
+ unlink(guestId: string): Promise<void>;
119
+ answerLink(guestId: string, allow: boolean): Promise<void>;
120
+ chooseNewPlayer(): Promise<void>;
121
+ reconnect(): Promise<void>;
122
+ /** The latest of an event the tray repeats as state, if any yet. */
123
+ latest<E extends 'room-state' | 'dice-availability' | 'history-changed'>(name: E): TrayEvents[E] | undefined;
124
+ }
125
+ /**
126
+ * The player's dice bag: their dice, collections, stats, cloud backup and
127
+ * Patreon sign-in. Fills its container; show it however suits your site.
128
+ */
129
+ export declare class DicePlusBag extends Embed<DicePlusBagEvents> {
130
+ constructor(options: DicePlusBagOptions);
131
+ /** Whether the player is signed in and a patron, once the bag has said. */
132
+ premium(): BagEvents['premium-changed'] | undefined;
133
+ }
@@ -0,0 +1,351 @@
1
+ import type { SiteDice } from '../features/site-dice/siteDiceTypes';
2
+ export type { SiteDice };
3
+ export type { StandardDiceStyle } from '../features/site-dice/siteDiceTypes';
4
+ export declare const EMBED_PROTOCOL = 1;
5
+ /** Every message carries this, so pages and frames ignore other postMessage traffic. */
6
+ export declare const EMBED_TAG = "dice-plus-embed";
7
+ export type RollTarget = 'everyone' | 'self' | 'dm' | 'gm_only';
8
+ /** One die in a result. */
9
+ export interface RolledDie {
10
+ diceId: string;
11
+ rollId: string;
12
+ diceType: string;
13
+ diceStyle?: string;
14
+ /** What it counts as: after custom face values, min/max, Fudge mapping and sign */
15
+ value: number;
16
+ /** The faces it physically landed on (every face of a compounding chain) */
17
+ faces?: number[];
18
+ /** The bag die's name */
19
+ customName?: string;
20
+ isAdvantage: boolean;
21
+ isDisadvantage: boolean;
22
+ /** Counted in the total (not dropped by kh/kl/dh/dl) */
23
+ kept: boolean;
24
+ groupDropped?: boolean;
25
+ isNegative?: boolean;
26
+ wasExploded?: boolean;
27
+ fromExplosion?: boolean;
28
+ wasRerolled?: boolean;
29
+ imploded?: boolean;
30
+ wasMinimum?: boolean;
31
+ wasMaximum?: boolean;
32
+ /** Pools: met the target */
33
+ success?: boolean;
34
+ failure?: boolean;
35
+ criticalSuccess?: boolean;
36
+ criticalFailure?: boolean;
37
+ /** A Text Face's text; `value` then counts toward nothing */
38
+ label?: string;
39
+ isFudge?: boolean;
40
+ /** Table rolls (T notation): each part's face, highest place value first */
41
+ tablePartValues?: number[];
42
+ }
43
+ /** The dice of one term of the notation, e.g. `3d6{Red} # Fire`. */
44
+ export interface RolledGroup {
45
+ /** The label after `#` */
46
+ description?: string;
47
+ /** The bag die asked for in `{}` */
48
+ diceModel?: string;
49
+ diceType: string;
50
+ dice: RolledDie[];
51
+ /** Total of kept dice, or successes for a pool */
52
+ total: number;
53
+ /** Text Faces among the kept dice, e.g. { "Skull": 2 } */
54
+ tally?: Record<string, number>;
55
+ isNegative?: boolean;
56
+ isPool?: boolean;
57
+ /** Very large groups (70+ dice) carry totals only */
58
+ isCondensed?: boolean;
59
+ condensedCount?: number;
60
+ }
61
+ /** A finished roll, as OBR's {source}/roll-result carries it. */
62
+ export interface DiceRollResult {
63
+ rollId: string;
64
+ playerId: string;
65
+ playerName: string;
66
+ rollTarget: RollTarget;
67
+ timestamp: number;
68
+ source: string;
69
+ showResults: boolean;
70
+ result: {
71
+ rollId: string;
72
+ diceNotation: string;
73
+ totalValue: number;
74
+ rollSummary: string;
75
+ groups: RolledGroup[];
76
+ tally?: Record<string, number>;
77
+ };
78
+ }
79
+ export interface DiceRollError {
80
+ rollId: string;
81
+ error: string;
82
+ notation: string;
83
+ /** The roll still went ahead; something in the request was ignored */
84
+ warning?: true;
85
+ }
86
+ export type SettleTime = 'very-fast' | 'fast' | 'normal' | 'slow' | 'very-slow';
87
+ export type DieType = 'd1' | 'd2' | 'd3' | 'd4' | 'd6' | 'd8' | 'd10' | 'd12' | 'd20' | 'd100' | 'dF';
88
+ export type CritDice = 'all' | Array<'d2' | 'd3' | 'd4' | 'd6' | 'd8' | 'd10' | 'd12' | 'd20' | 'd100'>;
89
+ /** Everything about the tray a site controls. Anything left out uses our default. */
90
+ export interface TraySettings {
91
+ /** How long dice tumble before settling */
92
+ settleTime?: SettleTime;
93
+ /** Seconds the dice stay after a roll, 1–10 */
94
+ clearDelaySeconds?: number;
95
+ sound?: boolean;
96
+ /** Flash a die when it settles */
97
+ settleFlash?: boolean;
98
+ /** Tint dice that rolled their min or max */
99
+ resultAccent?: boolean;
100
+ /** Mark the min and max of these dice critical without cs/cf */
101
+ critHighlight?: {
102
+ enabled: boolean;
103
+ dice?: CritDice;
104
+ };
105
+ /** Play effects for critical results */
106
+ critEffects?: {
107
+ enabled: boolean;
108
+ dice?: CritDice;
109
+ theme?: string;
110
+ };
111
+ /** 'results-only' skips drawing other players' dice */
112
+ performance?: 'normal' | 'default-dice-only' | 'results-only';
113
+ graphicsQuality?: 'auto' | 'high' | 'balanced' | 'low';
114
+ /**
115
+ * A Headless Tray: rolls in real time on a hidden canvas, draws nothing and
116
+ * makes no sound, for sites that show dice only on the VTT. Results arrive
117
+ * about 1.5 s after the dice settle, as they land on other screens. Not
118
+ * switchable while this player's roll is out.
119
+ */
120
+ headless?: boolean;
121
+ }
122
+ export interface TrayIdentity {
123
+ name: string;
124
+ /** `#rrggbb` */
125
+ color: string;
126
+ }
127
+ /** A roll, in the shape of OBR's dice-plus/roll-request. The tray fills in the player. */
128
+ export interface TrayRollRequest {
129
+ diceNotation: string;
130
+ rollTarget?: RollTarget;
131
+ /** Your id for the roll; one is made if left out */
132
+ rollId?: string;
133
+ /** Echoed on the result, e.g. which button rolled it */
134
+ source?: string;
135
+ /** Look for dice the player's bag does not cover */
136
+ dice?: SiteDice;
137
+ }
138
+ /**
139
+ * A site's colors for an embed's UI, all `#rrggbb` and optional. Anything
140
+ * left out is worked out from the rest. Dice never take these.
141
+ */
142
+ export interface EmbedTheme {
143
+ /** Light or dark base; left out, it follows `background` */
144
+ mode?: 'light' | 'dark';
145
+ /** Buttons, the active tab, selected chips and links */
146
+ primary?: string;
147
+ /** The panel behind everything */
148
+ background?: string;
149
+ /** Cards, menus and dialogs; left out, a step off `background` */
150
+ surface?: string;
151
+ /** Text; left out, black or white to suit `mode` */
152
+ text?: string;
153
+ }
154
+ export interface HelloMessage {
155
+ tag: typeof EMBED_TAG;
156
+ type: 'hello';
157
+ protocol: number;
158
+ sdkVersion: string;
159
+ apiKey: string;
160
+ settings?: TraySettings;
161
+ identity?: TrayIdentity;
162
+ dice?: SiteDice;
163
+ theme?: EmbedTheme;
164
+ }
165
+ export type TrayMethods = {
166
+ roll: (request: TrayRollRequest) => {
167
+ rollId: string;
168
+ };
169
+ setSettings: (settings: TraySettings) => void;
170
+ setIdentity: (identity: TrayIdentity) => void;
171
+ setSiteDice: (dice: SiteDice | null) => void;
172
+ setTheme: (theme: EmbedTheme | null) => void;
173
+ getHistory: () => HistoryEntry[];
174
+ /** A new room with this browser as Host. In a room already, a new Room Code and Passcode: everyone else must rejoin */
175
+ createRoom: () => void;
176
+ joinRoom: (roomCode: string, passcode: string | null) => void;
177
+ leaveRoom: () => void;
178
+ /** Host or GM: a new six-digit Passcode, or null to turn it off */
179
+ setPasscode: (passcode: string | null) => void;
180
+ setGm: (playerId: string, gm: boolean) => void;
181
+ kick: (playerId: string) => void;
182
+ /** A Guest in an OBR room: ask that player to let this browser roll as them */
183
+ requestLink: (playerId: string) => void;
184
+ cancelLinkRequest: () => void;
185
+ /** End a link: this browser's own, or (the player or a GM) another's */
186
+ unlink: (guestId: string) => void;
187
+ /** This player's answer to one of `RoomState.linkAsks`. Unanswered, an ask lapses as a denial after 60 s */
188
+ answerLink: (guestId: string, allow: boolean) => void;
189
+ /** Join an OBR room as a new player, not as one of its players */
190
+ chooseNewPlayer: () => void;
191
+ /** Try the room again now after the connection gave up */
192
+ reconnect: () => void;
193
+ };
194
+ export type TrayMethod = keyof TrayMethods;
195
+ export interface CallMessage<M extends TrayMethod = TrayMethod> {
196
+ tag: typeof EMBED_TAG;
197
+ type: 'call';
198
+ id: number;
199
+ method: M;
200
+ args: Parameters<TrayMethods[M]>;
201
+ }
202
+ export interface ReplyMessage {
203
+ tag: typeof EMBED_TAG;
204
+ type: 'reply';
205
+ id: number;
206
+ ok: boolean;
207
+ value?: unknown;
208
+ error?: string;
209
+ }
210
+ export interface ReadyMessage {
211
+ tag: typeof EMBED_TAG;
212
+ type: 'ready';
213
+ protocol: number;
214
+ playerId: string;
215
+ }
216
+ export type UnauthorizedReason = 'missing' | 'unknown' | 'revoked' | 'origin' | 'protocol';
217
+ export interface UnauthorizedMessage {
218
+ tag: typeof EMBED_TAG;
219
+ type: 'unauthorized';
220
+ reason: UnauthorizedReason;
221
+ message: string;
222
+ }
223
+ /** A roll this client saw finish, held until its dice settled here. */
224
+ export interface RollResultEvent {
225
+ result: DiceRollResult;
226
+ /** Rolled by this player (or this browser as a Linked Guest) */
227
+ isOwn: boolean;
228
+ }
229
+ /** How many dice of each type the player's bag holds in each state. */
230
+ export type DiceAvailability = Partial<Record<DieType, {
231
+ active: number;
232
+ jailed: number;
233
+ }>>;
234
+ export interface HistoryEntry {
235
+ id: string;
236
+ playerId: string;
237
+ playerName: string;
238
+ rollTarget: RollTarget;
239
+ timestamp: number;
240
+ result: DiceRollResult['result'];
241
+ }
242
+ export interface RoomMemberState {
243
+ id: string;
244
+ name: string;
245
+ color: string;
246
+ platform: string;
247
+ /** Created the room (website rooms) */
248
+ host: boolean;
249
+ gm: boolean;
250
+ /** A Linked Guest: the player it rolls as */
251
+ linkedTo?: string;
252
+ }
253
+ export interface RoomState {
254
+ /** Not in a room */
255
+ solo: boolean;
256
+ /** 'offline': gave up reconnecting for now; `reconnect` tries again */
257
+ status: 'connecting' | 'connected' | 'reconnecting' | 'offline' | 'closed';
258
+ /** The Room Code as players type it, `XXXX-XXXX` */
259
+ roomCode?: string;
260
+ /** Host or GM: the room's Passcode (null when off). A guest: the one they joined with. */
261
+ passcode?: string | null;
262
+ /** This browser created the room */
263
+ isHost: boolean;
264
+ /** 'web' rooms are made on a website; 'home' rooms belong to a VTT such as OBR */
265
+ kind?: 'web' | 'home';
266
+ you?: RoomMemberState;
267
+ members: RoomMemberState[];
268
+ /** Why the room closed, e.g. 'kicked', 'wrongPasscode', 'tooManyAttempts', 'full', 'outdated' */
269
+ closeReason?: string;
270
+ /** The Passcode was refused after this browser had been let in: the Host changed it */
271
+ passcodeChanged?: boolean;
272
+ /** A Guest in a home room: VTT players this browser may ask to roll as */
273
+ linkCandidates: RoomMemberState[];
274
+ /** This browser rolls as another player */
275
+ linkedAs?: {
276
+ playerId: string;
277
+ name: string;
278
+ color: string;
279
+ };
280
+ /** Joined a home room as a new player rather than as one of its players */
281
+ asNewPlayer: boolean;
282
+ /**
283
+ * Others asking to roll as this player, oldest first: another screen of
284
+ * theirs, or the Dice+ browser extension. Show each with Allow and Deny
285
+ * (`answerLink`); unanswered, they lapse as a denial after 60 s.
286
+ */
287
+ linkAsks: LinkAskState[];
288
+ }
289
+ export interface LinkAskState {
290
+ guest: {
291
+ id: string;
292
+ name: string;
293
+ color: string;
294
+ };
295
+ /** 'extension': the Dice+ browser extension; 'web': a browser on a Dice+ site */
296
+ platform: string;
297
+ /** Milliseconds since the epoch; it lapses 60 s later */
298
+ at: number;
299
+ }
300
+ export interface NoticeEvent {
301
+ message: string;
302
+ variant: 'DEFAULT' | 'INFO' | 'ERROR' | 'SUCCESS' | 'WARNING';
303
+ }
304
+ /** A link request did not go through. 'denied', 'timeout', 'offline' and 'blocked' are about `player`. */
305
+ export interface LinkRefusedEvent {
306
+ player: string;
307
+ reason: 'denied' | 'timeout' | 'offline' | 'busy' | 'cooldown' | 'blocked' | 'unavailable';
308
+ }
309
+ export type TrayEvents = {
310
+ 'roll-result': RollResultEvent;
311
+ 'roll-error': DiceRollError;
312
+ 'dice-availability': DiceAvailability;
313
+ 'history-changed': HistoryEntry[];
314
+ 'room-state': RoomState;
315
+ 'link-refused': LinkRefusedEvent;
316
+ notice: NoticeEvent;
317
+ /** This player's own roll went out (true) or finished (false), e.g. for a "Rolling…" state */
318
+ rolling: {
319
+ rolling: boolean;
320
+ };
321
+ };
322
+ export type TrayEventName = keyof TrayEvents;
323
+ export interface EventMessage<E extends TrayEventName = TrayEventName> {
324
+ tag: typeof EMBED_TAG;
325
+ type: 'event';
326
+ name: E;
327
+ data: TrayEvents[E];
328
+ }
329
+ /** Where the player stands with Patreon, as far as the page may know. */
330
+ export interface PremiumState {
331
+ /** Signed in with Patreon in this site's Dice+ */
332
+ signedIn: boolean;
333
+ /** A paying patron: premium materials, shapes, fonts and unlimited dice */
334
+ isPremium: boolean;
335
+ }
336
+ /** The player drives the bag; the site only sets its colors. */
337
+ export type BagMethods = {
338
+ setTheme: (theme: EmbedTheme | null) => void;
339
+ };
340
+ export type BagEvents = {
341
+ 'premium-changed': PremiumState;
342
+ /** The player pressed the bag's close button; hide it if you show it as a dialog */
343
+ 'close-requested': Record<string, never>;
344
+ };
345
+ export type BagEventName = keyof BagEvents;
346
+ export type PageToTray = HelloMessage | CallMessage;
347
+ export type TrayToPage = ReadyMessage | UnauthorizedMessage | ReplyMessage | EventMessage;
348
+ export declare function isEmbedMessage(data: unknown): data is {
349
+ tag: typeof EMBED_TAG;
350
+ type: string;
351
+ };
@@ -0,0 +1,41 @@
1
+ /**
2
+ * AUTO-GENERATED FILE - DO NOT EDIT MANUALLY
3
+ * Generated by scripts/generateDiceConfig.ts
4
+ *
5
+ * This file is automatically generated from metadata.json files in
6
+ * src/features/dice/models/
7
+ *
8
+ * To add a new dice shape:
9
+ * 1. Create the model directory with mesh.tsx, collider.tsx, and metadata.json
10
+ * 2. Run: npm run generate:dice-config
11
+ * 3. This file will be automatically updated
12
+ */
13
+ export type PhysicalDiceType = "d1" | "d10" | "d12" | "d2" | "d20" | "d3" | "d4" | "d6" | "d8";
14
+ export type DiceType = PhysicalDiceType | "d100" | "dF";
15
+ export type DiceStyle = "clipped" | "d6" | "gem" | "hex" | "rhombic" | "rounded" | "sharp" | "standard";
16
+ export interface DiceVariant {
17
+ id: DiceType;
18
+ name: string;
19
+ sides: number;
20
+ meshComponent: string;
21
+ colliderComponent: string;
22
+ availableStyles: readonly DiceStyle[];
23
+ defaultStyle: DiceStyle;
24
+ }
25
+ export interface SpawnConfiguration {
26
+ position: [number, number, number];
27
+ rotation: [number, number, number];
28
+ velocity: [number, number, number];
29
+ angularVelocity: [number, number, number];
30
+ }
31
+ export declare const DICE_VARIANTS: Partial<Record<DiceType, DiceVariant>>;
32
+ export declare const STYLE_COMPONENT_MAP: Partial<Record<DiceType, Partial<Record<DiceStyle, {
33
+ mesh: string;
34
+ collider: string;
35
+ }>>>>;
36
+ export declare function getDiceVariant(diceType: DiceType): DiceVariant | undefined;
37
+ export declare function getDiceVariantSafe(diceType: DiceType): DiceVariant;
38
+ export declare function getComponentsForStyle(diceType: DiceType, style: DiceStyle): {
39
+ mesh: string;
40
+ collider: string;
41
+ };
@@ -0,0 +1,32 @@
1
+ import type { DiceStyle, DiceType } from '../dice/types/DiceTypes';
2
+ /** One die's look, from the free fields of the standard material. Anything left out keeps our default. */
3
+ export interface StandardDiceStyle {
4
+ /** Body color, `#rrggbb` */
5
+ color?: string;
6
+ /** Number color, `#rrggbb` */
7
+ numberColor?: string;
8
+ /** Free fonts only: 'standard', 'norse' or 'aelfa' */
9
+ font?: string;
10
+ /** A free shape for the die type, e.g. 'sharp' or 'rounded' */
11
+ shape?: DiceStyle;
12
+ /** 0–1 */
13
+ roughness?: number;
14
+ /** 0–1 */
15
+ metalness?: number;
16
+ /** 0–1 */
17
+ opacity?: number;
18
+ /** 0–1, glossy clear coat */
19
+ sheen?: number;
20
+ /** 0–1, how deep the numbers are engraved */
21
+ numberDepth?: number;
22
+ }
23
+ /** The look for a roll, or for the whole site: a default, per die type, and per named die. */
24
+ export interface SiteDice {
25
+ default?: StandardDiceStyle;
26
+ byType?: Partial<Record<DiceType, StandardDiceStyle>>;
27
+ /**
28
+ * Dice the notation calls by name, as in `1d12{Hope}`, for players whose
29
+ * bag has no die of that name
30
+ */
31
+ byName?: Record<string, StandardDiceStyle>;
32
+ }
@@ -0,0 +1,247 @@
1
+ export declare const RELAY_PROTOCOL = 1;
2
+ /** 'extension': a Roll Link (the Dice+ browser extension), which rolls on its linked player's tray. */
3
+ export type RelayPlatform = 'web' | 'obr' | 'embed' | 'foundry' | 'extension';
4
+ /** The `source` a Roll Link's roll requests carry, so its errors can find their way back. */
5
+ export declare const ROLL_LINK_SOURCE = "browser-extension";
6
+ /** The channel a Roll Link's roll request reaches its player's tray on: the external roll request. */
7
+ export declare const ROLL_LINK_REQUEST_CHANNEL = "dice-plus/roll-request";
8
+ /**
9
+ * 'web' rooms are temporary sessions created on the website; 'home' rooms
10
+ * belong to a dedicated client's own room (an OBR room, a Foundry world).
11
+ */
12
+ export type RoomKind = 'web' | 'home';
13
+ export interface RelayPlayer {
14
+ id: string;
15
+ name: string;
16
+ color: string;
17
+ }
18
+ export interface RelayMember extends RelayPlayer {
19
+ platform: RelayPlatform;
20
+ /** What the player publishes about themselves (custom models, fonts), like OBR player metadata. */
21
+ metadata: Record<string, unknown>;
22
+ /** Holds the room key of a website room: assigns GM Tags. */
23
+ host: boolean;
24
+ /** Receives GM-only and GM & Self rolls. */
25
+ gm: boolean;
26
+ /**
27
+ * A Linked Guest: the Home Group player it rolls as. Its messages come from
28
+ * that id, and its name, color and GM Tag are that player's.
29
+ */
30
+ linkedTo?: string;
31
+ }
32
+ /** Why the Relay did not pass on, or the player did not allow, a link request. */
33
+ export type LinkRefusal = 'denied'
34
+ /** The player did not answer in time. */
35
+ | 'timeout'
36
+ /** Not in the Room's Home Group now. */
37
+ | 'offline'
38
+ /** A request is already waiting, or this guest is already linked. */
39
+ | 'busy'
40
+ /** Asked the same player again too soon. */
41
+ | 'cooldown'
42
+ /** That player denied this connection too often. */
43
+ | 'blocked'
44
+ /** The Home Group and the Host cannot link, nor can anyone link to themselves. */
45
+ | 'unavailable'
46
+ /** That player already has as many Roll Links as the Relay allows. */
47
+ | 'full';
48
+ /** Why the Relay did not pass on a Roll Link's roll request. */
49
+ export type RollRefusal =
50
+ /** Not linked to a player. */
51
+ 'unlinked'
52
+ /** The linked player has no connection that can roll. */
53
+ | 'unavailable'
54
+ /** Too many roll requests; wait a moment. */
55
+ | 'rateLimited'
56
+ /** Missing a roll id, the notation is too long, or the request is too large. */
57
+ | 'invalid';
58
+ /** Who a message is for. Absent: everyone. Otherwise GM-tagged members and/or these player ids. */
59
+ export interface Audience {
60
+ gm?: boolean;
61
+ to?: string[];
62
+ }
63
+ export type ClientMessage = {
64
+ t: 'join';
65
+ v: number;
66
+ player: RelayPlayer;
67
+ platform: RelayPlatform;
68
+ metadata?: Record<string, unknown>;
69
+ /** The room key. The first join with a key creates the room's claim to it. */
70
+ key?: string;
71
+ /** With a valid key in a home room: this player is a GM on their own platform. */
72
+ claimGm?: boolean;
73
+ /** Only read when the key first claims the room. */
74
+ kind?: RoomKind;
75
+ /**
76
+ * Guests: the room's Passcode. The Host or a platform GM (with the key):
77
+ * the Passcode to set, null to turn it off; absent leaves it as it is.
78
+ */
79
+ passcode?: string | null;
80
+ /** A Linked Guest's token from an earlier `linked`: joins already linked. */
81
+ link?: string;
82
+ } | {
83
+ t: 'send';
84
+ ch: string;
85
+ data: unknown;
86
+ aud?: Audience;
87
+ keep?: boolean;
88
+ } | {
89
+ t: 'profile';
90
+ name: string;
91
+ color: string;
92
+ metadata?: Record<string, unknown>;
93
+ } | {
94
+ t: 'setGm';
95
+ player: string;
96
+ gm: boolean;
97
+ } | {
98
+ t: 'kick';
99
+ player: string;
100
+ }
101
+ /** The Host or a platform GM: a new Passcode, or null for none. Players already in stay. */
102
+ | {
103
+ t: 'setPasscode';
104
+ passcode: string | null;
105
+ }
106
+ /** A Guest: ask this player (one in their own right, not a Linked Guest) to let it roll as them. */
107
+ | {
108
+ t: 'linkRequest';
109
+ player: string;
110
+ }
111
+ /** The Guest gave up waiting. */
112
+ | {
113
+ t: 'linkCancel';
114
+ }
115
+ /** The asked player's answer. */
116
+ | {
117
+ t: 'linkAnswer';
118
+ guest: string;
119
+ allow: boolean;
120
+ timedOut?: boolean;
121
+ }
122
+ /** End a link: the Linked Guest itself, the player it rolls as, or a GM. */
123
+ | {
124
+ t: 'unlink';
125
+ guest: string;
126
+ }
127
+ /**
128
+ * A Linked Guest with no tray of its own (a Roll Link): roll this on the
129
+ * linked player's tray. `data` is a dice-plus/roll-request; the Relay sets
130
+ * its player.
131
+ */
132
+ | {
133
+ t: 'rollRequest';
134
+ data: unknown;
135
+ };
136
+ export interface RelayEnvelope {
137
+ from: string;
138
+ ch: string;
139
+ data: unknown;
140
+ }
141
+ export type ServerMessage = {
142
+ t: 'welcome';
143
+ you: RelayMember;
144
+ members: RelayMember[];
145
+ history: RelayEnvelope[];
146
+ kind: RoomKind;
147
+ } | {
148
+ t: 'members';
149
+ members: RelayMember[];
150
+ } | ({
151
+ t: 'msg';
152
+ } & RelayEnvelope)
153
+ /** To the asked player's sockets: a Guest wants to roll as them, from this platform (absent from older relays). */
154
+ | {
155
+ t: 'linkAsk';
156
+ guest: RelayPlayer;
157
+ platform?: RelayPlatform;
158
+ }
159
+ /** To the asked player's sockets: the request is over (answered, cancelled, or the Guest left). */
160
+ | {
161
+ t: 'linkClosed';
162
+ guest: string;
163
+ }
164
+ /** To the Guest: it now rolls as `player`. Keep the token to rejoin linked. */
165
+ | {
166
+ t: 'linked';
167
+ player: string;
168
+ token: string;
169
+ } | {
170
+ t: 'linkRefused';
171
+ player: string;
172
+ reason: LinkRefusal;
173
+ }
174
+ /** To a Linked Guest: the link was ended. */
175
+ | {
176
+ t: 'unlinked';
177
+ }
178
+ /** To a Roll Link: its roll request went nowhere. */
179
+ | {
180
+ t: 'rollRefused';
181
+ rollId: string;
182
+ reason: RollRefusal;
183
+ };
184
+ /** WebSocket close codes the Relay uses; clients stop reconnecting on all but `replaced`. */
185
+ export declare const RELAY_CLOSE: {
186
+ readonly kicked: 4001;
187
+ readonly full: 4002;
188
+ readonly rateLimited: 4003;
189
+ readonly tooLarge: 4004;
190
+ readonly badRequest: 4005;
191
+ /** The same player connected again elsewhere (another tab took over). */
192
+ readonly replaced: 4006;
193
+ readonly outdated: 4007;
194
+ /** No Passcode, or the wrong one. */
195
+ readonly wrongPasscode: 4008;
196
+ /** Too many wrong Passcodes from this address, or for this room; try again later. */
197
+ readonly tooManyAttempts: 4009;
198
+ };
199
+ export declare const RELAY_LIMITS: {
200
+ readonly maxSockets: 20;
201
+ /** One wire message: a 64KB broadcast payload plus its envelope. */
202
+ readonly maxMessageBytes: number;
203
+ /** Token bucket per socket: sustained messages per second, and the burst a large chunked roll needs. */
204
+ readonly messagesPerSecond: 5;
205
+ readonly burst: 64;
206
+ readonly keptMessages: 50;
207
+ /** A member's published metadata, as JSON. */
208
+ readonly maxMetadataBytes: number;
209
+ readonly webRoomIdleMs: number;
210
+ readonly homeRoomIdleMs: number;
211
+ /** How long a link request waits for its answer. */
212
+ readonly linkAskMs: number;
213
+ /** Before the same Guest may ask the same player again. */
214
+ readonly linkCooldownMs: number;
215
+ /** Denials from one player before that connection may not ask them again. */
216
+ readonly linkDenials: 3;
217
+ /** Links a Room remembers. */
218
+ readonly maxLinks: 64;
219
+ /** Wrong Passcodes from one address within a minute before it is turned away for a minute. */
220
+ readonly passcodeTriesPerAddress: 5;
221
+ readonly passcodeAddressWindowMs: number;
222
+ readonly passcodeAddressBlockMs: number;
223
+ /** Wrong Passcodes for the room within 15 minutes before it refuses Passcode joins for 15 minutes. */
224
+ readonly passcodeTriesPerRoom: 50;
225
+ readonly passcodeRoomWindowMs: number;
226
+ readonly passcodeRoomLockMs: number;
227
+ /** Roll Links' roll requests, per socket: the burst, then one every two seconds. */
228
+ readonly rollRequestBurst: 5;
229
+ readonly rollRequestsPerSecond: 0.5;
230
+ /** A roll request as JSON, and its notation. */
231
+ readonly maxRollRequestBytes: number;
232
+ readonly maxNotationLength: 500;
233
+ readonly rollIdLength: 64;
234
+ /** Roll Links linked to one player at once. */
235
+ readonly rollLinksPerPlayer: 3;
236
+ };
237
+ export declare const ROOM_ID_PATTERN: RegExp;
238
+ /** A Passcode: six digits, leading zeros kept. */
239
+ export declare const PASSCODE_PATTERN: RegExp;
240
+ /**
241
+ * A room id from what a player typed: Room Codes ignore case, spaces and the
242
+ * dash, and read I and L as 1 and O as 0. Older long ids pass through exactly.
243
+ */
244
+ export declare function normalizeRoomId(input: string): string | null;
245
+ /** The keepalive text the Relay answers without waking (setWebSocketAutoResponse). */
246
+ export declare const RELAY_PING = "ping";
247
+ export declare const RELAY_PONG = "pong";
@@ -0,0 +1,12 @@
1
+ /** Random URL-safe text: 32 bytes for a Room key. */
2
+ export declare function randomToken(bytes: number): string;
3
+ /** 8 Crockford base32 characters: short enough to read out, 40 bits so codes never collide. */
4
+ export declare function newRoomCode(): string;
5
+ export declare function newPasscode(): string;
6
+ export declare function newRoomCredentials(): {
7
+ id: string;
8
+ key: string;
9
+ passcode: string;
10
+ };
11
+ /** `K7M2-QX9P`; older long ids as they are. */
12
+ export declare function formatRoomCode(roomId: string): string;
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "@dice-plus/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.3.0",
4
+ "description": "Embed the Dice+ 3D physics dice tray and dice bag on your site",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "MissingLinkDev",
8
+ "homepage": "https://dice-plus.missinglinkdev.com/devs",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/MissingLinkDev/dice-plus.git",
12
+ "directory": "sdk"
13
+ },
14
+ "keywords": ["dice", "dice-roller", "3d", "physics", "ttrpg", "owlbear-rodeo", "vtt"],
15
+ "main": "./dist/index.js",
16
+ "module": "./dist/index.js",
17
+ "types": "./dist/types/sdk/src/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/types/sdk/src/index.d.ts",
21
+ "import": "./dist/index.js"
22
+ }
23
+ },
24
+ "files": ["dist", "README.md", "LICENSE"],
25
+ "sideEffects": false,
26
+ "scripts": {
27
+ "build": "vite build && tsc -p tsconfig.build.json",
28
+ "typecheck": "tsc --noEmit",
29
+ "prepublishOnly": "npm run build"
30
+ }
31
+ }