dewdrop-sdk 0.4.0 → 0.4.1

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/README.md CHANGED
@@ -27,8 +27,9 @@ or later.
27
27
  On Dewdrop, `localStorage` and IndexedDB aren't local: nothing your game
28
28
  writes to them is stored in the player's browser or on their device, and they
29
29
  start empty each time a player opens your game. `saves.save()` keeps what they
30
- hold in Dewdrop's storage for that player, and `saves.load()` puts it back;
31
- each upload of your game starts with none.
30
+ hold in Dewdrop's storage for that player, and `saves.load()` puts it back,
31
+ in later uploads of your game too. A game with a `backend.js` keeps no saves:
32
+ its state is its rooms', and both calls refuse with `NotSupportedError`.
32
33
  `npm run dev` does the same in your browser: every page load starts with
33
34
  `localStorage` and IndexedDB empty, and saves are kept in the browser, in a
34
35
  database named `dewdrop-saves` your game doesn't see, for the game
@@ -36,6 +37,27 @@ database named `dewdrop-saves` your game doesn't see, for the game
36
37
  of one dev server share the browser's storage, so loading one empties the
37
38
  others'.
38
39
 
40
+ ## Rooms locally
41
+
42
+ `npm run dev` runs your `backend.js` for each room the tabs join: `?room=`
43
+ names the room, `?player=` the player, and `?players=` how many players a
44
+ room the tab opens seats, 100 unless it says 1 to 100, as Dewdrop's rooms
45
+ do; `?players=1` is singleplayer. A player is counted once however many tabs
46
+ they play from, and a tab past a full room is refused, with the reason in
47
+ the console. In the backend, `clients.capacity` is the room's size.
48
+
49
+ ## Sessions that end
50
+
51
+ On Dewdrop a session can end ahead of time: for maintenance, or a newer
52
+ version of your game published. Its player sees a countdown and reconnects
53
+ on their own, and your game hears of it first, up to fifteen minutes
54
+ before: `session.ending` from `dewdrop-sdk` is `{at, reason}`, `at` in
55
+ milliseconds as `Date.now()` counts and `reason` `'restart'` or `'update'`,
56
+ and an `ending` event fires each time it changes, its withdrawal to `null`
57
+ included. Call `saves.save()` then to keep what the player has done. `npm
58
+ run dev` ends no session ahead of time, so `session.ending` stays `null`
59
+ there.
60
+
39
61
  ## Docs
40
62
 
41
63
  How to build your game, from the look to model calls, multiplayer, saves and
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dewdrop-sdk",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "description": "Build a three.js game for Dewdrop: the Vite plugin, model calls, multiplayer and saves.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -11,7 +11,7 @@ import { pathToFileURL } from 'node:url';
11
11
  import { attachClients } from './clients.js';
12
12
 
13
13
  process.env.DEW_DEV_ORIGIN = workerData.origin;
14
- const start = attachClients(parentPort);
14
+ const start = attachClients(parentPort, { capacity: workerData.capacity });
15
15
  await import(pathToFileURL(workerData.entry).href);
16
16
  process.on('uncaughtException', (error) => console.error(`uncaught ${error?.stack ?? error}`));
17
17
  start();
package/src/backend.js CHANGED
@@ -7,7 +7,7 @@
7
7
  // past its cap. The page's URL says which room the tab joins and under
8
8
  // what name; on Dewdrop the game's page says which room, and the name is
9
9
  // the player's username.
10
- import { MAX_NET_CLIENT_FRAME_BYTES, createInbox, createOutbox, defineHandlers, label, side, unpack } from './net.js';
10
+ import { MAX_NET_CLIENTS, MAX_NET_CLIENT_FRAME_BYTES, createInbox, createOutbox, defineHandlers, label, side, unpack } from './net.js';
11
11
  import { NO_CHANNEL } from './route.js';
12
12
 
13
13
  let channel = null;
@@ -58,20 +58,35 @@ function name(text) {
58
58
  return label(text.replace(/\p{Cc}/gu, '').trim());
59
59
  }
60
60
 
61
- // Where a page's URL joins its tab: the room `?room=` names and the name
62
- // `?player=` names, each held to Dewdrop's rule — the empty room without
61
+ // The players a room seats as `?players=` names them: a whole number from
62
+ // 1 to MAX_NET_CLIENTS, or the most without one or with any other.
63
+ function players(text) {
64
+ return /^[0-9]{1,3}$/.test(text) && Number(text) >= 1 && Number(text) <= MAX_NET_CLIENTS ? Number(text) : MAX_NET_CLIENTS;
65
+ }
66
+
67
+ // Where a page's URL joins its tab: the room `?room=` names, the name
68
+ // `?player=` names, and the players `?players=` says the room seats should
69
+ // the tab make it, each held to Dewdrop's rule — the empty room without
63
70
  // one, or with one that names no room; unnamed without a name, or with one
64
71
  // that is nothing but space and control characters.
65
72
  export function joining(search) {
66
73
  const params = new URLSearchParams(search);
67
- return { room: room(params.get('room') ?? ''), player: name(params.get('player') ?? '') };
74
+ return { room: room(params.get('room') ?? ''), player: name(params.get('player') ?? ''), players: players(params.get('players') ?? '') };
75
+ }
76
+
77
+ // Whether the page's game has a backend, as the plugin said; false until
78
+ // it has.
79
+ export function gameHasBackend() {
80
+ return hasBackend;
68
81
  }
69
82
 
70
83
  // Joins the backend of `room` under `player`'s name over `hot`, the page's
71
- // hot context, once the plugin has said whether the game has one:
72
- // `present` is that, `schedule` runs a function at the next animation
73
- // frame. Without a plugin there is no channel, and `send` says so.
74
- export function attachBackend(hot, { channel: routed, hasBackend: present, frame: schedule, room = '', player = '' }) {
84
+ // hot context, once the plugin has said whether the game has one, a room
85
+ // it makes seating `players`: `present` is that, `schedule` runs a
86
+ // function at the next animation frame. Without a plugin there is no
87
+ // channel, and `send` says so. A room that seats no more says so in the
88
+ // console, as Dewdrop refuses the connect, and the tab's sends reach no one.
89
+ export function attachBackend(hot, { channel: routed, hasBackend: present, frame: schedule, room = '', player = '', players = MAX_NET_CLIENTS }) {
75
90
  if (!routed) return;
76
91
  channel = hot;
77
92
  hasBackend = present;
@@ -83,5 +98,6 @@ export function attachBackend(hot, { channel: routed, hasBackend: present, frame
83
98
  draining = true;
84
99
  frame(deliver);
85
100
  });
86
- hot.send('dew:join', { room, player });
101
+ hot.on('dew:full', ({ capacity }) => console.error(`[dewdrop] this room is full: it seats ${capacity === 1 ? '1 player' : `${capacity} players`}`));
102
+ hot.send('dew:join', { room, player, players });
87
103
  }
package/src/clients.js CHANGED
@@ -1,15 +1,16 @@
1
1
  // `clients` on a developer's machine: the backend's side of the messages a
2
- // game exchanges with its clients, run by the plugin in a thread of the
3
- // dev server with a port to the plugin, which carries each message over
4
- // the socket to the tab it names. The thread ticks sixty times a second:
2
+ // game exchanges with its clients, and the most players its room seats,
3
+ // run by the plugin in a thread of the dev server with a port to the
4
+ // plugin, which carries each message over the socket to the tab it names. The thread ticks sixty times a second:
5
5
  // each tick delivers what the clients sent as `join`, `leave`, `message`,
6
6
  // and `gap` events — a join naming the player's label — runs the
7
7
  // animation-frame callbacks, and sends the frame's messages.
8
- import { MAX_NET_BACKEND_FRAME_BYTES, NET_TICK_MS, ClientEvent, createInbox, createOutbox, defineHandlers, side, unpack } from './net.js';
8
+ import { MAX_NET_BACKEND_FRAME_BYTES, MAX_NET_CLIENTS, NET_TICK_MS, ClientEvent, createInbox, createOutbox, defineHandlers, side, unpack } from './net.js';
9
9
 
10
10
  const outbox = createOutbox(MAX_NET_BACKEND_FRAME_BYTES);
11
11
  const inbox = createInbox();
12
12
  let port = null;
13
+ let seats = 0;
13
14
 
14
15
  // A client number as the backend was told it: a whole number from one.
15
16
  function number(op, value) {
@@ -28,6 +29,12 @@ class Clients extends EventTarget {
28
29
  if (port === null) throw new DOMException('clients is unavailable in a client', 'NotSupportedError');
29
30
  outbox.push('clients.broadcast', 0, data);
30
31
  }
32
+ // The most players the room seats, as it was made: 1 for a room of one,
33
+ // a player counted once however many clients they play from.
34
+ get capacity() {
35
+ if (port === null) throw new DOMException('clients is unavailable in a client', 'NotSupportedError');
36
+ return seats;
37
+ }
31
38
  }
32
39
  defineHandlers(Clients.prototype, ['join', 'leave', 'message', 'gap']);
33
40
 
@@ -76,9 +83,11 @@ function frame() {
76
83
  // held until the returned function starts the ticks, which the host calls
77
84
  // once the backend has evaluated, so the first tick delivers what arrived
78
85
  // meanwhile, the first join included, to the handlers the module
79
- // registered. `tick` runs the frame once per tick from then on.
80
- export function attachClients(channel, { tick = (fn) => setInterval(fn, NET_TICK_MS) } = {}) {
86
+ // registered. `tick` runs the frame once per tick from then on, and
87
+ // `capacity` is the most players the room seats.
88
+ export function attachClients(channel, { tick = (fn) => setInterval(fn, NET_TICK_MS), capacity = MAX_NET_CLIENTS } = {}) {
81
89
  port = channel;
90
+ seats = capacity;
82
91
  side.backend = true;
83
92
  if (typeof globalThis.requestAnimationFrame !== 'function') {
84
93
  globalThis.requestAnimationFrame = requestAnimationFrame;
package/src/index.js CHANGED
@@ -4,10 +4,12 @@
4
4
  // over its route, `backend` over its socket to the backend the plugin
5
5
  // runs, `clients`, in that backend, over its port back, and `saves` into
6
6
  // the browser's own storage, which the plugin's script empties as each
7
- // page loads.
7
+ // page loads; `session` says when a session ends ahead of time, which here
8
+ // none does.
8
9
  export { llm } from './llm.js';
9
10
  export { backend } from './backend.js';
10
11
  export { clients } from './clients.js';
12
+ export { session } from './session.js';
11
13
  import { attachBackend, joining } from './backend.js';
12
14
  import { load, save } from './saves.js';
13
15
 
@@ -30,5 +32,6 @@ if (typeof document !== 'undefined' && import.meta.hot) {
30
32
  frame: (fn) => requestAnimationFrame(fn),
31
33
  room: joined.room,
32
34
  player: joined.player,
35
+ players: joined.players,
33
36
  });
34
37
  }
package/src/net.js CHANGED
@@ -15,6 +15,9 @@ export const NET_RECORD_HEADER_BYTES = 16;
15
15
  // The most bytes a player's label takes: the name the player joined
16
16
  // under, which the backend hears on the join.
17
17
  export const MAX_NET_PLAYER_BYTES = 64;
18
+ // The most players a room seats, and the most clients it holds: a room's
19
+ // size is 1 to this.
20
+ export const MAX_NET_CLIENTS = 100;
18
21
  // How often the local backend ticks: sixty times a second.
19
22
  export const NET_TICK_MS = 1000 / 60;
20
23
 
package/src/saves.js CHANGED
@@ -6,7 +6,7 @@
6
6
  // names and the player the page's URL names, and `load` puts it back.
7
7
  // Calls run in the order they are made, and the checks and their messages
8
8
  // are Dewdrop's, so a call that fails here fails there the same way.
9
- import { joining } from './backend.js';
9
+ import { gameHasBackend, joining } from './backend.js';
10
10
  import { SAVES_STATE } from './fresh.js';
11
11
  import { side } from './net.js';
12
12
  import { NO_SAVES } from './route.js';
@@ -24,10 +24,11 @@ let last = Promise.resolve();
24
24
  let loads = 0;
25
25
 
26
26
  // Runs `run` once every call made before has settled and the page's
27
- // storage has started empty; refused at once in a backend, and in a page
28
- // without the plugin's script.
27
+ // storage has started empty; refused at once in a game with a backend —
28
+ // its backend and its tabs alike, as on Dewdrop, where such a game keeps
29
+ // no saves — and in a page without the plugin's script.
29
30
  function inOrder(op, run) {
30
- if (side.backend) return Promise.reject(new DOMException('saves is unavailable in a backend', 'NotSupportedError'));
31
+ if (side.backend || gameHasBackend()) return Promise.reject(new DOMException('saves is unavailable in a game with a backend', 'NotSupportedError'));
31
32
  const state = globalThis[Symbol.for(SAVES_STATE)];
32
33
  if (state === undefined) return Promise.reject(new TypeError(`${op}: ${NO_SAVES}`));
33
34
  const call = last.then(() => state.ready).then(() => run(state));
package/src/serve.js CHANGED
@@ -1,7 +1,10 @@
1
1
  // The dev server's backend host, its stand-in for Dewdrop. A thread runs
2
2
  // the project's backend.js for each room the tabs join, from the room's
3
3
  // first tab's join until five minutes after its last tab's leave, as on
4
- // Dewdrop, so a tab that comes back in that time rejoins it; the tabs are
4
+ // Dewdrop, so a tab that comes back in that time rejoins it; a room seats
5
+ // the players its first tab's page said, a player counted once however
6
+ // many tabs they play from and an unnamed tab as one each, and refuses a
7
+ // tab past them as Dewdrop refuses its connect; the tabs are
5
8
  // numbered from one per room, never twice while its thread runs; each
6
9
  // tab's frame of sends reaches its room's thread over the port
7
10
  // with the tab's number, and each of the thread's sends reaches the tab it
@@ -14,7 +17,7 @@
14
17
  import { existsSync, readFileSync } from 'node:fs';
15
18
  import { dirname, resolve } from 'node:path';
16
19
  import { Worker } from 'node:worker_threads';
17
- import { label } from './net.js';
20
+ import { MAX_NET_CLIENTS, label } from './net.js';
18
21
 
19
22
  // How long a room's backend runs on after its last tab's leave, as on
20
23
  // Dewdrop.
@@ -47,12 +50,14 @@ export function createBackendHost({ entry, ws, watcher, origin = () => '', log =
47
50
  const rooms = new Map();
48
51
  const tabs = new Map();
49
52
 
50
- // One room's backend: its thread from the room's first tab's join until
51
- // EMPTY_ROOM_MS after its last tab's leave with none joining since, its
52
- // tabs by number from one.
53
- function createRoom(key) {
53
+ // One room's backend, seating `capacity` players: its thread from the
54
+ // room's first tab's join until EMPTY_ROOM_MS after its last tab's leave
55
+ // with none joining since, its tabs by number from one with their
56
+ // players' names.
57
+ function createRoom(key, capacity) {
54
58
  const name = key === '' ? 'the backend' : `the backend of room ${JSON.stringify(key)}`;
55
59
  const members = new Map();
60
+ const names = new Map();
56
61
  let worker = null;
57
62
  let next = 1;
58
63
  let broken = false;
@@ -68,7 +73,7 @@ export function createBackendHost({ entry, ws, watcher, origin = () => '', log =
68
73
 
69
74
  function start() {
70
75
  files = backendFiles(entry);
71
- worker = new Worker(new URL('./backend-host.js', import.meta.url), { workerData: { entry, origin: origin() } });
76
+ worker = new Worker(new URL('./backend-host.js', import.meta.url), { workerData: { entry, origin: origin(), capacity } });
72
77
  const started = worker;
73
78
  started.on('message', (message) => {
74
79
  if (message.kind === 'send' && worker === started) deliver(message.sends);
@@ -89,6 +94,7 @@ export function createBackendHost({ entry, ws, watcher, origin = () => '', log =
89
94
  idle = null;
90
95
  for (const client of members.keys()) tabs.delete(client);
91
96
  members.clear();
97
+ names.clear();
92
98
  next = 1;
93
99
  if (ended !== null) ended.terminate();
94
100
  }
@@ -101,13 +107,26 @@ export function createBackendHost({ entry, ws, watcher, origin = () => '', log =
101
107
  broken = true;
102
108
  }
103
109
 
110
+ // The room's players, each once: its tabs' names, and each unnamed tab.
111
+ function seated() {
112
+ const players = [...names.values()];
113
+ return players.filter((player, at) => player === '' || players.indexOf(player) === at).length;
114
+ }
115
+
104
116
  const room = {
105
117
  join(client, player) {
106
118
  if (broken) return;
119
+ const returning = player !== '' && [...names.values()].includes(player);
120
+ if (members.size >= MAX_NET_CLIENTS || (!returning && seated() >= capacity)) {
121
+ log.error(`[dewdrop] a tab is refused ${name}: it seats ${capacity === 1 ? '1 player' : `${capacity} players`}`);
122
+ client.send('dew:full', { capacity });
123
+ return;
124
+ }
107
125
  clearTimeout(idle);
108
126
  idle = null;
109
127
  const number = next++;
110
128
  members.set(client, number);
129
+ names.set(client, player);
111
130
  tabs.set(client, room);
112
131
  if (worker === null) start();
113
132
  worker.postMessage([{ kind: 'join', client: number, player }]);
@@ -117,6 +136,7 @@ export function createBackendHost({ entry, ws, watcher, origin = () => '', log =
117
136
  const number = members.get(client);
118
137
  if (number === undefined) return;
119
138
  members.delete(client);
139
+ names.delete(client);
120
140
  tabs.delete(client);
121
141
  worker.postMessage([{ kind: 'leave', client: number }]);
122
142
  if (members.size === 0) {
@@ -151,14 +171,17 @@ export function createBackendHost({ entry, ws, watcher, origin = () => '', log =
151
171
  }
152
172
 
153
173
  const host = {
154
- // A tab joins the room its page named under the name it gave; a page
155
- // that named neither joins the empty room unnamed.
156
- join(client, { room = '', player = '' } = {}) {
174
+ // A tab joins the room its page named under the name it gave, a room
175
+ // it makes seating the players its page said; a page that named
176
+ // neither joins the empty room unnamed, and one that named no size a
177
+ // room seating the most.
178
+ join(client, { room = '', player = '', players = MAX_NET_CLIENTS } = {}) {
157
179
  if (tabs.has(client)) return;
158
180
  const key = typeof room === 'string' ? room : '';
159
181
  let it = rooms.get(key);
160
182
  if (it === undefined) {
161
- it = createRoom(key);
183
+ const capacity = Number.isInteger(players) && players >= 1 && players <= MAX_NET_CLIENTS ? players : MAX_NET_CLIENTS;
184
+ it = createRoom(key, capacity);
162
185
  rooms.set(key, it);
163
186
  }
164
187
  it.join(client, label(player));
@@ -171,7 +194,7 @@ export function createBackendHost({ entry, ws, watcher, origin = () => '', log =
171
194
  },
172
195
  close,
173
196
  };
174
- ws.on('dew:join', (data, client) => host.join(client, { room: data?.room, player: data?.player }));
197
+ ws.on('dew:join', (data, client) => host.join(client, { room: data?.room, player: data?.player, players: data?.players }));
175
198
  ws.on('dew:send', (data, client) => host.receive(client, data.items ?? []));
176
199
  watcher.on('change', (file) => {
177
200
  if (files.has(resolve(file))) restart(`${file} changed`);
package/src/session.js ADDED
@@ -0,0 +1,17 @@
1
+ // `session` on a developer's machine. On Dewdrop a session can end ahead of
2
+ // time — for maintenance, or a newer version of its game published — and
3
+ // hears of it first, up to fifteen minutes before: `session.ending` is
4
+ // `{at, reason}`, `at` in milliseconds since the epoch as `Date.now()` counts
5
+ // and `reason` `'restart'` or `'update'`, and an `ending` event fires each
6
+ // time it changes, its withdrawal to null included, so a game can save and
7
+ // say so. `npm run dev` ends no session ahead of time, so here `ending`
8
+ // stays null and the event never fires; a game tries its handler by calling
9
+ // it.
10
+ import { defineHandlers } from './net.js';
11
+
12
+ class Session extends EventTarget {
13
+ get ending() { return null; }
14
+ }
15
+ defineHandlers(Session.prototype, ['ending']);
16
+
17
+ export const session = new Session();