@vite-hub/realtime 0.0.4 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -1,74 +1,22 @@
1
- import { _ as updateYFragment, c as realtimeSyncPendingCode, n as decodeWorkspaceChangePayload, o as readAwarenessClientIds, p as prosemirrorJSONToYDoc, r as encodeWorkspaceChange, s as realtimeCheckpointRejectedCode, t as createRealtimeEditorExtensions, u as createRealtimeIdentity, v as yDocToProsemirrorJSON } from "./editor-extensions-CZEzrJ-t.js";
2
- import { Editor } from "@tiptap/core";
3
- import * as Y from "yjs";
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";
7
+ import * as decoding from "lib0/decoding";
8
+ import * as encoding from "lib0/encoding";
4
9
  import * as awarenessProtocol from "y-protocols/awareness";
10
+ import * as Y from "yjs";
11
+ import { getViteHubErrorShape } from "@vite-hub/runtime";
12
+ import { Diagnostic } from "nostics";
5
13
  import { assertAuthOrigin } from "@vite-hub/auth/server";
6
14
  import { isWorkspaceConflict, normalizeSafeWorkspacePath, resolveWorkspaceStoreTarget, useWorkspace } from "@vite-hub/workspace";
7
- import { HTTPError, defineEventHandler, defineWebSocketHandler } from "h3";
8
- import * as decoding from "lib0/decoding";
9
- import * as encoding from "lib0/encoding";
15
+ import { H3Event, HTTPError, defineEventHandler, defineWebSocketHandler } from "h3";
10
16
  import * as syncProtocol from "y-protocols/sync";
11
- //#region src/server.ts
12
- const routePrefix = "/api/_vitehub/realtime/";
13
- const maxMessageBytes = 1024 * 1024;
14
- const maxRoomStateBytes = 8 * 1024 * 1024;
15
- const maxRoomAwarenessBytes = 8 * 1024 * 1024;
16
- const maxMemoryRooms = 128;
17
- const awarenessQueryIntervalMs = 1e4;
18
- const awarenessUpdateIntervalMs = 50;
19
- const workspaceChangeLimit = 100;
20
- const workspaceChangeWindowMs = 1e3;
21
- const syncUpdateIntervalMs = 50;
22
- const pendingCheckpointRetentionMs = 3e4;
23
- const durableUpdateCompactionInterval = 128;
24
- const messageSync = 0;
25
- const fragmentName = "default";
26
- function markdownToYDoc(markdown) {
27
- const editor = new Editor({
28
- content: markdown || {
29
- type: "doc",
30
- content: [{ type: "paragraph" }]
31
- },
32
- contentType: "markdown",
33
- extensions: createRealtimeEditorExtensions()
34
- });
35
- try {
36
- return prosemirrorJSONToYDoc(editor.schema, editor.getJSON(), fragmentName);
37
- } finally {
38
- editor.destroy();
39
- }
40
- }
41
- function yDocToMarkdown(document) {
42
- const editor = new Editor({
43
- content: yDocToProsemirrorJSON(document, fragmentName),
44
- extensions: createRealtimeEditorExtensions()
45
- });
46
- try {
47
- return editor.getMarkdown();
48
- } finally {
49
- editor.destroy();
50
- }
51
- }
52
- function replaceRealtimeDocument(document, markdown) {
53
- const editor = new Editor({
54
- content: markdown || {
55
- type: "doc",
56
- content: [{ type: "paragraph" }]
57
- },
58
- contentType: "markdown",
59
- extensions: createRealtimeEditorExtensions()
60
- });
61
- const state = Y.encodeStateVector(document);
62
- try {
63
- updateYFragment(document, document.getXmlFragment(fragmentName), editor.state.doc, {
64
- isOMark: /* @__PURE__ */ new Map(),
65
- mapping: /* @__PURE__ */ new Map()
66
- });
67
- return Y.encodeStateAsUpdate(document, state);
68
- } finally {
69
- editor.destroy();
70
- }
71
- }
17
+ import { AsyncLocalStorage } from "node:async_hooks";
18
+ //#region src/awareness.ts
19
+ const maxRoomAwarenessBytes = 8388608;
72
20
  function claimAwarenessClientIds(owners, peer, clients) {
73
21
  for (const client of clients) {
74
22
  const owner = owners.get(client);
@@ -76,44 +24,158 @@ function claimAwarenessClientIds(owners, peer, clients) {
76
24
  }
77
25
  const ownedClients = new Set([...owners].filter(([, owner]) => owner === peer).map(([client]) => client));
78
26
  for (const client of clients) ownedClients.add(client);
79
- if (ownedClients.size > 1024) throw new TypeError("Peer owns too many awareness clients.");
27
+ if (ownedClients.size > 1024) throw realtimeErrorDiagnostics.REALTIME_TOO_MANY_AWARENESS_CLIENTS();
80
28
  const claimed = clients.filter((client) => !owners.has(client));
81
29
  for (const client of clients) owners.set(client, peer);
82
30
  return claimed;
83
31
  }
84
- function realtimeRoomKey(definitionName, documentId) {
85
- return JSON.stringify([definitionName, documentId]);
86
- }
87
- var AwarenessOwnershipConflict = class extends TypeError {
32
+ var AwarenessOwnershipConflict = class AwarenessOwnershipConflict extends Diagnostic {
88
33
  constructor() {
89
- super("Awareness client id is already owned by another peer.");
34
+ const { code, docs, fix, why } = realtimeErrorDiagnostics.REALTIME_AWARENESS_OWNERSHIP_CONFLICT();
35
+ super({
36
+ code,
37
+ docs,
38
+ fix,
39
+ why
40
+ }, AwarenessOwnershipConflict);
41
+ this.name = "AwarenessOwnershipConflict";
90
42
  }
91
43
  };
92
44
  function bindAwarenessIdentity(update, identity) {
93
45
  return awarenessProtocol.modifyAwarenessUpdate(update, (state) => {
94
46
  if (state === null) return null;
95
- if (!state || typeof state !== "object" || Array.isArray(state)) throw new TypeError("Invalid awareness state.");
47
+ if (!isPlainObject(state)) throw realtimeErrorDiagnostics.REALTIME_INVALID_AWARENESS();
96
48
  return {
97
49
  ...state,
98
50
  user: identity
99
51
  };
100
52
  });
101
53
  }
102
- async function writeRealtimeDocument(workspace, documentId, document, ifDigest) {
103
- const current = ifDigest ? await workspace.fs.stat(documentId) : void 0;
104
- return await workspace.fs.writeFile(documentId, yDocToMarkdown(document), {
105
- ifDigest,
106
- mediaType: current?.mediaType,
107
- metadata: current?.metadata,
108
- preservePath: true
109
- });
54
+ function applyRealtimeAwarenessUpdate(awareness, update, origin, maxStateBytes = maxRoomAwarenessBytes) {
55
+ const candidateDocument = new Y.Doc();
56
+ const candidate = new awarenessProtocol.Awareness(candidateDocument);
57
+ candidate.setLocalState(null);
58
+ let stateBytes;
59
+ try {
60
+ const currentClients = [...awareness.getStates().keys()];
61
+ if (currentClients.length) awarenessProtocol.applyAwarenessUpdate(candidate, awarenessProtocol.encodeAwarenessUpdate(awareness, currentClients), origin);
62
+ awarenessProtocol.applyAwarenessUpdate(candidate, update, origin);
63
+ const candidateClients = [...candidate.getStates().keys()];
64
+ stateBytes = candidateClients.length ? awarenessProtocol.encodeAwarenessUpdate(candidate, candidateClients).byteLength : 0;
65
+ } finally {
66
+ candidate.destroy();
67
+ candidateDocument.destroy();
68
+ }
69
+ if (stateBytes > maxStateBytes) throw realtimeErrorDiagnostics.REALTIME_AWARENESS_TOO_LARGE();
70
+ awarenessProtocol.applyAwarenessUpdate(awareness, update, origin);
110
71
  }
111
- async function readRealtimeCheckpointState(request, maxBytes = maxRoomStateBytes) {
72
+ function compactRealtimeAwareness(awareness) {
73
+ const clients = [...awareness.getStates().keys()];
74
+ const update = clients.length ? awarenessProtocol.encodeAwarenessUpdate(awareness, clients) : void 0;
75
+ const compacted = new awarenessProtocol.Awareness(awareness.doc);
76
+ compacted.setLocalState(null);
77
+ if (update) awarenessProtocol.applyAwarenessUpdate(compacted, update, "compaction");
78
+ awareness.destroy();
79
+ return compacted;
80
+ }
81
+ /**
82
+ * Drops the entries of an awareness update that describe clients another peer owns. Stock y-websocket clients send
83
+ * every awareness change they see, other people's too, so an echo is normal and must not close the connection.
84
+ */
85
+ function dropForeignAwareness(update, owners, peer) {
86
+ const decoder = decoding.createDecoder(update);
87
+ const length = decoding.readVarUint(decoder);
88
+ if (length > 1024) throw realtimeErrorDiagnostics.REALTIME_TOO_MANY_AWARENESS_CLIENTS({});
89
+ const kept = [];
90
+ for (let index = 0; index < length; index++) {
91
+ const client = decoding.readVarUint(decoder);
92
+ const clock = decoding.readVarUint(decoder);
93
+ const state = decoding.readVarString(decoder);
94
+ const owner = owners.get(client);
95
+ if (!owner || owner === peer) kept.push([
96
+ client,
97
+ clock,
98
+ state
99
+ ]);
100
+ }
101
+ if (kept.length === length) return update;
102
+ const encoder = encoding.createEncoder();
103
+ encoding.writeVarUint(encoder, kept.length);
104
+ for (const [client, clock, state] of kept) {
105
+ encoding.writeVarUint(encoder, client);
106
+ encoding.writeVarUint(encoder, clock);
107
+ encoding.writeVarString(encoder, state);
108
+ }
109
+ return encoding.toUint8Array(encoder);
110
+ }
111
+ /** Owns peer claims and commits them only after identity binding and quota checks succeed. */
112
+ function createRealtimeAwarenessOwners(options = {}) {
113
+ const owners = /* @__PURE__ */ new Map();
114
+ const peerClients = /* @__PURE__ */ new WeakMap();
115
+ return {
116
+ apply(awareness, peer, input, identity) {
117
+ const update = dropForeignAwareness(input, owners, peer);
118
+ const clients = readAwarenessClientIds(update);
119
+ if (!clients.length) return [];
120
+ const claimed = claimAwarenessClientIds(owners, peer, clients);
121
+ try {
122
+ applyRealtimeAwarenessUpdate(awareness, identity ? bindAwarenessIdentity(update, identity) : update, peer, options.maxStateBytes);
123
+ const ownedClients = peerClients.get(peer) || /* @__PURE__ */ new Set();
124
+ for (const client of clients) ownedClients.add(client);
125
+ peerClients.set(peer, ownedClients);
126
+ return clients;
127
+ } catch (error) {
128
+ for (const client of claimed) if (owners.get(client) === peer) owners.delete(client);
129
+ throw error;
130
+ }
131
+ },
132
+ release(peer) {
133
+ const clients = [...peerClients.get(peer) || []];
134
+ peerClients.delete(peer);
135
+ for (const client of clients) if (owners.get(client) === peer) owners.delete(client);
136
+ return clients;
137
+ }
138
+ };
139
+ }
140
+ //#endregion
141
+ //#region src/transport.ts
142
+ const maxRequestStateBytes = 8388608;
143
+ const arrayBufferByteLengthGetter = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get;
144
+ const typedArrayByteLengthGetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "byteLength").get;
145
+ const typedArrayLengthGetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "length").get;
146
+ const typedArrayBufferGetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "buffer").get;
147
+ const typedArrayByteOffsetGetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "byteOffset").get;
148
+ function normalizeRealtimeStateChunk(value) {
149
+ if (ArrayBuffer.isView(value)) try {
150
+ let prototype = Object.getPrototypeOf(value);
151
+ let bytesPerElement;
152
+ while (prototype) {
153
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, "BYTES_PER_ELEMENT");
154
+ if (descriptor && "value" in descriptor) bytesPerElement = descriptor.value;
155
+ prototype = Object.getPrototypeOf(prototype);
156
+ }
157
+ if (bytesPerElement !== 1) return void 0;
158
+ const byteLength = Reflect.apply(typedArrayByteLengthGetter, value, []);
159
+ if (byteLength !== Reflect.apply(typedArrayLengthGetter, value, [])) return void 0;
160
+ const buffer = Reflect.apply(typedArrayBufferGetter, value, []);
161
+ const byteOffset = Reflect.apply(typedArrayByteOffsetGetter, value, []);
162
+ return new Uint8Array(buffer, byteOffset, byteLength);
163
+ } catch {
164
+ return;
165
+ }
166
+ try {
167
+ Reflect.apply(arrayBufferByteLengthGetter, value, []);
168
+ return new Uint8Array(value);
169
+ } catch {
170
+ return;
171
+ }
172
+ }
173
+ async function readRealtimeRequestState(request, maxBytes = maxRequestStateBytes) {
112
174
  if (Number(request.headers.get("content-length") || 0) > maxBytes) throw new HTTPError({
113
175
  status: 413,
114
- message: "Realtime checkpoint state exceeds 8 MiB."
176
+ message: "Realtime request state exceeds 8 MiB."
115
177
  });
116
- if (!request.body) return new Uint8Array();
178
+ if (!request.body) return /* @__PURE__ */ new Uint8Array();
117
179
  const reader = request.body.getReader();
118
180
  const chunks = [];
119
181
  let byteLength = 0;
@@ -121,15 +183,23 @@ async function readRealtimeCheckpointState(request, maxBytes = maxRoomStateBytes
121
183
  while (true) {
122
184
  const { done, value } = await reader.read();
123
185
  if (done) break;
124
- byteLength += value.byteLength;
186
+ const chunk = normalizeRealtimeStateChunk(value);
187
+ if (!chunk) {
188
+ reader.cancel().catch(() => {});
189
+ throw new HTTPError({
190
+ status: 400,
191
+ message: "Realtime request body contains invalid bytes."
192
+ });
193
+ }
194
+ byteLength += chunk.byteLength;
125
195
  if (byteLength > maxBytes) {
126
- await reader.cancel();
196
+ reader.cancel().catch(() => {});
127
197
  throw new HTTPError({
128
198
  status: 413,
129
- message: "Realtime checkpoint state exceeds 8 MiB."
199
+ message: "Realtime request state exceeds 8 MiB."
130
200
  });
131
201
  }
132
- chunks.push(value);
202
+ chunks.push(chunk);
133
203
  }
134
204
  } finally {
135
205
  reader.releaseLock();
@@ -142,6 +212,423 @@ async function readRealtimeCheckpointState(request, maxBytes = maxRoomStateBytes
142
212
  }
143
213
  return state;
144
214
  }
215
+ //#endregion
216
+ //#region src/workspace-document.ts
217
+ async function readRealtimeWorkspaceDocument(readable, writable, documentId) {
218
+ const stat = async () => {
219
+ try {
220
+ return await writable.fs.stat(documentId);
221
+ } catch (error) {
222
+ const shape = getViteHubErrorShape(error);
223
+ if (shape?.code === "WORKSPACE_NOT_FOUND" && shape.details?.name === void 0) return void 0;
224
+ throw error;
225
+ }
226
+ };
227
+ for (let attempt = 0; attempt < 3; attempt++) {
228
+ const before = await stat();
229
+ let markdown = "";
230
+ const source = await readable.fs.exists(documentId) ? readable.fs : before ? writable.fs : void 0;
231
+ if (source) try {
232
+ markdown = await source.readFile(documentId, { encoding: "utf8" });
233
+ } catch (error) {
234
+ if (!await stat()) continue;
235
+ throw error;
236
+ }
237
+ const after = await stat();
238
+ if (before?.digest === after?.digest) return {
239
+ baselineDigest: after?.digest,
240
+ markdown
241
+ };
242
+ }
243
+ throw new HTTPError({
244
+ status: 409,
245
+ message: "The Workspace document changed while opening its realtime room."
246
+ });
247
+ }
248
+ const checkpointQueues = /* @__PURE__ */ new Map();
249
+ async function serializeWorkspace(workspaceName, operation) {
250
+ const previous = checkpointQueues.get(workspaceName) || Promise.resolve();
251
+ let release;
252
+ const current = new Promise((resolve) => {
253
+ release = resolve;
254
+ });
255
+ checkpointQueues.set(workspaceName, current);
256
+ await previous;
257
+ try {
258
+ return await operation();
259
+ } finally {
260
+ release();
261
+ if (checkpointQueues.get(workspaceName) === current) checkpointQueues.delete(workspaceName);
262
+ }
263
+ }
264
+ /**
265
+ * Stores each Realtime document as the Markdown file at its path in a Workspace working tree.
266
+ * `history.checkpoint()` commits the working tree to Workspace history. `document: { workspace }`
267
+ * in a Realtime Definition uses this adapter.
268
+ */
269
+ function workspaceDocument(workspaceName) {
270
+ return {
271
+ kind: "workspace",
272
+ workspace: workspaceName,
273
+ async load({ documentId }) {
274
+ const current = await readRealtimeWorkspaceDocument(useWorkspace(workspaceName), useWorkspace(workspaceName, { mode: "write" }), documentId);
275
+ return {
276
+ body: current.markdown,
277
+ digest: current.baselineDigest ?? null
278
+ };
279
+ },
280
+ async save(context, document, { ifDigest }) {
281
+ const { documentId } = context;
282
+ const workspace = useWorkspace(workspaceName, { mode: "write" });
283
+ if (!(await workspace.capabilities()).conditionalWrites) throw new HTTPError({
284
+ status: 501,
285
+ message: "Realtime saves require a Workspace Store with conditional writes."
286
+ });
287
+ if (context.authority === "cloudflare" && (await resolveWorkspaceStoreTarget(workspace))?.provider === "memory") throw new HTTPError({
288
+ status: 501,
289
+ message: "Durable realtime rooms require a durable Workspace Store."
290
+ });
291
+ try {
292
+ const current = ifDigest ? await workspace.fs.stat(documentId).catch((error) => {
293
+ const shape = getViteHubErrorShape(error);
294
+ if (shape?.code === "WORKSPACE_NOT_FOUND" && shape.message.startsWith("[vitehub] Workspace path does not exist:")) throw new RealtimeDocumentConflict("The document changed in Workspace after this realtime room loaded it.");
295
+ throw error;
296
+ }) : void 0;
297
+ await workspace.fs.writeFile(documentId, document.body, {
298
+ ifDigest,
299
+ mediaType: current?.mediaType,
300
+ metadata: current?.metadata,
301
+ preservePath: true
302
+ });
303
+ } catch (error) {
304
+ if (isWorkspaceConflict(error)) throw new RealtimeDocumentConflict("The document changed in Workspace after this realtime room loaded it.");
305
+ throw error;
306
+ }
307
+ const written = await readRealtimeWorkspaceDocument(workspace, workspace, documentId);
308
+ if (!written.baselineDigest) throw realtimeErrorDiagnostics.REALTIME_MISSING_DIGEST({ operation: "save" });
309
+ return {
310
+ digest: written.baselineDigest,
311
+ stored: { body: written.markdown }
312
+ };
313
+ },
314
+ async checkpoint({ documentId }, { digest, message }) {
315
+ return await serializeWorkspace(workspaceName, async () => {
316
+ const workspace = useWorkspace(workspaceName, { mode: "write" });
317
+ const options = { message: message || `docs: checkpoint ${documentId}` };
318
+ let snapshot;
319
+ try {
320
+ try {
321
+ snapshot = await workspace.history.checkpoint(options);
322
+ } catch (error) {
323
+ if (!isWorkspaceConflict(error)) throw error;
324
+ await workspace.history.rebase({ takeRemote: [documentId] });
325
+ snapshot = await workspace.history.checkpoint(options);
326
+ }
327
+ } catch (error) {
328
+ if (isWorkspaceConflict(error)) throw new RealtimeDocumentConflict("The Workspace changed while checkpointing this realtime document.");
329
+ throw error;
330
+ }
331
+ if (snapshot.entries[documentId]?.digest !== digest) throw new RealtimeDocumentConflict("The Workspace document changed while creating its realtime checkpoint.");
332
+ return snapshot;
333
+ });
334
+ }
335
+ };
336
+ }
337
+ function isRealtimeWorkspaceDocument(adapter) {
338
+ return adapter.kind === "workspace" && "workspace" in adapter && typeof adapter.workspace === "string";
339
+ }
340
+ //#endregion
341
+ //#region src/cloudflare-sql.ts
342
+ function hasCloudflareSqlExecInternal(sql, allowOwnExec) {
343
+ if (sql === null || Object(sql) !== sql) return false;
344
+ try {
345
+ const ownExec = Object.getOwnPropertyDescriptor(sql, "exec");
346
+ if (ownExec) return allowOwnExec && "value" in ownExec && typeof ownExec.value === "function";
347
+ const prototype = Object.getPrototypeOf(sql);
348
+ if (!prototype) return false;
349
+ const findDescriptor = (key) => {
350
+ let current = prototype;
351
+ while (current && current !== Object.prototype) {
352
+ const descriptor = Object.getOwnPropertyDescriptor(current, key);
353
+ if (descriptor) return {
354
+ descriptor,
355
+ owner: current
356
+ };
357
+ current = Object.getPrototypeOf(current);
358
+ }
359
+ };
360
+ const constructorEntry = findDescriptor("constructor");
361
+ const execEntry = findDescriptor("exec");
362
+ const databaseSizeEntry = findDescriptor("databaseSize");
363
+ const constructor = constructorEntry?.descriptor.value;
364
+ const exec = execEntry?.descriptor.value;
365
+ const databaseSize = databaseSizeEntry?.descriptor.get;
366
+ if (!constructorEntry || !execEntry || !databaseSizeEntry || !databaseSize) return false;
367
+ if (typeof constructor !== "function" || typeof exec !== "function" || typeof databaseSize !== "function") return false;
368
+ if (constructor.prototype !== prototype) return false;
369
+ if (constructor === Map || constructor === Set || constructor === ArrayBuffer || constructor === DataView || constructor === Uint8Array) return false;
370
+ if (typeof URLSearchParams === "function" && constructor === URLSearchParams) return false;
371
+ if (typeof SharedArrayBuffer === "function" && constructor === SharedArrayBuffer) return false;
372
+ if (!/^function(?:\s+[\w$]+)*\s*\(\s*\)\s*\{\s*\[native\s+code\]\s*\}$/.test(Function.prototype.toString.call(databaseSize))) return false;
373
+ if (!/^(?:|databaseSize|get databaseSize|get size)$/i.test(databaseSize.name)) return false;
374
+ const hasFiniteDatabaseSize = (createReceiver) => {
375
+ try {
376
+ return Number.isFinite(Reflect.apply(databaseSize, createReceiver(), []));
377
+ } catch {
378
+ return false;
379
+ }
380
+ };
381
+ if (hasFiniteDatabaseSize(() => /* @__PURE__ */ new Map())) return false;
382
+ if (hasFiniteDatabaseSize(() => /* @__PURE__ */ new Set())) return false;
383
+ if (typeof URLSearchParams === "function" && hasFiniteDatabaseSize(() => new URLSearchParams())) return false;
384
+ if (hasFiniteDatabaseSize(() => /* @__PURE__ */ new ArrayBuffer(0))) return false;
385
+ if (hasFiniteDatabaseSize(() => /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(0)))) return false;
386
+ if (hasFiniteDatabaseSize(() => /* @__PURE__ */ new Uint8Array(0))) return false;
387
+ if (typeof SharedArrayBuffer === "function" && hasFiniteDatabaseSize(() => new SharedArrayBuffer(0))) return false;
388
+ try {
389
+ Reflect.apply(databaseSize, Object.create(prototype), []);
390
+ return false;
391
+ } catch {
392
+ return Number.isFinite(Reflect.apply(databaseSize, sql, []));
393
+ }
394
+ } catch {
395
+ return false;
396
+ }
397
+ }
398
+ /** Accept only the branded workerd SqlStorage receiver, never explicit adapters. */
399
+ function hasNativeCloudflareSql(sql) {
400
+ return hasCloudflareSqlExecInternal(sql, false);
401
+ }
402
+ //#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
+ //#region ../internal/src/runtime/request-origin.ts
574
+ function firstHeaderValue(headers, name) {
575
+ return headers.get(name)?.split(",", 1)[0]?.trim() || void 0;
576
+ }
577
+ /**
578
+ * The origin that the client used for `request`. A TLS-terminating proxy sends the client scheme in
579
+ * `X-Forwarded-Proto` and the client host in `X-Forwarded-Host`. Each proxy appends its value, so the first value wins.
580
+ * Without these headers, or with values that are not valid, the result is the origin of `request.url`.
581
+ */
582
+ function forwardedRequestOrigin(request) {
583
+ const url = new URL(request.url);
584
+ const forwardedProtocol = firstHeaderValue(request.headers, "x-forwarded-proto")?.toLowerCase();
585
+ const protocol = forwardedProtocol === "http" || forwardedProtocol === "https" ? forwardedProtocol : url.protocol.slice(0, -1);
586
+ const host = firstHeaderValue(request.headers, "x-forwarded-host") ?? url.host;
587
+ if (/[\u0000-\u001F\s/\\?#@]/.test(host)) return url.origin;
588
+ try {
589
+ return new URL(`${protocol}://${host}`).origin;
590
+ } catch {
591
+ return url.origin;
592
+ }
593
+ }
594
+ //#endregion
595
+ //#region src/server.ts
596
+ const routePrefix = "/api/_vitehub/realtime/";
597
+ const maxMessageBytes = 1048576;
598
+ const maxRoomStateBytes = 8388608;
599
+ const maxMemoryRooms = 128;
600
+ const awarenessQueryIntervalMs = 1e4;
601
+ const awarenessUpdateIntervalMs = 50;
602
+ const workspaceChangeLimit = 100;
603
+ const workspaceChangeWindowMs = 1e3;
604
+ /**
605
+ * Document updates per connection: a burst of 40, refilled at 20 per second. Typing sends one update per keystroke, so
606
+ * fast typing fits. Updates past the budget wait, merged, until it refills (a held key repeats ~30 times a second); a
607
+ * peer that holds back more than one message's worth is closed rather than having updates dropped.
608
+ */
609
+ const syncUpdateBurst = 40;
610
+ const syncUpdatesPerSecond = 20;
611
+ const durableUpdateCompactionInterval = 128;
612
+ const maxSaveRetryMs = 6e4;
613
+ const holdIntervalMs = 6e4;
614
+ const messageSync = 0;
615
+ /** Marks the request that `refreshRealtimeDocument()` sends to a Durable Object. The Worker strips it from client requests. */
616
+ 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
+ const realtimePersistenceDefaults = Object.freeze({
624
+ debounce: 2e3,
625
+ maxWait: 1e4
626
+ });
627
+ /** Origin of updates that the server writes itself: seeds, stored-form merges, and status. */
628
+ const serverOrigin = Symbol("vitehub.realtime.server");
629
+ const readOnlyDocumentMessage = "The editor cannot save this document without loss. The room is read-only.";
630
+ const readOnlyDocumentRejection = "This realtime document is read-only: the editor cannot save it without loss.";
631
+ const codecReadBackIssue = { message: "The editor cannot read back the Markdown that it saved. Some content can change when the document opens again." };
145
632
  function encodeSyncUpdate(update) {
146
633
  const encoder = encoding.createEncoder();
147
634
  encoding.writeVarUint(encoder, messageSync);
@@ -154,10 +641,20 @@ function encodeSyncStep1(document) {
154
641
  syncProtocol.writeSyncStep1(encoder, document);
155
642
  return encoding.toUint8Array(encoder);
156
643
  }
157
- function matchesRealtimeState(document, expected) {
158
- return matchesBytes(Y.encodeStateAsUpdate(document), expected);
644
+ function encodeAwarenessState(awareness, clients) {
645
+ const encoder = encoding.createEncoder();
646
+ encoding.writeVarUint(encoder, 1);
647
+ encoding.writeVarUint8Array(encoder, awarenessProtocol.encodeAwarenessUpdate(awareness, clients));
648
+ return encoding.toUint8Array(encoder);
159
649
  }
160
- function applyRealtimeSyncMessage(data, document, origin, maxStateBytes = maxRoomStateBytes) {
650
+ /** 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
+ };
657
+ function applyRealtimeSyncMessage(data, document, origin, options = {}) {
161
658
  const apply = (target) => {
162
659
  const decoder = decoding.createDecoder(data);
163
660
  decoding.readVarUint(decoder);
@@ -170,11 +667,17 @@ function applyRealtimeSyncMessage(data, document, origin, maxStateBytes = maxRoo
170
667
  decoding.readVarUint(messageDecoder);
171
668
  if (decoding.readVarUint(messageDecoder) === 0) return apply(document);
172
669
  const candidate = new Y.Doc();
173
- Y.applyUpdate(candidate, Y.encodeStateAsUpdate(document));
174
- apply(candidate);
175
- const stateBytes = Y.encodeStateAsUpdate(candidate).byteLength;
176
- candidate.destroy();
177
- if (stateBytes > maxStateBytes) throw new Error("Realtime document exceeds its 8 MiB room quota.");
670
+ try {
671
+ Y.applyUpdate(candidate, Y.encodeStateAsUpdate(document));
672
+ const before = Y.snapshot(candidate);
673
+ 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.");
677
+ if (Y.encodeStateAsUpdate(candidate).byteLength > (options.maxStateBytes ?? maxRoomStateBytes)) throw realtimeErrorDiagnostics.REALTIME_DOCUMENT_TOO_LARGE();
678
+ } finally {
679
+ candidate.destroy();
680
+ }
178
681
  return apply(document);
179
682
  }
180
683
  function assertRealtimeRoomStateQuota(document, maxStateBytes = maxRoomStateBytes) {
@@ -183,84 +686,158 @@ function assertRealtimeRoomStateQuota(document, maxStateBytes = maxRoomStateByte
183
686
  message: "Realtime document exceeds its 8 MiB room quota."
184
687
  });
185
688
  }
186
- function applyRealtimeAwarenessUpdate(awareness, update, origin, maxStateBytes = maxRoomAwarenessBytes) {
187
- const candidateDocument = new Y.Doc();
188
- const candidate = new awarenessProtocol.Awareness(candidateDocument);
189
- candidate.setLocalState(null);
190
- const currentClients = [...awareness.getStates().keys()];
191
- if (currentClients.length) awarenessProtocol.applyAwarenessUpdate(candidate, awarenessProtocol.encodeAwarenessUpdate(awareness, currentClients), origin);
192
- awarenessProtocol.applyAwarenessUpdate(candidate, update, origin);
193
- const candidateClients = [...candidate.getStates().keys()];
194
- const stateBytes = candidateClients.length ? awarenessProtocol.encodeAwarenessUpdate(candidate, candidateClients).byteLength : 0;
195
- candidate.destroy();
196
- candidateDocument.destroy();
197
- if (stateBytes > maxStateBytes) throw new Error("Realtime awareness exceeds its 8 MiB room quota.");
198
- awarenessProtocol.applyAwarenessUpdate(awareness, update, origin);
199
- }
200
- function compactRealtimeAwareness(awareness) {
201
- const clients = [...awareness.getStates().keys()];
202
- const update = clients.length ? awarenessProtocol.encodeAwarenessUpdate(awareness, clients) : void 0;
203
- const compacted = new awarenessProtocol.Awareness(awareness.doc);
204
- compacted.setLocalState(null);
205
- if (update) awarenessProtocol.applyAwarenessUpdate(compacted, update, "compaction");
206
- awareness.destroy();
207
- return compacted;
208
- }
209
- function matchesBytes(actual, expected) {
210
- return !!actual && actual.length === expected.length && actual.every((byte, index) => byte === expected[index]);
211
- }
212
- function storedUpdate(value) {
213
- if (value instanceof ArrayBuffer) return new Uint8Array(value);
214
- if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
689
+ function realtimeRoomKey(definitionName, documentId) {
690
+ return JSON.stringify([definitionName, documentId]);
215
691
  }
216
- function restoreRealtimeDocument(markdown, baselineDigest, stored) {
692
+ async function restoreRealtimeDocument(markdown, baselineDigest, stored) {
217
693
  const update = storedUpdate(stored?.update_blob);
218
694
  const storedDigest = typeof stored?.baseline_digest === "string" ? stored.baseline_digest : void 0;
219
- if (!update || storedDigest !== baselineDigest) return markdownToYDoc(markdown);
695
+ if (!update || storedDigest !== baselineDigest) return await createRealtimeYDoc(realtimeMarkdownEditor, { body: markdown });
220
696
  const document = new Y.Doc();
221
- Y.applyUpdate(document, update);
222
- return document;
697
+ try {
698
+ Y.applyUpdate(document, update);
699
+ return document;
700
+ } catch (error) {
701
+ document.destroy();
702
+ throw error;
703
+ }
223
704
  }
224
- function canRestoreRealtimeDocument(baselineDigest, stored) {
225
- const storedDigest = typeof stored?.baseline_digest === "string" ? stored.baseline_digest : void 0;
226
- return !!storedUpdate(stored?.update_blob) && storedDigest === baselineDigest;
705
+ function storedUpdate(value) {
706
+ if (ArrayBuffer.isView(value)) try {
707
+ const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
708
+ const typedBuffer = Object.getOwnPropertyDescriptor(typedArrayPrototype, "buffer")?.get;
709
+ const typedOffset = Object.getOwnPropertyDescriptor(typedArrayPrototype, "byteOffset")?.get;
710
+ const typedLength = Object.getOwnPropertyDescriptor(typedArrayPrototype, "byteLength")?.get;
711
+ let buffer;
712
+ let byteOffset;
713
+ let byteLength;
714
+ try {
715
+ buffer = typedBuffer.call(value);
716
+ byteOffset = typedOffset.call(value);
717
+ byteLength = typedLength.call(value);
718
+ } catch {
719
+ const dataViewPrototype = DataView.prototype;
720
+ buffer = Object.getOwnPropertyDescriptor(dataViewPrototype, "buffer").get.call(value);
721
+ byteOffset = Object.getOwnPropertyDescriptor(dataViewPrototype, "byteOffset").get.call(value);
722
+ byteLength = Object.getOwnPropertyDescriptor(dataViewPrototype, "byteLength").get.call(value);
723
+ }
724
+ if (!buffer || byteOffset === void 0 || byteLength === void 0) return void 0;
725
+ return new Uint8Array(buffer, byteOffset, byteLength);
726
+ } catch {
727
+ return;
728
+ }
729
+ try {
730
+ if ((Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength")?.get)?.call(value) !== void 0) return new Uint8Array(value);
731
+ } catch {
732
+ return;
733
+ }
227
734
  }
228
- async function readRealtimeWorkspaceDocument(readable, writable, documentId) {
229
- const stat = () => writable.fs.stat(documentId);
230
- for (let attempt = 0; attempt < 3; attempt++) {
231
- const before = await stat();
232
- let markdown = "";
233
- const source = await readable.fs.exists(documentId) ? readable.fs : before ? writable.fs : void 0;
234
- if (source) try {
235
- markdown = await source.readFile(documentId, { encoding: "utf8" });
236
- } catch (error) {
237
- if (!await stat()) continue;
238
- throw error;
735
+ const resolvedDefinitions = /* @__PURE__ */ new WeakMap();
736
+ function isDocumentAdapter(document) {
737
+ return "load" in document && "save" in document;
738
+ }
739
+ function duration(value, fallback, name) {
740
+ if (value === void 0) return fallback;
741
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) throw realtimeErrorDiagnostics.REALTIME_INVALID_PERSISTENCE({
742
+ name,
743
+ reason: "not-milliseconds"
744
+ });
745
+ return value;
746
+ }
747
+ /** Resolves the document adapter, editor codec, and persistence timing of a definition. */
748
+ function resolveRealtimeDefinition(definition) {
749
+ const cached = resolvedDefinitions.get(definition);
750
+ if (cached) return cached;
751
+ const document = definition.document;
752
+ const adapter = isDocumentAdapter(document) ? document : workspaceDocument(document.workspace);
753
+ const persistence = definition.persistence === false ? false : {
754
+ debounce: duration(definition.persistence?.debounce, realtimePersistenceDefaults.debounce, "debounce"),
755
+ maxWait: duration(definition.persistence?.maxWait, realtimePersistenceDefaults.maxWait, "maxWait")
756
+ };
757
+ if (persistence && persistence.maxWait < persistence.debounce) throw realtimeErrorDiagnostics.REALTIME_INVALID_PERSISTENCE({
758
+ name: "maxWait",
759
+ reason: "below-debounce"
760
+ });
761
+ const configured = definition.editor ?? realtimeMarkdownEditor;
762
+ const resolved = {
763
+ adapter,
764
+ definition,
765
+ editor: configured instanceof Function ? configured : () => configured,
766
+ persistence
767
+ };
768
+ resolvedDefinitions.set(definition, resolved);
769
+ return resolved;
770
+ }
771
+ async function verifyDocument(editor, loaded) {
772
+ const result = await editor.verify?.(loaded.body, { fields: loaded.fields });
773
+ const finalNewline = loaded.body.endsWith("\n");
774
+ const fields = Object.fromEntries(Object.entries(loaded.fields ?? {}).filter(([, value]) => value !== void 0));
775
+ return {
776
+ clean: {
777
+ body: keepRealtimeFinalNewline(result?.canonical ?? loaded.body, finalNewline),
778
+ fields
779
+ },
780
+ finalNewline,
781
+ issues: result?.issues ?? [],
782
+ readOnly: result?.writable === false
783
+ };
784
+ }
785
+ function guardStatus(guard) {
786
+ return {
787
+ error: guard.readOnly ? readOnlyDocumentMessage : null,
788
+ issues: guard.issues
789
+ };
790
+ }
791
+ 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)");
793
+ 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
+ try {
795
+ sql.exec("ALTER TABLE vitehub_realtime_document_updates ADD COLUMN client_update INTEGER NOT NULL DEFAULT 1");
796
+ return true;
797
+ } catch {
798
+ try {
799
+ sql.exec("SELECT client_update FROM vitehub_realtime_document_updates LIMIT 0").toArray();
800
+ return true;
801
+ } catch {
802
+ return false;
239
803
  }
240
- const after = await stat();
241
- if (before?.digest === after?.digest) return {
242
- baselineDigest: after?.digest,
243
- markdown
244
- };
245
804
  }
246
- throw new HTTPError({
247
- status: 409,
248
- message: "The Workspace document changed while opening its realtime room."
249
- });
250
805
  }
251
- function encodeAwarenessState(awareness, clients) {
252
- const encoder = encoding.createEncoder();
253
- encoding.writeVarUint(encoder, 1);
254
- encoding.writeVarUint8Array(encoder, awarenessProtocol.encodeAwarenessUpdate(awareness, clients));
255
- return encoding.toUint8Array(encoder);
806
+ /** Copy the pre-adapter Durable Object journal before reading the new schema. */
807
+ function migrateLegacyDocument(sql, key, clientUpdateColumn) {
808
+ if (sql.exec("SELECT room_key FROM vitehub_realtime_documents WHERE room_key = ?", key).toArray().length) return;
809
+ let legacy;
810
+ try {
811
+ legacy = sql.exec("SELECT baseline_digest, update_blob FROM vitehub_realtime_rooms WHERE room_key = ?", key).toArray()[0];
812
+ } catch {}
813
+ if (!legacy) return;
814
+ let updates = [];
815
+ try {
816
+ updates = sql.exec("SELECT update_blob FROM vitehub_realtime_updates WHERE room_key = ? ORDER BY sequence", key).toArray();
817
+ } catch {}
818
+ const update = storedUpdate(legacy.update_blob);
819
+ if (!update) return;
820
+ sql.exec("INSERT INTO vitehub_realtime_documents (room_key, epoch, digest, dirty, update_blob) VALUES (?, ?, ?, ?, ?)", key, crypto.randomUUID(), text(legacy.baseline_digest) ?? null, updates.length ? 1 : 0, Uint8Array.from(update).buffer);
821
+ for (const row of updates) {
822
+ const legacyUpdate = storedUpdate(row.update_blob);
823
+ if (!legacyUpdate) continue;
824
+ const blob = Uint8Array.from(legacyUpdate).buffer;
825
+ try {
826
+ if (!clientUpdateColumn) throw new Error("client_update column unavailable");
827
+ 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
+ }
831
+ }
256
832
  }
257
833
  function parseRoomPath(url) {
258
834
  const parsed = new URL(url);
259
835
  const path = parsed.pathname;
260
- if (!path.startsWith(routePrefix)) throw new HTTPError({ status: 404 });
836
+ const at = path.indexOf(routePrefix);
837
+ if (at === -1) throw new HTTPError({ status: 404 });
261
838
  let parts;
262
839
  try {
263
- parts = path.slice(23).split("/").map(decodeURIComponent);
840
+ parts = path.slice(at + 23).split("/").map(decodeURIComponent);
264
841
  } catch {
265
842
  throw new HTTPError({
266
843
  status: 400,
@@ -273,61 +850,191 @@ function parseRoomPath(url) {
273
850
  message: "Realtime definition and document path are required."
274
851
  });
275
852
  const documentId = documentParts.join("/");
853
+ let safePath;
276
854
  try {
277
- if (normalizeSafeWorkspacePath(documentId) !== documentId) throw new Error();
278
- } catch {
279
- throw new HTTPError({
280
- status: 400,
281
- message: "Realtime document paths must be safe Workspace paths."
282
- });
283
- }
855
+ safePath = normalizeSafeWorkspacePath(documentId);
856
+ } catch {}
857
+ if (safePath !== documentId) throw new HTTPError({
858
+ status: 400,
859
+ message: "Realtime document paths must be safe Workspace paths."
860
+ });
284
861
  return {
285
862
  definitionName,
286
863
  documentId,
864
+ searchParams: parsed.searchParams,
287
865
  workspaceEvents: parsed.searchParams.get("workspace") === "events"
288
866
  };
289
867
  }
290
- async function authorize(request, required, event) {
291
- if (!required) return;
868
+ function text(value) {
869
+ return typeof value === "string" && value ? value : void 0;
870
+ }
871
+ function toRealtimeUser(value) {
872
+ if (!value || !(value instanceof Object) || !("id" in value)) return null;
873
+ const id = text(value.id);
874
+ if (!id) return null;
875
+ const user = { id };
876
+ const name = "name" in value ? text(value.name) : void 0;
877
+ const email = "email" in value ? text(value.email) : void 0;
878
+ const image = "image" in value ? text(value.image) : void 0;
879
+ if (name) user.name = name;
880
+ if (email) user.email = email;
881
+ if (image) user.image = image;
882
+ return user;
883
+ }
884
+ async function identify(request, event, definitionName, definition) {
885
+ 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
+ const user = toRealtimeUser(await definition.identify({
892
+ definition: definitionName,
893
+ event,
894
+ request
895
+ }));
896
+ if (definition.auth && !user) throw new HTTPError({ status: 401 });
897
+ return user;
898
+ }
899
+ if (!definition.auth) return null;
292
900
  let auth;
293
901
  try {
294
902
  auth = await assertAuthOrigin(request, event);
295
903
  } catch {
296
904
  throw new HTTPError({ status: 403 });
297
905
  }
298
- const session = await auth.api.getSession({ headers: request.headers });
299
- if (!session?.user) throw new HTTPError({ status: 401 });
300
- return createRealtimeIdentity(session.user);
906
+ const user = toRealtimeUser((await auth.api.getSession({ headers: request.headers }))?.user);
907
+ if (!user) throw new HTTPError({ status: 401 });
908
+ return user;
909
+ }
910
+ async function allows(definition, context) {
911
+ if (!definition.authorize) return true;
912
+ return await definition.authorize(context) !== false;
913
+ }
914
+ function errorMessage(error) {
915
+ if (error instanceof Error && error.message) return error.message;
916
+ return "The realtime document could not be saved.";
917
+ }
918
+ const localRefreshKey = Symbol.for("vitehub.realtime.local-refresh");
919
+ const refreshScope = globalThis;
920
+ function localRefreshers() {
921
+ refreshScope[localRefreshKey] ??= /* @__PURE__ */ new Set();
922
+ return refreshScope[localRefreshKey];
923
+ }
924
+ /**
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
+ * 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
+ * CLI. A room without unsaved edits re-seeds at once and resets its clients. A room with unsaved edits finds the change
956
+ * at its next save, which also re-seeds it. A room that is not open loads the stored copy when it opens. Resolves
957
+ * whether a room re-seeded. It never throws: a failed refresh leaves the next save to find the change.
958
+ */
959
+ async function refreshRealtimeDocument(definition, documentId, options = {}) {
960
+ const binding = options.durableObjects ?? workerDurableObjects();
961
+ if (binding) return await refreshDurableRoom(binding, definition, documentId);
962
+ let reseeded = false;
963
+ for (const reference of localRefreshers()) {
964
+ const refresh = reference.deref();
965
+ if (!refresh) {
966
+ localRefreshers().delete(reference);
967
+ continue;
968
+ }
969
+ try {
970
+ if (await refresh(definition, documentId)) reseeded = true;
971
+ } catch {}
972
+ }
973
+ return reseeded;
974
+ }
975
+ /**
976
+ * On Cloudflare the rooms belong to the Durable Object, even when it shares an isolate with the Worker that calls this.
977
+ * Only the Durable Object may refresh them: from the Worker's request, a room's sockets cannot receive the reset.
978
+ */
979
+ async function refreshDurableRoom(binding, definition, documentId) {
980
+ try {
981
+ const room = documentId.split("/").map(encodeURIComponent).join("/");
982
+ const response = await binding.get(binding.idFromName(durableRoomsInstance)).fetch(new Request(`https://vitehub.internal${routePrefix}${encodeURIComponent(definition)}/${room}?document=refresh`, {
983
+ method: "POST",
984
+ headers: { [internalRefreshHeader]: "1" }
985
+ }));
986
+ const result = response.ok ? await response.json() : void 0;
987
+ return result instanceof Object && "reseeded" in result && result.reseeded === true;
988
+ } catch {
989
+ return false;
990
+ }
991
+ }
992
+ /**
993
+ * A rejected upgrade keeps its status, and carries crossws hooks that refuse the socket. Without hooks, crossws (and
994
+ * Nitro's adapters) still upgrade the request into a socket that never answers.
995
+ */
996
+ function refuseUpgrade(request, status) {
997
+ const hooks = { upgrade: () => new Response(null, { status }) };
998
+ const target = request;
999
+ target[webSocketHooksKey] = hooks;
1000
+ if (target.context) target.context[webSocketHooksKey] = hooks;
1001
+ return Object.assign(new Response(null, { status }), { crossws: hooks });
1002
+ }
1003
+ 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
+ };
301
1020
  }
302
1021
  function createRealtimeHandler(registry) {
303
1022
  const inactiveMemoryRoomKeys = /* @__PURE__ */ new Set();
304
1023
  const memoryRoomKeys = /* @__PURE__ */ new Set();
305
1024
  const rooms = /* @__PURE__ */ new Map();
306
- const peerAwarenessClients = /* @__PURE__ */ new WeakMap();
307
1025
  const peerAwarenessQueryAt = /* @__PURE__ */ new WeakMap();
308
1026
  const peerAwarenessUpdateAt = /* @__PURE__ */ new WeakMap();
309
1027
  const peerPendingAwareness = /* @__PURE__ */ new WeakMap();
310
1028
  const peerWorkspaceChanges = /* @__PURE__ */ new WeakMap();
311
1029
  const peerInitialSyncStep2 = /* @__PURE__ */ new WeakSet();
312
- const peerSyncUpdateAt = /* @__PURE__ */ new WeakMap();
313
- const workspaceCheckpointQueues = /* @__PURE__ */ new Map();
314
- async function serializeWorkspaceCheckpoint(workspaceName, operation) {
315
- const previous = workspaceCheckpointQueues.get(workspaceName) || Promise.resolve();
316
- let release;
317
- const current = new Promise((resolve) => {
318
- release = resolve;
319
- });
320
- workspaceCheckpointQueues.set(workspaceName, current);
321
- await previous;
322
- try {
323
- return await operation();
324
- } finally {
325
- release();
326
- if (workspaceCheckpointQueues.get(workspaceName) === current) workspaceCheckpointQueues.delete(workspaceName);
327
- }
328
- }
329
- async function refreshWritableWorkspace(workspaceName) {
330
- return useWorkspace(workspaceName, { mode: "write" });
1030
+ const peerSyncUpdates = /* @__PURE__ */ new WeakMap();
1031
+ const peerHeldUpdates = /* @__PURE__ */ new WeakMap();
1032
+ const terminalPeers = /* @__PURE__ */ new WeakSet();
1033
+ function clearHeldUpdates(peer) {
1034
+ const held = peerHeldUpdates.get(peer);
1035
+ if (!held) return;
1036
+ peerHeldUpdates.delete(peer);
1037
+ clearTimeout(held.timer);
331
1038
  }
332
1039
  function resolveCloudflare(event) {
333
1040
  const runtime = event.req.runtime?.cloudflare;
@@ -345,13 +1052,43 @@ function createRealtimeHandler(registry) {
345
1052
  const cloudflare = resolveCloudflare(event);
346
1053
  const context = cloudflare?.context;
347
1054
  const binding = (cloudflare?.env)?.$DurableObject;
348
- if (!binding || typeof context === "object" && context !== null && "storage" in context) return;
349
- const { definitionName, documentId, workspaceEvents } = parseRoomPath(event.req.url);
350
- const key = workspaceEvents ? JSON.stringify([definitionName, { workspaceEvents: true }]) : realtimeRoomKey(definitionName, documentId);
351
- return await binding.get(binding.idFromName(key)).fetch(event.req);
1055
+ if (!binding || !isRealtimeDurableObjectNamespace(binding) || typeof context === "object" && context !== null && "storage" in context) return;
1056
+ let request = event.req;
1057
+ if (request.headers.has(internalRefreshHeader)) {
1058
+ const headers = new Headers(request.headers);
1059
+ headers.delete(internalRefreshHeader);
1060
+ request = new Request(request, { headers });
1061
+ }
1062
+ return await binding.get(binding.idFromName(durableRoomsInstance)).fetch(request);
352
1063
  }
353
1064
  function resolveRealtimeRoomSql(event) {
354
- return (resolveCloudflare(event)?.context)?.storage?.sql;
1065
+ const context = resolveCloudflare(event)?.context;
1066
+ if (!context || typeof context !== "object" || !Object.hasOwn(context, "storage")) return void 0;
1067
+ const storageDescriptor = Object.getOwnPropertyDescriptor(context, "storage");
1068
+ if (!storageDescriptor || !("value" in storageDescriptor)) return void 0;
1069
+ const storage = storageDescriptor.value;
1070
+ if (!storage || typeof storage !== "object") return void 0;
1071
+ const readNativeSql = (descriptor, inherited = false) => {
1072
+ if ("value" in descriptor) return !inherited && hasNativeCloudflareSql(descriptor.value) ? descriptor.value : void 0;
1073
+ const getter = descriptor.get;
1074
+ if (typeof getter !== "function") return void 0;
1075
+ const source = Function.prototype.toString.call(getter);
1076
+ if (!/^function(?:\s+get(?:\s+\w+)?|\s+\w+)?\s*\(\s*\)\s*\{\s*\[native\s+code\]\s*\}$/.test(source)) return void 0;
1077
+ try {
1078
+ const sql = Reflect.get(storage, "sql");
1079
+ return hasNativeCloudflareSql(sql) ? sql : void 0;
1080
+ } catch {
1081
+ return;
1082
+ }
1083
+ };
1084
+ const descriptor = Object.getOwnPropertyDescriptor(storage, "sql");
1085
+ if (descriptor) return readNativeSql(descriptor);
1086
+ let prototype = Object.getPrototypeOf(storage);
1087
+ while (prototype && prototype !== Object.prototype) {
1088
+ const sqlDescriptor = Object.getOwnPropertyDescriptor(prototype, "sql");
1089
+ if (sqlDescriptor) return readNativeSql(sqlDescriptor, true);
1090
+ prototype = Object.getPrototypeOf(prototype);
1091
+ }
355
1092
  }
356
1093
  async function getDefinition(definitionName) {
357
1094
  const module = await (Object.hasOwn(registry, definitionName) ? registry[definitionName] : void 0)?.();
@@ -361,67 +1098,28 @@ function createRealtimeHandler(registry) {
361
1098
  });
362
1099
  return module.default;
363
1100
  }
364
- async function getRoom(definitionName, documentId, definition, sql, workspaceEvents = false) {
365
- const key = workspaceEvents ? JSON.stringify([definitionName, { workspaceEvents: true }]) : realtimeRoomKey(definitionName, documentId);
1101
+ async function reserveMemoryRoom() {
1102
+ if (memoryRoomKeys.size < maxMemoryRooms) return;
1103
+ const inactiveKey = inactiveMemoryRoomKeys.values().next().value;
1104
+ const inactive = inactiveKey ? await rooms.get(inactiveKey)?.catch(() => void 0) : void 0;
1105
+ if (inactive && inactiveMemoryRoomKeys.has(inactive.key) && inactive.peers.size === 0 && (inactive.kind === "events" || inactive.operations === 0 && !inactive.dirty)) destroyRoom(inactive);
1106
+ if (memoryRoomKeys.size >= maxMemoryRooms) throw new HTTPError({
1107
+ status: 503,
1108
+ message: "The in-memory realtime authority reached its active room limit."
1109
+ });
1110
+ }
1111
+ async function openRoom(key, sql, create) {
366
1112
  let room = rooms.get(key);
1113
+ if (!room && !sql) {
1114
+ await reserveMemoryRoom();
1115
+ room = rooms.get(key);
1116
+ }
367
1117
  if (!room) {
368
- if (!sql && memoryRoomKeys.size >= maxMemoryRooms) {
369
- const inactiveKey = inactiveMemoryRoomKeys.values().next().value;
370
- const inactiveRoom = inactiveKey ? await rooms.get(inactiveKey) : void 0;
371
- if (inactiveRoom && inactiveKey && inactiveMemoryRoomKeys.has(inactiveKey) && inactiveRoom.peers.size === 0 && !inactiveRoom.mutated && !inactiveRoom.checkpoint && !inactiveRoom.pendingCheckpoint) destroyRoom(inactiveRoom);
372
- if (memoryRoomKeys.size >= maxMemoryRooms) throw new HTTPError({
373
- status: 503,
374
- message: "The in-memory realtime authority reached its active room limit."
375
- });
376
- }
377
1118
  if (!sql) memoryRoomKeys.add(key);
378
- room = (async () => {
379
- const workspaceDocument = !workspaceEvents;
380
- const workspace = workspaceDocument ? useWorkspace(definition.document.workspace) : void 0;
381
- const writableWorkspace = workspaceDocument ? useWorkspace(definition.document.workspace, { mode: "write" }) : void 0;
382
- const initial = workspace && writableWorkspace ? await readRealtimeWorkspaceDocument(workspace, writableWorkspace, documentId) : {
383
- baselineDigest: void 0,
384
- markdown: ""
385
- };
386
- if (workspaceDocument && sql) {
387
- sql.exec("CREATE TABLE IF NOT EXISTS vitehub_realtime_rooms (room_key TEXT PRIMARY KEY, baseline_digest TEXT, update_blob BLOB NOT NULL)");
388
- sql.exec("CREATE TABLE IF NOT EXISTS vitehub_realtime_updates (sequence INTEGER PRIMARY KEY AUTOINCREMENT, room_key TEXT NOT NULL, update_blob BLOB NOT NULL)");
389
- }
390
- const stored = workspaceDocument && sql ? sql.exec("SELECT baseline_digest, update_blob FROM vitehub_realtime_rooms WHERE room_key = ?", key).toArray()[0] : void 0;
391
- const restoresStoredDocument = workspaceDocument && canRestoreRealtimeDocument(initial.baselineDigest, stored);
392
- const document = workspaceDocument ? restoreRealtimeDocument(initial.markdown, initial.baselineDigest, stored) : new Y.Doc();
393
- const storedUpdates = restoresStoredDocument && sql ? sql.exec("SELECT update_blob FROM vitehub_realtime_updates WHERE room_key = ? ORDER BY sequence", key).toArray() : [];
394
- for (const row of storedUpdates) {
395
- const update = storedUpdate(row.update_blob);
396
- if (update) Y.applyUpdate(document, update);
397
- }
398
- assertRealtimeRoomStateQuota(document);
399
- const awareness = new awarenessProtocol.Awareness(document);
400
- awareness.setLocalState(null);
401
- const value = {
402
- awareness,
403
- awarenessClientOwners: /* @__PURE__ */ new Map(),
404
- baselineDigest: initial.baselineDigest,
405
- channel: `vitehub:realtime:${key}`,
406
- document,
407
- durableReady: !!sql || !!initial.baselineDigest,
408
- key,
409
- mutated: false,
410
- peers: /* @__PURE__ */ new Set(),
411
- persistedUpdates: storedUpdates.length,
412
- sql: workspaceDocument ? sql : void 0
413
- };
414
- value.document.on("update", (update, origin) => {
415
- value.mutated = true;
416
- persistRoomUpdate(value, update);
417
- if (origin && typeof origin === "object" && "publish" in origin) origin.publish(value.channel, encodeSyncUpdate(update));
418
- });
419
- if (value.sql && !restoresStoredDocument) persistRoom(value);
420
- return value;
421
- })();
1119
+ room = create();
422
1120
  rooms.set(key, room);
423
1121
  room.catch(() => {
424
- rooms.delete(key);
1122
+ if (rooms.get(key) === room) rooms.delete(key);
425
1123
  inactiveMemoryRoomKeys.delete(key);
426
1124
  memoryRoomKeys.delete(key);
427
1125
  });
@@ -430,306 +1128,661 @@ function createRealtimeHandler(registry) {
430
1128
  inactiveMemoryRoomKeys.delete(key);
431
1129
  return value;
432
1130
  }
1131
+ function getEventsRoom(definitionName) {
1132
+ const key = JSON.stringify([definitionName, { workspaceEvents: true }]);
1133
+ return openRoom(key, void 0, async () => {
1134
+ const document = new Y.Doc();
1135
+ const awareness = new awarenessProtocol.Awareness(document);
1136
+ awareness.setLocalState(null);
1137
+ return {
1138
+ awareness,
1139
+ awarenessOwners: createRealtimeAwarenessOwners(),
1140
+ channel: `vitehub:realtime:${key}`,
1141
+ document,
1142
+ key,
1143
+ kind: "events",
1144
+ peers: /* @__PURE__ */ new Set()
1145
+ };
1146
+ });
1147
+ }
1148
+ function createAwareness(document) {
1149
+ const awareness = new awarenessProtocol.Awareness(document);
1150
+ awareness.setLocalState(null);
1151
+ return awareness;
1152
+ }
1153
+ function roomPeer(room, origin) {
1154
+ for (const peer of room.peers) if (peer === origin) return peer;
1155
+ }
1156
+ function listen(room, document) {
1157
+ document.on("update", (update, origin) => {
1158
+ if (room.document !== document) return;
1159
+ persistRoomUpdate(room, update, origin !== serverOrigin);
1160
+ const message = encodeSyncUpdate(update);
1161
+ const sender = roomPeer(room, origin);
1162
+ if (sender) sender.publish(room.channel, message);
1163
+ else for (const peer of room.peers) peer.send(message);
1164
+ if (origin !== serverOrigin) markDirty(room, sender && room.peerUsers.get(sender));
1165
+ });
1166
+ }
1167
+ function replaceDocument(room, document) {
1168
+ room.document = document;
1169
+ room.awareness = createAwareness(document);
1170
+ room.awarenessOwners = createRealtimeAwarenessOwners();
1171
+ listen(room, document);
1172
+ }
1173
+ async function seedDocument(editor, loaded, guard) {
1174
+ const document = await createRealtimeYDoc(editor, loaded);
1175
+ writeRealtimeStatus(document, {
1176
+ digest: loaded.digest,
1177
+ ...guardStatus(guard),
1178
+ savedAt: null,
1179
+ savedBy: null
1180
+ }, serverOrigin);
1181
+ assertRealtimeRoomStateQuota(document);
1182
+ return document;
1183
+ }
1184
+ function getDocumentRoom(definitionName, documentId, resolved, sql) {
1185
+ const key = realtimeRoomKey(definitionName, documentId);
1186
+ return openRoom(key, sql, async () => {
1187
+ const context = {
1188
+ authority: sql ? "cloudflare" : "memory",
1189
+ definition: definitionName,
1190
+ documentId
1191
+ };
1192
+ const editor = resolved.editor(context);
1193
+ const loaded = await resolved.adapter.load(context);
1194
+ const guard = await verifyDocument(editor, loaded);
1195
+ if (sql) {
1196
+ const clientUpdateColumn = documentTables(sql);
1197
+ migrateLegacyDocument(sql, key, clientUpdateColumn);
1198
+ }
1199
+ const stored = sql?.exec("SELECT epoch, digest, dirty, update_blob FROM vitehub_realtime_documents WHERE room_key = ?", key).toArray()[0];
1200
+ const storedDigest = text(stored?.digest) ?? null;
1201
+ const storedEpoch = text(stored?.epoch);
1202
+ const storedState = storedUpdate(stored?.update_blob);
1203
+ const restores = !!sql && !!storedState && !!storedEpoch && storedDigest === loaded.digest;
1204
+ let document;
1205
+ let persistedUpdates = 0;
1206
+ let dirty = false;
1207
+ if (restores) {
1208
+ document = new Y.Doc();
1209
+ try {
1210
+ Y.applyUpdate(document, storedState);
1211
+ let updates;
1212
+ try {
1213
+ updates = sql.exec("SELECT update_blob, client_update FROM vitehub_realtime_document_updates WHERE room_key = ? ORDER BY sequence", key).toArray();
1214
+ } catch {
1215
+ updates = sql.exec("SELECT update_blob FROM vitehub_realtime_document_updates WHERE room_key = ? ORDER BY sequence", key).toArray();
1216
+ }
1217
+ for (const row of updates) {
1218
+ const update = storedUpdate(row.update_blob);
1219
+ if (update) Y.applyUpdate(document, update);
1220
+ }
1221
+ persistedUpdates = updates.length;
1222
+ dirty = Number(stored?.dirty) === 1 || updates.some((update) => update.client_update === void 0 || Number(update.client_update) === 1);
1223
+ assertRealtimeRoomStateQuota(document);
1224
+ if (guard.readOnly || readRealtimeStatus(document).error === readOnlyDocumentMessage) writeRealtimeStatus(document, guardStatus(guard), serverOrigin);
1225
+ } catch (error) {
1226
+ document.destroy();
1227
+ throw error;
1228
+ }
1229
+ } else document = await seedDocument(editor, loaded, guard);
1230
+ const room = {
1231
+ awareness: createAwareness(document),
1232
+ awarenessOwners: createRealtimeAwarenessOwners(),
1233
+ channel: `vitehub:realtime:${key}`,
1234
+ context,
1235
+ destroyed: false,
1236
+ digest: loaded.digest,
1237
+ document,
1238
+ dirty,
1239
+ editor,
1240
+ editors: /* @__PURE__ */ new Map(),
1241
+ epoch: restores && storedEpoch ? storedEpoch : crypto.randomUUID(),
1242
+ guard,
1243
+ held: false,
1244
+ writers: /* @__PURE__ */ new Set(),
1245
+ key,
1246
+ kind: "document",
1247
+ operations: 0,
1248
+ peerUsers: /* @__PURE__ */ new WeakMap(),
1249
+ peers: /* @__PURE__ */ new Set(),
1250
+ persistedUpdates,
1251
+ queue: Promise.resolve(),
1252
+ resolved,
1253
+ retryDelay: 0,
1254
+ revision: 0,
1255
+ sql
1256
+ };
1257
+ listen(room, document);
1258
+ if (sql && !restores) persistRoom(room);
1259
+ if (dirty) scheduleSave(room);
1260
+ return room;
1261
+ });
1262
+ }
433
1263
  function persistRoom(room) {
434
- if (!room.sql || !room.durableReady) return;
435
- room.sql.exec("INSERT OR REPLACE INTO vitehub_realtime_rooms (room_key, baseline_digest, update_blob) VALUES (?, ?, ?)", room.key, room.baselineDigest ?? null, Uint8Array.from(Y.encodeStateAsUpdate(room.document)).buffer);
436
- room.sql.exec("DELETE FROM vitehub_realtime_updates WHERE room_key = ?", room.key);
1264
+ 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);
1266
+ room.sql.exec("DELETE FROM vitehub_realtime_document_updates WHERE room_key = ?", room.key);
437
1267
  room.persistedUpdates = 0;
438
1268
  }
439
- function persistRoomUpdate(room, update) {
440
- if (!room.sql || !room.durableReady) return;
441
- room.sql.exec("INSERT INTO vitehub_realtime_updates (room_key, update_blob) VALUES (?, ?)", room.key, Uint8Array.from(update).buffer);
1269
+ function persistRoomUpdate(room, update, clientUpdate) {
1270
+ if (!room.sql) return;
1271
+ const blob = Uint8Array.from(update).buffer;
1272
+ try {
1273
+ room.sql.exec("INSERT INTO vitehub_realtime_document_updates (room_key, update_blob, client_update) VALUES (?, ?, ?)", room.key, blob, clientUpdate ? 1 : 0);
1274
+ } catch {
1275
+ room.sql.exec("INSERT INTO vitehub_realtime_document_updates (room_key, update_blob) VALUES (?, ?)", room.key, blob);
1276
+ }
442
1277
  room.persistedUpdates++;
443
1278
  if (room.persistedUpdates >= durableUpdateCompactionInterval) persistRoom(room);
444
1279
  }
445
- function evictRoom(room) {
446
- if (room.peers.size > 0 || room.checkpoint || room.pendingCheckpoint) return;
447
- if (!room.sql) {
448
- if (room.mutated) return;
449
- inactiveMemoryRoomKeys.delete(room.key);
450
- inactiveMemoryRoomKeys.add(room.key);
451
- return;
452
- }
453
- destroyRoom(room);
454
- }
455
1280
  function destroyRoom(room) {
1281
+ if (room.kind === "document") {
1282
+ if (room.idleTimer) clearTimeout(room.idleTimer);
1283
+ room.idleTimer = void 0;
1284
+ if (room.holdTimer) clearInterval(room.holdTimer);
1285
+ room.holdTimer = void 0;
1286
+ room.destroyed = true;
1287
+ }
456
1288
  room.awareness.destroy();
457
1289
  room.document.destroy();
458
1290
  rooms.delete(room.key);
459
1291
  inactiveMemoryRoomKeys.delete(room.key);
460
1292
  memoryRoomKeys.delete(room.key);
461
1293
  }
462
- function clearPendingCheckpoint(room, pending) {
463
- if (room.pendingCheckpoint !== pending) return;
464
- room.pendingCheckpoint = void 0;
465
- if (room.pendingCheckpointTimer) clearTimeout(room.pendingCheckpointTimer);
466
- room.pendingCheckpointTimer = void 0;
467
- pending.submittedDocument.destroy();
468
- }
469
- function reconcilePendingCheckpoint(room, pending, content) {
470
- if (content === yDocToMarkdown(pending.submittedDocument)) return;
471
- const update = replaceRealtimeDocument(pending.submittedDocument, content);
472
- Y.applyUpdate(room.document, update);
473
- if (update.byteLength > 0) {
474
- const message = encodeSyncUpdate(update);
475
- for (const peer of room.peers) peer.send(message);
1294
+ /** Releases an idle room: durable rooms leave memory; clean memory rooms become reclaimable. */
1295
+ function releaseRoom(room) {
1296
+ if (room.peers.size > 0) return;
1297
+ if (room.kind === "events") {
1298
+ inactiveMemoryRoomKeys.delete(room.key);
1299
+ inactiveMemoryRoomKeys.add(room.key);
1300
+ return;
476
1301
  }
1302
+ if (room.operations > 0 || room.destroyed || room.held) return;
1303
+ if (room.sql) {
1304
+ persistRoom(room);
1305
+ destroyRoom(room);
1306
+ return;
1307
+ }
1308
+ if (room.dirty) return;
1309
+ inactiveMemoryRoomKeys.delete(room.key);
1310
+ inactiveMemoryRoomKeys.add(room.key);
477
1311
  }
478
- async function recoverPendingCheckpoint(room, pending) {
479
- const current = await readRealtimeWorkspaceDocument(pending.workspace, pending.workspace, pending.path);
480
- room.baselineDigest = current.baselineDigest;
481
- room.durableReady = !!room.sql || !!room.baselineDigest;
482
- reconcilePendingCheckpoint(room, pending, current.markdown);
483
- persistRoom(room);
484
- clearPendingCheckpoint(room, pending);
1312
+ function enqueue(room, operation) {
1313
+ room.operations++;
1314
+ const run = room.queue.then(() => {
1315
+ if (room.destroyed) throw new HTTPError({
1316
+ status: 409,
1317
+ message: "The realtime room closed."
1318
+ });
1319
+ return operation();
1320
+ });
1321
+ room.queue = run.then(() => {}, () => {});
1322
+ return run.finally(() => {
1323
+ room.operations--;
1324
+ releaseRoom(room);
1325
+ });
485
1326
  }
486
- function schedulePendingCheckpointExpiry(room, pending) {
487
- if (room.pendingCheckpoint !== pending || room.pendingCheckpointTimer) return;
488
- const expire = () => {
489
- room.pendingCheckpointTimer = void 0;
490
- (async () => {
491
- try {
492
- await recoverPendingCheckpoint(room, pending);
493
- } catch {
494
- if (room.pendingCheckpoint === pending) room.pendingCheckpointTimer = setTimeout(expire, pendingCheckpointRetentionMs);
495
- return;
496
- }
497
- clearPendingCheckpoint(room, pending);
498
- evictRoom(room);
499
- })();
500
- };
501
- room.pendingCheckpointTimer = setTimeout(expire, pendingCheckpointRetentionMs);
1327
+ function markDirty(room, user) {
1328
+ room.dirty = true;
1329
+ room.revision++;
1330
+ if (user) {
1331
+ room.editors.delete(user.id);
1332
+ room.editors.set(user.id, user);
1333
+ }
1334
+ scheduleSave(room);
502
1335
  }
503
- async function checkpointRoom(documentId, definition, room, state) {
504
- const configured = definition.history?.checkpoint;
505
- if (!configured) throw new HTTPError({ status: 404 });
506
- if (room.checkpoint) {
507
- const active = room.checkpoint;
508
- if (matchesBytes(room.checkpointState, state)) return await active;
509
- await active;
510
- return await checkpointRoom(documentId, definition, room, state);
511
- }
512
- const checkpoint = serializeWorkspaceCheckpoint(definition.document.workspace, async () => {
513
- let pending = room.pendingCheckpoint;
514
- if (pending && (pending.content === void 0 || pending.digest === void 0)) {
515
- await recoverPendingCheckpoint(room, pending);
516
- throw new HTTPError({
517
- status: 409,
518
- message: "The Workspace document changed while recovering its realtime checkpoint.",
519
- data: { code: realtimeCheckpointRejectedCode }
520
- });
521
- }
522
- if (pending && !matchesBytes(pending.state, state)) {
523
- const current = await readRealtimeWorkspaceDocument(pending.workspace, pending.workspace, pending.path);
524
- room.baselineDigest = current.baselineDigest;
525
- room.durableReady = !!room.sql || !!room.baselineDigest;
526
- if (current.markdown !== yDocToMarkdown(pending.submittedDocument)) {
527
- reconcilePendingCheckpoint(room, pending, current.markdown);
528
- persistRoom(room);
529
- clearPendingCheckpoint(room, pending);
530
- throw new HTTPError({
531
- status: 409,
532
- message: "The Workspace document changed while recovering its realtime checkpoint.",
533
- data: { code: realtimeCheckpointRejectedCode }
534
- });
535
- }
536
- clearPendingCheckpoint(room, pending);
537
- pending = void 0;
1336
+ /** Identified users of the writable clients, once each, in the order they joined. */
1337
+ function holdUsers(room) {
1338
+ const users = /* @__PURE__ */ new Map();
1339
+ for (const peer of room.writers) {
1340
+ const user = room.peerUsers.get(peer);
1341
+ if (user && !users.has(user.id)) users.set(user.id, user);
1342
+ }
1343
+ return [...users.values()];
1344
+ }
1345
+ /** Calls `adapter.hold()` for a room with writable clients, such as to keep a lease, and repeats it every minute. */
1346
+ function holdRoom(room) {
1347
+ const hold = room.resolved.adapter.hold;
1348
+ if (!hold || room.destroyed || room.guard.readOnly) return;
1349
+ if (room.writers.size === 0) {
1350
+ if (room.held) releaseHold(room);
1351
+ return;
1352
+ }
1353
+ room.held = true;
1354
+ room.holdTimer ??= setInterval(() => holdRoom(room), holdIntervalMs);
1355
+ enqueue(room, async () => {
1356
+ if (room.writers.size === 0) return;
1357
+ try {
1358
+ await hold.call(room.resolved.adapter, room.context, { users: holdUsers(room) });
1359
+ if (room.holdError !== void 0 && readRealtimeStatus(room.document).error === room.holdError) writeRealtimeStatus(room.document, { error: null }, serverOrigin);
1360
+ room.holdError = void 0;
1361
+ } catch (error) {
1362
+ room.holdError = errorMessage(error);
1363
+ writeRealtimeStatus(room.document, { error: room.holdError }, serverOrigin);
538
1364
  }
539
- if (!pending) {
540
- const workspace = useWorkspace(definition.document.workspace, { mode: "write" });
541
- const submittedDocument = new Y.Doc();
542
- Y.applyUpdate(submittedDocument, Y.encodeStateAsUpdate(room.document));
543
- const message = typeof configured === "object" && configured.message ? configured.message : `docs: checkpoint ${documentId}`;
544
- let path;
545
- try {
546
- path = await writeRealtimeDocument(workspace, documentId, submittedDocument, room.baselineDigest ?? null);
547
- } catch (error) {
548
- submittedDocument.destroy();
549
- if (isWorkspaceConflict(error)) throw new HTTPError({
550
- status: 409,
551
- message: "The document changed in Workspace after this realtime room opened."
552
- });
553
- room.baselineDigest = (await (await refreshWritableWorkspace(definition.document.workspace)).fs.stat(documentId))?.digest;
554
- room.durableReady = !!room.sql || !!room.baselineDigest;
555
- persistRoom(room);
556
- throw error;
557
- }
558
- try {
559
- const written = await readRealtimeWorkspaceDocument(workspace, workspace, path);
560
- if (!written.baselineDigest) throw new Error("Realtime checkpoints require Workspace file digests.");
561
- pending = {
562
- content: written.markdown,
563
- digest: written.baselineDigest,
564
- message,
565
- path,
566
- state: Uint8Array.from(state),
567
- submittedDocument,
568
- workspace
569
- };
570
- } catch (error) {
571
- room.pendingCheckpoint = {
572
- message,
573
- path,
574
- state: Uint8Array.from(state),
575
- submittedDocument,
576
- workspace
577
- };
578
- schedulePendingCheckpointExpiry(room, room.pendingCheckpoint);
579
- throw error;
580
- }
581
- room.pendingCheckpoint = pending;
1365
+ }).catch(() => {});
1366
+ }
1367
+ /** After the last writable client left: save what is left, then call `adapter.release()`. */
1368
+ function releaseHold(room) {
1369
+ if (room.holdTimer) clearInterval(room.holdTimer);
1370
+ room.holdTimer = void 0;
1371
+ if (room.dirty && room.resolved.persistence) enqueue(room, () => saveRoom(room, "leave", false)).catch(() => {});
1372
+ enqueue(room, async () => {
1373
+ if (room.writers.size > 0 || !room.held) return;
1374
+ room.held = false;
1375
+ await room.resolved.adapter.release?.(room.context);
1376
+ }).catch(() => {
1377
+ room.held = false;
1378
+ });
1379
+ }
1380
+ function scheduleSave(room, delay) {
1381
+ const persistence = room.resolved.persistence;
1382
+ if (!persistence || room.destroyed || room.guard.readOnly) return;
1383
+ const now = Date.now();
1384
+ room.firstDirtyAt ??= now;
1385
+ if (room.idleTimer) clearTimeout(room.idleTimer);
1386
+ const wait = delay ?? Math.max(0, Math.min(persistence.debounce, room.firstDirtyAt + persistence.maxWait - now));
1387
+ room.idleTimer = setTimeout(() => {
1388
+ room.idleTimer = void 0;
1389
+ enqueue(room, () => saveRoom(room, "idle", false)).catch(() => {});
1390
+ }, wait);
1391
+ }
1392
+ async function reseedRoom(room, reason, loaded, preserveEdits = false) {
1393
+ 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;
1398
+ const previous = {
1399
+ awareness: room.awareness,
1400
+ document: room.document
1401
+ };
1402
+ const peers = [...room.peers];
1403
+ room.epoch = crypto.randomUUID();
1404
+ room.digest = source.digest;
1405
+ room.guard = guard;
1406
+ room.dirty = false;
1407
+ room.editors.clear();
1408
+ room.firstDirtyAt = void 0;
1409
+ room.retryDelay = 0;
1410
+ if (room.idleTimer) clearTimeout(room.idleTimer);
1411
+ room.idleTimer = void 0;
1412
+ replaceDocument(room, next);
1413
+ previous.awareness.destroy();
1414
+ previous.document.destroy();
1415
+ persistRoom(room);
1416
+ const reset = encodeRealtimeControl({
1417
+ type: "reset",
1418
+ epoch: room.epoch,
1419
+ reason
1420
+ });
1421
+ for (const peer of peers) {
1422
+ terminalPeers.add(peer);
1423
+ clearHeldUpdates(peer);
1424
+ peer.unsubscribe(room.channel);
1425
+ peer.send(reset);
1426
+ peer.close(realtimeResetCloseCode, "The realtime document was re-seeded.");
1427
+ }
1428
+ return true;
1429
+ }
1430
+ async function saveRoom(room, reason, force) {
1431
+ const { adapter, persistence } = room.resolved;
1432
+ const editor = room.editor;
1433
+ if (room.guard.readOnly) {
1434
+ if (!force) return;
1435
+ throw new HTTPError({
1436
+ status: 409,
1437
+ message: readOnlyDocumentMessage,
1438
+ data: { code: realtimeReadOnlyCode }
1439
+ });
1440
+ }
1441
+ if (!room.dirty && !(force && room.digest === null)) {
1442
+ if (!force) return;
1443
+ return {
1444
+ ...readRealtimeStatus(room.document),
1445
+ document: await readRealtimeYDoc(editor, room.document)
1446
+ };
1447
+ }
1448
+ if (room.idleTimer) clearTimeout(room.idleTimer);
1449
+ room.idleTimer = void 0;
1450
+ room.firstDirtyAt = void 0;
1451
+ const revision = room.revision;
1452
+ const editors = [...room.editors.values()];
1453
+ const user = editors.at(-1);
1454
+ const submitted = new Y.Doc();
1455
+ Y.applyUpdate(submitted, Y.encodeStateAsUpdate(room.document));
1456
+ const finishSave = () => {
1457
+ room.retryDelay = 0;
1458
+ if (room.revision === revision) {
1459
+ room.dirty = false;
1460
+ room.editors.clear();
1461
+ } else scheduleSave(room);
1462
+ persistRoom(room);
1463
+ };
1464
+ try {
1465
+ const written = await readRealtimeYDoc(editor, submitted);
1466
+ const document = {
1467
+ ...written,
1468
+ body: keepRealtimeFinalNewline(written.body, room.guard.finalNewline)
1469
+ };
1470
+ const { clean } = room.guard;
1471
+ if (room.digest !== null && document.body === clean.body && realtimeJsonEqual(document.fields, clean.fields)) {
1472
+ writeRealtimeStatus(room.document, { error: null }, serverOrigin);
1473
+ finishSave();
1474
+ return {
1475
+ ...readRealtimeStatus(room.document),
1476
+ document
1477
+ };
582
1478
  }
583
- let snapshot;
1479
+ const readsBack = await realtimeCodecReadsBack(editor, submitted, written.body);
1480
+ let result;
584
1481
  try {
585
- try {
586
- snapshot = await pending.workspace.history.checkpoint({ message: pending.message });
587
- } catch (error) {
588
- if (!isWorkspaceConflict(error)) throw error;
589
- await pending.workspace.history.rebase({ takeRemote: [pending.path] });
590
- snapshot = await pending.workspace.history.checkpoint({ message: pending.message });
591
- }
1482
+ result = await adapter.save(room.context, document, {
1483
+ editors,
1484
+ ifDigest: room.digest,
1485
+ reason,
1486
+ user
1487
+ });
592
1488
  } catch (error) {
593
- if (isWorkspaceConflict(error)) {
594
- schedulePendingCheckpointExpiry(room, pending);
595
- throw new HTTPError({
596
- status: 409,
597
- message: "The Workspace changed while checkpointing this realtime document.",
598
- data: { code: realtimeCheckpointRejectedCode }
599
- });
600
- }
601
- schedulePendingCheckpointExpiry(room, pending);
602
- throw error;
603
- }
604
- if (snapshot.entries[pending.path]?.digest !== pending.digest) {
605
- let current;
606
- try {
607
- current = await readRealtimeWorkspaceDocument(pending.workspace, pending.workspace, pending.path);
608
- } catch (error) {
609
- pending.content = void 0;
610
- pending.digest = void 0;
611
- schedulePendingCheckpointExpiry(room, pending);
612
- throw error;
613
- }
614
- room.baselineDigest = current.baselineDigest;
615
- room.durableReady = !!room.sql || !!room.baselineDigest;
616
- reconcilePendingCheckpoint(room, pending, current.markdown);
617
- persistRoom(room);
618
- clearPendingCheckpoint(room, pending);
1489
+ if (!isRealtimeDocumentConflict(error) && !isWorkspaceConflict(error)) throw error;
1490
+ await reseedRoom(room, "source-changed");
619
1491
  throw new HTTPError({
620
1492
  status: 409,
621
- message: "The Workspace document changed while creating its realtime checkpoint.",
622
- data: { code: realtimeCheckpointRejectedCode }
1493
+ message: "The stored document changed outside this realtime room. The room was re-seeded.",
1494
+ data: { code: realtimeSourceChangedCode }
623
1495
  });
624
1496
  }
625
- room.baselineDigest = snapshot.entries[pending.path]?.digest;
626
- room.durableReady = !!room.sql || !!room.baselineDigest;
627
- reconcilePendingCheckpoint(room, pending, pending.content);
628
- room.mutated = !matchesRealtimeState(room.document, Y.encodeStateAsUpdate(pending.submittedDocument));
629
- persistRoom(room);
630
- clearPendingCheckpoint(room, pending);
1497
+ room.digest = result.digest;
1498
+ const storedBody = result.stored?.body ?? document.body;
1499
+ room.guard = {
1500
+ clean: {
1501
+ body: storedBody,
1502
+ fields: result.stored?.fields ?? document.fields
1503
+ },
1504
+ finalNewline: storedBody.endsWith("\n"),
1505
+ issues: [],
1506
+ readOnly: false
1507
+ };
1508
+ if (result.stored) {
1509
+ const update = await diffRealtimeYDoc(editor, submitted, result.stored);
1510
+ if (update.byteLength > 0) Y.applyUpdate(room.document, update, serverOrigin);
1511
+ }
1512
+ const status = {
1513
+ digest: result.digest,
1514
+ error: null,
1515
+ issues: readsBack ? result.issues ?? [] : [...result.issues ?? [], codecReadBackIssue],
1516
+ savedAt: (/* @__PURE__ */ new Date()).toISOString(),
1517
+ savedBy: user ?? null
1518
+ };
1519
+ writeRealtimeStatus(room.document, status, serverOrigin);
1520
+ finishSave();
631
1521
  return {
632
- content: pending.content,
633
- snapshot
1522
+ ...status,
1523
+ document: {
1524
+ ...document,
1525
+ ...result.stored,
1526
+ fields: result.stored?.fields ?? document.fields
1527
+ }
634
1528
  };
635
- });
636
- room.checkpoint = checkpoint;
637
- room.checkpointState = state;
638
- try {
639
- return await checkpoint;
640
- } finally {
641
- if (room.checkpoint === checkpoint) {
642
- room.checkpoint = void 0;
643
- room.checkpointState = void 0;
1529
+ } catch (error) {
1530
+ if (room.destroyed || !room.dirty) throw error;
1531
+ writeRealtimeStatus(room.document, { error: errorMessage(error) }, serverOrigin);
1532
+ if (persistence) {
1533
+ room.retryDelay = Math.min(Math.max(persistence.debounce, room.retryDelay * 2), maxSaveRetryMs);
1534
+ room.firstDirtyAt = void 0;
1535
+ scheduleSave(room, room.retryDelay);
644
1536
  }
645
- evictRoom(room);
1537
+ throw error;
1538
+ } finally {
1539
+ submitted.destroy();
646
1540
  }
647
1541
  }
648
- const httpHandler = defineEventHandler(async (event) => {
649
- if (event.req.method !== "POST" || new URL(event.req.url).searchParams.get("history") !== "checkpoint") throw new HTTPError({ status: 405 });
650
- const { definitionName, documentId, workspaceEvents } = parseRoomPath(event.req.url);
651
- if (workspaceEvents) throw new HTTPError({
652
- status: 400,
653
- message: "Workspace events cannot be checkpointed."
654
- });
1542
+ async function refreshRoom(room) {
1543
+ const revision = room.revision;
1544
+ const loaded = await room.resolved.adapter.load(room.context);
1545
+ if (room.dirty || room.revision !== revision) return {
1546
+ digest: room.digest,
1547
+ reseeded: false
1548
+ };
1549
+ if (loaded.digest === room.digest) return {
1550
+ digest: room.digest,
1551
+ reseeded: false
1552
+ };
1553
+ const reseeded = await reseedRoom(room, "source-changed", loaded, true);
1554
+ return {
1555
+ digest: room.digest,
1556
+ reseeded
1557
+ };
1558
+ }
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));
1562
+ const room = pending ? await pending.catch(() => void 0) : void 0;
1563
+ if (!room || room.kind !== "document" || room.destroyed) return false;
1564
+ return await enqueue(room, async () => !room.dirty && (await refreshRoom(room)).reseeded);
1565
+ }
1566
+ localRefreshers().add(new WeakRef(refreshOpenRoom));
1567
+ async function checkpointRoom(room, user) {
1568
+ const { adapter, definition } = room.resolved;
1569
+ const configured = definition.history?.checkpoint;
1570
+ const saved = await saveRoom(room, "request", true);
1571
+ if (!saved.digest) throw realtimeErrorDiagnostics.REALTIME_MISSING_DIGEST({ operation: "checkpoint" });
1572
+ let snapshot;
1573
+ try {
1574
+ snapshot = await adapter.checkpoint(room.context, {
1575
+ digest: saved.digest,
1576
+ message: configured === true ? void 0 : configured?.message,
1577
+ user: user ?? saved.savedBy ?? void 0
1578
+ });
1579
+ } catch (error) {
1580
+ if (!isRealtimeDocumentConflict(error) && !isWorkspaceConflict(error)) throw error;
1581
+ await reseedRoom(room, "source-changed");
1582
+ throw new HTTPError({
1583
+ status: 409,
1584
+ message: "The stored document changed while checkpointing. The room was re-seeded.",
1585
+ data: { code: realtimeSourceChangedCode }
1586
+ });
1587
+ }
1588
+ return {
1589
+ ...saved,
1590
+ digest: saved.digest,
1591
+ snapshot
1592
+ };
1593
+ }
1594
+ async function requestContext(event) {
1595
+ const { definitionName, documentId, searchParams, workspaceEvents } = parseRoomPath(event.req.url);
655
1596
  const definition = await getDefinition(definitionName);
656
- await authorize(event.req, definition.auth, event);
657
- if (!definition.history?.checkpoint) throw new HTTPError({ status: 404 });
658
- const workspace = useWorkspace(definition.document.workspace, { mode: "write" });
659
- if (!(await workspace.capabilities()).conditionalWrites) throw new HTTPError({
660
- status: 501,
661
- message: "Realtime checkpoints require a Workspace Store with conditional writes."
1597
+ const resolved = resolveRealtimeDefinition(definition);
1598
+ const user = await identify(event.req, event, definitionName, definition);
1599
+ const access = (mode, id = workspaceEvents ? null : documentId) => allows(definition, {
1600
+ definition: definitionName,
1601
+ documentId: id,
1602
+ event,
1603
+ mode,
1604
+ request: event.req,
1605
+ user
662
1606
  });
663
- const sql = resolveRealtimeRoomSql(event);
664
- if (sql && (await resolveWorkspaceStoreTarget(workspace))?.provider === "memory") throw new HTTPError({
665
- status: 501,
666
- message: "Durable realtime checkpoints require a durable Workspace Store."
1607
+ return {
1608
+ access,
1609
+ definitionName,
1610
+ documentId,
1611
+ resolved,
1612
+ searchParams,
1613
+ user,
1614
+ workspaceEvents
1615
+ };
1616
+ }
1617
+ const httpHandler = defineEventHandler(async (event) => {
1618
+ const url = new URL(event.req.url);
1619
+ const action = url.searchParams.get("history") === "checkpoint" ? "checkpoint" : url.searchParams.get("document");
1620
+ if (event.req.method !== "POST" || action !== "checkpoint" && action !== "save" && action !== "refresh") throw new HTTPError({ status: 405 });
1621
+ const request = await requestContext(event);
1622
+ if (request.workspaceEvents) throw new HTTPError({
1623
+ status: 400,
1624
+ message: "Workspace events have no document to save."
667
1625
  });
668
- const state = await readRealtimeCheckpointState(event.req);
669
- if (!state.byteLength) throw new HTTPError({
1626
+ if (action === "checkpoint" && (!request.resolved.definition.history?.checkpoint || !request.resolved.adapter.checkpoint)) throw new HTTPError({ status: 404 });
1627
+ if (!await request.access("read") || action !== "refresh" && !await request.access("write")) throw new HTTPError({ status: 403 });
1628
+ const state = action === "refresh" ? void 0 : await readRealtimeRequestState(event.req);
1629
+ if (state && !state.byteLength) throw new HTTPError({
670
1630
  status: 400,
671
- message: "Realtime checkpoint state is required."
1631
+ message: "Realtime document state is required."
672
1632
  });
673
- const room = await getRoom(definitionName, documentId, definition, sql, workspaceEvents);
674
- if (!matchesRealtimeState(room.document, state)) {
675
- evictRoom(room);
676
- throw new HTTPError({
1633
+ const room = await getDocumentRoom(request.definitionName, request.documentId, request.resolved, resolveRealtimeRoomSql(event));
1634
+ if (action === "refresh") return await enqueue(room, async () => room.dirty ? {
1635
+ digest: room.digest,
1636
+ reseeded: false
1637
+ } : refreshRoom(room));
1638
+ return await enqueue(room, async () => {
1639
+ if (!containsRealtimeState(room.document, state)) throw new HTTPError({
677
1640
  status: 409,
678
1641
  message: "The realtime document is still syncing.",
679
1642
  data: { code: realtimeSyncPendingCode }
680
1643
  });
681
- }
682
- return await checkpointRoom(documentId, definition, room, state);
1644
+ return action === "save" ? await saveRoom(room, "request", true) : await checkpointRoom(room, request.user);
1645
+ });
683
1646
  });
684
1647
  const websocketHandler = defineWebSocketHandler(async (event) => {
685
- const { definitionName, documentId, workspaceEvents } = parseRoomPath(event.req.url);
686
- const definition = await getDefinition(definitionName);
687
- const identity = await authorize(event.req, definition.auth, event);
688
- const room = await getRoom(definitionName, documentId, definition, resolveRealtimeRoomSql(event), workspaceEvents);
1648
+ const request = await requestContext(event);
1649
+ if (!await request.access("read")) throw new HTTPError({ status: 403 });
1650
+ const writable = !request.workspaceEvents && await request.access("write");
1651
+ 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));
1653
+ const clientEpoch = request.searchParams.get("epoch");
689
1654
  function leave(peer) {
1655
+ if (terminalPeers.has(peer)) clearHeldUpdates(peer);
1656
+ else applyHeldUpdates(peer);
690
1657
  if (!room.peers.delete(peer)) return;
691
1658
  const pendingAwareness = peerPendingAwareness.get(peer);
692
1659
  if (pendingAwareness) clearTimeout(pendingAwareness.timer);
693
1660
  peerPendingAwareness.delete(peer);
694
- const clients = [...peerAwarenessClients.get(peer) || []];
695
- peerAwarenessClients.delete(peer);
1661
+ const clients = room.awarenessOwners.release(peer);
696
1662
  if (clients.length) {
697
- for (const client of clients) if (room.awarenessClientOwners.get(client) === peer) room.awarenessClientOwners.delete(client);
698
1663
  awarenessProtocol.removeAwarenessStates(room.awareness, clients, peer);
699
1664
  peer.publish(room.channel, encodeAwarenessState(room.awareness, clients));
700
1665
  room.awareness = compactRealtimeAwareness(room.awareness);
701
1666
  }
702
1667
  peer.unsubscribe(room.channel);
703
- evictRoom(room);
1668
+ if (room.kind === "document" && room.writers.delete(peer) && room.held) {
1669
+ if (room.writers.size === 0) releaseHold(room);
1670
+ else holdRoom(room);
1671
+ return;
1672
+ }
1673
+ if (room.kind === "document" && room.peers.size === 0 && room.dirty && room.resolved.persistence) {
1674
+ enqueue(room, () => saveRoom(room, "leave", false)).catch(() => {});
1675
+ return;
1676
+ }
1677
+ releaseRoom(room);
1678
+ }
1679
+ function applyDocumentMessage(peer, data) {
1680
+ if (room.kind !== "document") return;
1681
+ try {
1682
+ const readOnly = room.guard.readOnly ? readOnlyDocumentRejection : !writable;
1683
+ const response = applyRealtimeSyncMessage(data, room.document, peer, { readOnly });
1684
+ if (response) peer.send(response);
1685
+ } catch (error) {
1686
+ if (error instanceof RealtimeWriteRejected) peer.close(realtimeForbiddenWriteCloseCode, error.message);
1687
+ else peer.close(4400, "Realtime document exceeds its 8 MiB room quota.");
1688
+ }
1689
+ }
1690
+ function refillUpdates(peer) {
1691
+ const now = Date.now();
1692
+ const bucket = peerSyncUpdates.get(peer) ?? {
1693
+ at: now,
1694
+ tokens: syncUpdateBurst
1695
+ };
1696
+ bucket.tokens = Math.min(syncUpdateBurst, bucket.tokens + (now - bucket.at) * syncUpdatesPerSecond / 1e3);
1697
+ bucket.at = now;
1698
+ peerSyncUpdates.set(peer, bucket);
1699
+ return bucket;
1700
+ }
1701
+ function holdUpdate(peer, update, bucket) {
1702
+ const held = peerHeldUpdates.get(peer);
1703
+ const bytes = (held?.bytes ?? 0) + update.byteLength;
1704
+ if (bytes > maxMessageBytes) {
1705
+ terminalPeers.add(peer);
1706
+ clearHeldUpdates(peer);
1707
+ peer.close(1013, "Realtime updates are arriving too quickly.");
1708
+ return;
1709
+ }
1710
+ if (held) {
1711
+ held.updates.push(update);
1712
+ held.bytes = bytes;
1713
+ return;
1714
+ }
1715
+ const wait = Math.ceil((1 - bucket.tokens) * 1e3 / syncUpdatesPerSecond);
1716
+ peerHeldUpdates.set(peer, {
1717
+ bytes,
1718
+ timer: setTimeout(() => applyHeldUpdates(peer), wait),
1719
+ updates: [update]
1720
+ });
1721
+ }
1722
+ /** Applies the updates a peer sent past its budget as one merged update, for one token. */
1723
+ function applyHeldUpdates(peer) {
1724
+ if (terminalPeers.has(peer)) {
1725
+ clearHeldUpdates(peer);
1726
+ return;
1727
+ }
1728
+ const held = peerHeldUpdates.get(peer);
1729
+ if (!held) return;
1730
+ peerHeldUpdates.delete(peer);
1731
+ clearTimeout(held.timer);
1732
+ const bucket = refillUpdates(peer);
1733
+ bucket.tokens = Math.max(0, bucket.tokens - 1);
1734
+ applyDocumentMessage(peer, encodeSyncUpdate(held.updates.length === 1 ? held.updates[0] : Y.mergeUpdates(held.updates)));
704
1735
  }
705
1736
  function applyAwareness(peer, input) {
706
- let update = input;
707
1737
  let clients;
708
- let claimed = [];
709
1738
  try {
710
- clients = readAwarenessClientIds(update);
711
- claimed = claimAwarenessClientIds(room.awarenessClientOwners, peer, clients);
712
- if (identity) update = bindAwarenessIdentity(update, identity);
713
- applyRealtimeAwarenessUpdate(room.awareness, update, peer);
714
- const ownedClients = peerAwarenessClients.get(peer) || /* @__PURE__ */ new Set();
715
- for (const client of clients) ownedClients.add(client);
716
- peerAwarenessClients.set(peer, ownedClients);
1739
+ clients = room.awarenessOwners.apply(room.awareness, peer, input, identity);
717
1740
  } catch (error) {
718
- for (const client of claimed) if (room.awarenessClientOwners.get(client) === peer) room.awarenessClientOwners.delete(client);
719
1741
  peer.close(error instanceof AwarenessOwnershipConflict ? 4500 : 4400, "Invalid awareness update.");
720
1742
  return;
721
1743
  }
722
- peer.publish(room.channel, encodeAwarenessState(room.awareness, clients));
1744
+ if (clients.length) peer.publish(room.channel, encodeAwarenessState(room.awareness, clients));
723
1745
  }
724
1746
  return {
725
1747
  open(peer) {
1748
+ if (room.kind === "document") {
1749
+ if (clientEpoch && clientEpoch !== room.epoch) {
1750
+ peer.send(encodeRealtimeControl({
1751
+ type: "reset",
1752
+ epoch: room.epoch,
1753
+ reason: "stale"
1754
+ }));
1755
+ peer.close(realtimeResetCloseCode, "The realtime document was re-seeded.");
1756
+ releaseRoom(room);
1757
+ return;
1758
+ }
1759
+ if (request.user) room.peerUsers.set(peer, request.user);
1760
+ }
726
1761
  room.peers.add(peer);
727
1762
  peer.subscribe(room.channel);
1763
+ if (room.kind === "document") {
1764
+ const reason = room.guard.readOnly ? "document" : writable ? void 0 : "access";
1765
+ peer.send(encodeRealtimeControl(reason ? {
1766
+ type: "session",
1767
+ access: "read",
1768
+ epoch: room.epoch,
1769
+ reason
1770
+ } : {
1771
+ type: "session",
1772
+ access: "write",
1773
+ epoch: room.epoch
1774
+ }));
1775
+ if (!reason) {
1776
+ room.writers.add(peer);
1777
+ holdRoom(room);
1778
+ }
1779
+ }
728
1780
  peer.send(encodeSyncStep1(room.document));
729
1781
  const clients = [...room.awareness.getStates().keys()];
730
1782
  if (clients.length) peer.send(encodeAwarenessState(room.awareness, clients));
731
1783
  },
732
1784
  message(peer, message) {
1785
+ if (!room.peers.has(peer)) return;
733
1786
  const data = message.uint8Array();
734
1787
  if (data.byteLength > maxMessageBytes) {
735
1788
  peer.close(4400, "Realtime message exceeds 1 MiB.");
@@ -744,7 +1797,7 @@ function createRealtimeHandler(registry) {
744
1797
  return;
745
1798
  }
746
1799
  if (messageType === 4) {
747
- if (!workspaceEvents) {
1800
+ if (room.kind !== "events") {
748
1801
  peer.close(4400, "Workspace changes require the workspace room.");
749
1802
  return;
750
1803
  }
@@ -803,7 +1856,7 @@ function createRealtimeHandler(registry) {
803
1856
  timer: setTimeout(() => {
804
1857
  peerPendingAwareness.delete(peer);
805
1858
  peerAwarenessUpdateAt.set(peer, Date.now());
806
- applyAwareness(peer, next.update);
1859
+ if (room.peers.has(peer)) applyAwareness(peer, next.update);
807
1860
  }, awarenessUpdateIntervalMs - (now - previous)),
808
1861
  update
809
1862
  };
@@ -818,7 +1871,7 @@ function createRealtimeHandler(registry) {
818
1871
  if (messageType !== messageSync) return;
819
1872
  try {
820
1873
  const syncType = decoding.readVarUint(decoder);
821
- if (workspaceEvents) {
1874
+ if (room.kind === "events") {
822
1875
  if (syncType === syncProtocol.messageYjsSyncStep1) {
823
1876
  const response = applyRealtimeSyncMessage(data, room.document, peer);
824
1877
  if (response) peer.send(response);
@@ -827,18 +1880,16 @@ function createRealtimeHandler(registry) {
827
1880
  }
828
1881
  if (syncType === syncProtocol.messageYjsSyncStep2 && !peerInitialSyncStep2.has(peer)) peerInitialSyncStep2.add(peer);
829
1882
  else if (syncType === syncProtocol.messageYjsSyncStep2 || syncType === syncProtocol.messageYjsUpdate) {
830
- const now = Date.now();
831
- const previous = peerSyncUpdateAt.get(peer);
832
- if (previous !== void 0 && now - previous < syncUpdateIntervalMs) {
833
- peer.close(1013, "Realtime updates are arriving too quickly.");
1883
+ const bucket = refillUpdates(peer);
1884
+ if (peerHeldUpdates.has(peer) || bucket.tokens < 1) {
1885
+ holdUpdate(peer, decoding.readVarUint8Array(decoder), bucket);
834
1886
  return;
835
1887
  }
836
- peerSyncUpdateAt.set(peer, now);
1888
+ bucket.tokens--;
837
1889
  }
838
- const response = applyRealtimeSyncMessage(data, room.document, peer);
839
- if (response) peer.send(response);
1890
+ applyDocumentMessage(peer, data);
840
1891
  } catch {
841
- peer.close(4400, "Realtime document exceeds its 8 MiB room quota.");
1892
+ peer.close(4400, "Invalid realtime message.");
842
1893
  }
843
1894
  },
844
1895
  close(peer) {
@@ -849,11 +1900,59 @@ function createRealtimeHandler(registry) {
849
1900
  }
850
1901
  };
851
1902
  });
852
- return defineEventHandler(async (event) => {
1903
+ const handler = defineEventHandler(async (input) => {
1904
+ const event = toWebEvent(input);
853
1905
  const forwarded = await forwardToCloudflareDurableObject(event);
854
1906
  if (forwarded) return forwarded;
855
- return event.req.headers.get("upgrade")?.toLowerCase() === "websocket" ? websocketHandler(event) : httpHandler(event);
1907
+ if (event.req.headers.has(internalRefreshHeader) && resolveRealtimeRoomSql(event)) {
1908
+ const { definitionName, documentId } = parseRoomPath(event.req.url);
1909
+ return { reseeded: await refreshOpenRoom(definitionName, documentId) };
1910
+ }
1911
+ if (event.req.headers.get("upgrade")?.toLowerCase() !== "websocket") return httpHandler(event);
1912
+ try {
1913
+ return await websocketHandler(event);
1914
+ } catch (error) {
1915
+ return refuseUpgrade(event.req, error instanceof HTTPError ? error.status : 500);
1916
+ }
856
1917
  });
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
+ } });
857
1956
  }
858
1957
  //#endregion
859
- export { applyRealtimeAwarenessUpdate, applyRealtimeSyncMessage, assertRealtimeRoomStateQuota, bindAwarenessIdentity, claimAwarenessClientIds, compactRealtimeAwareness, createRealtimeHandler, encodeAwarenessState, encodeSyncStep1, encodeSyncUpdate, markdownToYDoc, matchesRealtimeState, readRealtimeCheckpointState, readRealtimeWorkspaceDocument, realtimeRoomKey, replaceRealtimeDocument, restoreRealtimeDocument, writeRealtimeDocument, yDocToMarkdown };
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 };