@docx-editor.dev/pro/collaboration

@docx-editor.dev/pro/collaboration — Yjs replica factories and the module factory.

The default entry imports no network provider. Import @docx-editor.dev/pro/collaboration/webrtc for the WebRTC wrapper and @docx-editor.dev/pro/collaboration/hocuspocus for the Hocuspocus wrapper.

Functions (15)

assertCollaborationFormatCompatibilityfunctionSource ↗

Refuse a collaboration format version unsupported by this deployment.

Pass the untrusted value received during connection admission, after authorizing document access and before synchronization. Only an exact string match succeeds. This check does not authenticate clients, validate room content, or migrate data.

declare function assertCollaborationFormatCompatibility(version: unknown): void;

assertDocumentCollaborationCompatibilityfunctionSource ↗

Deprecated. Use `assertCollaborationFormatCompatibility` with `COLLABORATION_FORMAT_VERSION`. This function stays supported for existing handshakes.

Refuse an incompatible full-document client or persisted-room version descriptor.

Pass the client's version tuple from your admission handshake before permitting sync. Check persisted-room versions separately: a compatible client cannot migrate an older room. This validates compatibility only; your server must also authorize access. Missing or malformed fields refuse. Additional fields are ignored. Exact equality is required for all four supported versions; no migration or shared-state mutation occurs. Handle the stable error code; detail is a bounded diagnostic, not a parsing contract.

declare function assertDocumentCollaborationCompatibility(versions: unknown): void;

checkCollaborationRoomGenerationfunctionSource ↗

Refuse a connection whose replica holds another generation of the room. Call it from the Hocuspocus beforeHandleMessage hook. A client sends the generation it holds before its first sync message; on a mismatch, or a sync message without one, this throws an error that closes the connection with room-generation-changed before any of its state merges. A message the gate cannot read is refused the same way.

A replica that holds no room yet names no generation and passes: it has no state of an earlier generation to merge. The gate keeps honest replicas of two generations apart. It is not access control: a client that may write to the room can send any update, so authenticate connections in onAuthenticate.

declare function checkCollaborationRoomGeneration(payload: CollaborationRoomGatePayload): void;

collaborationMigrationNeedfunctionSource ↗

Whether saved room state needs a migration before this build can serve it.

A room whose version information is missing or malformed was written before collaboration formats were versioned, and counts as earlier-format.

Throws CollaborationSchemaError with code not-initialized for state that holds no room, and with code invalid-baseline for bytes that are not room state.

declare function collaborationMigrationNeed(state: Uint8Array): CollaborationMigrationNeed;

collaborationModulefunctionSource ↗

Build the collaboration module. Construction never validates the key and never touches the network.

declare function collaborationModule(options: CollaborationModuleOptions): EditorModule;

collaborationServerExtensionfunctionSource ↗

The collaboration room checks, as one Hocuspocus extension.

The extension runs before your other extensions and your own hooks:

- onAuthenticate refuses a client whose collaboration format differs from this build's, with collaboration-format-mismatch, before any sync. Authenticate the connection in your own onAuthenticate, which still runs. - onLoadDocument prepares the room document before any update reaches it. - afterLoadDocument flushes the loaded room, so the first participant receives it once. - beforeHandleMessage refuses a replica of an earlier room generation.

With storage, the extension also loads and stores the room:

- A stored room is checked before it becomes the live room: it must be in this build's format and must export as a complete document. - A stored room of an earlier format is created again from its stored export, checked against that export, and stored. The room keeps its ID. A replica that still holds the earlier room is refused with room-generation-changed, and rejoins. - Each store writes the room state and a .docx export of it. - A stored room with no export, or with the export of another state, gets a current export when the server loads it.

Do not load or store the room in your own hooks when you pass storage.

The upgraded room is checked against the export, not against the earlier state, which this build cannot read. The digest is the only link between the two: store each export with the digest it came with, and never one without the other.

One process must hold a room at a time while rooms upgrade. If two servers load one earlier-format room at once, each creates its own room, and the later store replaces the other. Stop the servers of the earlier build before the servers of this build start.

declare function collaborationServerExtension(options?: CollaborationServerOptions): CollaborationServerExtension;
```ts
import { Server } from '@hocuspocus/server';
import { collaborationServerExtension } from '@docx-editor.dev/pro/collaboration';

const server = new Server({
  port: 1234,
  onAuthenticate,
  extensions: [collaborationServerExtension({ storage: { load: loadRoom, save: saveRoom } })],
});
```

compactCollaborationStatefunctionSource ↗

Build a new generation of a room from its stored state, or return null when compaction would gain less than minimumGain.

The new generation holds the room's current content, read as a .docx package, under the same document ID and a new generation ID. Deleted text and records, formatting history, and unreferenced media are gone. Call it when the server loads a room, before any participant syncs, and store the result in place of the old state.

A check reads the whole room and builds it again. The answer for a state found not worth compacting is remembered in this process, so the same bytes are checked once. A state that changed is checked again.

Throws CollaborationSchemaError when the stored state cannot be read, as readCollaborationDocument does.

declare function compactCollaborationState(state: Uint8Array, options?: CompactCollaborationStateOptions): Promise<Uint8Array | null>;

createCollaborationStatefunctionSource ↗

Build the state of a new room from a .docx file, on a server.

declare function createCollaborationState(document: Uint8Array, options: CreateCollaborationStateOptions): Promise<Uint8Array>;

Call it only for a room that your application knows is new, for example from a durable record that it writes when it creates the room. Store the result with a create-only write before any participant syncs, then apply it to the room document with Y.applyUpdate. Participants find the room seeded and join it with a join or create-or-join bootstrap. No participant uploads the document, and none receives its own seed back.

Do not seed a known room whose stored state is missing. A second seed replaces the room's content with the original file, and every edit made since is gone from the room. Refuse the room instead, for example with saved-room-unavailable: participants keep their copies, and you can restore the stored state. As a last defense, each seed carries a new room generation ID, so checkCollaborationRoomGeneration refuses a participant that holds the earlier state with room-generation-changed instead of merging a second copy of the document.

Hocuspocus does not call onStoreDocument for state applied while it loads a room, so store the result yourself. Hocuspocus also holds back an update smaller than flushMaxBytes and then sends it to every connection, the first participant included, which would receive the room twice. Call document.flush() in afterLoadDocument, before the first participant joins.

The work is synchronous for most of its run. Measured on a laptop, 4.4 MiB of expanded XML (10,000 paragraphs) took 5.2 s, held the event loop for up to 210 ms at a time, and used several hundred MiB of memory. Set maxBytes for the documents you accept, and seed in a worker thread or a job queue with a small concurrency limit, not on the thread that serves rooms.

Throws CollaborationSchemaError: baseline-too-large for a file over maxBytes, invalid-baseline for a file that is not a usable .docx package, and invalid-document-id for a document ID that is empty or longer than 256 characters. Throws TypeError for a maxBytes that is not a whole number from 1 to MAX_BASELINE_BYTES.

createDocumentCollaborationfunctionSource ↗

Create or join one full-document collaboration replica.

The caller owns ydoc, awareness, and the provider, and destroys them after handle.destroy().

declare function createDocumentCollaboration(options: CreateDocumentCollaborationOptions): Promise<DocumentCollaborationHandle>;
```ts
await new Promise((resolve) => provider.once('sync', resolve));
const room = await createDocumentCollaboration({
  ydoc,
  awareness,
  documentId: 'room-1',
  identity: { actorId: 'user-1', name: 'Ada' },
  bootstrap: { kind: 'join' },
});
// Mount the editor with room.document and collaborationModule({ session: room.session }).
```

migrateCollaborationRoomfunctionSource ↗

Seed a room in this build's format from the .docx that the earlier build exported, and check the new room against that export.

The new room keeps the earlier room's document ID unless documentId gives another. It is a new room generation: a replica that still holds the earlier room is refused with room-generation-changed and rejoins.

This function does not check that exported was made from state. Store a digest of the state with each export, and compare it before you call this function: an export made before later edits would lose them.

Throws CollaborationSchemaError when the inputs cannot be used: invalid-baseline for bytes that are not room state or not a .docx, not-initialized for state that holds no room, invalid-document-id for an unusable document ID, and a limit code such as too-many-nodes for an export larger than a room's limits.

declare function migrateCollaborationRoom(options: MigrateCollaborationRoomOptions): Promise<CollaborationMigration>;

prepareCollaborationServerDocumentfunctionSource ↗

Prepare a room's Y.Doc on a server that holds it, such as a Hocuspocus server. Call it once when the server creates or loads the document, before it applies any update.

declare function prepareCollaborationServerDocument(document: Y.Doc): () => void;

Paragraph text keeps formatting in Yjs formatting markers. After a remote update, Yjs removes the markers it finds redundant from the document that received it. On a server, that removal is a change of the server's own, which the server sends to every participant, and it can remove the formatting of text a participant is typing. A prepared document does not remove markers. Every editor replica is prepared already.

readCollaborationDocumentfunctionSource ↗

Read the document a synchronized Y.Doc holds, as .docx bytes.

This is the server side of a room: export, autosave to your own storage, search indexing, a nightly PDF, a webhook. It JOINS NOTHING. There is no identity, no Awareness and no session, so the job that calls it never appears in anyone's avatar stack, and it creates no editing gate, so it cannot write back.

ydoc must already hold the room's state: connect your provider and wait for its initial sync first, exactly as a { kind: \'join\' } bootstrap does. A document that was never seeded refuses with not-initialized rather than returning a truncated file.

ts // Hocuspocus hands onStoreDocument the synced Y.Doc already: async onStoreDocument({ documentName, document }) { await writeFile(${documentName}.docx, readCollaborationDocument(document)); }

Synchronous, and it materializes the whole package per call — this is a job, not a render.

declare function readCollaborationDocument(ydoc: Y.Doc): Uint8Array;

readCollaborationFormatVersionfunctionSource ↗

Read the opaque format version recorded in a synchronized or restored room.

Reads version metadata without joining, exporting, or changing shared state. Can inspect incompatible rooms; pass the result to [assertCollaborationFormatCompatibility](assertCollaborationFormatCompatibility) before admitting their state. The result does not validate document content or guarantee a successful export. Use [readCollaborationDocument](readCollaborationDocument) to validate and export compatible content.

declare function readCollaborationFormatVersion(ydoc: Y.Doc): string;

readCollaborationResourceUsagefunctionSource ↗

Read a room's resource usage from a synchronized Y.Doc, joining nothing.

The server-side sibling of readCollaborationDocument: call it from the same jobs — an autosave hook, a metrics scraper — to watch a room's growth against the caps that would end it. It creates no session and writes nothing, and it walks the node map once per call.

declare function readCollaborationResourceUsage(ydoc: Y.Doc): CollaborationResourceUsage;

readCollaborationRoomGenerationfunctionSource ↗

The generation ID of the room a document holds. It is empty for a room that a participant seeded and nobody compacted since, and for a document that holds no room yet. A room that createCollaborationState or compactCollaborationState built has one.

declare function readCollaborationRoomGeneration(document: Y.Doc): string;

Classes (2)

CollaborationSchemaErrorclassSource ↗

Typed collaboration schema or trust-boundary failure. Version-mismatch messages include recovery guidance and a documentation link. Use code for application logic; detail remains diagnostic information.

declare class CollaborationSchemaError extends Error
MemberTypeSummary
(constructor)Constructs a new instance of the `CollaborationSchemaError` class
codeCollaborationFailureCodeStable failure code. Branch on it.
detail?string | undefinedBounded diagnostic text for logs. Not a parsing contract.

CollaborationUndoGroupErrorclassSource ↗

Thrown by beginUndoGroup when the session cannot open a group. Branch on code.

declare class CollaborationUndoGroupError extends Error
MemberTypeSummary
(constructor)Constructs a new instance of the `CollaborationUndoGroupError` class
codeCollaborationUndoGroupErrorCodeStable refusal code.

Interfaces (28)

CollaborationHandleinterfaceSource ↗

Owned collaboration replica: document bytes, session, and teardown.

A host reads [CollaborationSession](CollaborationSession); the engine session remains assignable.

interface CollaborationHandle<TSession extends CollaborationSession>
MemberTypeSummary
destroyStop the replica and release its listeners. The session becomes `destroyed`.
documentUint8ArrayThe room's document as `.docx` bytes. Mount the editor with them.
sessionTSessionThe live session. Pass it to `collaborationModule`.

CollaborationIdentityUpdateinterfaceSource ↗

Display-identity fields a live session can update.

actorId and role are attribution and stay immutable for the session lifetime, so this type cannot name them.

interface CollaborationIdentityUpdate
MemberTypeSummary
color?stringNew presence color, at most 64 characters.
name?stringNew display name, 1 to 256 characters after trimming.

CollaborationMigrationDifferenceinterfaceSource ↗

One paragraph that differs between the export and the new room.

expected and actual hold document text. Treat them as document content: keep them out of logs that people without access to the document can read.

interface CollaborationMigrationDifference extends CollaborationMigrationPosition
MemberTypeSummary
actualstring | nullThe paragraph's text in the new room, or null when the new room has no such paragraph.
expectedstring | nullThe paragraph's text in the export, or null when the export has no such paragraph.
kind'text' | 'formatting' | 'missing' | 'added'- `text`: the paragraph's text differs. - `formatting`: its text is the same, but its properties or character formatting differ. - `missing`: the export has the paragraph and the new room does not. - `added`: the new room has a paragraph the export does not.

CollaborationMigrationPositioninterfaceSource ↗

A paragraph by its part and its position in that part, from 1.

interface CollaborationMigrationPosition
MemberTypeSummary
paragraphnumberThe paragraph's position in its part, from 1, in document order.
partstringThe package part that holds the paragraph, such as `/word/document.xml`.

CollaborationMigrationReportinterfaceSource ↗

What a migration found, comparing the new room with the export it was seeded from.

The check compares each XML part of the export with the new room's. It ignores only what every save writes anew: namespace declarations, the values of paragraph IDs (w14:paraId, w14:textId) and of w:id, and the relationship parts. A reference to an ID, such as a comment anchor or a comment extension, must still name the same element. Revision IDs are not compared: they only have to be unique. For each paragraph it also reports its text and formatting, to locate a difference. It compares every media part by its bytes, and every external link target.

interface CollaborationMigrationReport
MemberTypeSummary
changedPartsreadonly string[]XML parts that differ, by name, or that one side does not have. A part whose paragraphs differ is listed too.
differenceCountnumberHow many paragraphs differ. `differences` lists at most the first 20.
differencesreadonly CollaborationMigrationDifference[]The first paragraphs that differ, at most 20.
documentIdstringThe document ID of the new room. Every client must open the room with this ID.
failedreadonly CollaborationMigrationCheck[]The checks that failed. Empty when `ok` is true.
fromstringThe earlier room's format, or `unversioned` for a room written before formats had one.
hiddennumberParagraphs the new room keeps but the editor can neither show nor edit. They save back unchanged, and they do not fail the check. Check such rooms before people edit them.
hiddenAtreadonly CollaborationMigrationPosition[]Where the first hidden paragraphs are, at most 20.
missingMediareadonly string[]Media parts of the export, by name, whose bytes the new room does not hold.
okbooleanTrue when every check passed.
paragraphsnumberParagraphs in the export, in every part: body, tables, headers, footers, notes, and comments. A paragraph inside another, as in a text box, counts with the one that holds it.
tostringThe format of the new room: this build's.

CollaborationModuleOptionsinterfaceSource ↗

How [collaborationModule](collaborationModule) is configured. The session is required; the licence key is optional and never validated.

interface CollaborationModuleOptions extends ProLicenseOptions
MemberTypeSummary
sessionEditorCollaborationSessionThe session from a collaboration factory. The editor attaches its document port to it.

CollaborationResourcePressureinterfaceSource ↗

The cap a room is closest to, delivered when the room crosses a threshold.

interface CollaborationResourcePressure
MemberTypeSummary
fractionnumber`used / max` for that cap. A value over 1 means the cap is crossed and the room has ended.
limitCollaborationResourceLimitThe cap with the highest fraction used.
maxnumberThe cap.
thresholdnumberThe highest threshold `fraction` reaches, or 0 when it is below every threshold.
usednumberThe replicated count for that cap.

CollaborationResourcePressureOptionsinterfaceSource ↗

Options for [DocumentCollaborationSession.subscribeResourcePressure](DocumentCollaborationSession.subscribeResourcePressure).

interface CollaborationResourcePressureOptions
MemberTypeSummary
thresholds?readonly number[]Fractions of a cap that notify, each greater than 0 and at most 1. Order and duplicates do not matter. At most 16 values. Default: `[0.75, 0.9]`.

CollaborationResourceUsageinterfaceSource ↗

One reading of a room's replicated size against this replica's hard limits.

Every max* value is the cap whose crossing turns the session status terminal. tombstonedNodes is included in nodes: a tombstone is never map-deleted, so it keeps counting against maxNodes for the life of the room. A reading is a snapshot — take a new one to observe growth, or subscribe with subscribeResourcePressure.

interface CollaborationResourceUsage
MemberTypeSummary
blobBytesnumberBytes in the shared blob map, unreferenced bytes included.
formattingMarkersnumberFormatting markers in paragraph text. Each formatting change leaves some, and deleting the text does not remove them, because a participant who edited offline may still depend on them. They have no cap, but every reader walks them, so a room whose count keeps growing far past its text is one to move to a new room.
maxBlobBytesnumberBlob byte limit. Shared state over it is a terminal `blob-store-full`.
maxNodesnumberNode limit. Shared state over it is a terminal `too-many-nodes`.
maxPartsnumberPart limit. Shared state over it is a terminal `too-many-parts`.
maxRelationshipsnumberRelationship limit. Shared state over it is a terminal `too-many-relationships`.
nodesnumberReplicated node records, tombstones included.
partsnumberReplicated package parts.
relationshipsnumberReplicated relationship records.
tombstonedNodesnumberThe subset of `nodes` that is tombstoned: permanent, and only compaction reclaims it.

CollaborationRoomExportinterfaceSource ↗

A .docx export of a room, with the state it was exported from.

interface CollaborationRoomExport
MemberTypeSummary
docxUint8ArrayThe room's document as a `.docx` file.
stateDigeststringThe SHA-256 of the room state that `docx` was exported from, in lowercase hex.

CollaborationRoomGatePayloadinterfaceSource ↗

What the gate reads of a Hocuspocus beforeHandleMessage payload.

interface CollaborationRoomGatePayload
MemberTypeSummary
contextobjectThe connection's context object, which the gate marks once the generation matched.
documentY.DocThe room's server-side `Y.Doc`.
updateUint8ArrayThe incoming message bytes.

CollaborationRoomStorageinterfaceSource ↗

Where collaborationServerExtension keeps rooms. Implement it over your database or object storage.

Write state and export in one atomic operation where storage allows. If it does not, write the state first, and the export and its digest together. The digest then protects an upgrade: an export of another state is never used, and the next load replaces it.

interface CollaborationRoomStorage
MemberTypeSummary
backUpKeep the state of an earlier format before an upgraded room replaces it. Called once for each upgrade, before `save`. An error from it stops the upgrade and leaves the stored room as it is. Without this method, the earlier state is not kept.
loadThe stored room, or `null` when storage holds no room of this name.
saveStore the room. When `room.export` is `null`, keep the stored export.

CollaborationServerConnectioninterfaceSource ↗

What the server knows about a connecting client in onAuthenticate.

interface CollaborationServerConnection
MemberTypeSummary
documentNamestringThe room the client asks for.
requestParametersURLSearchParamsThe query parameters of the connection URL.
tokenstringThe token the provider sent.

CollaborationServerExtensioninterfaceSource ↗

The Hocuspocus extension that [collaborationServerExtension](collaborationServerExtension) returns. Pass it in the extensions of your server configuration.

interface CollaborationServerExtension
MemberTypeSummary
afterLoadDocumentSends the loaded room to nobody, so the first participant receives it once.
afterUnloadDocumentForgets when the room was last exported.
beforeHandleMessageRefuses a replica of an earlier room generation.
beforeUnloadDocumentStores a room whose last store wrote no export or failed, before the room unloads.
extensionNamestringThe extension's name in Hocuspocus.
onAuthenticateRefuses a client of another collaboration format.
onLoadDocumentPrepares the room document and, with `storage`, loads the room.
onStoreDocumentStores the room with its export. Present only with `storage`.
prioritynumberHigh, so the extension runs before the other extensions and your own hooks.

CollaborationServerLoadinterfaceSource ↗

What Hocuspocus passes to onLoadDocument, as far as the extension reads it.

interface CollaborationServerLoad
MemberTypeSummary
contextunknownThe context that `onAuthenticate` returned for the connection that opens the room.
documentY.DocThe room's server-side `Y.Doc`, still empty.
documentNamestringThe room's name on the server.

CollaborationServerOptionsinterfaceSource ↗

Options for [collaborationServerExtension](collaborationServerExtension).

interface CollaborationServerOptions
MemberTypeSummary
compactOnLoad?boolean | CompactCollaborationStateOptionsCompact a stored room when the server loads it, with `compactCollaborationState`, and store the result. Default `false`. Pass options to set the gain that makes a compaction worth it. A compacted room is a new generation: a replica of the room before it is refused with `room-generation-changed`, and rejoins.
createRoom?(request: CreateCollaborationRoomRequest) => Promise<Uint8Array | null> | Uint8Array | nullThe state of a room that storage does not hold, such as the result of `createCollaborationState`. The server stores it before anyone syncs. Return `null` to leave the room empty, for its first participant to seed. Throw to refuse the room. Used only with `storage`.
exportIntervalMs?numberThe shortest time, in milliseconds, between two exports of one room while people are connected. Default 0: every store exports, so every stored state is one that exports. An export runs on the server's thread: on a laptop, 0.2 seconds for a 75 KB document and 2 seconds for a 521-page document. Raise this for large documents.
maxUpgradeStateBytes?numberThe largest saved state, in bytes, that the server upgrades while it loads the room. Default 64 MiB. The upgrade runs on the server's thread, so every room on the process waits for it: on a laptop, 0.5 seconds for a 75 KB document (4 MiB of state) and 7 seconds for a 521-page document (46 MiB). A larger room is refused with `too-large`; upgrade it in a job with `migrateCollaborationRoom`. Lower the value to keep long upgrades off the server.
onEvent?(event: CollaborationServerEvent) => voidCalled for each event. Errors it throws are ignored. Events hold no document text.
readClientFormat?(connection: CollaborationServerConnection) => unknownThe collaboration format a connecting client names. The default reads the `collaborationFormat` query parameter, which the provider hooks and `createHocuspocusCollaboration` send. Replace it to read the format from your own token. The claim prevents accidental mixed rooms; it does not authenticate a client.
storage?CollaborationRoomStorageWhere rooms are kept. With it, the server loads each room from storage, checks it, and stores it with a `.docx` export. Without it, load and store the room in your own hooks.
upgradeOnLoad?booleanUpgrade a saved room of an earlier collaboration format when the server loads it, from its stored export. Default `true`. With `false`, the server refuses such a room.

CollaborationServerStoreinterfaceSource ↗

What Hocuspocus passes to onStoreDocument, as far as the extension reads it.

interface CollaborationServerStore
MemberTypeSummary
clientsCount?numberConnections to the room when Hocuspocus built the payload.
documentY.DocThe room's server-side `Y.Doc`.
documentNamestringThe room's name on the server.

CollaborationSessioninterfaceSource ↗

Host-facing collaboration session.

A host reads identity, status, presence, and undo. The editor attaches [EditorCollaborationSession](EditorCollaborationSession) internally and never through this type.

interface CollaborationSession
MemberTypeSummary
canRedoWhether the shared undo history holds a local step to redo.
canUndoWhether the shared undo history holds a local step to undo.
documentIdstringThe room's document id.
identityCollaborationIdentityThe validated local identity.
offlineEditing?booleanWhether edits continue while the transport is down (`disconnected`). Set by the `offlineEditing` option; absent means true.
participantsParticipants in presence, this replica included. Capped at 256.
redoRedo this participant's last undone step. Returns false when refused.
remoteSelectionsOther participants' selections, resolved into this replica's addresses.
sessionIdstringUnique identity for this attachment lifetime.
setIdentityUpdate the display name and color mid-session, when the replica supports it.
statusCurrent lifecycle state.
statusSnapshotCached status, current reason, and last failure.
subscribeParticipantsCall `listener` when the participant list changes. Returns the unsubscribe function.
subscribeRemoteSelectionsCall `listener` when a remote selection changes. Returns the unsubscribe function.
subscribeStatusCall `listener` on each status or reason change. Returns the unsubscribe function.
undoUndo this participant's last step; others' edits stay. Returns false when refused.

CollaborationUndoGroupinterfaceSource ↗

One open undo group of a collaboration session.

Every local write the session publishes while the group is open becomes part of one undo step, however long the group stays open. end() closes the step, so the next write starts a new one, however soon it follows.

interface CollaborationUndoGroup
MemberTypeSummary
endPublish committed local writes into the group, then close it. Reverts nothing. Safe to call more than once, and after the session is destroyed.
state'open' | 'closed'`closed` after `end()`, after the session is destroyed, or after an editor attaches.

CompactCollaborationStateOptionsinterfaceSource ↗

Options for [compactCollaborationState](compactCollaborationState).

interface CompactCollaborationStateOptions
MemberTypeSummary
minimumGain?numberCompact only when the stored state is at least this many times the size of the compacted state. Default 2. Pass 1 to compact whenever it makes the room smaller.

CreateCollaborationRoomRequestinterfaceSource ↗

What a new room starts from.

interface CreateCollaborationRoomRequest
MemberTypeSummary
contextunknownThe context that `onAuthenticate` returned for the connection that opens the room.
roomNamestringThe room's name on the server.

CreateCollaborationStateOptionsinterfaceSource ↗

Options for [createCollaborationState](createCollaborationState).

interface CreateCollaborationStateOptions
MemberTypeSummary
documentIdstringThe room's document ID. Participants must use the same ID. With Hocuspocus it is the room name, the `documentName` of the server hooks.
maxBytes?numberRefuse a file whose size, or whose expanded package size, is over this many bytes, with `baseline-too-large`. The check runs before any part is parsed. Default and maximum `MAX_BASELINE_BYTES` (20 MiB). A value that is not a whole number in that range throws `TypeError`.

CreateDocumentCollaborationOptionsinterfaceSource ↗

Options for one full-document collaboration replica.

The caller owns ydoc.

interface CreateDocumentCollaborationOptions
MemberTypeSummary
awarenessAwarenessPresence channel for participants and remote selections, from `y-protocols/awareness`.
bootstrapCollaborationBootstrapWhether to seed the room, join it, or let the peers decide.
documentIdstringThe room's document id, 1 to 256 characters. A room seeded with another id refuses.
identityCollaborationIdentityThe local participant. Recorded as the author of this replica's changes.
offlineEditing?booleanAdmit local edits while the transport is `disconnected`.
sessionId?stringUnique attachment identity. Omit it to generate a new identity for this session.
ydocY.DocThe room's Yjs document. Connect its provider before a `join` bootstrap.

DocumentCollaborationSessioninterfaceSource ↗

Full-document collaboration session: the engine-facing seam, the transport status a provider sets, and a live display-identity update.

interface DocumentCollaborationSession extends EditorCollaborationSession
MemberTypeSummary
beginUndoGroupOpen an explicit undo group: every local write this session publishes until `end()` is one undo step. For a server or headless replica, such as an agent's.
resourceUsageOne reading of the room's replicated size against this replica's hard limits.
setIdentityUpdate the display identity for the rest of this session and republish presence.
setTransportStatusProvider convenience seam. Low-level consumers normally leave the session ready.
subscribeResourcePressureCall `listener` when the room crosses a fraction of any cap that would end it.
undoGroupOpenbooleanWhether an undo group from [DocumentCollaborationSession.beginUndoGroup](DocumentCollaborationSession.beginUndoGroup) is open.

DocumentCollaborationVersionsinterfaceSource ↗

Version contract for full-document collaboration clients and export workers.

interface DocumentCollaborationVersions
MemberTypeSummary
canonicalModelVersionnumberCanonical document model interpreted by a replica.
protocolVersionnumberTransport-level interpretation of the shared package.
repairVersionnumberDeterministic rules for repairing shared structure.
sharedSchemaVersionnumberShared node and character representation.

MigrateCollaborationRoomOptionsinterfaceSource ↗

Options for [migrateCollaborationRoom](migrateCollaborationRoom).

interface MigrateCollaborationRoomOptions
MemberTypeSummary
documentId?stringThe document ID of the new room. Omit it to keep the earlier room's ID, which is what its clients open the room with: a client whose ID differs is refused with `document-id-mismatch`. Pass it only to give the room a new ID, and open it with that ID.
exportedUint8ArrayThe `.docx` that the build which created the room exported from `state`, with `readCollaborationDocument`.
stateUint8ArrayThe earlier room's saved state: the exact bytes that `exported` was exported from.

StoredCollaborationRoominterfaceSource ↗

A room as storage holds it.

interface StoredCollaborationRoom
MemberTypeSummary
exportCollaborationRoomExport | nullThe export of `state`. In `save`, `null` means that this store has no new export: keep the export that storage already holds. In `load`, `null` means that storage holds none.
stateUint8ArrayThe room state: one Yjs update.

TextCollaborationSessioninterfaceSource ↗

Deprecated. Use DocumentCollaborationSession for full-document collaboration.

Retained type for integrations with the retired text-only collaboration factory.

interface TextCollaborationSession extends EditorCollaborationSession
MemberTypeSummary
setTransportStatus

Type aliases (9)

CollaborationBootstraptypeSource ↗

Create or join bootstrap for one collaboration replica.

The document and WebRTC factories share this union.

create-or-join removes the out-of-band decision about which peer creates a room. The replica probes for an initialized room and joins it when one appears. Otherwise it runs a short awareness election and only the winning candidate seeds from document. A room that two peers seeded concurrently reports the terminal failure code concurrent-seed on every replica.

type CollaborationBootstrap = {
    readonly kind: 'create';
    readonly document: Uint8Array;
} | {
    readonly kind: 'join';
    readonly timeoutMs?: number;
    readonly signal?: AbortSignal;
} | {
    readonly kind: 'create-or-join';
    readonly document: Uint8Array;
    readonly probeTimeoutMs?: number;
    readonly electionWindowMs?: number;
    readonly timeoutMs?: number;
    readonly signal?: AbortSignal;
};

CollaborationMigrationtypeSource ↗

The result of migrateCollaborationRoom.

- ok: true: the check passed. Store state in place of the earlier room's state. - reason: 'check-failed': the new room differs from the export. Nothing is returned to store; report says what differs. - reason: 'current': the room is already in this build's format. Leave it as it is. - reason: 'later-format': a later build wrote the room. Do not open or replace it.

type CollaborationMigration = {
    readonly ok: true;
    readonly state: Uint8Array;
    readonly report: CollaborationMigrationReport;
} | {
    readonly ok: false;
    readonly reason: 'check-failed';
    readonly report: CollaborationMigrationReport;
} | {
    readonly ok: false;
    readonly reason: 'current' | 'later-format';
};

CollaborationMigrationChecktypeSource ↗

A check that a migration runs on the new room, compared with the export.

- paragraphs: the new room holds a different number of paragraphs. - text: a paragraph's text differs. - formatting: a paragraph's properties, or the character formatting of its text, differ. - structure: an XML part differs in something the other checks do not cover, such as tables, sections, styles, numbering, tracked changes, comments, or notes. - media: a media part's bytes are missing. - links: an external link target is missing.

type CollaborationMigrationCheck = 'paragraphs' | 'text' | 'formatting' | 'structure' | 'media' | 'links';

CollaborationMigrationNeedtypeSource ↗

How saved room state relates to the format this build writes.

- current: the room is in this build's format; it needs no migration. - earlier-format: an earlier build wrote it; export it with that build and migrate it. - later-format: a later build wrote it; this build must not open or replace it.

type CollaborationMigrationNeed = 'current' | 'earlier-format' | 'later-format';

CollaborationResourceLimittypeSource ↗

A cap whose crossing ends a room.

- nodes: document node records, deleted nodes included. - parts: package parts. - relationships: relationship records. - blobBytes: bytes in the shared blob map, including bytes no part references any more.

type CollaborationResourceLimit = 'nodes' | 'parts' | 'relationships' | 'blobBytes';

CollaborationRoomUpgradeRefusaltypeSource ↗

Why the server did not upgrade a saved room of an earlier format.

- disabled: upgradeOnLoad is false. - no-export: storage holds no export of the room. - stale-export: the export was made from another state than the stored one. - too-large: the state is larger than maxUpgradeStateBytes. - check-failed: the upgraded room differs from the export. - error: the state or the export cannot be read; code says why.

type CollaborationRoomUpgradeRefusal = 'disabled' | 'no-export' | 'stale-export' | 'too-large' | 'check-failed' | 'error';

CollaborationServerEventtypeSource ↗

Something the collaboration server did to a room, for logs and metrics.

type CollaborationServerEvent = {
    readonly type: 'room-upgraded';
    readonly roomName: string;
    readonly from: string;
    readonly to: string;
    readonly hidden: number;
    readonly hiddenAt: readonly CollaborationMigrationPosition[];
} | {
    readonly type: 'room-upgrade-refused';
    readonly roomName: string;
    readonly reason: CollaborationRoomUpgradeRefusal;
    readonly code?: string;
    readonly failed?: readonly CollaborationMigrationCheck[];
    readonly changedParts?: readonly string[];
    readonly differencesAt?: readonly CollaborationMigrationPosition[];
} | {
    readonly type: 'room-load-refused';
    readonly roomName: string;
    readonly code: string;
} | {
    readonly type: 'room-compaction-failed';
    readonly roomName: string;
    readonly code: string;
} | {
    readonly type: 'room-export-failed';
    readonly roomName: string;
    readonly code: string;
};

CollaborationUndoGroupErrorCodetypeSource ↗

Why beginUndoGroup refused.

- undo-group-already-open: this session already has an open group. Groups do not nest and two operations cannot share one session's group. End the open group first, or give each concurrent operation its own session. - editor-attached: an editor that people edit through is attached to this session. Use the editor's own beginHistoryGroup() there. - collaboration-session-destroyed: the session was destroyed.

type CollaborationUndoGroupErrorCode = 'undo-group-already-open' | 'editor-attached' | 'collaboration-session-destroyed';

DocumentCollaborationHandletypeSource ↗

Owned full-document collaboration replica.

type DocumentCollaborationHandle = CollaborationHandle<DocumentCollaborationSession>;

Variables (6)

COLLABORATION_FORMAT_PARAMETERconstSource ↗

The query parameter in which a Hocuspocus client names its collaboration format.

createHocuspocusCollaboration and the provider hooks add it to the server URL, with COLLABORATION_FORMAT_VERSION as its value. A server reads it from requestParameters in onAuthenticate; collaborationServerExtension does that for you.

COLLABORATION_FORMAT_PARAMETER = "collaborationFormat"

COLLABORATION_FORMAT_VERSIONconstSource ↗

Opaque collaboration format version, independent of the editor package version.

Send this value unchanged during connection admission. Check it with [assertCollaborationFormatCompatibility](assertCollaborationFormatCompatibility) before allowing synchronization. Equal values declare format compatibility across clients, workers, and saved rooms. Do not parse, order, hard-code, or override the value. It is not a credential. Inspect saved rooms separately with [readCollaborationFormatVersion](readCollaborationFormatVersion).

COLLABORATION_FORMAT_VERSION: string

DOCUMENT_COLLABORATION_VERSIONSconstSource ↗

Deprecated. Send `COLLABORATION_FORMAT_VERSION` in the connection handshake and check it with `assertCollaborationFormatCompatibility`. This tuple stays supported for existing handshakes.

Versions supported by this full-document collaboration release.

These values describe the application schema, not the DOCX format or the Yjs binary update format. Releases with the same tuple can share rooms. A changed tuple requires a coordinated upgrade. This descriptor does not migrate persisted rooms or authenticate clients.

DOCUMENT_COLLABORATION_VERSIONS: DocumentCollaborationVersions

MAX_BASELINE_BYTESconstSource ↗

Deprecated. Use the full-document factory's validation and typed failure codes.

Historical baseline byte limit for the retired text-only collaboration factory. This value does not configure full-document collaboration limits.

MAX_BASELINE_BYTES: number

PROTOCOL_VERSIONconstSource ↗

Deprecated. Use COLLABORATION_FORMAT_VERSION for full-document connection checks.

Protocol identifier for the retired text-only collaboration format.

PROTOCOL_VERSION = 1

SCHEMA_VERSIONconstSource ↗

Deprecated. Use COLLABORATION_FORMAT_VERSION for full-document connection checks.

Schema identifier for the retired text-only collaboration format.

SCHEMA_VERSION = 1