@dovetail-ts/server 0.0.0-stage → 1.0.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/CHANGELOG.md +20 -0
- package/LICENSE +21 -0
- package/README.md +149 -2
- package/dist/browser.d.ts +6 -0
- package/dist/browser.js +3 -0
- package/dist/browser.js.map +1 -0
- package/dist/chunk-YXFPYQRL.js +685 -0
- package/dist/chunk-YXFPYQRL.js.map +1 -0
- package/dist/http.d.ts +29 -0
- package/dist/in-page.d.ts +22 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +213 -0
- package/dist/index.js.map +1 -0
- package/dist/server.d.ts +155 -0
- package/dist/socket.d.ts +28 -0
- package/dist/stores.d.ts +66 -0
- package/package.json +56 -3
|
@@ -0,0 +1,685 @@
|
|
|
1
|
+
import { DEFAULT_LIMITS, isUserRoom, userRoom, NOTIFICATION_TYPE, parseMessage, negotiateVersion, SUPPORTED_VERSIONS, fromBase64, toBase64, encodeMessage } from '@dovetail-ts/protocol';
|
|
2
|
+
|
|
3
|
+
// src/stores.ts
|
|
4
|
+
var TooLargeError = class extends Error {
|
|
5
|
+
};
|
|
6
|
+
var MemoryDocPersistence = class {
|
|
7
|
+
maxDocBytes;
|
|
8
|
+
#updates = /* @__PURE__ */ new Map();
|
|
9
|
+
constructor(options = {}) {
|
|
10
|
+
this.maxDocBytes = options.maxDocBytes ?? 16 * 1024 * 1024;
|
|
11
|
+
}
|
|
12
|
+
append(room, doc, update) {
|
|
13
|
+
const key = JSON.stringify([room, doc]);
|
|
14
|
+
let entry = this.#updates.get(key);
|
|
15
|
+
if (!entry) this.#updates.set(key, entry = { list: [], bytes: 0 });
|
|
16
|
+
if (entry.bytes + update.length > this.maxDocBytes)
|
|
17
|
+
throw new TooLargeError(`The document is larger than ${this.maxDocBytes} bytes.`);
|
|
18
|
+
entry.list.push(update);
|
|
19
|
+
entry.bytes += update.length;
|
|
20
|
+
}
|
|
21
|
+
load(room, doc) {
|
|
22
|
+
return [...this.#updates.get(JSON.stringify([room, doc]))?.list ?? []];
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
var copy = (n) => structuredClone(n);
|
|
26
|
+
var MATCH = {
|
|
27
|
+
all: (n) => !n.attributes.archivedAt,
|
|
28
|
+
unread: (n) => !n.attributes.archivedAt && !n.attributes.readAt,
|
|
29
|
+
archived: (n) => Boolean(n.attributes.archivedAt)
|
|
30
|
+
};
|
|
31
|
+
var MemoryNotificationStore = class {
|
|
32
|
+
/** The notifications of each user, the oldest first. */
|
|
33
|
+
#users = /* @__PURE__ */ new Map();
|
|
34
|
+
/** The users that have notifications. */
|
|
35
|
+
get users() {
|
|
36
|
+
return this.#users.size;
|
|
37
|
+
}
|
|
38
|
+
/** The list of a user. A read does not add the user. */
|
|
39
|
+
#of(userId) {
|
|
40
|
+
return this.#users.get(userId) ?? [];
|
|
41
|
+
}
|
|
42
|
+
async add(userId, notification) {
|
|
43
|
+
const list = this.#of(userId);
|
|
44
|
+
this.#users.set(userId, list);
|
|
45
|
+
list.push(copy(notification));
|
|
46
|
+
}
|
|
47
|
+
async get(userId, id) {
|
|
48
|
+
const found = this.#of(userId).find((n) => n.id === id);
|
|
49
|
+
return found ? copy(found) : null;
|
|
50
|
+
}
|
|
51
|
+
async list(userId, query) {
|
|
52
|
+
const limit = Math.min(Math.max(query.limit ?? 20, 1), 100);
|
|
53
|
+
let items = [...this.#of(userId)].reverse().filter(MATCH[query.filter ?? "all"]);
|
|
54
|
+
if (query.before !== void 0) {
|
|
55
|
+
const at = items.findIndex((n) => n.id === query.before);
|
|
56
|
+
items = at === -1 ? [] : items.slice(at + 1);
|
|
57
|
+
}
|
|
58
|
+
const data = items.slice(0, limit).map(copy);
|
|
59
|
+
return { data, next: items.length > limit ? data.at(-1)?.id ?? null : null };
|
|
60
|
+
}
|
|
61
|
+
async update(userId, id, changes) {
|
|
62
|
+
const found = this.#of(userId).find((n) => n.id === id);
|
|
63
|
+
if (!found) return null;
|
|
64
|
+
Object.assign(found.attributes, changes);
|
|
65
|
+
return copy(found);
|
|
66
|
+
}
|
|
67
|
+
async markAllRead(userId, at) {
|
|
68
|
+
const changed = this.#of(userId).filter(MATCH.unread);
|
|
69
|
+
for (const n of changed) n.attributes.readAt = at;
|
|
70
|
+
return changed.map(copy);
|
|
71
|
+
}
|
|
72
|
+
async unreadCount(userId) {
|
|
73
|
+
return this.#of(userId).filter(MATCH.unread).length;
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
var SYSTEM_CLOCK = {
|
|
77
|
+
now: () => Date.now(),
|
|
78
|
+
setTimeout: (run, ms) => {
|
|
79
|
+
const timer = setTimeout(run, ms);
|
|
80
|
+
timer.unref?.();
|
|
81
|
+
return timer;
|
|
82
|
+
},
|
|
83
|
+
clearTimeout: (id) => clearTimeout(id)
|
|
84
|
+
};
|
|
85
|
+
var Session = class {
|
|
86
|
+
constructor(id, transport) {
|
|
87
|
+
this.id = id;
|
|
88
|
+
this.transport = transport;
|
|
89
|
+
}
|
|
90
|
+
id;
|
|
91
|
+
transport;
|
|
92
|
+
version;
|
|
93
|
+
closed = false;
|
|
94
|
+
user = null;
|
|
95
|
+
rooms = /* @__PURE__ */ new Set();
|
|
96
|
+
queue = Promise.resolve();
|
|
97
|
+
/** The frames in the queue. */
|
|
98
|
+
pending = 0;
|
|
99
|
+
/** The rate limit: the frames that the connection can send now, and the time of the count. */
|
|
100
|
+
tokens = 0;
|
|
101
|
+
counted = 0;
|
|
102
|
+
helloTimer;
|
|
103
|
+
send(message) {
|
|
104
|
+
if (this.transport.isOpen) this.transport.send(message);
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
var Room = class {
|
|
108
|
+
members = /* @__PURE__ */ new Set();
|
|
109
|
+
/** The seq of the last op. 0 until the first op. */
|
|
110
|
+
seq = 0;
|
|
111
|
+
/** The seq before the first op. It comes from the clock, so it is above each earlier seq. */
|
|
112
|
+
base = 0;
|
|
113
|
+
/** The seq of the last op that the log dropped. A join can replay only after it. */
|
|
114
|
+
floor = 0;
|
|
115
|
+
log = [];
|
|
116
|
+
bytes = 0;
|
|
117
|
+
idle;
|
|
118
|
+
awareness = /* @__PURE__ */ new Map();
|
|
119
|
+
get cursor() {
|
|
120
|
+
return `c${this.seq}`;
|
|
121
|
+
}
|
|
122
|
+
/** True when the log has each op after the cursor `since`. */
|
|
123
|
+
canReplay(since) {
|
|
124
|
+
const match = /^c(\d+)$/.exec(since);
|
|
125
|
+
if (!match) return false;
|
|
126
|
+
const after = Number(match[1]);
|
|
127
|
+
if (after > this.seq) return false;
|
|
128
|
+
return after >= this.floor || after === 0 && this.floor === this.base;
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
var Refusal = class extends Error {
|
|
132
|
+
constructor(code, message) {
|
|
133
|
+
super(message);
|
|
134
|
+
this.code = code;
|
|
135
|
+
}
|
|
136
|
+
code;
|
|
137
|
+
};
|
|
138
|
+
var refId = (message) => "id" in message ? { ref: message.id } : {};
|
|
139
|
+
var hasNotification = (document) => [document.data, document.included].flat().some((r) => r?.type === NOTIFICATION_TYPE);
|
|
140
|
+
var DovetailServer = class {
|
|
141
|
+
limits;
|
|
142
|
+
notifications;
|
|
143
|
+
#options;
|
|
144
|
+
#docs;
|
|
145
|
+
#clock;
|
|
146
|
+
#rooms = /* @__PURE__ */ new Map();
|
|
147
|
+
#sessions = /* @__PURE__ */ new Set();
|
|
148
|
+
/** The highest seq of this process, so a new room never gives a cursor again. */
|
|
149
|
+
#highest = 0;
|
|
150
|
+
constructor(options = {}) {
|
|
151
|
+
this.#options = options;
|
|
152
|
+
this.limits = {
|
|
153
|
+
...DEFAULT_LIMITS,
|
|
154
|
+
maxRooms: 100,
|
|
155
|
+
feedHistory: 1e3,
|
|
156
|
+
feedHistoryBytes: 1024 * 1024,
|
|
157
|
+
roomIdleMs: 6e5,
|
|
158
|
+
maxConnections: 1e4,
|
|
159
|
+
maxQueue: 1e3,
|
|
160
|
+
maxMessagesPerSecond: 200,
|
|
161
|
+
helloTimeoutMs: 1e4,
|
|
162
|
+
pingMs: 3e4,
|
|
163
|
+
maxBufferedBytes: 4 * 1024 * 1024,
|
|
164
|
+
...options.limits
|
|
165
|
+
};
|
|
166
|
+
this.notifications = options.notifications ?? new MemoryNotificationStore();
|
|
167
|
+
this.#docs = options.docs ?? new MemoryDocPersistence();
|
|
168
|
+
this.#clock = options.clock ?? SYSTEM_CLOCK;
|
|
169
|
+
if (options.authenticate && !options.authorize) {
|
|
170
|
+
(options.onWarning ?? console.warn)(
|
|
171
|
+
"dovetail: the server has no authorize hook, so each user can join and write each room."
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
/** The open connections. */
|
|
176
|
+
get connections() {
|
|
177
|
+
return this.#sessions.size;
|
|
178
|
+
}
|
|
179
|
+
/** The rooms that the server keeps in memory. */
|
|
180
|
+
get rooms() {
|
|
181
|
+
return this.#rooms.size;
|
|
182
|
+
}
|
|
183
|
+
/** Serves one connection. The transport must parse each frame with parseMessage. */
|
|
184
|
+
accept(transport) {
|
|
185
|
+
if (this.#sessions.size >= this.limits.maxConnections) {
|
|
186
|
+
transport.close(1013, "too many connections");
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
const session = new Session(`s-${crypto.randomUUID()}`, transport);
|
|
190
|
+
this.#sessions.add(session);
|
|
191
|
+
session.tokens = this.limits.maxMessagesPerSecond;
|
|
192
|
+
session.counted = this.#clock.now();
|
|
193
|
+
session.helloTimer = this.#clock.setTimeout(() => {
|
|
194
|
+
if (session.version === void 0) transport.close(1008, "no hello");
|
|
195
|
+
}, this.limits.helloTimeoutMs);
|
|
196
|
+
transport.onMessage((message) => {
|
|
197
|
+
if (session.pending >= this.limits.maxQueue || !this.#take(session)) {
|
|
198
|
+
if (message.type === "doc-update" || message.type === "doc-sync")
|
|
199
|
+
return transport.close(1013, "rate limited");
|
|
200
|
+
session.send({
|
|
201
|
+
type: "error",
|
|
202
|
+
...refId(message),
|
|
203
|
+
code: "rate-limited",
|
|
204
|
+
message: "Slow down."
|
|
205
|
+
});
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
session.pending++;
|
|
209
|
+
session.queue = session.queue.then(() => this.#handle(session, message)).catch((error) => this.#fail(session, message, error)).then(() => void session.pending--);
|
|
210
|
+
});
|
|
211
|
+
transport.onClose(() => {
|
|
212
|
+
if (!this.#sessions.delete(session)) return;
|
|
213
|
+
session.closed = true;
|
|
214
|
+
this.#clock.clearTimeout(session.helloTimer);
|
|
215
|
+
session.queue = session.queue.then(async () => {
|
|
216
|
+
const rooms = [...session.rooms];
|
|
217
|
+
for (const room of rooms) this.#leave(session, room);
|
|
218
|
+
await this.#options.onSessionEnd?.({ id: session.id, user: session.user, rooms });
|
|
219
|
+
}).catch((error) => this.#options.onError?.(error));
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
/** Takes one frame from the rate limit of the session. False when it has none. */
|
|
223
|
+
#take(session) {
|
|
224
|
+
const max = this.limits.maxMessagesPerSecond;
|
|
225
|
+
const now = this.#clock.now();
|
|
226
|
+
session.tokens = Math.min(max, session.tokens + (now - session.counted) / 1e3 * max);
|
|
227
|
+
session.counted = now;
|
|
228
|
+
if (session.tokens < 1) return false;
|
|
229
|
+
session.tokens--;
|
|
230
|
+
return true;
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* The user of a token, with the host `authenticate` hook. Null without the hook, for a token
|
|
234
|
+
* that is not valid, or when the hook throws.
|
|
235
|
+
*/
|
|
236
|
+
async authenticate(token) {
|
|
237
|
+
const blank = token === void 0 || token.trim() === "";
|
|
238
|
+
if (blank && !this.#options.allowAnonymous) return null;
|
|
239
|
+
try {
|
|
240
|
+
return await this.#options.authenticate?.(blank ? void 0 : token) ?? null;
|
|
241
|
+
} catch (error) {
|
|
242
|
+
this.#options.onError?.(error);
|
|
243
|
+
return null;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
/** Sends a document to the store feed of a room. Gives the cursor after it. */
|
|
247
|
+
publish(room, document) {
|
|
248
|
+
if (!isUserRoom(room) && hasNotification(document))
|
|
249
|
+
throw new Error("dovetail: a notification goes only to a per-user room");
|
|
250
|
+
return this.#feed(room, [{ op: "upsert", document }]);
|
|
251
|
+
}
|
|
252
|
+
/** Sends the delete of one record to the store feed of a room. Gives the cursor after it. */
|
|
253
|
+
remove(room, ref) {
|
|
254
|
+
return this.#feed(room, [{ op: "delete", ref }]);
|
|
255
|
+
}
|
|
256
|
+
/** Makes a notification for a user, stores it and sends it to the per-user room (ADR 0009). */
|
|
257
|
+
async notify(userId, payload) {
|
|
258
|
+
const notification = {
|
|
259
|
+
type: NOTIFICATION_TYPE,
|
|
260
|
+
id: payload.id ?? crypto.randomUUID(),
|
|
261
|
+
attributes: {
|
|
262
|
+
...payload.attributes,
|
|
263
|
+
verb: payload.verb,
|
|
264
|
+
createdAt: this.#now(),
|
|
265
|
+
readAt: null,
|
|
266
|
+
seenAt: null,
|
|
267
|
+
archivedAt: null
|
|
268
|
+
},
|
|
269
|
+
relationships: { actor: { data: payload.actor }, target: { data: payload.target } }
|
|
270
|
+
};
|
|
271
|
+
this.#check(userRoom(userId), [{ op: "upsert", document: { data: notification } }]);
|
|
272
|
+
await this.notifications.add(userId, notification);
|
|
273
|
+
this.publish(userRoom(userId), { data: notification });
|
|
274
|
+
return notification;
|
|
275
|
+
}
|
|
276
|
+
/** Marks one notification as read. Null when the user has no such notification. */
|
|
277
|
+
markRead(userId, id) {
|
|
278
|
+
return this.#change(userId, id, { readAt: this.#now() });
|
|
279
|
+
}
|
|
280
|
+
/** Archives one notification. Null when the user has no such notification. */
|
|
281
|
+
archive(userId, id) {
|
|
282
|
+
return this.#change(userId, id, { archivedAt: this.#now() });
|
|
283
|
+
}
|
|
284
|
+
/** Marks each unread notification of the user as read. Gives the count that changed. */
|
|
285
|
+
async markAllRead(userId) {
|
|
286
|
+
const changed = await this.notifications.markAllRead(userId, this.#now());
|
|
287
|
+
const ops = changed.map((n) => ({ op: "upsert", document: { data: n } }));
|
|
288
|
+
for (let i = 0; i < ops.length; i += this.limits.maxOps)
|
|
289
|
+
this.#feed(userRoom(userId), ops.slice(i, i + this.limits.maxOps));
|
|
290
|
+
return changed.length;
|
|
291
|
+
}
|
|
292
|
+
/** Closes each connection. */
|
|
293
|
+
close() {
|
|
294
|
+
for (const session of [...this.#sessions]) session.transport.close(1001, "server closed");
|
|
295
|
+
}
|
|
296
|
+
async #change(userId, id, changes) {
|
|
297
|
+
const changed = await this.notifications.update(userId, id, changes);
|
|
298
|
+
if (changed) this.publish(userRoom(userId), { data: changed });
|
|
299
|
+
return changed;
|
|
300
|
+
}
|
|
301
|
+
#now() {
|
|
302
|
+
return new Date(this.#clock.now()).toISOString();
|
|
303
|
+
}
|
|
304
|
+
#room(name) {
|
|
305
|
+
let room = this.#rooms.get(name);
|
|
306
|
+
if (!room) this.#rooms.set(name, room = new Room());
|
|
307
|
+
return room;
|
|
308
|
+
}
|
|
309
|
+
/** Throws when the ops do not make a valid feed message, so a client never gets one. */
|
|
310
|
+
#check(room, ops) {
|
|
311
|
+
const result = parseMessage({ type: "feed", room, cursor: "c0", ops }, { from: "server" });
|
|
312
|
+
if (!result.ok) throw new Error(`dovetail: ${result.error.message}`);
|
|
313
|
+
}
|
|
314
|
+
/** Adds ops to the feed of a room and sends them to its members, but not to `except`. */
|
|
315
|
+
#feed(name, ops, except) {
|
|
316
|
+
this.#check(name, ops);
|
|
317
|
+
const room = this.#room(name);
|
|
318
|
+
if (room.seq === 0) {
|
|
319
|
+
room.seq = room.base = room.floor = Math.max(Math.floor(this.#clock.now() * 1e3), this.#highest);
|
|
320
|
+
}
|
|
321
|
+
for (const op of ops) {
|
|
322
|
+
const bytes = JSON.stringify(op).length;
|
|
323
|
+
room.log.push({ seq: ++room.seq, op, bytes });
|
|
324
|
+
room.bytes += bytes;
|
|
325
|
+
}
|
|
326
|
+
this.#highest = Math.max(this.#highest, room.seq);
|
|
327
|
+
const { feedHistory, feedHistoryBytes } = this.limits;
|
|
328
|
+
while (room.log.length > feedHistory || room.log.length > 0 && room.bytes > feedHistoryBytes) {
|
|
329
|
+
const dropped = room.log.shift();
|
|
330
|
+
room.floor = dropped?.seq ?? room.floor;
|
|
331
|
+
room.bytes -= dropped?.bytes ?? 0;
|
|
332
|
+
}
|
|
333
|
+
this.#idle(name, room);
|
|
334
|
+
const message = { type: "feed", room: name, cursor: room.cursor, ops };
|
|
335
|
+
for (const member of room.members) if (member !== except) member.send(message);
|
|
336
|
+
return room.cursor;
|
|
337
|
+
}
|
|
338
|
+
/** Forgets a room with no members: at once with no log, else after `roomIdleMs`. */
|
|
339
|
+
#idle(name, room) {
|
|
340
|
+
this.#clock.clearTimeout(room.idle);
|
|
341
|
+
room.idle = void 0;
|
|
342
|
+
if (room.members.size > 0) return;
|
|
343
|
+
const forget = () => {
|
|
344
|
+
if (room.members.size === 0 && this.#rooms.get(name) === room) this.#rooms.delete(name);
|
|
345
|
+
};
|
|
346
|
+
if (room.log.length === 0) forget();
|
|
347
|
+
else room.idle = this.#clock.setTimeout(forget, this.limits.roomIdleMs);
|
|
348
|
+
}
|
|
349
|
+
#relay(name, message, except) {
|
|
350
|
+
for (const member of this.#rooms.get(name)?.members ?? [])
|
|
351
|
+
if (member !== except) member.send(message);
|
|
352
|
+
}
|
|
353
|
+
async #allowed(user, room, action) {
|
|
354
|
+
if (isUserRoom(room) && (user === null || room !== userRoom(user.id))) return false;
|
|
355
|
+
if (!this.#options.authorize) return true;
|
|
356
|
+
return await this.#options.authorize(user, room, action) === true;
|
|
357
|
+
}
|
|
358
|
+
#joined(session, room) {
|
|
359
|
+
if (!session.rooms.has(room)) throw new Refusal("not-joined", "Join the room first.");
|
|
360
|
+
}
|
|
361
|
+
/** A write, a doc update and a step 2 change the room, so each one needs the write right. */
|
|
362
|
+
async #writable(session, room) {
|
|
363
|
+
this.#joined(session, room);
|
|
364
|
+
if (!await this.#allowed(session.user, room, "write"))
|
|
365
|
+
throw new Refusal("forbidden", "You cannot write to this room.");
|
|
366
|
+
}
|
|
367
|
+
#fail(session, message, error) {
|
|
368
|
+
if (error instanceof Refusal) {
|
|
369
|
+
session.send({ type: "error", ...refId(message), code: error.code, message: error.message });
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
this.#options.onError?.(error);
|
|
373
|
+
session.send({ type: "error", ...refId(message), code: "internal", message: "Internal error." });
|
|
374
|
+
}
|
|
375
|
+
async #handle(session, message) {
|
|
376
|
+
if (message.type === "hello") return this.#hello(session, message.versions, message.token);
|
|
377
|
+
if (session.version === void 0) throw new Refusal("invalid-message", "Send hello first.");
|
|
378
|
+
switch (message.type) {
|
|
379
|
+
case "ping":
|
|
380
|
+
return session.send({ type: "pong", ref: message.id });
|
|
381
|
+
case "join":
|
|
382
|
+
return this.#join(session, message.id, message.room, message.since);
|
|
383
|
+
case "leave":
|
|
384
|
+
this.#leave(session, message.room);
|
|
385
|
+
return session.send({ type: "ack", ref: message.id });
|
|
386
|
+
case "write":
|
|
387
|
+
return this.#write(session, message);
|
|
388
|
+
case "doc-update":
|
|
389
|
+
return this.#storeUpdate(session, message.room, message.doc, message.update);
|
|
390
|
+
case "doc-sync":
|
|
391
|
+
if (message.step === 2)
|
|
392
|
+
return this.#storeUpdate(session, message.room, message.doc, message.update);
|
|
393
|
+
this.#joined(session, message.room);
|
|
394
|
+
return this.#sync(session, message.room, message.doc);
|
|
395
|
+
case "awareness": {
|
|
396
|
+
this.#joined(session, message.room);
|
|
397
|
+
if (message.state === null) return this.#awareness(session, message.room, null);
|
|
398
|
+
const state = await this.#checkAwareness(session, message.room, message.state);
|
|
399
|
+
if (session.closed || !session.rooms.has(message.room)) return;
|
|
400
|
+
return this.#awareness(session, message.room, state);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
async #hello(session, versions, token) {
|
|
405
|
+
if (session.version !== void 0) throw new Refusal("invalid-message", "Send hello once.");
|
|
406
|
+
const version = negotiateVersion(versions, SUPPORTED_VERSIONS);
|
|
407
|
+
if (version === null) {
|
|
408
|
+
session.send({
|
|
409
|
+
type: "error",
|
|
410
|
+
code: "unsupported-version",
|
|
411
|
+
message: `This server speaks the versions ${SUPPORTED_VERSIONS.join(", ")}.`
|
|
412
|
+
});
|
|
413
|
+
return this.#closeLater(session, 1002, "unsupported version");
|
|
414
|
+
}
|
|
415
|
+
if (this.#options.authenticate) {
|
|
416
|
+
const user = await this.authenticate(token);
|
|
417
|
+
if (!user) {
|
|
418
|
+
session.send({ type: "error", code: "unauthorized", message: "The token is not valid." });
|
|
419
|
+
return this.#closeLater(session, 1008, "unauthorized");
|
|
420
|
+
}
|
|
421
|
+
session.user = user;
|
|
422
|
+
}
|
|
423
|
+
session.version = version;
|
|
424
|
+
this.#clock.clearTimeout(session.helloTimer);
|
|
425
|
+
session.send({
|
|
426
|
+
type: "welcome",
|
|
427
|
+
version,
|
|
428
|
+
session: session.id,
|
|
429
|
+
...session.user ? { user: { id: session.user.id } } : {}
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
/** Closes after the frames that wait, so the client gets the error before the close. */
|
|
433
|
+
#closeLater(session, code, reason) {
|
|
434
|
+
this.#clock.setTimeout(() => session.transport.close(code, reason), 0);
|
|
435
|
+
}
|
|
436
|
+
async #join(session, id, name, since) {
|
|
437
|
+
if (!session.rooms.has(name) && session.rooms.size >= this.limits.maxRooms)
|
|
438
|
+
throw new Refusal("rate-limited", `A connection can join ${this.limits.maxRooms} rooms.`);
|
|
439
|
+
if (!await this.#allowed(session.user, name, "join"))
|
|
440
|
+
throw new Refusal("forbidden", "You cannot join this room.");
|
|
441
|
+
if (session.closed) return;
|
|
442
|
+
const room = this.#room(name);
|
|
443
|
+
this.#clock.clearTimeout(room.idle);
|
|
444
|
+
room.members.add(session);
|
|
445
|
+
session.rooms.add(name);
|
|
446
|
+
const reset = since !== void 0 && !room.canReplay(since);
|
|
447
|
+
session.send({ type: "ack", ref: id, cursor: room.cursor, ...reset ? { reset } : {} });
|
|
448
|
+
if (since === void 0 || reset) return;
|
|
449
|
+
const after = Number(since.slice(1));
|
|
450
|
+
const entries = room.log.filter((entry) => entry.seq > after);
|
|
451
|
+
for (let i = 0; i < entries.length; i += this.limits.maxOps) {
|
|
452
|
+
const chunk = entries.slice(i, i + this.limits.maxOps);
|
|
453
|
+
session.send({
|
|
454
|
+
type: "feed",
|
|
455
|
+
room: name,
|
|
456
|
+
cursor: `c${chunk.at(-1)?.seq}`,
|
|
457
|
+
ops: chunk.map((entry) => entry.op)
|
|
458
|
+
});
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
#leave(session, name) {
|
|
462
|
+
this.#clearAwareness(session, name);
|
|
463
|
+
const room = this.#rooms.get(name);
|
|
464
|
+
room?.members.delete(session);
|
|
465
|
+
session.rooms.delete(name);
|
|
466
|
+
if (room) this.#idle(name, room);
|
|
467
|
+
}
|
|
468
|
+
async #write(session, message) {
|
|
469
|
+
const { id, room, op } = message;
|
|
470
|
+
await this.#writable(session, room);
|
|
471
|
+
if (isUserRoom(room)) return this.#notificationWrite(session, message);
|
|
472
|
+
if (op.op === "upsert" && hasNotification(op.document)) {
|
|
473
|
+
return session.send({
|
|
474
|
+
type: "reject",
|
|
475
|
+
ref: id,
|
|
476
|
+
status: 403,
|
|
477
|
+
errors: [{ status: "403", title: "A notification goes only to a per-user room." }]
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
const result = await this.#options.handleWrite?.({
|
|
481
|
+
user: session.user,
|
|
482
|
+
session: session.id,
|
|
483
|
+
id,
|
|
484
|
+
room,
|
|
485
|
+
op
|
|
486
|
+
}) ?? { ok: true };
|
|
487
|
+
if (!result.ok) {
|
|
488
|
+
return session.send({ type: "reject", ref: id, status: result.status, errors: result.errors });
|
|
489
|
+
}
|
|
490
|
+
const fed = result.document ? { op: "upsert", document: result.document } : op;
|
|
491
|
+
const cursor = this.#feed(room, [fed], session);
|
|
492
|
+
session.send({
|
|
493
|
+
type: "ack",
|
|
494
|
+
ref: id,
|
|
495
|
+
cursor,
|
|
496
|
+
...result.document ? { document: result.document } : {}
|
|
497
|
+
});
|
|
498
|
+
}
|
|
499
|
+
/** A write to the own per-user room changes the read, seen and archived times only. */
|
|
500
|
+
async #notificationWrite(session, { id, room, op }) {
|
|
501
|
+
const data = op.op === "upsert" ? op.document.data : null;
|
|
502
|
+
if (!data || Array.isArray(data) || data.type !== NOTIFICATION_TYPE || !session.user) {
|
|
503
|
+
return session.send({
|
|
504
|
+
type: "reject",
|
|
505
|
+
ref: id,
|
|
506
|
+
status: 422,
|
|
507
|
+
errors: [{ status: "422", title: "A per-user room takes only notification upserts." }]
|
|
508
|
+
});
|
|
509
|
+
}
|
|
510
|
+
const stored = await this.notifications.get(session.user.id, data.id);
|
|
511
|
+
const changes = {};
|
|
512
|
+
for (const key of ["readAt", "seenAt", "archivedAt"]) {
|
|
513
|
+
const value = data.attributes?.[key];
|
|
514
|
+
if (typeof value === "string" && !stored?.attributes[key]) changes[key] = value;
|
|
515
|
+
}
|
|
516
|
+
const changed = stored && await this.notifications.update(session.user.id, data.id, changes);
|
|
517
|
+
if (!changed) {
|
|
518
|
+
return session.send({
|
|
519
|
+
type: "reject",
|
|
520
|
+
ref: id,
|
|
521
|
+
status: 404,
|
|
522
|
+
errors: [{ status: "404", title: "Not found" }]
|
|
523
|
+
});
|
|
524
|
+
}
|
|
525
|
+
const document = { data: changed };
|
|
526
|
+
const cursor = this.#feed(room, [{ op: "upsert", document }], session);
|
|
527
|
+
session.send({ type: "ack", ref: id, cursor, document });
|
|
528
|
+
}
|
|
529
|
+
async #storeUpdate(session, room, doc, update) {
|
|
530
|
+
await this.#writable(session, room);
|
|
531
|
+
const validate = this.#options.validateUpdate;
|
|
532
|
+
if (validate) {
|
|
533
|
+
const context = { user: session.user, session: session.id, room, doc };
|
|
534
|
+
const valid = await Promise.resolve().then(() => validate(fromBase64(update), context)).catch((error) => void this.#options.onError?.(error));
|
|
535
|
+
if (valid !== true) throw new Refusal("invalid-message", "The update is not valid.");
|
|
536
|
+
}
|
|
537
|
+
try {
|
|
538
|
+
await this.#docs.append(room, doc, update);
|
|
539
|
+
} catch (error) {
|
|
540
|
+
if (error instanceof TooLargeError) throw new Refusal("too-large", error.message);
|
|
541
|
+
throw error;
|
|
542
|
+
}
|
|
543
|
+
this.#relay(room, { type: "doc-update", room, doc, update, origin: session.id }, session);
|
|
544
|
+
}
|
|
545
|
+
async #sync(session, room, doc) {
|
|
546
|
+
let updates = await this.#docs.load(room, doc);
|
|
547
|
+
if (updates.length === 0) updates = [""];
|
|
548
|
+
else if (updates.length > 1 && this.#options.mergeUpdates) {
|
|
549
|
+
try {
|
|
550
|
+
updates = [toBase64(this.#options.mergeUpdates(updates.map(fromBase64)))];
|
|
551
|
+
} catch (error) {
|
|
552
|
+
this.#options.onError?.(error);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
for (const update of updates) session.send({ type: "doc-sync", room, doc, step: 2, update });
|
|
556
|
+
}
|
|
557
|
+
/** The state to relay: the one of `authorizeAwareness`, or the state with the user id. */
|
|
558
|
+
async #checkAwareness(session, room, state) {
|
|
559
|
+
const hook = this.#options.authorizeAwareness;
|
|
560
|
+
if (hook) {
|
|
561
|
+
const checked = await hook(session.user, room, state);
|
|
562
|
+
if (checked === false) throw new Refusal("forbidden", "You cannot send this awareness state.");
|
|
563
|
+
return checked;
|
|
564
|
+
}
|
|
565
|
+
const user = state["user"];
|
|
566
|
+
if (!session.user || typeof user !== "object" || user === null || Array.isArray(user))
|
|
567
|
+
return state;
|
|
568
|
+
return { ...state, user: { ...user, id: session.user.id } };
|
|
569
|
+
}
|
|
570
|
+
#awareness(session, name, state) {
|
|
571
|
+
if (state === null) return this.#clearAwareness(session, name);
|
|
572
|
+
const room = this.#room(name);
|
|
573
|
+
const old = room.awareness.get(session);
|
|
574
|
+
if (old) this.#clock.clearTimeout(old.timer);
|
|
575
|
+
const timer = this.#clock.setTimeout(
|
|
576
|
+
() => this.#clearAwareness(session, name),
|
|
577
|
+
this.#options.awarenessTimeout ?? 3e4
|
|
578
|
+
);
|
|
579
|
+
room.awareness.set(session, { state, timer });
|
|
580
|
+
this.#relay(name, { type: "awareness", room: name, clientId: session.id, state }, session);
|
|
581
|
+
}
|
|
582
|
+
#clearAwareness(session, name) {
|
|
583
|
+
const room = this.#rooms.get(name);
|
|
584
|
+
const entry = room?.awareness.get(session);
|
|
585
|
+
if (!room || !entry) return;
|
|
586
|
+
this.#clock.clearTimeout(entry.timer);
|
|
587
|
+
room.awareness.delete(session);
|
|
588
|
+
this.#relay(name, { type: "awareness", room: name, clientId: session.id, state: null }, session);
|
|
589
|
+
}
|
|
590
|
+
};
|
|
591
|
+
function createDovetailServer(options = {}) {
|
|
592
|
+
return new DovetailServer(options);
|
|
593
|
+
}
|
|
594
|
+
var DROPPED = { code: 1006, reason: "offline", wasClean: false };
|
|
595
|
+
var End = class {
|
|
596
|
+
constructor(from, clock, opened = () => Promise.resolve()) {
|
|
597
|
+
this.from = from;
|
|
598
|
+
this.clock = clock;
|
|
599
|
+
this.opened = opened;
|
|
600
|
+
}
|
|
601
|
+
from;
|
|
602
|
+
clock;
|
|
603
|
+
opened;
|
|
604
|
+
peer;
|
|
605
|
+
isOpen = false;
|
|
606
|
+
#messages = /* @__PURE__ */ new Set();
|
|
607
|
+
#closes = /* @__PURE__ */ new Set();
|
|
608
|
+
open() {
|
|
609
|
+
return this.opened();
|
|
610
|
+
}
|
|
611
|
+
send(message) {
|
|
612
|
+
if (!this.isOpen) throw new Error("The in-page transport is not open.");
|
|
613
|
+
const text = encodeMessage(message);
|
|
614
|
+
this.clock.setTimeout(() => this.peer?.receive(text), 0);
|
|
615
|
+
}
|
|
616
|
+
receive(text) {
|
|
617
|
+
if (!this.isOpen) return;
|
|
618
|
+
const result = parseMessage(text, { from: this.from });
|
|
619
|
+
if (!result.ok) {
|
|
620
|
+
this.close(1007, result.error.message);
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
for (const listener of [...this.#messages]) listener(result.message);
|
|
624
|
+
}
|
|
625
|
+
close(code = 1e3, reason = "") {
|
|
626
|
+
this.drop({ code, reason, wasClean: code === 1e3 });
|
|
627
|
+
}
|
|
628
|
+
/** Closes both ends with `info`. */
|
|
629
|
+
drop(info) {
|
|
630
|
+
for (const end of [this, this.peer]) {
|
|
631
|
+
if (!end?.isOpen) continue;
|
|
632
|
+
end.isOpen = false;
|
|
633
|
+
for (const listener of [...end.#closes]) listener(info);
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
onMessage(listener) {
|
|
637
|
+
this.#messages.add(listener);
|
|
638
|
+
return () => this.#messages.delete(listener);
|
|
639
|
+
}
|
|
640
|
+
onClose(listener) {
|
|
641
|
+
this.#closes.add(listener);
|
|
642
|
+
return () => this.#closes.delete(listener);
|
|
643
|
+
}
|
|
644
|
+
};
|
|
645
|
+
function inPageServer(options = {}) {
|
|
646
|
+
const server = createDovetailServer(options);
|
|
647
|
+
const clock = options.clock ?? globalThis;
|
|
648
|
+
const ends = /* @__PURE__ */ new Set();
|
|
649
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
650
|
+
let online = true;
|
|
651
|
+
const network = {
|
|
652
|
+
get isOnline() {
|
|
653
|
+
return online;
|
|
654
|
+
},
|
|
655
|
+
set(mode) {
|
|
656
|
+
if (online === (mode === "online")) return;
|
|
657
|
+
online = mode === "online";
|
|
658
|
+
if (!online) for (const end of [...ends]) end.drop(DROPPED);
|
|
659
|
+
for (const listener of [...listeners]) listener();
|
|
660
|
+
},
|
|
661
|
+
subscribe(listener) {
|
|
662
|
+
listeners.add(listener);
|
|
663
|
+
return () => listeners.delete(listener);
|
|
664
|
+
}
|
|
665
|
+
};
|
|
666
|
+
const connect = () => {
|
|
667
|
+
const serverEnd = new End("client", clock);
|
|
668
|
+
const client = new End("server", clock, async () => {
|
|
669
|
+
if (client.isOpen) return;
|
|
670
|
+
if (!online) throw new Error("The in-page network is offline.");
|
|
671
|
+
client.isOpen = serverEnd.isOpen = true;
|
|
672
|
+
ends.add(client);
|
|
673
|
+
client.onClose(() => ends.delete(client));
|
|
674
|
+
server.accept(serverEnd);
|
|
675
|
+
});
|
|
676
|
+
client.peer = serverEnd;
|
|
677
|
+
serverEnd.peer = client;
|
|
678
|
+
return client;
|
|
679
|
+
};
|
|
680
|
+
return { server, network, connect };
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
export { DovetailServer, MemoryDocPersistence, MemoryNotificationStore, TooLargeError, createDovetailServer, inPageServer };
|
|
684
|
+
//# sourceMappingURL=chunk-YXFPYQRL.js.map
|
|
685
|
+
//# sourceMappingURL=chunk-YXFPYQRL.js.map
|