@tldraw/sync-core 5.5.0-next.a2698a88ecfb → 5.5.0-next.b6a9f7cd7be2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist-cjs/index.d.ts +7 -2
  2. package/dist-cjs/index.js +1 -1
  3. package/dist-cjs/lib/ClientWebSocketAdapter.js +35 -13
  4. package/dist-cjs/lib/ClientWebSocketAdapter.js.map +2 -2
  5. package/dist-cjs/lib/InMemorySyncStorage.js +18 -18
  6. package/dist-cjs/lib/InMemorySyncStorage.js.map +2 -2
  7. package/dist-cjs/lib/SQLiteSyncStorage.js +15 -7
  8. package/dist-cjs/lib/SQLiteSyncStorage.js.map +2 -2
  9. package/dist-cjs/lib/TLSocketRoom.js +9 -8
  10. package/dist-cjs/lib/TLSocketRoom.js.map +2 -2
  11. package/dist-cjs/lib/TLSyncClient.js +3 -1
  12. package/dist-cjs/lib/TLSyncClient.js.map +2 -2
  13. package/dist-cjs/lib/TLSyncRoom.js +50 -5
  14. package/dist-cjs/lib/TLSyncRoom.js.map +2 -2
  15. package/dist-cjs/lib/chunk.js +35 -3
  16. package/dist-cjs/lib/chunk.js.map +2 -2
  17. package/dist-esm/index.d.mts +7 -2
  18. package/dist-esm/index.mjs +1 -1
  19. package/dist-esm/lib/ClientWebSocketAdapter.mjs +36 -14
  20. package/dist-esm/lib/ClientWebSocketAdapter.mjs.map +2 -2
  21. package/dist-esm/lib/InMemorySyncStorage.mjs +18 -18
  22. package/dist-esm/lib/InMemorySyncStorage.mjs.map +2 -2
  23. package/dist-esm/lib/SQLiteSyncStorage.mjs +15 -7
  24. package/dist-esm/lib/SQLiteSyncStorage.mjs.map +2 -2
  25. package/dist-esm/lib/TLSocketRoom.mjs +10 -9
  26. package/dist-esm/lib/TLSocketRoom.mjs.map +2 -2
  27. package/dist-esm/lib/TLSyncClient.mjs +3 -1
  28. package/dist-esm/lib/TLSyncClient.mjs.map +2 -2
  29. package/dist-esm/lib/TLSyncRoom.mjs +50 -5
  30. package/dist-esm/lib/TLSyncRoom.mjs.map +2 -2
  31. package/dist-esm/lib/chunk.mjs +35 -3
  32. package/dist-esm/lib/chunk.mjs.map +2 -2
  33. package/package.json +7 -7
  34. package/src/lib/ClientWebSocketAdapter.test.ts +190 -16
  35. package/src/lib/ClientWebSocketAdapter.ts +45 -16
  36. package/src/lib/InMemorySyncStorage.test.ts +21 -0
  37. package/src/lib/InMemorySyncStorage.ts +20 -22
  38. package/src/lib/SQLiteSyncStorage.test.ts +60 -1
  39. package/src/lib/SQLiteSyncStorage.ts +22 -14
  40. package/src/lib/TLSocketRoom.ts +16 -9
  41. package/src/lib/TLSyncClient.ts +2 -0
  42. package/src/lib/TLSyncRoom.ts +66 -5
  43. package/src/lib/chunk.test.ts +88 -1
  44. package/src/lib/chunk.ts +66 -3
  45. package/src/test/TLSocketRoom.test.ts +63 -0
  46. package/src/test/TLSyncRoom.test.ts +130 -0
  47. package/src/test/objectStore.test.ts +35 -0
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/lib/TLSyncRoom.ts"],
4
- "sourcesContent": ["import {\n\tAtomMap,\n\tMigrationFailureReason,\n\tRecordType,\n\tSerializedSchema,\n\tStoreSchema,\n\tUnknownRecord,\n} from '@tldraw/store'\nimport {\n\tassert,\n\tassertExists,\n\texhaustiveSwitchError,\n\tgetOwnProperty,\n\tisEqual,\n\tisNativeStructuredClone,\n\tobjectMapEntriesIterable,\n\tResult,\n\tthrottle,\n} from '@tldraw/utils'\nimport { createNanoEvents } from 'nanoevents'\nimport {\n\tapplyObjectDiff,\n\tdiffRecord,\n\tNetworkDiff,\n\tObjectDiff,\n\tRecordOp,\n\tRecordOpType,\n\tValueOpType,\n} from './diff'\nimport { interval } from './interval'\nimport {\n\tgetTlsyncProtocolVersion,\n\tTLIncompatibilityReason,\n\tTLObjectStoreAccess,\n\tTLSocketClientSentEvent,\n\tTLSocketServerSentDataEvent,\n\tTLSocketServerSentEvent,\n} from './protocol'\nimport { applyAndDiffRecord, diffAndValidateRecord, validateRecord } from './recordDiff'\nimport {\n\tRoomSession,\n\tRoomSessionState,\n\tSESSION_IDLE_TIMEOUT,\n\tSESSION_REMOVAL_WAIT_TIME,\n\tSESSION_START_WAIT_TIME,\n} from './RoomSession'\nimport { TLSyncLog } from './TLSocketRoom'\nimport { TLSyncError, TLSyncErrorCloseEventCode, TLSyncErrorCloseEventReason } from './TLSyncClient'\nimport {\n\tTLSyncForwardDiff,\n\tTLSyncStorage,\n\tTLSyncStorageTransaction,\n\ttoNetworkDiff,\n} from './TLSyncStorage'\n\n/**\n * WebSocket interface for server-side room connections. This defines the contract\n * that socket implementations must follow to work with TLSyncRoom.\n *\n * @internal\n */\nexport interface TLRoomSocket<R extends UnknownRecord> {\n\t/**\n\t * Whether the socket connection is currently open and ready to send messages.\n\t */\n\tisOpen: boolean\n\t/**\n\t * Send a message to the connected client through this socket.\n\t *\n\t * @param msg - The server-sent event message to transmit\n\t */\n\tsendMessage(msg: TLSocketServerSentEvent<R>): void\n\t/**\n\t * Close the socket connection with optional status code and reason.\n\t *\n\t * @param code - WebSocket close code (optional)\n\t * @param reason - Human-readable close reason (optional)\n\t */\n\tclose(code?: number, reason?: string): void\n}\n\n/**\n * The minimum time interval (in milliseconds) between sending batched data messages\n * to clients. This debouncing prevents overwhelming clients with rapid updates.\n * @public\n */\nexport const DATA_MESSAGE_DEBOUNCE_INTERVAL = 1000 / 60\n\nconst timeSince = (time: number) => Date.now() - time\n\n/**\n * Snapshot of a room's complete state that can be persisted and restored.\n * Contains all documents, tombstones, and metadata needed to reconstruct the room.\n *\n * @public\n */\nexport interface RoomSnapshot {\n\t/**\n\t * The current logical clock value for the room\n\t */\n\tclock?: number\n\t/**\n\t * Clock value when document data was last changed (optional for backwards compatibility)\n\t */\n\tdocumentClock?: number\n\t/**\n\t * Array of all document records with their last modification clocks\n\t */\n\tdocuments: Array<{ state: UnknownRecord; lastChangedClock: number }>\n\t/**\n\t * Map of deleted record IDs to their deletion clock values (optional)\n\t */\n\ttombstones?: Record<string, number>\n\t/**\n\t * Clock value where tombstone history begins - older deletions are not tracked (optional)\n\t */\n\ttombstoneHistoryStartsAtClock?: number\n\t/**\n\t * Serialized schema used when creating this snapshot (optional)\n\t */\n\tschema?: SerializedSchema\n}\n\n/**\n * Authorizes a single record write from a client: any per-record, per-session rule the host wants\n * to enforce server-side \u2014 veto writes the session isn't allowed to make, or rewrite the record on\n * create. The session's `meta` carries whatever the rule needs (identity, roles, \u2026); for example,\n * force a comment's `authorId` to the signed-in user so nobody can post in someone else's name.\n *\n * Called on **create**, **update**, and **delete** of records whose `typeName` it's registered for\n * (see {@link TLRecordAuthorizers}), and only for client pushes \u2014 never for server-initiated writes.\n *\n * `prev` and `next` are always at the **server's** schema version: client writes are migrated\n * before the authorizer runs, so guarding or stamping a field never requires knowing what older\n * clients call it. On create, the record you return is what gets stored (after validation) \u2014 no\n * migration runs afterwards, so stamped fields can't be clobbered.\n *\n * Return `null` to reject the write \u2014 it's skipped and the client self-corrects, exactly like the\n * `objectAccess` gate. Otherwise the write is allowed, and:\n *\n * - on **create**, the record you return is what gets stored, so stamp identity fields here (e.g.\n * set `authorId` from `session.meta`);\n * - on **update** and **delete**, only allow-vs-reject is used (the returned record's contents are\n * ignored), so use them to veto changes to immutable fields or unauthorized deletes \u2014 return\n * `next`/`prev` to allow, `null` to reject.\n *\n * \u26A0\uFE0E Runs synchronously inside the commit transaction, on the same path as every document edit \u2014 it\n * must be fast and do **no** I/O. `next`/`prev` are client-controlled records, so treat their\n * contents as untrusted; prefer returning `null` to reject over throwing, though a throw is\n * caught, logged, and treated as a rejection (fail closed) rather than crashing the push. For\n * expensive, async checks (e.g. resolving mentions against who can access a file), react after the\n * fact via `onCommittedChanges`.\n *\n * @public\n */\nexport type TLRecordAuthorizer<Rec extends UnknownRecord, SessionMeta> = (\n\targs: {\n\t\t/** The session performing the write: its host-provided `meta` (e.g. the authenticated user\n\t\t * id) and the canvas-lane `isReadonly` state, for hosts whose object-lane policy follows\n\t\t * canvas access. */\n\t\tsession: { sessionId: string; isReadonly: boolean; meta: SessionMeta }\n\t} & (\n\t\t| { type: 'create'; prev: null; next: Rec }\n\t\t| { type: 'update'; prev: Rec; next: Rec }\n\t\t| { type: 'delete'; prev: Rec; next: null }\n\t)\n) => Rec | null\n\n/**\n * A map from record `typeName` to a {@link TLRecordAuthorizer} for that record type. Only listed\n * types are authorized; every other record writes through untouched, so this stays off the hot path\n * for the vast majority of writes (shape drags etc.).\n *\n * Each authorizer is typed to its record \u2014 e.g. `next` in the `comment` entry is a `TLComment` \u2014 so\n * renaming a field on the record makes the authorizer that reads it fail to compile, rather than\n * silently stamp or guard the wrong field.\n *\n * Presence records are never authorized (presence is per-session and ephemeral); registering the\n * presence typeName is a construction-time error.\n *\n * @public\n */\nexport type TLRecordAuthorizers<R extends UnknownRecord, SessionMeta> = {\n\t[K in R['typeName']]?: TLRecordAuthorizer<Extract<R, { typeName: K }>, SessionMeta>\n}\n\n/**\n * A collaborative workspace that manages multiple client sessions and synchronizes\n * document changes between them. The room serves as the authoritative source for\n * all document state and handles conflict resolution, schema migrations, and\n * real-time data distribution.\n *\n * @example\n * ```ts\n * const room = new TLSyncRoom({\n * schema: mySchema,\n * onDataChange: () => saveToDatabase(room.getSnapshot()),\n * onPresenceChange: () => updateLiveCursors()\n * })\n *\n * // Handle new client connections\n * room.handleNewSession({\n * sessionId: 'user-123',\n * socket: webSocketAdapter,\n * meta: { userId: '123', name: 'Alice' },\n * isReadonly: false\n * })\n * ```\n *\n * @internal\n */\nexport class TLSyncRoom<R extends UnknownRecord, SessionMeta> {\n\t// A table of connected clients\n\treadonly sessions = new Map<string, RoomSession<R, SessionMeta>>()\n\n\tprivate lastDocumentClock = 0\n\n\tprivate pruneTimer: ReturnType<typeof setTimeout> | null = null\n\n\tpruneSessions = throttle(() => {\n\t\tif (this.pruneTimer) {\n\t\t\tclearTimeout(this.pruneTimer)\n\t\t\tthis.pruneTimer = null\n\t\t}\n\t\tfor (const client of this.sessions.values()) {\n\t\t\tswitch (client.state) {\n\t\t\t\tcase RoomSessionState.Connected: {\n\t\t\t\t\tconst hasTimedOut = timeSince(client.lastInteractionTime) > this.sessionIdleTimeout\n\t\t\t\t\tif (hasTimedOut || !client.socket.isOpen) {\n\t\t\t\t\t\tthis.cancelSession(client.sessionId)\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcase RoomSessionState.AwaitingConnectMessage: {\n\t\t\t\t\tconst hasTimedOut = timeSince(client.sessionStartTime) > SESSION_START_WAIT_TIME\n\t\t\t\t\tif (hasTimedOut || !client.socket.isOpen) {\n\t\t\t\t\t\t// remove immediately\n\t\t\t\t\t\tthis.removeSession(client.sessionId)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.scheduleFollowUpPrune()\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcase RoomSessionState.AwaitingRemoval: {\n\t\t\t\t\tconst hasTimedOut = timeSince(client.cancellationTime) > SESSION_REMOVAL_WAIT_TIME\n\t\t\t\t\tif (hasTimedOut) {\n\t\t\t\t\t\tthis.removeSession(client.sessionId)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.scheduleFollowUpPrune()\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\texhaustiveSwitchError(client)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}, 1000)\n\n\tprivate scheduleFollowUpPrune() {\n\t\tif (this.pruneTimer) return\n\t\tthis.pruneTimer = setTimeout(this.pruneSessions, SESSION_REMOVAL_WAIT_TIME + 100)\n\t}\n\n\treadonly presenceStore = new PresenceStore<R>()\n\n\tprivate disposables: Array<() => void> = []\n\n\tprivate _isClosed = false\n\n\t/**\n\t * Close the room and clean up all resources. Disconnects all sessions\n\t * and stops background processes.\n\t */\n\tclose() {\n\t\tthis.disposables.forEach((d) => d())\n\t\tthis.sessions.forEach((session) => {\n\t\t\tsession.socket.close()\n\t\t})\n\t\tthis._isClosed = true\n\t}\n\n\t/**\n\t * Check if the room has been closed and is no longer accepting connections.\n\t *\n\t * @returns True if the room is closed\n\t */\n\tisClosed() {\n\t\treturn this._isClosed\n\t}\n\n\treadonly events = createNanoEvents<{\n\t\troom_became_empty(): void\n\t\tsession_removed(args: { sessionId: string; meta: SessionMeta }): void\n\t}>()\n\n\t// Storage layer for documents, tombstones, and clocks\n\tprivate readonly storage: TLSyncStorage<R>\n\n\treadonly serializedSchema: SerializedSchema\n\n\treadonly documentTypes: Set<string>\n\t/**\n\t * Record types served by the object-store lane. Object records ride the same wire messages\n\t * as document records but are gated by the session's `objectAccess` instead of `isReadonly`,\n\t * and are excluded from `documentTypes` so hosts can persist them in a separate lane.\n\t */\n\treadonly objectTypes: Set<string>\n\treadonly presenceType: RecordType<R, any> | null\n\tprivate log?: TLSyncLog\n\tpublic readonly schema: StoreSchema<R, any>\n\tprivate onPresenceChange?(): void\n\tprivate onCommittedChanges?(args: { diff: TLSyncForwardDiff<R>; documentClock: number }): void\n\tprivate readonly authorizeRecord?: TLRecordAuthorizers<R, SessionMeta>\n\tprivate readonly sessionIdleTimeout: number\n\n\t/**\n\t * The authorizer registered for a record type, widened to the room's record union. Each entry in\n\t * `authorizeRecord` is typed to its specific record; the cast here is the one place we can't\n\t * statically correlate a runtime `typeName` with its record type, so it lives in the library\n\t * rather than in every consumer.\n\t */\n\tprivate authorizerFor(typeName: R['typeName']): TLRecordAuthorizer<R, SessionMeta> | undefined {\n\t\tconst authorize = this.authorizeRecord?.[typeName] as\n\t\t\t| TLRecordAuthorizer<R, SessionMeta>\n\t\t\t| undefined\n\t\tif (!authorize) return undefined\n\t\t// Fail closed: an authorizer that throws rejects the write (and is logged) rather than\n\t\t// aborting the whole push. Authorizers are security-sensitive, so a bug must never let a\n\t\t// write through.\n\t\treturn (args) => {\n\t\t\ttry {\n\t\t\t\treturn authorize(args)\n\t\t\t} catch (e) {\n\t\t\t\tthis.log?.error?.('record authorizer threw; rejecting the write', e)\n\t\t\t\treturn null\n\t\t\t}\n\t\t}\n\t}\n\n\tconstructor(opts: {\n\t\tlog?: TLSyncLog\n\t\tschema: StoreSchema<R, any>\n\t\tonPresenceChange?(): void\n\t\t/**\n\t\t * Called once after a client push commits, with the committed document diff. Fires for\n\t\t * local and remote pushes. Use this to react to document changes (e.g. persist certain\n\t\t * record types to a separate lane, or project them to an external store) as soon as they\n\t\t * commit. Best-effort \u2014 do not throw; do not block.\n\t\t */\n\t\tonCommittedChanges?(args: { diff: TLSyncForwardDiff<R>; documentClock: number }): void\n\t\t/**\n\t\t * Record type names to serve through the object-store lane instead of the document lane.\n\t\t * Each must be a document-scoped type registered in the schema. Object-lane writes are\n\t\t * gated per session by `objectAccess` rather than `isReadonly`.\n\t\t */\n\t\tobjectTypes?: readonly string[]\n\t\t/**\n\t\t * Per-type authorizers for client record writes (create, update, delete): veto or, on\n\t\t * create, rewrite. See {@link TLRecordAuthorizers}.\n\t\t */\n\t\tauthorizeRecord?: TLRecordAuthorizers<R, SessionMeta>\n\t\tstorage: TLSyncStorage<R>\n\t\tclientTimeout?: number\n\t}) {\n\t\tthis.schema = opts.schema\n\t\tthis.log = opts.log\n\t\tthis.onPresenceChange = opts.onPresenceChange\n\t\tthis.onCommittedChanges = opts.onCommittedChanges\n\t\tthis.authorizeRecord = opts.authorizeRecord\n\t\tthis.storage = opts.storage\n\t\tthis.sessionIdleTimeout = opts.clientTimeout ?? SESSION_IDLE_TIMEOUT\n\n\t\tassert(\n\t\t\tisNativeStructuredClone,\n\t\t\t'TLSyncRoom is supposed to run either on Cloudflare Workers' +\n\t\t\t\t'or on a 18+ version of Node.js, which both support the native structuredClone API'\n\t\t)\n\n\t\t// do a json serialization cycle to make sure the schema has no 'undefined' values\n\t\tthis.serializedSchema = JSON.parse(JSON.stringify(this.schema.serialize()))\n\n\t\tthis.objectTypes = new Set(opts.objectTypes ?? [])\n\t\tfor (const typeName of this.objectTypes) {\n\t\t\tconst type = getOwnProperty(this.schema.types, typeName)\n\t\t\tassert(type, `TLSyncRoom: object type '${typeName}' is not registered in the schema`)\n\t\t\tassert(\n\t\t\t\ttype.scope === 'document',\n\t\t\t\t`TLSyncRoom: object type '${typeName}' must have scope 'document', got '${type.scope}'`\n\t\t\t)\n\t\t}\n\n\t\t// object-lane types are partitioned out of the document lane\n\t\tthis.documentTypes = new Set(\n\t\t\tObject.values<RecordType<R, any>>(this.schema.types)\n\t\t\t\t.filter((t) => t.scope === 'document' && !this.objectTypes.has(t.typeName))\n\t\t\t\t.map((t) => t.typeName)\n\t\t)\n\n\t\tconst presenceTypes = new Set(\n\t\t\tObject.values<RecordType<R, any>>(this.schema.types).filter((t) => t.scope === 'presence')\n\t\t)\n\n\t\tif (presenceTypes.size > 1) {\n\t\t\tthrow new Error(\n\t\t\t\t`TLSyncRoom: exactly zero or one presence type is expected, but found ${presenceTypes.size}`\n\t\t\t)\n\t\t}\n\n\t\tthis.presenceType = presenceTypes.values().next()?.value ?? null\n\n\t\t// The presence lane never consults authorizers, so a presence key in `authorizeRecord`\n\t\t// would be a silent no-op \u2014 fail loudly at construction instead.\n\t\tif (this.presenceType && this.authorizeRecord) {\n\t\t\tassert(\n\t\t\t\t!getOwnProperty(this.authorizeRecord, this.presenceType.typeName),\n\t\t\t\t`TLSyncRoom: authorizeRecord['${this.presenceType.typeName}'] is a presence type; presence records are not authorized`\n\t\t\t)\n\t\t}\n\n\t\tconst { documentClock } = this.storage.transaction((txn) => {\n\t\t\tthis.schema.migrateStorage(txn)\n\t\t})\n\n\t\tthis.lastDocumentClock = documentClock\n\n\t\tthis.disposables.push(\n\t\t\tthis.storage.onChange(({ id }) => {\n\t\t\t\tif (id !== this.internalTxnId) {\n\t\t\t\t\tthis.broadcastExternalStorageChanges()\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\tthis.disposables.push(() => {\n\t\t\tthis.pruneSessions.cancel()\n\t\t\tif (this.pruneTimer) {\n\t\t\t\tclearTimeout(this.pruneTimer)\n\t\t\t\tthis.pruneTimer = null\n\t\t\t}\n\t\t})\n\n\t\t// When clientTimeout is finite, run periodic pruning so idle sessions are\n\t\t// cleaned up even with no traffic. When Infinity or 0 we skip the interval\n\t\t// (e.g. for hibernation); without it, pruning only runs on message or when\n\t\t// socket close/error triggers cancelSession, so pruning idle sessions\n\t\t// reliably depends on the runtime delivering those events.\n\t\tif (Number.isFinite(this.sessionIdleTimeout) && this.sessionIdleTimeout > 0) {\n\t\t\tconst pruneIntervalMs = Math.min(2000, Math.floor(this.sessionIdleTimeout / 4))\n\t\t\tthis.disposables.push(interval(() => this.pruneSessions(), pruneIntervalMs))\n\t\t}\n\t}\n\tprivate broadcastExternalStorageChanges() {\n\t\tthis.storage.transaction((txn) => {\n\t\t\tthis.broadcastChanges(txn)\n\t\t\tthis.lastDocumentClock = txn.getClock()\n\t\t}) // no id needed because this only reads, no writes.\n\t}\n\n\t/**\n\t * Send a message to a particular client. Debounces data events\n\t *\n\t * @param sessionId - The id of the session to send the message to.\n\t * @param message - The message to send. UNSAFE Any diffs must have been downgraded already if necessary\n\t */\n\tprivate _unsafe_sendMessage(\n\t\tsessionId: string,\n\t\tmessage: TLSocketServerSentEvent<R> | TLSocketServerSentDataEvent<R>\n\t) {\n\t\tconst session = this.sessions.get(sessionId)\n\t\tif (!session) {\n\t\t\tthis.log?.warn?.('Tried to send message to unknown session', message.type)\n\t\t\treturn\n\t\t}\n\t\tif (session.state !== RoomSessionState.Connected) {\n\t\t\tthis.log?.warn?.('Tried to send message to disconnected client', message.type)\n\t\t\treturn\n\t\t}\n\t\tif (session.socket.isOpen) {\n\t\t\tif (message.type !== 'patch' && message.type !== 'push_result') {\n\t\t\t\t// this is not a data message\n\t\t\t\tif (message.type !== 'pong') {\n\t\t\t\t\t// non-data messages like \"connect\" might still need to be ordered correctly with\n\t\t\t\t\t// respect to data messages, so it's better to flush just in case\n\t\t\t\t\tthis._flushDataMessages(sessionId)\n\t\t\t\t}\n\t\t\t\tsession.socket.sendMessage(message)\n\t\t\t} else {\n\t\t\t\tif (session.debounceTimer === null) {\n\t\t\t\t\t// this is the first message since the last flush, don't delay it\n\t\t\t\t\tsession.socket.sendMessage({ type: 'data', data: [message] })\n\n\t\t\t\t\tsession.debounceTimer = setTimeout(\n\t\t\t\t\t\t() => this._flushDataMessages(sessionId),\n\t\t\t\t\t\tDATA_MESSAGE_DEBOUNCE_INTERVAL\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\tsession.outstandingDataMessages.push(message)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tthis.cancelSession(session.sessionId)\n\t\t}\n\t}\n\n\t// needs to accept sessionId and not a session because the session might be dead by the time\n\t// the timer fires\n\t_flushDataMessages(sessionId: string) {\n\t\tconst session = this.sessions.get(sessionId)\n\n\t\tif (!session || session.state !== RoomSessionState.Connected) {\n\t\t\treturn\n\t\t}\n\n\t\tsession.debounceTimer = null\n\n\t\tif (session.outstandingDataMessages.length > 0) {\n\t\t\t// hand the buffer over and start a fresh one, rather than truncating in\n\t\t\t// place, so sockets that defer serialization don't see an emptied array\n\t\t\tconst data = session.outstandingDataMessages\n\t\t\tsession.outstandingDataMessages = []\n\t\t\tsession.socket.sendMessage({ type: 'data', data })\n\t\t}\n\t}\n\n\t/** @internal */\n\tprivate removeSession(sessionId: string, fatalReason?: string) {\n\t\tconst session = this.sessions.get(sessionId)\n\t\tif (!session) {\n\t\t\tthis.log?.warn?.('Tried to remove unknown session')\n\t\t\treturn\n\t\t}\n\n\t\tthis.sessions.delete(sessionId)\n\n\t\ttry {\n\t\t\tif (fatalReason) {\n\t\t\t\tsession.socket.close(TLSyncErrorCloseEventCode, fatalReason)\n\t\t\t} else {\n\t\t\t\tsession.socket.close()\n\t\t\t}\n\t\t} catch {\n\t\t\t// noop, calling .close() multiple times is fine\n\t\t}\n\n\t\tconst presence = this.presenceStore.get(session.presenceId ?? '')\n\t\tif (presence) {\n\t\t\tthis.presenceStore.delete(session.presenceId!)\n\t\t\t// Broadcast presence removal - use RecordsDiff with the removed record\n\t\t\tthis.broadcastPatch({\n\t\t\t\tputs: {},\n\t\t\t\tdeletes: [session.presenceId!],\n\t\t\t})\n\t\t}\n\n\t\tthis.events.emit('session_removed', { sessionId, meta: session.meta })\n\t\tif (this.sessions.size === 0) {\n\t\t\tthis.events.emit('room_became_empty')\n\t\t}\n\t}\n\n\tprivate cancelSession(sessionId: string) {\n\t\tconst session = this.sessions.get(sessionId)\n\t\tif (!session) {\n\t\t\treturn\n\t\t}\n\n\t\tif (session.state === RoomSessionState.AwaitingRemoval) {\n\t\t\tthis.log?.warn?.('Tried to cancel session that is already awaiting removal')\n\t\t\treturn\n\t\t}\n\n\t\tthis.sessions.set(sessionId, {\n\t\t\tstate: RoomSessionState.AwaitingRemoval,\n\t\t\tsessionId,\n\t\t\tpresenceId: session.presenceId,\n\t\t\tsocket: session.socket,\n\t\t\tcancellationTime: Date.now(),\n\t\t\tmeta: session.meta,\n\t\t\tisReadonly: session.isReadonly,\n\t\t\tobjectAccess: session.objectAccess,\n\t\t\trequiresLegacyRejection: session.requiresLegacyRejection,\n\t\t\tsupportsStringAppend: session.supportsStringAppend,\n\t\t})\n\n\t\ttry {\n\t\t\tsession.socket.close()\n\t\t} catch {\n\t\t\t// noop, calling .close() multiple times is fine\n\t\t}\n\n\t\tthis.scheduleFollowUpPrune()\n\t}\n\n\treadonly internalTxnId = 'TLSyncRoom.txn'\n\n\t/**\n\t * Broadcast a patch to all connected clients except the one with the sessionId provided.\n\t *\n\t * @param diff - The TLSyncForwardDiff with full records (used for migration)\n\t * @param networkDiff - Optional pre-computed NetworkDiff for sessions not needing migration.\n\t * If not provided, will be computed from recordsDiff.\n\t * @param sourceSessionId - Optional session ID to exclude from the broadcast\n\t */\n\tprivate broadcastPatch(\n\t\tdiff: TLSyncForwardDiff<R>,\n\t\tnetworkDiff?: NetworkDiff<R> | null,\n\t\tsourceSessionId?: string\n\t) {\n\t\t// Pre-compute network diff if not provided\n\t\tconst unmigrated = networkDiff ?? toNetworkDiff(diff)\n\t\tif (!unmigrated) return this\n\n\t\tthis.sessions.forEach((session) => {\n\t\t\tif (session.state !== RoomSessionState.Connected) return\n\t\t\tif (sourceSessionId === session.sessionId) return\n\t\t\tif (!session.socket.isOpen) {\n\t\t\t\tthis.cancelSession(session.sessionId)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tconst diffResult = this.migrateDiffOrRejectSession(\n\t\t\t\tsession.sessionId,\n\t\t\t\tsession.serializedSchema,\n\t\t\t\tsession.requiresDownMigrations,\n\t\t\t\tdiff\n\t\t\t)\n\t\t\tif (!diffResult.ok) return\n\n\t\t\tthis._unsafe_sendMessage(session.sessionId, {\n\t\t\t\ttype: 'patch',\n\t\t\t\tdiff: diffResult.value,\n\t\t\t\tserverClock: this.lastDocumentClock,\n\t\t\t})\n\t\t})\n\t\treturn this\n\t}\n\n\t/**\n\t * Send a custom message to a connected client. Useful for application-specific\n\t * communication that doesn't involve document synchronization.\n\t *\n\t * @param sessionId - The ID of the session to send the message to\n\t * @param data - The custom payload to send (will be JSON serialized)\n\t * @example\n\t * ```ts\n\t * // Send a custom notification\n\t * room.sendCustomMessage('user-123', {\n\t * type: 'notification',\n\t * message: 'Document saved successfully'\n\t * })\n\t *\n\t * // Send user-specific data\n\t * room.sendCustomMessage('user-456', {\n\t * type: 'user_permissions',\n\t * canEdit: true,\n\t * canDelete: false\n\t * })\n\t * ```\n\t */\n\tsendCustomMessage(sessionId: string, data: any): void {\n\t\tthis._unsafe_sendMessage(sessionId, { type: 'custom', data })\n\t}\n\n\t/**\n\t * Register a new client session with the room. The session will be in an awaiting\n\t * state until it sends a connect message with protocol handshake.\n\t *\n\t * @param opts - Session configuration\n\t * - sessionId - Unique identifier for this session\n\t * - socket - WebSocket adapter for communication\n\t * - meta - Application-specific metadata for this session\n\t * - isReadonly - Whether this session can modify documents\n\t * @returns This room instance for method chaining\n\t * @example\n\t * ```ts\n\t * room.handleNewSession({\n\t * sessionId: crypto.randomUUID(),\n\t * socket: new WebSocketAdapter(ws),\n\t * meta: { userId: '123', name: 'Alice', avatar: 'url' },\n\t * isReadonly: !hasEditPermission\n\t * })\n\t * ```\n\t *\n\t * @internal\n\t */\n\thandleNewSession(opts: {\n\t\tsessionId: string\n\t\tsocket: TLRoomSocket<R>\n\t\tmeta: SessionMeta\n\t\tisReadonly: boolean\n\t\tobjectAccess?: TLObjectStoreAccess\n\t}) {\n\t\tconst { sessionId, socket, meta, isReadonly, objectAccess } = opts\n\t\tconst existing = this.sessions.get(sessionId)\n\t\tthis.sessions.set(sessionId, {\n\t\t\tstate: RoomSessionState.AwaitingConnectMessage,\n\t\t\tsessionId,\n\t\t\tsocket,\n\t\t\tpresenceId: existing?.presenceId ?? this.presenceType?.createId() ?? null,\n\t\t\tsessionStartTime: Date.now(),\n\t\t\tmeta,\n\t\t\tisReadonly: isReadonly ?? false,\n\t\t\tobjectAccess: objectAccess ?? 'write',\n\t\t\t// this gets set later during handleConnectMessage\n\t\t\trequiresLegacyRejection: false,\n\t\t\tsupportsStringAppend: true,\n\t\t})\n\t\treturn this\n\t}\n\n\t/**\n\t * Resume a previously-connected session directly into `Connected` state, bypassing the\n\t * connect handshake. Used after server hibernation when the WebSocket is still alive but\n\t * all in-memory state has been lost.\n\t *\n\t * @internal\n\t */\n\thandleResumedSession(opts: {\n\t\tsessionId: string\n\t\tsocket: TLRoomSocket<R>\n\t\tmeta: SessionMeta\n\t\tisReadonly: boolean\n\t\tobjectAccess?: TLObjectStoreAccess\n\t\tserializedSchema: SerializedSchema\n\t\tpresenceId: string | null\n\t\tpresenceRecord: UnknownRecord | null\n\t\trequiresLegacyRejection: boolean\n\t\tsupportsStringAppend: boolean\n\t}) {\n\t\tconst {\n\t\t\tsessionId,\n\t\t\tsocket,\n\t\t\tmeta,\n\t\t\tisReadonly,\n\t\t\tobjectAccess,\n\t\t\tserializedSchema,\n\t\t\tpresenceId,\n\t\t\tpresenceRecord,\n\t\t\trequiresLegacyRejection,\n\t\t\tsupportsStringAppend,\n\t\t} = opts\n\n\t\tconst migrations = this.schema.getMigrationsSince(serializedSchema)\n\t\tconst requiresDownMigrations = migrations.ok ? migrations.value.length > 0 : false\n\n\t\tthis.sessions.set(sessionId, {\n\t\t\tstate: RoomSessionState.Connected,\n\t\t\tsessionId,\n\t\t\tsocket,\n\t\t\tpresenceId: presenceId ?? this.presenceType?.createId() ?? null,\n\t\t\tserializedSchema,\n\t\t\trequiresDownMigrations,\n\t\t\tlastInteractionTime: Date.now(),\n\t\t\tdebounceTimer: null,\n\t\t\toutstandingDataMessages: [],\n\t\t\tmeta,\n\t\t\tisReadonly,\n\t\t\tobjectAccess: objectAccess ?? 'write',\n\t\t\trequiresLegacyRejection,\n\t\t\tsupportsStringAppend,\n\t\t})\n\n\t\tif (presenceRecord && presenceId) {\n\t\t\tthis.presenceStore.set(presenceId, presenceRecord as R)\n\t\t}\n\t}\n\n\t/**\n\t * Checks if all connected sessions support string append operations (protocol version 8+).\n\t * If any client is on an older version, returns false to enable legacy append mode.\n\t *\n\t * @returns True if all connected sessions are on protocol version 8 or higher\n\t */\n\tgetCanEmitStringAppend(): boolean {\n\t\tfor (const session of this.sessions.values()) {\n\t\t\tif (session.state === RoomSessionState.Connected) {\n\t\t\t\tif (!session.supportsStringAppend) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\n\t/**\n\t * When we send a diff to a client, if that client is on a lower version than us, we need to make\n\t * the diff compatible with their version. This method takes a TLSyncForwardDiff (which has full\n\t * records) and migrates all records down to the client's schema version, returning a NetworkDiff.\n\t *\n\t * For updates (entries with [before, after] tuples), both records are migrated and a patch is\n\t * computed from the migrated versions, preserving efficient patch semantics even across versions.\n\t *\n\t * If a migration fails, the session will be rejected.\n\t *\n\t * @param sessionId - The session ID (for rejection on migration failure)\n\t * @param serializedSchema - The client's schema to migrate to\n\t * @param requiresDownMigrations - Whether the client needs down migrations\n\t * @param diff - The TLSyncForwardDiff containing full records to migrate\n\t * @param unmigrated - Optional pre-computed NetworkDiff for when no migration is needed\n\t * @returns A NetworkDiff with migrated records, or a migration failure\n\t */\n\tprivate migrateDiffOrRejectSession(\n\t\tsessionId: string,\n\t\tserializedSchema: SerializedSchema,\n\t\trequiresDownMigrations: boolean,\n\t\tdiff: TLSyncForwardDiff<R>,\n\t\tunmigrated?: NetworkDiff<R>\n\t): Result<NetworkDiff<R>, MigrationFailureReason> {\n\t\tif (!requiresDownMigrations) {\n\t\t\treturn Result.ok(unmigrated ?? toNetworkDiff(diff) ?? {})\n\t\t}\n\n\t\tconst result: NetworkDiff<R> = {}\n\n\t\t// Migrate puts (either adds or updates)\n\t\tfor (const [id, put] of objectMapEntriesIterable(diff.puts)) {\n\t\t\tif (Array.isArray(put)) {\n\t\t\t\t// Update: [before, after] tuple - migrate both and compute patch\n\t\t\t\tconst [from, to] = put\n\t\t\t\tconst fromResult = this.schema.migratePersistedRecord(from, serializedSchema, 'down')\n\t\t\t\tif (fromResult.type === 'error') {\n\t\t\t\t\tthis.rejectSession(sessionId, TLSyncErrorCloseEventReason.CLIENT_TOO_OLD)\n\t\t\t\t\treturn Result.err(fromResult.reason)\n\t\t\t\t}\n\t\t\t\tconst toResult = this.schema.migratePersistedRecord(to, serializedSchema, 'down')\n\t\t\t\tif (toResult.type === 'error') {\n\t\t\t\t\tthis.rejectSession(sessionId, TLSyncErrorCloseEventReason.CLIENT_TOO_OLD)\n\t\t\t\t\treturn Result.err(toResult.reason)\n\t\t\t\t}\n\t\t\t\tconst patch = diffRecord(fromResult.value, toResult.value)\n\t\t\t\tif (patch) {\n\t\t\t\t\tresult[id] = [RecordOpType.Patch, patch]\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Add: single record - migrate and put\n\t\t\t\tconst migrationResult = this.schema.migratePersistedRecord(put, serializedSchema, 'down')\n\t\t\t\tif (migrationResult.type === 'error') {\n\t\t\t\t\tthis.rejectSession(sessionId, TLSyncErrorCloseEventReason.CLIENT_TOO_OLD)\n\t\t\t\t\treturn Result.err(migrationResult.reason)\n\t\t\t\t}\n\t\t\t\tresult[id] = [RecordOpType.Put, migrationResult.value]\n\t\t\t}\n\t\t}\n\n\t\t// Deletes don't need migration\n\t\tfor (const id of diff.deletes) {\n\t\t\tresult[id] = [RecordOpType.Remove]\n\t\t}\n\n\t\treturn Result.ok(result)\n\t}\n\n\t/**\n\t * Process an incoming message from a client session. Handles connection requests,\n\t * data synchronization pushes, and ping/pong for connection health.\n\t *\n\t * @param sessionId - The ID of the session that sent the message\n\t * @param message - The client message to process\n\t * @example\n\t * ```ts\n\t * // Typically called by WebSocket message handlers\n\t * websocket.onMessage((data) => {\n\t * const message = JSON.parse(data)\n\t * room.handleMessage(sessionId, message)\n\t * })\n\t * ```\n\t */\n\tasync handleMessage(sessionId: string, message: TLSocketClientSentEvent<R>) {\n\t\tconst session = this.sessions.get(sessionId)\n\t\tif (!session) {\n\t\t\tthis.log?.warn?.('Received message from unknown session')\n\t\t\treturn\n\t\t}\n\t\ttry {\n\t\t\tswitch (message.type) {\n\t\t\t\tcase 'connect': {\n\t\t\t\t\treturn this.handleConnectRequest(session, message)\n\t\t\t\t}\n\t\t\t\tcase 'push': {\n\t\t\t\t\treturn this.handlePushRequest(session, message)\n\t\t\t\t}\n\t\t\t\tcase 'ping': {\n\t\t\t\t\tif (session.state === RoomSessionState.Connected) {\n\t\t\t\t\t\tsession.lastInteractionTime = Date.now()\n\t\t\t\t\t}\n\t\t\t\t\treturn this._unsafe_sendMessage(session.sessionId, { type: 'pong' })\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\texhaustiveSwitchError(message)\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof TLSyncError) {\n\t\t\t\tthis.rejectSession(session.sessionId, e.reason)\n\t\t\t} else {\n\t\t\t\t// log error and reboot the room?\n\t\t\t\tthrow e\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Reject and disconnect a session due to incompatibility or other fatal errors.\n\t * Sends appropriate error messages before closing the connection.\n\t *\n\t * @param sessionId - The session to reject\n\t * @param fatalReason - The reason for rejection (optional)\n\t * @example\n\t * ```ts\n\t * // Reject due to version mismatch\n\t * room.rejectSession('user-123', TLSyncErrorCloseEventReason.CLIENT_TOO_OLD)\n\t *\n\t * // Reject due to permission issue\n\t * room.rejectSession('user-456', 'Insufficient permissions')\n\t * ```\n\t */\n\trejectSession(sessionId: string, fatalReason?: TLSyncErrorCloseEventReason | string) {\n\t\tconst session = this.sessions.get(sessionId)\n\t\tif (!session) return\n\t\tif (!fatalReason) {\n\t\t\tthis.removeSession(sessionId)\n\t\t\treturn\n\t\t}\n\t\tif (session.requiresLegacyRejection) {\n\t\t\ttry {\n\t\t\t\tif (session.socket.isOpen) {\n\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-deprecated\n\t\t\t\t\tlet legacyReason: TLIncompatibilityReason\n\t\t\t\t\tswitch (fatalReason) {\n\t\t\t\t\t\tcase TLSyncErrorCloseEventReason.CLIENT_TOO_OLD:\n\t\t\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-deprecated\n\t\t\t\t\t\t\tlegacyReason = TLIncompatibilityReason.ClientTooOld\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tcase TLSyncErrorCloseEventReason.SERVER_TOO_OLD:\n\t\t\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-deprecated\n\t\t\t\t\t\t\tlegacyReason = TLIncompatibilityReason.ServerTooOld\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tcase TLSyncErrorCloseEventReason.INVALID_RECORD:\n\t\t\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-deprecated\n\t\t\t\t\t\t\tlegacyReason = TLIncompatibilityReason.InvalidRecord\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-deprecated\n\t\t\t\t\t\t\tlegacyReason = TLIncompatibilityReason.InvalidOperation\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tsession.socket.sendMessage({\n\t\t\t\t\t\ttype: 'incompatibility_error',\n\t\t\t\t\t\treason: legacyReason,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// noop\n\t\t\t} finally {\n\t\t\t\tthis.removeSession(sessionId)\n\t\t\t}\n\t\t} else {\n\t\t\tthis.removeSession(sessionId, fatalReason)\n\t\t}\n\t}\n\n\tprivate forceAllReconnect() {\n\t\tfor (const session of this.sessions.values()) {\n\t\t\tthis.removeSession(session.sessionId)\n\t\t}\n\t}\n\n\tprivate broadcastChanges(txn: TLSyncStorageTransaction<R>) {\n\t\tconst changes = txn.getChangesSince(this.lastDocumentClock)\n\t\tif (!changes) return\n\t\tconst { wipeAll, diff } = changes\n\t\tthis.lastDocumentClock = txn.getClock()\n\t\tif (wipeAll) {\n\t\t\t// If this happens it means we'd need to broadcast a wipe_all message to all clients,\n\t\t\t// which is not part of the protocol yet, so we need to force all clients to reconnect instead.\n\t\t\tthis.forceAllReconnect()\n\t\t\treturn\n\t\t}\n\t\tthis.broadcastPatch(diff)\n\t}\n\n\t/**\n\t * Work out whether a client we can't reconcile schemas with is running a newer or older SDK\n\t * than us.\n\t */\n\tprivate getVersionMismatchReason(theirSchema: SerializedSchema) {\n\t\tconst ourSchema = this.serializedSchema\n\n\t\tif (theirSchema.schemaVersion > ourSchema.schemaVersion) {\n\t\t\treturn TLSyncErrorCloseEventReason.SERVER_TOO_OLD\n\t\t}\n\n\t\tif (theirSchema.schemaVersion === 2 && ourSchema.schemaVersion === 2) {\n\t\t\tfor (const [sequenceId, theirVersion] of Object.entries(theirSchema.sequences)) {\n\t\t\t\tconst ourVersion = ourSchema.sequences[sequenceId]\n\t\t\t\tif (ourVersion === undefined || theirVersion > ourVersion) {\n\t\t\t\t\treturn TLSyncErrorCloseEventReason.SERVER_TOO_OLD\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn TLSyncErrorCloseEventReason.CLIENT_TOO_OLD\n\t}\n\n\tprivate handleConnectRequest(\n\t\tsession: RoomSession<R, SessionMeta>,\n\t\tmessage: Extract<TLSocketClientSentEvent<R>, { type: 'connect' }>\n\t) {\n\t\t// if the protocol versions don't match, disconnect the client\n\t\t// we will eventually want to try to make our protocol backwards compatible to some degree\n\t\t// and have a MIN_PROTOCOL_VERSION constant that the TLSyncRoom implements support for\n\t\tlet theirProtocolVersion = message.protocolVersion\n\t\t// 5 is the same as 6\n\t\tif (theirProtocolVersion === 5) {\n\t\t\ttheirProtocolVersion = 6\n\t\t}\n\t\t// 6 is almost the same as 7\n\t\tsession.requiresLegacyRejection = theirProtocolVersion === 6\n\t\tif (theirProtocolVersion === 6) {\n\t\t\ttheirProtocolVersion++\n\t\t}\n\t\tif (theirProtocolVersion === 7) {\n\t\t\ttheirProtocolVersion++\n\t\t\tsession.supportsStringAppend = false\n\t\t}\n\n\t\tif (theirProtocolVersion == null || theirProtocolVersion < getTlsyncProtocolVersion()) {\n\t\t\tthis.rejectSession(session.sessionId, TLSyncErrorCloseEventReason.CLIENT_TOO_OLD)\n\t\t\treturn\n\t\t} else if (theirProtocolVersion > getTlsyncProtocolVersion()) {\n\t\t\tthis.rejectSession(session.sessionId, TLSyncErrorCloseEventReason.SERVER_TOO_OLD)\n\t\t\treturn\n\t\t}\n\t\t// If the client's store is at a different version to ours, it could cause corruption.\n\t\t// We should disconnect the client and ask them to refresh.\n\t\tif (message.schema == null) {\n\t\t\tthis.rejectSession(session.sessionId, TLSyncErrorCloseEventReason.CLIENT_TOO_OLD)\n\t\t\treturn\n\t\t}\n\t\tconst migrations = this.schema.getMigrationsSince(message.schema)\n\t\tif (!migrations.ok) {\n\t\t\tthis.rejectSession(session.sessionId, this.getVersionMismatchReason(message.schema))\n\t\t\treturn\n\t\t}\n\t\t// The client's schema is older than ours, but we can't migrate our data down to their\n\t\t// version (a migration isn't record-scoped or has no down migration), so they're too old.\n\t\tif (migrations.value.some((m) => m.scope !== 'record' || !m.down)) {\n\t\t\tthis.rejectSession(session.sessionId, TLSyncErrorCloseEventReason.CLIENT_TOO_OLD)\n\t\t\treturn\n\t\t}\n\n\t\tconst sessionSchema = isEqual(message.schema, this.serializedSchema)\n\t\t\t? this.serializedSchema\n\t\t\t: message.schema\n\n\t\tconst requiresDownMigrations = migrations.value.length > 0\n\n\t\tconst connect = async (msg: Extract<TLSocketServerSentEvent<R>, { type: 'connect' }>) => {\n\t\t\tthis.sessions.set(session.sessionId, {\n\t\t\t\tstate: RoomSessionState.Connected,\n\t\t\t\tsessionId: session.sessionId,\n\t\t\t\tpresenceId: session.presenceId,\n\t\t\t\tsocket: session.socket,\n\t\t\t\tserializedSchema: sessionSchema,\n\t\t\t\trequiresDownMigrations,\n\t\t\t\tlastInteractionTime: Date.now(),\n\t\t\t\tdebounceTimer: null,\n\t\t\t\toutstandingDataMessages: [],\n\t\t\t\tsupportsStringAppend: session.supportsStringAppend,\n\t\t\t\tmeta: session.meta,\n\t\t\t\tisReadonly: session.isReadonly,\n\t\t\t\tobjectAccess: session.objectAccess,\n\t\t\t\trequiresLegacyRejection: session.requiresLegacyRejection,\n\t\t\t})\n\t\t\tthis._unsafe_sendMessage(session.sessionId, msg)\n\t\t}\n\n\t\tconst { documentClock, result } = this.storage.transaction((txn) => {\n\t\t\tthis.broadcastChanges(txn)\n\t\t\tconst docChanges = txn.getChangesSince(message.lastServerClock)\n\t\t\tconst presenceDiff = this.migrateDiffOrRejectSession(\n\t\t\t\tsession.sessionId,\n\t\t\t\tsessionSchema,\n\t\t\t\trequiresDownMigrations,\n\t\t\t\t{\n\t\t\t\t\t// Exclude the connecting session's own presence \u2014 it will push fresh\n\t\t\t\t\t// data immediately after connecting. Sending the stale record back\n\t\t\t\t\t// would leave an orphaned presence in the client's local store (the\n\t\t\t\t\t// server never echoes a session's own updates back to it).\n\t\t\t\t\tputs: Object.fromEntries(\n\t\t\t\t\t\t[...this.presenceStore.values()]\n\t\t\t\t\t\t\t.filter((p) => p.id !== session.presenceId)\n\t\t\t\t\t\t\t.map((p) => [p.id, p])\n\t\t\t\t\t),\n\t\t\t\t\tdeletes: [],\n\t\t\t\t}\n\t\t\t)\n\t\t\tif (!presenceDiff.ok) return null\n\n\t\t\t// Migrate the diff if needed, or use the pre-computed network diff\n\t\t\tlet docDiff: NetworkDiff<R> | null = null\n\t\t\tif (docChanges && sessionSchema !== this.serializedSchema) {\n\t\t\t\tconst migrated = this.migrateDiffOrRejectSession(\n\t\t\t\t\tsession.sessionId,\n\t\t\t\t\tsessionSchema,\n\t\t\t\t\trequiresDownMigrations,\n\t\t\t\t\tdocChanges.diff\n\t\t\t\t)\n\t\t\t\tif (!migrated.ok) return null\n\t\t\t\tdocDiff = migrated.value\n\t\t\t} else if (docChanges) {\n\t\t\t\tdocDiff = toNetworkDiff(docChanges.diff)\n\t\t\t}\n\t\t\treturn {\n\t\t\t\ttype: 'connect',\n\t\t\t\tconnectRequestId: message.connectRequestId,\n\t\t\t\thydrationType: docChanges?.wipeAll ? 'wipe_all' : 'wipe_presence',\n\t\t\t\tprotocolVersion: getTlsyncProtocolVersion(),\n\t\t\t\tschema: this.schema.serialize(),\n\t\t\t\tserverClock: txn.getClock(),\n\t\t\t\tdiff: { ...presenceDiff.value, ...docDiff },\n\t\t\t\tisReadonly: session.isReadonly,\n\t\t\t\tobjectAccess: session.objectAccess,\n\t\t\t} satisfies Extract<TLSocketServerSentEvent<R>, { type: 'connect' }>\n\t\t}) // no id needed because this only reads, no writes.\n\n\t\tthis.lastDocumentClock = documentClock\n\n\t\tif (result) {\n\t\t\tconnect(result)\n\t\t}\n\t}\n\n\tprivate handlePushRequest(\n\t\tsession: RoomSession<R, SessionMeta> | null,\n\t\tmessage: Extract<TLSocketClientSentEvent<R>, { type: 'push' }>\n\t) {\n\t\t// We must be connected to handle push requests\n\t\tif (session && session.state !== RoomSessionState.Connected) {\n\t\t\treturn\n\t\t}\n\t\t// update the last interaction time\n\t\tif (session) {\n\t\t\tsession.lastInteractionTime = Date.now()\n\t\t}\n\n\t\tconst legacyAppendMode = !this.getCanEmitStringAppend()\n\n\t\tinterface ActualChanges {\n\t\t\tdiffs: {\n\t\t\t\tnetworkDiff: NetworkDiff<R>\n\t\t\t\tdiff: TLSyncForwardDiff<R>\n\t\t\t} | null\n\t\t}\n\n\t\tconst propagateOp = (\n\t\t\tchanges: ActualChanges,\n\t\t\tid: string,\n\t\t\top: RecordOp<R>,\n\t\t\tbefore: R | undefined,\n\t\t\tafter: R | undefined\n\t\t) => {\n\t\t\tif (!changes.diffs) changes.diffs = { networkDiff: {}, diff: { puts: {}, deletes: [] } }\n\t\t\tchanges.diffs.networkDiff[id] = op\n\t\t\tswitch (op[0]) {\n\t\t\t\tcase RecordOpType.Put:\n\t\t\t\t\tchanges.diffs.diff.puts[id] = op[1]\n\t\t\t\t\tbreak\n\t\t\t\tcase RecordOpType.Patch:\n\t\t\t\t\tassert(before && after, 'before and after are required for patches')\n\t\t\t\t\tchanges.diffs.diff.puts[id] = [before, after]\n\t\t\t\t\tbreak\n\t\t\t\tcase RecordOpType.Remove:\n\t\t\t\t\tchanges.diffs.diff.deletes.push(id)\n\t\t\t\t\tbreak\n\t\t\t\tdefault:\n\t\t\t\t\texhaustiveSwitchError(op[0])\n\t\t\t}\n\t\t}\n\n\t\tconst addDocument = (\n\t\t\tstorage: MinimalDocStore<R>,\n\t\t\tchanges: ActualChanges,\n\t\t\tid: string,\n\t\t\t_state: R,\n\t\t\tauthorize?: (prev: R | null, next: R) => R | null,\n\t\t\t// The existing document if the caller already fetched it; `null` for fetched-and-absent,\n\t\t\t// `undefined` for not fetched. Saves a second SELECT + JSON.parse on the push hot path.\n\t\t\tprevDoc?: R | null\n\t\t): Result<void, void> => {\n\t\t\tconst res = session\n\t\t\t\t? this.schema.migratePersistedRecord(_state, session.serializedSchema, 'up')\n\t\t\t\t: { type: 'success' as const, value: _state }\n\t\t\tif (res.type === 'error') {\n\t\t\t\tthrow new TLSyncError(res.reason, TLSyncErrorCloseEventReason.CLIENT_TOO_OLD)\n\t\t\t}\n\t\t\tlet { value: state } = res\n\n\t\t\t// Get the existing document, if any\n\t\t\tconst doc =\n\t\t\t\tprevDoc !== undefined ? (prevDoc ?? undefined) : (storage.get(id) as R | undefined)\n\n\t\t\t// Authorize on the up-migrated record; on create the authorizer's return is stored as-is,\n\t\t\t// so no later migration can clobber stamped fields.\n\t\t\tif (authorize) {\n\t\t\t\tconst result = authorize(doc ?? null, state)\n\t\t\t\tif (!result) return Result.ok(undefined) // vetoed: skip the op, the client self-corrects\n\t\t\t\tif (!doc) state = result // create: store the authorizer's (stamped) record\n\t\t\t}\n\n\t\t\tif (doc) {\n\t\t\t\t// If there's an existing document, replace it with the new state\n\t\t\t\t// but propagate a diff rather than the entire value\n\t\t\t\tconst recordType = assertExists(getOwnProperty(this.schema.types, doc.typeName))\n\t\t\t\tconst diff = diffAndValidateRecord(doc, state, recordType)\n\t\t\t\tif (diff) {\n\t\t\t\t\tstorage.set(id, state)\n\t\t\t\t\tpropagateOp(changes, id, [RecordOpType.Patch, diff], doc, state)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Otherwise, if we don't already have a document with this id\n\t\t\t\t// create the document and propagate the put op\n\t\t\t\t// set automatically clears tombstones if they exist\n\t\t\t\tconst recordType = assertExists(getOwnProperty(this.schema.types, state.typeName))\n\t\t\t\tvalidateRecord(state, recordType)\n\t\t\t\tstorage.set(id, state)\n\t\t\t\tpropagateOp(changes, id, [RecordOpType.Put, state], undefined, undefined)\n\t\t\t}\n\n\t\t\treturn Result.ok(undefined)\n\t\t}\n\n\t\tconst patchDocument = (\n\t\t\tstorage: MinimalDocStore<R>,\n\t\t\tchanges: ActualChanges,\n\t\t\tid: string,\n\t\t\tpatch: ObjectDiff,\n\t\t\tauthorize?: (prev: R, next: R) => R | null,\n\t\t\t// The existing document if the caller already fetched it (see `addDocument`).\n\t\t\tprevDoc?: R\n\t\t) => {\n\t\t\t// if it was already deleted, there's no need to apply the patch\n\t\t\tconst doc = prevDoc ?? (storage.get(id) as R | undefined)\n\t\t\tif (!doc) return\n\n\t\t\tconst recordType = assertExists(getOwnProperty(this.schema.types, doc.typeName))\n\t\t\t// If the client's version of the record is older than ours,\n\t\t\t// we apply the patch to the downgraded version of the record\n\t\t\tconst downgraded = session\n\t\t\t\t? this.schema.migratePersistedRecord(doc, session.serializedSchema, 'down')\n\t\t\t\t: { type: 'success' as const, value: doc }\n\t\t\tif (downgraded.type === 'error') {\n\t\t\t\tthrow new TLSyncError(downgraded.reason, TLSyncErrorCloseEventReason.CLIENT_TOO_OLD)\n\t\t\t}\n\n\t\t\tif (downgraded.value === doc) {\n\t\t\t\t// If the versions are compatible, apply the patch and propagate the patch op\n\t\t\t\tconst diff = applyAndDiffRecord(doc, patch, recordType, legacyAppendMode)\n\t\t\t\tif (diff) {\n\t\t\t\t\t// Authorize on the committed candidate \u2014 the record that will actually be stored.\n\t\t\t\t\tif (authorize && !authorize(doc, diff[1])) return\n\t\t\t\t\tstorage.set(id, diff[1])\n\t\t\t\t\tpropagateOp(changes, id, [RecordOpType.Patch, diff[0]], doc, diff[1])\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// need to apply the patch to the downgraded version and then upgrade it\n\n\t\t\t\t// apply the patch to the downgraded version\n\t\t\t\tconst patched = applyObjectDiff(downgraded.value, patch)\n\t\t\t\t// then upgrade the patched version and use that as the new state\n\t\t\t\tconst upgraded = session\n\t\t\t\t\t? this.schema.migratePersistedRecord(patched, session.serializedSchema, 'up')\n\t\t\t\t\t: { type: 'success' as const, value: patched }\n\t\t\t\t// If the client's version is too old, we'll hit an error\n\t\t\t\tif (upgraded.type === 'error') {\n\t\t\t\t\tthrow new TLSyncError(upgraded.reason, TLSyncErrorCloseEventReason.CLIENT_TOO_OLD)\n\t\t\t\t}\n\t\t\t\t// replace the state with the upgraded version and propagate the patch op\n\t\t\t\tconst diff = diffAndValidateRecord(doc, upgraded.value, recordType, legacyAppendMode)\n\t\t\t\tif (diff) {\n\t\t\t\t\t// Authorize on the committed candidate \u2014 the upgraded record, not a raw preview.\n\t\t\t\t\tif (authorize && !authorize(doc, upgraded.value)) return\n\t\t\t\t\tstorage.set(id, upgraded.value)\n\t\t\t\t\tpropagateOp(changes, id, [RecordOpType.Patch, diff], doc, upgraded.value)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst { result, documentClock, changes } = this.storage.transaction(\n\t\t\t(txn) => {\n\t\t\t\tthis.broadcastChanges(txn)\n\t\t\t\t// collect actual ops that resulted from the push\n\t\t\t\t// these will be broadcast to other users\n\n\t\t\t\tconst docChanges: ActualChanges = { diffs: null }\n\t\t\t\tconst presenceChanges: ActualChanges = { diffs: null }\n\n\t\t\t\tif (this.presenceType && session?.presenceId && 'presence' in message && message.presence) {\n\t\t\t\t\tif (!session) throw new Error('session is required for presence pushes')\n\t\t\t\t\t// The push request was for the presence scope.\n\t\t\t\t\tconst id = session.presenceId\n\t\t\t\t\tconst [type, val] = message.presence\n\t\t\t\t\tconst { typeName } = this.presenceType\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase RecordOpType.Put: {\n\t\t\t\t\t\t\t// Try to put the document. If it fails, stop here.\n\t\t\t\t\t\t\taddDocument(this.presenceStore, presenceChanges, id, {\n\t\t\t\t\t\t\t\t...val,\n\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\ttypeName,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase RecordOpType.Patch: {\n\t\t\t\t\t\t\t// Try to patch the document. If it fails, stop here.\n\t\t\t\t\t\t\tpatchDocument(this.presenceStore, presenceChanges, id, {\n\t\t\t\t\t\t\t\t...val,\n\t\t\t\t\t\t\t\tid: [ValueOpType.Put, id],\n\t\t\t\t\t\t\t\ttypeName: [ValueOpType.Put, typeName],\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Per-op write gate: document-lane records are gated by `isReadonly`, object-lane\n\t\t\t\t// records by `objectAccess`. Denied ops are skipped (the client is corrected by the\n\t\t\t\t// resulting discard/rebase push_result, exactly as whole-diff readonly skips were).\n\t\t\t\t// Server-initiated pushes (no session) are always allowed.\n\t\t\t\tconst canWrite = (typeName: string) =>\n\t\t\t\t\t!session ||\n\t\t\t\t\t(this.objectTypes.has(typeName) ? session.objectAccess !== 'read' : !session.isReadonly)\n\n\t\t\t\tif (message.diff) {\n\t\t\t\t\t// The push request was for the document scope.\n\t\t\t\t\tfor (const [id, op] of objectMapEntriesIterable(message.diff!)) {\n\t\t\t\t\t\tswitch (op[0]) {\n\t\t\t\t\t\t\tcase RecordOpType.Put: {\n\t\t\t\t\t\t\t\t// The write gate is checked before type validation so that a denied\n\t\t\t\t\t\t\t\t// session's ops are skipped without rejection, matching the previous\n\t\t\t\t\t\t\t\t// whole-diff readonly behavior.\n\t\t\t\t\t\t\t\tif (!canWrite(op[1].typeName)) continue\n\t\t\t\t\t\t\t\t// Try to add the document.\n\t\t\t\t\t\t\t\t// If we're putting a record with a type that we don't recognize, fail\n\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t!this.documentTypes.has(op[1].typeName) &&\n\t\t\t\t\t\t\t\t\t!this.objectTypes.has(op[1].typeName)\n\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\tthrow new TLSyncError(\n\t\t\t\t\t\t\t\t\t\t'invalid record',\n\t\t\t\t\t\t\t\t\t\tTLSyncErrorCloseEventReason.INVALID_RECORD\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst record = op[1]\n\t\t\t\t\t\t\t\t// A put must not change the record's typeName. Two reasons, and the first\n\t\t\t\t\t\t\t\t// applies whether or not authorizers are configured: the write gate above\n\t\t\t\t\t\t\t\t// keyed off the *incoming* typeName, so a swap between lanes (document <->\n\t\t\t\t\t\t\t\t// object) would let a session denied on one lane write through the other by\n\t\t\t\t\t\t\t\t// relabeling an existing record. The second is that the authorizer lookup\n\t\t\t\t\t\t\t\t// also keys off the incoming typeName while the replace path validates\n\t\t\t\t\t\t\t\t// against the stored one, so a swap would consult the wrong authorizer (or\n\t\t\t\t\t\t\t\t// none). Skip it like a veto; the client self-corrects.\n\t\t\t\t\t\t\t\t// `undefined` (no session) means the guard didn't fetch, so addDocument will.\n\t\t\t\t\t\t\t\tconst prevRecord = session ? ((txn.get(id) as R | undefined) ?? null) : undefined\n\t\t\t\t\t\t\t\tif (session && prevRecord && prevRecord.typeName !== record.typeName) {\n\t\t\t\t\t\t\t\t\tthis.log?.warn?.(\n\t\t\t\t\t\t\t\t\t\t'skipping put that changes typeName',\n\t\t\t\t\t\t\t\t\t\t`${prevRecord.typeName} -> ${record.typeName}`,\n\t\t\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\t\t\t'session:',\n\t\t\t\t\t\t\t\t\t\tsession.sessionId\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// Per-type authorizer: stamp/veto the write from the session's identity.\n\t\t\t\t\t\t\t\t// Client pushes only; runs inside `addDocument`, on the up-migrated record.\n\t\t\t\t\t\t\t\tlet authorize: ((prev: R | null, next: R) => R | null) | undefined\n\t\t\t\t\t\t\t\tif (session && this.authorizeRecord) {\n\t\t\t\t\t\t\t\t\tconst authorizePut = this.authorizerFor(record.typeName)\n\t\t\t\t\t\t\t\t\tif (authorizePut) {\n\t\t\t\t\t\t\t\t\t\tauthorize = (prevRec, next) => {\n\t\t\t\t\t\t\t\t\t\t\tconst result = authorizePut(\n\t\t\t\t\t\t\t\t\t\t\t\tprevRec\n\t\t\t\t\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsession: {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsessionId: session.sessionId,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tisReadonly: session.isReadonly,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmeta: session.meta,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttype: 'update',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprev: prevRec,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnext,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsession: {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsessionId: session.sessionId,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tisReadonly: session.isReadonly,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmeta: session.meta,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttype: 'create',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprev: null,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnext,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\tif (!result) {\n\t\t\t\t\t\t\t\t\t\t\t\tthis.log?.warn?.(\n\t\t\t\t\t\t\t\t\t\t\t\t\t'authorizer vetoed put',\n\t\t\t\t\t\t\t\t\t\t\t\t\trecord.typeName,\n\t\t\t\t\t\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'session:',\n\t\t\t\t\t\t\t\t\t\t\t\t\tsession.sessionId\n\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\treturn null\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t// create: store the stamped record; update: allow/veto only\n\t\t\t\t\t\t\t\t\t\t\treturn prevRec ? next : result\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// The guard above already fetched this, so don't hit storage again.\n\t\t\t\t\t\t\t\taddDocument(txn, docChanges, id, record, authorize, prevRecord)\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcase RecordOpType.Patch: {\n\t\t\t\t\t\t\t\tconst doc = txn.get(id) as R | undefined\n\t\t\t\t\t\t\t\t// if it was already deleted, there's no need to apply the patch\n\t\t\t\t\t\t\t\tif (!doc) continue\n\t\t\t\t\t\t\t\tif (!canWrite(doc.typeName)) continue\n\t\t\t\t\t\t\t\t// Per-type authorizer (update, allow/veto only): runs inside `patchDocument`\n\t\t\t\t\t\t\t\t// on the committed candidate, never on a raw client-version preview.\n\t\t\t\t\t\t\t\tconst authorizePatch = session && this.authorizerFor(doc.typeName)\n\t\t\t\t\t\t\t\tconst authorize = authorizePatch\n\t\t\t\t\t\t\t\t\t? (prev: R, next: R) => {\n\t\t\t\t\t\t\t\t\t\t\tconst result = authorizePatch({\n\t\t\t\t\t\t\t\t\t\t\t\tsession: {\n\t\t\t\t\t\t\t\t\t\t\t\t\tsessionId: session.sessionId,\n\t\t\t\t\t\t\t\t\t\t\t\t\tisReadonly: session.isReadonly,\n\t\t\t\t\t\t\t\t\t\t\t\t\tmeta: session.meta,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\ttype: 'update',\n\t\t\t\t\t\t\t\t\t\t\t\tprev,\n\t\t\t\t\t\t\t\t\t\t\t\tnext,\n\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\tif (!result) {\n\t\t\t\t\t\t\t\t\t\t\t\tthis.log?.warn?.(\n\t\t\t\t\t\t\t\t\t\t\t\t\t'authorizer vetoed patch',\n\t\t\t\t\t\t\t\t\t\t\t\t\tdoc.typeName,\n\t\t\t\t\t\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'session:',\n\t\t\t\t\t\t\t\t\t\t\t\t\tsession.sessionId\n\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\treturn result\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t: undefined\n\t\t\t\t\t\t\t\t// Try to patch the document. If it fails, stop here. The write gate above\n\t\t\t\t\t\t\t\t// already fetched the record, so pass it through.\n\t\t\t\t\t\t\t\tpatchDocument(txn, docChanges, id, op[1], authorize, doc)\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcase RecordOpType.Remove: {\n\t\t\t\t\t\t\t\tconst doc = txn.get(id) as R | undefined\n\t\t\t\t\t\t\t\tif (!doc) {\n\t\t\t\t\t\t\t\t\t// If the doc was already deleted, don't do anything, no need to propagate a delete op\n\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (!canWrite(doc.typeName)) continue\n\t\t\t\t\t\t\t\t// Per-type authorizer (delete): veto deletes the session isn't allowed to make,\n\t\t\t\t\t\t\t\t// e.g. deleting someone else's comment. Allow/veto only.\n\t\t\t\t\t\t\t\tconst authorizeRemove = session && this.authorizerFor(doc.typeName)\n\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\tauthorizeRemove &&\n\t\t\t\t\t\t\t\t\t!authorizeRemove({\n\t\t\t\t\t\t\t\t\t\tsession: {\n\t\t\t\t\t\t\t\t\t\t\tsessionId: session.sessionId,\n\t\t\t\t\t\t\t\t\t\t\tisReadonly: session.isReadonly,\n\t\t\t\t\t\t\t\t\t\t\tmeta: session.meta,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\ttype: 'delete',\n\t\t\t\t\t\t\t\t\t\tprev: doc,\n\t\t\t\t\t\t\t\t\t\tnext: null,\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\tthis.log?.warn?.(\n\t\t\t\t\t\t\t\t\t\t'authorizer vetoed delete',\n\t\t\t\t\t\t\t\t\t\tdoc.typeName,\n\t\t\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\t\t\t'session:',\n\t\t\t\t\t\t\t\t\t\tsession.sessionId\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t// Delete the document and propagate the delete op\n\t\t\t\t\t\t\t\t// delete automatically creates tombstones\n\t\t\t\t\t\t\t\ttxn.delete(id)\n\t\t\t\t\t\t\t\tpropagateOp(docChanges, id, op, doc, undefined)\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn { docChanges, presenceChanges }\n\t\t\t},\n\t\t\t{ id: this.internalTxnId, emitChanges: 'when-different' }\n\t\t)\n\n\t\tthis.lastDocumentClock = documentClock\n\n\t\tlet pushResult: TLSocketServerSentEvent<R> | undefined\n\t\tif (changes && session) {\n\t\t\t// txn did not apply verbatim so we should broadcast the actual changes\n\t\t\tresult.docChanges.diffs = { networkDiff: toNetworkDiff(changes) ?? {}, diff: changes }\n\t\t}\n\n\t\tif (isEqual(result.docChanges.diffs?.networkDiff, message.diff)) {\n\t\t\tpushResult = {\n\t\t\t\ttype: 'push_result',\n\t\t\t\tclientClock: message.clientClock,\n\t\t\t\tserverClock: documentClock,\n\t\t\t\taction: 'commit',\n\t\t\t}\n\t\t} else if (!result.docChanges.diffs?.networkDiff) {\n\t\t\tpushResult = {\n\t\t\t\ttype: 'push_result',\n\t\t\t\tclientClock: message.clientClock,\n\t\t\t\tserverClock: documentClock,\n\t\t\t\taction: 'discard',\n\t\t\t}\n\t\t} else if (session) {\n\t\t\t// if recordsDiff is null but diff is not, then there are no clients that need down migrations\n\t\t\t// so we can just use the diff directly\n\t\t\tconst diff = this.migrateDiffOrRejectSession(\n\t\t\t\tsession.sessionId,\n\t\t\t\tsession.serializedSchema,\n\t\t\t\tsession.requiresDownMigrations,\n\t\t\t\tresult.docChanges.diffs.diff,\n\t\t\t\tresult.docChanges.diffs.networkDiff\n\t\t\t)\n\t\t\tif (diff.ok) {\n\t\t\t\tpushResult = {\n\t\t\t\t\ttype: 'push_result',\n\t\t\t\t\tclientClock: message.clientClock,\n\t\t\t\t\tserverClock: documentClock,\n\t\t\t\t\taction: { rebaseWithDiff: diff.value },\n\t\t\t\t}\n\t\t\t}\n\t\t\t// if the difff was not ok then the session was rejected and it's ok to continue without a push result\n\t\t}\n\n\t\tif (session && pushResult) {\n\t\t\tthis._unsafe_sendMessage(session.sessionId, pushResult)\n\t\t}\n\t\tif (result.docChanges.diffs || result.presenceChanges.diffs) {\n\t\t\tthis.broadcastPatch(\n\t\t\t\t{\n\t\t\t\t\tputs: {\n\t\t\t\t\t\t...result.docChanges.diffs?.diff.puts,\n\t\t\t\t\t\t...result.presenceChanges.diffs?.diff.puts,\n\t\t\t\t\t},\n\t\t\t\t\tdeletes: [\n\t\t\t\t\t\t...(result.docChanges.diffs?.diff.deletes ?? []),\n\t\t\t\t\t\t...(result.presenceChanges.diffs?.diff.deletes ?? []),\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t...result.docChanges.diffs?.networkDiff,\n\t\t\t\t\t...result.presenceChanges.diffs?.networkDiff,\n\t\t\t\t},\n\t\t\t\tsession?.sessionId\n\t\t\t)\n\t\t}\n\n\t\tif (result.presenceChanges.diffs) {\n\t\t\tqueueMicrotask(() => {\n\t\t\t\tthis.onPresenceChange?.()\n\t\t\t})\n\t\t}\n\n\t\tif (result.docChanges.diffs && this.onCommittedChanges) {\n\t\t\tconst diff = result.docChanges.diffs.diff\n\t\t\tqueueMicrotask(() => {\n\t\t\t\ttry {\n\t\t\t\t\tthis.onCommittedChanges?.({ diff, documentClock })\n\t\t\t\t} catch (e) {\n\t\t\t\t\tthis.log?.error?.('onCommittedChanges threw', e)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n\n\t/**\n\t * Handle the event when a client disconnects. Cleans up the session and\n\t * removes any presence information.\n\t *\n\t * @param sessionId - The session that disconnected\n\t * @example\n\t * ```ts\n\t * websocket.onClose(() => {\n\t * room.handleClose(sessionId)\n\t * })\n\t * ```\n\t */\n\thandleClose(sessionId: string) {\n\t\tthis.cancelSession(sessionId)\n\t}\n}\n\n/** @internal */\nexport interface MinimalDocStore<R extends UnknownRecord> {\n\tget(id: string): UnknownRecord | undefined\n\tset(id: string, record: R): void\n\tdelete(id: string): void\n}\n\n/** @internal */\nexport class PresenceStore<R extends UnknownRecord> implements MinimalDocStore<R> {\n\tprivate readonly presences = new AtomMap<string, R>('presences')\n\n\tget(id: string): UnknownRecord | undefined {\n\t\treturn this.presences.get(id)\n\t}\n\n\tset(id: string, state: R): void {\n\t\tthis.presences.set(id, state)\n\t}\n\n\tdelete(id: string): void {\n\t\tthis.presences.delete(id)\n\t}\n\n\tvalues() {\n\t\treturn this.presences.values()\n\t}\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAOO;AACP,mBAUO;AACP,wBAAiC;AACjC,kBAQO;AACP,sBAAyB;AACzB,sBAOO;AACP,wBAA0E;AAC1E,yBAMO;AAEP,0BAAoF;AACpF,2BAKO;AAiCA,MAAM,iCAAiC,MAAO;AAErD,MAAM,YAAY,CAAC,SAAiB,KAAK,IAAI,IAAI;AA2H1C,MAAM,WA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AA,EAC9B;AACD;",
4
+ "sourcesContent": ["import {\n\tAtomMap,\n\tMigrationFailureReason,\n\tRecordType,\n\tSerializedSchema,\n\tStoreSchema,\n\tUnknownRecord,\n} from '@tldraw/store'\nimport {\n\tassert,\n\tassertExists,\n\texhaustiveSwitchError,\n\tgetOwnProperty,\n\tisEqual,\n\tisNativeStructuredClone,\n\tobjectMapEntriesIterable,\n\tResult,\n\tthrottle,\n} from '@tldraw/utils'\nimport { createNanoEvents } from 'nanoevents'\nimport {\n\tapplyObjectDiff,\n\tdiffRecord,\n\tNetworkDiff,\n\tObjectDiff,\n\tRecordOp,\n\tRecordOpType,\n\tValueOpType,\n} from './diff'\nimport { interval } from './interval'\nimport {\n\tgetTlsyncProtocolVersion,\n\tTLIncompatibilityReason,\n\tTLObjectStoreAccess,\n\tTLSocketClientSentEvent,\n\tTLSocketServerSentDataEvent,\n\tTLSocketServerSentEvent,\n} from './protocol'\nimport { applyAndDiffRecord, diffAndValidateRecord, validateRecord } from './recordDiff'\nimport {\n\tRoomSession,\n\tRoomSessionState,\n\tSESSION_IDLE_TIMEOUT,\n\tSESSION_REMOVAL_WAIT_TIME,\n\tSESSION_START_WAIT_TIME,\n} from './RoomSession'\nimport { TLSyncLog } from './TLSocketRoom'\nimport { TLSyncError, TLSyncErrorCloseEventCode, TLSyncErrorCloseEventReason } from './TLSyncClient'\nimport {\n\tTLSyncForwardDiff,\n\tTLSyncStorage,\n\tTLSyncStorageTransaction,\n\ttoNetworkDiff,\n} from './TLSyncStorage'\n\n/**\n * WebSocket interface for server-side room connections. This defines the contract\n * that socket implementations must follow to work with TLSyncRoom.\n *\n * @internal\n */\nexport interface TLRoomSocket<R extends UnknownRecord> {\n\t/**\n\t * Whether the socket connection is currently open and ready to send messages.\n\t */\n\tisOpen: boolean\n\t/**\n\t * Send a message to the connected client through this socket.\n\t *\n\t * @param msg - The server-sent event message to transmit\n\t */\n\tsendMessage(msg: TLSocketServerSentEvent<R>): void\n\t/**\n\t * Close the socket connection with optional status code and reason.\n\t *\n\t * @param code - WebSocket close code (optional)\n\t * @param reason - Human-readable close reason (optional)\n\t */\n\tclose(code?: number, reason?: string): void\n}\n\n/**\n * The minimum time interval (in milliseconds) between sending batched data messages\n * to clients. This debouncing prevents overwhelming clients with rapid updates.\n * @public\n */\nexport const DATA_MESSAGE_DEBOUNCE_INTERVAL = 1000 / 60\n\nconst timeSince = (time: number) => Date.now() - time\n\n// WebSocket close frames cap the reason at 123 UTF-8 bytes; a longer one makes `close()` throw\nconst MAX_CLOSE_REASON_BYTES = 123\nconst closeReasonEncoder = new TextEncoder()\n\nconst truncatedSuffix = (droppedBytes: number) => `... (+${droppedBytes} bytes)`\n\nfunction truncateCloseReason(reason: string) {\n\tconst totalBytes = closeReasonEncoder.encode(reason).length\n\tif (totalBytes <= MAX_CLOSE_REASON_BYTES) return reason\n\t// the dropped count can't have more digits than the total, so reserving room for it always fits\n\tconst budget = MAX_CLOSE_REASON_BYTES - truncatedSuffix(totalBytes).length\n\tlet out = ''\n\tlet outBytes = 0\n\t// step by code point so a multi-byte character is never cut in half\n\tfor (const char of reason) {\n\t\tconst charBytes = closeReasonEncoder.encode(char).length\n\t\tif (outBytes + charBytes > budget) break\n\t\tout += char\n\t\toutBytes += charBytes\n\t}\n\treturn out + truncatedSuffix(totalBytes - outBytes)\n}\n\n/**\n * Snapshot of a room's complete state that can be persisted and restored.\n * Contains all documents, tombstones, and metadata needed to reconstruct the room.\n *\n * @public\n */\nexport interface RoomSnapshot {\n\t/**\n\t * The current logical clock value for the room\n\t */\n\tclock?: number\n\t/**\n\t * Clock value when document data was last changed (optional for backwards compatibility)\n\t */\n\tdocumentClock?: number\n\t/**\n\t * Array of all document records with their last modification clocks\n\t */\n\tdocuments: Array<{ state: UnknownRecord; lastChangedClock: number }>\n\t/**\n\t * Map of deleted record IDs to their deletion clock values (optional)\n\t */\n\ttombstones?: Record<string, number>\n\t/**\n\t * Clock value where tombstone history begins - older deletions are not tracked (optional)\n\t */\n\ttombstoneHistoryStartsAtClock?: number\n\t/**\n\t * Serialized schema used when creating this snapshot (optional)\n\t */\n\tschema?: SerializedSchema\n}\n\n/**\n * Authorizes a single record write from a client: any per-record, per-session rule the host wants\n * to enforce server-side \u2014 veto writes the session isn't allowed to make, or rewrite the record on\n * create. The session's `meta` carries whatever the rule needs (identity, roles, \u2026); for example,\n * force a comment's `authorId` to the signed-in user so nobody can post in someone else's name.\n *\n * Called on **create**, **update**, and **delete** of records whose `typeName` it's registered for\n * (see {@link TLRecordAuthorizers}), and only for client pushes \u2014 never for server-initiated writes.\n *\n * `prev` and `next` are always at the **server's** schema version: client writes are migrated\n * before the authorizer runs, so guarding or stamping a field never requires knowing what older\n * clients call it. On create, the record you return is what gets stored (after validation) \u2014 no\n * migration runs afterwards, so stamped fields can't be clobbered.\n *\n * Return `null` to reject the write \u2014 it's skipped and the client self-corrects, exactly like the\n * `objectAccess` gate. Otherwise the write is allowed, and:\n *\n * - on **create**, the record you return is what gets stored, so stamp identity fields here (e.g.\n * set `authorId` from `session.meta`);\n * - on **update** and **delete**, only allow-vs-reject is used (the returned record's contents are\n * ignored), so use them to veto changes to immutable fields or unauthorized deletes \u2014 return\n * `next`/`prev` to allow, `null` to reject.\n *\n * \u26A0\uFE0E Runs synchronously inside the commit transaction, on the same path as every document edit \u2014 it\n * must be fast and do **no** I/O. `next`/`prev` are client-controlled records, so treat their\n * contents as untrusted; prefer returning `null` to reject over throwing, though a throw is\n * caught, logged, and treated as a rejection (fail closed) rather than crashing the push. For\n * expensive, async checks (e.g. resolving mentions against who can access a file), react after the\n * fact via `onCommittedChanges`.\n *\n * @public\n */\nexport type TLRecordAuthorizer<Rec extends UnknownRecord, SessionMeta> = (\n\targs: {\n\t\t/** The session performing the write: its host-provided `meta` (e.g. the authenticated user\n\t\t * id) and the canvas-lane `isReadonly` state, for hosts whose object-lane policy follows\n\t\t * canvas access. */\n\t\tsession: { sessionId: string; isReadonly: boolean; meta: SessionMeta }\n\t} & (\n\t\t| { type: 'create'; prev: null; next: Rec }\n\t\t| { type: 'update'; prev: Rec; next: Rec }\n\t\t| { type: 'delete'; prev: Rec; next: null }\n\t)\n) => Rec | null\n\n/**\n * A map from record `typeName` to a {@link TLRecordAuthorizer} for that record type. Only listed\n * types are authorized; every other record writes through untouched, so this stays off the hot path\n * for the vast majority of writes (shape drags etc.).\n *\n * Each authorizer is typed to its record \u2014 e.g. `next` in the `comment` entry is a `TLComment` \u2014 so\n * renaming a field on the record makes the authorizer that reads it fail to compile, rather than\n * silently stamp or guard the wrong field.\n *\n * Presence records are never authorized (presence is per-session and ephemeral); registering the\n * presence typeName is a construction-time error.\n *\n * @public\n */\nexport type TLRecordAuthorizers<R extends UnknownRecord, SessionMeta> = {\n\t[K in R['typeName']]?: TLRecordAuthorizer<Extract<R, { typeName: K }>, SessionMeta>\n}\n\n/**\n * A collaborative workspace that manages multiple client sessions and synchronizes\n * document changes between them. The room serves as the authoritative source for\n * all document state and handles conflict resolution, schema migrations, and\n * real-time data distribution.\n *\n * @example\n * ```ts\n * const room = new TLSyncRoom({\n * schema: mySchema,\n * onDataChange: () => saveToDatabase(room.getSnapshot()),\n * onPresenceChange: () => updateLiveCursors()\n * })\n *\n * // Handle new client connections\n * room.handleNewSession({\n * sessionId: 'user-123',\n * socket: webSocketAdapter,\n * meta: { userId: '123', name: 'Alice' },\n * isReadonly: false\n * })\n * ```\n *\n * @internal\n */\nexport class TLSyncRoom<R extends UnknownRecord, SessionMeta> {\n\t// A table of connected clients\n\treadonly sessions = new Map<string, RoomSession<R, SessionMeta>>()\n\n\tprivate lastDocumentClock = 0\n\n\tprivate pruneTimer: ReturnType<typeof setTimeout> | null = null\n\n\tpruneSessions = throttle(() => {\n\t\tif (this.pruneTimer) {\n\t\t\tclearTimeout(this.pruneTimer)\n\t\t\tthis.pruneTimer = null\n\t\t}\n\t\tfor (const client of this.sessions.values()) {\n\t\t\tswitch (client.state) {\n\t\t\t\tcase RoomSessionState.Connected: {\n\t\t\t\t\tconst hasTimedOut = timeSince(client.lastInteractionTime) > this.sessionIdleTimeout\n\t\t\t\t\tif (hasTimedOut || !client.socket.isOpen) {\n\t\t\t\t\t\tthis.cancelSession(client.sessionId)\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcase RoomSessionState.AwaitingConnectMessage: {\n\t\t\t\t\tconst hasTimedOut = timeSince(client.sessionStartTime) > SESSION_START_WAIT_TIME\n\t\t\t\t\tif (hasTimedOut || !client.socket.isOpen) {\n\t\t\t\t\t\t// remove immediately\n\t\t\t\t\t\tthis.removeSession(client.sessionId)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.scheduleFollowUpPrune()\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcase RoomSessionState.AwaitingRemoval: {\n\t\t\t\t\tconst hasTimedOut = timeSince(client.cancellationTime) > SESSION_REMOVAL_WAIT_TIME\n\t\t\t\t\tif (hasTimedOut) {\n\t\t\t\t\t\tthis.removeSession(client.sessionId)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.scheduleFollowUpPrune()\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\texhaustiveSwitchError(client)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}, 1000)\n\n\tprivate scheduleFollowUpPrune() {\n\t\t// don't leave a stray timer on a room the host has already torn down\n\t\tif (this._isClosed || this.pruneTimer) return\n\t\tthis.pruneTimer = setTimeout(this.pruneSessions, SESSION_REMOVAL_WAIT_TIME + 100)\n\t}\n\n\treadonly presenceStore = new PresenceStore<R>()\n\n\tprivate disposables: Array<() => void> = []\n\n\tprivate _isClosed = false\n\n\t/**\n\t * Close the room and clean up all resources. Disconnects all sessions\n\t * and stops background processes.\n\t */\n\tclose() {\n\t\tthis._isClosed = true\n\t\tthis.disposables.forEach((d) => d())\n\t\tthis.sessions.forEach((session) => {\n\t\t\tthis.clearDebounceTimer(session)\n\t\t\ttry {\n\t\t\t\tsession.socket.close()\n\t\t\t} catch {\n\t\t\t\t// noop, one bad socket must not leave the rest open\n\t\t\t}\n\t\t})\n\t\t// forgetting the sessions is what makes late socket close/error events no-ops, so\n\t\t// nothing can emit session_removed / room_became_empty on a closed room\n\t\tthis.sessions.clear()\n\t}\n\n\tprivate clearDebounceTimer(session: RoomSession<R, SessionMeta>) {\n\t\tif (session.state === RoomSessionState.Connected && session.debounceTimer !== null) {\n\t\t\tclearTimeout(session.debounceTimer)\n\t\t\tsession.debounceTimer = null\n\t\t\tsession.outstandingDataMessages = []\n\t\t}\n\t}\n\n\t/**\n\t * Check if the room has been closed and is no longer accepting connections.\n\t *\n\t * @returns True if the room is closed\n\t */\n\tisClosed() {\n\t\treturn this._isClosed\n\t}\n\n\treadonly events = createNanoEvents<{\n\t\troom_became_empty(): void\n\t\tsession_removed(args: { sessionId: string; meta: SessionMeta }): void\n\t}>()\n\n\t// Storage layer for documents, tombstones, and clocks\n\tprivate readonly storage: TLSyncStorage<R>\n\n\treadonly serializedSchema: SerializedSchema\n\n\treadonly documentTypes: Set<string>\n\t/**\n\t * Record types served by the object-store lane. Object records ride the same wire messages\n\t * as document records but are gated by the session's `objectAccess` instead of `isReadonly`,\n\t * and are excluded from `documentTypes` so hosts can persist them in a separate lane.\n\t */\n\treadonly objectTypes: Set<string>\n\treadonly presenceType: RecordType<R, any> | null\n\tprivate log?: TLSyncLog\n\tpublic readonly schema: StoreSchema<R, any>\n\tprivate onPresenceChange?(): void\n\tprivate onCommittedChanges?(args: { diff: TLSyncForwardDiff<R>; documentClock: number }): void\n\tprivate readonly authorizeRecord?: TLRecordAuthorizers<R, SessionMeta>\n\tprivate readonly sessionIdleTimeout: number\n\n\t/**\n\t * The authorizer registered for a record type, widened to the room's record union. Each entry in\n\t * `authorizeRecord` is typed to its specific record; the cast here is the one place we can't\n\t * statically correlate a runtime `typeName` with its record type, so it lives in the library\n\t * rather than in every consumer.\n\t */\n\tprivate authorizerFor(typeName: R['typeName']): TLRecordAuthorizer<R, SessionMeta> | undefined {\n\t\tconst authorize = this.authorizeRecord?.[typeName] as\n\t\t\t| TLRecordAuthorizer<R, SessionMeta>\n\t\t\t| undefined\n\t\tif (!authorize) return undefined\n\t\t// Fail closed: an authorizer that throws rejects the write (and is logged) rather than\n\t\t// aborting the whole push. Authorizers are security-sensitive, so a bug must never let a\n\t\t// write through.\n\t\treturn (args) => {\n\t\t\ttry {\n\t\t\t\treturn authorize(args)\n\t\t\t} catch (e) {\n\t\t\t\tthis.log?.error?.('record authorizer threw; rejecting the write', e)\n\t\t\t\treturn null\n\t\t\t}\n\t\t}\n\t}\n\n\tconstructor(opts: {\n\t\tlog?: TLSyncLog\n\t\tschema: StoreSchema<R, any>\n\t\tonPresenceChange?(): void\n\t\t/**\n\t\t * Called once after a client push commits, with the committed document diff. Fires for\n\t\t * local and remote pushes. Use this to react to document changes (e.g. persist certain\n\t\t * record types to a separate lane, or project them to an external store) as soon as they\n\t\t * commit. Best-effort \u2014 do not throw; do not block.\n\t\t */\n\t\tonCommittedChanges?(args: { diff: TLSyncForwardDiff<R>; documentClock: number }): void\n\t\t/**\n\t\t * Record type names to serve through the object-store lane instead of the document lane.\n\t\t * Each must be a document-scoped type registered in the schema. Object-lane writes are\n\t\t * gated per session by `objectAccess` rather than `isReadonly`.\n\t\t */\n\t\tobjectTypes?: readonly string[]\n\t\t/**\n\t\t * Per-type authorizers for client record writes (create, update, delete): veto or, on\n\t\t * create, rewrite. See {@link TLRecordAuthorizers}.\n\t\t */\n\t\tauthorizeRecord?: TLRecordAuthorizers<R, SessionMeta>\n\t\tstorage: TLSyncStorage<R>\n\t\tclientTimeout?: number\n\t}) {\n\t\tthis.schema = opts.schema\n\t\tthis.log = opts.log\n\t\tthis.onPresenceChange = opts.onPresenceChange\n\t\tthis.onCommittedChanges = opts.onCommittedChanges\n\t\tthis.authorizeRecord = opts.authorizeRecord\n\t\tthis.storage = opts.storage\n\t\tthis.sessionIdleTimeout = opts.clientTimeout ?? SESSION_IDLE_TIMEOUT\n\n\t\tassert(\n\t\t\tisNativeStructuredClone,\n\t\t\t'TLSyncRoom is supposed to run either on Cloudflare Workers' +\n\t\t\t\t'or on a 18+ version of Node.js, which both support the native structuredClone API'\n\t\t)\n\n\t\t// do a json serialization cycle to make sure the schema has no 'undefined' values\n\t\tthis.serializedSchema = JSON.parse(JSON.stringify(this.schema.serialize()))\n\n\t\tthis.objectTypes = new Set(opts.objectTypes ?? [])\n\t\tfor (const typeName of this.objectTypes) {\n\t\t\tconst type = getOwnProperty(this.schema.types, typeName)\n\t\t\tassert(type, `TLSyncRoom: object type '${typeName}' is not registered in the schema`)\n\t\t\tassert(\n\t\t\t\ttype.scope === 'document',\n\t\t\t\t`TLSyncRoom: object type '${typeName}' must have scope 'document', got '${type.scope}'`\n\t\t\t)\n\t\t}\n\n\t\t// object-lane types are partitioned out of the document lane\n\t\tthis.documentTypes = new Set(\n\t\t\tObject.values<RecordType<R, any>>(this.schema.types)\n\t\t\t\t.filter((t) => t.scope === 'document' && !this.objectTypes.has(t.typeName))\n\t\t\t\t.map((t) => t.typeName)\n\t\t)\n\n\t\tconst presenceTypes = new Set(\n\t\t\tObject.values<RecordType<R, any>>(this.schema.types).filter((t) => t.scope === 'presence')\n\t\t)\n\n\t\tif (presenceTypes.size > 1) {\n\t\t\tthrow new Error(\n\t\t\t\t`TLSyncRoom: exactly zero or one presence type is expected, but found ${presenceTypes.size}`\n\t\t\t)\n\t\t}\n\n\t\tthis.presenceType = presenceTypes.values().next()?.value ?? null\n\n\t\t// The presence lane never consults authorizers, so a presence key in `authorizeRecord`\n\t\t// would be a silent no-op \u2014 fail loudly at construction instead.\n\t\tif (this.presenceType && this.authorizeRecord) {\n\t\t\tassert(\n\t\t\t\t!getOwnProperty(this.authorizeRecord, this.presenceType.typeName),\n\t\t\t\t`TLSyncRoom: authorizeRecord['${this.presenceType.typeName}'] is a presence type; presence records are not authorized`\n\t\t\t)\n\t\t}\n\n\t\tconst { documentClock } = this.storage.transaction((txn) => {\n\t\t\tthis.schema.migrateStorage(txn)\n\t\t})\n\n\t\tthis.lastDocumentClock = documentClock\n\n\t\tthis.disposables.push(\n\t\t\tthis.storage.onChange(({ id }) => {\n\t\t\t\tif (id !== this.internalTxnId) {\n\t\t\t\t\tthis.broadcastExternalStorageChanges()\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\n\t\tthis.disposables.push(() => {\n\t\t\tthis.pruneSessions.cancel()\n\t\t\tif (this.pruneTimer) {\n\t\t\t\tclearTimeout(this.pruneTimer)\n\t\t\t\tthis.pruneTimer = null\n\t\t\t}\n\t\t})\n\n\t\t// When clientTimeout is finite, run periodic pruning so idle sessions are\n\t\t// cleaned up even with no traffic. When Infinity or 0 we skip the interval\n\t\t// (e.g. for hibernation); without it, pruning only runs on message or when\n\t\t// socket close/error triggers cancelSession, so pruning idle sessions\n\t\t// reliably depends on the runtime delivering those events.\n\t\tif (Number.isFinite(this.sessionIdleTimeout) && this.sessionIdleTimeout > 0) {\n\t\t\tconst pruneIntervalMs = Math.min(2000, Math.floor(this.sessionIdleTimeout / 4))\n\t\t\tthis.disposables.push(interval(() => this.pruneSessions(), pruneIntervalMs))\n\t\t}\n\t}\n\tprivate broadcastExternalStorageChanges() {\n\t\tthis.storage.transaction((txn) => {\n\t\t\tthis.broadcastChanges(txn)\n\t\t\tthis.lastDocumentClock = txn.getClock()\n\t\t}) // no id needed because this only reads, no writes.\n\t}\n\n\t/**\n\t * Send a message to a particular client. Debounces data events\n\t *\n\t * @param sessionId - The id of the session to send the message to.\n\t * @param message - The message to send. UNSAFE Any diffs must have been downgraded already if necessary\n\t */\n\tprivate _unsafe_sendMessage(\n\t\tsessionId: string,\n\t\tmessage: TLSocketServerSentEvent<R> | TLSocketServerSentDataEvent<R>\n\t) {\n\t\tconst session = this.sessions.get(sessionId)\n\t\tif (!session) {\n\t\t\tthis.log?.warn?.('Tried to send message to unknown session', message.type)\n\t\t\treturn\n\t\t}\n\t\tif (session.state !== RoomSessionState.Connected) {\n\t\t\tthis.log?.warn?.('Tried to send message to disconnected client', message.type)\n\t\t\treturn\n\t\t}\n\t\tif (session.socket.isOpen) {\n\t\t\tif (message.type !== 'patch' && message.type !== 'push_result') {\n\t\t\t\t// this is not a data message\n\t\t\t\tif (message.type !== 'pong') {\n\t\t\t\t\t// non-data messages like \"connect\" might still need to be ordered correctly with\n\t\t\t\t\t// respect to data messages, so it's better to flush just in case\n\t\t\t\t\tthis._flushDataMessages(sessionId)\n\t\t\t\t}\n\t\t\t\tsession.socket.sendMessage(message)\n\t\t\t} else {\n\t\t\t\tif (session.debounceTimer === null) {\n\t\t\t\t\t// this is the first message since the last flush, don't delay it\n\t\t\t\t\tsession.socket.sendMessage({ type: 'data', data: [message] })\n\n\t\t\t\t\tsession.debounceTimer = setTimeout(\n\t\t\t\t\t\t() => this._flushDataMessages(sessionId),\n\t\t\t\t\t\tDATA_MESSAGE_DEBOUNCE_INTERVAL\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\tsession.outstandingDataMessages.push(message)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tthis.cancelSession(session.sessionId)\n\t\t}\n\t}\n\n\t// needs to accept sessionId and not a session because the session might be dead by the time\n\t// the timer fires\n\t_flushDataMessages(sessionId: string) {\n\t\tconst session = this.sessions.get(sessionId)\n\n\t\tif (!session || session.state !== RoomSessionState.Connected) {\n\t\t\treturn\n\t\t}\n\n\t\tsession.debounceTimer = null\n\n\t\tif (session.outstandingDataMessages.length > 0) {\n\t\t\t// hand the buffer over and start a fresh one, rather than truncating in\n\t\t\t// place, so sockets that defer serialization don't see an emptied array\n\t\t\tconst data = session.outstandingDataMessages\n\t\t\tsession.outstandingDataMessages = []\n\t\t\tif (!session.socket.isOpen) {\n\t\t\t\t// same as the immediate-send path: send() into a closed socket throws on\n\t\t\t\t// some runtimes (Cloudflare), and here that would be from inside a timer\n\t\t\t\tthis.cancelSession(sessionId)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tsession.socket.sendMessage({ type: 'data', data })\n\t\t}\n\t}\n\n\t/** @internal */\n\tprivate removeSession(sessionId: string, fatalReason?: string) {\n\t\tconst session = this.sessions.get(sessionId)\n\t\tif (!session) {\n\t\t\tthis.log?.warn?.('Tried to remove unknown session')\n\t\t\treturn\n\t\t}\n\n\t\tthis.sessions.delete(sessionId)\n\t\tthis.clearDebounceTimer(session)\n\n\t\ttry {\n\t\t\tif (fatalReason) {\n\t\t\t\t// the session is already gone, so a throwing close() would leave its socket open\n\t\t\t\tsession.socket.close(TLSyncErrorCloseEventCode, truncateCloseReason(fatalReason))\n\t\t\t} else {\n\t\t\t\tsession.socket.close()\n\t\t\t}\n\t\t} catch {\n\t\t\t// noop, calling .close() multiple times is fine\n\t\t}\n\n\t\tconst presence = this.presenceStore.get(session.presenceId ?? '')\n\t\tif (presence) {\n\t\t\tthis.presenceStore.delete(session.presenceId!)\n\t\t\t// Broadcast presence removal - use RecordsDiff with the removed record\n\t\t\tthis.broadcastPatch({\n\t\t\t\tputs: {},\n\t\t\t\tdeletes: [session.presenceId!],\n\t\t\t})\n\t\t}\n\n\t\tthis.events.emit('session_removed', { sessionId, meta: session.meta })\n\t\tif (this.sessions.size === 0) {\n\t\t\tthis.events.emit('room_became_empty')\n\t\t}\n\t}\n\n\tprivate cancelSession(sessionId: string) {\n\t\tconst session = this.sessions.get(sessionId)\n\t\tif (!session) {\n\t\t\treturn\n\t\t}\n\n\t\tif (session.state === RoomSessionState.AwaitingRemoval) {\n\t\t\tthis.log?.warn?.('Tried to cancel session that is already awaiting removal')\n\t\t\treturn\n\t\t}\n\n\t\tthis.clearDebounceTimer(session)\n\t\tthis.sessions.set(sessionId, {\n\t\t\tstate: RoomSessionState.AwaitingRemoval,\n\t\t\tsessionId,\n\t\t\tpresenceId: session.presenceId,\n\t\t\tsocket: session.socket,\n\t\t\tcancellationTime: Date.now(),\n\t\t\tmeta: session.meta,\n\t\t\tisReadonly: session.isReadonly,\n\t\t\tobjectAccess: session.objectAccess,\n\t\t\trequiresLegacyRejection: session.requiresLegacyRejection,\n\t\t\tsupportsStringAppend: session.supportsStringAppend,\n\t\t})\n\n\t\ttry {\n\t\t\tsession.socket.close()\n\t\t} catch {\n\t\t\t// noop, calling .close() multiple times is fine\n\t\t}\n\n\t\tthis.scheduleFollowUpPrune()\n\t}\n\n\treadonly internalTxnId = 'TLSyncRoom.txn'\n\n\t/**\n\t * Broadcast a patch to all connected clients except the one with the sessionId provided.\n\t *\n\t * @param diff - The TLSyncForwardDiff with full records (used for migration)\n\t * @param networkDiff - Optional pre-computed NetworkDiff for sessions not needing migration.\n\t * If not provided, will be computed from recordsDiff.\n\t * @param sourceSessionId - Optional session ID to exclude from the broadcast\n\t */\n\tprivate broadcastPatch(\n\t\tdiff: TLSyncForwardDiff<R>,\n\t\tnetworkDiff?: NetworkDiff<R> | null,\n\t\tsourceSessionId?: string\n\t) {\n\t\t// Pre-compute network diff if not provided\n\t\tconst unmigrated = networkDiff ?? toNetworkDiff(diff)\n\t\tif (!unmigrated) return this\n\n\t\tthis.sessions.forEach((session) => {\n\t\t\tif (session.state !== RoomSessionState.Connected) return\n\t\t\tif (sourceSessionId === session.sessionId) return\n\t\t\tif (!session.socket.isOpen) {\n\t\t\t\tthis.cancelSession(session.sessionId)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tconst diffResult = this.migrateDiffOrRejectSession(\n\t\t\t\tsession.sessionId,\n\t\t\t\tsession.serializedSchema,\n\t\t\t\tsession.requiresDownMigrations,\n\t\t\t\tdiff\n\t\t\t)\n\t\t\tif (!diffResult.ok) return\n\n\t\t\tthis._unsafe_sendMessage(session.sessionId, {\n\t\t\t\ttype: 'patch',\n\t\t\t\tdiff: diffResult.value,\n\t\t\t\tserverClock: this.lastDocumentClock,\n\t\t\t})\n\t\t})\n\t\treturn this\n\t}\n\n\t/**\n\t * Send a custom message to a connected client. Useful for application-specific\n\t * communication that doesn't involve document synchronization.\n\t *\n\t * @param sessionId - The ID of the session to send the message to\n\t * @param data - The custom payload to send (will be JSON serialized)\n\t * @example\n\t * ```ts\n\t * // Send a custom notification\n\t * room.sendCustomMessage('user-123', {\n\t * type: 'notification',\n\t * message: 'Document saved successfully'\n\t * })\n\t *\n\t * // Send user-specific data\n\t * room.sendCustomMessage('user-456', {\n\t * type: 'user_permissions',\n\t * canEdit: true,\n\t * canDelete: false\n\t * })\n\t * ```\n\t */\n\tsendCustomMessage(sessionId: string, data: any): void {\n\t\tthis._unsafe_sendMessage(sessionId, { type: 'custom', data })\n\t}\n\n\t/**\n\t * Register a new client session with the room. The session will be in an awaiting\n\t * state until it sends a connect message with protocol handshake.\n\t *\n\t * @param opts - Session configuration\n\t * - sessionId - Unique identifier for this session\n\t * - socket - WebSocket adapter for communication\n\t * - meta - Application-specific metadata for this session\n\t * - isReadonly - Whether this session can modify documents\n\t * @returns This room instance for method chaining\n\t * @example\n\t * ```ts\n\t * room.handleNewSession({\n\t * sessionId: crypto.randomUUID(),\n\t * socket: new WebSocketAdapter(ws),\n\t * meta: { userId: '123', name: 'Alice', avatar: 'url' },\n\t * isReadonly: !hasEditPermission\n\t * })\n\t * ```\n\t *\n\t * @internal\n\t */\n\thandleNewSession(opts: {\n\t\tsessionId: string\n\t\tsocket: TLRoomSocket<R>\n\t\tmeta: SessionMeta\n\t\tisReadonly: boolean\n\t\tobjectAccess?: TLObjectStoreAccess\n\t}) {\n\t\tconst { sessionId, socket, meta, isReadonly, objectAccess } = opts\n\t\t// a connect racing close() would otherwise create a session nothing ever prunes\n\t\tif (this._isClosed) {\n\t\t\tsocket.close()\n\t\t\treturn this\n\t\t}\n\t\tconst existing = this.sessions.get(sessionId)\n\t\tif (existing) this.clearDebounceTimer(existing)\n\t\tthis.sessions.set(sessionId, {\n\t\t\tstate: RoomSessionState.AwaitingConnectMessage,\n\t\t\tsessionId,\n\t\t\tsocket,\n\t\t\tpresenceId: existing?.presenceId ?? this.presenceType?.createId() ?? null,\n\t\t\tsessionStartTime: Date.now(),\n\t\t\tmeta,\n\t\t\tisReadonly: isReadonly ?? false,\n\t\t\tobjectAccess: objectAccess ?? 'write',\n\t\t\t// this gets set later during handleConnectMessage\n\t\t\trequiresLegacyRejection: false,\n\t\t\tsupportsStringAppend: true,\n\t\t})\n\t\treturn this\n\t}\n\n\t/**\n\t * Resume a previously-connected session directly into `Connected` state, bypassing the\n\t * connect handshake. Used after server hibernation when the WebSocket is still alive but\n\t * all in-memory state has been lost.\n\t *\n\t * @internal\n\t */\n\thandleResumedSession(opts: {\n\t\tsessionId: string\n\t\tsocket: TLRoomSocket<R>\n\t\tmeta: SessionMeta\n\t\tisReadonly: boolean\n\t\tobjectAccess?: TLObjectStoreAccess\n\t\tserializedSchema: SerializedSchema\n\t\tpresenceId: string | null\n\t\tpresenceRecord: UnknownRecord | null\n\t\trequiresLegacyRejection: boolean\n\t\tsupportsStringAppend: boolean\n\t}) {\n\t\tconst {\n\t\t\tsessionId,\n\t\t\tsocket,\n\t\t\tmeta,\n\t\t\tisReadonly,\n\t\t\tobjectAccess,\n\t\t\tserializedSchema,\n\t\t\tpresenceId,\n\t\t\tpresenceRecord,\n\t\t\trequiresLegacyRejection,\n\t\t\tsupportsStringAppend,\n\t\t} = opts\n\n\t\tif (this._isClosed) {\n\t\t\tsocket.close()\n\t\t\treturn\n\t\t}\n\n\t\tconst migrations = this.schema.getMigrationsSince(serializedSchema)\n\t\tconst requiresDownMigrations = migrations.ok ? migrations.value.length > 0 : false\n\n\t\tthis.sessions.set(sessionId, {\n\t\t\tstate: RoomSessionState.Connected,\n\t\t\tsessionId,\n\t\t\tsocket,\n\t\t\tpresenceId: presenceId ?? this.presenceType?.createId() ?? null,\n\t\t\tserializedSchema,\n\t\t\trequiresDownMigrations,\n\t\t\tlastInteractionTime: Date.now(),\n\t\t\tdebounceTimer: null,\n\t\t\toutstandingDataMessages: [],\n\t\t\tmeta,\n\t\t\tisReadonly,\n\t\t\tobjectAccess: objectAccess ?? 'write',\n\t\t\trequiresLegacyRejection,\n\t\t\tsupportsStringAppend,\n\t\t})\n\n\t\tif (presenceRecord && presenceId) {\n\t\t\tthis.presenceStore.set(presenceId, presenceRecord as R)\n\t\t}\n\t}\n\n\t/**\n\t * Checks if all connected sessions support string append operations (protocol version 8+).\n\t * If any client is on an older version, returns false to enable legacy append mode.\n\t *\n\t * @returns True if all connected sessions are on protocol version 8 or higher\n\t */\n\tgetCanEmitStringAppend(): boolean {\n\t\tfor (const session of this.sessions.values()) {\n\t\t\tif (session.state === RoomSessionState.Connected) {\n\t\t\t\tif (!session.supportsStringAppend) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\n\t/**\n\t * When we send a diff to a client, if that client is on a lower version than us, we need to make\n\t * the diff compatible with their version. This method takes a TLSyncForwardDiff (which has full\n\t * records) and migrates all records down to the client's schema version, returning a NetworkDiff.\n\t *\n\t * For updates (entries with [before, after] tuples), both records are migrated and a patch is\n\t * computed from the migrated versions, preserving efficient patch semantics even across versions.\n\t *\n\t * If a migration fails, the session will be rejected.\n\t *\n\t * @param sessionId - The session ID (for rejection on migration failure)\n\t * @param serializedSchema - The client's schema to migrate to\n\t * @param requiresDownMigrations - Whether the client needs down migrations\n\t * @param diff - The TLSyncForwardDiff containing full records to migrate\n\t * @param unmigrated - Optional pre-computed NetworkDiff for when no migration is needed\n\t * @returns A NetworkDiff with migrated records, or a migration failure\n\t */\n\tprivate migrateDiffOrRejectSession(\n\t\tsessionId: string,\n\t\tserializedSchema: SerializedSchema,\n\t\trequiresDownMigrations: boolean,\n\t\tdiff: TLSyncForwardDiff<R>,\n\t\tunmigrated?: NetworkDiff<R>\n\t): Result<NetworkDiff<R>, MigrationFailureReason> {\n\t\tif (!requiresDownMigrations) {\n\t\t\treturn Result.ok(unmigrated ?? toNetworkDiff(diff) ?? {})\n\t\t}\n\n\t\tconst result: NetworkDiff<R> = {}\n\n\t\t// Migrate puts (either adds or updates)\n\t\tfor (const [id, put] of objectMapEntriesIterable(diff.puts)) {\n\t\t\tif (Array.isArray(put)) {\n\t\t\t\t// Update: [before, after] tuple - migrate both and compute patch\n\t\t\t\tconst [from, to] = put\n\t\t\t\tconst fromResult = this.schema.migratePersistedRecord(from, serializedSchema, 'down')\n\t\t\t\tif (fromResult.type === 'error') {\n\t\t\t\t\tthis.rejectSession(sessionId, TLSyncErrorCloseEventReason.CLIENT_TOO_OLD)\n\t\t\t\t\treturn Result.err(fromResult.reason)\n\t\t\t\t}\n\t\t\t\tconst toResult = this.schema.migratePersistedRecord(to, serializedSchema, 'down')\n\t\t\t\tif (toResult.type === 'error') {\n\t\t\t\t\tthis.rejectSession(sessionId, TLSyncErrorCloseEventReason.CLIENT_TOO_OLD)\n\t\t\t\t\treturn Result.err(toResult.reason)\n\t\t\t\t}\n\t\t\t\tconst patch = diffRecord(fromResult.value, toResult.value)\n\t\t\t\tif (patch) {\n\t\t\t\t\tresult[id] = [RecordOpType.Patch, patch]\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Add: single record - migrate and put\n\t\t\t\tconst migrationResult = this.schema.migratePersistedRecord(put, serializedSchema, 'down')\n\t\t\t\tif (migrationResult.type === 'error') {\n\t\t\t\t\tthis.rejectSession(sessionId, TLSyncErrorCloseEventReason.CLIENT_TOO_OLD)\n\t\t\t\t\treturn Result.err(migrationResult.reason)\n\t\t\t\t}\n\t\t\t\tresult[id] = [RecordOpType.Put, migrationResult.value]\n\t\t\t}\n\t\t}\n\n\t\t// Deletes don't need migration\n\t\tfor (const id of diff.deletes) {\n\t\t\tresult[id] = [RecordOpType.Remove]\n\t\t}\n\n\t\treturn Result.ok(result)\n\t}\n\n\t/**\n\t * Process an incoming message from a client session. Handles connection requests,\n\t * data synchronization pushes, and ping/pong for connection health.\n\t *\n\t * @param sessionId - The ID of the session that sent the message\n\t * @param message - The client message to process\n\t * @example\n\t * ```ts\n\t * // Typically called by WebSocket message handlers\n\t * websocket.onMessage((data) => {\n\t * const message = JSON.parse(data)\n\t * room.handleMessage(sessionId, message)\n\t * })\n\t * ```\n\t */\n\tasync handleMessage(sessionId: string, message: TLSocketClientSentEvent<R>) {\n\t\tconst session = this.sessions.get(sessionId)\n\t\tif (!session) {\n\t\t\tthis.log?.warn?.('Received message from unknown session')\n\t\t\treturn\n\t\t}\n\t\ttry {\n\t\t\tswitch (message.type) {\n\t\t\t\tcase 'connect': {\n\t\t\t\t\treturn this.handleConnectRequest(session, message)\n\t\t\t\t}\n\t\t\t\tcase 'push': {\n\t\t\t\t\treturn this.handlePushRequest(session, message)\n\t\t\t\t}\n\t\t\t\tcase 'ping': {\n\t\t\t\t\tif (session.state === RoomSessionState.Connected) {\n\t\t\t\t\t\tsession.lastInteractionTime = Date.now()\n\t\t\t\t\t}\n\t\t\t\t\treturn this._unsafe_sendMessage(session.sessionId, { type: 'pong' })\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\texhaustiveSwitchError(message)\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof TLSyncError) {\n\t\t\t\tthis.rejectSession(session.sessionId, e.reason)\n\t\t\t} else {\n\t\t\t\t// log error and reboot the room?\n\t\t\t\tthrow e\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Reject and disconnect a session due to incompatibility or other fatal errors.\n\t * Sends appropriate error messages before closing the connection.\n\t *\n\t * @param sessionId - The session to reject\n\t * @param fatalReason - The reason for rejection (optional). WebSocket close reasons are capped\n\t * at 123 UTF-8 bytes, so a longer reason is truncated and ends with `... (+N bytes)`.\n\t * @example\n\t * ```ts\n\t * // Reject due to version mismatch\n\t * room.rejectSession('user-123', TLSyncErrorCloseEventReason.CLIENT_TOO_OLD)\n\t *\n\t * // Reject due to permission issue\n\t * room.rejectSession('user-456', 'Insufficient permissions')\n\t * ```\n\t */\n\trejectSession(sessionId: string, fatalReason?: TLSyncErrorCloseEventReason | string) {\n\t\tconst session = this.sessions.get(sessionId)\n\t\tif (!session) return\n\t\tif (!fatalReason) {\n\t\t\tthis.removeSession(sessionId)\n\t\t\treturn\n\t\t}\n\t\tif (session.requiresLegacyRejection) {\n\t\t\ttry {\n\t\t\t\tif (session.socket.isOpen) {\n\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-deprecated\n\t\t\t\t\tlet legacyReason: TLIncompatibilityReason\n\t\t\t\t\tswitch (fatalReason) {\n\t\t\t\t\t\tcase TLSyncErrorCloseEventReason.CLIENT_TOO_OLD:\n\t\t\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-deprecated\n\t\t\t\t\t\t\tlegacyReason = TLIncompatibilityReason.ClientTooOld\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tcase TLSyncErrorCloseEventReason.SERVER_TOO_OLD:\n\t\t\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-deprecated\n\t\t\t\t\t\t\tlegacyReason = TLIncompatibilityReason.ServerTooOld\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tcase TLSyncErrorCloseEventReason.INVALID_RECORD:\n\t\t\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-deprecated\n\t\t\t\t\t\t\tlegacyReason = TLIncompatibilityReason.InvalidRecord\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-deprecated\n\t\t\t\t\t\t\tlegacyReason = TLIncompatibilityReason.InvalidOperation\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tsession.socket.sendMessage({\n\t\t\t\t\t\ttype: 'incompatibility_error',\n\t\t\t\t\t\treason: legacyReason,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// noop\n\t\t\t} finally {\n\t\t\t\tthis.removeSession(sessionId)\n\t\t\t}\n\t\t} else {\n\t\t\tthis.removeSession(sessionId, fatalReason)\n\t\t}\n\t}\n\n\tprivate forceAllReconnect() {\n\t\tfor (const session of this.sessions.values()) {\n\t\t\tthis.removeSession(session.sessionId)\n\t\t}\n\t}\n\n\tprivate broadcastChanges(txn: TLSyncStorageTransaction<R>) {\n\t\tconst changes = txn.getChangesSince(this.lastDocumentClock)\n\t\tif (!changes) return\n\t\tconst { wipeAll, diff } = changes\n\t\tthis.lastDocumentClock = txn.getClock()\n\t\tif (wipeAll) {\n\t\t\t// If this happens it means we'd need to broadcast a wipe_all message to all clients,\n\t\t\t// which is not part of the protocol yet, so we need to force all clients to reconnect instead.\n\t\t\tthis.forceAllReconnect()\n\t\t\treturn\n\t\t}\n\t\tthis.broadcastPatch(diff)\n\t}\n\n\t/**\n\t * Work out whether a client we can't reconcile schemas with is running a newer or older SDK\n\t * than us.\n\t */\n\tprivate getVersionMismatchReason(theirSchema: SerializedSchema) {\n\t\tconst ourSchema = this.serializedSchema\n\n\t\tif (theirSchema.schemaVersion > ourSchema.schemaVersion) {\n\t\t\treturn TLSyncErrorCloseEventReason.SERVER_TOO_OLD\n\t\t}\n\n\t\tif (theirSchema.schemaVersion === 2 && ourSchema.schemaVersion === 2) {\n\t\t\tfor (const [sequenceId, theirVersion] of Object.entries(theirSchema.sequences)) {\n\t\t\t\tconst ourVersion = ourSchema.sequences[sequenceId]\n\t\t\t\tif (ourVersion === undefined || theirVersion > ourVersion) {\n\t\t\t\t\treturn TLSyncErrorCloseEventReason.SERVER_TOO_OLD\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn TLSyncErrorCloseEventReason.CLIENT_TOO_OLD\n\t}\n\n\tprivate handleConnectRequest(\n\t\tsession: RoomSession<R, SessionMeta>,\n\t\tmessage: Extract<TLSocketClientSentEvent<R>, { type: 'connect' }>\n\t) {\n\t\t// if the protocol versions don't match, disconnect the client\n\t\t// we will eventually want to try to make our protocol backwards compatible to some degree\n\t\t// and have a MIN_PROTOCOL_VERSION constant that the TLSyncRoom implements support for\n\t\tlet theirProtocolVersion = message.protocolVersion\n\t\t// 5 is the same as 6\n\t\tif (theirProtocolVersion === 5) {\n\t\t\ttheirProtocolVersion = 6\n\t\t}\n\t\t// 6 is almost the same as 7\n\t\tsession.requiresLegacyRejection = theirProtocolVersion === 6\n\t\tif (theirProtocolVersion === 6) {\n\t\t\ttheirProtocolVersion++\n\t\t}\n\t\tif (theirProtocolVersion === 7) {\n\t\t\ttheirProtocolVersion++\n\t\t\tsession.supportsStringAppend = false\n\t\t}\n\n\t\tif (theirProtocolVersion == null || theirProtocolVersion < getTlsyncProtocolVersion()) {\n\t\t\tthis.rejectSession(session.sessionId, TLSyncErrorCloseEventReason.CLIENT_TOO_OLD)\n\t\t\treturn\n\t\t} else if (theirProtocolVersion > getTlsyncProtocolVersion()) {\n\t\t\tthis.rejectSession(session.sessionId, TLSyncErrorCloseEventReason.SERVER_TOO_OLD)\n\t\t\treturn\n\t\t}\n\t\t// If the client's store is at a different version to ours, it could cause corruption.\n\t\t// We should disconnect the client and ask them to refresh.\n\t\tif (message.schema == null) {\n\t\t\tthis.rejectSession(session.sessionId, TLSyncErrorCloseEventReason.CLIENT_TOO_OLD)\n\t\t\treturn\n\t\t}\n\t\tconst migrations = this.schema.getMigrationsSince(message.schema)\n\t\tif (!migrations.ok) {\n\t\t\tthis.rejectSession(session.sessionId, this.getVersionMismatchReason(message.schema))\n\t\t\treturn\n\t\t}\n\t\t// The client's schema is older than ours, but we can't migrate our data down to their\n\t\t// version (a migration isn't record-scoped or has no down migration), so they're too old.\n\t\tif (migrations.value.some((m) => m.scope !== 'record' || !m.down)) {\n\t\t\tthis.rejectSession(session.sessionId, TLSyncErrorCloseEventReason.CLIENT_TOO_OLD)\n\t\t\treturn\n\t\t}\n\n\t\tconst sessionSchema = isEqual(message.schema, this.serializedSchema)\n\t\t\t? this.serializedSchema\n\t\t\t: message.schema\n\n\t\tconst requiresDownMigrations = migrations.value.length > 0\n\n\t\tconst connect = async (msg: Extract<TLSocketServerSentEvent<R>, { type: 'connect' }>) => {\n\t\t\tthis.sessions.set(session.sessionId, {\n\t\t\t\tstate: RoomSessionState.Connected,\n\t\t\t\tsessionId: session.sessionId,\n\t\t\t\tpresenceId: session.presenceId,\n\t\t\t\tsocket: session.socket,\n\t\t\t\tserializedSchema: sessionSchema,\n\t\t\t\trequiresDownMigrations,\n\t\t\t\tlastInteractionTime: Date.now(),\n\t\t\t\tdebounceTimer: null,\n\t\t\t\toutstandingDataMessages: [],\n\t\t\t\tsupportsStringAppend: session.supportsStringAppend,\n\t\t\t\tmeta: session.meta,\n\t\t\t\tisReadonly: session.isReadonly,\n\t\t\t\tobjectAccess: session.objectAccess,\n\t\t\t\trequiresLegacyRejection: session.requiresLegacyRejection,\n\t\t\t})\n\t\t\tthis._unsafe_sendMessage(session.sessionId, msg)\n\t\t}\n\n\t\tconst { documentClock, result } = this.storage.transaction((txn) => {\n\t\t\tthis.broadcastChanges(txn)\n\t\t\tconst docChanges = txn.getChangesSince(message.lastServerClock)\n\t\t\tconst presenceDiff = this.migrateDiffOrRejectSession(\n\t\t\t\tsession.sessionId,\n\t\t\t\tsessionSchema,\n\t\t\t\trequiresDownMigrations,\n\t\t\t\t{\n\t\t\t\t\t// Exclude the connecting session's own presence \u2014 it will push fresh\n\t\t\t\t\t// data immediately after connecting. Sending the stale record back\n\t\t\t\t\t// would leave an orphaned presence in the client's local store (the\n\t\t\t\t\t// server never echoes a session's own updates back to it).\n\t\t\t\t\tputs: Object.fromEntries(\n\t\t\t\t\t\t[...this.presenceStore.values()]\n\t\t\t\t\t\t\t.filter((p) => p.id !== session.presenceId)\n\t\t\t\t\t\t\t.map((p) => [p.id, p])\n\t\t\t\t\t),\n\t\t\t\t\tdeletes: [],\n\t\t\t\t}\n\t\t\t)\n\t\t\tif (!presenceDiff.ok) return null\n\n\t\t\t// Migrate the diff if needed, or use the pre-computed network diff\n\t\t\tlet docDiff: NetworkDiff<R> | null = null\n\t\t\tif (docChanges && sessionSchema !== this.serializedSchema) {\n\t\t\t\tconst migrated = this.migrateDiffOrRejectSession(\n\t\t\t\t\tsession.sessionId,\n\t\t\t\t\tsessionSchema,\n\t\t\t\t\trequiresDownMigrations,\n\t\t\t\t\tdocChanges.diff\n\t\t\t\t)\n\t\t\t\tif (!migrated.ok) return null\n\t\t\t\tdocDiff = migrated.value\n\t\t\t} else if (docChanges) {\n\t\t\t\tdocDiff = toNetworkDiff(docChanges.diff)\n\t\t\t}\n\t\t\treturn {\n\t\t\t\ttype: 'connect',\n\t\t\t\tconnectRequestId: message.connectRequestId,\n\t\t\t\thydrationType: docChanges?.wipeAll ? 'wipe_all' : 'wipe_presence',\n\t\t\t\tprotocolVersion: getTlsyncProtocolVersion(),\n\t\t\t\tschema: this.schema.serialize(),\n\t\t\t\tserverClock: txn.getClock(),\n\t\t\t\tdiff: { ...presenceDiff.value, ...docDiff },\n\t\t\t\tisReadonly: session.isReadonly,\n\t\t\t\tobjectAccess: session.objectAccess,\n\t\t\t} satisfies Extract<TLSocketServerSentEvent<R>, { type: 'connect' }>\n\t\t}) // no id needed because this only reads, no writes.\n\n\t\tthis.lastDocumentClock = documentClock\n\n\t\tif (result) {\n\t\t\tconnect(result)\n\t\t}\n\t}\n\n\tprivate handlePushRequest(\n\t\tsession: RoomSession<R, SessionMeta> | null,\n\t\tmessage: Extract<TLSocketClientSentEvent<R>, { type: 'push' }>\n\t) {\n\t\t// We must be connected to handle push requests\n\t\tif (session && session.state !== RoomSessionState.Connected) {\n\t\t\treturn\n\t\t}\n\t\t// update the last interaction time\n\t\tif (session) {\n\t\t\tsession.lastInteractionTime = Date.now()\n\t\t}\n\n\t\tconst legacyAppendMode = !this.getCanEmitStringAppend()\n\n\t\tinterface ActualChanges {\n\t\t\tdiffs: {\n\t\t\t\tnetworkDiff: NetworkDiff<R>\n\t\t\t\tdiff: TLSyncForwardDiff<R>\n\t\t\t} | null\n\t\t}\n\n\t\tconst propagateOp = (\n\t\t\tchanges: ActualChanges,\n\t\t\tid: string,\n\t\t\top: RecordOp<R>,\n\t\t\tbefore: R | undefined,\n\t\t\tafter: R | undefined\n\t\t) => {\n\t\t\tif (!changes.diffs) changes.diffs = { networkDiff: {}, diff: { puts: {}, deletes: [] } }\n\t\t\tchanges.diffs.networkDiff[id] = op\n\t\t\tswitch (op[0]) {\n\t\t\t\tcase RecordOpType.Put:\n\t\t\t\t\tchanges.diffs.diff.puts[id] = op[1]\n\t\t\t\t\tbreak\n\t\t\t\tcase RecordOpType.Patch:\n\t\t\t\t\tassert(before && after, 'before and after are required for patches')\n\t\t\t\t\tchanges.diffs.diff.puts[id] = [before, after]\n\t\t\t\t\tbreak\n\t\t\t\tcase RecordOpType.Remove:\n\t\t\t\t\tchanges.diffs.diff.deletes.push(id)\n\t\t\t\t\tbreak\n\t\t\t\tdefault:\n\t\t\t\t\texhaustiveSwitchError(op[0])\n\t\t\t}\n\t\t}\n\n\t\tconst addDocument = (\n\t\t\tstorage: MinimalDocStore<R>,\n\t\t\tchanges: ActualChanges,\n\t\t\tid: string,\n\t\t\t_state: R,\n\t\t\tauthorize?: (prev: R | null, next: R) => R | null,\n\t\t\t// The existing document if the caller already fetched it; `null` for fetched-and-absent,\n\t\t\t// `undefined` for not fetched. Saves a second SELECT + JSON.parse on the push hot path.\n\t\t\tprevDoc?: R | null\n\t\t): Result<void, void> => {\n\t\t\tconst res = session\n\t\t\t\t? this.schema.migratePersistedRecord(_state, session.serializedSchema, 'up')\n\t\t\t\t: { type: 'success' as const, value: _state }\n\t\t\tif (res.type === 'error') {\n\t\t\t\tthrow new TLSyncError(res.reason, TLSyncErrorCloseEventReason.CLIENT_TOO_OLD)\n\t\t\t}\n\t\t\tlet { value: state } = res\n\n\t\t\t// Get the existing document, if any\n\t\t\tconst doc =\n\t\t\t\tprevDoc !== undefined ? (prevDoc ?? undefined) : (storage.get(id) as R | undefined)\n\n\t\t\t// Authorize on the up-migrated record; on create the authorizer's return is stored as-is,\n\t\t\t// so no later migration can clobber stamped fields.\n\t\t\tif (authorize) {\n\t\t\t\tconst result = authorize(doc ?? null, state)\n\t\t\t\tif (!result) return Result.ok(undefined) // vetoed: skip the op, the client self-corrects\n\t\t\t\tif (!doc) state = result // create: store the authorizer's (stamped) record\n\t\t\t}\n\n\t\t\tif (doc) {\n\t\t\t\t// If there's an existing document, replace it with the new state\n\t\t\t\t// but propagate a diff rather than the entire value\n\t\t\t\tconst recordType = assertExists(getOwnProperty(this.schema.types, doc.typeName))\n\t\t\t\tconst diff = diffAndValidateRecord(doc, state, recordType)\n\t\t\t\tif (diff) {\n\t\t\t\t\tstorage.set(id, state)\n\t\t\t\t\tpropagateOp(changes, id, [RecordOpType.Patch, diff], doc, state)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Otherwise, if we don't already have a document with this id\n\t\t\t\t// create the document and propagate the put op\n\t\t\t\t// set automatically clears tombstones if they exist\n\t\t\t\tconst recordType = assertExists(getOwnProperty(this.schema.types, state.typeName))\n\t\t\t\tvalidateRecord(state, recordType)\n\t\t\t\tstorage.set(id, state)\n\t\t\t\tpropagateOp(changes, id, [RecordOpType.Put, state], undefined, undefined)\n\t\t\t}\n\n\t\t\treturn Result.ok(undefined)\n\t\t}\n\n\t\tconst patchDocument = (\n\t\t\tstorage: MinimalDocStore<R>,\n\t\t\tchanges: ActualChanges,\n\t\t\tid: string,\n\t\t\tpatch: ObjectDiff,\n\t\t\tauthorize?: (prev: R, next: R) => R | null,\n\t\t\t// The existing document if the caller already fetched it (see `addDocument`).\n\t\t\tprevDoc?: R\n\t\t) => {\n\t\t\t// if it was already deleted, there's no need to apply the patch\n\t\t\tconst doc = prevDoc ?? (storage.get(id) as R | undefined)\n\t\t\tif (!doc) return\n\n\t\t\tconst recordType = assertExists(getOwnProperty(this.schema.types, doc.typeName))\n\t\t\t// If the client's version of the record is older than ours,\n\t\t\t// we apply the patch to the downgraded version of the record\n\t\t\tconst downgraded = session\n\t\t\t\t? this.schema.migratePersistedRecord(doc, session.serializedSchema, 'down')\n\t\t\t\t: { type: 'success' as const, value: doc }\n\t\t\tif (downgraded.type === 'error') {\n\t\t\t\tthrow new TLSyncError(downgraded.reason, TLSyncErrorCloseEventReason.CLIENT_TOO_OLD)\n\t\t\t}\n\n\t\t\tif (downgraded.value === doc) {\n\t\t\t\t// If the versions are compatible, apply the patch and propagate the patch op\n\t\t\t\tconst diff = applyAndDiffRecord(doc, patch, recordType, legacyAppendMode)\n\t\t\t\tif (diff) {\n\t\t\t\t\t// Authorize on the committed candidate \u2014 the record that will actually be stored.\n\t\t\t\t\tif (authorize && !authorize(doc, diff[1])) return\n\t\t\t\t\tstorage.set(id, diff[1])\n\t\t\t\t\tpropagateOp(changes, id, [RecordOpType.Patch, diff[0]], doc, diff[1])\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// need to apply the patch to the downgraded version and then upgrade it\n\n\t\t\t\t// apply the patch to the downgraded version\n\t\t\t\tconst patched = applyObjectDiff(downgraded.value, patch)\n\t\t\t\t// then upgrade the patched version and use that as the new state\n\t\t\t\tconst upgraded = session\n\t\t\t\t\t? this.schema.migratePersistedRecord(patched, session.serializedSchema, 'up')\n\t\t\t\t\t: { type: 'success' as const, value: patched }\n\t\t\t\t// If the client's version is too old, we'll hit an error\n\t\t\t\tif (upgraded.type === 'error') {\n\t\t\t\t\tthrow new TLSyncError(upgraded.reason, TLSyncErrorCloseEventReason.CLIENT_TOO_OLD)\n\t\t\t\t}\n\t\t\t\t// replace the state with the upgraded version and propagate the patch op\n\t\t\t\tconst diff = diffAndValidateRecord(doc, upgraded.value, recordType, legacyAppendMode)\n\t\t\t\tif (diff) {\n\t\t\t\t\t// Authorize on the committed candidate \u2014 the upgraded record, not a raw preview.\n\t\t\t\t\tif (authorize && !authorize(doc, upgraded.value)) return\n\t\t\t\t\tstorage.set(id, upgraded.value)\n\t\t\t\t\tpropagateOp(changes, id, [RecordOpType.Patch, diff], doc, upgraded.value)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst { result, documentClock, changes } = this.storage.transaction(\n\t\t\t(txn) => {\n\t\t\t\tthis.broadcastChanges(txn)\n\t\t\t\t// collect actual ops that resulted from the push\n\t\t\t\t// these will be broadcast to other users\n\n\t\t\t\tconst docChanges: ActualChanges = { diffs: null }\n\t\t\t\tconst presenceChanges: ActualChanges = { diffs: null }\n\n\t\t\t\tif (this.presenceType && session?.presenceId && 'presence' in message && message.presence) {\n\t\t\t\t\tif (!session) throw new Error('session is required for presence pushes')\n\t\t\t\t\t// The push request was for the presence scope.\n\t\t\t\t\tconst id = session.presenceId\n\t\t\t\t\tconst [type, val] = message.presence\n\t\t\t\t\tconst { typeName } = this.presenceType\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase RecordOpType.Put: {\n\t\t\t\t\t\t\t// Try to put the document. If it fails, stop here.\n\t\t\t\t\t\t\taddDocument(this.presenceStore, presenceChanges, id, {\n\t\t\t\t\t\t\t\t...val,\n\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\ttypeName,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase RecordOpType.Patch: {\n\t\t\t\t\t\t\t// Try to patch the document. If it fails, stop here.\n\t\t\t\t\t\t\tpatchDocument(this.presenceStore, presenceChanges, id, {\n\t\t\t\t\t\t\t\t...val,\n\t\t\t\t\t\t\t\tid: [ValueOpType.Put, id],\n\t\t\t\t\t\t\t\ttypeName: [ValueOpType.Put, typeName],\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Per-op write gate: document-lane records are gated by `isReadonly`, object-lane\n\t\t\t\t// records by `objectAccess`. Denied ops are skipped (the client is corrected by the\n\t\t\t\t// resulting discard/rebase push_result, exactly as whole-diff readonly skips were).\n\t\t\t\t// Server-initiated pushes (no session) are always allowed.\n\t\t\t\tconst canWrite = (typeName: string) =>\n\t\t\t\t\t!session ||\n\t\t\t\t\t(this.objectTypes.has(typeName) ? session.objectAccess !== 'read' : !session.isReadonly)\n\n\t\t\t\tif (message.diff) {\n\t\t\t\t\t// The push request was for the document scope.\n\t\t\t\t\tfor (const [id, op] of objectMapEntriesIterable(message.diff!)) {\n\t\t\t\t\t\tswitch (op[0]) {\n\t\t\t\t\t\t\tcase RecordOpType.Put: {\n\t\t\t\t\t\t\t\t// The write gate is checked before type validation so that a denied\n\t\t\t\t\t\t\t\t// session's ops are skipped without rejection, matching the previous\n\t\t\t\t\t\t\t\t// whole-diff readonly behavior.\n\t\t\t\t\t\t\t\tif (!canWrite(op[1].typeName)) continue\n\t\t\t\t\t\t\t\t// Try to add the document.\n\t\t\t\t\t\t\t\t// If we're putting a record with a type that we don't recognize, fail\n\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t!this.documentTypes.has(op[1].typeName) &&\n\t\t\t\t\t\t\t\t\t!this.objectTypes.has(op[1].typeName)\n\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\tthrow new TLSyncError(\n\t\t\t\t\t\t\t\t\t\t'invalid record',\n\t\t\t\t\t\t\t\t\t\tTLSyncErrorCloseEventReason.INVALID_RECORD\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst record = op[1]\n\t\t\t\t\t\t\t\t// A put must not change the record's typeName. Two reasons, and the first\n\t\t\t\t\t\t\t\t// applies whether or not authorizers are configured: the write gate above\n\t\t\t\t\t\t\t\t// keyed off the *incoming* typeName, so a swap between lanes (document <->\n\t\t\t\t\t\t\t\t// object) would let a session denied on one lane write through the other by\n\t\t\t\t\t\t\t\t// relabeling an existing record. The second is that the authorizer lookup\n\t\t\t\t\t\t\t\t// also keys off the incoming typeName while the replace path validates\n\t\t\t\t\t\t\t\t// against the stored one, so a swap would consult the wrong authorizer (or\n\t\t\t\t\t\t\t\t// none). Skip it like a veto; the client self-corrects.\n\t\t\t\t\t\t\t\t// `undefined` (no session) means the guard didn't fetch, so addDocument will.\n\t\t\t\t\t\t\t\tconst prevRecord = session ? ((txn.get(id) as R | undefined) ?? null) : undefined\n\t\t\t\t\t\t\t\tif (session && prevRecord && prevRecord.typeName !== record.typeName) {\n\t\t\t\t\t\t\t\t\tthis.log?.warn?.(\n\t\t\t\t\t\t\t\t\t\t'skipping put that changes typeName',\n\t\t\t\t\t\t\t\t\t\t`${prevRecord.typeName} -> ${record.typeName}`,\n\t\t\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\t\t\t'session:',\n\t\t\t\t\t\t\t\t\t\tsession.sessionId\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// Per-type authorizer: stamp/veto the write from the session's identity.\n\t\t\t\t\t\t\t\t// Client pushes only; runs inside `addDocument`, on the up-migrated record.\n\t\t\t\t\t\t\t\tlet authorize: ((prev: R | null, next: R) => R | null) | undefined\n\t\t\t\t\t\t\t\tif (session && this.authorizeRecord) {\n\t\t\t\t\t\t\t\t\tconst authorizePut = this.authorizerFor(record.typeName)\n\t\t\t\t\t\t\t\t\tif (authorizePut) {\n\t\t\t\t\t\t\t\t\t\tauthorize = (prevRec, next) => {\n\t\t\t\t\t\t\t\t\t\t\tconst result = authorizePut(\n\t\t\t\t\t\t\t\t\t\t\t\tprevRec\n\t\t\t\t\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsession: {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsessionId: session.sessionId,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tisReadonly: session.isReadonly,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmeta: session.meta,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttype: 'update',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprev: prevRec,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnext,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsession: {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsessionId: session.sessionId,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tisReadonly: session.isReadonly,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmeta: session.meta,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttype: 'create',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprev: null,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnext,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\tif (!result) {\n\t\t\t\t\t\t\t\t\t\t\t\tthis.log?.warn?.(\n\t\t\t\t\t\t\t\t\t\t\t\t\t'authorizer vetoed put',\n\t\t\t\t\t\t\t\t\t\t\t\t\trecord.typeName,\n\t\t\t\t\t\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'session:',\n\t\t\t\t\t\t\t\t\t\t\t\t\tsession.sessionId\n\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\treturn null\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t// create: store the stamped record; update: allow/veto only\n\t\t\t\t\t\t\t\t\t\t\treturn prevRec ? next : result\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// The guard above already fetched this, so don't hit storage again.\n\t\t\t\t\t\t\t\taddDocument(txn, docChanges, id, record, authorize, prevRecord)\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcase RecordOpType.Patch: {\n\t\t\t\t\t\t\t\tconst doc = txn.get(id) as R | undefined\n\t\t\t\t\t\t\t\t// if it was already deleted, there's no need to apply the patch\n\t\t\t\t\t\t\t\tif (!doc) continue\n\t\t\t\t\t\t\t\tif (!canWrite(doc.typeName)) continue\n\t\t\t\t\t\t\t\t// Per-type authorizer (update, allow/veto only): runs inside `patchDocument`\n\t\t\t\t\t\t\t\t// on the committed candidate, never on a raw client-version preview.\n\t\t\t\t\t\t\t\tconst authorizePatch = session && this.authorizerFor(doc.typeName)\n\t\t\t\t\t\t\t\tconst authorize = authorizePatch\n\t\t\t\t\t\t\t\t\t? (prev: R, next: R) => {\n\t\t\t\t\t\t\t\t\t\t\tconst result = authorizePatch({\n\t\t\t\t\t\t\t\t\t\t\t\tsession: {\n\t\t\t\t\t\t\t\t\t\t\t\t\tsessionId: session.sessionId,\n\t\t\t\t\t\t\t\t\t\t\t\t\tisReadonly: session.isReadonly,\n\t\t\t\t\t\t\t\t\t\t\t\t\tmeta: session.meta,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\ttype: 'update',\n\t\t\t\t\t\t\t\t\t\t\t\tprev,\n\t\t\t\t\t\t\t\t\t\t\t\tnext,\n\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\tif (!result) {\n\t\t\t\t\t\t\t\t\t\t\t\tthis.log?.warn?.(\n\t\t\t\t\t\t\t\t\t\t\t\t\t'authorizer vetoed patch',\n\t\t\t\t\t\t\t\t\t\t\t\t\tdoc.typeName,\n\t\t\t\t\t\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'session:',\n\t\t\t\t\t\t\t\t\t\t\t\t\tsession.sessionId\n\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\treturn result\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t: undefined\n\t\t\t\t\t\t\t\t// Try to patch the document. If it fails, stop here. The write gate above\n\t\t\t\t\t\t\t\t// already fetched the record, so pass it through.\n\t\t\t\t\t\t\t\tpatchDocument(txn, docChanges, id, op[1], authorize, doc)\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcase RecordOpType.Remove: {\n\t\t\t\t\t\t\t\tconst doc = txn.get(id) as R | undefined\n\t\t\t\t\t\t\t\tif (!doc) {\n\t\t\t\t\t\t\t\t\t// If the doc was already deleted, don't do anything, no need to propagate a delete op\n\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (!canWrite(doc.typeName)) continue\n\t\t\t\t\t\t\t\t// Per-type authorizer (delete): veto deletes the session isn't allowed to make,\n\t\t\t\t\t\t\t\t// e.g. deleting someone else's comment. Allow/veto only.\n\t\t\t\t\t\t\t\tconst authorizeRemove = session && this.authorizerFor(doc.typeName)\n\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\tauthorizeRemove &&\n\t\t\t\t\t\t\t\t\t!authorizeRemove({\n\t\t\t\t\t\t\t\t\t\tsession: {\n\t\t\t\t\t\t\t\t\t\t\tsessionId: session.sessionId,\n\t\t\t\t\t\t\t\t\t\t\tisReadonly: session.isReadonly,\n\t\t\t\t\t\t\t\t\t\t\tmeta: session.meta,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\ttype: 'delete',\n\t\t\t\t\t\t\t\t\t\tprev: doc,\n\t\t\t\t\t\t\t\t\t\tnext: null,\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\tthis.log?.warn?.(\n\t\t\t\t\t\t\t\t\t\t'authorizer vetoed delete',\n\t\t\t\t\t\t\t\t\t\tdoc.typeName,\n\t\t\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\t\t\t'session:',\n\t\t\t\t\t\t\t\t\t\tsession.sessionId\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t// Delete the document and propagate the delete op\n\t\t\t\t\t\t\t\t// delete automatically creates tombstones\n\t\t\t\t\t\t\t\ttxn.delete(id)\n\t\t\t\t\t\t\t\tpropagateOp(docChanges, id, op, doc, undefined)\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn { docChanges, presenceChanges }\n\t\t\t},\n\t\t\t{ id: this.internalTxnId, emitChanges: 'when-different' }\n\t\t)\n\n\t\tthis.lastDocumentClock = documentClock\n\n\t\tlet pushResult: TLSocketServerSentEvent<R> | undefined\n\t\tif (changes && session) {\n\t\t\t// txn did not apply verbatim so we should broadcast the actual changes\n\t\t\tresult.docChanges.diffs = { networkDiff: toNetworkDiff(changes) ?? {}, diff: changes }\n\t\t}\n\n\t\tif (isEqual(result.docChanges.diffs?.networkDiff, message.diff)) {\n\t\t\tpushResult = {\n\t\t\t\ttype: 'push_result',\n\t\t\t\tclientClock: message.clientClock,\n\t\t\t\tserverClock: documentClock,\n\t\t\t\taction: 'commit',\n\t\t\t}\n\t\t} else if (!result.docChanges.diffs?.networkDiff) {\n\t\t\tpushResult = {\n\t\t\t\ttype: 'push_result',\n\t\t\t\tclientClock: message.clientClock,\n\t\t\t\tserverClock: documentClock,\n\t\t\t\taction: 'discard',\n\t\t\t}\n\t\t} else if (session) {\n\t\t\t// if recordsDiff is null but diff is not, then there are no clients that need down migrations\n\t\t\t// so we can just use the diff directly\n\t\t\tconst diff = this.migrateDiffOrRejectSession(\n\t\t\t\tsession.sessionId,\n\t\t\t\tsession.serializedSchema,\n\t\t\t\tsession.requiresDownMigrations,\n\t\t\t\tresult.docChanges.diffs.diff,\n\t\t\t\tresult.docChanges.diffs.networkDiff\n\t\t\t)\n\t\t\tif (diff.ok) {\n\t\t\t\tpushResult = {\n\t\t\t\t\ttype: 'push_result',\n\t\t\t\t\tclientClock: message.clientClock,\n\t\t\t\t\tserverClock: documentClock,\n\t\t\t\t\taction: { rebaseWithDiff: diff.value },\n\t\t\t\t}\n\t\t\t}\n\t\t\t// if the difff was not ok then the session was rejected and it's ok to continue without a push result\n\t\t}\n\n\t\tif (session && pushResult) {\n\t\t\tthis._unsafe_sendMessage(session.sessionId, pushResult)\n\t\t}\n\t\tif (result.docChanges.diffs || result.presenceChanges.diffs) {\n\t\t\tthis.broadcastPatch(\n\t\t\t\t{\n\t\t\t\t\tputs: {\n\t\t\t\t\t\t...result.docChanges.diffs?.diff.puts,\n\t\t\t\t\t\t...result.presenceChanges.diffs?.diff.puts,\n\t\t\t\t\t},\n\t\t\t\t\tdeletes: [\n\t\t\t\t\t\t...(result.docChanges.diffs?.diff.deletes ?? []),\n\t\t\t\t\t\t...(result.presenceChanges.diffs?.diff.deletes ?? []),\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t...result.docChanges.diffs?.networkDiff,\n\t\t\t\t\t...result.presenceChanges.diffs?.networkDiff,\n\t\t\t\t},\n\t\t\t\tsession?.sessionId\n\t\t\t)\n\t\t}\n\n\t\tif (result.presenceChanges.diffs) {\n\t\t\tqueueMicrotask(() => {\n\t\t\t\tthis.onPresenceChange?.()\n\t\t\t})\n\t\t}\n\n\t\tif (result.docChanges.diffs && this.onCommittedChanges) {\n\t\t\tconst diff = result.docChanges.diffs.diff\n\t\t\tqueueMicrotask(() => {\n\t\t\t\ttry {\n\t\t\t\t\tthis.onCommittedChanges?.({ diff, documentClock })\n\t\t\t\t} catch (e) {\n\t\t\t\t\tthis.log?.error?.('onCommittedChanges threw', e)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n\n\t/**\n\t * Handle the event when a client disconnects. Cleans up the session and\n\t * removes any presence information.\n\t *\n\t * @param sessionId - The session that disconnected\n\t * @example\n\t * ```ts\n\t * websocket.onClose(() => {\n\t * room.handleClose(sessionId)\n\t * })\n\t * ```\n\t */\n\thandleClose(sessionId: string) {\n\t\tthis.cancelSession(sessionId)\n\t}\n}\n\n/** @internal */\nexport interface MinimalDocStore<R extends UnknownRecord> {\n\tget(id: string): UnknownRecord | undefined\n\tset(id: string, record: R): void\n\tdelete(id: string): void\n}\n\n/** @internal */\nexport class PresenceStore<R extends UnknownRecord> implements MinimalDocStore<R> {\n\tprivate readonly presences = new AtomMap<string, R>('presences')\n\n\tget(id: string): UnknownRecord | undefined {\n\t\treturn this.presences.get(id)\n\t}\n\n\tset(id: string, state: R): void {\n\t\tthis.presences.set(id, state)\n\t}\n\n\tdelete(id: string): void {\n\t\tthis.presences.delete(id)\n\t}\n\n\tvalues() {\n\t\treturn this.presences.values()\n\t}\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAOO;AACP,mBAUO;AACP,wBAAiC;AACjC,kBAQO;AACP,sBAAyB;AACzB,sBAOO;AACP,wBAA0E;AAC1E,yBAMO;AAEP,0BAAoF;AACpF,2BAKO;AAiCA,MAAM,iCAAiC,MAAO;AAErD,MAAM,YAAY,CAAC,SAAiB,KAAK,IAAI,IAAI;AAGjD,MAAM,yBAAyB;AAC/B,MAAM,qBAAqB,IAAI,YAAY;AAE3C,MAAM,kBAAkB,CAAC,iBAAyB,SAAS,YAAY;AAEvE,SAAS,oBAAoB,QAAgB;AAC5C,QAAM,aAAa,mBAAmB,OAAO,MAAM,EAAE;AACrD,MAAI,cAAc,uBAAwB,QAAO;AAEjD,QAAM,SAAS,yBAAyB,gBAAgB,UAAU,EAAE;AACpE,MAAI,MAAM;AACV,MAAI,WAAW;AAEf,aAAW,QAAQ,QAAQ;AAC1B,UAAM,YAAY,mBAAmB,OAAO,IAAI,EAAE;AAClD,QAAI,WAAW,YAAY,OAAQ;AACnC,WAAO;AACP,gBAAY;AAAA,EACb;AACA,SAAO,MAAM,gB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AAe,MAAM;AACpB,YAAI;AACH,eAAK,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAAA,QAClD,SAAS,GAAG;AACX,eAAK,KAAK,QAAQ,4BAA4B,CAAC;AAAA,QAChD;AAAA,MACD,CAAC;AAAA,IACF;AAAA,EACD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcA,YAAY,WAAmB;AAC9B,SAAK,cAAc,SAAS;AAAA,EAC7B;AACD;AAUO,MAAM,cAAqE;AAAA,EAChE,YAAY,IAAI,qBAAmB,WAAW;AAAA,EAE/D,IAAI,IAAuC;AAC1C,WAAO,KAAK,UAAU,IAAI,EAAE;AAAA,EAC7B;AAAA,EAEA,IAAI,IAAY,OAAgB;AAC/B,SAAK,UAAU,IAAI,IAAI,KAAK;AAAA,EAC7B;AAAA,EAEA,OAAO,IAAkB;AACxB,SAAK,UAAU,OAAO,EAAE;AAAA,EACzB;AAAA,EAEA,SAAS;AACR,WAAO,KAAK,UAAU,OAAO;AAAA,EAC9B;AACD;",
6
6
  "names": ["changes", "result"]
7
7
  }
@@ -19,12 +19,23 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
19
19
  var chunk_exports = {};
20
20
  __export(chunk_exports, {
21
21
  JsonChunkAssembler: () => JsonChunkAssembler,
22
+ MAX_ASSEMBLED_MESSAGE_CHARS: () => MAX_ASSEMBLED_MESSAGE_CHARS,
23
+ MAX_CHUNK_COUNT: () => MAX_CHUNK_COUNT,
24
+ MessageTooLargeError: () => MessageTooLargeError,
22
25
  chunk: () => chunk
23
26
  });
24
27
  module.exports = __toCommonJS(chunk_exports);
25
28
  const MAX_CLIENT_SENT_MESSAGE_SIZE_BYTES = 1024 * 1024;
26
29
  const MAX_BYTES_PER_CHAR = 4;
27
30
  const MAX_SAFE_MESSAGE_SIZE = MAX_CLIENT_SENT_MESSAGE_SIZE_BYTES / MAX_BYTES_PER_CHAR;
31
+ const MAX_ASSEMBLED_MESSAGE_CHARS = 16 * 1024 * 1024;
32
+ const MAX_CHUNK_COUNT = 1e5;
33
+ class MessageTooLargeError extends Error {
34
+ constructor(chars) {
35
+ super(`Message too large: ${chars} characters, max ${MAX_ASSEMBLED_MESSAGE_CHARS}`);
36
+ this.name = "MessageTooLargeError";
37
+ }
38
+ }
28
39
  function chunk(msg, maxSafeMessageSize = MAX_SAFE_MESSAGE_SIZE) {
29
40
  if (msg.length < maxSafeMessageSize) {
30
41
  return [msg];
@@ -34,7 +45,10 @@ function chunk(msg, maxSafeMessageSize = MAX_SAFE_MESSAGE_SIZE) {
34
45
  let offset = msg.length;
35
46
  while (offset > 0) {
36
47
  const prefix = `${chunkNumber}_`;
37
- const chunkSize = Math.max(Math.min(maxSafeMessageSize - prefix.length, offset), 1);
48
+ let chunkSize = Math.max(Math.min(maxSafeMessageSize - prefix.length, offset), 1);
49
+ if (chunkSize < offset && isLowSurrogate(msg.charCodeAt(offset - chunkSize)) && isHighSurrogate(msg.charCodeAt(offset - chunkSize - 1))) {
50
+ chunkSize += chunkSize > 1 ? -1 : 1;
51
+ }
38
52
  chunks.unshift(prefix + msg.slice(offset - chunkSize, offset));
39
53
  offset -= chunkSize;
40
54
  chunkNumber++;
@@ -42,6 +56,12 @@ function chunk(msg, maxSafeMessageSize = MAX_SAFE_MESSAGE_SIZE) {
42
56
  return chunks;
43
57
  }
44
58
  }
59
+ function isHighSurrogate(code) {
60
+ return code >= 55296 && code <= 56319;
61
+ }
62
+ function isLowSurrogate(code) {
63
+ return code >= 56320 && code <= 57343;
64
+ }
45
65
  const chunkRe = /^(\d+)_(.*)$/s;
46
66
  class JsonChunkAssembler {
47
67
  /**
@@ -56,7 +76,8 @@ class JsonChunkAssembler {
56
76
  * @param msg - The message to process, either JSON or chunk format
57
77
  * @returns Result object with data/stringified on success, error object on failure, or null for incomplete chunks
58
78
  * - `\{ data: object, stringified: string \}` - Successfully parsed complete message
59
- * - `\{ error: Error \}` - Parse error or invalid chunk sequence
79
+ * - `\{ error: Error \}` - Parse error, invalid chunk sequence, or a message exceeding
80
+ * MAX_ASSEMBLED_MESSAGE_CHARS / MAX_CHUNK_COUNT
60
81
  * - `null` - Chunk received but more chunks expected
61
82
  *
62
83
  * @example
@@ -89,17 +110,28 @@ class JsonChunkAssembler {
89
110
  const numChunksRemaining = Number(match[1]);
90
111
  const data = match[2];
91
112
  if (this.state === "idle") {
113
+ const totalChunks = numChunksRemaining + 1;
114
+ if (totalChunks > MAX_CHUNK_COUNT) {
115
+ return { error: new Error(`Too many chunks: ${totalChunks}`) };
116
+ }
92
117
  this.state = {
93
118
  chunksReceived: [data],
94
- totalChunks: numChunksRemaining + 1
119
+ totalChunks,
120
+ charsReceived: data.length
95
121
  };
96
122
  } else {
97
123
  this.state.chunksReceived.push(data);
124
+ this.state.charsReceived += data.length;
98
125
  if (numChunksRemaining !== this.state.totalChunks - this.state.chunksReceived.length) {
99
126
  this.state = "idle";
100
127
  return { error: new Error(`Chunks received in wrong order`) };
101
128
  }
102
129
  }
130
+ if (this.state.charsReceived > MAX_ASSEMBLED_MESSAGE_CHARS) {
131
+ const charsReceived = this.state.charsReceived;
132
+ this.state = "idle";
133
+ return { error: new MessageTooLargeError(charsReceived) };
134
+ }
103
135
  if (this.state.chunksReceived.length === this.state.totalChunks) {
104
136
  try {
105
137
  const stringified = this.state.chunksReceived.join("");
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/lib/chunk.ts"],
4
- "sourcesContent": ["// quarter of a megabyte, max possible utf-8 string size\n\n// cloudflare workers only accept messages of max 1mb\nconst MAX_CLIENT_SENT_MESSAGE_SIZE_BYTES = 1024 * 1024\n// utf-8 is max 4 bytes per char\nconst MAX_BYTES_PER_CHAR = 4\n\n// in the (admittedly impossible) worst case, the max size is 1/4 of a megabyte\nconst MAX_SAFE_MESSAGE_SIZE = MAX_CLIENT_SENT_MESSAGE_SIZE_BYTES / MAX_BYTES_PER_CHAR\n\n/**\n * Splits a string into smaller chunks suitable for transmission over WebSockets.\n * This function ensures messages don't exceed size limits imposed by platforms like Cloudflare Workers (1MB max).\n * Each chunk is prefixed with a number indicating how many more chunks follow.\n *\n * @param msg - The string to split into chunks\n * @param maxSafeMessageSize - Maximum safe size for each chunk in characters. Defaults to quarter megabyte to account for UTF-8 encoding\n * @returns Array of chunked strings, each prefixed with \"\\{number\\}_\" where number indicates remaining chunks\n *\n * @example\n * ```ts\n * // Small message - returns as single chunk\n * chunk('hello world') // ['hello world']\n *\n * // Large message - splits into multiple chunks\n * chunk('very long message...', 10)\n * // ['2_very long', '1_ message', '0_...']\n * ```\n *\n * @internal\n */\nexport function chunk(msg: string, maxSafeMessageSize = MAX_SAFE_MESSAGE_SIZE) {\n\tif (msg.length < maxSafeMessageSize) {\n\t\treturn [msg]\n\t} else {\n\t\tconst chunks = []\n\t\tlet chunkNumber = 0\n\t\tlet offset = msg.length\n\t\twhile (offset > 0) {\n\t\t\tconst prefix = `${chunkNumber}_`\n\t\t\tconst chunkSize = Math.max(Math.min(maxSafeMessageSize - prefix.length, offset), 1)\n\t\t\tchunks.unshift(prefix + msg.slice(offset - chunkSize, offset))\n\t\t\toffset -= chunkSize\n\t\t\tchunkNumber++\n\t\t}\n\t\treturn chunks\n\t}\n}\n\n// The 's' flag (dotAll) makes '.' match any character including line terminators\n// like U+2028 and U+2029, which are commonly introduced via copy/paste from Word\nconst chunkRe = /^(\\d+)_(.*)$/s\n\n/**\n * Assembles chunked JSON messages back into complete objects.\n * Handles both regular JSON messages and chunked messages created by the chunk() function.\n * Maintains internal state to track partially received chunked messages.\n *\n * @example\n * ```ts\n * const assembler = new JsonChunkAssembler()\n *\n * // Handle regular JSON message\n * const result1 = assembler.handleMessage('{\"hello\": \"world\"}')\n * // Returns: { data: { hello: \"world\" }, stringified: '{\"hello\": \"world\"}' }\n *\n * // Handle chunked message\n * assembler.handleMessage('1_hello') // Returns: null (partial)\n * const result2 = assembler.handleMessage('0_ world')\n * // Returns: { data: \"hello world\", stringified: \"hello world\" }\n * ```\n *\n * @public\n */\nexport class JsonChunkAssembler {\n\t/**\n\t * Current assembly state - either 'idle' or tracking chunks being received\n\t */\n\tstate:\n\t\t| 'idle'\n\t\t| {\n\t\t\t\tchunksReceived: string[]\n\t\t\t\ttotalChunks: number\n\t\t } = 'idle'\n\n\t/**\n\t * Processes a single message, which can be either a complete JSON object or a chunk.\n\t * For complete JSON objects (starting with '\\{'), parses immediately.\n\t * For chunks (prefixed with \"\\{number\\}_\"), accumulates until all chunks received.\n\t *\n\t * @param msg - The message to process, either JSON or chunk format\n\t * @returns Result object with data/stringified on success, error object on failure, or null for incomplete chunks\n\t * \t- `\\{ data: object, stringified: string \\}` - Successfully parsed complete message\n\t * \t- `\\{ error: Error \\}` - Parse error or invalid chunk sequence\n\t * \t- `null` - Chunk received but more chunks expected\n\t *\n\t * @example\n\t * ```ts\n\t * const assembler = new JsonChunkAssembler()\n\t *\n\t * // Complete JSON message\n\t * const result = assembler.handleMessage('{\"key\": \"value\"}')\n\t * if (result && 'data' in result) {\n\t * console.log(result.data) // { key: \"value\" }\n\t * }\n\t *\n\t * // Chunked message sequence\n\t * assembler.handleMessage('2_hel') // null - more chunks expected\n\t * assembler.handleMessage('1_lo ') // null - more chunks expected\n\t * assembler.handleMessage('0_wor') // { data: \"hello wor\", stringified: \"hello wor\" }\n\t * ```\n\t */\n\thandleMessage(msg: string): { error: Error } | { stringified: string; data: object } | null {\n\t\tif (msg.startsWith('{')) {\n\t\t\tconst error = this.state === 'idle' ? undefined : new Error('Unexpected non-chunk message')\n\t\t\tthis.state = 'idle'\n\t\t\treturn error ? { error } : { data: JSON.parse(msg), stringified: msg }\n\t\t} else {\n\t\t\tconst match = chunkRe.exec(msg)!\n\t\t\tif (!match) {\n\t\t\t\tthis.state = 'idle'\n\t\t\t\treturn { error: new Error('Invalid chunk: ' + JSON.stringify(msg.slice(0, 20) + '...')) }\n\t\t\t}\n\t\t\tconst numChunksRemaining = Number(match[1])\n\t\t\tconst data = match[2]\n\n\t\t\tif (this.state === 'idle') {\n\t\t\t\tthis.state = {\n\t\t\t\t\tchunksReceived: [data],\n\t\t\t\t\ttotalChunks: numChunksRemaining + 1,\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthis.state.chunksReceived.push(data)\n\t\t\t\tif (numChunksRemaining !== this.state.totalChunks - this.state.chunksReceived.length) {\n\t\t\t\t\tthis.state = 'idle'\n\t\t\t\t\treturn { error: new Error(`Chunks received in wrong order`) }\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (this.state.chunksReceived.length === this.state.totalChunks) {\n\t\t\t\ttry {\n\t\t\t\t\tconst stringified = this.state.chunksReceived.join('')\n\t\t\t\t\tconst data = JSON.parse(stringified)\n\t\t\t\t\treturn { data, stringified }\n\t\t\t\t} catch (e) {\n\t\t\t\t\treturn { error: e as Error }\n\t\t\t\t} finally {\n\t\t\t\t\tthis.state = 'idle'\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn null\n\t\t}\n\t}\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,MAAM,qCAAqC,OAAO;AAElD,MAAM,qBAAqB;AAG3B,MAAM,wBAAwB,qCAAqC;AAuB5D,SAAS,MAAM,KAAa,qBAAqB,uBAAuB;AAC9E,MAAI,IAAI,SAAS,oBAAoB;AACpC,WAAO,CAAC,GAAG;AAAA,EACZ,OAAO;AACN,UAAM,SAAS,CAAC;AAChB,QAAI,cAAc;AAClB,QAAI,SAAS,IAAI;AACjB,WAAO,SAAS,GAAG;AAClB,YAAM,SAAS,GAAG,WAAW;AAC7B,YAAM,YAAY,KAAK,IAAI,KAAK,IAAI,qBAAqB,OAAO,QAAQ,MAAM,GAAG,CAAC;AAClF,aAAO,QAAQ,SAAS,IAAI,MAAM,SAAS,WAAW,MAAM,CAAC;AAC7D,gBAAU;AACV;AAAA,IACD;AACA,WAAO;AAAA,EACR;AACD;AAIA,M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WAAW;AACnC,iBAAO,EAAE,MAAAA,OAAM,YAAY;AAAA,QAC5B,SAAS,GAAG;AACX,iBAAO,EAAE,OAAO,EAAW;AAAA,QAC5B,UAAE;AACD,eAAK,QAAQ;AAAA,QACd;AAAA,MACD;AACA,aAAO;AAAA,IACR;AAAA,EACD;AACD;",
4
+ "sourcesContent": ["// quarter of a megabyte, max possible utf-8 string size\n\n// cloudflare workers only accept messages of max 1mb\nconst MAX_CLIENT_SENT_MESSAGE_SIZE_BYTES = 1024 * 1024\n// utf-8 is max 4 bytes per char\nconst MAX_BYTES_PER_CHAR = 4\n\n// in the (admittedly impossible) worst case, the max size is 1/4 of a megabyte\nconst MAX_SAFE_MESSAGE_SIZE = MAX_CLIENT_SENT_MESSAGE_SIZE_BYTES / MAX_BYTES_PER_CHAR\n\n// JsonChunkAssembler holds every chunk of a message until the last one arrives, and the sender\n// decides how many that is \u2014 the count is just a prefix on the first chunk. Nothing in the\n// protocol obliges a sender to ever send the last chunk, so without a ceiling a single connection\n// can make the receiver hold an arbitrarily large buffer for as long as the socket stays open.\n//\n// The cap counts UTF-16 code units, which is what a JS string costs in memory: 16M of them is the\n// 32MB of retained string data a room can afford to hold per session and stay inside a Durable\n// Object's 128MB instance limit with room for the document itself. It is far above anything\n// chunk() produces for a real document push. The character cap is the real bound; the chunk-count\n// cap only rejects an absurd declared count on arrival instead of waiting for the characters to\n// accumulate, and is loose enough not to constrain a sender that chunks more finely than the\n// default.\nexport const MAX_ASSEMBLED_MESSAGE_CHARS = 16 * 1024 * 1024\nexport const MAX_CHUNK_COUNT = 100_000\n\n/**\n * Thrown when a message would exceed MAX_ASSEMBLED_MESSAGE_CHARS, on either side of the wire.\n * Distinct from the other assembly errors because it is fatal: retrying sends the same\n * oversized message, so the session is rejected rather than reset.\n *\n * @internal\n */\nexport class MessageTooLargeError extends Error {\n\tconstructor(chars: number) {\n\t\tsuper(`Message too large: ${chars} characters, max ${MAX_ASSEMBLED_MESSAGE_CHARS}`)\n\t\tthis.name = 'MessageTooLargeError'\n\t}\n}\n\n/**\n * Splits a string into smaller chunks suitable for transmission over WebSockets.\n * This function ensures messages don't exceed size limits imposed by platforms like Cloudflare Workers (1MB max).\n * Each chunk is prefixed with a number indicating how many more chunks follow.\n *\n * @param msg - The string to split into chunks\n * @param maxSafeMessageSize - Maximum safe size for each chunk in characters. Defaults to quarter megabyte to account for UTF-8 encoding\n * @returns Array of chunked strings, each prefixed with \"\\{number\\}_\" where number indicates remaining chunks\n *\n * @example\n * ```ts\n * // Small message - returns as single chunk\n * chunk('hello world') // ['hello world']\n *\n * // Large message - splits into multiple chunks\n * chunk('very long message...', 10)\n * // ['2_very long', '1_ message', '0_...']\n * ```\n *\n * @internal\n */\nexport function chunk(msg: string, maxSafeMessageSize = MAX_SAFE_MESSAGE_SIZE) {\n\tif (msg.length < maxSafeMessageSize) {\n\t\treturn [msg]\n\t} else {\n\t\tconst chunks = []\n\t\tlet chunkNumber = 0\n\t\tlet offset = msg.length\n\t\twhile (offset > 0) {\n\t\t\tconst prefix = `${chunkNumber}_`\n\t\t\tlet chunkSize = Math.max(Math.min(maxSafeMessageSize - prefix.length, offset), 1)\n\t\t\t// Never split a surrogate pair across chunks: WebSocket.send converts each chunk to a\n\t\t\t// USVString, turning a lone surrogate into U+FFFD, so the reassembled JSON silently\n\t\t\t// carries corrupted text. Shrink by one so the pair moves whole into the preceding\n\t\t\t// chunk; a single-character chunk grows by one instead (one over the CH3 bound, see CH9).\n\t\t\tif (\n\t\t\t\tchunkSize < offset &&\n\t\t\t\tisLowSurrogate(msg.charCodeAt(offset - chunkSize)) &&\n\t\t\t\tisHighSurrogate(msg.charCodeAt(offset - chunkSize - 1))\n\t\t\t) {\n\t\t\t\tchunkSize += chunkSize > 1 ? -1 : 1\n\t\t\t}\n\t\t\tchunks.unshift(prefix + msg.slice(offset - chunkSize, offset))\n\t\t\toffset -= chunkSize\n\t\t\tchunkNumber++\n\t\t}\n\t\treturn chunks\n\t}\n}\n\nfunction isHighSurrogate(code: number) {\n\treturn code >= 0xd800 && code <= 0xdbff\n}\n\nfunction isLowSurrogate(code: number) {\n\treturn code >= 0xdc00 && code <= 0xdfff\n}\n\n// The 's' flag (dotAll) makes '.' match any character including line terminators\n// like U+2028 and U+2029, which are commonly introduced via copy/paste from Word\nconst chunkRe = /^(\\d+)_(.*)$/s\n\n/**\n * Assembles chunked JSON messages back into complete objects.\n * Handles both regular JSON messages and chunked messages created by the chunk() function.\n * Maintains internal state to track partially received chunked messages.\n *\n * @example\n * ```ts\n * const assembler = new JsonChunkAssembler()\n *\n * // Handle regular JSON message\n * const result1 = assembler.handleMessage('{\"hello\": \"world\"}')\n * // Returns: { data: { hello: \"world\" }, stringified: '{\"hello\": \"world\"}' }\n *\n * // Handle chunked message\n * assembler.handleMessage('1_hello') // Returns: null (partial)\n * const result2 = assembler.handleMessage('0_ world')\n * // Returns: { data: \"hello world\", stringified: \"hello world\" }\n * ```\n *\n * @public\n */\nexport class JsonChunkAssembler {\n\t/**\n\t * Current assembly state - either 'idle' or tracking chunks being received\n\t */\n\tstate:\n\t\t| 'idle'\n\t\t| {\n\t\t\t\tchunksReceived: string[]\n\t\t\t\ttotalChunks: number\n\t\t\t\tcharsReceived: number\n\t\t } = 'idle'\n\n\t/**\n\t * Processes a single message, which can be either a complete JSON object or a chunk.\n\t * For complete JSON objects (starting with '\\{'), parses immediately.\n\t * For chunks (prefixed with \"\\{number\\}_\"), accumulates until all chunks received.\n\t *\n\t * @param msg - The message to process, either JSON or chunk format\n\t * @returns Result object with data/stringified on success, error object on failure, or null for incomplete chunks\n\t * \t- `\\{ data: object, stringified: string \\}` - Successfully parsed complete message\n\t * \t- `\\{ error: Error \\}` - Parse error, invalid chunk sequence, or a message exceeding\n\t * \t MAX_ASSEMBLED_MESSAGE_CHARS / MAX_CHUNK_COUNT\n\t * \t- `null` - Chunk received but more chunks expected\n\t *\n\t * @example\n\t * ```ts\n\t * const assembler = new JsonChunkAssembler()\n\t *\n\t * // Complete JSON message\n\t * const result = assembler.handleMessage('{\"key\": \"value\"}')\n\t * if (result && 'data' in result) {\n\t * console.log(result.data) // { key: \"value\" }\n\t * }\n\t *\n\t * // Chunked message sequence\n\t * assembler.handleMessage('2_hel') // null - more chunks expected\n\t * assembler.handleMessage('1_lo ') // null - more chunks expected\n\t * assembler.handleMessage('0_wor') // { data: \"hello wor\", stringified: \"hello wor\" }\n\t * ```\n\t */\n\thandleMessage(msg: string): { error: Error } | { stringified: string; data: object } | null {\n\t\tif (msg.startsWith('{')) {\n\t\t\tconst error = this.state === 'idle' ? undefined : new Error('Unexpected non-chunk message')\n\t\t\tthis.state = 'idle'\n\t\t\treturn error ? { error } : { data: JSON.parse(msg), stringified: msg }\n\t\t} else {\n\t\t\tconst match = chunkRe.exec(msg)!\n\t\t\tif (!match) {\n\t\t\t\tthis.state = 'idle'\n\t\t\t\treturn { error: new Error('Invalid chunk: ' + JSON.stringify(msg.slice(0, 20) + '...')) }\n\t\t\t}\n\t\t\tconst numChunksRemaining = Number(match[1])\n\t\t\tconst data = match[2]\n\n\t\t\tif (this.state === 'idle') {\n\t\t\t\tconst totalChunks = numChunksRemaining + 1\n\t\t\t\tif (totalChunks > MAX_CHUNK_COUNT) {\n\t\t\t\t\t// Nothing has been buffered yet, so the state is already idle.\n\t\t\t\t\treturn { error: new Error(`Too many chunks: ${totalChunks}`) }\n\t\t\t\t}\n\t\t\t\tthis.state = {\n\t\t\t\t\tchunksReceived: [data],\n\t\t\t\t\ttotalChunks,\n\t\t\t\t\tcharsReceived: data.length,\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthis.state.chunksReceived.push(data)\n\t\t\t\tthis.state.charsReceived += data.length\n\t\t\t\tif (numChunksRemaining !== this.state.totalChunks - this.state.chunksReceived.length) {\n\t\t\t\t\tthis.state = 'idle'\n\t\t\t\t\treturn { error: new Error(`Chunks received in wrong order`) }\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (this.state.charsReceived > MAX_ASSEMBLED_MESSAGE_CHARS) {\n\t\t\t\t// Drop what was buffered rather than keeping it until the socket closes.\n\t\t\t\tconst charsReceived = this.state.charsReceived\n\t\t\t\tthis.state = 'idle'\n\t\t\t\treturn { error: new MessageTooLargeError(charsReceived) }\n\t\t\t}\n\t\t\tif (this.state.chunksReceived.length === this.state.totalChunks) {\n\t\t\t\ttry {\n\t\t\t\t\tconst stringified = this.state.chunksReceived.join('')\n\t\t\t\t\tconst data = JSON.parse(stringified)\n\t\t\t\t\treturn { data, stringified }\n\t\t\t\t} catch (e) {\n\t\t\t\t\treturn { error: e as Error }\n\t\t\t\t} finally {\n\t\t\t\t\tthis.state = 'idle'\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn null\n\t\t}\n\t}\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,MAAM,qCAAqC,OAAO;AAElD,MAAM,qBAAqB;AAG3B,MAAM,wBAAwB,qCAAqC;AAc5D,MAAM,8BAA8B,KAAK,OAAO;AAChD,MAAM,kBAAkB;AASxB,MAAM,6BAA6B,MAAM;AAAA,EAC/C,YAAY,OAAe;AAC1B,UAAM,sBAAsB,KAAK,oBAAoB,2BAA2B,EAAE;AAClF,SAAK,OAAO;AAAA,EACb;AACD;AAuBO,SAAS,MAAM,KAAa,qBAAqB,uBAAuB;AAC9E,MAAI,IAAI,SAAS,oBAAoB;AACpC,WAAO,CAAC,GAAG;AAAA,EACZ,OAAO;AACN,UAAM,SAAS,CAAC;AAChB,QAAI,cAAc;AAClB,QAAI,SAAS,IAAI;AACjB,WAAO,SAAS,GAAG;AAClB,YAAM,SAAS,GAAG,WAAW;AAC7B,UAAI,YAAY,KAAK,IAAI,KAAK,IAAI,qBAAqB,OAAO,QAAQ,MAAM,GAAG,CAAC;AAKhF,UACC,YAAY,UACZ,eAAe,IAAI,WAAW,SAAS,SAAS,CAAC,KACjD,gBAAgB,IAAI,WAAW,SAAS,YAAY,CAAC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A,aAAK,QAAQ;AAAA,UACZ,gBAAgB,CAAC,IAAI;AAAA,UACrB;AAAA,UACA,eAAe,KAAK;AAAA,QACrB;AAAA,MACD,OAAO;AACN,aAAK,MAAM,eAAe,KAAK,IAAI;AACnC,aAAK,MAAM,iBAAiB,KAAK;AACjC,YAAI,uBAAuB,KAAK,MAAM,cAAc,KAAK,MAAM,eAAe,QAAQ;AACrF,eAAK,QAAQ;AACb,iBAAO,EAAE,OAAO,IAAI,MAAM,gCAAgC,EAAE;AAAA,QAC7D;AAAA,MACD;AACA,UAAI,KAAK,MAAM,gBAAgB,6BAA6B;AAE3D,cAAM,gBAAgB,KAAK,MAAM;AACjC,aAAK,QAAQ;AACb,eAAO,EAAE,OAAO,IAAI,qBAAqB,aAAa,EAAE;AAAA,MACzD;AACA,UAAI,KAAK,MAAM,eAAe,WAAW,KAAK,MAAM,aAAa;AAChE,YAAI;AACH,gBAAM,cAAc,KAAK,MAAM,eAAe,KAAK,EAAE;AACrD,gBAAMA,QAAO,KAAK,MAAM,WAAW;AACnC,iBAAO,EAAE,MAAAA,OAAM,YAAY;AAAA,QAC5B,SAAS,GAAG;AACX,iBAAO,EAAE,OAAO,EAAW;AAAA,QAC5B,UAAE;AACD,eAAK,QAAQ;AAAA,QACd;AAAA,MACD;AACA,aAAO;AAAA,IACR;AAAA,EACD;AACD;",
6
6
  "names": ["data"]
7
7
  }
@@ -158,6 +158,7 @@ export declare class JsonChunkAssembler {
158
158
  * Current assembly state - either 'idle' or tracking chunks being received
159
159
  */
160
160
  state: 'idle' | {
161
+ charsReceived: number;
161
162
  chunksReceived: string[];
162
163
  totalChunks: number;
163
164
  };
@@ -169,7 +170,8 @@ export declare class JsonChunkAssembler {
169
170
  * @param msg - The message to process, either JSON or chunk format
170
171
  * @returns Result object with data/stringified on success, error object on failure, or null for incomplete chunks
171
172
  * - `\{ data: object, stringified: string \}` - Successfully parsed complete message
172
- * - `\{ error: Error \}` - Parse error or invalid chunk sequence
173
+ * - `\{ error: Error \}` - Parse error, invalid chunk sequence, or a message exceeding
174
+ * MAX_ASSEMBLED_MESSAGE_CHARS / MAX_CHUNK_COUNT
173
175
  * - `null` - Chunk received but more chunks expected
174
176
  *
175
177
  * @example
@@ -1200,7 +1202,8 @@ export declare class TLSocketRoom<R extends UnknownRecord = UnknownRecord, Sessi
1200
1202
  * The client will attempt to reconnect automatically unless a fatal reason is provided.
1201
1203
  *
1202
1204
  * @param sessionId - Session identifier to remove
1203
- * @param fatalReason - Optional fatal error reason that prevents reconnection
1205
+ * @param fatalReason - Optional fatal error reason that prevents reconnection. WebSocket close
1206
+ * reasons are capped at 123 UTF-8 bytes, so a longer reason is truncated and ends with `... (+N bytes)`.
1204
1207
  *
1205
1208
  * @example
1206
1209
  * ```ts
@@ -1617,6 +1620,8 @@ export declare const TLSyncErrorCloseEventCode: 4099;
1617
1620
  * @public
1618
1621
  */
1619
1622
  export declare const TLSyncErrorCloseEventReason: {
1623
+ /** A single message exceeded the size the server will assemble */
1624
+ readonly MESSAGE_TOO_LARGE: 'MESSAGE_TOO_LARGE';
1620
1625
  /** Client exceeded rate limits */
1621
1626
  readonly RATE_LIMITED: 'RATE_LIMITED';
1622
1627
  /** Client protocol version too old */
@@ -36,7 +36,7 @@ import {
36
36
  } from "./lib/TLSyncStorage.mjs";
37
37
  registerTldrawLibraryVersion(
38
38
  "@tldraw/sync-core",
39
- "5.5.0-next.a2698a88ecfb",
39
+ "5.5.0-next.b6a9f7cd7be2",
40
40
  "esm"
41
41
  );
42
42
  export {