cotchu 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -2
- package/dist/cli.js +119 -0
- package/dist/cotchu.min.js +2 -0
- package/dist/cotchu.min.js.map +7 -0
- package/dist/index.d.ts +519 -0
- package/dist/index.js +1749 -0
- package/dist/index.js.map +7 -0
- package/package.json +42 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,1749 @@
|
|
|
1
|
+
// ../protocol/src/limits.ts
|
|
2
|
+
var MAX_MSG_BYTES = 16384;
|
|
3
|
+
var MAX_SEATS = 32;
|
|
4
|
+
var RATE_LIMIT_PER_SEC = 60;
|
|
5
|
+
var CLIENT_RATE_LIMIT_PER_SEC = 40;
|
|
6
|
+
var CLIENT_RATE_LIMIT_BURST = 40;
|
|
7
|
+
var MAX_OPEN_ROOMS_PER_PROJECT = 50;
|
|
8
|
+
var MIN_TICK_HZ = 1;
|
|
9
|
+
var MAX_TICK_HZ = 30;
|
|
10
|
+
var MAX_INPUT_BYTES = 1024;
|
|
11
|
+
var MIN_TURN_MS = 1e3;
|
|
12
|
+
var MAX_TURN_MS = 36e5;
|
|
13
|
+
var MAX_PATH_DEPTH = 16;
|
|
14
|
+
var MAX_KEY_LENGTH = 128;
|
|
15
|
+
var MAX_VALUE_DEPTH = 32;
|
|
16
|
+
var MAX_OPS_PER_PATCH = 64;
|
|
17
|
+
var MAX_WRITABLE_PATTERNS = 32;
|
|
18
|
+
var MAX_SCHEMA_BYTES = 4096;
|
|
19
|
+
var MAX_SCHEMA_DEPTH = 8;
|
|
20
|
+
var MAX_NAME_LENGTH = 32;
|
|
21
|
+
var MAX_ROOM_NAME_LENGTH = 64;
|
|
22
|
+
|
|
23
|
+
// ../protocol/src/room.ts
|
|
24
|
+
var PROTOCOL_VERSION = 1;
|
|
25
|
+
var ROOM_TYPES = ["shared", "turns", "realtime", "script"];
|
|
26
|
+
var REGIONS = [
|
|
27
|
+
"wnam",
|
|
28
|
+
"enam",
|
|
29
|
+
"sam",
|
|
30
|
+
"weur",
|
|
31
|
+
"eeur",
|
|
32
|
+
"apac",
|
|
33
|
+
"apac-ne",
|
|
34
|
+
"apac-se",
|
|
35
|
+
"oc",
|
|
36
|
+
"afr",
|
|
37
|
+
"me"
|
|
38
|
+
];
|
|
39
|
+
var ROOMS_PATH_PREFIX = "/v1/rooms/";
|
|
40
|
+
var DEFAULT_ROOMS_URL = "wss://rooms.cotchu.com";
|
|
41
|
+
var ROOM_NAME_PATTERN = new RegExp(`^[A-Za-z0-9][A-Za-z0-9._-]{0,${MAX_ROOM_NAME_LENGTH - 1}}$`);
|
|
42
|
+
var PING_FRAME = '{"t":"ping"}';
|
|
43
|
+
function isRoomType(value) {
|
|
44
|
+
return typeof value === "string" && ROOM_TYPES.includes(value);
|
|
45
|
+
}
|
|
46
|
+
function isRegion(value) {
|
|
47
|
+
return typeof value === "string" && REGIONS.includes(value);
|
|
48
|
+
}
|
|
49
|
+
var SCRIPT_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,31}$/;
|
|
50
|
+
function isScriptName(value) {
|
|
51
|
+
return typeof value === "string" && SCRIPT_NAME_PATTERN.test(value);
|
|
52
|
+
}
|
|
53
|
+
function isRoomName(value) {
|
|
54
|
+
return typeof value === "string" && ROOM_NAME_PATTERN.test(value);
|
|
55
|
+
}
|
|
56
|
+
var CLOSE_CODES = {
|
|
57
|
+
FATAL: 4e3,
|
|
58
|
+
REPLACED: 4001
|
|
59
|
+
};
|
|
60
|
+
var LEAVE_REASON = "leave";
|
|
61
|
+
|
|
62
|
+
// ../protocol/src/errors.ts
|
|
63
|
+
var ERRORS = {
|
|
64
|
+
bad_message: {
|
|
65
|
+
fatal: false,
|
|
66
|
+
message: "That message isn't valid Cotchu protocol; send it through the cotchu SDK or match the formats in llms.txt."
|
|
67
|
+
},
|
|
68
|
+
hello_required: {
|
|
69
|
+
fatal: false,
|
|
70
|
+
message: "The room hasn't had your hello yet; send a hello message first, or use cotchu.join(), which sends it for you."
|
|
71
|
+
},
|
|
72
|
+
unsupported_version: {
|
|
73
|
+
fatal: true,
|
|
74
|
+
message: "This client speaks a different protocol version than the room; update the cotchu package to the latest."
|
|
75
|
+
},
|
|
76
|
+
bad_key: {
|
|
77
|
+
fatal: true,
|
|
78
|
+
message: "That key isn't a valid Cotchu publishable key; pass your project's pk_ key as the key option to cotchu.join()."
|
|
79
|
+
},
|
|
80
|
+
bad_origin: {
|
|
81
|
+
fatal: true,
|
|
82
|
+
message: "This page's website isn't on your project's allowed origins; add it to the project's allowed origins, then reload."
|
|
83
|
+
},
|
|
84
|
+
room_full: {
|
|
85
|
+
fatal: true,
|
|
86
|
+
message: "Every seat in this room is taken; try again in a moment or join a different room name."
|
|
87
|
+
},
|
|
88
|
+
room_limit: {
|
|
89
|
+
fatal: true,
|
|
90
|
+
message: `This project already has ${MAX_OPEN_ROOMS_PER_PROJECT} rooms open, its current limit; finished rooms close a minute after their last player leaves.`
|
|
91
|
+
},
|
|
92
|
+
type_mismatch: {
|
|
93
|
+
fatal: true,
|
|
94
|
+
message: "This room already exists with a different type; join with the room's type or pick a new room name."
|
|
95
|
+
},
|
|
96
|
+
wrong_room_type: {
|
|
97
|
+
fatal: false,
|
|
98
|
+
message: "That call doesn't work in this type of room; use set() in shared rooms, move() in turns rooms and input() in realtime rooms."
|
|
99
|
+
},
|
|
100
|
+
rate_limited: {
|
|
101
|
+
fatal: false,
|
|
102
|
+
message: `This player sent more than ${RATE_LIMIT_PER_SEC} messages a second; batch changes into fewer messages or send inputs on a fixed timer.`
|
|
103
|
+
},
|
|
104
|
+
too_large: {
|
|
105
|
+
fatal: false,
|
|
106
|
+
message: `That message is over ${MAX_MSG_BYTES / 1024} KB; send smaller changes, or split large data across several paths.`
|
|
107
|
+
},
|
|
108
|
+
forbidden_path: {
|
|
109
|
+
fatal: false,
|
|
110
|
+
message: "This player isn't allowed to write that path; write only to paths the room's writable list allows."
|
|
111
|
+
},
|
|
112
|
+
bad_move: {
|
|
113
|
+
fatal: false,
|
|
114
|
+
message: "That move doesn't match the room's move schema; send a move shaped the way the room's moveSchema describes."
|
|
115
|
+
},
|
|
116
|
+
not_your_turn: {
|
|
117
|
+
fatal: false,
|
|
118
|
+
message: "It isn't this player's turn; wait for a turn event naming this player before calling move()."
|
|
119
|
+
},
|
|
120
|
+
balance_empty: {
|
|
121
|
+
fatal: true,
|
|
122
|
+
message: "This project's Cotchu balance is empty, so new rooms can't open; top up the balance in the console."
|
|
123
|
+
},
|
|
124
|
+
action_rejected: {
|
|
125
|
+
fatal: false,
|
|
126
|
+
message: "The room's script turned that action down; check the game's rules, or read the message the script gave."
|
|
127
|
+
},
|
|
128
|
+
script_error: {
|
|
129
|
+
fatal: false,
|
|
130
|
+
message: "The room's script failed, so the room restarted it from its last save; try again, and fix the script if it keeps happening."
|
|
131
|
+
},
|
|
132
|
+
script_not_found: {
|
|
133
|
+
fatal: true,
|
|
134
|
+
message: "This project has no deployed script by that name; deploy it with npx cotchu deploy room.js --name <name>, then join again."
|
|
135
|
+
},
|
|
136
|
+
bad_path: {
|
|
137
|
+
fatal: false,
|
|
138
|
+
message: "That path runs through a value that isn't an object; set the parent to an object first, or write a different path."
|
|
139
|
+
},
|
|
140
|
+
unknown_player: {
|
|
141
|
+
fatal: false,
|
|
142
|
+
message: "No player with that id is in the room; send direct messages only to ids from the room's player list."
|
|
143
|
+
},
|
|
144
|
+
internal: {
|
|
145
|
+
fatal: false,
|
|
146
|
+
message: "Something went wrong inside Cotchu; retry, and if it keeps happening, report it with the room name and time."
|
|
147
|
+
},
|
|
148
|
+
replaced: {
|
|
149
|
+
fatal: true,
|
|
150
|
+
message: "This seat was taken over by a newer connection using the same resume token; keep one connection per player."
|
|
151
|
+
},
|
|
152
|
+
// SDK errors: raised by the cotchu package itself, never sent by a room.
|
|
153
|
+
room_closed: {
|
|
154
|
+
fatal: true,
|
|
155
|
+
message: "This room is closed because you left or it ended; call cotchu.join() again to get a new room object."
|
|
156
|
+
},
|
|
157
|
+
unreachable: {
|
|
158
|
+
fatal: true,
|
|
159
|
+
message: "Couldn't reach a Cotchu room; check the network and any url option you passed, then call cotchu.join() again."
|
|
160
|
+
},
|
|
161
|
+
// HTTP errors: returned before a WebSocket opens, as JSON { error, message }.
|
|
162
|
+
not_found: {
|
|
163
|
+
fatal: true,
|
|
164
|
+
message: "Nothing lives at that path; connect with the cotchu SDK, which opens /v1/rooms/<project>/<room> for you."
|
|
165
|
+
},
|
|
166
|
+
bad_room: {
|
|
167
|
+
fatal: true,
|
|
168
|
+
message: "Project ids use lowercase letters and digits, and room names letters, digits, '.', '_' and '-' up to 64 characters; fix the URL."
|
|
169
|
+
},
|
|
170
|
+
bad_script: {
|
|
171
|
+
fatal: true,
|
|
172
|
+
message: "That script couldn't be loaded; fix what the message describes in room.js, then deploy again."
|
|
173
|
+
},
|
|
174
|
+
bad_region: {
|
|
175
|
+
fatal: true,
|
|
176
|
+
message: `That region isn't one Cotchu knows; use auto or one of ${REGIONS.join(", ")}.`
|
|
177
|
+
},
|
|
178
|
+
upgrade_required: {
|
|
179
|
+
fatal: true,
|
|
180
|
+
message: "Rooms only speak WebSocket; open the URL with new WebSocket(), or let cotchu.join() do it for you."
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
var ERROR_CODES = Object.keys(ERRORS);
|
|
184
|
+
function isErrorCode(value) {
|
|
185
|
+
return typeof value === "string" && Object.hasOwn(ERRORS, value);
|
|
186
|
+
}
|
|
187
|
+
function isFatal(code) {
|
|
188
|
+
return isErrorCode(code) && ERRORS[code].fatal;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// ../protocol/src/keys.ts
|
|
192
|
+
var PUBLISHABLE_KEY_PATTERN = /^pk_live_([a-z0-9]{1,32})_([A-Za-z0-9]{16,64})$/;
|
|
193
|
+
function projectOfKey(key) {
|
|
194
|
+
return PUBLISHABLE_KEY_PATTERN.exec(key)?.[1] ?? null;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// ../protocol/src/messages.ts
|
|
198
|
+
var CLIENT_MESSAGE_TYPES = [
|
|
199
|
+
"hello",
|
|
200
|
+
"patch",
|
|
201
|
+
"move",
|
|
202
|
+
"input",
|
|
203
|
+
"msg",
|
|
204
|
+
"ping",
|
|
205
|
+
"act"
|
|
206
|
+
];
|
|
207
|
+
var SERVER_MESSAGE_TYPES = [
|
|
208
|
+
"welcome",
|
|
209
|
+
"patch",
|
|
210
|
+
"turn",
|
|
211
|
+
"move",
|
|
212
|
+
"snap",
|
|
213
|
+
"join",
|
|
214
|
+
"leave",
|
|
215
|
+
"msg",
|
|
216
|
+
"err",
|
|
217
|
+
"pong",
|
|
218
|
+
"ack",
|
|
219
|
+
"priv",
|
|
220
|
+
"event",
|
|
221
|
+
"sync"
|
|
222
|
+
];
|
|
223
|
+
|
|
224
|
+
// ../protocol/src/paths.ts
|
|
225
|
+
var FORBIDDEN_KEYS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
|
|
226
|
+
var SELF_SEGMENT = "$self";
|
|
227
|
+
var ANY_SEGMENT = "*";
|
|
228
|
+
function keyProblem(key) {
|
|
229
|
+
if (key.length === 0) return "is an empty key";
|
|
230
|
+
if (key.length > MAX_KEY_LENGTH) return `has a key longer than ${MAX_KEY_LENGTH} characters`;
|
|
231
|
+
if (FORBIDDEN_KEYS.has(key)) return `uses the reserved key "${key}"`;
|
|
232
|
+
return null;
|
|
233
|
+
}
|
|
234
|
+
function writablePatternProblem(pattern) {
|
|
235
|
+
const segments = pattern.split(".");
|
|
236
|
+
if (segments.length > MAX_PATH_DEPTH) return `has more than ${MAX_PATH_DEPTH} keys`;
|
|
237
|
+
for (const segment of segments) {
|
|
238
|
+
if (segment === ANY_SEGMENT || segment === SELF_SEGMENT) continue;
|
|
239
|
+
const problem = keyProblem(segment);
|
|
240
|
+
if (problem) return problem;
|
|
241
|
+
}
|
|
242
|
+
return null;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// ../protocol/src/schema.ts
|
|
246
|
+
var SCHEMA_TYPES = ["object", "array", "string", "number", "integer", "boolean", "null"];
|
|
247
|
+
var KEYWORDS = [
|
|
248
|
+
"type",
|
|
249
|
+
"enum",
|
|
250
|
+
"properties",
|
|
251
|
+
"required",
|
|
252
|
+
"additionalProperties",
|
|
253
|
+
"items",
|
|
254
|
+
"minItems",
|
|
255
|
+
"maxItems",
|
|
256
|
+
"minimum",
|
|
257
|
+
"maximum",
|
|
258
|
+
"minLength",
|
|
259
|
+
"maxLength"
|
|
260
|
+
];
|
|
261
|
+
var COUNTS = ["minItems", "maxItems", "minLength", "maxLength"];
|
|
262
|
+
function isObject(value) {
|
|
263
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
264
|
+
}
|
|
265
|
+
function schemaProblem(schema, at = "moveSchema", depth = 0) {
|
|
266
|
+
if (depth > MAX_SCHEMA_DEPTH) return `${at} nests deeper than ${MAX_SCHEMA_DEPTH} levels`;
|
|
267
|
+
if (!isObject(schema)) return `${at} must be an object such as {"type":"integer"}`;
|
|
268
|
+
for (const key of Object.keys(schema)) {
|
|
269
|
+
if (!KEYWORDS.includes(key)) {
|
|
270
|
+
return `${at} uses "${key.slice(0, 40)}", which move schemas don't support (they support ${KEYWORDS.join(", ")})`;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
const { type, enum: options, properties, required, additionalProperties, items } = schema;
|
|
274
|
+
if (type !== void 0 && !SCHEMA_TYPES.includes(type)) {
|
|
275
|
+
return `${at}.type must be one of ${SCHEMA_TYPES.join(", ")}`;
|
|
276
|
+
}
|
|
277
|
+
if (options !== void 0 && (!Array.isArray(options) || options.length === 0)) {
|
|
278
|
+
return `${at}.enum must be a non-empty list`;
|
|
279
|
+
}
|
|
280
|
+
if (properties !== void 0) {
|
|
281
|
+
if (!isObject(properties)) return `${at}.properties must be an object of schemas`;
|
|
282
|
+
for (const [key, inner] of Object.entries(properties)) {
|
|
283
|
+
const bad = keyProblem(key);
|
|
284
|
+
if (bad) return `${at}.properties ${bad}`;
|
|
285
|
+
const problem = schemaProblem(inner, `${at}.properties.${key}`, depth + 1);
|
|
286
|
+
if (problem) return problem;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
if (required !== void 0 && (!Array.isArray(required) || !required.every((k) => typeof k === "string"))) {
|
|
290
|
+
return `${at}.required must be a list of field names`;
|
|
291
|
+
}
|
|
292
|
+
if (additionalProperties !== void 0 && typeof additionalProperties !== "boolean") {
|
|
293
|
+
return `${at}.additionalProperties must be true or false`;
|
|
294
|
+
}
|
|
295
|
+
if (items !== void 0) {
|
|
296
|
+
const problem = schemaProblem(items, `${at}.items`, depth + 1);
|
|
297
|
+
if (problem) return problem;
|
|
298
|
+
}
|
|
299
|
+
for (const key of ["minimum", "maximum", ...COUNTS]) {
|
|
300
|
+
const value = schema[key];
|
|
301
|
+
if (value === void 0) continue;
|
|
302
|
+
if (typeof value !== "number" || !Number.isFinite(value)) return `${at}.${key} must be a number`;
|
|
303
|
+
if (COUNTS.includes(key) && (!Number.isInteger(value) || value < 0)) {
|
|
304
|
+
return `${at}.${key} must be a whole number of 0 or more`;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
return null;
|
|
308
|
+
}
|
|
309
|
+
function typeOf(value) {
|
|
310
|
+
if (value === null) return "null";
|
|
311
|
+
if (Array.isArray(value)) return "array";
|
|
312
|
+
if (typeof value === "number") return Number.isInteger(value) ? "integer" : "number";
|
|
313
|
+
return typeof value;
|
|
314
|
+
}
|
|
315
|
+
function equal(a, b) {
|
|
316
|
+
if (a === b) return true;
|
|
317
|
+
if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
|
|
318
|
+
if (Array.isArray(a) !== Array.isArray(b)) return false;
|
|
319
|
+
if (Array.isArray(a) && Array.isArray(b))
|
|
320
|
+
return a.length === b.length && a.every((x, i) => equal(x, b[i]));
|
|
321
|
+
const ak = Object.keys(a);
|
|
322
|
+
const bo = b;
|
|
323
|
+
return ak.length === Object.keys(bo).length && ak.every((k) => Object.hasOwn(bo, k) && equal(a[k], bo[k]));
|
|
324
|
+
}
|
|
325
|
+
var article = (type) => type === "object" || type === "array" || type === "integer" ? `an ${type}` : `a ${type}`;
|
|
326
|
+
function moveProblem(schema, value, at = "move") {
|
|
327
|
+
if (schema.enum && !schema.enum.some((option) => equal(option, value))) {
|
|
328
|
+
return `${at} must be one of ${schema.enum.map((o) => JSON.stringify(o)).join(", ")}`;
|
|
329
|
+
}
|
|
330
|
+
const actual = typeOf(value);
|
|
331
|
+
if (schema.type && actual !== schema.type && !(schema.type === "number" && actual === "integer")) {
|
|
332
|
+
return `${at} must be ${article(schema.type)}, not ${article(actual)}`;
|
|
333
|
+
}
|
|
334
|
+
if (typeof value === "number") {
|
|
335
|
+
if (schema.minimum !== void 0 && value < schema.minimum) return `${at} must be at least ${schema.minimum}`;
|
|
336
|
+
if (schema.maximum !== void 0 && value > schema.maximum) return `${at} must be at most ${schema.maximum}`;
|
|
337
|
+
}
|
|
338
|
+
if (typeof value === "string") {
|
|
339
|
+
if (schema.minLength !== void 0 && value.length < schema.minLength) {
|
|
340
|
+
return `${at} must be at least ${schema.minLength} characters`;
|
|
341
|
+
}
|
|
342
|
+
if (schema.maxLength !== void 0 && value.length > schema.maxLength) {
|
|
343
|
+
return `${at} must be at most ${schema.maxLength} characters`;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
if (Array.isArray(value)) {
|
|
347
|
+
if (schema.minItems !== void 0 && value.length < schema.minItems) {
|
|
348
|
+
return `${at} must have at least ${schema.minItems} items`;
|
|
349
|
+
}
|
|
350
|
+
if (schema.maxItems !== void 0 && value.length > schema.maxItems) {
|
|
351
|
+
return `${at} must have at most ${schema.maxItems} items`;
|
|
352
|
+
}
|
|
353
|
+
if (schema.items) {
|
|
354
|
+
for (const [i, item] of value.entries()) {
|
|
355
|
+
const problem = moveProblem(schema.items, item, `${at}[${i}]`);
|
|
356
|
+
if (problem) return problem;
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
if (actual === "object") {
|
|
361
|
+
const object = value;
|
|
362
|
+
for (const key of schema.required ?? []) {
|
|
363
|
+
if (!Object.hasOwn(object, key)) return `${at}.${key} is missing`;
|
|
364
|
+
}
|
|
365
|
+
for (const [key, inner] of Object.entries(object)) {
|
|
366
|
+
const rule = schema.properties && Object.hasOwn(schema.properties, key) ? schema.properties[key] : void 0;
|
|
367
|
+
if (rule) {
|
|
368
|
+
const problem = moveProblem(rule, inner, `${at}.${key}`);
|
|
369
|
+
if (problem) return problem;
|
|
370
|
+
} else if (schema.additionalProperties === false) {
|
|
371
|
+
return `${at} has no field "${key.slice(0, 40)}"`;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
return null;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// ../protocol/src/state.ts
|
|
379
|
+
function isObject2(value) {
|
|
380
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
381
|
+
}
|
|
382
|
+
function entrySize(key, value) {
|
|
383
|
+
return key.length + 4 + JSON.stringify(value).length;
|
|
384
|
+
}
|
|
385
|
+
function put(parent, key, value) {
|
|
386
|
+
const had = Object.hasOwn(parent, key);
|
|
387
|
+
const old = parent[key];
|
|
388
|
+
parent[key] = value;
|
|
389
|
+
return {
|
|
390
|
+
sizeDelta: entrySize(key, value) - (had && old !== void 0 ? entrySize(key, old) : 0),
|
|
391
|
+
undo: () => {
|
|
392
|
+
if (had && old !== void 0) parent[key] = old;
|
|
393
|
+
else delete parent[key];
|
|
394
|
+
}
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
function remove(parent, key) {
|
|
398
|
+
if (!Object.hasOwn(parent, key)) return { sizeDelta: 0, undo: () => {
|
|
399
|
+
} };
|
|
400
|
+
const old = parent[key];
|
|
401
|
+
const keys = Object.keys(parent);
|
|
402
|
+
const after = keys.slice(keys.indexOf(key) + 1);
|
|
403
|
+
delete parent[key];
|
|
404
|
+
return {
|
|
405
|
+
sizeDelta: -entrySize(key, old),
|
|
406
|
+
// Re-adding a key puts it last; move the keys that followed it back behind it,
|
|
407
|
+
// so a rolled-back patch leaves even the key order untouched.
|
|
408
|
+
undo: () => {
|
|
409
|
+
parent[key] = old;
|
|
410
|
+
for (const k of after) {
|
|
411
|
+
const value = parent[k];
|
|
412
|
+
delete parent[k];
|
|
413
|
+
parent[k] = value;
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
};
|
|
417
|
+
}
|
|
418
|
+
function walk(state, path, create, applied) {
|
|
419
|
+
let node = state;
|
|
420
|
+
for (let i = 0; i < path.length; i++) {
|
|
421
|
+
const key = path[i];
|
|
422
|
+
const next = node[key];
|
|
423
|
+
if (next === void 0) {
|
|
424
|
+
if (!create) return null;
|
|
425
|
+
const made = {};
|
|
426
|
+
applied.push(put(node, key, made));
|
|
427
|
+
node = made;
|
|
428
|
+
} else if (isObject2(next)) {
|
|
429
|
+
node = next;
|
|
430
|
+
} else {
|
|
431
|
+
return path.slice(0, i + 1).join(".");
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
return node;
|
|
435
|
+
}
|
|
436
|
+
function applyOp(state, op, applied) {
|
|
437
|
+
const parentPath = op.op === "merge" ? op.path : op.path.slice(0, -1);
|
|
438
|
+
const target = walk(state, parentPath, op.op !== "delete", applied);
|
|
439
|
+
if (typeof target === "string") {
|
|
440
|
+
return `can't write ${op.path.join(".") || "the root"} because ${target} isn't an object; set ${target} to an object first, or write a different path.`;
|
|
441
|
+
}
|
|
442
|
+
if (target === null) return null;
|
|
443
|
+
switch (op.op) {
|
|
444
|
+
case "set":
|
|
445
|
+
applied.push(put(target, op.path.at(-1), op.value));
|
|
446
|
+
return null;
|
|
447
|
+
case "merge":
|
|
448
|
+
for (const [key, value] of Object.entries(op.value)) applied.push(put(target, key, value));
|
|
449
|
+
return null;
|
|
450
|
+
case "delete":
|
|
451
|
+
applied.push(remove(target, op.path.at(-1)));
|
|
452
|
+
return null;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
function applyOps(state, ops) {
|
|
456
|
+
const applied = [];
|
|
457
|
+
const undo = () => {
|
|
458
|
+
for (let i = applied.length - 1; i >= 0; i--) applied[i]?.undo();
|
|
459
|
+
};
|
|
460
|
+
for (const [i, op] of ops.entries()) {
|
|
461
|
+
const problem = applyOp(state, op, applied);
|
|
462
|
+
if (problem) {
|
|
463
|
+
undo();
|
|
464
|
+
return { ok: false, message: `patch.ops[${i}] ${problem}` };
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
return { ok: true, sizeDelta: applied.reduce((sum, a) => sum + a.sizeDelta, 0), undo };
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
// ../protocol/src/validate.ts
|
|
471
|
+
var MAX_KEY_STRING = 256;
|
|
472
|
+
var MAX_SDK_STRING = 64;
|
|
473
|
+
var MAX_TOKEN_STRING = 4096;
|
|
474
|
+
var MAX_PLAYER_ID_STRING = 64;
|
|
475
|
+
var ROOM_OPTION_KEYS = ["type", "seats", "writable", "turnMs", "tickHz", "moveSchema", "script"];
|
|
476
|
+
var FORMATS_HINT = "see the message formats in llms.txt, or send it through the cotchu SDK";
|
|
477
|
+
var Invalid = class extends Error {
|
|
478
|
+
constructor(code, message) {
|
|
479
|
+
super(message);
|
|
480
|
+
this.code = code;
|
|
481
|
+
}
|
|
482
|
+
code;
|
|
483
|
+
};
|
|
484
|
+
function invalid(where, problem, fix = FORMATS_HINT) {
|
|
485
|
+
throw new Invalid("bad_message", `${where} ${problem}; ${fix}.`);
|
|
486
|
+
}
|
|
487
|
+
function failure(code, message, id) {
|
|
488
|
+
return { ok: false, error: id === void 0 ? { code, message } : { code, message, id } };
|
|
489
|
+
}
|
|
490
|
+
function isObject3(value) {
|
|
491
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
492
|
+
}
|
|
493
|
+
function describe(value) {
|
|
494
|
+
if (value === void 0) return "missing";
|
|
495
|
+
if (typeof value === "string") return JSON.stringify(value.length > 40 ? `${value.slice(0, 40)}\u2026` : value);
|
|
496
|
+
if (Array.isArray(value)) return "a list";
|
|
497
|
+
if (value === null) return "null";
|
|
498
|
+
if (typeof value === "object") return "an object";
|
|
499
|
+
return String(value);
|
|
500
|
+
}
|
|
501
|
+
function utf8ByteLength(text) {
|
|
502
|
+
let bytes = 0;
|
|
503
|
+
for (let i = 0; i < text.length; i++) {
|
|
504
|
+
const code = text.charCodeAt(i);
|
|
505
|
+
if (code < 128) bytes += 1;
|
|
506
|
+
else if (code < 2048) bytes += 2;
|
|
507
|
+
else if (code >= 55296 && code <= 56319 && (text.charCodeAt(i + 1) & 64512) === 56320) {
|
|
508
|
+
bytes += 4;
|
|
509
|
+
i++;
|
|
510
|
+
} else bytes += 3;
|
|
511
|
+
}
|
|
512
|
+
return bytes;
|
|
513
|
+
}
|
|
514
|
+
function fitsMessageLimit(text) {
|
|
515
|
+
if (text.length > MAX_MSG_BYTES) return false;
|
|
516
|
+
if (text.length * 3 <= MAX_MSG_BYTES) return true;
|
|
517
|
+
return utf8ByteLength(text) <= MAX_MSG_BYTES;
|
|
518
|
+
}
|
|
519
|
+
function checkValue(value, where, depth = 0) {
|
|
520
|
+
if (depth > MAX_VALUE_DEPTH) invalid(where, `nests deeper than ${MAX_VALUE_DEPTH} levels`, "flatten the data");
|
|
521
|
+
if (typeof value === "number") {
|
|
522
|
+
if (!Number.isFinite(value)) invalid(where, "has a number too large to store", "send it as a string instead");
|
|
523
|
+
return;
|
|
524
|
+
}
|
|
525
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return;
|
|
526
|
+
if (Array.isArray(value)) {
|
|
527
|
+
for (const item of value) checkValue(item, where, depth + 1);
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
530
|
+
if (isObject3(value)) {
|
|
531
|
+
for (const [key, item] of Object.entries(value)) {
|
|
532
|
+
const problem = keyProblem(key);
|
|
533
|
+
if (problem) invalid(where, problem, "rename that key");
|
|
534
|
+
checkValue(item, where, depth + 1);
|
|
535
|
+
}
|
|
536
|
+
return;
|
|
537
|
+
}
|
|
538
|
+
invalid(where, "isn't JSON data");
|
|
539
|
+
}
|
|
540
|
+
function readInt(value, where, min, max) {
|
|
541
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) {
|
|
542
|
+
invalid(
|
|
543
|
+
where,
|
|
544
|
+
`is ${describe(value)} but must be a whole number from ${min} to ${max}`,
|
|
545
|
+
"pick a value in that range"
|
|
546
|
+
);
|
|
547
|
+
}
|
|
548
|
+
return value;
|
|
549
|
+
}
|
|
550
|
+
function readString(value, where, max, fix) {
|
|
551
|
+
if (typeof value !== "string" || value.length === 0 || value.length > max) {
|
|
552
|
+
invalid(where, `must be text of 1 to ${max} characters`, fix);
|
|
553
|
+
}
|
|
554
|
+
return value;
|
|
555
|
+
}
|
|
556
|
+
function readId(value) {
|
|
557
|
+
if (value === void 0) return void 0;
|
|
558
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
|
|
559
|
+
invalid(
|
|
560
|
+
"id",
|
|
561
|
+
`is ${describe(value)} but must be a whole number of 0 or more`,
|
|
562
|
+
"number each message from 0 upwards"
|
|
563
|
+
);
|
|
564
|
+
}
|
|
565
|
+
return value;
|
|
566
|
+
}
|
|
567
|
+
function readPath(value, where, minLength) {
|
|
568
|
+
const at = `${where}.path`;
|
|
569
|
+
if (!Array.isArray(value)) invalid(at, "must be a list of keys", 'for example ["players", "abc", "x"]');
|
|
570
|
+
if (value.length < minLength) invalid(at, "is empty", "name the key to change, or use merge to change the root");
|
|
571
|
+
if (value.length > MAX_PATH_DEPTH) invalid(at, `has more than ${MAX_PATH_DEPTH} keys`, "keep the state flatter");
|
|
572
|
+
const path = [];
|
|
573
|
+
for (const key of value) {
|
|
574
|
+
if (typeof key !== "string") {
|
|
575
|
+
invalid(at, "must contain only text keys", 'write numbers as text, for example ["slots", "3"]');
|
|
576
|
+
}
|
|
577
|
+
const problem = keyProblem(key);
|
|
578
|
+
if (problem) invalid(at, problem, "pick a different key");
|
|
579
|
+
path.push(key);
|
|
580
|
+
}
|
|
581
|
+
return path;
|
|
582
|
+
}
|
|
583
|
+
function readOp(value, where) {
|
|
584
|
+
if (!isObject3(value)) invalid(where, "must be an object with op and path", '"op" is "set", "merge" or "delete"');
|
|
585
|
+
switch (value.op) {
|
|
586
|
+
case "set": {
|
|
587
|
+
const path = readPath(value.path, where, 1);
|
|
588
|
+
if (!("value" in value)) invalid(`${where}.value`, "is missing", 'use "delete" to remove a value');
|
|
589
|
+
const data = value.value;
|
|
590
|
+
checkValue(data, `${where}.value`);
|
|
591
|
+
return { op: "set", path, value: data };
|
|
592
|
+
}
|
|
593
|
+
case "merge": {
|
|
594
|
+
const path = readPath(value.path, where, 0);
|
|
595
|
+
const data = value.value;
|
|
596
|
+
if (!isObject3(data)) invalid(`${where}.value`, "must be an object to merge", 'use "set" to store other values');
|
|
597
|
+
checkValue(data, `${where}.value`);
|
|
598
|
+
return { op: "merge", path, value: data };
|
|
599
|
+
}
|
|
600
|
+
case "delete":
|
|
601
|
+
return { op: "delete", path: readPath(value.path, where, 1) };
|
|
602
|
+
default:
|
|
603
|
+
return invalid(`${where}.op`, `is ${describe(value.op)}`, 'use "set", "merge" or "delete"');
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
function readOps(value) {
|
|
607
|
+
if (!Array.isArray(value)) {
|
|
608
|
+
invalid("patch.ops", "must be a list of operations", 'for example [{"op":"set","path":["score"],"value":1}]');
|
|
609
|
+
}
|
|
610
|
+
if (value.length === 0) invalid("patch.ops", "is empty", "include at least one operation");
|
|
611
|
+
if (value.length > MAX_OPS_PER_PATCH) {
|
|
612
|
+
invalid("patch.ops", `has more than ${MAX_OPS_PER_PATCH} operations`, "split the change across several patches");
|
|
613
|
+
}
|
|
614
|
+
return value.map((op, i) => readOp(op, `patch.ops[${i}]`));
|
|
615
|
+
}
|
|
616
|
+
function readData(message, type) {
|
|
617
|
+
if (!("data" in message)) {
|
|
618
|
+
invalid(`${type}.data`, "is missing", `put the payload in "data", for example {"t":"${type}","data":{}}`);
|
|
619
|
+
}
|
|
620
|
+
const data = message.data;
|
|
621
|
+
checkValue(data, `${type}.data`);
|
|
622
|
+
return data;
|
|
623
|
+
}
|
|
624
|
+
function readName(value) {
|
|
625
|
+
if (typeof value !== "string")
|
|
626
|
+
invalid("hello.name", `is ${describe(value)} but must be text`, "send the name as text");
|
|
627
|
+
const name = value.trim();
|
|
628
|
+
if (name.length === 0 || name.length > MAX_NAME_LENGTH) {
|
|
629
|
+
invalid("hello.name", `must be 1 to ${MAX_NAME_LENGTH} characters`, "shorten the player's name");
|
|
630
|
+
}
|
|
631
|
+
if (/\p{Cc}/u.test(name)) invalid("hello.name", "contains control characters", "remove line breaks and tabs");
|
|
632
|
+
return name;
|
|
633
|
+
}
|
|
634
|
+
function readWritable(value) {
|
|
635
|
+
const where = "hello.room.writable";
|
|
636
|
+
if (!Array.isArray(value) || value.length > MAX_WRITABLE_PATTERNS) {
|
|
637
|
+
invalid(where, `must be a list of up to ${MAX_WRITABLE_PATTERNS} path patterns`, 'for example ["players.$self"]');
|
|
638
|
+
}
|
|
639
|
+
return value.map((pattern, i) => {
|
|
640
|
+
const text = readString(pattern, `${where}[${i}]`, MAX_KEY_STRING, 'write it like "players.$self"');
|
|
641
|
+
const problem = writablePatternProblem(text);
|
|
642
|
+
if (problem) invalid(`${where}[${i}]`, problem, 'write it like "players.$self"');
|
|
643
|
+
return text;
|
|
644
|
+
});
|
|
645
|
+
}
|
|
646
|
+
function readRoomOptions(value) {
|
|
647
|
+
const where = "hello.room";
|
|
648
|
+
if (!isObject3(value)) invalid(where, "must be an object", 'for example {"type":"shared","seats":8}');
|
|
649
|
+
for (const key of Object.keys(value)) {
|
|
650
|
+
if (!ROOM_OPTION_KEYS.includes(key)) {
|
|
651
|
+
invalid(where, `has no option ${describe(key)}`, `the options are ${ROOM_OPTION_KEYS.join(", ")}`);
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
const options = {};
|
|
655
|
+
const { type, seats, writable, turnMs, tickHz, moveSchema, script } = value;
|
|
656
|
+
if (type !== void 0) {
|
|
657
|
+
if (!isRoomType(type)) {
|
|
658
|
+
invalid(`${where}.type`, `is ${describe(type)}`, 'use "shared", "turns", "realtime" or "script"');
|
|
659
|
+
}
|
|
660
|
+
options.type = type;
|
|
661
|
+
}
|
|
662
|
+
if (script !== void 0) {
|
|
663
|
+
if (type !== void 0 && type !== "script") {
|
|
664
|
+
invalid(`${where}.script`, "only applies to script rooms", 'remove it, or set type to "script"');
|
|
665
|
+
}
|
|
666
|
+
if (!isScriptName(script)) {
|
|
667
|
+
invalid(`${where}.script`, `is ${describe(script)}`, 'use the name the script was deployed with, like "cards"');
|
|
668
|
+
}
|
|
669
|
+
options.type = "script";
|
|
670
|
+
options.script = script;
|
|
671
|
+
} else if (type === "script") {
|
|
672
|
+
invalid(`${where}.script`, "is missing", 'name the deployed script, like {"type":"script","script":"cards"}');
|
|
673
|
+
}
|
|
674
|
+
if (seats !== void 0) options.seats = readInt(seats, `${where}.seats`, 1, MAX_SEATS);
|
|
675
|
+
if (writable !== void 0) options.writable = readWritable(writable);
|
|
676
|
+
if (turnMs !== void 0) {
|
|
677
|
+
if (type !== void 0 && type !== "turns") {
|
|
678
|
+
invalid(`${where}.turnMs`, "only applies to turns rooms", 'remove it, or set type to "turns"');
|
|
679
|
+
}
|
|
680
|
+
options.turnMs = readInt(turnMs, `${where}.turnMs`, MIN_TURN_MS, MAX_TURN_MS);
|
|
681
|
+
}
|
|
682
|
+
if (tickHz !== void 0) {
|
|
683
|
+
if (options.type !== void 0 && options.type !== "realtime" && options.type !== "script") {
|
|
684
|
+
invalid(`${where}.tickHz`, "only applies to realtime and script rooms", 'remove it, or set type to "realtime"');
|
|
685
|
+
}
|
|
686
|
+
options.tickHz = readInt(tickHz, `${where}.tickHz`, MIN_TICK_HZ, MAX_TICK_HZ);
|
|
687
|
+
}
|
|
688
|
+
if (moveSchema !== void 0) {
|
|
689
|
+
if (type !== void 0 && type !== "turns") {
|
|
690
|
+
invalid(`${where}.moveSchema`, "only applies to turns rooms", 'remove it, or set type to "turns"');
|
|
691
|
+
}
|
|
692
|
+
const problem = schemaProblem(moveSchema, `${where}.moveSchema`);
|
|
693
|
+
if (problem) throw new Invalid("bad_message", `${problem}; fix the schema.`);
|
|
694
|
+
if (utf8ByteLength(JSON.stringify(moveSchema)) > MAX_SCHEMA_BYTES) {
|
|
695
|
+
invalid(`${where}.moveSchema`, `is over ${MAX_SCHEMA_BYTES / 1024} KB`, "describe the move more simply");
|
|
696
|
+
}
|
|
697
|
+
options.moveSchema = moveSchema;
|
|
698
|
+
}
|
|
699
|
+
return options;
|
|
700
|
+
}
|
|
701
|
+
function readHello(message) {
|
|
702
|
+
const { v, key, sdk, name, token, resume, room } = message;
|
|
703
|
+
if (typeof v !== "number" || !Number.isInteger(v)) {
|
|
704
|
+
invalid("hello.v", "must be the protocol version number", `send ${PROTOCOL_VERSION}`);
|
|
705
|
+
}
|
|
706
|
+
if (v !== PROTOCOL_VERSION) {
|
|
707
|
+
throw new Invalid(
|
|
708
|
+
"unsupported_version",
|
|
709
|
+
`This client speaks protocol ${v} but the room speaks ${PROTOCOL_VERSION}; update the cotchu package to the latest.`
|
|
710
|
+
);
|
|
711
|
+
}
|
|
712
|
+
if (key === void 0) {
|
|
713
|
+
throw new Invalid(
|
|
714
|
+
"bad_key",
|
|
715
|
+
"No project key was sent; pass your project's pk_ key as the key option to cotchu.join()."
|
|
716
|
+
);
|
|
717
|
+
}
|
|
718
|
+
if (typeof key !== "string" || key.length === 0 || key.length > MAX_KEY_STRING) {
|
|
719
|
+
throw new Invalid("bad_key", ERRORS.bad_key.message);
|
|
720
|
+
}
|
|
721
|
+
const hello = {
|
|
722
|
+
t: "hello",
|
|
723
|
+
v,
|
|
724
|
+
key,
|
|
725
|
+
sdk: readString(sdk, "hello.sdk", MAX_SDK_STRING, 'name the client and its version, like "cotchu-js/0.1.0"')
|
|
726
|
+
};
|
|
727
|
+
if (name !== void 0) hello.name = readName(name);
|
|
728
|
+
if (token !== void 0) hello.token = readString(token, "hello.token", MAX_TOKEN_STRING, "send the token as issued");
|
|
729
|
+
if (resume !== void 0) {
|
|
730
|
+
hello.resume = readString(resume, "hello.resume", MAX_KEY_STRING, "send the resume value from welcome unchanged");
|
|
731
|
+
}
|
|
732
|
+
if (room !== void 0) hello.room = readRoomOptions(room);
|
|
733
|
+
return hello;
|
|
734
|
+
}
|
|
735
|
+
function readClientMessage(message, id) {
|
|
736
|
+
const tagged = id === void 0 ? {} : { id };
|
|
737
|
+
switch (message.t) {
|
|
738
|
+
case "hello":
|
|
739
|
+
return readHello(message);
|
|
740
|
+
case "patch":
|
|
741
|
+
return { t: "patch", ...tagged, ops: readOps(message.ops) };
|
|
742
|
+
case "move":
|
|
743
|
+
return { t: "move", ...tagged, data: readData(message, "move") };
|
|
744
|
+
case "input":
|
|
745
|
+
return { t: "input", data: readData(message, "input") };
|
|
746
|
+
case "msg": {
|
|
747
|
+
const data = readData(message, "msg");
|
|
748
|
+
if (message.to === void 0) return { t: "msg", ...tagged, data };
|
|
749
|
+
const to = readString(message.to, "msg.to", MAX_PLAYER_ID_STRING, "use a player id from the room");
|
|
750
|
+
return { t: "msg", ...tagged, to, data };
|
|
751
|
+
}
|
|
752
|
+
case "ping":
|
|
753
|
+
return { t: "ping" };
|
|
754
|
+
case "act":
|
|
755
|
+
return { t: "act", ...tagged, data: readData(message, "act") };
|
|
756
|
+
default:
|
|
757
|
+
throw new Invalid(
|
|
758
|
+
"bad_message",
|
|
759
|
+
`Unknown message type ${describe(message.t)}; use one of ${CLIENT_MESSAGE_TYPES.join(", ")}.`
|
|
760
|
+
);
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
function parseClientMessage(raw) {
|
|
764
|
+
if (typeof raw !== "string") {
|
|
765
|
+
if (raw.byteLength > MAX_MSG_BYTES) return failure("too_large", ERRORS.too_large.message);
|
|
766
|
+
return failure("bad_message", "Binary frames aren't supported yet; send each message as a JSON text frame.");
|
|
767
|
+
}
|
|
768
|
+
if (!fitsMessageLimit(raw)) return failure("too_large", ERRORS.too_large.message);
|
|
769
|
+
let parsed;
|
|
770
|
+
try {
|
|
771
|
+
parsed = JSON.parse(raw);
|
|
772
|
+
} catch {
|
|
773
|
+
return failure(
|
|
774
|
+
"bad_message",
|
|
775
|
+
`That frame isn't valid JSON; send each message as one JSON object, such as ${PING_FRAME}.`
|
|
776
|
+
);
|
|
777
|
+
}
|
|
778
|
+
if (!isObject3(parsed)) {
|
|
779
|
+
return failure(
|
|
780
|
+
"bad_message",
|
|
781
|
+
`Each message must be a JSON object with a "t" field naming its type; for example ${PING_FRAME}.`
|
|
782
|
+
);
|
|
783
|
+
}
|
|
784
|
+
let id;
|
|
785
|
+
try {
|
|
786
|
+
id = readId(parsed.id);
|
|
787
|
+
return { ok: true, message: readClientMessage(parsed, id) };
|
|
788
|
+
} catch (error) {
|
|
789
|
+
if (error instanceof Invalid) return failure(error.code, error.message, id);
|
|
790
|
+
throw error;
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
function parseServerMessage(raw) {
|
|
794
|
+
let parsed;
|
|
795
|
+
try {
|
|
796
|
+
parsed = JSON.parse(raw);
|
|
797
|
+
} catch {
|
|
798
|
+
return failure(
|
|
799
|
+
"bad_message",
|
|
800
|
+
"The room sent a frame that isn't JSON; check the SDK is pointed at a Cotchu rooms URL."
|
|
801
|
+
);
|
|
802
|
+
}
|
|
803
|
+
if (!isObject3(parsed) || !SERVER_MESSAGE_TYPES.includes(parsed.t)) {
|
|
804
|
+
const type = isObject3(parsed) ? describe(parsed.t) : "missing";
|
|
805
|
+
return failure(
|
|
806
|
+
"bad_message",
|
|
807
|
+
`The room sent an unknown message type ${type}; update the cotchu package to the latest.`
|
|
808
|
+
);
|
|
809
|
+
}
|
|
810
|
+
return { ok: true, message: parsed };
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
// src/errors.ts
|
|
814
|
+
var CotchuError = class extends Error {
|
|
815
|
+
constructor(code, message) {
|
|
816
|
+
super(
|
|
817
|
+
message ?? (isErrorCode(code) ? ERRORS[code].message : `The room reported "${code}"; update the cotchu package.`)
|
|
818
|
+
);
|
|
819
|
+
this.code = code;
|
|
820
|
+
this.fatal = isFatal(code);
|
|
821
|
+
}
|
|
822
|
+
code;
|
|
823
|
+
name = "CotchuError";
|
|
824
|
+
/** True when the room is closed for good and the SDK won't reconnect. */
|
|
825
|
+
fatal;
|
|
826
|
+
};
|
|
827
|
+
|
|
828
|
+
// src/emitter.ts
|
|
829
|
+
var Emitter = class {
|
|
830
|
+
// Listeners of every event share one map; on/emit restore their types.
|
|
831
|
+
listeners = /* @__PURE__ */ new Map();
|
|
832
|
+
/** Calls `listener` on every `event`. Returns a function that stops it. */
|
|
833
|
+
on(event, listener) {
|
|
834
|
+
let set = this.listeners.get(event);
|
|
835
|
+
if (!set) this.listeners.set(event, set = /* @__PURE__ */ new Set());
|
|
836
|
+
set.add(listener);
|
|
837
|
+
return () => this.off(event, listener);
|
|
838
|
+
}
|
|
839
|
+
/** Calls `listener` on the next `event` only. */
|
|
840
|
+
once(event, listener) {
|
|
841
|
+
const off = this.on(event, (...args) => {
|
|
842
|
+
off();
|
|
843
|
+
listener(...args);
|
|
844
|
+
});
|
|
845
|
+
return off;
|
|
846
|
+
}
|
|
847
|
+
off(event, listener) {
|
|
848
|
+
this.listeners.get(event)?.delete(listener);
|
|
849
|
+
}
|
|
850
|
+
/** Returns false when nobody was listening. A throwing listener is reported, not fatal. */
|
|
851
|
+
emit(event, ...args) {
|
|
852
|
+
const set = this.listeners.get(event);
|
|
853
|
+
if (!set || set.size === 0) return false;
|
|
854
|
+
for (const listener of [...set]) {
|
|
855
|
+
try {
|
|
856
|
+
listener(...args);
|
|
857
|
+
} catch (error) {
|
|
858
|
+
console.error(`[cotchu] A "${String(event)}" listener threw:`, error);
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
return true;
|
|
862
|
+
}
|
|
863
|
+
};
|
|
864
|
+
|
|
865
|
+
// src/outbox.ts
|
|
866
|
+
var PATCH_ENVELOPE_BYTES = 64;
|
|
867
|
+
var OUTBOX_LIMIT = 256;
|
|
868
|
+
function covers(prefix, path) {
|
|
869
|
+
return prefix.length <= path.length && prefix.every((key, i) => path[i] === key);
|
|
870
|
+
}
|
|
871
|
+
var Outbox = class {
|
|
872
|
+
constructor(transmit, nextId, now = Date.now) {
|
|
873
|
+
this.transmit = transmit;
|
|
874
|
+
this.nextId = nextId;
|
|
875
|
+
this.now = now;
|
|
876
|
+
this.refilledAt = now();
|
|
877
|
+
}
|
|
878
|
+
transmit;
|
|
879
|
+
nextId;
|
|
880
|
+
now;
|
|
881
|
+
queue = [];
|
|
882
|
+
sizes = /* @__PURE__ */ new WeakMap();
|
|
883
|
+
tokens = CLIENT_RATE_LIMIT_BURST;
|
|
884
|
+
refilledAt;
|
|
885
|
+
timer;
|
|
886
|
+
flushQueued = false;
|
|
887
|
+
get size() {
|
|
888
|
+
return this.queue.length;
|
|
889
|
+
}
|
|
890
|
+
/** Ops not yet sent, in order. */
|
|
891
|
+
queuedOps() {
|
|
892
|
+
return this.queue.flatMap((m) => m.t === "patch" ? m.ops : []);
|
|
893
|
+
}
|
|
894
|
+
/** Returns false when the outbox is full. */
|
|
895
|
+
addOps(ops) {
|
|
896
|
+
for (const op of ops) {
|
|
897
|
+
const bytes = utf8ByteLength(JSON.stringify(op)) + 1;
|
|
898
|
+
const last = this.queue.at(-1);
|
|
899
|
+
if (last?.t === "patch") {
|
|
900
|
+
if (op.op !== "merge") last.ops = last.ops.filter((queued) => !covers(op.path, queued.path));
|
|
901
|
+
const size = last.ops.length === 0 ? 0 : this.sizes.get(last) ?? 0;
|
|
902
|
+
if (last.ops.length < MAX_OPS_PER_PATCH && size + bytes <= MAX_MSG_BYTES - PATCH_ENVELOPE_BYTES) {
|
|
903
|
+
last.ops.push(op);
|
|
904
|
+
this.sizes.set(last, size + bytes);
|
|
905
|
+
continue;
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
if (this.queue.length >= OUTBOX_LIMIT) return false;
|
|
909
|
+
const patch = { t: "patch", id: this.nextId(), ops: [op] };
|
|
910
|
+
this.sizes.set(patch, bytes);
|
|
911
|
+
this.queue.push(patch);
|
|
912
|
+
}
|
|
913
|
+
this.scheduleFlush();
|
|
914
|
+
return true;
|
|
915
|
+
}
|
|
916
|
+
/** Returns false when the outbox is full. */
|
|
917
|
+
add(message) {
|
|
918
|
+
const last = this.queue.at(-1);
|
|
919
|
+
if (message.t === "input" && last?.t === "input") {
|
|
920
|
+
last.data = message.data;
|
|
921
|
+
return true;
|
|
922
|
+
}
|
|
923
|
+
if (this.queue.length >= OUTBOX_LIMIT) return false;
|
|
924
|
+
this.queue.push(message);
|
|
925
|
+
this.scheduleFlush();
|
|
926
|
+
return true;
|
|
927
|
+
}
|
|
928
|
+
/** Sends on the next microtask, so every write made in this tick shares one message. */
|
|
929
|
+
scheduleFlush() {
|
|
930
|
+
if (this.flushQueued || this.timer !== void 0) return;
|
|
931
|
+
this.flushQueued = true;
|
|
932
|
+
queueMicrotask(() => {
|
|
933
|
+
this.flushQueued = false;
|
|
934
|
+
this.flush();
|
|
935
|
+
});
|
|
936
|
+
}
|
|
937
|
+
flush() {
|
|
938
|
+
while (this.queue.length > 0) {
|
|
939
|
+
const head = this.queue[0];
|
|
940
|
+
if (head.t === "patch" && head.ops.length === 0) {
|
|
941
|
+
this.queue.shift();
|
|
942
|
+
continue;
|
|
943
|
+
}
|
|
944
|
+
if (!this.take()) {
|
|
945
|
+
const wait = Math.ceil((1 - this.tokens) * 1e3 / CLIENT_RATE_LIMIT_PER_SEC);
|
|
946
|
+
this.timer ??= setTimeout(() => {
|
|
947
|
+
this.timer = void 0;
|
|
948
|
+
this.flush();
|
|
949
|
+
}, wait);
|
|
950
|
+
return;
|
|
951
|
+
}
|
|
952
|
+
const next = this.queue[0];
|
|
953
|
+
if (!this.transmit(next)) {
|
|
954
|
+
this.tokens += 1;
|
|
955
|
+
return;
|
|
956
|
+
}
|
|
957
|
+
this.queue.shift();
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
take() {
|
|
961
|
+
const now = this.now();
|
|
962
|
+
this.tokens = Math.min(
|
|
963
|
+
CLIENT_RATE_LIMIT_BURST,
|
|
964
|
+
this.tokens + (now - this.refilledAt) * CLIENT_RATE_LIMIT_PER_SEC / 1e3
|
|
965
|
+
);
|
|
966
|
+
this.refilledAt = now;
|
|
967
|
+
if (this.tokens < 1) return false;
|
|
968
|
+
this.tokens -= 1;
|
|
969
|
+
return true;
|
|
970
|
+
}
|
|
971
|
+
clear() {
|
|
972
|
+
this.queue.length = 0;
|
|
973
|
+
if (this.timer !== void 0) clearTimeout(this.timer);
|
|
974
|
+
this.timer = void 0;
|
|
975
|
+
}
|
|
976
|
+
};
|
|
977
|
+
|
|
978
|
+
// src/paths.ts
|
|
979
|
+
var ME = "me";
|
|
980
|
+
function toPath(path, me, call, allowRoot = false) {
|
|
981
|
+
const keys = typeof path === "string" ? path === "" ? [] : path.split(".").map((k) => k === ME ? me : k) : [...path];
|
|
982
|
+
const shown = typeof path === "string" ? JSON.stringify(path) : JSON.stringify(keys);
|
|
983
|
+
if (keys.length === 0 && !allowRoot) {
|
|
984
|
+
throw new CotchuError("bad_message", `${call}() needs a path such as "players.me.x"; an empty path names nothing.`);
|
|
985
|
+
}
|
|
986
|
+
if (keys.length > MAX_PATH_DEPTH) {
|
|
987
|
+
throw new CotchuError(
|
|
988
|
+
"bad_message",
|
|
989
|
+
`${call}() path ${shown} has more than ${MAX_PATH_DEPTH} keys; keep the state flatter.`
|
|
990
|
+
);
|
|
991
|
+
}
|
|
992
|
+
for (const key of keys) {
|
|
993
|
+
if (typeof key !== "string") {
|
|
994
|
+
throw new CotchuError(
|
|
995
|
+
"bad_message",
|
|
996
|
+
`${call}() path ${shown} must contain only text keys; write numbers as text.`
|
|
997
|
+
);
|
|
998
|
+
}
|
|
999
|
+
const problem = keyProblem(key);
|
|
1000
|
+
if (problem) throw new CotchuError("bad_message", `${call}() path ${shown} ${problem}; pick a different key.`);
|
|
1001
|
+
}
|
|
1002
|
+
return keys;
|
|
1003
|
+
}
|
|
1004
|
+
function toJson(value, call) {
|
|
1005
|
+
if (value === void 0 || typeof value === "function" || typeof value === "symbol") {
|
|
1006
|
+
throw new CotchuError(
|
|
1007
|
+
"bad_message",
|
|
1008
|
+
`${call}() needs a JSON value, not ${typeof value}; use delete() to remove a value.`
|
|
1009
|
+
);
|
|
1010
|
+
}
|
|
1011
|
+
let text;
|
|
1012
|
+
try {
|
|
1013
|
+
text = JSON.stringify(value);
|
|
1014
|
+
} catch {
|
|
1015
|
+
throw new CotchuError(
|
|
1016
|
+
"bad_message",
|
|
1017
|
+
`${call}() got a value that can't become JSON, such as a circular object; send plain data.`
|
|
1018
|
+
);
|
|
1019
|
+
}
|
|
1020
|
+
if (utf8ByteLength(text) > MAX_MSG_BYTES) {
|
|
1021
|
+
throw new CotchuError(
|
|
1022
|
+
"too_large",
|
|
1023
|
+
`${call}() got a value over ${MAX_MSG_BYTES / 1024} KB as JSON; split it across several paths.`
|
|
1024
|
+
);
|
|
1025
|
+
}
|
|
1026
|
+
return JSON.parse(text);
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
// src/room.ts
|
|
1030
|
+
var OPEN = 1;
|
|
1031
|
+
var HELLO_TIMEOUT_MS = 1e4;
|
|
1032
|
+
var HEARTBEAT_MS = 15e3;
|
|
1033
|
+
var DEAD_AFTER_MS = 35e3;
|
|
1034
|
+
var BACKOFF_BASE_MS = 250;
|
|
1035
|
+
var BACKOFF_MAX_MS = 5e3;
|
|
1036
|
+
var JOIN_ATTEMPTS = 3;
|
|
1037
|
+
function isObject4(value) {
|
|
1038
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1039
|
+
}
|
|
1040
|
+
var Room = class extends Emitter {
|
|
1041
|
+
/** @internal Use `cotchu.join()`. */
|
|
1042
|
+
constructor(name, connection) {
|
|
1043
|
+
super();
|
|
1044
|
+
this.connection = connection;
|
|
1045
|
+
this.name = name;
|
|
1046
|
+
this.outbox = new Outbox(
|
|
1047
|
+
(message) => this.transmit(message),
|
|
1048
|
+
() => this.nextId++
|
|
1049
|
+
);
|
|
1050
|
+
}
|
|
1051
|
+
connection;
|
|
1052
|
+
/** The room's name, as passed to cotchu.join(). */
|
|
1053
|
+
name;
|
|
1054
|
+
me_ = { id: "", name: "" };
|
|
1055
|
+
config_ = { type: "shared", seats: 0 };
|
|
1056
|
+
players_ = /* @__PURE__ */ new Map();
|
|
1057
|
+
/** State in the room's order, as confirmed by the room. */
|
|
1058
|
+
confirmed = {};
|
|
1059
|
+
/** What the game sees: `confirmed` plus this player's writes the room hasn't confirmed yet. */
|
|
1060
|
+
view = {};
|
|
1061
|
+
inflight = [];
|
|
1062
|
+
turn_ = { player: null };
|
|
1063
|
+
moves_ = [];
|
|
1064
|
+
snap_ = { tick: 0, players: {} };
|
|
1065
|
+
private_ = {};
|
|
1066
|
+
/** `script` rooms: act() calls waiting for the script's answer, by message id. */
|
|
1067
|
+
acts = /* @__PURE__ */ new Map();
|
|
1068
|
+
outbox;
|
|
1069
|
+
nextId = 1;
|
|
1070
|
+
ws = null;
|
|
1071
|
+
welcomed = false;
|
|
1072
|
+
status_ = "connecting";
|
|
1073
|
+
resume;
|
|
1074
|
+
attempt = 0;
|
|
1075
|
+
lastSeen = 0;
|
|
1076
|
+
helloTimer;
|
|
1077
|
+
reconnectTimer;
|
|
1078
|
+
heartbeat;
|
|
1079
|
+
settle;
|
|
1080
|
+
/** The room's last reason for turning a join attempt away, if any; join() rejects with it when it gives up. */
|
|
1081
|
+
refusal;
|
|
1082
|
+
/** @internal Connects; resolves on the room's welcome. */
|
|
1083
|
+
open() {
|
|
1084
|
+
return new Promise((resolve, reject) => {
|
|
1085
|
+
this.settle = { resolve, reject };
|
|
1086
|
+
this.resume = this.connection.seats?.take();
|
|
1087
|
+
this.connect();
|
|
1088
|
+
});
|
|
1089
|
+
}
|
|
1090
|
+
/** This player. The id is stable across reconnects within the 60 s resume window. */
|
|
1091
|
+
get me() {
|
|
1092
|
+
return this.me_;
|
|
1093
|
+
}
|
|
1094
|
+
/** The shared state. Read it freely; change it only with set(), merge() and delete(). */
|
|
1095
|
+
get state() {
|
|
1096
|
+
return this.view;
|
|
1097
|
+
}
|
|
1098
|
+
/** Everyone connected to the room, this player included. */
|
|
1099
|
+
get players() {
|
|
1100
|
+
return [...this.players_.values()];
|
|
1101
|
+
}
|
|
1102
|
+
/** The room's rules, set by whoever joined first. */
|
|
1103
|
+
get config() {
|
|
1104
|
+
return this.config_;
|
|
1105
|
+
}
|
|
1106
|
+
get status() {
|
|
1107
|
+
return this.status_;
|
|
1108
|
+
}
|
|
1109
|
+
/** `turns` rooms: id of the player whose turn it is, or null. */
|
|
1110
|
+
get turn() {
|
|
1111
|
+
return this.turn_.player;
|
|
1112
|
+
}
|
|
1113
|
+
/** `turns` rooms: true when this player may move now. */
|
|
1114
|
+
get isMyTurn() {
|
|
1115
|
+
return this.turn_.player !== null && this.turn_.player === this.me_.id;
|
|
1116
|
+
}
|
|
1117
|
+
/** `turns` rooms: epoch milliseconds when the current turn times out, or null without a turn timer. */
|
|
1118
|
+
get deadline() {
|
|
1119
|
+
return this.turn_.deadline ?? null;
|
|
1120
|
+
}
|
|
1121
|
+
/** `turns` rooms: every move so far, oldest first. Derive the game from these. */
|
|
1122
|
+
get moves() {
|
|
1123
|
+
return this.moves_;
|
|
1124
|
+
}
|
|
1125
|
+
/** `realtime` rooms: each player's latest input, by player id, as of the last snapshot. */
|
|
1126
|
+
get inputs() {
|
|
1127
|
+
return this.snap_.players;
|
|
1128
|
+
}
|
|
1129
|
+
/** `realtime` rooms: the last snapshot's tick number. Grows by tickHz every second. */
|
|
1130
|
+
/** `script` rooms: this player's private state, which only this player receives (a hand of cards, a secret goal). */
|
|
1131
|
+
get private() {
|
|
1132
|
+
return this.private_;
|
|
1133
|
+
}
|
|
1134
|
+
get tick() {
|
|
1135
|
+
return this.snap_.tick;
|
|
1136
|
+
}
|
|
1137
|
+
on(event, listener) {
|
|
1138
|
+
const off = super.on(event, listener);
|
|
1139
|
+
if (event === "state" || event === "change") {
|
|
1140
|
+
queueMicrotask(() => {
|
|
1141
|
+
if (this.status_ === "closed") return;
|
|
1142
|
+
if (event === "state") {
|
|
1143
|
+
listener(this.view, { ops: [], by: null, reset: true });
|
|
1144
|
+
} else {
|
|
1145
|
+
listener();
|
|
1146
|
+
}
|
|
1147
|
+
});
|
|
1148
|
+
}
|
|
1149
|
+
return off;
|
|
1150
|
+
}
|
|
1151
|
+
// ---------------------------------------------------------------- writes
|
|
1152
|
+
/** Puts `value` at `path`. In a dotted path, `me` means this player: `room.set("players.me.x", 120)`. */
|
|
1153
|
+
set(path, value) {
|
|
1154
|
+
this.write("set", { op: "set", path: toPath(path, this.me_.id, "set"), value: toJson(value, "set") });
|
|
1155
|
+
}
|
|
1156
|
+
/** Copies the keys of `value` into the object at `path`, leaving its other keys alone. "" merges into the root. */
|
|
1157
|
+
merge(path, value) {
|
|
1158
|
+
const json = toJson(value, "merge");
|
|
1159
|
+
if (!isObject4(json)) {
|
|
1160
|
+
throw new CotchuError(
|
|
1161
|
+
"bad_message",
|
|
1162
|
+
"merge() needs a plain object such as { x: 1 }; use set() for other values."
|
|
1163
|
+
);
|
|
1164
|
+
}
|
|
1165
|
+
this.write("merge", { op: "merge", path: toPath(path, this.me_.id, "merge", true), value: json });
|
|
1166
|
+
}
|
|
1167
|
+
/** Removes whatever is at `path`. */
|
|
1168
|
+
delete(path) {
|
|
1169
|
+
this.write("delete", { op: "delete", path: toPath(path, this.me_.id, "delete") });
|
|
1170
|
+
}
|
|
1171
|
+
/** Sends `data` to everyone else in the room, or to one player. Not saved in the state. */
|
|
1172
|
+
send(data, to) {
|
|
1173
|
+
const message = { t: "msg", data: toJson(data, "send") };
|
|
1174
|
+
if (to !== void 0) message.to = typeof to === "string" ? to : to.id;
|
|
1175
|
+
this.enqueue("send", message);
|
|
1176
|
+
}
|
|
1177
|
+
/**
|
|
1178
|
+
* `turns` rooms: plays a move on this player's turn. The room records it in
|
|
1179
|
+
* room.moves and passes the turn. Throws if it isn't this player's turn or
|
|
1180
|
+
* the move doesn't match the room's moveSchema.
|
|
1181
|
+
*/
|
|
1182
|
+
move(data) {
|
|
1183
|
+
this.ensureOpen("move");
|
|
1184
|
+
this.ensureType("move", "turns");
|
|
1185
|
+
const json = toJson(data, "move");
|
|
1186
|
+
if (!this.isMyTurn) {
|
|
1187
|
+
const holder = this.turn_.player === null ? null : this.players_.get(this.turn_.player);
|
|
1188
|
+
throw new CotchuError(
|
|
1189
|
+
"not_your_turn",
|
|
1190
|
+
holder ? `It's ${holder.name}'s turn, not yours; wait for the turn event, or check room.isMyTurn before calling move().` : "It isn't your turn; wait for the turn event, or check room.isMyTurn before calling move()."
|
|
1191
|
+
);
|
|
1192
|
+
}
|
|
1193
|
+
const schema = this.config_.moveSchema;
|
|
1194
|
+
const problem = schema ? moveProblem(schema, json) : null;
|
|
1195
|
+
if (problem) throw new CotchuError("bad_move", `${problem}; send a move that matches the room's moveSchema.`);
|
|
1196
|
+
this.enqueue("move", { t: "move", id: this.nextId++, data: json });
|
|
1197
|
+
}
|
|
1198
|
+
/**
|
|
1199
|
+
* `script` rooms: sends what this player did to the room's script (its
|
|
1200
|
+
* onAction). Resolves once the script accepts it; rejects with the script's
|
|
1201
|
+
* own reason (code `action_rejected`) if it turns it down.
|
|
1202
|
+
*/
|
|
1203
|
+
act(data) {
|
|
1204
|
+
this.ensureOpen("act");
|
|
1205
|
+
this.ensureType("act", "script");
|
|
1206
|
+
const id = this.nextId++;
|
|
1207
|
+
const message = { t: "act", id, data: toJson(data, "act") };
|
|
1208
|
+
return new Promise((resolve, reject) => {
|
|
1209
|
+
this.acts.set(id, { resolve, reject });
|
|
1210
|
+
try {
|
|
1211
|
+
this.enqueue("act", message);
|
|
1212
|
+
} catch (error) {
|
|
1213
|
+
this.acts.delete(id);
|
|
1214
|
+
reject(error);
|
|
1215
|
+
}
|
|
1216
|
+
});
|
|
1217
|
+
}
|
|
1218
|
+
/** `realtime` and `script` rooms: sets this player's latest input. Unsent inputs are replaced, not queued. */
|
|
1219
|
+
input(data) {
|
|
1220
|
+
this.ensureOpen("input");
|
|
1221
|
+
if (this.config_.type !== "script") this.ensureType("input", "realtime");
|
|
1222
|
+
const json = toJson(data, "input");
|
|
1223
|
+
if (utf8ByteLength(JSON.stringify(json)) > MAX_INPUT_BYTES) {
|
|
1224
|
+
throw new CotchuError(
|
|
1225
|
+
"too_large",
|
|
1226
|
+
`input() got more than ${MAX_INPUT_BYTES / 1024} KB; send only what changes each frame, such as keys held or a direction.`
|
|
1227
|
+
);
|
|
1228
|
+
}
|
|
1229
|
+
this.enqueue("input", { t: "input", data: json });
|
|
1230
|
+
}
|
|
1231
|
+
ensureType(call, type) {
|
|
1232
|
+
if (this.config_.type === type) return;
|
|
1233
|
+
throw new CotchuError(
|
|
1234
|
+
"wrong_room_type",
|
|
1235
|
+
type === "script" ? `${call}() only works in script rooms and this is a ${this.config_.type} room; join with a deployed script, like cotchu.join(name, { key, script: "cards" }).` : `${call}() only works in ${type} rooms and this is a ${this.config_.type} room; create the room with type "${type}", or use set() here.`
|
|
1236
|
+
);
|
|
1237
|
+
}
|
|
1238
|
+
/** Leaves the room for good and frees the seat at once. */
|
|
1239
|
+
leave() {
|
|
1240
|
+
if (this.status_ === "closed") return;
|
|
1241
|
+
this.connection.seats?.forget();
|
|
1242
|
+
this.outbox.flush();
|
|
1243
|
+
const ws = this.ws;
|
|
1244
|
+
this.shutDown();
|
|
1245
|
+
if (ws) {
|
|
1246
|
+
try {
|
|
1247
|
+
ws.close(1e3, LEAVE_REASON);
|
|
1248
|
+
} catch {
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
ensureOpen(call) {
|
|
1253
|
+
if (this.status_ === "closed") {
|
|
1254
|
+
throw new CotchuError(
|
|
1255
|
+
"room_closed",
|
|
1256
|
+
`${call}() can't run because this room is closed; call cotchu.join() again.`
|
|
1257
|
+
);
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
write(call, op) {
|
|
1261
|
+
this.ensureOpen(call);
|
|
1262
|
+
if (this.config_.type === "script") {
|
|
1263
|
+
throw new CotchuError(
|
|
1264
|
+
"wrong_room_type",
|
|
1265
|
+
`${call}() doesn't work in script rooms, where the script owns the state; send what the player did with room.act().`
|
|
1266
|
+
);
|
|
1267
|
+
}
|
|
1268
|
+
const target = this.view === this.confirmed ? structuredClone(this.confirmed) : this.view;
|
|
1269
|
+
const result = applyOps(target, [op]);
|
|
1270
|
+
if (!result.ok) throw new CotchuError("bad_path", result.message.replace(/^patch\.ops\[0\] /, `${call}() `));
|
|
1271
|
+
if (!this.outbox.addOps([op])) {
|
|
1272
|
+
result.undo();
|
|
1273
|
+
throw this.backlogError(call);
|
|
1274
|
+
}
|
|
1275
|
+
this.view = target;
|
|
1276
|
+
this.emit("state", this.view, { ops: [op], by: this.me_.id, reset: false });
|
|
1277
|
+
this.emit("change");
|
|
1278
|
+
}
|
|
1279
|
+
enqueue(call, message) {
|
|
1280
|
+
this.ensureOpen(call);
|
|
1281
|
+
if (!this.outbox.add(message)) throw this.backlogError(call);
|
|
1282
|
+
}
|
|
1283
|
+
backlogError(call) {
|
|
1284
|
+
return new CotchuError(
|
|
1285
|
+
"rate_limited",
|
|
1286
|
+
`${call}() was dropped because too many messages are waiting to send; send less often, or wait for status "connected".`
|
|
1287
|
+
);
|
|
1288
|
+
}
|
|
1289
|
+
/** Sends one queued message if connected. Returns false to keep it queued. */
|
|
1290
|
+
transmit(message) {
|
|
1291
|
+
const ws = this.ws;
|
|
1292
|
+
if (!ws || !this.welcomed || ws.readyState !== OPEN) return false;
|
|
1293
|
+
try {
|
|
1294
|
+
ws.send(JSON.stringify(message));
|
|
1295
|
+
} catch {
|
|
1296
|
+
return false;
|
|
1297
|
+
}
|
|
1298
|
+
if (message.t === "patch" && message.id !== void 0) this.inflight.push({ id: message.id, ops: message.ops });
|
|
1299
|
+
return true;
|
|
1300
|
+
}
|
|
1301
|
+
// ------------------------------------------------------------ connection
|
|
1302
|
+
connect() {
|
|
1303
|
+
const { url, hello, WebSocket: Socket } = this.connection;
|
|
1304
|
+
let ws;
|
|
1305
|
+
try {
|
|
1306
|
+
ws = new Socket(url);
|
|
1307
|
+
} catch {
|
|
1308
|
+
return this.fail(
|
|
1309
|
+
new CotchuError("unreachable", `Couldn't open a WebSocket to ${url}; check the url option if you passed one.`)
|
|
1310
|
+
);
|
|
1311
|
+
}
|
|
1312
|
+
this.ws = ws;
|
|
1313
|
+
this.welcomed = false;
|
|
1314
|
+
ws.onopen = () => {
|
|
1315
|
+
if (this.ws === ws) ws.send(JSON.stringify(this.resume ? { ...hello, resume: this.resume } : hello));
|
|
1316
|
+
};
|
|
1317
|
+
ws.onmessage = (event) => {
|
|
1318
|
+
if (this.ws === ws) this.receive(typeof event.data === "string" ? event.data : "");
|
|
1319
|
+
};
|
|
1320
|
+
ws.onclose = (event) => {
|
|
1321
|
+
if (this.ws === ws) this.dropped(event.code);
|
|
1322
|
+
};
|
|
1323
|
+
ws.onerror = () => {
|
|
1324
|
+
};
|
|
1325
|
+
this.helloTimer = setTimeout(() => {
|
|
1326
|
+
if (this.ws === ws && !this.welcomed) this.abandon(ws);
|
|
1327
|
+
}, HELLO_TIMEOUT_MS);
|
|
1328
|
+
}
|
|
1329
|
+
/** Gives up on a socket that has gone quiet, without waiting for TCP to notice. */
|
|
1330
|
+
abandon(ws) {
|
|
1331
|
+
ws.onopen = ws.onmessage = ws.onclose = null;
|
|
1332
|
+
try {
|
|
1333
|
+
ws.close();
|
|
1334
|
+
} catch {
|
|
1335
|
+
}
|
|
1336
|
+
if (this.ws === ws) this.dropped(1006);
|
|
1337
|
+
}
|
|
1338
|
+
dropped(code) {
|
|
1339
|
+
this.stopTimers();
|
|
1340
|
+
this.ws = null;
|
|
1341
|
+
this.welcomed = false;
|
|
1342
|
+
if (this.status_ === "closed") return;
|
|
1343
|
+
if (code === CLOSE_CODES.FATAL) {
|
|
1344
|
+
return this.fail(new CotchuError("internal", "The room closed this connection; call cotchu.join() again."));
|
|
1345
|
+
}
|
|
1346
|
+
if (code === CLOSE_CODES.REPLACED) return this.fail(new CotchuError("replaced"));
|
|
1347
|
+
this.attempt++;
|
|
1348
|
+
if (this.settle && this.attempt >= JOIN_ATTEMPTS) {
|
|
1349
|
+
return this.fail(
|
|
1350
|
+
this.refusal ?? new CotchuError(
|
|
1351
|
+
"unreachable",
|
|
1352
|
+
`Couldn't reach a Cotchu room at ${this.connection.url}; check the network (and the url option, if you passed one), then call cotchu.join() again.`
|
|
1353
|
+
)
|
|
1354
|
+
);
|
|
1355
|
+
}
|
|
1356
|
+
if (!this.settle) this.setStatus("reconnecting");
|
|
1357
|
+
const delay = Math.min(BACKOFF_MAX_MS, BACKOFF_BASE_MS * 2 ** (this.attempt - 1)) * (0.5 + Math.random() / 2);
|
|
1358
|
+
this.reconnectTimer = setTimeout(() => {
|
|
1359
|
+
this.reconnectTimer = void 0;
|
|
1360
|
+
this.connect();
|
|
1361
|
+
}, delay);
|
|
1362
|
+
}
|
|
1363
|
+
/** Closes for good: rejects a pending join, or reports the error. */
|
|
1364
|
+
fail(error) {
|
|
1365
|
+
if (this.status_ === "closed") return;
|
|
1366
|
+
const ws = this.ws;
|
|
1367
|
+
this.shutDown();
|
|
1368
|
+
if (ws) {
|
|
1369
|
+
ws.onopen = ws.onmessage = ws.onclose = null;
|
|
1370
|
+
try {
|
|
1371
|
+
ws.close();
|
|
1372
|
+
} catch {
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
const settle = this.settle;
|
|
1376
|
+
this.settle = void 0;
|
|
1377
|
+
if (settle) settle.reject(error);
|
|
1378
|
+
else this.report(error);
|
|
1379
|
+
}
|
|
1380
|
+
shutDown() {
|
|
1381
|
+
this.settleActs(
|
|
1382
|
+
new CotchuError("room_closed", "The room closed before it answered this action; join again to keep playing.")
|
|
1383
|
+
);
|
|
1384
|
+
this.connection.seats?.forget();
|
|
1385
|
+
this.stopTimers();
|
|
1386
|
+
this.outbox.clear();
|
|
1387
|
+
this.ws = null;
|
|
1388
|
+
this.welcomed = false;
|
|
1389
|
+
this.setStatus("closed");
|
|
1390
|
+
}
|
|
1391
|
+
stopTimers() {
|
|
1392
|
+
if (this.helloTimer !== void 0) clearTimeout(this.helloTimer);
|
|
1393
|
+
if (this.reconnectTimer !== void 0) clearTimeout(this.reconnectTimer);
|
|
1394
|
+
if (this.heartbeat !== void 0) clearInterval(this.heartbeat);
|
|
1395
|
+
this.helloTimer = this.reconnectTimer = this.heartbeat = void 0;
|
|
1396
|
+
}
|
|
1397
|
+
startHeartbeat() {
|
|
1398
|
+
this.lastSeen = Date.now();
|
|
1399
|
+
this.heartbeat = setInterval(() => {
|
|
1400
|
+
const ws = this.ws;
|
|
1401
|
+
if (!ws) return;
|
|
1402
|
+
if (Date.now() - this.lastSeen > DEAD_AFTER_MS) return this.abandon(ws);
|
|
1403
|
+
try {
|
|
1404
|
+
ws.send(PING_FRAME);
|
|
1405
|
+
} catch {
|
|
1406
|
+
}
|
|
1407
|
+
}, HEARTBEAT_MS);
|
|
1408
|
+
}
|
|
1409
|
+
setStatus(status) {
|
|
1410
|
+
if (this.status_ === status) return;
|
|
1411
|
+
this.status_ = status;
|
|
1412
|
+
this.emit("status", status);
|
|
1413
|
+
this.emit("change");
|
|
1414
|
+
}
|
|
1415
|
+
report(error) {
|
|
1416
|
+
if (!this.emit("error", error)) console.warn(`[cotchu] ${error.code}: ${error.message}`);
|
|
1417
|
+
}
|
|
1418
|
+
// -------------------------------------------------------------- receiving
|
|
1419
|
+
receive(text) {
|
|
1420
|
+
this.lastSeen = Date.now();
|
|
1421
|
+
const parsed = parseServerMessage(text);
|
|
1422
|
+
if (!parsed.ok) return this.report(new CotchuError(parsed.error.code, parsed.error.message));
|
|
1423
|
+
const message = parsed.message;
|
|
1424
|
+
switch (message.t) {
|
|
1425
|
+
case "welcome":
|
|
1426
|
+
return this.welcome(message);
|
|
1427
|
+
case "patch":
|
|
1428
|
+
return this.patched(message);
|
|
1429
|
+
case "err":
|
|
1430
|
+
return this.errored(message);
|
|
1431
|
+
case "join":
|
|
1432
|
+
this.players_.set(message.player.id, message.player);
|
|
1433
|
+
this.emit("join", message.player);
|
|
1434
|
+
this.emit("change");
|
|
1435
|
+
return;
|
|
1436
|
+
case "leave":
|
|
1437
|
+
this.players_.delete(message.player.id);
|
|
1438
|
+
if (Object.hasOwn(this.snap_.players, message.player.id)) {
|
|
1439
|
+
const { [message.player.id]: _gone, ...rest } = this.snap_.players;
|
|
1440
|
+
this.snap_ = { tick: this.snap_.tick, players: rest };
|
|
1441
|
+
}
|
|
1442
|
+
this.emit("leave", message.player);
|
|
1443
|
+
this.emit("change");
|
|
1444
|
+
return;
|
|
1445
|
+
case "msg":
|
|
1446
|
+
this.emit("message", message.data, this.playerFor(message.from));
|
|
1447
|
+
return;
|
|
1448
|
+
case "turn":
|
|
1449
|
+
this.turn_ = message.deadline === void 0 ? { player: message.player } : { player: message.player, deadline: message.deadline };
|
|
1450
|
+
this.emit("turn", message.player === null ? null : this.playerFor(message.player), message.deadline ?? null);
|
|
1451
|
+
this.emit("change");
|
|
1452
|
+
return;
|
|
1453
|
+
case "move":
|
|
1454
|
+
return this.moved(message);
|
|
1455
|
+
case "snap":
|
|
1456
|
+
this.snap_ = { tick: message.tick, players: message.players };
|
|
1457
|
+
this.emit("snap", message.players, message.tick);
|
|
1458
|
+
this.emit("change");
|
|
1459
|
+
return;
|
|
1460
|
+
case "ack":
|
|
1461
|
+
this.acts.get(message.id)?.resolve();
|
|
1462
|
+
this.acts.delete(message.id);
|
|
1463
|
+
return;
|
|
1464
|
+
case "priv": {
|
|
1465
|
+
const result = applyOps(this.private_, message.ops);
|
|
1466
|
+
if (!result.ok) {
|
|
1467
|
+
this.report(
|
|
1468
|
+
new CotchuError("internal", "This copy of your private state fell out of sync; reconnecting to fix it.")
|
|
1469
|
+
);
|
|
1470
|
+
if (this.ws) this.abandon(this.ws);
|
|
1471
|
+
return;
|
|
1472
|
+
}
|
|
1473
|
+
this.emit("change");
|
|
1474
|
+
return;
|
|
1475
|
+
}
|
|
1476
|
+
case "event":
|
|
1477
|
+
this.emit("event", message.name, message.data);
|
|
1478
|
+
return;
|
|
1479
|
+
case "sync":
|
|
1480
|
+
this.confirmed = message.state;
|
|
1481
|
+
this.private_ = message.private;
|
|
1482
|
+
this.inflight = [];
|
|
1483
|
+
this.rebuild();
|
|
1484
|
+
this.emit("state", this.view, { ops: [], by: null, reset: true });
|
|
1485
|
+
this.emit("change");
|
|
1486
|
+
return;
|
|
1487
|
+
default:
|
|
1488
|
+
return;
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
playerFor(id) {
|
|
1492
|
+
return this.players_.get(id) ?? { id, name: id };
|
|
1493
|
+
}
|
|
1494
|
+
moved(message) {
|
|
1495
|
+
if (message.n !== this.moves_.length) {
|
|
1496
|
+
this.report(
|
|
1497
|
+
new CotchuError("internal", "This copy of the room's moves fell out of sync; reconnecting to fix it.")
|
|
1498
|
+
);
|
|
1499
|
+
if (this.ws) this.abandon(this.ws);
|
|
1500
|
+
return;
|
|
1501
|
+
}
|
|
1502
|
+
this.moves_.push({ by: message.by, data: message.data });
|
|
1503
|
+
this.emit("move", message.data, this.playerFor(message.by), message.n);
|
|
1504
|
+
this.emit("change");
|
|
1505
|
+
}
|
|
1506
|
+
welcome(message) {
|
|
1507
|
+
if (this.helloTimer !== void 0) clearTimeout(this.helloTimer);
|
|
1508
|
+
this.helloTimer = void 0;
|
|
1509
|
+
this.welcomed = true;
|
|
1510
|
+
this.attempt = 0;
|
|
1511
|
+
const previous = new Map(this.players_);
|
|
1512
|
+
this.me_ = message.you;
|
|
1513
|
+
this.config_ = message.config;
|
|
1514
|
+
this.resume = message.resume;
|
|
1515
|
+
this.connection.seats?.watch(() => this.status_ === "closed" ? void 0 : this.resume);
|
|
1516
|
+
this.players_.clear();
|
|
1517
|
+
for (const player of message.players) this.players_.set(player.id, player);
|
|
1518
|
+
this.confirmed = message.state;
|
|
1519
|
+
this.inflight = [];
|
|
1520
|
+
this.turn_ = message.turn ?? { player: null };
|
|
1521
|
+
this.moves_ = message.moves ?? [];
|
|
1522
|
+
this.snap_ = message.snap ?? { tick: 0, players: {} };
|
|
1523
|
+
this.private_ = message.private ?? {};
|
|
1524
|
+
this.settleActs(
|
|
1525
|
+
new CotchuError(
|
|
1526
|
+
"internal",
|
|
1527
|
+
"The connection dropped before the room answered this action; check room.state, and act again if it didn't happen."
|
|
1528
|
+
)
|
|
1529
|
+
);
|
|
1530
|
+
this.rebuild();
|
|
1531
|
+
this.startHeartbeat();
|
|
1532
|
+
this.setStatus("connected");
|
|
1533
|
+
const settle = this.settle;
|
|
1534
|
+
this.settle = void 0;
|
|
1535
|
+
if (settle) {
|
|
1536
|
+
settle.resolve(this);
|
|
1537
|
+
} else {
|
|
1538
|
+
for (const [id, player] of previous) if (!this.players_.has(id)) this.emit("leave", player);
|
|
1539
|
+
for (const [id, player] of this.players_) if (!previous.has(id)) this.emit("join", player);
|
|
1540
|
+
this.emit("state", this.view, { ops: [], by: null, reset: true });
|
|
1541
|
+
this.emit("change");
|
|
1542
|
+
}
|
|
1543
|
+
this.outbox.flush();
|
|
1544
|
+
}
|
|
1545
|
+
patched(message) {
|
|
1546
|
+
const result = applyOps(this.confirmed, message.ops);
|
|
1547
|
+
if (!result.ok) {
|
|
1548
|
+
this.report(new CotchuError("internal", "This copy of the room fell out of sync; reconnecting to fix it."));
|
|
1549
|
+
if (this.ws) this.abandon(this.ws);
|
|
1550
|
+
return;
|
|
1551
|
+
}
|
|
1552
|
+
const own = message.by !== null && message.by === this.me_.id;
|
|
1553
|
+
const confirms = message.id;
|
|
1554
|
+
if (own && confirms !== void 0) {
|
|
1555
|
+
this.inflight = this.inflight.filter((patch) => patch.id > confirms);
|
|
1556
|
+
}
|
|
1557
|
+
this.rebuild();
|
|
1558
|
+
if (!own) {
|
|
1559
|
+
this.emit("state", this.view, { ops: message.ops, by: message.by, reset: false });
|
|
1560
|
+
this.emit("change");
|
|
1561
|
+
}
|
|
1562
|
+
}
|
|
1563
|
+
settleActs(error) {
|
|
1564
|
+
for (const [, act] of this.acts) act.reject(error);
|
|
1565
|
+
this.acts.clear();
|
|
1566
|
+
}
|
|
1567
|
+
errored(message) {
|
|
1568
|
+
const error = new CotchuError(message.code, message.message);
|
|
1569
|
+
const rejected = message.id;
|
|
1570
|
+
const act = rejected === void 0 ? void 0 : this.acts.get(rejected);
|
|
1571
|
+
if (act && rejected !== void 0) {
|
|
1572
|
+
this.acts.delete(rejected);
|
|
1573
|
+
act.reject(error);
|
|
1574
|
+
return;
|
|
1575
|
+
}
|
|
1576
|
+
if (rejected !== void 0) {
|
|
1577
|
+
const before = this.inflight.length;
|
|
1578
|
+
this.inflight = this.inflight.filter((patch) => patch.id !== rejected);
|
|
1579
|
+
if (this.inflight.length !== before) {
|
|
1580
|
+
this.rebuild();
|
|
1581
|
+
this.emit("state", this.view, { ops: [], by: null, reset: true });
|
|
1582
|
+
this.emit("change");
|
|
1583
|
+
}
|
|
1584
|
+
}
|
|
1585
|
+
if (error.fatal) return this.fail(error);
|
|
1586
|
+
if (this.settle) this.refusal = error;
|
|
1587
|
+
this.report(error);
|
|
1588
|
+
}
|
|
1589
|
+
/** view = confirmed + every write the room hasn't confirmed yet, in order. */
|
|
1590
|
+
rebuild() {
|
|
1591
|
+
const pending = [...this.inflight.flatMap((patch) => patch.ops), ...this.outbox.queuedOps()];
|
|
1592
|
+
if (pending.length === 0) {
|
|
1593
|
+
this.view = this.confirmed;
|
|
1594
|
+
return;
|
|
1595
|
+
}
|
|
1596
|
+
const view = structuredClone(this.confirmed);
|
|
1597
|
+
for (const op of pending) applyOps(view, [op]);
|
|
1598
|
+
this.view = view;
|
|
1599
|
+
}
|
|
1600
|
+
};
|
|
1601
|
+
|
|
1602
|
+
// src/seat-memory.ts
|
|
1603
|
+
var SeatMemory = class _SeatMemory {
|
|
1604
|
+
constructor(key, browser) {
|
|
1605
|
+
this.key = key;
|
|
1606
|
+
this.browser = browser;
|
|
1607
|
+
}
|
|
1608
|
+
key;
|
|
1609
|
+
browser;
|
|
1610
|
+
token;
|
|
1611
|
+
onPageHide = () => {
|
|
1612
|
+
const token = this.token?.();
|
|
1613
|
+
if (token) this.write(token);
|
|
1614
|
+
};
|
|
1615
|
+
/** Null outside browsers, or when storage is blocked (private mode, sandboxed frames). */
|
|
1616
|
+
static for(project, room) {
|
|
1617
|
+
const browser = globalThis;
|
|
1618
|
+
try {
|
|
1619
|
+
if (!browser.sessionStorage || !browser.addEventListener || !browser.removeEventListener) return null;
|
|
1620
|
+
void browser.sessionStorage.length;
|
|
1621
|
+
} catch {
|
|
1622
|
+
return null;
|
|
1623
|
+
}
|
|
1624
|
+
return new _SeatMemory(`cotchu:seat:${project}/${room}`, browser);
|
|
1625
|
+
}
|
|
1626
|
+
/** Returns the remembered token, if any, and forgets it. */
|
|
1627
|
+
take() {
|
|
1628
|
+
try {
|
|
1629
|
+
const token = this.browser.sessionStorage.getItem(this.key) ?? void 0;
|
|
1630
|
+
this.browser.sessionStorage.removeItem(this.key);
|
|
1631
|
+
return token;
|
|
1632
|
+
} catch {
|
|
1633
|
+
return void 0;
|
|
1634
|
+
}
|
|
1635
|
+
}
|
|
1636
|
+
/** From now on, saves the current token whenever the page is hidden or unloaded. */
|
|
1637
|
+
watch(token) {
|
|
1638
|
+
this.token = token;
|
|
1639
|
+
this.browser.addEventListener("pagehide", this.onPageHide);
|
|
1640
|
+
}
|
|
1641
|
+
/** Stops saving and forgets the token: the player left for good. */
|
|
1642
|
+
forget() {
|
|
1643
|
+
this.token = void 0;
|
|
1644
|
+
this.browser.removeEventListener("pagehide", this.onPageHide);
|
|
1645
|
+
try {
|
|
1646
|
+
this.browser.sessionStorage.removeItem(this.key);
|
|
1647
|
+
} catch {
|
|
1648
|
+
}
|
|
1649
|
+
}
|
|
1650
|
+
write(token) {
|
|
1651
|
+
try {
|
|
1652
|
+
this.browser.sessionStorage.setItem(this.key, token);
|
|
1653
|
+
} catch {
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1656
|
+
};
|
|
1657
|
+
|
|
1658
|
+
// src/index.ts
|
|
1659
|
+
var SDK_VERSION = "0.1.0";
|
|
1660
|
+
function fail(code, message) {
|
|
1661
|
+
throw new CotchuError(code, message);
|
|
1662
|
+
}
|
|
1663
|
+
function roomsUrl(raw) {
|
|
1664
|
+
let url;
|
|
1665
|
+
try {
|
|
1666
|
+
url = new URL(raw.replace(/^http(s?):/, "ws$1:"));
|
|
1667
|
+
} catch {
|
|
1668
|
+
fail(
|
|
1669
|
+
"unreachable",
|
|
1670
|
+
`The url option ${JSON.stringify(raw)} isn't a valid address; pass one like wss://rooms.example.com.`
|
|
1671
|
+
);
|
|
1672
|
+
}
|
|
1673
|
+
if (url.protocol !== "ws:" && url.protocol !== "wss:") {
|
|
1674
|
+
fail("unreachable", `The url option must start with wss:// or ws://, not ${url.protocol}//; fix the url.`);
|
|
1675
|
+
}
|
|
1676
|
+
return url.origin.replace(/^http/, "ws") + url.pathname.replace(/\/+$/, "");
|
|
1677
|
+
}
|
|
1678
|
+
function prepare(room, options) {
|
|
1679
|
+
if (typeof options !== "object" || options === null) {
|
|
1680
|
+
fail("bad_key", 'cotchu.join() needs options with your key, like cotchu.join("lobby", { key: "pk_live_\u2026" }).');
|
|
1681
|
+
}
|
|
1682
|
+
const { key } = options;
|
|
1683
|
+
if (typeof key === "string" && key.startsWith("sk_")) {
|
|
1684
|
+
fail("bad_key", "That's a secret key, which must never be in game code; pass your project's pk_live_ key instead.");
|
|
1685
|
+
}
|
|
1686
|
+
const project = typeof key === "string" ? projectOfKey(key) : null;
|
|
1687
|
+
if (project === null) {
|
|
1688
|
+
fail(
|
|
1689
|
+
"bad_key",
|
|
1690
|
+
"That isn't a Cotchu publishable key; pass your project's key, which looks like pk_live_<project>_<secret>, as the key option."
|
|
1691
|
+
);
|
|
1692
|
+
}
|
|
1693
|
+
if (!isRoomName(room)) {
|
|
1694
|
+
fail(
|
|
1695
|
+
"bad_room",
|
|
1696
|
+
`Room name ${JSON.stringify(room)} isn't valid; use letters, digits, '.', '_' and '-', up to 64 characters, starting with a letter or digit.`
|
|
1697
|
+
);
|
|
1698
|
+
}
|
|
1699
|
+
const region = options.region ?? "auto";
|
|
1700
|
+
if (region !== "auto" && !isRegion(region))
|
|
1701
|
+
fail("bad_region", `Region ${JSON.stringify(region)} isn't valid; use "auto".`);
|
|
1702
|
+
const Socket = options.WebSocket ?? globalThis.WebSocket;
|
|
1703
|
+
if (!Socket) {
|
|
1704
|
+
fail("unreachable", "This runtime has no WebSocket; use Node 22 or newer, or pass one with the WebSocket option.");
|
|
1705
|
+
}
|
|
1706
|
+
const roomOptions = {};
|
|
1707
|
+
if (options.type !== void 0) roomOptions.type = options.type;
|
|
1708
|
+
if (options.seats !== void 0) roomOptions.seats = options.seats;
|
|
1709
|
+
if (options.writable !== void 0) roomOptions.writable = options.writable;
|
|
1710
|
+
if (options.turnMs !== void 0) roomOptions.turnMs = options.turnMs;
|
|
1711
|
+
if (options.tickHz !== void 0) roomOptions.tickHz = options.tickHz;
|
|
1712
|
+
if (options.script !== void 0) roomOptions.script = options.script;
|
|
1713
|
+
if (options.moveSchema !== void 0) roomOptions.moveSchema = options.moveSchema;
|
|
1714
|
+
const hello = { t: "hello", v: PROTOCOL_VERSION, key, sdk: `cotchu-js/${SDK_VERSION}` };
|
|
1715
|
+
if (options.name !== void 0) hello.name = options.name;
|
|
1716
|
+
if (Object.keys(roomOptions).length > 0) hello.room = roomOptions;
|
|
1717
|
+
const checked = parseClientMessage(JSON.stringify(hello));
|
|
1718
|
+
if (!checked.ok) {
|
|
1719
|
+
fail(
|
|
1720
|
+
checked.error.code,
|
|
1721
|
+
checked.error.message.replace(/^hello\.room\./, "cotchu.join() option ").replace(/^hello\./, "cotchu.join() option ")
|
|
1722
|
+
);
|
|
1723
|
+
}
|
|
1724
|
+
const query = region === "auto" ? "" : `?region=${region}`;
|
|
1725
|
+
return {
|
|
1726
|
+
url: `${roomsUrl(options.url ?? DEFAULT_ROOMS_URL)}${ROOMS_PATH_PREFIX}${project}/${room}${query}`,
|
|
1727
|
+
hello: checked.message,
|
|
1728
|
+
WebSocket: Socket,
|
|
1729
|
+
seats: options.rememberSeat === false ? null : SeatMemory.for(project, room)
|
|
1730
|
+
};
|
|
1731
|
+
}
|
|
1732
|
+
function join(room, options) {
|
|
1733
|
+
let connection;
|
|
1734
|
+
try {
|
|
1735
|
+
connection = prepare(room, options);
|
|
1736
|
+
} catch (error) {
|
|
1737
|
+
return Promise.reject(error);
|
|
1738
|
+
}
|
|
1739
|
+
return new Room(room, connection).open();
|
|
1740
|
+
}
|
|
1741
|
+
var cotchu = { join, version: SDK_VERSION };
|
|
1742
|
+
export {
|
|
1743
|
+
CotchuError,
|
|
1744
|
+
Room,
|
|
1745
|
+
SDK_VERSION,
|
|
1746
|
+
cotchu,
|
|
1747
|
+
join
|
|
1748
|
+
};
|
|
1749
|
+
//# sourceMappingURL=index.js.map
|