@vite-hub/realtime 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +71 -12
  2. package/dist/agent.d.ts +2 -0
  3. package/dist/agent.js +2 -0
  4. package/dist/bus-Bi-Ec414.js +476 -0
  5. package/dist/bus-protocol-wXkXW28q.d.ts +66 -0
  6. package/dist/bus.d.ts +85 -0
  7. package/dist/bus.js +2 -0
  8. package/dist/client/browser.js +53 -0
  9. package/dist/client.d.ts +25 -4
  10. package/dist/client.js +66 -8
  11. package/dist/conflict-Bg8vCisd.js +63 -0
  12. package/dist/{document-CtY6umWY.d.ts → document-DPaywuCO.d.ts} +2 -2
  13. package/dist/{document-BFaqcCAL.js → document-DjBrcgpY.js} +22 -10
  14. package/dist/durability.d.ts +10 -0
  15. package/dist/durability.js +46 -0
  16. package/dist/{layout-Br1aOL7o.js → editor-BM5-vHqf.js} +30 -36
  17. package/dist/error-diagnostics-B_66irmt.js +141 -0
  18. package/dist/index.d.ts +9 -4
  19. package/dist/index.js +3 -7
  20. package/dist/internal/runtime/unavailable.d.ts +5 -0
  21. package/dist/internal/runtime/unavailable.js +8 -0
  22. package/dist/keepalive-BCs-uXp4.js +33 -0
  23. package/dist/layout-DNaxppTZ.js +34 -0
  24. package/dist/{layout-WNWejwOY.d.ts → layout-fyQnhwCg.d.ts} +1 -1
  25. package/dist/{protocol-9ZDLEcSS.js → object-CzKyK0hX.js} +57 -58
  26. package/dist/presence-Tuy1y_l9.js +53 -0
  27. package/dist/request-BUwa359H.d.ts +48 -0
  28. package/dist/request-CWaHqW3R.js +192 -0
  29. package/dist/server.d.ts +64 -28
  30. package/dist/server.js +1002 -379
  31. package/dist/{types-Bw6-42Se.d.ts → types-1DVVG5ro.d.ts} +118 -14
  32. package/dist/vite.d.ts +109 -12
  33. package/dist/vite.js +469 -138
  34. package/dist/vue.d.ts +8 -5
  35. package/dist/vue.js +25 -11
  36. package/package.json +71 -19
  37. package/dist/application-path-CJblgbWK.js +0 -6
  38. package/dist/conflict-rguoaHlE.js +0 -34
  39. package/dist/durable-key-tnSw58ZK.js +0 -8
  40. package/dist/error-diagnostics-Cvm6vRXQ.js +0 -73
package/dist/server.js CHANGED
@@ -1,26 +1,32 @@
1
- import { c as realtimeForbiddenWriteCloseCode, d as realtimeSourceChangedCode, f as realtimeSyncPendingCode, g as isPlainObject, i as encodeWorkspaceChange, l as realtimeReadOnlyCode, m as createRealtimeIdentity, n as decodeWorkspaceChangePayload, r as encodeRealtimeControl, s as readAwarenessClientIds, u as realtimeResetCloseCode } from "./protocol-9ZDLEcSS.js";
2
- import { t as realtimeErrorDiagnostics } from "./error-diagnostics-Cvm6vRXQ.js";
3
- import { n as isRealtimeDocumentConflict, t as RealtimeDocumentConflict } from "./conflict-rguoaHlE.js";
4
- import { a as realtimeMarkdownEditor, n as realtimeDocumentLayout, t as readRealtimeStatus } from "./layout-Br1aOL7o.js";
5
- import { a as readRealtimeYDoc, c as realtimeStatusFingerprint, i as keepRealtimeFinalNewline, l as writeRealtimeStatus, n as createRealtimeYDoc, o as realtimeCodecReadsBack, r as diffRealtimeYDoc, s as realtimeJsonEqual, t as containsRealtimeState } from "./document-BFaqcCAL.js";
6
- import { t as realtimeDurableObjectKey } from "./durable-key-tnSw58ZK.js";
1
+ import { a as internalRequestHeader, c as localRequesters, d as routePrefix, f as toDurableRequestReply, i as durableRoomsInstance, l as requestRealtimeRoom, m as isRealtimeAvailable, n as defaultRequestTimeout, o as isDurableSockets, p as workerDurableObjects, r as defaultRequestWait, s as isRealtimeDurableObjectNamespace, u as roomRequestError } from "./request-CWaHqW3R.js";
2
+ import { t as realtimeErrorDiagnostics } from "./error-diagnostics-B_66irmt.js";
3
+ import { _ as realtimeReadOnlyCode, a as decodeRealtimeRequestFramePayload, b as realtimeSyncPendingCode, c as encodeRealtimeRequestFrame, f as readAwarenessClientIds, g as realtimeKeepalivePong, h as realtimeKeepalivePing, l as encodeWorkspaceChange, m as realtimeInvalidDocumentCode, n as isRecord, o as decodeWorkspaceChangePayload, p as realtimeForbiddenWriteCloseCode, s as encodeRealtimeControl, v as realtimeResetCloseCode, y as realtimeSourceChangedCode } from "./object-CzKyK0hX.js";
4
+ import { n as realtimeDocumentLayout, t as readRealtimeStatus } from "./layout-DNaxppTZ.js";
5
+ import { t as createRealtimeIdentity } from "./presence-Tuy1y_l9.js";
6
+ import { i as assertRealtimeCheckpoint, n as isRealtimeDocumentConflict, r as assertRealtimeAccess, t as RealtimeDocumentConflict } from "./conflict-Bg8vCisd.js";
7
+ import { r as realtimeMarkdownEditor } from "./editor-BM5-vHqf.js";
8
+ import { a as keepRealtimeFinalNewline, c as realtimeJsonEqual, d as writeRealtimeStatus, i as diffRealtimeYDoc, l as realtimeStatusFingerprint, n as containsRealtimeState, o as readRealtimeYDoc, r as createRealtimeYDoc, s as realtimeCodecReadsBack, t as checkRealtimeBody, u as writeRealtimeFields } from "./document-DjBrcgpY.js";
9
+ import { getViteHubErrorShape } from "@vite-hub/runtime";
7
10
  import * as decoding from "lib0/decoding";
8
11
  import * as encoding from "lib0/encoding";
9
12
  import * as awarenessProtocol from "y-protocols/awareness";
10
13
  import * as Y from "yjs";
11
- import { getViteHubErrorShape } from "@vite-hub/runtime";
12
14
  import { Diagnostic } from "nostics";
13
- import { assertAuthOrigin } from "@vite-hub/auth/server";
14
- import { isWorkspaceConflict, normalizeSafeWorkspacePath, resolveWorkspaceStoreTarget, useWorkspace } from "@vite-hub/workspace";
15
- import { H3Event, HTTPError, defineEventHandler, defineWebSocketHandler } from "h3";
15
+ import { assertAuthOrigin } from "@vite-hub/auth/internal/server";
16
+ import { isWorkspaceConflict, normalizeSafeWorkspacePath, resolveWorkspaceStoreTarget, useWorkspaceFiles } from "@vite-hub/workspace/files";
17
+ import { HTTPError, defineEventHandler, defineWebSocketHandler } from "nitro/h3";
16
18
  import * as syncProtocol from "y-protocols/sync";
17
- import { AsyncLocalStorage } from "node:async_hooks";
19
+ import { getStandardContext } from "@vite-hub/runtime/internal/h3";
18
20
  //#region src/awareness.ts
19
21
  const maxRoomAwarenessBytes = 8388608;
20
- function claimAwarenessClientIds(owners, peer, clients) {
22
+ /**
23
+ * Records that `peer` owns `clients`. A client that another peer owns is a conflict, unless `transferable` accepts its
24
+ * owner, such as another server instance that the client left.
25
+ */
26
+ function claimAwarenessClientIds(owners, peer, clients, transferable = () => false) {
21
27
  for (const client of clients) {
22
28
  const owner = owners.get(client);
23
- if (owner && owner !== peer) throw new AwarenessOwnershipConflict();
29
+ if (owner && owner !== peer && !transferable(owner)) throw new AwarenessOwnershipConflict();
24
30
  }
25
31
  const ownedClients = new Set([...owners].filter(([, owner]) => owner === peer).map(([client]) => client));
26
32
  for (const client of clients) ownedClients.add(client);
@@ -44,7 +50,7 @@ var AwarenessOwnershipConflict = class AwarenessOwnershipConflict extends Diagno
44
50
  function bindAwarenessIdentity(update, identity) {
45
51
  return awarenessProtocol.modifyAwarenessUpdate(update, (state) => {
46
52
  if (state === null) return null;
47
- if (!isPlainObject(state)) throw realtimeErrorDiagnostics.REALTIME_INVALID_AWARENESS();
53
+ if (!isRecord(state)) throw realtimeErrorDiagnostics.REALTIME_INVALID_AWARENESS();
48
54
  return {
49
55
  ...state,
50
56
  user: identity
@@ -82,7 +88,7 @@ function compactRealtimeAwareness(awareness) {
82
88
  * Drops the entries of an awareness update that describe clients another peer owns. Stock y-websocket clients send
83
89
  * every awareness change they see, other people's too, so an echo is normal and must not close the connection.
84
90
  */
85
- function dropForeignAwareness(update, owners, peer) {
91
+ function dropForeignAwareness(update, owners, peer, awareness) {
86
92
  const decoder = decoding.createDecoder(update);
87
93
  const length = decoding.readVarUint(decoder);
88
94
  if (length > 1024) throw realtimeErrorDiagnostics.REALTIME_TOO_MANY_AWARENESS_CLIENTS({});
@@ -92,7 +98,7 @@ function dropForeignAwareness(update, owners, peer) {
92
98
  const clock = decoding.readVarUint(decoder);
93
99
  const state = decoding.readVarString(decoder);
94
100
  const owner = owners.get(client);
95
- if (!owner || owner === peer) kept.push([
101
+ if (owner === peer || !owner && state.trim() !== "null" && clock > (awareness.meta.get(client)?.clock ?? -1)) kept.push([
96
102
  client,
97
103
  clock,
98
104
  state
@@ -108,32 +114,75 @@ function dropForeignAwareness(update, owners, peer) {
108
114
  }
109
115
  return encoding.toUint8Array(encoder);
110
116
  }
111
- /** Owns peer claims and commits them only after identity binding and quota checks succeed. */
117
+ /**
118
+ * Owns peer claims and commits them only after identity binding and quota checks succeed. With several server
119
+ * instances, an object that stands for another instance owns the clients of that instance's peers: `apply()` with
120
+ * `remote: true` records them. Ownership handoff is explicit through `claim()`, independent of awareness clocks.
121
+ * Awareness payloads never transfer an existing claim or claim a client from a null echo.
122
+ */
112
123
  function createRealtimeAwarenessOwners(options = {}) {
113
124
  const owners = /* @__PURE__ */ new Map();
114
125
  const peerClients = /* @__PURE__ */ new WeakMap();
126
+ const remoteOwners = /* @__PURE__ */ new WeakSet();
127
+ const transferable = (owner) => remoteOwners.has(owner);
128
+ function disown(client, owner) {
129
+ owners.delete(client);
130
+ peerClients.get(owner)?.delete(client);
131
+ }
115
132
  return {
116
- apply(awareness, peer, input, identity) {
117
- const update = dropForeignAwareness(input, owners, peer);
133
+ /** A WebSocket declares its own client id at connection time; the bus relays that claim to retire the old socket. */
134
+ claim(awareness, peer, client, identity, remote = false) {
135
+ const state = awareness.getStates().get(client);
136
+ if (!remote && identity && state && (!isRecord(state.user) || state.user.id !== identity.id)) return false;
137
+ if (remote) remoteOwners.add(peer);
138
+ const owner = owners.get(client);
139
+ if (owner && owner !== peer) disown(client, owner);
140
+ claimAwarenessClientIds(owners, peer, [client]);
141
+ const clients = peerClients.get(peer) || /* @__PURE__ */ new Set();
142
+ clients.add(client);
143
+ peerClients.set(peer, clients);
144
+ return true;
145
+ },
146
+ apply(awareness, peer, input, identity, remote = false) {
147
+ if (remote) remoteOwners.add(peer);
148
+ const update = dropForeignAwareness(input, owners, peer, awareness);
118
149
  const clients = readAwarenessClientIds(update);
119
150
  if (!clients.length) return [];
120
- const claimed = claimAwarenessClientIds(owners, peer, clients);
151
+ const previous = new Map(clients.flatMap((client) => {
152
+ const owner = owners.get(client);
153
+ return owner && owner !== peer ? [[client, owner]] : [];
154
+ }));
155
+ const claimed = claimAwarenessClientIds(owners, peer, clients, transferable);
121
156
  try {
122
157
  applyRealtimeAwarenessUpdate(awareness, identity ? bindAwarenessIdentity(update, identity) : update, peer, options.maxStateBytes);
158
+ for (const [client, owner] of previous) peerClients.get(owner)?.delete(client);
123
159
  const ownedClients = peerClients.get(peer) || /* @__PURE__ */ new Set();
124
160
  for (const client of clients) ownedClients.add(client);
125
161
  peerClients.set(peer, ownedClients);
126
162
  return clients;
127
163
  } catch (error) {
128
164
  for (const client of claimed) if (owners.get(client) === peer) owners.delete(client);
165
+ for (const [client, owner] of previous) owners.set(client, owner);
129
166
  throw error;
130
167
  }
131
168
  },
169
+ /** Whether a peer of this instance owns the client. */
170
+ ownsLocally(client) {
171
+ const owner = owners.get(client);
172
+ return !!owner && !remoteOwners.has(owner);
173
+ },
132
174
  release(peer) {
133
175
  const clients = [...peerClients.get(peer) || []];
134
176
  peerClients.delete(peer);
135
177
  for (const client of clients) if (owners.get(client) === peer) owners.delete(client);
136
178
  return clients;
179
+ },
180
+ /** Forgets the clients that another instance owned, after their state was removed. */
181
+ releaseRemote(clients) {
182
+ for (const client of clients) {
183
+ const owner = owners.get(client);
184
+ if (owner && remoteOwners.has(owner)) disown(client, owner);
185
+ }
137
186
  }
138
187
  };
139
188
  }
@@ -271,7 +320,7 @@ function workspaceDocument(workspaceName) {
271
320
  kind: "workspace",
272
321
  workspace: workspaceName,
273
322
  async load({ documentId }) {
274
- const current = await readRealtimeWorkspaceDocument(useWorkspace(workspaceName), useWorkspace(workspaceName, { mode: "write" }), documentId);
323
+ const current = await readRealtimeWorkspaceDocument(useWorkspaceFiles(workspaceName), useWorkspaceFiles(workspaceName, { mode: "write" }), documentId);
275
324
  return {
276
325
  body: current.markdown,
277
326
  digest: current.baselineDigest ?? null
@@ -279,14 +328,14 @@ function workspaceDocument(workspaceName) {
279
328
  },
280
329
  async save(context, document, { ifDigest }) {
281
330
  const { documentId } = context;
282
- const workspace = useWorkspace(workspaceName, { mode: "write" });
331
+ const workspace = useWorkspaceFiles(workspaceName, { mode: "write" });
283
332
  if (!(await workspace.capabilities()).conditionalWrites) throw new HTTPError({
284
333
  status: 501,
285
334
  message: "Realtime saves require a Workspace Store with conditional writes."
286
335
  });
287
- if (context.authority === "cloudflare" && (await resolveWorkspaceStoreTarget(workspace))?.provider === "memory") throw new HTTPError({
336
+ if (context.authority !== "memory" && (await resolveWorkspaceStoreTarget(workspace))?.provider === "memory") throw new HTTPError({
288
337
  status: 501,
289
- message: "Durable realtime rooms require a durable Workspace Store."
338
+ message: "Durable and shared realtime rooms require a durable Workspace Store."
290
339
  });
291
340
  try {
292
341
  const current = ifDigest ? await workspace.fs.stat(documentId).catch((error) => {
@@ -313,7 +362,7 @@ function workspaceDocument(workspaceName) {
313
362
  },
314
363
  async checkpoint({ documentId }, { digest, message }) {
315
364
  return await serializeWorkspace(workspaceName, async () => {
316
- const workspace = useWorkspace(workspaceName, { mode: "write" });
365
+ const workspace = useWorkspaceFiles(workspaceName, { mode: "write" });
317
366
  const options = { message: message || `docs: checkpoint ${documentId}` };
318
367
  let snapshot;
319
368
  try {
@@ -400,176 +449,6 @@ function hasNativeCloudflareSql(sql) {
400
449
  return hasCloudflareSqlExecInternal(sql, false);
401
450
  }
402
451
  //#endregion
403
- //#region ../internal/src/runtime/cloudflare-env.ts
404
- let activeEnv;
405
- const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
406
- const runtimeGlobal = globalThis;
407
- const activeEnvStorage = runtimeGlobal[activeEnvStorageKey] ||= new AsyncLocalStorage();
408
- function getActiveCloudflareEnv() {
409
- const scoped = activeEnvStorage.getStore();
410
- if (scoped) return scoped.env;
411
- const host = globalThis;
412
- return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
413
- }
414
- function getActiveCloudflareBinding(name) {
415
- const env = getActiveCloudflareEnv();
416
- return env && Object.hasOwn(env, name) ? env[name] : void 0;
417
- }
418
- //#endregion
419
- //#region ../internal/src/runtime/h3-v1-request.ts
420
- const payloadMethods = /* @__PURE__ */ new Set([
421
- "DELETE",
422
- "PATCH",
423
- "POST",
424
- "PUT"
425
- ]);
426
- const rawBodySymbol = Symbol.for("h3RawBody");
427
- const nodeEventRequests = /* @__PURE__ */ new WeakMap();
428
- /** Return true for an event with an own `node.req` object, such as an H3 1 event. */
429
- function isH3V1Event(input) {
430
- if (!Object.hasOwn(input, "node")) return false;
431
- const node = Reflect.get(input, "node");
432
- return isObjectLike(node) && isObjectLike(Reflect.get(node, "req"));
433
- }
434
- function isObjectLike(value) {
435
- return value !== null && (typeof value === "object" || typeof value === "function");
436
- }
437
- function isWebRequest(value) {
438
- if (!isObjectLike(value)) return false;
439
- const headers = Reflect.get(value, "headers");
440
- return typeof Reflect.get(value, "url") === "string" && typeof Reflect.get(value, "method") === "string" && isObjectLike(headers) && typeof Reflect.get(headers, "get") === "function";
441
- }
442
- function firstHeader(value) {
443
- return Array.isArray(value) ? value[0] : value;
444
- }
445
- function readNodeRequestHeaders(request) {
446
- const headers = new Headers();
447
- for (const [name, value] of Object.entries(request.headers)) if (Array.isArray(value)) for (const item of value) headers.append(name, item);
448
- else if (value !== void 0) headers.set(name, value);
449
- return headers;
450
- }
451
- /** Rebuild the public URL. H3 1 removes the app base path from `url` and keeps it in `originalUrl`. */
452
- function readNodeRequestURL(request) {
453
- const host = firstHeader(request.headers.host) || "localhost";
454
- const encrypted = request.socket?.encrypted || request.connection?.encrypted;
455
- const protocol = firstHeader(request.headers["x-forwarded-proto"]) === "https" || encrypted ? "https" : "http";
456
- const path = (request.originalUrl || request.url || "/").replace(/^[/\\]+/, "/");
457
- return new URL(path, `${protocol}://${host}`);
458
- }
459
- function toBodyStream(value) {
460
- if (value instanceof ReadableStream) return value;
461
- if (value instanceof Uint8Array) return new ReadableStream({ start(controller) {
462
- controller.enqueue(value);
463
- controller.close();
464
- } });
465
- if (typeof value === "string") return new Blob([value]).stream();
466
- if (value instanceof URLSearchParams) return new Blob([value.toString()]).stream();
467
- if (value instanceof Object && Object.getPrototypeOf(value) === Object.prototype) return new Blob([JSON.stringify(value)]).stream();
468
- }
469
- async function openNodeRequestBody(event) {
470
- const request = event.node.req;
471
- const stored = event._requestBody ?? request[rawBodySymbol] ?? request.rawBody ?? request.body;
472
- if (stored !== void 0 && stored !== null) {
473
- const stream = toBodyStream(await stored);
474
- if (stream) {
475
- const reader = stream.getReader();
476
- return () => reader.read();
477
- }
478
- }
479
- const iterator = request[Symbol.asyncIterator]?.();
480
- if (!iterator) return void 0;
481
- const chunks = [];
482
- const collected = [];
483
- let total = 0;
484
- let ended = false;
485
- let failed = false;
486
- let failure;
487
- let waiting;
488
- const produce = async () => {
489
- try {
490
- for await (const chunk of { [Symbol.asyncIterator]: () => iterator }) {
491
- let bytes;
492
- if (typeof chunk === "string") bytes = new TextEncoder().encode(chunk);
493
- else if (chunk instanceof Uint8Array) bytes = chunk;
494
- else throw new TypeError("[vitehub] Request body chunks must be strings or bytes.");
495
- collected.push(bytes);
496
- total += bytes.byteLength;
497
- if (waiting) {
498
- waiting.resolve({ value: bytes });
499
- waiting = void 0;
500
- } else chunks.push(bytes);
501
- }
502
- ended = true;
503
- waiting?.resolve({ done: true });
504
- waiting = void 0;
505
- } catch (error) {
506
- failed = true;
507
- failure = error;
508
- ended = true;
509
- waiting?.reject(error);
510
- waiting = void 0;
511
- throw error;
512
- }
513
- const bytes = new Uint8Array(total);
514
- let offset = 0;
515
- for (const chunk of collected) {
516
- bytes.set(chunk, offset);
517
- offset += chunk.byteLength;
518
- }
519
- return bytes;
520
- };
521
- let body;
522
- const start = () => body ??= produce();
523
- event._requestBody = { then: (resolve, reject) => start().then(resolve, reject) };
524
- return async () => {
525
- start();
526
- body?.catch(() => {});
527
- if (failed) throw failure;
528
- if (chunks.length) return { value: chunks.shift() };
529
- if (ended) return { done: true };
530
- return new Promise((resolve, reject) => {
531
- waiting = {
532
- resolve,
533
- reject
534
- };
535
- });
536
- };
537
- }
538
- /** Read the body lazily, from a value a host already read or from the Node request stream. */
539
- function readNodeRequestBody(event) {
540
- let reader;
541
- return new ReadableStream({ async pull(controller) {
542
- const chunk = await (await (reader ??= openNodeRequestBody(event)))?.();
543
- if (!chunk || chunk.done) {
544
- controller.close();
545
- return;
546
- }
547
- const value = chunk.value;
548
- if (typeof value === "string") controller.enqueue(new TextEncoder().encode(value));
549
- else if (value instanceof Uint8Array) controller.enqueue(value);
550
- else controller.error(/* @__PURE__ */ new TypeError("[vitehub] Request body chunks must be strings or bytes."));
551
- } }, { highWaterMark: 0 });
552
- }
553
- /** Return one Web Request per H3 1 event. The body is read only when a caller reads the Request body. */
554
- function toH3V1Request(event) {
555
- const cached = nodeEventRequests.get(event);
556
- if (cached) return cached;
557
- if (isWebRequest(event.web?.request)) return event.web.request;
558
- const request = event.node.req;
559
- const method = (request.method || "GET").toUpperCase();
560
- const init = {
561
- headers: readNodeRequestHeaders(request),
562
- method
563
- };
564
- if (payloadMethods.has(method)) {
565
- init.body = readNodeRequestBody(event);
566
- init.duplex = "half";
567
- }
568
- const webRequest = new Request(readNodeRequestURL(request), init);
569
- nodeEventRequests.set(event, webRequest);
570
- return webRequest;
571
- }
572
- //#endregion
573
452
  //#region ../internal/src/runtime/request-origin.ts
574
453
  function firstHeaderValue(headers, name) {
575
454
  return headers.get(name)?.split(",", 1)[0]?.trim() || void 0;
@@ -592,8 +471,61 @@ function forwardedRequestOrigin(request) {
592
471
  }
593
472
  }
594
473
  //#endregion
474
+ //#region src/blob-document.ts
475
+ function errorCode(error) {
476
+ return error !== null && typeof error === "object" && "code" in error ? error.code : void 0;
477
+ }
478
+ async function digestOf(text) {
479
+ const bytes = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));
480
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
481
+ }
482
+ /**
483
+ * Stores each Realtime document as one Blob file at `prefix + documentId`. Its digest is the SHA-256 of the
484
+ * body. `save()` reads the stored file and throws `RealtimeDocumentConflict` when its digest is not `ifDigest`. It
485
+ * writes only if the file still has the ETag that it read, so a writer outside the room that writes between that read
486
+ * and the save's write also makes the save throw `RealtimeDocumentConflict`, and keeps its file.
487
+ */
488
+ function blobDocument(store, options = {}) {
489
+ const { contentType = "text/markdown; charset=utf-8", prefix = "" } = options;
490
+ const pathnameOf = (documentId) => (prefix + documentId).replaceAll("%", "%25");
491
+ const read = async (pathname) => {
492
+ const [error, file] = await store.get(pathname);
493
+ if (errorCode(error) === "BLOB_NOT_FOUND") return null;
494
+ if (error) throw error;
495
+ return file ? await file.text() : null;
496
+ };
497
+ return {
498
+ kind: "blob",
499
+ async load({ documentId }) {
500
+ const body = await read(pathnameOf(documentId));
501
+ return {
502
+ body: body ?? "",
503
+ digest: body === null ? null : await digestOf(body)
504
+ };
505
+ },
506
+ async save({ documentId }, { body }, { ifDigest }) {
507
+ const pathname = pathnameOf(documentId);
508
+ const [headError, object] = await store.head(pathname);
509
+ if (headError && errorCode(headError) !== "BLOB_NOT_FOUND") throw headError;
510
+ const stored = object ? await read(pathname) : null;
511
+ if ((stored === null ? null : await digestOf(stored)) !== ifDigest) throw new RealtimeDocumentConflict(stored === null ? "The Blob file of this document was deleted after the realtime room loaded it." : "The Blob file of this document changed after the realtime room loaded it.");
512
+ const etag = object?.httpEtag;
513
+ if (object && !etag) throw realtimeErrorDiagnostics.REALTIME_BLOB_ETAG_MISSING({ pathname });
514
+ const [error] = await store.put(pathname, body, etag ? {
515
+ contentType,
516
+ ifMatch: etag
517
+ } : {
518
+ contentType,
519
+ overwrite: false
520
+ });
521
+ if (errorCode(error) === "BLOB_CONFLICT") throw new RealtimeDocumentConflict("Another writer changed the Blob file of this document while the realtime room saved it.");
522
+ if (error) throw error;
523
+ return { digest: await digestOf(body) };
524
+ }
525
+ };
526
+ }
527
+ //#endregion
595
528
  //#region src/server.ts
596
- const routePrefix = "/api/_vitehub/realtime/";
597
529
  const maxMessageBytes = 1048576;
598
530
  const maxRoomStateBytes = 8388608;
599
531
  const maxMemoryRooms = 128;
@@ -612,22 +544,33 @@ const durableUpdateCompactionInterval = 128;
612
544
  const maxSaveRetryMs = 6e4;
613
545
  const holdIntervalMs = 6e4;
614
546
  const messageSync = 0;
547
+ const keepalivePing = new TextEncoder().encode(realtimeKeepalivePing);
615
548
  /** Marks the request that `refreshRealtimeDocument()` sends to a Durable Object. The Worker strips it from client requests. */
616
549
  const internalRefreshHeader = "x-vitehub-realtime-refresh";
617
- /**
618
- * The one Durable Object instance that holds every room. Nitro's `cloudflare-durable` entry hands each WebSocket upgrade
619
- * to this instance before the application runs, so saves, checkpoints, and refreshes must reach it too: a Durable
620
- * Object per room would have no peers and never match a room's state.
621
- */
622
- const durableRoomsInstance = "server";
623
550
  const realtimePersistenceDefaults = Object.freeze({
624
551
  debounce: 2e3,
625
552
  maxWait: 1e4
626
553
  });
627
554
  /** Origin of updates that the server writes itself: seeds, stored-form merges, and status. */
628
555
  const serverOrigin = Symbol("vitehub.realtime.server");
556
+ /** Origin of updates that another instance sent over the bus. */
557
+ const busOrigin = Symbol("vitehub.realtime.bus");
558
+ /** A Yjs update with no structs and no deletions. */
559
+ const emptyUpdateBytes = 2;
560
+ /** The epoch of rooms that hold no document: Workspace event rooms and the rooms of presence definitions. */
561
+ const eventsEpoch = "events";
562
+ /** The fields that the adapter loaded, without the ones it left undefined. */
563
+ function loadedFields(loaded) {
564
+ return Object.fromEntries(Object.entries(loaded.fields ?? {}).filter(([, value]) => value !== void 0));
565
+ }
566
+ /** True when the field map holds exactly these fields, including fields whose value is null. */
567
+ function holdsFields(map, fields) {
568
+ const keys = Object.keys(fields);
569
+ return map.size === keys.length && keys.every((key) => map.has(key) && realtimeJsonEqual(map.get(key), fields[key]));
570
+ }
629
571
  const readOnlyDocumentMessage = "The editor cannot save this document without loss. The room is read-only.";
630
572
  const readOnlyDocumentRejection = "This realtime document is read-only: the editor cannot save it without loss.";
573
+ const invalidDocumentMessage = "The room document does not fit the editor schema, so Realtime did not save it. Undo the last change or reload.";
631
574
  const codecReadBackIssue = { message: "The editor cannot read back the Markdown that it saved. Some content can change when the document opens again." };
632
575
  function encodeSyncUpdate(update) {
633
576
  const encoder = encoding.createEncoder();
@@ -642,18 +585,31 @@ function encodeSyncStep1(document) {
642
585
  return encoding.toUint8Array(encoder);
643
586
  }
644
587
  function encodeAwarenessState(awareness, clients) {
588
+ return encodeAwareness(awarenessProtocol.encodeAwarenessUpdate(awareness, clients));
589
+ }
590
+ function encodeAwareness(update) {
645
591
  const encoder = encoding.createEncoder();
646
592
  encoding.writeVarUint(encoder, 1);
647
- encoding.writeVarUint8Array(encoder, awarenessProtocol.encodeAwarenessUpdate(awareness, clients));
593
+ encoding.writeVarUint8Array(encoder, update);
648
594
  return encoding.toUint8Array(encoder);
649
595
  }
596
+ /**
597
+ * The clients that the awareness has a clock for. A client's first awareness update has clock 0, which Yjs does not
598
+ * apply, so the client has no clock yet and cannot be encoded.
599
+ */
600
+ function knownAwarenessClients(awareness, clients) {
601
+ return clients.filter((client) => awareness.meta.has(client));
602
+ }
603
+ /** Whether a transaction changed only the server-written `status` map. */
604
+ function changesOnlyStatus(document, transaction) {
605
+ const status = document.getMap(realtimeDocumentLayout.status);
606
+ for (const type of transaction.changed.keys()) if (type !== status) return false;
607
+ return true;
608
+ }
650
609
  /** A peer tried to write what it may not: a read-only connection, or the server-written status map. */
651
- var RealtimeWriteRejected = class extends Error {
652
- constructor(message) {
653
- super(message);
654
- this.name = "RealtimeWriteRejected";
655
- }
656
- };
610
+ function isWriteRejected(error) {
611
+ return error instanceof Error && Reflect.get(error, "code") === "REALTIME_WRITE_REJECTED";
612
+ }
657
613
  function applyRealtimeSyncMessage(data, document, origin, options = {}) {
658
614
  const apply = (target) => {
659
615
  const decoder = decoding.createDecoder(data);
@@ -671,9 +627,12 @@ function applyRealtimeSyncMessage(data, document, origin, options = {}) {
671
627
  Y.applyUpdate(candidate, Y.encodeStateAsUpdate(document));
672
628
  const before = Y.snapshot(candidate);
673
629
  apply(candidate);
674
- if (candidate.store.pendingStructs || candidate.store.pendingDs) throw new RealtimeWriteRejected("Realtime update depends on state this room does not have.");
675
- if (options.readOnly && !Y.equalSnapshots(before, Y.snapshot(candidate))) throw new RealtimeWriteRejected(typeof options.readOnly === "string" ? options.readOnly : "This realtime connection is read-only.");
676
- if (options.protectStatus !== false && realtimeStatusFingerprint(candidate) !== realtimeStatusFingerprint(document)) throw new RealtimeWriteRejected("Realtime document status is written by the server.");
630
+ if (candidate.store.pendingStructs || candidate.store.pendingDs) throw realtimeErrorDiagnostics.REALTIME_WRITE_REJECTED({ problem: "missing-state" });
631
+ if (options.readOnly && !Y.equalSnapshots(before, Y.snapshot(candidate))) throw realtimeErrorDiagnostics.REALTIME_WRITE_REJECTED({
632
+ problem: "read-only",
633
+ ...typeof options.readOnly === "string" ? { readOnly: options.readOnly } : {}
634
+ });
635
+ if (options.protectStatus !== false && realtimeStatusFingerprint(candidate) !== realtimeStatusFingerprint(document)) throw realtimeErrorDiagnostics.REALTIME_WRITE_REJECTED({ problem: "status" });
677
636
  if (Y.encodeStateAsUpdate(candidate).byteLength > (options.maxStateBytes ?? maxRoomStateBytes)) throw realtimeErrorDiagnostics.REALTIME_DOCUMENT_TOO_LARGE();
678
637
  } finally {
679
638
  candidate.destroy();
@@ -686,8 +645,17 @@ function assertRealtimeRoomStateQuota(document, maxStateBytes = maxRoomStateByte
686
645
  message: "Realtime document exceeds its 8 MiB room quota."
687
646
  });
688
647
  }
689
- function realtimeRoomKey(definitionName, documentId) {
690
- return JSON.stringify([definitionName, documentId]);
648
+ function realtimeRoomKey(definitionName, documentId, scope) {
649
+ return JSON.stringify(scope === void 0 ? [definitionName, documentId] : [
650
+ definitionName,
651
+ documentId,
652
+ scope
653
+ ]);
654
+ }
655
+ /** The scope of a person's rooms in a Definition with `scope: "user"`, or `undefined` for shared rooms. */
656
+ function roomScope(definition, user) {
657
+ if (definition.document !== false || definition.scope !== "user") return void 0;
658
+ return user === null ? "anonymous" : `user:${user}`;
691
659
  }
692
660
  async function restoreRealtimeDocument(markdown, baselineDigest, stored) {
693
661
  const update = storedUpdate(stored?.update_blob);
@@ -748,6 +716,7 @@ function duration(value, fallback, name) {
748
716
  function resolveRealtimeDefinition(definition) {
749
717
  const cached = resolvedDefinitions.get(definition);
750
718
  if (cached) return cached;
719
+ assertRealtimeCheckpoint(definition);
751
720
  const document = definition.document;
752
721
  const adapter = isDocumentAdapter(document) ? document : workspaceDocument(document.workspace);
753
722
  const persistence = definition.persistence === false ? false : {
@@ -771,11 +740,10 @@ function resolveRealtimeDefinition(definition) {
771
740
  async function verifyDocument(editor, loaded) {
772
741
  const result = await editor.verify?.(loaded.body, { fields: loaded.fields });
773
742
  const finalNewline = loaded.body.endsWith("\n");
774
- const fields = Object.fromEntries(Object.entries(loaded.fields ?? {}).filter(([, value]) => value !== void 0));
775
743
  return {
776
744
  clean: {
777
745
  body: keepRealtimeFinalNewline(result?.canonical ?? loaded.body, finalNewline),
778
- fields
746
+ fields: loadedFields(loaded)
779
747
  },
780
748
  finalNewline,
781
749
  issues: result?.issues ?? [],
@@ -789,7 +757,10 @@ function guardStatus(guard) {
789
757
  };
790
758
  }
791
759
  function documentTables(sql) {
792
- sql.exec("CREATE TABLE IF NOT EXISTS vitehub_realtime_documents (room_key TEXT PRIMARY KEY, epoch TEXT NOT NULL, digest TEXT, dirty INTEGER NOT NULL, update_blob BLOB NOT NULL)");
760
+ sql.exec("CREATE TABLE IF NOT EXISTS vitehub_realtime_documents (room_key TEXT PRIMARY KEY, epoch TEXT NOT NULL, digest TEXT, dirty INTEGER NOT NULL, update_blob BLOB NOT NULL, editor_version TEXT)");
761
+ try {
762
+ sql.exec("ALTER TABLE vitehub_realtime_documents ADD COLUMN editor_version TEXT");
763
+ } catch {}
793
764
  sql.exec("CREATE TABLE IF NOT EXISTS vitehub_realtime_document_updates (sequence INTEGER PRIMARY KEY AUTOINCREMENT, room_key TEXT NOT NULL, update_blob BLOB NOT NULL, client_update INTEGER NOT NULL DEFAULT 1)");
794
765
  try {
795
766
  sql.exec("ALTER TABLE vitehub_realtime_document_updates ADD COLUMN client_update INTEGER NOT NULL DEFAULT 1");
@@ -822,12 +793,18 @@ function migrateLegacyDocument(sql, key, clientUpdateColumn) {
822
793
  const legacyUpdate = storedUpdate(row.update_blob);
823
794
  if (!legacyUpdate) continue;
824
795
  const blob = Uint8Array.from(legacyUpdate).buffer;
825
- try {
826
- if (!clientUpdateColumn) throw new Error("client_update column unavailable");
796
+ if (clientUpdateColumn) try {
827
797
  sql.exec("INSERT INTO vitehub_realtime_document_updates (room_key, update_blob, client_update) VALUES (?, ?, 1)", key, blob);
828
- } catch {
829
- sql.exec("INSERT INTO vitehub_realtime_document_updates (room_key, update_blob) VALUES (?, ?)", key, blob);
830
- }
798
+ continue;
799
+ } catch {}
800
+ sql.exec("INSERT INTO vitehub_realtime_document_updates (room_key, update_blob) VALUES (?, ?)", key, blob);
801
+ }
802
+ }
803
+ function readStoredRoom(sql, key) {
804
+ try {
805
+ return sql.exec("SELECT epoch, digest, dirty, update_blob, editor_version FROM vitehub_realtime_documents WHERE room_key = ?", key).toArray()[0];
806
+ } catch {
807
+ return sql.exec("SELECT epoch, digest, dirty, update_blob FROM vitehub_realtime_documents WHERE room_key = ?", key).toArray()[0];
831
808
  }
832
809
  }
833
810
  function parseRoomPath(url) {
@@ -837,7 +814,7 @@ function parseRoomPath(url) {
837
814
  if (at === -1) throw new HTTPError({ status: 404 });
838
815
  let parts;
839
816
  try {
840
- parts = path.slice(at + 23).split("/").map(decodeURIComponent);
817
+ parts = path.slice(at + routePrefix.length).split("/").map(decodeURIComponent);
841
818
  } catch {
842
819
  throw new HTTPError({
843
820
  status: 400,
@@ -882,12 +859,28 @@ function toRealtimeUser(value) {
882
859
  return user;
883
860
  }
884
861
  async function identify(request, event, definitionName, definition) {
862
+ if (definition.auth && !definition.identify) {
863
+ let auth;
864
+ try {
865
+ auth = await assertAuthOrigin(request, event);
866
+ } catch {
867
+ throw new HTTPError({ status: 403 });
868
+ }
869
+ const user = toRealtimeUser((await auth.api.getSession({ headers: request.headers }))?.user);
870
+ if (!user) throw new HTTPError({ status: 401 });
871
+ return user;
872
+ }
873
+ const origin = request.headers.get("origin");
874
+ if (origin && origin !== forwardedRequestOrigin(request) && !await definition.origins?.({
875
+ definition: definitionName,
876
+ event,
877
+ origin,
878
+ request
879
+ })) throw new HTTPError({
880
+ status: 403,
881
+ message: "Realtime requests must come from the application origin."
882
+ });
885
883
  if (definition.identify) {
886
- const origin = request.headers.get("origin");
887
- if (origin && origin !== forwardedRequestOrigin(request)) throw new HTTPError({
888
- status: 403,
889
- message: "Realtime requests must come from the application origin."
890
- });
891
884
  const user = toRealtimeUser(await definition.identify({
892
885
  definition: definitionName,
893
886
  event,
@@ -896,20 +889,23 @@ async function identify(request, event, definitionName, definition) {
896
889
  if (definition.auth && !user) throw new HTTPError({ status: 401 });
897
890
  return user;
898
891
  }
899
- if (!definition.auth) return null;
892
+ if (definition.document !== false || definition.scope !== "user") return null;
900
893
  let auth;
901
894
  try {
902
895
  auth = await assertAuthOrigin(request, event);
903
- } catch {
896
+ } catch (error) {
897
+ if (isMissingAuth(error)) return null;
904
898
  throw new HTTPError({ status: 403 });
905
899
  }
906
- const user = toRealtimeUser((await auth.api.getSession({ headers: request.headers }))?.user);
907
- if (!user) throw new HTTPError({ status: 401 });
908
- return user;
900
+ return toRealtimeUser((await auth.api.getSession({ headers: request.headers }))?.user);
901
+ }
902
+ /** The app has no Auth Definition (`AUTH_R0005`), so nobody is signed in. */
903
+ function isMissingAuth(error) {
904
+ return typeof error === "object" && error !== null && "code" in error && error.code === "AUTH_R0005";
909
905
  }
910
906
  async function allows(definition, context) {
911
- if (!definition.authorize) return true;
912
- return await definition.authorize(context) !== false;
907
+ if (definition.authorize) return await definition.authorize(context) === true;
908
+ return definition.auth === true || definition.access === "public";
913
909
  }
914
910
  function errorMessage(error) {
915
911
  if (error instanceof Error && error.message) return error.message;
@@ -922,35 +918,6 @@ function localRefreshers() {
922
918
  return refreshScope[localRefreshKey];
923
919
  }
924
920
  /**
925
- * Accepts the namespace that holds Realtime rooms, and nothing that only inherits `get` and `idFromName` from an
926
- * arbitrary prototype. Workerd's binding owns no methods: they belong to its `DurableObjectNamespace` class prototype,
927
- * and Workers have no global `DurableObjectNamespace` to compare with. Any other namespace, such as a test double,
928
- * must own both methods.
929
- */
930
- function isRealtimeDurableObjectNamespace(value) {
931
- if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
932
- const methods = (target) => ["get", "idFromName"].map((name) => Object.getOwnPropertyDescriptor(target, name));
933
- const callable = (method) => !!method && !method.get && typeof method.value === "function" && Function.prototype.toString.call(method.value) !== "function () { [native code] }";
934
- try {
935
- const own = methods(value);
936
- if (own.every(callable)) return true;
937
- const prototype = Object.getPrototypeOf(value);
938
- if (own.some(Boolean) || prototype === null || typeof prototype !== "object" || Object.getPrototypeOf(prototype) !== Object.prototype) return false;
939
- return Object.prototype.toString.call(value) === "[object DurableObjectNamespace]" && methods(prototype).every(callable);
940
- } catch {
941
- return false;
942
- }
943
- }
944
- /** The `$DurableObject` binding of the running Worker. Nitro's Cloudflare entry stores each request's bindings in `globalThis.__env__`. */
945
- function workerDurableObjects() {
946
- try {
947
- const binding = getActiveCloudflareBinding("$DurableObject");
948
- return isRealtimeDurableObjectNamespace(binding) ? binding : void 0;
949
- } catch {
950
- return;
951
- }
952
- }
953
- /**
954
921
  * Tells the open room of a document that its stored copy changed outside the room, such as a save by an Agent or the
955
922
  * CLI. A room without unsaved edits re-seeds at once and resets its clients. A room with unsaved edits finds the change
956
923
  * at its next save, which also re-seeds it. A room that is not open loads the stored copy when it opens. Resolves
@@ -1001,24 +968,11 @@ function refuseUpgrade(request, status) {
1001
968
  return Object.assign(new Response(null, { status }), { crossws: hooks });
1002
969
  }
1003
970
  const webSocketHooksKey = Symbol.for("crossws.hooks");
1004
- /** An H3 2 event over a Web Request. Nuxt 4 runs Nitro 2, whose H3 1 events carry Node's request. */
1005
- function toWebEvent(event) {
1006
- return isH3V1Event(event) ? new H3Event(toH3V1Request(event), event.context) : event;
1007
- }
1008
- const durableObjectKey = Symbol.for(realtimeDurableObjectKey);
1009
- const durableScope = globalThis;
1010
- /**
1011
- * Remembers the Durable Object of this isolate, for the sockets that Nitro 2 upgrades in it: its upgrade hook gets only
1012
- * the request, and the rooms keep their tables in the Durable Object's storage. Realtime's Nitro plugin calls it at
1013
- * `cloudflare:durable:init`.
1014
- */
1015
- function registerRealtimeDurableObject(state, env) {
1016
- durableScope[durableObjectKey] = {
1017
- env,
1018
- state
1019
- };
971
+ /** A request with no headers at all, like the stub that crossws restores a hibernated socket's peer with. Browsers always send some. */
972
+ function isBareRequest(request) {
973
+ return request.headers.keys().next().done === true;
1020
974
  }
1021
- function createRealtimeHandler(registry) {
975
+ function createRealtimeHandler(registry, options = {}) {
1022
976
  const inactiveMemoryRoomKeys = /* @__PURE__ */ new Set();
1023
977
  const memoryRoomKeys = /* @__PURE__ */ new Set();
1024
978
  const rooms = /* @__PURE__ */ new Map();
@@ -1036,17 +990,189 @@ function createRealtimeHandler(registry) {
1036
990
  peerHeldUpdates.delete(peer);
1037
991
  clearTimeout(held.timer);
1038
992
  }
993
+ let pendingBus;
994
+ /** Rooms that finished opening, by key. */
995
+ const openRooms = /* @__PURE__ */ new Map();
996
+ /** One owner object per other instance, for the awareness clients of its peers. */
997
+ const remoteOwners = /* @__PURE__ */ new Map();
998
+ const repairRequestedAt = /* @__PURE__ */ new WeakMap();
999
+ const syncing = /* @__PURE__ */ new WeakSet();
1000
+ /** The bus that shares rooms with other instances, connected and subscribed on first use. */
1001
+ function sharedBus() {
1002
+ if (!options.bus) return Promise.resolve(void 0);
1003
+ if (pendingBus) return pendingBus;
1004
+ const connect = options.bus;
1005
+ const pending = (async () => {
1006
+ const bus = await connect();
1007
+ if (!bus) return void 0;
1008
+ await bus.subscribe(receive, () => {
1009
+ for (const room of rooms.values()) room.then(requestSync, () => {});
1010
+ });
1011
+ bus.onClose(announceDeparture);
1012
+ const syncTimer = setInterval(() => {
1013
+ for (const room of openRooms.values()) if (room.peers.size || room.kind === "document" && room.dirty) requestSync(room);
1014
+ }, 1e4);
1015
+ syncTimer.unref?.();
1016
+ bus.onClose(async () => {
1017
+ clearInterval(syncTimer);
1018
+ });
1019
+ return bus;
1020
+ })();
1021
+ pendingBus = pending;
1022
+ pending.catch(() => {
1023
+ if (pendingBus === pending) pendingBus = void 0;
1024
+ });
1025
+ return pending;
1026
+ }
1027
+ function roomEpoch(room) {
1028
+ return room.kind === "document" ? room.epoch : eventsEpoch;
1029
+ }
1030
+ function publish(room, type, data) {
1031
+ room.bus?.publish({
1032
+ type,
1033
+ room: room.key,
1034
+ epoch: roomEpoch(room),
1035
+ data
1036
+ }).catch((error) => {
1037
+ console.error("[vitehub] Realtime could not send a room message to the other instances.", error);
1038
+ });
1039
+ }
1040
+ /** Asks the other instances for the document updates and the presence that this room lacks. */
1041
+ function requestSync(room) {
1042
+ if (!room.bus) return;
1043
+ if (room.kind !== "document") {
1044
+ publish(room, "sync", /* @__PURE__ */ new Uint8Array());
1045
+ return;
1046
+ }
1047
+ if (room.destroyed || syncing.has(room)) return;
1048
+ if (!room.peers.size && !room.dirty) {
1049
+ publish(room, "sync", Y.encodeStateVector(room.document));
1050
+ return;
1051
+ }
1052
+ syncing.add(room);
1053
+ enqueue(room, async () => {
1054
+ const record = await room.bus?.readRoom(room.key);
1055
+ if (room.destroyed) return;
1056
+ if (record && record.epoch !== room.epoch) await reseedRoom(room, "source-changed", void 0, false, true);
1057
+ if (!room.destroyed) publish(room, "sync", Y.encodeStateVector(room.document));
1058
+ }).catch((error) => {
1059
+ console.error("[vitehub] Realtime could not repair a shared room.", error);
1060
+ }).finally(() => syncing.delete(room));
1061
+ }
1062
+ /** Awareness clients of this instance's peers. */
1063
+ function localAwarenessClients(room) {
1064
+ return knownAwarenessClients(room.awareness, [...room.awareness.getStates().keys()].filter((client) => room.awarenessOwners.ownsLocally(client)));
1065
+ }
1066
+ /** Tells the other instances that the peers of this instance left, before the bus closes. */
1067
+ async function announceDeparture() {
1068
+ const sent = [];
1069
+ for (const pending of rooms.values()) {
1070
+ const room = await pending.catch(() => void 0);
1071
+ if (!room?.bus) continue;
1072
+ const clients = localAwarenessClients(room);
1073
+ if (!clients.length) continue;
1074
+ const update = awarenessProtocol.encodeAwarenessUpdate(room.awareness, clients, /* @__PURE__ */ new Map());
1075
+ sent.push(room.bus.publish({
1076
+ type: "awareness",
1077
+ room: room.key,
1078
+ epoch: roomEpoch(room),
1079
+ data: update
1080
+ }));
1081
+ }
1082
+ await Promise.allSettled(sent);
1083
+ }
1084
+ function remoteOwner(instance) {
1085
+ let owner = remoteOwners.get(instance);
1086
+ if (!owner) remoteOwners.set(instance, owner = { instance });
1087
+ return owner;
1088
+ }
1089
+ /**
1090
+ * Applies a message from another instance to the open room it names. A room that is still opening skips the
1091
+ * message: it asks for what it lacks when it opens.
1092
+ */
1093
+ function receive(message) {
1094
+ if (message.type === "refresh") {
1095
+ const key = JSON.parse(message.room);
1096
+ const [definitionName, documentId] = Array.isArray(key) ? key : [];
1097
+ if (typeof definitionName === "string" && typeof documentId === "string") refreshOpenRoom(definitionName, documentId, false).catch(() => {});
1098
+ return;
1099
+ }
1100
+ if (message.type === "reset") {
1101
+ rooms.get(message.room)?.then((room) => {
1102
+ if (room.kind !== "document" || !room.bus || room.destroyed || room.epoch === message.epoch) return;
1103
+ enqueue(room, async () => {
1104
+ if (room.epoch !== message.epoch) await reseedRoom(room, "source-changed", void 0, false, true);
1105
+ }).catch(() => {});
1106
+ }, () => {});
1107
+ return;
1108
+ }
1109
+ const room = openRooms.get(message.room);
1110
+ if (!room?.bus || room.kind === "document" && room.destroyed) return;
1111
+ if (message.epoch !== roomEpoch(room)) {
1112
+ if (message.type === "sync") requestSync(room);
1113
+ return;
1114
+ }
1115
+ switch (message.type) {
1116
+ case "update":
1117
+ if (room.kind === "document") {
1118
+ Y.applyUpdate(room.document, message.data, busOrigin);
1119
+ if ((room.document.store.pendingStructs || room.document.store.pendingDs) && Date.now() - (repairRequestedAt.get(room) ?? -Infinity) >= 1e3) {
1120
+ repairRequestedAt.set(room, Date.now());
1121
+ requestSync(room);
1122
+ }
1123
+ }
1124
+ return;
1125
+ case "claim":
1126
+ try {
1127
+ const client = decoding.readVarUint(decoding.createDecoder(message.data));
1128
+ room.awarenessOwners.claim(room.awareness, remoteOwner(message.instance), client, void 0, true);
1129
+ } catch {}
1130
+ return;
1131
+ case "awareness": {
1132
+ let clients;
1133
+ try {
1134
+ clients = room.awarenessOwners.apply(room.awareness, remoteOwner(message.instance), message.data, void 0, true);
1135
+ } catch {
1136
+ return;
1137
+ }
1138
+ const known = knownAwarenessClients(room.awareness, clients);
1139
+ if (!known.length) return;
1140
+ const frame = encodeAwarenessState(room.awareness, known);
1141
+ for (const peer of room.peers) peer.send(frame);
1142
+ return;
1143
+ }
1144
+ case "sync": {
1145
+ if (room.kind === "document") {
1146
+ const missing = Y.encodeStateAsUpdate(room.document, message.data);
1147
+ if (missing.byteLength > emptyUpdateBytes) publish(room, "update", missing);
1148
+ }
1149
+ const clients = localAwarenessClients(room);
1150
+ if (clients.length) publish(room, "awareness", awarenessProtocol.encodeAwarenessUpdate(room.awareness, clients));
1151
+ return;
1152
+ }
1153
+ case "frame": for (const peer of room.peers) peer.send(message.data);
1154
+ }
1155
+ }
1156
+ /**
1157
+ * Relays the awareness changes that are not a peer's own message: clients that timed out, and clients that another
1158
+ * instance removed. Awareness removes a client 30 seconds after its last update, so the presence of an instance that
1159
+ * stopped without a goodbye expires on the others.
1160
+ */
1161
+ function watchAwareness(room) {
1162
+ const awareness = room.awareness;
1163
+ awareness.on("update", ({ removed }, origin) => {
1164
+ if (room.awareness !== awareness || !removed.length) return;
1165
+ room.awarenessOwners.releaseRemote(removed);
1166
+ if (origin !== "timeout") return;
1167
+ const clients = knownAwarenessClients(awareness, removed);
1168
+ if (!clients.length) return;
1169
+ const frame = encodeAwarenessState(awareness, clients);
1170
+ for (const peer of room.peers) peer.send(frame);
1171
+ });
1172
+ }
1173
+ /** The Cloudflare bindings and execution context, or the Durable Object state, in the event's Standard Context. */
1039
1174
  function resolveCloudflare(event) {
1040
- const runtime = event.req.runtime?.cloudflare;
1041
- const platform = event.context._platform?.cloudflare;
1042
- if (!runtime) return platform;
1043
- if (!platform) return runtime;
1044
- return {
1045
- ...runtime,
1046
- ...platform,
1047
- context: runtime.context ?? platform.context,
1048
- env: platform.env ?? runtime.env
1049
- };
1175
+ return getStandardContext(event).runtime?.cloudflare;
1050
1176
  }
1051
1177
  async function forwardToCloudflareDurableObject(event) {
1052
1178
  const cloudflare = resolveCloudflare(event);
@@ -1054,9 +1180,10 @@ function createRealtimeHandler(registry) {
1054
1180
  const binding = (cloudflare?.env)?.$DurableObject;
1055
1181
  if (!binding || !isRealtimeDurableObjectNamespace(binding) || typeof context === "object" && context !== null && "storage" in context) return;
1056
1182
  let request = event.req;
1057
- if (request.headers.has(internalRefreshHeader)) {
1183
+ if (request.headers.has(internalRefreshHeader) || request.headers.has("x-vitehub-realtime-request")) {
1058
1184
  const headers = new Headers(request.headers);
1059
1185
  headers.delete(internalRefreshHeader);
1186
+ headers.delete(internalRequestHeader);
1060
1187
  request = new Request(request, { headers });
1061
1188
  }
1062
1189
  return await binding.get(binding.idFromName(durableRoomsInstance)).fetch(request);
@@ -1096,6 +1223,7 @@ function createRealtimeHandler(registry) {
1096
1223
  status: 404,
1097
1224
  message: `Unknown realtime definition ${JSON.stringify(definitionName)}.`
1098
1225
  });
1226
+ assertRealtimeAccess(module.default);
1099
1227
  return module.default;
1100
1228
  }
1101
1229
  async function reserveMemoryRoom() {
@@ -1128,21 +1256,27 @@ function createRealtimeHandler(registry) {
1128
1256
  inactiveMemoryRoomKeys.delete(key);
1129
1257
  return value;
1130
1258
  }
1131
- function getEventsRoom(definitionName) {
1132
- const key = JSON.stringify([definitionName, { workspaceEvents: true }]);
1133
- return openRoom(key, void 0, async () => {
1259
+ function getEventsRoom(key, workspace, sql) {
1260
+ return openRoom(key, sql, async () => {
1261
+ const bus = await sharedBus();
1134
1262
  const document = new Y.Doc();
1135
1263
  const awareness = new awarenessProtocol.Awareness(document);
1136
1264
  awareness.setLocalState(null);
1137
- return {
1265
+ const room = {
1138
1266
  awareness,
1139
1267
  awarenessOwners: createRealtimeAwarenessOwners(),
1268
+ bus,
1140
1269
  channel: `vitehub:realtime:${key}`,
1141
1270
  document,
1142
1271
  key,
1143
1272
  kind: "events",
1144
- peers: /* @__PURE__ */ new Set()
1273
+ peers: /* @__PURE__ */ new Set(),
1274
+ workspace
1145
1275
  };
1276
+ watchAwareness(room);
1277
+ openRooms.set(key, room);
1278
+ requestSync(room);
1279
+ return room;
1146
1280
  });
1147
1281
  }
1148
1282
  function createAwareness(document) {
@@ -1154,13 +1288,18 @@ function createRealtimeHandler(registry) {
1154
1288
  for (const peer of room.peers) if (peer === origin) return peer;
1155
1289
  }
1156
1290
  function listen(room, document) {
1157
- document.on("update", (update, origin) => {
1291
+ document.on("update", (update, origin, _document, transaction) => {
1158
1292
  if (room.document !== document) return;
1159
1293
  persistRoomUpdate(room, update, origin !== serverOrigin);
1160
1294
  const message = encodeSyncUpdate(update);
1161
1295
  const sender = roomPeer(room, origin);
1162
1296
  if (sender) sender.publish(room.channel, message);
1163
1297
  else for (const peer of room.peers) peer.send(message);
1298
+ if (origin === busOrigin) {
1299
+ if (!changesOnlyStatus(document, transaction)) markDirty(room, void 0);
1300
+ return;
1301
+ }
1302
+ publish(room, "update", update);
1164
1303
  if (origin !== serverOrigin) markDirty(room, sender && room.peerUsers.get(sender));
1165
1304
  });
1166
1305
  }
@@ -1168,8 +1307,165 @@ function createRealtimeHandler(registry) {
1168
1307
  room.document = document;
1169
1308
  room.awareness = createAwareness(document);
1170
1309
  room.awarenessOwners = createRealtimeAwarenessOwners();
1310
+ watchAwareness(room);
1171
1311
  listen(room, document);
1172
1312
  }
1313
+ /**
1314
+ * The document of a shared room: the shared record when it holds the stored digest, else a new seed that becomes the
1315
+ * record. Instances that open a room at the same time agree on one record, so every instance edits one Yjs history.
1316
+ * `replaced` is true when this instance moved the record to a new epoch.
1317
+ */
1318
+ async function sharedDocument(bus, key, editor, loaded, guard) {
1319
+ for (let attempt = 0; attempt < 5; attempt++) {
1320
+ const found = await bus.readRoom(key);
1321
+ const record = found && await recoverSharedRecord(bus, key, editor, loaded, found);
1322
+ if (record && record.digest === loaded.digest) {
1323
+ const document = new Y.Doc();
1324
+ try {
1325
+ Y.applyUpdate(document, record.state);
1326
+ if (readRealtimeStatus(document).digest !== record.digest) writeRealtimeStatus(document, { digest: record.digest }, serverOrigin);
1327
+ return {
1328
+ document,
1329
+ epoch: record.epoch,
1330
+ replaced: false,
1331
+ dirty: record.pending
1332
+ };
1333
+ } catch (error) {
1334
+ document.destroy();
1335
+ throw error;
1336
+ }
1337
+ }
1338
+ const document = await seedDocument(editor, loaded, guard);
1339
+ const epoch = crypto.randomUUID();
1340
+ if (await bus.writeRoom(key, {
1341
+ epoch,
1342
+ digest: loaded.digest,
1343
+ state: Y.encodeStateAsUpdate(document)
1344
+ }, record?.epoch ?? null)) return {
1345
+ document,
1346
+ epoch,
1347
+ replaced: !!record
1348
+ };
1349
+ document.destroy();
1350
+ }
1351
+ throw new HTTPError({
1352
+ status: 503,
1353
+ message: "Realtime instances changed this room at the same time. Connect again."
1354
+ });
1355
+ }
1356
+ /** All callers hold the room lock. Never report a save as clean when its record was not written. */
1357
+ async function writeSharedRecord(bus, key, record) {
1358
+ let failure;
1359
+ for (let attempt = 0; attempt < 3; attempt++) try {
1360
+ if (await bus.writeRoom(key, record, record.epoch)) return;
1361
+ console.error("[vitehub] Realtime room record compare-and-set failed.", key);
1362
+ throw realtimeErrorDiagnostics.REALTIME_ROOM_WRITE_CONFLICT();
1363
+ } catch (error) {
1364
+ failure = error;
1365
+ }
1366
+ console.error("[vitehub] Realtime could not write the shared room record.", failure);
1367
+ throw failure;
1368
+ }
1369
+ /** A process can stop between adapter.save() and the final record write. Recover that save without a new epoch. */
1370
+ async function recoverSharedRecord(bus, key, editor, loaded, record) {
1371
+ if (!record.pending || loaded.digest === record.digest) return record;
1372
+ const submitted = new Y.Doc();
1373
+ try {
1374
+ Y.applyUpdate(submitted, record.state);
1375
+ const snapshot = await readRealtimeYDoc(editor, submitted);
1376
+ if (keepRealtimeFinalNewline(snapshot.body, loaded.body.endsWith("\n")) !== loaded.body || !realtimeJsonEqual(snapshot.fields, loadedFields(loaded))) return record;
1377
+ writeRealtimeStatus(submitted, {
1378
+ digest: loaded.digest,
1379
+ error: null
1380
+ }, serverOrigin);
1381
+ const recovered = {
1382
+ ...record,
1383
+ digest: loaded.digest,
1384
+ state: Y.encodeStateAsUpdate(submitted),
1385
+ pending: false
1386
+ };
1387
+ await writeSharedRecord(bus, key, recovered);
1388
+ return recovered;
1389
+ } finally {
1390
+ submitted.destroy();
1391
+ }
1392
+ }
1393
+ /**
1394
+ * Takes the saves of other instances into a shared room before it saves: their Yjs state, their digest, and the
1395
+ * stored form that a save with no edits keeps. Returns `false` when the room re-seeded on another instance, after
1396
+ * this room followed it.
1397
+ */
1398
+ async function adoptSharedRecord(room, bus) {
1399
+ let record = await bus.readRoom(room.key);
1400
+ let pendingLoaded;
1401
+ if (!record) return true;
1402
+ if (record.epoch !== room.epoch) {
1403
+ room.unwrittenRecord = void 0;
1404
+ await reseedRoom(room, "source-changed", void 0, false, true);
1405
+ return false;
1406
+ }
1407
+ const unwritten = room.unwrittenRecord;
1408
+ if (unwritten) {
1409
+ const saved = new Y.Doc();
1410
+ try {
1411
+ Y.applyUpdate(saved, unwritten.state);
1412
+ if (record.pending && unwritten.epoch === record.epoch && containsRealtimeState(saved, record.state)) {
1413
+ if ((await room.resolved.adapter.load(room.context)).digest === unwritten.digest) {
1414
+ await writeSharedRecord(bus, room.key, unwritten);
1415
+ record = unwritten;
1416
+ }
1417
+ }
1418
+ room.unwrittenRecord = void 0;
1419
+ } finally {
1420
+ saved.destroy();
1421
+ }
1422
+ }
1423
+ if (record.pending) {
1424
+ const loaded = await room.resolved.adapter.load(room.context);
1425
+ pendingLoaded = loaded;
1426
+ record = await recoverSharedRecord(bus, room.key, room.editor, loaded, record);
1427
+ if (record.digest !== loaded.digest) {
1428
+ if (room.pendingRecovery?.digest !== loaded.digest) room.pendingRecovery = {
1429
+ digest: loaded.digest,
1430
+ since: Date.now()
1431
+ };
1432
+ if (Date.now() - room.pendingRecovery.since < 1e4) throw new HTTPError({
1433
+ status: 503,
1434
+ message: "Realtime is waiting for another instance to finish its interrupted save. Retry the save."
1435
+ });
1436
+ await reseedRoom(room, "source-changed", loaded);
1437
+ return false;
1438
+ }
1439
+ }
1440
+ room.pendingRecovery = void 0;
1441
+ const sameStored = record.digest === room.digest && !record.pending;
1442
+ const saved = new Y.Doc();
1443
+ try {
1444
+ Y.applyUpdate(saved, record.state);
1445
+ const stored = record.pending && pendingLoaded ? {
1446
+ body: pendingLoaded.body,
1447
+ fields: loadedFields(pendingLoaded)
1448
+ } : await readRealtimeYDoc(room.editor, saved);
1449
+ if (room.destroyed || room.epoch !== record.epoch) return false;
1450
+ Y.applyUpdate(room.document, record.state, busOrigin);
1451
+ room.digest = record.digest;
1452
+ if (readRealtimeStatus(room.document).digest !== record.digest) writeRealtimeStatus(room.document, { digest: record.digest }, serverOrigin);
1453
+ if (sameStored) return true;
1454
+ room.guard = {
1455
+ clean: {
1456
+ body: keepRealtimeFinalNewline(stored.body, room.guard.finalNewline),
1457
+ fields: stored.fields
1458
+ },
1459
+ finalNewline: room.guard.finalNewline,
1460
+ issues: [],
1461
+ readOnly: false
1462
+ };
1463
+ if (record.pending) markDirty(room, void 0);
1464
+ return true;
1465
+ } finally {
1466
+ saved.destroy();
1467
+ }
1468
+ }
1173
1469
  async function seedDocument(editor, loaded, guard) {
1174
1470
  const document = await createRealtimeYDoc(editor, loaded);
1175
1471
  writeRealtimeStatus(document, {
@@ -1184,27 +1480,50 @@ function createRealtimeHandler(registry) {
1184
1480
  function getDocumentRoom(definitionName, documentId, resolved, sql) {
1185
1481
  const key = realtimeRoomKey(definitionName, documentId);
1186
1482
  return openRoom(key, sql, async () => {
1483
+ const bus = sql ? void 0 : await sharedBus();
1187
1484
  const context = {
1188
- authority: sql ? "cloudflare" : "memory",
1485
+ authority: sql ? "cloudflare" : bus?.authority ?? "memory",
1189
1486
  definition: definitionName,
1190
1487
  documentId
1191
1488
  };
1192
1489
  const editor = resolved.editor(context);
1193
- const loaded = await resolved.adapter.load(context);
1194
- const guard = await verifyDocument(editor, loaded);
1490
+ const { loaded, guard, shared } = bus ? await bus.withRoomLock(key, async () => {
1491
+ const loaded = await resolved.adapter.load(context);
1492
+ const guard = await verifyDocument(editor, loaded);
1493
+ return {
1494
+ loaded,
1495
+ guard,
1496
+ shared: await sharedDocument(bus, key, editor, loaded, guard)
1497
+ };
1498
+ }) : await (async () => {
1499
+ const loaded = await resolved.adapter.load(context);
1500
+ return {
1501
+ loaded,
1502
+ guard: await verifyDocument(editor, loaded),
1503
+ shared: void 0
1504
+ };
1505
+ })();
1195
1506
  if (sql) {
1196
1507
  const clientUpdateColumn = documentTables(sql);
1197
1508
  migrateLegacyDocument(sql, key, clientUpdateColumn);
1198
1509
  }
1199
- const stored = sql?.exec("SELECT epoch, digest, dirty, update_blob FROM vitehub_realtime_documents WHERE room_key = ?", key).toArray()[0];
1510
+ const stored = sql && readStoredRoom(sql, key);
1200
1511
  const storedDigest = text(stored?.digest) ?? null;
1201
1512
  const storedEpoch = text(stored?.epoch);
1202
1513
  const storedState = storedUpdate(stored?.update_blob);
1203
- const restores = !!sql && !!storedState && !!storedEpoch && storedDigest === loaded.digest;
1514
+ const restores = !!sql && !!storedState && !!storedEpoch && storedDigest === loaded.digest && (text(stored?.editor_version) ?? null) === (editor.version ?? null);
1204
1515
  let document;
1205
1516
  let persistedUpdates = 0;
1206
1517
  let dirty = false;
1207
- if (restores) {
1518
+ let refreshedFields = false;
1519
+ let sharedEpoch;
1520
+ let replacedEpoch = false;
1521
+ if (shared) {
1522
+ document = shared.document;
1523
+ sharedEpoch = shared.epoch;
1524
+ replacedEpoch = shared.replaced;
1525
+ dirty = shared.dirty ?? false;
1526
+ } else if (restores) {
1208
1527
  document = new Y.Doc();
1209
1528
  try {
1210
1529
  Y.applyUpdate(document, storedState);
@@ -1220,6 +1539,11 @@ function createRealtimeHandler(registry) {
1220
1539
  }
1221
1540
  persistedUpdates = updates.length;
1222
1541
  dirty = Number(stored?.dirty) === 1 || updates.some((update) => update.client_update === void 0 || Number(update.client_update) === 1);
1542
+ const fields = document.getMap(realtimeDocumentLayout.fields);
1543
+ if (!dirty && !holdsFields(fields, guard.clean.fields)) {
1544
+ document.transact(() => writeRealtimeFields(fields, guard.clean.fields), serverOrigin);
1545
+ refreshedFields = true;
1546
+ }
1223
1547
  assertRealtimeRoomStateQuota(document);
1224
1548
  if (guard.readOnly || readRealtimeStatus(document).error === readOnlyDocumentMessage) writeRealtimeStatus(document, guardStatus(guard), serverOrigin);
1225
1549
  } catch (error) {
@@ -1230,6 +1554,7 @@ function createRealtimeHandler(registry) {
1230
1554
  const room = {
1231
1555
  awareness: createAwareness(document),
1232
1556
  awarenessOwners: createRealtimeAwarenessOwners(),
1557
+ bus,
1233
1558
  channel: `vitehub:realtime:${key}`,
1234
1559
  context,
1235
1560
  destroyed: false,
@@ -1238,7 +1563,7 @@ function createRealtimeHandler(registry) {
1238
1563
  dirty,
1239
1564
  editor,
1240
1565
  editors: /* @__PURE__ */ new Map(),
1241
- epoch: restores && storedEpoch ? storedEpoch : crypto.randomUUID(),
1566
+ epoch: sharedEpoch ?? (restores && storedEpoch ? storedEpoch : crypto.randomUUID()),
1242
1567
  guard,
1243
1568
  held: false,
1244
1569
  writers: /* @__PURE__ */ new Set(),
@@ -1254,15 +1579,30 @@ function createRealtimeHandler(registry) {
1254
1579
  revision: 0,
1255
1580
  sql
1256
1581
  };
1582
+ watchAwareness(room);
1257
1583
  listen(room, document);
1258
- if (sql && !restores) persistRoom(room);
1584
+ if (sql && (!restores || refreshedFields)) persistRoom(room);
1259
1585
  if (dirty) scheduleSave(room);
1586
+ openRooms.set(key, room);
1587
+ if (replacedEpoch) publish(room, "reset", /* @__PURE__ */ new Uint8Array());
1588
+ requestSync(room);
1260
1589
  return room;
1261
1590
  });
1262
1591
  }
1263
1592
  function persistRoom(room) {
1264
1593
  if (!room.sql) return;
1265
- room.sql.exec("INSERT OR REPLACE INTO vitehub_realtime_documents (room_key, epoch, digest, dirty, update_blob) VALUES (?, ?, ?, ?, ?)", room.key, room.epoch, room.digest, room.dirty ? 1 : 0, Uint8Array.from(Y.encodeStateAsUpdate(room.document)).buffer);
1594
+ const row = [
1595
+ room.key,
1596
+ room.epoch,
1597
+ room.digest,
1598
+ room.dirty ? 1 : 0,
1599
+ Uint8Array.from(Y.encodeStateAsUpdate(room.document)).buffer
1600
+ ];
1601
+ try {
1602
+ room.sql.exec("INSERT OR REPLACE INTO vitehub_realtime_documents (room_key, epoch, digest, dirty, update_blob, editor_version) VALUES (?, ?, ?, ?, ?, ?)", ...row, room.editor.version ?? null);
1603
+ } catch {
1604
+ room.sql.exec("INSERT OR REPLACE INTO vitehub_realtime_documents (room_key, epoch, digest, dirty, update_blob) VALUES (?, ?, ?, ?, ?)", ...row);
1605
+ }
1266
1606
  room.sql.exec("DELETE FROM vitehub_realtime_document_updates WHERE room_key = ?", room.key);
1267
1607
  room.persistedUpdates = 0;
1268
1608
  }
@@ -1288,12 +1628,17 @@ function createRealtimeHandler(registry) {
1288
1628
  room.awareness.destroy();
1289
1629
  room.document.destroy();
1290
1630
  rooms.delete(room.key);
1631
+ if (openRooms.get(room.key) === room) openRooms.delete(room.key);
1291
1632
  inactiveMemoryRoomKeys.delete(room.key);
1292
1633
  memoryRoomKeys.delete(room.key);
1293
1634
  }
1294
1635
  /** Releases an idle room: durable rooms leave memory; clean memory rooms become reclaimable. */
1295
1636
  function releaseRoom(room) {
1296
1637
  if (room.peers.size > 0) return;
1638
+ if (room.kind === "events" && (room.bus || !room.workspace)) {
1639
+ destroyRoom(room);
1640
+ return;
1641
+ }
1297
1642
  if (room.kind === "events") {
1298
1643
  inactiveMemoryRoomKeys.delete(room.key);
1299
1644
  inactiveMemoryRoomKeys.add(room.key);
@@ -1305,6 +1650,10 @@ function createRealtimeHandler(registry) {
1305
1650
  destroyRoom(room);
1306
1651
  return;
1307
1652
  }
1653
+ if (room.bus && !room.dirty) {
1654
+ destroyRoom(room);
1655
+ return;
1656
+ }
1308
1657
  if (room.dirty) return;
1309
1658
  inactiveMemoryRoomKeys.delete(room.key);
1310
1659
  inactiveMemoryRoomKeys.add(room.key);
@@ -1389,21 +1738,72 @@ function createRealtimeHandler(registry) {
1389
1738
  enqueue(room, () => saveRoom(room, "idle", false)).catch(() => {});
1390
1739
  }, wait);
1391
1740
  }
1392
- async function reseedRoom(room, reason, loaded, preserveEdits = false) {
1741
+ /** Runs `task` under the room lock of a shared room, or at once when this instance already holds it. */
1742
+ async function underRoomLock(room, task) {
1743
+ const bus = room.bus;
1744
+ if (!bus || room.locked) return await task();
1745
+ return await bus.withRoomLock(room.key, async () => {
1746
+ room.locked = true;
1747
+ try {
1748
+ return await task();
1749
+ } finally {
1750
+ room.locked = false;
1751
+ }
1752
+ });
1753
+ }
1754
+ /**
1755
+ * `follow` re-seeds a shared room at the epoch that another instance moved its record to. It replaces the document
1756
+ * also after a concurrent edit: a room at an older epoch cannot reach the other instances.
1757
+ */
1758
+ async function reseedRoom(room, reason, loaded, preserveEdits = false, follow = false) {
1393
1759
  const revision = room.revision;
1394
- const source = loaded ?? await room.resolved.adapter.load(room.context);
1395
- const guard = await verifyDocument(room.editor, source);
1396
- const next = await seedDocument(room.editor, source, guard);
1397
- if (room.destroyed || room.revision !== revision || preserveEdits && room.dirty) return false;
1760
+ const stale = () => room.destroyed || !follow && (room.revision !== revision || preserveEdits && room.dirty);
1761
+ let source;
1762
+ let guard;
1763
+ let next;
1764
+ let epoch;
1765
+ let replaced = false;
1766
+ let dirty = false;
1767
+ const bus = room.bus;
1768
+ if (bus) {
1769
+ const shared = await underRoomLock(room, async () => {
1770
+ const source = loaded ?? await room.resolved.adapter.load(room.context);
1771
+ const guard = await verifyDocument(room.editor, source);
1772
+ if (stale()) return void 0;
1773
+ return {
1774
+ source,
1775
+ guard,
1776
+ ...await sharedDocument(bus, room.key, room.editor, source, guard)
1777
+ };
1778
+ });
1779
+ if (!shared) return false;
1780
+ ({source, guard, document: next, epoch, replaced} = shared);
1781
+ dirty = shared.dirty ?? false;
1782
+ if (room.destroyed) {
1783
+ next.destroy();
1784
+ return false;
1785
+ }
1786
+ } else {
1787
+ source = loaded ?? await room.resolved.adapter.load(room.context);
1788
+ guard = await verifyDocument(room.editor, source);
1789
+ next = await seedDocument(room.editor, source, guard);
1790
+ epoch = crypto.randomUUID();
1791
+ }
1792
+ if (!room.bus && stale()) {
1793
+ next.destroy();
1794
+ return false;
1795
+ }
1398
1796
  const previous = {
1399
1797
  awareness: room.awareness,
1400
1798
  document: room.document
1401
1799
  };
1402
1800
  const peers = [...room.peers];
1403
- room.epoch = crypto.randomUUID();
1801
+ room.epoch = epoch;
1802
+ room.unwrittenRecord = void 0;
1803
+ room.pendingRecovery = void 0;
1404
1804
  room.digest = source.digest;
1405
1805
  room.guard = guard;
1406
- room.dirty = false;
1806
+ room.dirty = dirty;
1407
1807
  room.editors.clear();
1408
1808
  room.firstDirtyAt = void 0;
1409
1809
  room.retryDelay = 0;
@@ -1413,6 +1813,9 @@ function createRealtimeHandler(registry) {
1413
1813
  previous.awareness.destroy();
1414
1814
  previous.document.destroy();
1415
1815
  persistRoom(room);
1816
+ if (dirty) scheduleSave(room);
1817
+ if (replaced) publish(room, "reset", /* @__PURE__ */ new Uint8Array());
1818
+ requestSync(room);
1416
1819
  const reset = encodeRealtimeControl({
1417
1820
  type: "reset",
1418
1821
  epoch: room.epoch,
@@ -1427,7 +1830,52 @@ function createRealtimeHandler(registry) {
1427
1830
  }
1428
1831
  return true;
1429
1832
  }
1833
+ /**
1834
+ * Saves of a shared room run one at a time across instances, under the room lock. Each first takes in the saves of
1835
+ * the other instances, so its `ifDigest` is the stored digest, unless the document changed outside the room. After
1836
+ * the save, the record holds the saved state and digest for the next instance.
1837
+ */
1430
1838
  async function saveRoom(room, reason, force) {
1839
+ const bus = room.bus;
1840
+ if (!bus) return await saveRoomNow(room, reason, force);
1841
+ try {
1842
+ return await underRoomLock(room, async () => {
1843
+ if (!await adoptSharedRecord(room, bus)) {
1844
+ if (!force) return void 0;
1845
+ throw new HTTPError({
1846
+ status: 409,
1847
+ message: "The document re-seeded on another instance. The room was re-seeded.",
1848
+ data: { code: realtimeSourceChangedCode }
1849
+ });
1850
+ }
1851
+ return await saveRoomNow(room, reason, force, async (digest, state) => {
1852
+ const record = {
1853
+ epoch: room.epoch,
1854
+ digest,
1855
+ state
1856
+ };
1857
+ room.unwrittenRecord = record;
1858
+ await writeSharedRecord(bus, room.key, record);
1859
+ room.unwrittenRecord = void 0;
1860
+ }, async (state) => {
1861
+ await writeSharedRecord(bus, room.key, {
1862
+ epoch: room.epoch,
1863
+ digest: room.digest,
1864
+ state,
1865
+ pending: true
1866
+ });
1867
+ });
1868
+ });
1869
+ } catch (error) {
1870
+ if (room.dirty && room.resolved.persistence && !room.idleTimer) {
1871
+ room.retryDelay = Math.min(Math.max(room.resolved.persistence.debounce, room.retryDelay * 2), maxSaveRetryMs);
1872
+ scheduleSave(room, room.retryDelay);
1873
+ }
1874
+ throw error;
1875
+ }
1876
+ }
1877
+ /** `onStored` gets the digest and the Yjs state of what the adapter stored, before later edits. */
1878
+ async function saveRoomNow(room, reason, force, onStored, onSubmitting) {
1431
1879
  const { adapter, persistence } = room.resolved;
1432
1880
  const editor = room.editor;
1433
1881
  if (room.guard.readOnly) {
@@ -1462,6 +1910,15 @@ function createRealtimeHandler(registry) {
1462
1910
  persistRoom(room);
1463
1911
  };
1464
1912
  try {
1913
+ try {
1914
+ checkRealtimeBody(editor, submitted);
1915
+ } catch {
1916
+ throw new HTTPError({
1917
+ status: 422,
1918
+ message: invalidDocumentMessage,
1919
+ data: { code: realtimeInvalidDocumentCode }
1920
+ });
1921
+ }
1465
1922
  const written = await readRealtimeYDoc(editor, submitted);
1466
1923
  const document = {
1467
1924
  ...written,
@@ -1469,7 +1926,12 @@ function createRealtimeHandler(registry) {
1469
1926
  };
1470
1927
  const { clean } = room.guard;
1471
1928
  if (room.digest !== null && document.body === clean.body && realtimeJsonEqual(document.fields, clean.fields)) {
1472
- writeRealtimeStatus(room.document, { error: null }, serverOrigin);
1929
+ writeRealtimeStatus(submitted, {
1930
+ digest: room.digest,
1931
+ error: null
1932
+ }, serverOrigin);
1933
+ await onStored?.(room.digest, Y.encodeStateAsUpdate(submitted));
1934
+ Y.applyUpdate(room.document, Y.encodeStateAsUpdate(submitted), serverOrigin);
1473
1935
  finishSave();
1474
1936
  return {
1475
1937
  ...readRealtimeStatus(room.document),
@@ -1477,6 +1939,7 @@ function createRealtimeHandler(registry) {
1477
1939
  };
1478
1940
  }
1479
1941
  const readsBack = await realtimeCodecReadsBack(editor, submitted, written.body);
1942
+ await onSubmitting?.(Y.encodeStateAsUpdate(submitted));
1480
1943
  let result;
1481
1944
  try {
1482
1945
  result = await adapter.save(room.context, document, {
@@ -1507,7 +1970,10 @@ function createRealtimeHandler(registry) {
1507
1970
  };
1508
1971
  if (result.stored) {
1509
1972
  const update = await diffRealtimeYDoc(editor, submitted, result.stored);
1510
- if (update.byteLength > 0) Y.applyUpdate(room.document, update, serverOrigin);
1973
+ if (update.byteLength > 0) {
1974
+ Y.applyUpdate(room.document, update, serverOrigin);
1975
+ Y.applyUpdate(submitted, update, serverOrigin);
1976
+ }
1511
1977
  }
1512
1978
  const status = {
1513
1979
  digest: result.digest,
@@ -1516,7 +1982,9 @@ function createRealtimeHandler(registry) {
1516
1982
  savedAt: (/* @__PURE__ */ new Date()).toISOString(),
1517
1983
  savedBy: user ?? null
1518
1984
  };
1519
- writeRealtimeStatus(room.document, status, serverOrigin);
1985
+ writeRealtimeStatus(submitted, status, serverOrigin);
1986
+ await onStored?.(result.digest, Y.encodeStateAsUpdate(submitted));
1987
+ Y.applyUpdate(room.document, Y.encodeStateAsUpdate(submitted), serverOrigin);
1520
1988
  finishSave();
1521
1989
  return {
1522
1990
  ...status,
@@ -1539,31 +2007,174 @@ function createRealtimeHandler(registry) {
1539
2007
  submitted.destroy();
1540
2008
  }
1541
2009
  }
2010
+ /**
2011
+ * Shows a clean room's stored file with the fields that it loads now, when they differ from the room's: a schema can
2012
+ * read the same file differently. The new fields become the clean baseline. A state over the room quota changes nothing.
2013
+ */
2014
+ function refreshFields(room, fields) {
2015
+ const map = room.document.getMap(realtimeDocumentLayout.fields);
2016
+ if (holdsFields(map, fields)) return;
2017
+ const candidate = new Y.Doc();
2018
+ try {
2019
+ Y.applyUpdate(candidate, Y.encodeStateAsUpdate(room.document));
2020
+ candidate.transact(() => writeRealtimeFields(candidate.getMap(realtimeDocumentLayout.fields), fields));
2021
+ assertRealtimeRoomStateQuota(candidate);
2022
+ } finally {
2023
+ candidate.destroy();
2024
+ }
2025
+ room.document.transact(() => writeRealtimeFields(map, fields), serverOrigin);
2026
+ room.guard = {
2027
+ ...room.guard,
2028
+ clean: {
2029
+ ...room.guard.clean,
2030
+ fields
2031
+ }
2032
+ };
2033
+ persistRoom(room);
2034
+ }
2035
+ /**
2036
+ * For a shared room, the whole refresh holds the room lock: a load from before another instance's reseed or save
2037
+ * would otherwise replace the newer record with stale state.
2038
+ */
1542
2039
  async function refreshRoom(room) {
2040
+ return await underRoomLock(room, () => refreshRoomNow(room));
2041
+ }
2042
+ async function refreshRoomNow(room) {
2043
+ if (room.bus && !await adoptSharedRecord(room, room.bus)) return {
2044
+ digest: room.digest,
2045
+ reseeded: true
2046
+ };
1543
2047
  const revision = room.revision;
1544
2048
  const loaded = await room.resolved.adapter.load(room.context);
1545
2049
  if (room.dirty || room.revision !== revision) return {
1546
2050
  digest: room.digest,
1547
2051
  reseeded: false
1548
2052
  };
1549
- if (loaded.digest === room.digest) return {
1550
- digest: room.digest,
1551
- reseeded: false
1552
- };
2053
+ if (loaded.digest === room.digest) {
2054
+ refreshFields(room, loadedFields(loaded));
2055
+ return {
2056
+ digest: room.digest,
2057
+ reseeded: false
2058
+ };
2059
+ }
1553
2060
  const reseeded = await reseedRoom(room, "source-changed", loaded, true);
1554
2061
  return {
1555
2062
  digest: room.digest,
1556
2063
  reseeded
1557
2064
  };
1558
2065
  }
1559
- /** Refreshes an open room without unsaved edits. A dirty room finds the outside change at its next save. */
1560
- async function refreshOpenRoom(definitionName, documentId) {
1561
- const pending = rooms.get(realtimeRoomKey(definitionName, documentId));
2066
+ /**
2067
+ * Refreshes an open room without unsaved edits. A dirty room finds the outside change at its next save. With a bus,
2068
+ * the rooms of the other instances refresh too, unless the call came from the bus.
2069
+ */
2070
+ async function refreshOpenRoom(definitionName, documentId, fanOut = true) {
2071
+ const key = realtimeRoomKey(definitionName, documentId);
2072
+ if (fanOut) await (await sharedBus().catch(() => void 0))?.publish({
2073
+ type: "refresh",
2074
+ room: key,
2075
+ epoch: "",
2076
+ data: /* @__PURE__ */ new Uint8Array()
2077
+ }).catch(() => {});
2078
+ const pending = rooms.get(key);
1562
2079
  const room = pending ? await pending.catch(() => void 0) : void 0;
1563
2080
  if (!room || room.kind !== "document" || room.destroyed) return false;
1564
2081
  return await enqueue(room, async () => !room.dirty && (await refreshRoom(room)).reseeded);
1565
2082
  }
1566
2083
  localRefreshers().add(new WeakRef(refreshOpenRoom));
2084
+ /** Requests that wait for a browser's answer, by request id, with the id of the peer that must answer. */
2085
+ const pendingRequests = /* @__PURE__ */ new Map();
2086
+ /**
2087
+ * The browsers in a room. Inside a Durable Object they come from its sockets and their crossws attachment (`i` is the
2088
+ * peer id, `t` the subscribed channels), which outlive hibernation; elsewhere from the open room.
2089
+ */
2090
+ function requestTargets(key, durable) {
2091
+ const channel = `vitehub:realtime:${key}`;
2092
+ if (durable) return durable.getWebSockets().flatMap((socket) => {
2093
+ const state = socket.deserializeAttachment();
2094
+ if (!state || typeof state !== "object" || !("i" in state) || typeof state.i !== "string" || !("t" in state)) return [];
2095
+ const topics = state.t;
2096
+ return topics instanceof Set && topics.has(channel) ? [{
2097
+ id: state.i,
2098
+ send: (frame) => socket.send(frame)
2099
+ }] : [];
2100
+ });
2101
+ const room = openRooms.get(key);
2102
+ return room ? [...room.peers].map((peer) => ({
2103
+ id: peer.id,
2104
+ send: (frame) => peer.send(frame)
2105
+ })) : [];
2106
+ }
2107
+ /** Asks the one browser in a room of this process or Durable Object. `requestRealtimeRoom()` calls it. */
2108
+ async function requestRoom(definitionName, documentId, body, ask, durable) {
2109
+ let definition;
2110
+ try {
2111
+ definition = await getDefinition(definitionName);
2112
+ } catch {
2113
+ return roomRequestError("REALTIME_ROOM_REQUESTS_OFF", { definition: definitionName });
2114
+ }
2115
+ if (definition.document !== false || definition.requests !== true) return roomRequestError("REALTIME_ROOM_REQUESTS_OFF", { definition: definitionName });
2116
+ if (definition.scope === "user" && ask.user === void 0) return roomRequestError("REALTIME_ROOM_REFUSED", { reason: `the Definition "${definitionName}" keeps a room per person, so the request must name one with { user }.` });
2117
+ const key = realtimeRoomKey(definitionName, documentId, roomScope(definition, ask.user ?? null));
2118
+ const deadline = Date.now() + ask.wait;
2119
+ let targets = requestTargets(key, durable);
2120
+ while (targets.length !== 1 && Date.now() < deadline && !ask.signal?.aborted) {
2121
+ await new Promise((resolve) => setTimeout(resolve, 50));
2122
+ targets = requestTargets(key, durable);
2123
+ }
2124
+ if (ask.signal?.aborted) return roomRequestError("REALTIME_ROOM_ABORTED");
2125
+ if (targets.length > 1) return roomRequestError("REALTIME_ROOM_CROWDED", { count: targets.length });
2126
+ const target = targets[0];
2127
+ if (!target) return roomRequestError(options.bus ? "REALTIME_ROOM_ELSEWHERE" : "REALTIME_ROOM_EMPTY");
2128
+ const id = crypto.randomUUID();
2129
+ return await new Promise((resolve) => {
2130
+ const finish = (result) => {
2131
+ clearTimeout(timer);
2132
+ ask.signal?.removeEventListener("abort", abort);
2133
+ pendingRequests.delete(id);
2134
+ resolve(result);
2135
+ };
2136
+ const abort = () => finish(roomRequestError("REALTIME_ROOM_ABORTED"));
2137
+ const timer = setTimeout(() => finish(roomRequestError("REALTIME_ROOM_TIMEOUT", { timeout: ask.timeout })), ask.timeout);
2138
+ ask.signal?.addEventListener("abort", abort, { once: true });
2139
+ pendingRequests.set(id, {
2140
+ peer: target.id,
2141
+ settle: finish
2142
+ });
2143
+ try {
2144
+ target.send(encodeRealtimeRequestFrame({
2145
+ kind: "request",
2146
+ id,
2147
+ body
2148
+ }));
2149
+ } catch {
2150
+ finish(roomRequestError("REALTIME_ROOM_EMPTY"));
2151
+ }
2152
+ });
2153
+ }
2154
+ localRequesters().add(new WeakRef(requestRoom));
2155
+ /** Settles the request that a browser's answer frame names, when that browser is the one asked. */
2156
+ function settleRequest(peer, data) {
2157
+ const decoder = decoding.createDecoder(data);
2158
+ let frame;
2159
+ try {
2160
+ decoding.readVarUint(decoder);
2161
+ frame = decodeRealtimeRequestFramePayload(decoder);
2162
+ } catch {
2163
+ return;
2164
+ }
2165
+ if (frame?.kind !== "answer") return;
2166
+ const pending = pendingRequests.get(frame.id);
2167
+ if (!pending || pending.peer !== peer.id) return;
2168
+ pending.settle(frame.ok ? [void 0, frame.body] : roomRequestError("REALTIME_ROOM_REFUSED", { reason: frame.why }));
2169
+ }
2170
+ const restoredPeerHandler = defineWebSocketHandler({ message(peer, message) {
2171
+ const data = message.uint8Array();
2172
+ if (data[0] === 6 && data.byteLength <= maxMessageBytes) settleRequest(peer, data);
2173
+ } });
2174
+ /** The browser asked has left: its requests fail now instead of at their timeout. */
2175
+ function settleRequestsOf(peer) {
2176
+ for (const pending of pendingRequests.values()) if (pending.peer === peer.id) pending.settle(roomRequestError("REALTIME_ROOM_EMPTY"));
2177
+ }
1567
2178
  async function checkpointRoom(room, user) {
1568
2179
  const { adapter, definition } = room.resolved;
1569
2180
  const configured = definition.history?.checkpoint;
@@ -1594,7 +2205,7 @@ function createRealtimeHandler(registry) {
1594
2205
  async function requestContext(event) {
1595
2206
  const { definitionName, documentId, searchParams, workspaceEvents } = parseRoomPath(event.req.url);
1596
2207
  const definition = await getDefinition(definitionName);
1597
- const resolved = resolveRealtimeDefinition(definition);
2208
+ const resolved = definition.document === false ? void 0 : resolveRealtimeDefinition(definition);
1598
2209
  const user = await identify(event.req, event, definitionName, definition);
1599
2210
  const access = (mode, id = workspaceEvents ? null : documentId) => allows(definition, {
1600
2211
  definition: definitionName,
@@ -1609,6 +2220,7 @@ function createRealtimeHandler(registry) {
1609
2220
  definitionName,
1610
2221
  documentId,
1611
2222
  resolved,
2223
+ scope: roomScope(definition, user?.id ?? null),
1612
2224
  searchParams,
1613
2225
  user,
1614
2226
  workspaceEvents
@@ -1623,14 +2235,19 @@ function createRealtimeHandler(registry) {
1623
2235
  status: 400,
1624
2236
  message: "Workspace events have no document to save."
1625
2237
  });
1626
- if (action === "checkpoint" && (!request.resolved.definition.history?.checkpoint || !request.resolved.adapter.checkpoint)) throw new HTTPError({ status: 404 });
2238
+ const resolved = request.resolved;
2239
+ if (!resolved) throw new HTTPError({
2240
+ status: 404,
2241
+ message: "This Realtime Definition has no document."
2242
+ });
2243
+ if (action === "checkpoint" && !resolved.definition.history?.checkpoint) throw new HTTPError({ status: 404 });
1627
2244
  if (!await request.access("read") || action !== "refresh" && !await request.access("write")) throw new HTTPError({ status: 403 });
1628
2245
  const state = action === "refresh" ? void 0 : await readRealtimeRequestState(event.req);
1629
2246
  if (state && !state.byteLength) throw new HTTPError({
1630
2247
  status: 400,
1631
2248
  message: "Realtime document state is required."
1632
2249
  });
1633
- const room = await getDocumentRoom(request.definitionName, request.documentId, request.resolved, resolveRealtimeRoomSql(event));
2250
+ const room = await getDocumentRoom(request.definitionName, request.documentId, resolved, resolveRealtimeRoomSql(event));
1634
2251
  if (action === "refresh") return await enqueue(room, async () => room.dirty ? {
1635
2252
  digest: room.digest,
1636
2253
  reseeded: false
@@ -1647,11 +2264,15 @@ function createRealtimeHandler(registry) {
1647
2264
  const websocketHandler = defineWebSocketHandler(async (event) => {
1648
2265
  const request = await requestContext(event);
1649
2266
  if (!await request.access("read")) throw new HTTPError({ status: 403 });
1650
- const writable = !request.workspaceEvents && await request.access("write");
2267
+ const writable = !request.workspaceEvents && !!request.resolved && await request.access("write");
1651
2268
  const identity = request.user ? createRealtimeIdentity({ ...request.user }) : void 0;
1652
- const room = request.workspaceEvents ? await getEventsRoom(request.definitionName) : await getDocumentRoom(request.definitionName, request.documentId, request.resolved, resolveRealtimeRoomSql(event));
2269
+ const room = request.workspaceEvents ? await getEventsRoom(JSON.stringify([request.definitionName, { workspaceEvents: true }]), true, void 0) : request.resolved ? await getDocumentRoom(request.definitionName, request.documentId, request.resolved, resolveRealtimeRoomSql(event)) : await getEventsRoom(realtimeRoomKey(request.definitionName, request.documentId, request.scope), false, resolveRealtimeRoomSql(event));
1653
2270
  const clientEpoch = request.searchParams.get("epoch");
2271
+ const otherEditor = room.kind === "document" && request.searchParams.get("editor") !== (room.editor.version ?? null);
2272
+ const clientId = request.searchParams.get("clientId");
2273
+ const awarenessClient = clientId !== null && /^\d+$/.test(clientId) && Number.isSafeInteger(Number(clientId)) ? Number(clientId) : void 0;
1654
2274
  function leave(peer) {
2275
+ settleRequestsOf(peer);
1655
2276
  if (terminalPeers.has(peer)) clearHeldUpdates(peer);
1656
2277
  else applyHeldUpdates(peer);
1657
2278
  if (!room.peers.delete(peer)) return;
@@ -1661,8 +2282,14 @@ function createRealtimeHandler(registry) {
1661
2282
  const clients = room.awarenessOwners.release(peer);
1662
2283
  if (clients.length) {
1663
2284
  awarenessProtocol.removeAwarenessStates(room.awareness, clients, peer);
1664
- peer.publish(room.channel, encodeAwarenessState(room.awareness, clients));
2285
+ const known = knownAwarenessClients(room.awareness, clients);
2286
+ if (known.length) {
2287
+ const update = awarenessProtocol.encodeAwarenessUpdate(room.awareness, known);
2288
+ peer.publish(room.channel, encodeAwareness(update));
2289
+ publish(room, "awareness", update);
2290
+ }
1665
2291
  room.awareness = compactRealtimeAwareness(room.awareness);
2292
+ watchAwareness(room);
1666
2293
  }
1667
2294
  peer.unsubscribe(room.channel);
1668
2295
  if (room.kind === "document" && room.writers.delete(peer) && room.held) {
@@ -1679,11 +2306,12 @@ function createRealtimeHandler(registry) {
1679
2306
  function applyDocumentMessage(peer, data) {
1680
2307
  if (room.kind !== "document") return;
1681
2308
  try {
1682
- const readOnly = room.guard.readOnly ? readOnlyDocumentRejection : !writable;
2309
+ const readOnly = room.guard.readOnly ? readOnlyDocumentRejection : !writable || otherEditor;
1683
2310
  const response = applyRealtimeSyncMessage(data, room.document, peer, { readOnly });
1684
2311
  if (response) peer.send(response);
1685
2312
  } catch (error) {
1686
- if (error instanceof RealtimeWriteRejected) peer.close(realtimeForbiddenWriteCloseCode, error.message);
2313
+ if (isWriteRejected(error) && otherEditor) return;
2314
+ if (isWriteRejected(error)) peer.close(realtimeForbiddenWriteCloseCode, error.message);
1687
2315
  else peer.close(4400, "Realtime document exceeds its 8 MiB room quota.");
1688
2316
  }
1689
2317
  }
@@ -1741,7 +2369,11 @@ function createRealtimeHandler(registry) {
1741
2369
  peer.close(error instanceof AwarenessOwnershipConflict ? 4500 : 4400, "Invalid awareness update.");
1742
2370
  return;
1743
2371
  }
1744
- if (clients.length) peer.publish(room.channel, encodeAwarenessState(room.awareness, clients));
2372
+ const known = knownAwarenessClients(room.awareness, clients);
2373
+ if (!known.length) return;
2374
+ const update = awarenessProtocol.encodeAwarenessUpdate(room.awareness, known);
2375
+ peer.publish(room.channel, encodeAwareness(update));
2376
+ publish(room, "awareness", update);
1745
2377
  }
1746
2378
  return {
1747
2379
  open(peer) {
@@ -1760,8 +2392,13 @@ function createRealtimeHandler(registry) {
1760
2392
  }
1761
2393
  room.peers.add(peer);
1762
2394
  peer.subscribe(room.channel);
2395
+ if (awarenessClient !== void 0 && room.awarenessOwners.claim(room.awareness, peer, awarenessClient, identity)) {
2396
+ const claim = encoding.createEncoder();
2397
+ encoding.writeVarUint(claim, awarenessClient);
2398
+ publish(room, "claim", encoding.toUint8Array(claim));
2399
+ }
1763
2400
  if (room.kind === "document") {
1764
- const reason = room.guard.readOnly ? "document" : writable ? void 0 : "access";
2401
+ const reason = room.guard.readOnly ? "document" : !writable ? "access" : otherEditor ? "version" : void 0;
1765
2402
  peer.send(encodeRealtimeControl(reason ? {
1766
2403
  type: "session",
1767
2404
  access: "read",
@@ -1782,8 +2419,16 @@ function createRealtimeHandler(registry) {
1782
2419
  if (clients.length) peer.send(encodeAwarenessState(room.awareness, clients));
1783
2420
  },
1784
2421
  message(peer, message) {
1785
- if (!room.peers.has(peer)) return;
1786
2422
  const data = message.uint8Array();
2423
+ if (data[0] === 6) {
2424
+ if (data.byteLength <= maxMessageBytes) settleRequest(peer, data);
2425
+ return;
2426
+ }
2427
+ if (!room.peers.has(peer)) return;
2428
+ if (data.byteLength === keepalivePing.byteLength && data.every((byte, index) => byte === keepalivePing[index])) {
2429
+ peer.send(realtimeKeepalivePong);
2430
+ return;
2431
+ }
1787
2432
  if (data.byteLength > maxMessageBytes) {
1788
2433
  peer.close(4400, "Realtime message exceeds 1 MiB.");
1789
2434
  return;
@@ -1797,7 +2442,7 @@ function createRealtimeHandler(registry) {
1797
2442
  return;
1798
2443
  }
1799
2444
  if (messageType === 4) {
1800
- if (room.kind !== "events") {
2445
+ if (room.kind !== "events" || !room.workspace) {
1801
2446
  peer.close(4400, "Workspace changes require the workspace room.");
1802
2447
  return;
1803
2448
  }
@@ -1826,7 +2471,9 @@ function createRealtimeHandler(registry) {
1826
2471
  peer.close(4429, "Workspace change rate limit exceeded.");
1827
2472
  return;
1828
2473
  }
1829
- peer.publish(room.channel, encodeWorkspaceChange(change));
2474
+ const frame = encodeWorkspaceChange(change);
2475
+ peer.publish(room.channel, frame);
2476
+ publish(room, "frame", frame);
1830
2477
  return;
1831
2478
  }
1832
2479
  if (messageType === 3) {
@@ -1875,7 +2522,7 @@ function createRealtimeHandler(registry) {
1875
2522
  if (syncType === syncProtocol.messageYjsSyncStep1) {
1876
2523
  const response = applyRealtimeSyncMessage(data, room.document, peer);
1877
2524
  if (response) peer.send(response);
1878
- } else if (syncType !== syncProtocol.messageYjsSyncStep2) peer.close(4400, "Document updates cannot use the workspace room.");
2525
+ } else if (syncType !== syncProtocol.messageYjsSyncStep2) peer.close(4400, room.workspace ? "Document updates cannot use the workspace room." : "This Realtime Definition has no document.");
1879
2526
  return;
1880
2527
  }
1881
2528
  if (syncType === syncProtocol.messageYjsSyncStep2 && !peerInitialSyncStep2.has(peer)) peerInitialSyncStep2.add(peer);
@@ -1900,14 +2547,28 @@ function createRealtimeHandler(registry) {
1900
2547
  }
1901
2548
  };
1902
2549
  });
1903
- const handler = defineEventHandler(async (input) => {
1904
- const event = toWebEvent(input);
2550
+ return defineEventHandler(async (event) => {
1905
2551
  const forwarded = await forwardToCloudflareDurableObject(event);
1906
2552
  if (forwarded) return forwarded;
1907
2553
  if (event.req.headers.has(internalRefreshHeader) && resolveRealtimeRoomSql(event)) {
1908
2554
  const { definitionName, documentId } = parseRoomPath(event.req.url);
1909
2555
  return { reseeded: await refreshOpenRoom(definitionName, documentId) };
1910
2556
  }
2557
+ if (event.req.headers.has("x-vitehub-realtime-request") && resolveRealtimeRoomSql(event)) {
2558
+ const { definitionName, documentId } = parseRoomPath(event.req.url);
2559
+ const input = await event.req.json().catch(() => void 0);
2560
+ const field = (name) => input && typeof input === "object" && name in input ? input[name] : void 0;
2561
+ const timeout = field("timeout");
2562
+ const wait = field("wait");
2563
+ const user = field("user");
2564
+ const context = resolveCloudflare(event)?.context;
2565
+ return toDurableRequestReply(await requestRoom(definitionName, documentId, field("body"), {
2566
+ timeout: typeof timeout === "number" && timeout > 0 ? timeout : defaultRequestTimeout,
2567
+ wait: typeof wait === "number" && wait >= 0 ? wait : defaultRequestWait,
2568
+ ...typeof user === "string" || user === null ? { user } : {}
2569
+ }, isDurableSockets(context) ? context : void 0));
2570
+ }
2571
+ if (event.req.method === "GET" && isBareRequest(event.req)) return restoredPeerHandler(event);
1911
2572
  if (event.req.headers.get("upgrade")?.toLowerCase() !== "websocket") return httpHandler(event);
1912
2573
  try {
1913
2574
  return await websocketHandler(event);
@@ -1915,44 +2576,6 @@ function createRealtimeHandler(registry) {
1915
2576
  return refuseUpgrade(event.req, error instanceof HTTPError ? error.status : 500);
1916
2577
  }
1917
2578
  });
1918
- const socketHooks = /* @__PURE__ */ new WeakMap();
1919
- const hooksOf = (peer) => {
1920
- const context = Reflect.get(peer.request, "context");
1921
- return socketHooks.get(peer.context) ?? (context instanceof Object ? socketHooks.get(context) : void 0);
1922
- };
1923
- return Object.assign(handler, { __websocket__: {
1924
- async upgrade(request) {
1925
- const durable = durableScope[durableObjectKey];
1926
- const context = { ...request.context };
1927
- if (durable) {
1928
- const platform = context._platform;
1929
- context._platform = {
1930
- ...platform,
1931
- cloudflare: {
1932
- ...platform?.cloudflare,
1933
- context: durable.state,
1934
- env: durable.env
1935
- }
1936
- };
1937
- }
1938
- const response = await handler(new H3Event(new Request(request.url, {
1939
- headers: request.headers,
1940
- method: request.method
1941
- }), context));
1942
- const hooks = response instanceof Response ? Reflect.get(response, "crossws") : void 0;
1943
- if (!hooks || typeof hooks !== "object") return response instanceof Response ? response : new Response(null, { status: 500 });
1944
- if (request.context) socketHooks.set(request.context, hooks);
1945
- return await hooks.upgrade?.(request);
1946
- },
1947
- open: (peer) => hooksOf(peer)?.open?.(peer),
1948
- message(peer, message) {
1949
- const hooks = hooksOf(peer);
1950
- if (!hooks) return peer.close(1012, "The realtime room restarted.");
1951
- return hooks.message?.(peer, message);
1952
- },
1953
- close: (peer, details) => hooksOf(peer)?.close?.(peer, details),
1954
- error: (peer, error) => hooksOf(peer)?.error?.(peer, error)
1955
- } });
1956
2579
  }
1957
2580
  //#endregion
1958
- export { RealtimeDocumentConflict, RealtimeWriteRejected, applyRealtimeAwarenessUpdate, applyRealtimeSyncMessage, assertRealtimeRoomStateQuota, bindAwarenessIdentity, claimAwarenessClientIds, compactRealtimeAwareness, containsRealtimeState, createRealtimeHandler, createRealtimeYDoc, diffRealtimeYDoc, encodeAwarenessState, encodeSyncStep1, encodeSyncUpdate, isRealtimeDocumentConflict, isRealtimeWorkspaceDocument, readRealtimeRequestState, readRealtimeStatus, readRealtimeWorkspaceDocument, readRealtimeYDoc, realtimeDocumentLayout, realtimePersistenceDefaults, realtimeRoomKey, refreshRealtimeDocument, registerRealtimeDurableObject, resolveRealtimeDefinition, restoreRealtimeDocument, workspaceDocument };
2581
+ export { RealtimeDocumentConflict, applyRealtimeAwarenessUpdate, applyRealtimeSyncMessage, assertRealtimeRoomStateQuota, bindAwarenessIdentity, blobDocument, claimAwarenessClientIds, compactRealtimeAwareness, containsRealtimeState, createRealtimeHandler, createRealtimeYDoc, diffRealtimeYDoc, encodeAwarenessState, encodeSyncStep1, encodeSyncUpdate, isRealtimeAvailable, isRealtimeDocumentConflict, isRealtimeWorkspaceDocument, readRealtimeRequestState, readRealtimeStatus, readRealtimeWorkspaceDocument, readRealtimeYDoc, realtimeDocumentLayout, realtimePersistenceDefaults, realtimeRoomKey, refreshRealtimeDocument, requestRealtimeRoom, resolveRealtimeDefinition, restoreRealtimeDocument, workspaceDocument };