y-partyserver 2.0.0 → 2.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/provider/index.d.ts +0 -1
- package/dist/provider/index.js +9 -17
- package/dist/provider/index.js.map +1 -1
- package/dist/server/index.d.ts +14 -43
- package/dist/server/index.js +197 -675
- package/dist/server/index.js.map +1 -1
- package/package.json +28 -24
package/dist/server/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["#cache","#connections","#ParentClass","#_props","#_name","#status","#initialize","#connectionManager","#attachSocketEventHandlers","#_longErrorAboutNameThrown","#sendMessageToConnection","YDoc","controlledIds: Set<number>","#ParentClass","encoder"],"sources":["../../../partyserver/dist/index.js","../../src/server/index.ts"],"sourcesContent":["import { DurableObject, env } from \"cloudflare:workers\";\nimport { nanoid } from \"nanoid\";\n\n//#region src/connection.ts\nif (!(\"OPEN\" in WebSocket)) {\n\tconst WebSocketStatus = {\n\t\tCONNECTING: WebSocket.READY_STATE_CONNECTING,\n\t\tOPEN: WebSocket.READY_STATE_OPEN,\n\t\tCLOSING: WebSocket.READY_STATE_CLOSING,\n\t\tCLOSED: WebSocket.READY_STATE_CLOSED\n\t};\n\tObject.assign(WebSocket, WebSocketStatus);\n\tObject.assign(WebSocket.prototype, WebSocketStatus);\n}\nfunction tryGetPartyServerMeta(ws) {\n\ttry {\n\t\tconst attachment = WebSocket.prototype.deserializeAttachment.call(ws);\n\t\tif (!attachment || typeof attachment !== \"object\") return null;\n\t\tif (!(\"__pk\" in attachment)) return null;\n\t\tconst pk = attachment.__pk;\n\t\tif (!pk || typeof pk !== \"object\") return null;\n\t\tconst { id, server, tags } = pk;\n\t\tif (typeof id !== \"string\" || typeof server !== \"string\") return null;\n\t\treturn {\n\t\t\tid,\n\t\t\tserver,\n\t\t\ttags: Array.isArray(tags) ? tags : []\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction isPartyServerWebSocket(ws) {\n\treturn tryGetPartyServerMeta(ws) !== null;\n}\n/**\n* Cache websocket attachments to avoid having to rehydrate them on every property access.\n*/\nvar AttachmentCache = class {\n\t#cache = /* @__PURE__ */ new WeakMap();\n\tget(ws) {\n\t\tlet attachment = this.#cache.get(ws);\n\t\tif (!attachment) {\n\t\t\tattachment = WebSocket.prototype.deserializeAttachment.call(ws);\n\t\t\tif (attachment !== void 0) this.#cache.set(ws, attachment);\n\t\t\telse throw new Error(\"Missing websocket attachment. This is most likely an issue in PartyServer, please open an issue at https://github.com/cloudflare/partykit/issues\");\n\t\t}\n\t\treturn attachment;\n\t}\n\tset(ws, attachment) {\n\t\tthis.#cache.set(ws, attachment);\n\t\tWebSocket.prototype.serializeAttachment.call(ws, attachment);\n\t}\n};\nconst attachments = new AttachmentCache();\nconst connections = /* @__PURE__ */ new WeakSet();\nconst isWrapped = (ws) => {\n\treturn connections.has(ws);\n};\n/**\n* Wraps a WebSocket with Connection fields that rehydrate the\n* socket attachments lazily only when requested.\n*/\nconst createLazyConnection = (ws) => {\n\tif (isWrapped(ws)) return ws;\n\tlet initialState;\n\tif (\"state\" in ws) {\n\t\tinitialState = ws.state;\n\t\tdelete ws.state;\n\t}\n\tconst connection = Object.defineProperties(ws, {\n\t\tid: { get() {\n\t\t\treturn attachments.get(ws).__pk.id;\n\t\t} },\n\t\tserver: { get() {\n\t\t\treturn attachments.get(ws).__pk.server;\n\t\t} },\n\t\ttags: { get() {\n\t\t\treturn attachments.get(ws).__pk.tags ?? [];\n\t\t} },\n\t\tsocket: { get() {\n\t\t\treturn ws;\n\t\t} },\n\t\tstate: {\n\t\t\tconfigurable: true,\n\t\t\tget() {\n\t\t\t\treturn ws.deserializeAttachment();\n\t\t\t}\n\t\t},\n\t\tsetState: {\n\t\t\tconfigurable: true,\n\t\t\tvalue: function setState(setState$1) {\n\t\t\t\tlet state;\n\t\t\t\tif (setState$1 instanceof Function) state = setState$1(this.state);\n\t\t\t\telse state = setState$1;\n\t\t\t\tws.serializeAttachment(state);\n\t\t\t\treturn state;\n\t\t\t}\n\t\t},\n\t\tdeserializeAttachment: {\n\t\t\tconfigurable: true,\n\t\t\tvalue: function deserializeAttachment() {\n\t\t\t\treturn attachments.get(ws).__user ?? null;\n\t\t\t}\n\t\t},\n\t\tserializeAttachment: {\n\t\t\tconfigurable: true,\n\t\t\tvalue: function serializeAttachment(attachment) {\n\t\t\t\tconst setting = {\n\t\t\t\t\t...attachments.get(ws),\n\t\t\t\t\t__user: attachment ?? null\n\t\t\t\t};\n\t\t\t\tattachments.set(ws, setting);\n\t\t\t}\n\t\t}\n\t});\n\tif (initialState) connection.setState(initialState);\n\tconnections.add(connection);\n\treturn connection;\n};\nvar HibernatingConnectionIterator = class {\n\tindex = 0;\n\tsockets;\n\tconstructor(state, tag) {\n\t\tthis.state = state;\n\t\tthis.tag = tag;\n\t}\n\t[Symbol.iterator]() {\n\t\treturn this;\n\t}\n\tnext() {\n\t\tconst sockets = this.sockets ?? (this.sockets = this.state.getWebSockets(this.tag));\n\t\tlet socket;\n\t\twhile (socket = sockets[this.index++]) if (socket.readyState === WebSocket.READY_STATE_OPEN) {\n\t\t\tif (!isPartyServerWebSocket(socket)) continue;\n\t\t\treturn {\n\t\t\t\tdone: false,\n\t\t\t\tvalue: createLazyConnection(socket)\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tdone: true,\n\t\t\tvalue: void 0\n\t\t};\n\t}\n};\n/**\n* Deduplicate and validate connection tags.\n* Returns the final tag array (always includes the connection id as the first tag).\n*/\nfunction prepareTags(connectionId, userTags) {\n\tconst tags = [connectionId, ...userTags.filter((t) => t !== connectionId)];\n\tif (tags.length > 10) throw new Error(\"A connection can only have 10 tags, including the default id tag.\");\n\tfor (const tag of tags) {\n\t\tif (typeof tag !== \"string\") throw new Error(`A connection tag must be a string. Received: ${tag}`);\n\t\tif (tag === \"\") throw new Error(\"A connection tag must not be an empty string.\");\n\t\tif (tag.length > 256) throw new Error(\"A connection tag must not exceed 256 characters\");\n\t}\n\treturn tags;\n}\n/**\n* When not using hibernation, we track active connections manually.\n*/\nvar InMemoryConnectionManager = class {\n\t#connections = /* @__PURE__ */ new Map();\n\ttags = /* @__PURE__ */ new WeakMap();\n\tgetCount() {\n\t\treturn this.#connections.size;\n\t}\n\tgetConnection(id) {\n\t\treturn this.#connections.get(id);\n\t}\n\t*getConnections(tag) {\n\t\tif (!tag) {\n\t\t\tyield* this.#connections.values().filter((c) => c.readyState === WebSocket.READY_STATE_OPEN);\n\t\t\treturn;\n\t\t}\n\t\tfor (const connection of this.#connections.values()) if ((this.tags.get(connection) ?? []).includes(tag)) yield connection;\n\t}\n\taccept(connection, options) {\n\t\tconnection.accept();\n\t\tconst tags = prepareTags(connection.id, options.tags);\n\t\tthis.#connections.set(connection.id, connection);\n\t\tthis.tags.set(connection, tags);\n\t\tObject.defineProperty(connection, \"tags\", {\n\t\t\tget: () => tags,\n\t\t\tconfigurable: true\n\t\t});\n\t\tconst removeConnection = () => {\n\t\t\tthis.#connections.delete(connection.id);\n\t\t\tconnection.removeEventListener(\"close\", removeConnection);\n\t\t\tconnection.removeEventListener(\"error\", removeConnection);\n\t\t};\n\t\tconnection.addEventListener(\"close\", removeConnection);\n\t\tconnection.addEventListener(\"error\", removeConnection);\n\t\treturn connection;\n\t}\n};\n/**\n* When opting into hibernation, the platform tracks connections for us.\n*/\nvar HibernatingConnectionManager = class {\n\tconstructor(controller) {\n\t\tthis.controller = controller;\n\t}\n\tgetCount() {\n\t\tlet count = 0;\n\t\tfor (const ws of this.controller.getWebSockets()) if (isPartyServerWebSocket(ws)) count++;\n\t\treturn count;\n\t}\n\tgetConnection(id) {\n\t\tconst matching = this.controller.getWebSockets(id).filter((ws) => {\n\t\t\treturn tryGetPartyServerMeta(ws)?.id === id;\n\t\t});\n\t\tif (matching.length === 0) return void 0;\n\t\tif (matching.length === 1) return createLazyConnection(matching[0]);\n\t\tthrow new Error(`More than one connection found for id ${id}. Did you mean to use getConnections(tag) instead?`);\n\t}\n\tgetConnections(tag) {\n\t\treturn new HibernatingConnectionIterator(this.controller, tag);\n\t}\n\taccept(connection, options) {\n\t\tconst tags = prepareTags(connection.id, options.tags);\n\t\tthis.controller.acceptWebSocket(connection, tags);\n\t\tconnection.serializeAttachment({\n\t\t\t__pk: {\n\t\t\t\tid: connection.id,\n\t\t\t\tserver: options.server,\n\t\t\t\ttags\n\t\t\t},\n\t\t\t__user: null\n\t\t});\n\t\treturn createLazyConnection(connection);\n\t}\n};\n\n//#endregion\n//#region src/index.ts\nconst serverMapCache = /* @__PURE__ */ new WeakMap();\nconst bindingNameCache = /* @__PURE__ */ new WeakMap();\n/**\n* For a given server namespace, create a server with a name.\n*/\nasync function getServerByName(serverNamespace, name, options) {\n\tif (options?.jurisdiction) serverNamespace = serverNamespace.jurisdiction(options.jurisdiction);\n\tconst id = serverNamespace.idFromName(name);\n\tconst stub = serverNamespace.get(id, options);\n\tconst req = new Request(\"http://dummy-example.cloudflare.com/cdn-cgi/partyserver/set-name/\");\n\treq.headers.set(\"x-partykit-room\", name);\n\tif (options?.props) req.headers.set(\"x-partykit-props\", JSON.stringify(options?.props));\n\tawait stub.fetch(req).then((res) => res.text());\n\treturn stub;\n}\nfunction camelCaseToKebabCase(str) {\n\tif (str === str.toUpperCase() && str !== str.toLowerCase()) return str.toLowerCase().replace(/_/g, \"-\");\n\tlet kebabified = str.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n\tkebabified = kebabified.startsWith(\"-\") ? kebabified.slice(1) : kebabified;\n\treturn kebabified.replace(/_/g, \"-\").replace(/-$/, \"\");\n}\n/**\n* Resolve CORS options into a concrete headers object (or null if CORS is disabled).\n*/\nfunction resolveCorsHeaders(cors) {\n\tif (cors === true) return {\n\t\t\"Access-Control-Allow-Origin\": \"*\",\n\t\t\"Access-Control-Allow-Methods\": \"GET, POST, HEAD, OPTIONS\",\n\t\t\"Access-Control-Allow-Headers\": \"*\",\n\t\t\"Access-Control-Max-Age\": \"86400\"\n\t};\n\tif (cors && typeof cors === \"object\") {\n\t\tconst h = new Headers(cors);\n\t\tconst record = {};\n\t\th.forEach((value, key) => {\n\t\t\trecord[key] = value;\n\t\t});\n\t\treturn record;\n\t}\n\treturn null;\n}\nasync function routePartykitRequest(req, env$1 = env, options) {\n\tif (!serverMapCache.has(env$1)) {\n\t\tconst namespaceMap = {};\n\t\tconst bindingNames$1 = {};\n\t\tfor (const [k, v] of Object.entries(env$1)) if (v && typeof v === \"object\" && \"idFromName\" in v && typeof v.idFromName === \"function\") {\n\t\t\tconst kebab = camelCaseToKebabCase(k);\n\t\t\tnamespaceMap[kebab] = v;\n\t\t\tbindingNames$1[kebab] = k;\n\t\t}\n\t\tserverMapCache.set(env$1, namespaceMap);\n\t\tbindingNameCache.set(env$1, bindingNames$1);\n\t}\n\tconst map = serverMapCache.get(env$1);\n\tconst bindingNames = bindingNameCache.get(env$1);\n\tconst prefixParts = (options?.prefix || \"parties\").split(\"/\");\n\tconst parts = new URL(req.url).pathname.split(\"/\").filter(Boolean);\n\tif (!prefixParts.every((part, index) => parts[index] === part) || parts.length < prefixParts.length + 2) return null;\n\tconst namespace = parts[prefixParts.length];\n\tconst name = parts[prefixParts.length + 1];\n\tif (name && namespace) {\n\t\tif (!map[namespace]) {\n\t\t\tif (namespace === \"main\") {\n\t\t\t\tconsole.warn(\"You appear to be migrating a PartyKit project to PartyServer.\");\n\t\t\t\tconsole.warn(`PartyServer doesn't have a \"main\" party by default. Try adding this to your PartySocket client:\\n \nparty: \"${camelCaseToKebabCase(Object.keys(map)[0])}\"`);\n\t\t\t} else console.error(`The url ${req.url} with namespace \"${namespace}\" and name \"${name}\" does not match any server namespace. \nDid you forget to add a durable object binding to the class ${namespace[0].toUpperCase() + namespace.slice(1)} in your wrangler.jsonc?`);\n\t\t\treturn new Response(\"Invalid request\", { status: 400 });\n\t\t}\n\t\tconst corsHeaders = resolveCorsHeaders(options?.cors);\n\t\tconst isWebSocket = req.headers.get(\"Upgrade\")?.toLowerCase() === \"websocket\";\n\t\tfunction withCorsHeaders(response) {\n\t\t\tif (!corsHeaders || isWebSocket) return response;\n\t\t\tconst newResponse = new Response(response.body, response);\n\t\t\tfor (const [key, value] of Object.entries(corsHeaders)) newResponse.headers.set(key, value);\n\t\t\treturn newResponse;\n\t\t}\n\t\tif (req.method === \"OPTIONS\" && corsHeaders) return new Response(null, { headers: corsHeaders });\n\t\tlet doNamespace = map[namespace];\n\t\tif (options?.jurisdiction) doNamespace = doNamespace.jurisdiction(options.jurisdiction);\n\t\tconst id = doNamespace.idFromName(name);\n\t\tconst stub = doNamespace.get(id, options);\n\t\treq = new Request(req);\n\t\treq.headers.set(\"x-partykit-room\", name);\n\t\treq.headers.set(\"x-partykit-namespace\", namespace);\n\t\tif (options?.jurisdiction) req.headers.set(\"x-partykit-jurisdiction\", options.jurisdiction);\n\t\tif (options?.props) req.headers.set(\"x-partykit-props\", JSON.stringify(options?.props));\n\t\tconst className = bindingNames[namespace];\n\t\tlet partyDeprecationWarned = false;\n\t\tconst lobby = {\n\t\t\tget party() {\n\t\t\t\tif (!partyDeprecationWarned) {\n\t\t\t\t\tpartyDeprecationWarned = true;\n\t\t\t\t\tconsole.warn(\"lobby.party is deprecated and currently returns the kebab-case namespace (e.g. \\\"my-agent\\\"). Use lobby.className instead to get the Durable Object class name (e.g. \\\"MyAgent\\\"). In the next major version, lobby.party will return the class name.\");\n\t\t\t\t}\n\t\t\t\treturn namespace;\n\t\t\t},\n\t\t\tclassName,\n\t\t\tname\n\t\t};\n\t\tif (isWebSocket) {\n\t\t\tif (options?.onBeforeConnect) {\n\t\t\t\tconst reqOrRes = await options.onBeforeConnect(req, lobby);\n\t\t\t\tif (reqOrRes instanceof Request) req = reqOrRes;\n\t\t\t\telse if (reqOrRes instanceof Response) return reqOrRes;\n\t\t\t}\n\t\t} else if (options?.onBeforeRequest) {\n\t\t\tconst reqOrRes = await options.onBeforeRequest(req, lobby);\n\t\t\tif (reqOrRes instanceof Request) req = reqOrRes;\n\t\t\telse if (reqOrRes instanceof Response) return withCorsHeaders(reqOrRes);\n\t\t}\n\t\treturn withCorsHeaders(await stub.fetch(req));\n\t} else return null;\n}\nvar Server = class extends DurableObject {\n\tstatic options = { hibernate: false };\n\t#status = \"zero\";\n\t#ParentClass = Object.getPrototypeOf(this).constructor;\n\t#connectionManager = this.#ParentClass.options.hibernate ? new HibernatingConnectionManager(this.ctx) : new InMemoryConnectionManager();\n\t/**\n\t* Execute SQL queries against the Server's database\n\t* @template T Type of the returned rows\n\t* @param strings SQL query template strings\n\t* @param values Values to be inserted into the query\n\t* @returns Array of query results\n\t*/\n\tsql(strings, ...values) {\n\t\tlet query = \"\";\n\t\ttry {\n\t\t\tquery = strings.reduce((acc, str, i) => acc + str + (i < values.length ? \"?\" : \"\"), \"\");\n\t\t\treturn [...this.ctx.storage.sql.exec(query, ...values)];\n\t\t} catch (e) {\n\t\t\tconsole.error(`failed to execute sql query: ${query}`, e);\n\t\t\tthrow this.onException(e);\n\t\t}\n\t}\n\tconstructor(ctx, env$1) {\n\t\tsuper(ctx, env$1);\n\t}\n\t/**\n\t* Handle incoming requests to the server.\n\t*/\n\tasync fetch(request) {\n\t\ttry {\n\t\t\tconst props = request.headers.get(\"x-partykit-props\");\n\t\t\tif (props) this.#_props = JSON.parse(props);\n\t\t\tif (!this.#_name) {\n\t\t\t\tconst room = request.headers.get(\"x-partykit-room\");\n\t\t\t\tif (!room) throw new Error(`Missing namespace or room headers when connecting to ${this.#ParentClass.name}.\nDid you try connecting directly to this Durable Object? Try using getServerByName(namespace, id) instead.`);\n\t\t\t\tawait this.setName(room);\n\t\t\t} else if (this.#status !== \"started\") await this.#initialize();\n\t\t\tconst url = new URL(request.url);\n\t\t\tif (url.pathname === \"/cdn-cgi/partyserver/set-name/\") return Response.json({ ok: true });\n\t\t\tif (request.headers.get(\"Upgrade\")?.toLowerCase() !== \"websocket\") return await this.onRequest(request);\n\t\t\telse {\n\t\t\t\tconst { 0: clientWebSocket, 1: serverWebSocket } = new WebSocketPair();\n\t\t\t\tlet connectionId = url.searchParams.get(\"_pk\");\n\t\t\t\tif (!connectionId) connectionId = nanoid();\n\t\t\t\tlet connection = Object.assign(serverWebSocket, {\n\t\t\t\t\tid: connectionId,\n\t\t\t\t\tserver: this.name,\n\t\t\t\t\ttags: [],\n\t\t\t\t\tstate: null,\n\t\t\t\t\tsetState(setState) {\n\t\t\t\t\t\tlet state;\n\t\t\t\t\t\tif (setState instanceof Function) state = setState(this.state);\n\t\t\t\t\t\telse state = setState;\n\t\t\t\t\t\tthis.state = state;\n\t\t\t\t\t\treturn this.state;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tconst ctx = { request };\n\t\t\t\tconst tags = await this.getConnectionTags(connection, ctx);\n\t\t\t\tconnection = this.#connectionManager.accept(connection, {\n\t\t\t\t\ttags,\n\t\t\t\t\tserver: this.name\n\t\t\t\t});\n\t\t\t\tif (!this.#ParentClass.options.hibernate) this.#attachSocketEventHandlers(connection);\n\t\t\t\tawait this.onConnect(connection, ctx);\n\t\t\t\treturn new Response(null, {\n\t\t\t\t\tstatus: 101,\n\t\t\t\t\twebSocket: clientWebSocket\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tconsole.error(`Error in ${this.#ParentClass.name}:${this.#_name ?? \"<unnamed>\"} fetch:`, err);\n\t\t\tif (!(err instanceof Error)) throw err;\n\t\t\tif (request.headers.get(\"Upgrade\") === \"websocket\") {\n\t\t\t\tconst pair = new WebSocketPair();\n\t\t\t\tpair[1].accept();\n\t\t\t\tpair[1].send(JSON.stringify({ error: err.stack }));\n\t\t\t\tpair[1].close(1011, \"Uncaught exception during session setup\");\n\t\t\t\treturn new Response(null, {\n\t\t\t\t\tstatus: 101,\n\t\t\t\t\twebSocket: pair[0]\n\t\t\t\t});\n\t\t\t} else return new Response(err.stack, { status: 500 });\n\t\t}\n\t}\n\tasync webSocketMessage(ws, message) {\n\t\tif (!isPartyServerWebSocket(ws)) return;\n\t\ttry {\n\t\t\tconst connection = createLazyConnection(ws);\n\t\t\tawait this.setName(connection.server);\n\t\t\treturn this.onMessage(connection, message);\n\t\t} catch (e) {\n\t\t\tconsole.error(`Error in ${this.#ParentClass.name}:${this.#_name ?? \"<unnamed>\"} webSocketMessage:`, e);\n\t\t}\n\t}\n\tasync webSocketClose(ws, code, reason, wasClean) {\n\t\tif (!isPartyServerWebSocket(ws)) return;\n\t\ttry {\n\t\t\tconst connection = createLazyConnection(ws);\n\t\t\tawait this.setName(connection.server);\n\t\t\treturn this.onClose(connection, code, reason, wasClean);\n\t\t} catch (e) {\n\t\t\tconsole.error(`Error in ${this.#ParentClass.name}:${this.#_name ?? \"<unnamed>\"} webSocketClose:`, e);\n\t\t}\n\t}\n\tasync webSocketError(ws, error) {\n\t\tif (!isPartyServerWebSocket(ws)) return;\n\t\ttry {\n\t\t\tconst connection = createLazyConnection(ws);\n\t\t\tawait this.setName(connection.server);\n\t\t\treturn this.onError(connection, error);\n\t\t} catch (e) {\n\t\t\tconsole.error(`Error in ${this.#ParentClass.name}:${this.#_name ?? \"<unnamed>\"} webSocketError:`, e);\n\t\t}\n\t}\n\tasync #initialize() {\n\t\tlet error;\n\t\tawait this.ctx.blockConcurrencyWhile(async () => {\n\t\t\tthis.#status = \"starting\";\n\t\t\ttry {\n\t\t\t\tawait this.onStart(this.#_props);\n\t\t\t\tthis.#status = \"started\";\n\t\t\t} catch (e) {\n\t\t\t\tthis.#status = \"zero\";\n\t\t\t\terror = e;\n\t\t\t}\n\t\t});\n\t\tif (error) throw error;\n\t}\n\t#attachSocketEventHandlers(connection) {\n\t\tconst handleMessageFromClient = (event) => {\n\t\t\tthis.onMessage(connection, event.data)?.catch((e) => {\n\t\t\t\tconsole.error(\"onMessage error:\", e);\n\t\t\t});\n\t\t};\n\t\tconst handleCloseFromClient = (event) => {\n\t\t\tconnection.removeEventListener(\"message\", handleMessageFromClient);\n\t\t\tconnection.removeEventListener(\"close\", handleCloseFromClient);\n\t\t\tthis.onClose(connection, event.code, event.reason, event.wasClean)?.catch((e) => {\n\t\t\t\tconsole.error(\"onClose error:\", e);\n\t\t\t});\n\t\t};\n\t\tconst handleErrorFromClient = (e) => {\n\t\t\tconnection.removeEventListener(\"message\", handleMessageFromClient);\n\t\t\tconnection.removeEventListener(\"error\", handleErrorFromClient);\n\t\t\tthis.onError(connection, e.error)?.catch((e$1) => {\n\t\t\t\tconsole.error(\"onError error:\", e$1);\n\t\t\t});\n\t\t};\n\t\tconnection.addEventListener(\"close\", handleCloseFromClient);\n\t\tconnection.addEventListener(\"error\", handleErrorFromClient);\n\t\tconnection.addEventListener(\"message\", handleMessageFromClient);\n\t}\n\t#_name;\n\t#_longErrorAboutNameThrown = false;\n\t/**\n\t* The name for this server. Write-once-only.\n\t*/\n\tget name() {\n\t\tif (!this.#_name) if (!this.#_longErrorAboutNameThrown) {\n\t\t\tthis.#_longErrorAboutNameThrown = true;\n\t\t\tthrow new Error(`Attempting to read .name on ${this.#ParentClass.name} before it was set. The name can be set by explicitly calling .setName(name) on the stub, or by using routePartyKitRequest(). This is a known issue and will be fixed soon. Follow https://github.com/cloudflare/workerd/issues/2240 for more updates.`);\n\t\t} else throw new Error(`Attempting to read .name on ${this.#ParentClass.name} before it was set.`);\n\t\treturn this.#_name;\n\t}\n\tasync setName(name) {\n\t\tif (!name) throw new Error(\"A name is required.\");\n\t\tif (this.#_name && this.#_name !== name) throw new Error(`This server already has a name: ${this.#_name}, attempting to set to: ${name}`);\n\t\tthis.#_name = name;\n\t\tif (this.#status !== \"started\") await this.#initialize();\n\t}\n\t#sendMessageToConnection(connection, message) {\n\t\ttry {\n\t\t\tconnection.send(message);\n\t\t} catch (_e) {\n\t\t\tconnection.close(1011, \"Unexpected error\");\n\t\t}\n\t}\n\t/** Send a message to all connected clients, except connection ids listed in `without` */\n\tbroadcast(msg, without) {\n\t\tfor (const connection of this.#connectionManager.getConnections()) if (!without || !without.includes(connection.id)) this.#sendMessageToConnection(connection, msg);\n\t}\n\t/** Get a connection by connection id */\n\tgetConnection(id) {\n\t\treturn this.#connectionManager.getConnection(id);\n\t}\n\t/**\n\t* Get all connections. Optionally, you can provide a tag to filter returned connections.\n\t* Use `Server#getConnectionTags` to tag the connection on connect.\n\t*/\n\tgetConnections(tag) {\n\t\treturn this.#connectionManager.getConnections(tag);\n\t}\n\t/**\n\t* You can tag a connection to filter them in Server#getConnections.\n\t* Each connection supports up to 9 tags, each tag max length is 256 characters.\n\t*/\n\tgetConnectionTags(connection, context) {\n\t\treturn [];\n\t}\n\t#_props;\n\t/**\n\t* Called when the server is started for the first time.\n\t*/\n\tonStart(props) {}\n\t/**\n\t* Called when a new connection is made to the server.\n\t*/\n\tonConnect(connection, ctx) {\n\t\tconsole.log(`Connection ${connection.id} connected to ${this.#ParentClass.name}:${this.name}`);\n\t}\n\t/**\n\t* Called when a message is received from a connection.\n\t*/\n\tonMessage(connection, message) {\n\t\tconsole.log(`Received message on connection ${this.#ParentClass.name}:${connection.id}`);\n\t\tconsole.info(`Implement onMessage on ${this.#ParentClass.name} to handle this message.`);\n\t}\n\t/**\n\t* Called when a connection is closed.\n\t*/\n\tonClose(connection, code, reason, wasClean) {}\n\t/**\n\t* Called when an error occurs on a connection.\n\t*/\n\tonError(connection, error) {\n\t\tconsole.error(`Error on connection ${connection.id} in ${this.#ParentClass.name}:${this.name}:`, error);\n\t\tconsole.info(`Implement onError on ${this.#ParentClass.name} to handle this error.`);\n\t}\n\t/**\n\t* Called when a request is made to the server.\n\t*/\n\tonRequest(request) {\n\t\tconsole.warn(`onRequest hasn't been implemented on ${this.#ParentClass.name}:${this.name} responding to ${request.url}`);\n\t\treturn new Response(\"Not implemented\", { status: 404 });\n\t}\n\t/**\n\t* Called when an exception occurs.\n\t* @param error - The error that occurred.\n\t*/\n\tonException(error) {\n\t\tconsole.error(`Exception in ${this.#ParentClass.name}:${this.name}:`, error);\n\t\tconsole.info(`Implement onException on ${this.#ParentClass.name} to handle this error.`);\n\t}\n\tonAlarm() {\n\t\tconsole.log(`Implement onAlarm on ${this.#ParentClass.name} to handle alarms.`);\n\t}\n\tasync alarm() {\n\t\tif (this.#status !== \"started\") await this.#initialize();\n\t\tawait this.onAlarm();\n\t}\n};\n\n//#endregion\nexport { Server, getServerByName, routePartykitRequest };\n//# sourceMappingURL=index.js.map","import * as decoding from \"lib0/decoding\";\nimport * as encoding from \"lib0/encoding\";\nimport debounce from \"lodash.debounce\";\nimport type { Connection, ConnectionContext, WSMessage } from \"partyserver\";\nimport { Server } from \"partyserver\";\nimport * as awarenessProtocol from \"y-protocols/awareness\";\nimport * as syncProtocol from \"y-protocols/sync\";\nimport {\n applyUpdate,\n Doc as YDoc,\n encodeStateAsUpdate,\n encodeStateVector,\n UndoManager,\n XmlText,\n XmlElement,\n XmlFragment\n} from \"yjs\";\n\nconst snapshotOrigin = Symbol(\"snapshot-origin\");\ntype YjsRootType =\n | \"Text\"\n | \"Map\"\n | \"Array\"\n | \"XmlText\"\n | \"XmlElement\"\n | \"XmlFragment\";\n\nconst wsReadyStateConnecting = 0;\nconst wsReadyStateOpen = 1;\n// biome-ignore lint/correctness/noUnusedVariables: it's fine\nconst wsReadyStateClosing = 2;\n// biome-ignore lint/correctness/noUnusedVariables: it's fine\nconst wsReadyStateClosed = 3;\n\nconst messageSync = 0;\nconst messageAwareness = 1;\n// biome-ignore lint/correctness/noUnusedVariables: it's fine\nconst messageAuth = 2;\n\nfunction updateHandler(update: Uint8Array, _origin: unknown, doc: WSSharedDoc) {\n const encoder = encoding.createEncoder();\n encoding.writeVarUint(encoder, messageSync);\n syncProtocol.writeUpdate(encoder, update);\n const message = encoding.toUint8Array(encoder);\n doc.conns.forEach((_, conn) => {\n send(doc, conn, message);\n });\n}\n\nclass WSSharedDoc extends YDoc {\n conns: Map<Connection, Set<number>>;\n awareness: awarenessProtocol.Awareness;\n\n constructor() {\n super({ gc: true });\n\n /**\n * Maps from conn to set of controlled user ids. Delete all user ids from awareness when this conn is closed\n */\n this.conns = new Map();\n\n this.awareness = new awarenessProtocol.Awareness(this);\n this.awareness.setLocalState(null);\n\n const awarenessChangeHandler = (\n {\n added,\n updated,\n removed\n }: {\n added: Array<number>;\n updated: Array<number>;\n removed: Array<number>;\n },\n conn: Connection | null // Origin is the connection that made the change\n ) => {\n const changedClients = added.concat(updated, removed);\n if (conn !== null) {\n const connControlledIDs =\n /** @type {Set<number>} */ this.conns.get(conn);\n if (connControlledIDs !== undefined) {\n added.forEach((clientID) => {\n connControlledIDs.add(clientID);\n });\n removed.forEach((clientID) => {\n connControlledIDs.delete(clientID);\n });\n }\n }\n // broadcast awareness update\n const encoder = encoding.createEncoder();\n encoding.writeVarUint(encoder, messageAwareness);\n encoding.writeVarUint8Array(\n encoder,\n awarenessProtocol.encodeAwarenessUpdate(this.awareness, changedClients)\n );\n const buff = encoding.toUint8Array(encoder);\n this.conns.forEach((_, c) => {\n send(this, c, buff);\n });\n };\n this.awareness.on(\"update\", awarenessChangeHandler);\n // @ts-expect-error - TODO: fix this\n this.on(\"update\", updateHandler);\n }\n}\n\nconst CALLBACK_DEFAULTS = {\n debounceWait: 2000,\n debounceMaxWait: 10000,\n timeout: 5000\n};\n\nfunction readSyncMessage(\n decoder: decoding.Decoder,\n encoder: encoding.Encoder,\n doc: YDoc,\n transactionOrigin: Connection,\n readOnly = false\n) {\n const messageType = decoding.readVarUint(decoder);\n switch (messageType) {\n case syncProtocol.messageYjsSyncStep1:\n syncProtocol.readSyncStep1(decoder, encoder, doc);\n break;\n case syncProtocol.messageYjsSyncStep2:\n if (!readOnly)\n syncProtocol.readSyncStep2(decoder, doc, transactionOrigin);\n break;\n case syncProtocol.messageYjsUpdate:\n if (!readOnly) syncProtocol.readUpdate(decoder, doc, transactionOrigin);\n break;\n default:\n throw new Error(\"Unknown message type\");\n }\n return messageType;\n}\n\nfunction closeConn(doc: WSSharedDoc, conn: Connection): void {\n if (doc.conns.has(conn)) {\n const controlledIds: Set<number> = doc.conns.get(conn)!;\n doc.conns.delete(conn);\n awarenessProtocol.removeAwarenessStates(\n doc.awareness,\n Array.from(controlledIds),\n null\n );\n }\n try {\n conn.close();\n } catch (e) {\n console.warn(\"failed to close connection\", e);\n }\n}\n\nfunction send(doc: WSSharedDoc, conn: Connection, m: Uint8Array) {\n if (\n conn.readyState !== undefined &&\n conn.readyState !== wsReadyStateConnecting &&\n conn.readyState !== wsReadyStateOpen\n ) {\n closeConn(doc, conn);\n }\n try {\n conn.send(m);\n } catch (_e) {\n closeConn(doc, conn);\n }\n}\n\nexport interface CallbackOptions {\n debounceWait?: number;\n debounceMaxWait?: number;\n timeout?: number;\n}\n\nexport class YServer<\n Env extends Cloudflare.Env = Cloudflare.Env\n> extends Server<Env> {\n static callbackOptions: CallbackOptions = {};\n\n #ParentClass: typeof YServer = Object.getPrototypeOf(this).constructor;\n readonly document: WSSharedDoc = new WSSharedDoc();\n\n async onLoad(): Promise<void> {\n // to be implemented by the user\n return;\n }\n\n async onSave(): Promise<void> {\n // to be implemented by the user\n }\n\n /**\n * Replaces the document with a different state using Yjs UndoManager key remapping.\n *\n * @param snapshotUpdate - The snapshot update to replace the document with.\n * @param getMetadata (optional) - A function that returns the type of the root for a given key.\n */\n unstable_replaceDocument(\n snapshotUpdate: Uint8Array,\n getMetadata: (key: string) => YjsRootType = () => \"Map\"\n ): void {\n try {\n const doc = this.document;\n const snapshotDoc = new YDoc();\n applyUpdate(snapshotDoc, snapshotUpdate, snapshotOrigin);\n\n const currentStateVector = encodeStateVector(doc);\n const snapshotStateVector = encodeStateVector(snapshotDoc);\n\n const changesSinceSnapshotUpdate = encodeStateAsUpdate(\n doc,\n snapshotStateVector\n );\n\n const undoManager = new UndoManager(\n [...snapshotDoc.share.keys()].map((key) => {\n const type = getMetadata(key);\n if (type === \"Text\") {\n return snapshotDoc.getText(key);\n } else if (type === \"Map\") {\n return snapshotDoc.getMap(key);\n } else if (type === \"Array\") {\n return snapshotDoc.getArray(key);\n } else if (type === \"XmlText\") {\n return snapshotDoc.get(key, XmlText);\n } else if (type === \"XmlElement\") {\n return snapshotDoc.get(key, XmlElement);\n } else if (type === \"XmlFragment\") {\n return snapshotDoc.get(key, XmlFragment);\n }\n throw new Error(`Unknown root type: ${type} for key: ${key}`);\n }),\n {\n trackedOrigins: new Set([snapshotOrigin])\n }\n );\n\n applyUpdate(snapshotDoc, changesSinceSnapshotUpdate, snapshotOrigin);\n undoManager.undo();\n\n const documentChangesSinceSnapshotUpdate = encodeStateAsUpdate(\n snapshotDoc,\n currentStateVector\n );\n\n applyUpdate(this.document, documentChangesSinceSnapshotUpdate);\n } catch (error) {\n throw new Error(\n `Failed to replace document: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n }\n }\n\n async onStart(): Promise<void> {\n const src = await this.onLoad();\n if (src != null) {\n const state = encodeStateAsUpdate(src);\n applyUpdate(this.document, state);\n }\n\n this.document.on(\n \"update\",\n debounce(\n (_update: Uint8Array, _origin: Connection, _doc: YDoc) => {\n try {\n this.onSave().catch((err) => {\n console.error(\"failed to persist:\", err);\n });\n } catch (err) {\n console.error(\"failed to persist:\", err);\n }\n },\n this.#ParentClass.callbackOptions.debounceWait ||\n CALLBACK_DEFAULTS.debounceWait,\n {\n maxWait:\n this.#ParentClass.callbackOptions.debounceMaxWait ||\n CALLBACK_DEFAULTS.debounceMaxWait\n }\n )\n );\n }\n\n // biome-ignore lint/correctness/noUnusedFunctionParameters: so autocomplete works\n isReadOnly(connection: Connection): boolean {\n // to be implemented by the user\n return false;\n }\n\n /**\n * Handle custom string messages from the client.\n * Override this method to implement custom message handling.\n * @param connection - The connection that sent the message\n * @param message - The custom message string (without the __YPS: prefix)\n */\n // biome-ignore lint/correctness/noUnusedFunctionParameters: so autocomplete works\n onCustomMessage(connection: Connection, message: string): void {\n // to be implemented by the user\n console.warn(\n `Received custom message but onCustomMessage is not implemented in ${this.#ParentClass.name}:`,\n message\n );\n }\n\n /**\n * Send a custom string message to a specific connection.\n * @param connection - The connection to send the message to\n * @param message - The custom message string to send\n */\n sendCustomMessage(connection: Connection, message: string): void {\n if (\n connection.readyState !== undefined &&\n connection.readyState !== wsReadyStateConnecting &&\n connection.readyState !== wsReadyStateOpen\n ) {\n return;\n }\n try {\n connection.send(`__YPS:${message}`);\n } catch (e) {\n console.warn(\"Failed to send custom message\", e);\n }\n }\n\n /**\n * Broadcast a custom string message to all connected clients.\n * @param message - The custom message string to broadcast\n * @param excludeConnection - Optional connection to exclude from the broadcast\n */\n broadcastCustomMessage(\n message: string,\n excludeConnection?: Connection\n ): void {\n const formattedMessage = `__YPS:${message}`;\n this.document.conns.forEach((_, conn) => {\n if (excludeConnection && conn === excludeConnection) {\n return;\n }\n if (\n conn.readyState !== undefined &&\n conn.readyState !== wsReadyStateConnecting &&\n conn.readyState !== wsReadyStateOpen\n ) {\n return;\n }\n try {\n conn.send(formattedMessage);\n } catch (e) {\n console.warn(\"Failed to broadcast custom message\", e);\n }\n });\n }\n\n handleMessage(connection: Connection, message: WSMessage) {\n if (typeof message === \"string\") {\n // Handle custom messages with __YPS: prefix\n if (message.startsWith(\"__YPS:\")) {\n const customMessage = message.slice(6); // Remove __YPS: prefix\n this.onCustomMessage(connection, customMessage);\n return;\n }\n console.warn(\n `Received non-prefixed string message. Custom messages should be sent using sendMessage() on the provider.`\n );\n return;\n }\n try {\n const encoder = encoding.createEncoder();\n // Convert ArrayBuffer to Uint8Array if needed (ArrayBufferView like Uint8Array can be used directly)\n const uint8Array =\n message instanceof Uint8Array\n ? message\n : message instanceof ArrayBuffer\n ? new Uint8Array(message)\n : new Uint8Array(\n message.buffer,\n message.byteOffset,\n message.byteLength\n );\n const decoder = decoding.createDecoder(uint8Array);\n const messageType = decoding.readVarUint(decoder);\n switch (messageType) {\n case messageSync:\n encoding.writeVarUint(encoder, messageSync);\n readSyncMessage(\n decoder,\n encoder,\n this.document,\n connection,\n this.isReadOnly(connection)\n );\n\n // If the `encoder` only contains the type of reply message and no\n // message, there is no need to send the message. When `encoder` only\n // contains the type of reply, its length is 1.\n if (encoding.length(encoder) > 1) {\n send(this.document, connection, encoding.toUint8Array(encoder));\n }\n break;\n case messageAwareness: {\n awarenessProtocol.applyAwarenessUpdate(\n this.document.awareness,\n decoding.readVarUint8Array(decoder),\n connection\n );\n break;\n }\n }\n } catch (err) {\n console.error(err);\n // @ts-expect-error - TODO: fix this\n this.document.emit(\"error\", [err]);\n }\n }\n\n onMessage(conn: Connection, message: WSMessage) {\n this.handleMessage(conn, message);\n }\n\n onClose(\n connection: Connection<unknown>,\n _code: number,\n _reason: string,\n _wasClean: boolean\n ): void | Promise<void> {\n closeConn(this.document, connection);\n }\n\n // TODO: explore why onError gets triggered when a connection closes\n\n onConnect(\n conn: Connection<unknown>,\n _ctx: ConnectionContext\n ): void | Promise<void> {\n // conn.binaryType = \"arraybuffer\"; // from y-websocket, breaks in our runtime\n\n this.document.conns.set(conn, new Set());\n\n // send sync step 1\n const encoder = encoding.createEncoder();\n encoding.writeVarUint(encoder, messageSync);\n syncProtocol.writeSyncStep1(encoder, this.document);\n send(this.document, conn, encoding.toUint8Array(encoder));\n const awarenessStates = this.document.awareness.getStates();\n if (awarenessStates.size > 0) {\n const encoder = encoding.createEncoder();\n encoding.writeVarUint(encoder, messageAwareness);\n encoding.writeVarUint8Array(\n encoder,\n awarenessProtocol.encodeAwarenessUpdate(\n this.document.awareness,\n Array.from(awarenessStates.keys())\n )\n );\n send(this.document, conn, encoding.toUint8Array(encoder));\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAIA,IAAI,EAAE,UAAU,YAAY;CAC3B,MAAM,kBAAkB;EACvB,YAAY,UAAU;EACtB,MAAM,UAAU;EAChB,SAAS,UAAU;EACnB,QAAQ,UAAU;EAClB;AACD,QAAO,OAAO,WAAW,gBAAgB;AACzC,QAAO,OAAO,UAAU,WAAW,gBAAgB;;AAEpD,SAAS,sBAAsB,IAAI;AAClC,KAAI;EACH,MAAM,aAAa,UAAU,UAAU,sBAAsB,KAAK,GAAG;AACrE,MAAI,CAAC,cAAc,OAAO,eAAe,SAAU,QAAO;AAC1D,MAAI,EA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,MAAM,kBAAkB,KAAK,SAAS,UAAU,WAAW;AAC3D,MAAI,gBAAgB,OAAO,GAAG;GAC5B,MAAMC,YAAU,SAAS,eAAe;AACxC,YAAS,aAAaA,WAAS,iBAAiB;AAChD,YAAS,mBACPA,WACA,kBAAkB,sBAChB,KAAK,SAAS,WACd,MAAM,KAAK,gBAAgB,MAAM,CAAC,CACnC,CACF;AACD,QAAK,KAAK,UAAU,MAAM,SAAS,aAAaA,UAAQ,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["YDoc"],"sources":["../../src/server/index.ts"],"sourcesContent":["import * as decoding from \"lib0/decoding\";\nimport * as encoding from \"lib0/encoding\";\nimport debounce from \"lodash.debounce\";\nimport type { Connection, ConnectionContext, WSMessage } from \"partyserver\";\nimport { Server } from \"partyserver\";\nimport * as awarenessProtocol from \"y-protocols/awareness\";\nimport * as syncProtocol from \"y-protocols/sync\";\nimport {\n applyUpdate,\n Doc as YDoc,\n encodeStateAsUpdate,\n encodeStateVector,\n UndoManager,\n XmlText,\n XmlElement,\n XmlFragment\n} from \"yjs\";\n\nconst snapshotOrigin = Symbol(\"snapshot-origin\");\ntype YjsRootType =\n | \"Text\"\n | \"Map\"\n | \"Array\"\n | \"XmlText\"\n | \"XmlElement\"\n | \"XmlFragment\";\n\nconst wsReadyStateConnecting = 0;\nconst wsReadyStateOpen = 1;\n// oxlint-disable-next-line no-unused-vars\nconst wsReadyStateClosing = 2;\n// oxlint-disable-next-line no-unused-vars\nconst wsReadyStateClosed = 3;\n\nconst messageSync = 0;\nconst messageAwareness = 1;\n// oxlint-disable-next-line no-unused-vars\nconst messageAuth = 2;\n\n/**\n * Internal key used in connection.setState() to track which awareness\n * client IDs are controlled by each connection. This survives hibernation\n * because connection state is persisted to WebSocket attachments.\n */\nconst AWARENESS_IDS_KEY = \"__ypsAwarenessIds\";\n\ntype YServerConnectionState = {\n [AWARENESS_IDS_KEY]?: number[];\n [key: string]: unknown;\n};\n\nfunction getAwarenessIds(conn: Connection): number[] {\n try {\n const state = conn.state as YServerConnectionState | null;\n return state?.[AWARENESS_IDS_KEY] ?? [];\n } catch {\n return [];\n }\n}\n\nfunction setAwarenessIds(conn: Connection, ids: number[]): void {\n try {\n conn.setState((prev: YServerConnectionState | null) => ({\n ...prev,\n [AWARENESS_IDS_KEY]: ids\n }));\n } catch {\n // ignore — may fail if connection is already closed\n }\n}\n\nclass WSSharedDoc extends YDoc {\n awareness: awarenessProtocol.Awareness;\n\n constructor() {\n super({ gc: true });\n this.awareness = new awarenessProtocol.Awareness(this);\n this.awareness.setLocalState(null);\n\n // Disable the awareness protocol's built-in check interval.\n // It renews the local clock every 15s and removes peers after 30s,\n // but we handle peer cleanup via onClose instead. Clearing it here\n // prevents it from defeating Durable Object hibernation.\n clearInterval(\n (\n this.awareness as unknown as {\n _checkInterval: ReturnType<typeof setInterval>;\n }\n )._checkInterval\n );\n }\n}\n\nconst CALLBACK_DEFAULTS = {\n debounceWait: 2000,\n debounceMaxWait: 10000,\n timeout: 5000\n};\n\nfunction readSyncMessage(\n decoder: decoding.Decoder,\n encoder: encoding.Encoder,\n doc: YDoc,\n transactionOrigin: Connection,\n readOnly = false\n) {\n const messageType = decoding.readVarUint(decoder);\n switch (messageType) {\n case syncProtocol.messageYjsSyncStep1:\n syncProtocol.readSyncStep1(decoder, encoder, doc);\n break;\n case syncProtocol.messageYjsSyncStep2:\n if (!readOnly)\n syncProtocol.readSyncStep2(decoder, doc, transactionOrigin);\n break;\n case syncProtocol.messageYjsUpdate:\n if (!readOnly) syncProtocol.readUpdate(decoder, doc, transactionOrigin);\n break;\n default:\n throw new Error(\"Unknown message type\");\n }\n return messageType;\n}\n\nfunction send(conn: Connection, m: Uint8Array): void {\n if (\n conn.readyState !== undefined &&\n conn.readyState !== wsReadyStateConnecting &&\n conn.readyState !== wsReadyStateOpen\n ) {\n return;\n }\n try {\n conn.send(m);\n } catch {\n // connection is broken, ignore\n }\n}\n\nexport interface CallbackOptions {\n debounceWait?: number;\n debounceMaxWait?: number;\n timeout?: number;\n}\n\ntype ServerClass = new (...args: any[]) => Server;\n\nexport interface YjsInstance {\n readonly document: WSSharedDoc;\n onLoad(): Promise<YDoc | void>;\n onSave(): Promise<void>;\n unstable_replaceDocument(\n snapshotUpdate: Uint8Array,\n getMetadata?: (key: string) => YjsRootType\n ): void;\n isReadOnly(connection: Connection): boolean;\n onCustomMessage(connection: Connection, message: string): void;\n sendCustomMessage(connection: Connection, message: string): void;\n broadcastCustomMessage(message: string, excludeConnection?: Connection): void;\n handleMessage(connection: Connection, message: WSMessage): void;\n}\n\nexport interface YjsStatic {\n callbackOptions: CallbackOptions;\n}\n\nexport function withYjs<TBase extends ServerClass>(\n Base: TBase\n): TBase & YjsStatic & (new (...args: any[]) => YjsInstance) {\n class YjsMixin extends Base {\n static callbackOptions: CallbackOptions = {};\n\n readonly document: WSSharedDoc = new WSSharedDoc();\n\n async onLoad(): Promise<YDoc | void> {\n // to be implemented by the user\n return;\n }\n\n async onSave(): Promise<void> {\n // to be implemented by the user\n }\n\n /**\n * Replaces the document with a different state using Yjs UndoManager key remapping.\n *\n * @param snapshotUpdate - The snapshot update to replace the document with.\n * @param getMetadata (optional) - A function that returns the type of the root for a given key.\n */\n unstable_replaceDocument(\n snapshotUpdate: Uint8Array,\n getMetadata: (key: string) => YjsRootType = () => \"Map\"\n ): void {\n try {\n const doc = this.document;\n const snapshotDoc = new YDoc();\n applyUpdate(snapshotDoc, snapshotUpdate, snapshotOrigin);\n\n const currentStateVector = encodeStateVector(doc);\n const snapshotStateVector = encodeStateVector(snapshotDoc);\n\n const changesSinceSnapshotUpdate = encodeStateAsUpdate(\n doc,\n snapshotStateVector\n );\n\n const undoManager = new UndoManager(\n [...snapshotDoc.share.keys()].map((key) => {\n const type = getMetadata(key);\n if (type === \"Text\") {\n return snapshotDoc.getText(key);\n } else if (type === \"Map\") {\n return snapshotDoc.getMap(key);\n } else if (type === \"Array\") {\n return snapshotDoc.getArray(key);\n } else if (type === \"XmlText\") {\n return snapshotDoc.get(key, XmlText);\n } else if (type === \"XmlElement\") {\n return snapshotDoc.get(key, XmlElement);\n } else if (type === \"XmlFragment\") {\n return snapshotDoc.get(key, XmlFragment);\n }\n throw new Error(`Unknown root type: ${type} for key: ${key}`);\n }),\n {\n trackedOrigins: new Set([snapshotOrigin])\n }\n );\n\n applyUpdate(snapshotDoc, changesSinceSnapshotUpdate, snapshotOrigin);\n undoManager.undo();\n\n const documentChangesSinceSnapshotUpdate = encodeStateAsUpdate(\n snapshotDoc,\n currentStateVector\n );\n\n applyUpdate(this.document, documentChangesSinceSnapshotUpdate);\n } catch (error) {\n throw new Error(\n `Failed to replace document: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n }\n }\n\n async onStart(): Promise<void> {\n const src = await this.onLoad();\n if (src != null) {\n const state = encodeStateAsUpdate(src);\n applyUpdate(this.document, state);\n }\n\n // Broadcast doc updates to all connections.\n // Uses this.getConnections() which works for both hibernate and non-hibernate\n // modes and survives DO hibernation (unlike an in-memory Map).\n this.document.on(\"update\", (update: Uint8Array) => {\n const encoder = encoding.createEncoder();\n encoding.writeVarUint(encoder, messageSync);\n syncProtocol.writeUpdate(encoder, update);\n const message = encoding.toUint8Array(encoder);\n for (const conn of this.getConnections()) {\n send(conn, message);\n }\n });\n\n // Track which awareness clientIDs each connection controls.\n // Stored in connection.setState() so it survives hibernation.\n // When conn is null (internal changes like removeAwarenessStates on close),\n // broadcast the update to remaining connections.\n // When conn is non-null (client message), handleMessage broadcasts directly.\n this.document.awareness.on(\n \"update\",\n (\n {\n added,\n updated,\n removed\n }: {\n added: Array<number>;\n updated: Array<number>;\n removed: Array<number>;\n },\n conn: Connection | null\n ) => {\n if (conn !== null) {\n // Track which clientIDs this connection controls\n try {\n const currentIds = new Set(getAwarenessIds(conn));\n for (const clientID of added) currentIds.add(clientID);\n for (const clientID of removed) currentIds.delete(clientID);\n setAwarenessIds(conn, [...currentIds]);\n } catch (_e) {\n // ignore — best-effort tracking\n }\n } else {\n // Internal awareness change (e.g. removeAwarenessStates on close)\n // — broadcast to all remaining connections\n const changedClients = added.concat(updated, removed);\n const encoder = encoding.createEncoder();\n encoding.writeVarUint(encoder, messageAwareness);\n encoding.writeVarUint8Array(\n encoder,\n awarenessProtocol.encodeAwarenessUpdate(\n this.document.awareness,\n changedClients\n )\n );\n const buff = encoding.toUint8Array(encoder);\n for (const c of this.getConnections()) {\n send(c, buff);\n }\n }\n }\n );\n\n // Debounced persistence handler\n const ctor = this.constructor as typeof YjsMixin;\n this.document.on(\n \"update\",\n debounce(\n (_update: Uint8Array, _origin: Connection, _doc: YDoc) => {\n try {\n this.onSave().catch((err) => {\n console.error(\"failed to persist:\", err);\n });\n } catch (err) {\n console.error(\"failed to persist:\", err);\n }\n },\n ctor.callbackOptions.debounceWait || CALLBACK_DEFAULTS.debounceWait,\n {\n maxWait:\n ctor.callbackOptions.debounceMaxWait ||\n CALLBACK_DEFAULTS.debounceMaxWait\n }\n )\n );\n\n // After hibernation wake-up, the doc is empty but existing connections\n // survive. Re-sync by sending sync step 1 to all connections — they'll\n // respond with sync step 2 containing their full state.\n // On first start there are no connections, so this is a no-op.\n const syncEncoder = encoding.createEncoder();\n encoding.writeVarUint(syncEncoder, messageSync);\n syncProtocol.writeSyncStep1(syncEncoder, this.document);\n const syncMessage = encoding.toUint8Array(syncEncoder);\n for (const conn of this.getConnections()) {\n send(conn, syncMessage);\n }\n }\n\n // oxlint-disable-next-line no-unused-vars\n isReadOnly(connection: Connection): boolean {\n // to be implemented by the user\n return false;\n }\n\n /**\n * Handle custom string messages from the client.\n * Override this method to implement custom message handling.\n * @param connection - The connection that sent the message\n * @param message - The custom message string (without the __YPS: prefix)\n */\n // oxlint-disable-next-line no-unused-vars\n onCustomMessage(connection: Connection, message: string): void {\n // to be implemented by the user\n console.warn(\n `Received custom message but onCustomMessage is not implemented in ${this.constructor.name}:`,\n message\n );\n }\n\n /**\n * Send a custom string message to a specific connection.\n * @param connection - The connection to send the message to\n * @param message - The custom message string to send\n */\n sendCustomMessage(connection: Connection, message: string): void {\n if (\n connection.readyState !== undefined &&\n connection.readyState !== wsReadyStateConnecting &&\n connection.readyState !== wsReadyStateOpen\n ) {\n return;\n }\n try {\n connection.send(`__YPS:${message}`);\n } catch (e) {\n console.warn(\"Failed to send custom message\", e);\n }\n }\n\n /**\n * Broadcast a custom string message to all connected clients.\n * @param message - The custom message string to broadcast\n * @param excludeConnection - Optional connection to exclude from the broadcast\n */\n broadcastCustomMessage(\n message: string,\n excludeConnection?: Connection\n ): void {\n const formattedMessage = `__YPS:${message}`;\n for (const conn of this.getConnections()) {\n if (excludeConnection && conn === excludeConnection) {\n continue;\n }\n if (\n conn.readyState !== undefined &&\n conn.readyState !== wsReadyStateConnecting &&\n conn.readyState !== wsReadyStateOpen\n ) {\n continue;\n }\n try {\n conn.send(formattedMessage);\n } catch (e) {\n console.warn(\"Failed to broadcast custom message\", e);\n }\n }\n }\n\n handleMessage(connection: Connection, message: WSMessage) {\n if (typeof message === \"string\") {\n // Handle custom messages with __YPS: prefix\n if (message.startsWith(\"__YPS:\")) {\n const customMessage = message.slice(6); // Remove __YPS: prefix\n this.onCustomMessage(connection, customMessage);\n return;\n }\n console.warn(\n `Received non-prefixed string message. Custom messages should be sent using sendMessage() on the provider.`\n );\n return;\n }\n try {\n const encoder = encoding.createEncoder();\n // Convert ArrayBuffer to Uint8Array if needed (ArrayBufferView like Uint8Array can be used directly)\n const uint8Array =\n message instanceof Uint8Array\n ? message\n : message instanceof ArrayBuffer\n ? new Uint8Array(message)\n : new Uint8Array(\n message.buffer,\n message.byteOffset,\n message.byteLength\n );\n const decoder = decoding.createDecoder(uint8Array);\n const messageType = decoding.readVarUint(decoder);\n switch (messageType) {\n case messageSync:\n encoding.writeVarUint(encoder, messageSync);\n readSyncMessage(\n decoder,\n encoder,\n this.document,\n connection,\n this.isReadOnly(connection)\n );\n\n // If the `encoder` only contains the type of reply message and no\n // message, there is no need to send the message. When `encoder` only\n // contains the type of reply, its length is 1.\n if (encoding.length(encoder) > 1) {\n send(connection, encoding.toUint8Array(encoder));\n }\n break;\n case messageAwareness: {\n const awarenessData = decoding.readVarUint8Array(decoder);\n awarenessProtocol.applyAwarenessUpdate(\n this.document.awareness,\n awarenessData,\n connection\n );\n // Forward raw awareness bytes to all connections\n const awarenessEncoder = encoding.createEncoder();\n encoding.writeVarUint(awarenessEncoder, messageAwareness);\n encoding.writeVarUint8Array(awarenessEncoder, awarenessData);\n const awarenessBuff = encoding.toUint8Array(awarenessEncoder);\n for (const c of this.getConnections()) {\n send(c, awarenessBuff);\n }\n break;\n }\n }\n } catch (err) {\n console.error(err);\n // @ts-expect-error - TODO: fix this\n this.document.emit(\"error\", [err]);\n }\n }\n\n onMessage(conn: Connection, message: WSMessage) {\n this.handleMessage(conn, message);\n }\n\n onClose(\n connection: Connection<unknown>,\n _code: number,\n _reason: string,\n _wasClean: boolean\n ): void | Promise<void> {\n // Read controlled awareness clientIDs from connection state\n // (survives hibernation unlike an in-memory Map)\n const controlledIds = getAwarenessIds(connection);\n if (controlledIds.length > 0) {\n awarenessProtocol.removeAwarenessStates(\n this.document.awareness,\n controlledIds,\n null\n );\n }\n }\n\n // TODO: explore why onError gets triggered when a connection closes\n\n onConnect(\n conn: Connection<unknown>,\n _ctx: ConnectionContext\n ): void | Promise<void> {\n // Note: awareness IDs are lazily initialized when the first awareness\n // message is received — no need to call setAwarenessIds(conn, []) here\n\n // send sync step 1\n const encoder = encoding.createEncoder();\n encoding.writeVarUint(encoder, messageSync);\n syncProtocol.writeSyncStep1(encoder, this.document);\n send(conn, encoding.toUint8Array(encoder));\n const awarenessStates = this.document.awareness.getStates();\n if (awarenessStates.size > 0) {\n const encoder = encoding.createEncoder();\n encoding.writeVarUint(encoder, messageAwareness);\n encoding.writeVarUint8Array(\n encoder,\n awarenessProtocol.encodeAwarenessUpdate(\n this.document.awareness,\n Array.from(awarenessStates.keys())\n )\n );\n send(conn, encoding.toUint8Array(encoder));\n }\n }\n }\n\n return YjsMixin as unknown as TBase &\n YjsStatic &\n (new (...args: any[]) => YjsInstance);\n}\n\nexport const YServer = withYjs(Server);\n"],"mappings":";;;;;;;;;AAkBA,MAAM,iBAAiB,OAAO,kBAAkB;AAShD,MAAM,yBAAyB;AAC/B,MAAM,mBAAmB;AAMzB,MAAM,cAAc;AACpB,MAAM,mBAAmB;;;;;;AASzB,MAAM,oBAAoB;AAO1B,SAAS,gBAAgB,MAA4B;AACnD,KAAI;AAEF,SADc,KAAK,QACJ,sBAAsB,EAAE;SACjC;AACN,SAAO,EAAE;;;AAIb,SAAS,gBAAgB,MAAkB,KAAqB;AAC9D,KAAI;AACF,OAAK,UAAU,UAAyC;GACtD,GAAG;IACF,oBAAoB;GACtB,EAAE;SACG;;AAKV,IAAM,cAAN,cAA0BA,IAAK;CAC7B;CAEA,cAAc;AACZ,QAAM,EAAE,IAAI,MAAM,CAAC;AACnB,OAAK,YAAY,IAAI,kBAAkB,UAAU,KAAK;AACtD,OAAK,UAAU,cAAc,KAAK;AAMlC,gBAEI,KAAK,UAGL,eACH;;;AAIL,MAAM,oBAAoB;CACxB,cAAc;CACd,iBAAiB;CACjB,SAAS;CACV;AAED,SAAS,gBACP,SACA,SACA,KACA,mBACA,WAAW,OACX;CACA,MAAM,cAAc,SAAS,YAAY,QAAQ;AACjD,SAAQ,aAAR;EACE,KAAK,aAAa;AAChB,gBAAa,cAAc,SAAS,SAAS,IAAI;AACjD;EACF,KAAK,aAAa;AAChB,OAAI,CAAC,SACH,cAAa,cAAc,SAAS,KAAK,kBAAkB;AAC7D;EACF,KAAK,aAAa;AAChB,OAAI,CAAC,SAAU,cAAa,WAAW,SAAS,KAAK,kBAAkB;AACvE;EACF,QACE,OAAM,IAAI,MAAM,uBAAuB;;AAE3C,QAAO;;AAGT,SAAS,KAAK,MAAkB,GAAqB;AACnD,KACE,KAAK,eAAe,UACpB,KAAK,eAAe,0BACpB,KAAK,eAAe,iBAEpB;AAEF,KAAI;AACF,OAAK,KAAK,EAAE;SACN;;A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Aa,UAAU,QAAQ,OAAO"}
|
package/package.json
CHANGED
|
@@ -1,11 +1,23 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "y-partyserver",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.1.1",
|
|
4
|
+
"description": "",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"collaboration",
|
|
7
|
+
"text-editors",
|
|
8
|
+
"yjs"
|
|
9
|
+
],
|
|
10
|
+
"homepage": "https://github.com/cloudflare/partykit/tree/main/packages/y-partyserver",
|
|
11
|
+
"license": "ISC",
|
|
12
|
+
"author": "Sunil Pai <spai@cloudflare.com>",
|
|
4
13
|
"repository": {
|
|
5
14
|
"type": "git",
|
|
6
15
|
"url": "git://github.com/cloudflare/partykit.git"
|
|
7
16
|
},
|
|
8
|
-
"
|
|
17
|
+
"files": [
|
|
18
|
+
"dist",
|
|
19
|
+
"README.md"
|
|
20
|
+
],
|
|
9
21
|
"type": "module",
|
|
10
22
|
"exports": {
|
|
11
23
|
".": {
|
|
@@ -25,36 +37,28 @@
|
|
|
25
37
|
}
|
|
26
38
|
},
|
|
27
39
|
"scripts": {
|
|
28
|
-
"build": "tsx scripts/build.ts"
|
|
40
|
+
"build": "tsx scripts/build.ts",
|
|
41
|
+
"check:test": "vitest -r src/tests --watch false",
|
|
42
|
+
"test": "vitest -r src/tests",
|
|
43
|
+
"test:integration": "vitest -r src/tests --config vitest.integration.config.ts --watch false",
|
|
44
|
+
"test:hibernation": "vitest -r src/tests --config vitest.hibernation.config.ts --watch false"
|
|
29
45
|
},
|
|
30
|
-
"files": [
|
|
31
|
-
"dist",
|
|
32
|
-
"README.md"
|
|
33
|
-
],
|
|
34
|
-
"keywords": [
|
|
35
|
-
"yjs",
|
|
36
|
-
"collaboration",
|
|
37
|
-
"text-editors"
|
|
38
|
-
],
|
|
39
|
-
"author": "Sunil Pai <spai@cloudflare.com>",
|
|
40
|
-
"license": "ISC",
|
|
41
|
-
"description": "",
|
|
42
46
|
"dependencies": {
|
|
43
|
-
"lib0": "^0.2.
|
|
47
|
+
"lib0": "^0.2.117",
|
|
44
48
|
"lodash.debounce": "^4.0.8",
|
|
45
49
|
"nanoid": "^5.1.6",
|
|
46
50
|
"y-protocols": "^1.0.7"
|
|
47
51
|
},
|
|
52
|
+
"devDependencies": {
|
|
53
|
+
"@cloudflare/workers-types": "^4.20260303.0",
|
|
54
|
+
"@types/lodash.debounce": "^4.0.9",
|
|
55
|
+
"partyserver": "^0.3.1",
|
|
56
|
+
"ws": "^8.19.0",
|
|
57
|
+
"yjs": "^13.6.29"
|
|
58
|
+
},
|
|
48
59
|
"peerDependencies": {
|
|
49
60
|
"@cloudflare/workers-types": "^4.20240729.0",
|
|
50
|
-
"partyserver": "
|
|
61
|
+
"partyserver": ">=0.2.0 <1.0.0",
|
|
51
62
|
"yjs": "^13.6.14"
|
|
52
|
-
},
|
|
53
|
-
"devDependencies": {
|
|
54
|
-
"@cloudflare/workers-types": "^4.20251218.0",
|
|
55
|
-
"@types/lodash.debounce": "^4.0.9",
|
|
56
|
-
"partyserver": "^0.2.0",
|
|
57
|
-
"ws": "^8.18.3",
|
|
58
|
-
"yjs": "^13.6.28"
|
|
59
63
|
}
|
|
60
64
|
}
|