@ably/spaces

中文文档
0.6.0发布于 2026/11/02ISCTypeScriptESM + CJS构建来源已验证近 30 天下载 11.8万

The Spaces SDK contains a purpose built set of APIs that help you build collaborative environments for your apps to quickly enable remote team collaboration. Try out a live demo of a slideshow application for an example of re

原始使用文档
文档目录20 节
  1. Realtime collaboration
  2. Who is in the application?
  3. Where is each user within the application?
  4. What is everyone doing in the application?
  5. SDK Development Status
  6. Prerequisites
  7. Installation and authentication
  8. Spaces for React Developers
  9. Creating a new Space
  10. Space members
  11. Getting a snapshot of space members
  12. Member locations
  13. Getting a snapshot of member locations
  14. Live cursors
  15. Getting a snapshot of member cursors
  16. Component Locking
  17. Query
  18. Acquire
  19. Release
  20. Subscribe

Ably Spaces SDK

The Spaces SDK contains a purpose built set of APIs that help you build collaborative environments for your apps to quickly enable remote team collaboration. Try out a live demo of a slideshow application for an example of realtime collaboration powered by the Spaces SDK.

Example collaboration GIF

Development status CI status License

Ably is the scalable and five nines reliable middleware, used by developers at over 500 companies worldwide, to quickly build realtime applications - from collaborative experiences and live chat, to data broadcast and notifications. Supported by its globally distributed infrastructure, Ably offers 25 SDKs for various programming languages and platforms, as well as partner integrations with technologies including Datadog, Kafka, and Vercel, that accelerate the delivery of realtime experiences.


Realtime collaboration

Rather than having to coordinate resources on calls, or send documents and spreadsheets back and forth using a combination of tools, having in-app realtime collaboration features has proven to boost productivity in remote workplaces. Such features enable end users to have contextual awareness of other users within an application. This means knowing:

Who is in the application?

One of the most important aspects of collaboration is knowing who else you're working with. The most common way to display this is using an "Avatar Stack" to show who else is currently online, and those that have recently gone offline.

Where is each user within the application?

Knowing where each user is within an application helps you understand their intentions without having to explicitly ask them. For example, seeing that a colleague is currently viewing slide 2 of a presentation deck means that you can carry out your own edits to slide 3 without interfering with their work. Displaying the locations of your users can be achieved by highlighting the UI element they have selected, displaying a miniature avatar stack on the slide they are viewing, or showing the live location of their cursors. In Spaces, we call this "Member Location".

What is everyone doing in the application?

Changes to the app state made by users not only need to be synced with your backend for validation and long term storage, but also be immediately reflected in the UI so that users are always viewing the latest information. For example, in a spreadsheet application, if one user has entered a value in a cell, all other users need to see that change instantly. Pub/Sub Channels help flexibly broadcast live updates in a collaborative space.

SDK Development Status

The Spaces SDK is currently under development. If you are interested in being an early adopter and providing feedback then you can sign up for early access and are welcome to provide us with feedback.

The next section gives you an overview of how to use the SDK. Alternatively, you can jump to:

Prerequisites

To start using this SDK, you will need the following:

  • An Ably account
    • You can sign up to the generous free tier.
  • An Ably API key
    • Use the default or create a new API key in an app within your Ably account dashboard.
    • Make sure your API key has the following capabilities: publish, subscribe, presence and history.

Installation and authentication

Upgrading from an earlier version? See the upgrade guide.

Option 1: Using NPM

Install the Ably Pub/Sub SDK and the Spaces SDK:

npm install @ably/pubsub-device @ably/spaces

To instantiate the Spaces SDK, create an Ably client and pass it to createSpacesClient():

import { createSpacesClient } from '@ably/spaces';
import { createClient } from '@ably/pubsub-device';

const client = createClient({ key: "<API-key>", clientId: "<client-ID>" });
const spaces = createSpacesClient(client);

You can use basic authentication i.e. the API Key directly for testing purposes, however it is strongly recommended that you use token authentication in production environments.

To use Spaces you must also set a clientId so that clients are identifiable. If you are prototyping, you can use a package like nanoid to generate an ID.

Option 2: Using a CDN

You can also use Spaces with a CDN, such as unpkg:

<script src="https://cdn.ably.com/lib/ably.min-3.js"></script>
<script src="https://cdn.ably.com/spaces/0.6.0/iife/index.bundle.js"></script>

After this, instantiate the SDK in the same way as in the NPM option above:

const client = AblyPubSub.createClient({ key: "<API-key>", clientId: "<client-ID>" });
const spaces = AblySpaces.createSpacesClient(client);

Spaces for React Developers

A set of React Hooks are available which make it seamless to use Spaces in any React application. See the React Hooks documentation for further details.

Creating a new Space

A space is the virtual area of your application where you want to enable synchronous collaboration. A space can be anything from a web page, a sheet within a spreadsheet, an individual slide in a slideshow, or the slideshow itself. A space has a participant state containing online and recently left members, their profile details, their locations and any locks they have acquired for the UI components.

Create a space and subscribe to any updates to the participant state.

// Create a new space
const space = await spaces.get('demoSlideshow');

// Subscribe to space state events
space.subscribe('update', (spaceState) => {
  console.log(spaceState.members);
});

// Enter a space, publishing an update event, including optional profile data
await space.enter({
  username: 'Claire Lemons',
  avatar: 'https://slides-internal.com/users/clemons.png',
});

The following is an example event payload received by subscribers when a user enters a space:

[
  {
    "clientId": "clemons#142",
    "connectionId": "hd9743gjDc",
    "isConnected": true,
    "lastEvent": {
      "name": "enter",
      "timestamp": 1677595689759
    },
    "location": null,
    "profileData": {
      "username": "Claire Lemons",
      "avatar": "https://slides-internal.com/users/clemons.png"
    }
  }
]

Space members

The members namespace contains methods dedicated to building avatar stacks. Subscribe to members entering, leaving, being removed from the Space (after a timeout) or updating their profile information.

// Subscribe to all member events in a space
space.members.subscribe((memberUpdate) => {
  console.log(memberUpdate);
});

// Subscribe to member enter events only
space.members.subscribe('enter', (memberJoined) => {
  console.log(memberJoined);
});

// Subscribe to member leave events only
space.members.subscribe('leave', (memberLeft) => {
  console.log(memberLeft);
});

// Subscribe to member remove events only
space.members.subscribe('remove', (memberRemoved) => {
  console.log(memberRemoved);
});

// Subscribe to profile updates on members only
space.members.subscribe('updateProfile', (memberProfileUpdated) => {
  console.log(memberProfileUpdated);
});

// Subscribe to all updates to members
space.members.subscribe('update', (memberUpdate) => {
  console.log(memberUpdate);
});

The following is an example event payload received by subscribers when member updates occur in a space:

{
  "clientId": "clemons#142",
  "connectionId": "hd9743gjDc",
  "isConnected": true,
  "lastEvent": {
    "name": "enter",
    "timestamp": 1677595689759
  },
  "location": null,
  "profileData": {
    "username": "Claire Lemons",
    "avatar": "https://slides-internal.com/users/clemons.png"
  }
}

Getting a snapshot of space members

Space members has methods to get the current snapshot of member state:

// Get all members in a space
const allMembers = await space.members.getAll();

// Get your own member object
const myMemberInfo = await space.members.getSelf();

// Get everyone else's member object but yourself
const othersMemberInfo = await space.members.getOthers();

Member locations

The locations namespace contains methods dedicated to building member locations, enabling you to track where users are within an application. A location could be a form field, multiple cells in a spreadsheet or a slide in a slide deck editor.

// You need to enter a space before publishing your location
await space.enter({
  username: 'Claire Lemons',
  avatar: 'https://slides-internal.com/users/clemons.png',
});

// Publish your location based on the UI element selected
await space.locations.set({ slide: '3', component: 'slide-title' });

// Subscribe to location events from all members in a space
space.locations.subscribe('update', (locationUpdate) => {
  console.log(locationUpdate);
});

The following is an example event payload received by subscribers when a member changes location:

{
  "member": {
    "clientId": "clemons#142",
    "connectionId": "hd9743gjDc",
    "isConnected": true,
    "profileData": {
      "username": "Claire Lemons",
      "avatar": "https://slides-internal.com/users/clemons.png"
    },
    "location": {
      "slide": "3",
      "component": "slide-title"
    },
    "lastEvent": {
      "name": "update",
      "timestamp": 1
    }
  },
  "previousLocation": {
    "slide": "2",
    "component": null
  },
  "currentLocation": {
    "slide": "3",
    "component": "slide-title"
  }
}

Getting a snapshot of member locations

Member locations has methods to get the current snapshot of member state:

// Get a snapshot of all the member locations
const allLocations = await space.locations.getAll();

// Get a snapshot of my location
const myLocation = await space.locations.getSelf();

// Get a snapshot of everyone else's locations
const othersLocations = await space.locations.getOthers();

Live cursors

The cursors namespace contains methods dedicated to building live cursors, allowing you to track a member's pointer position updates across an application. Events can also include associated data, such as pointer attributes and the IDs of associated UI elements:

// You need to enter a space before publishing your cursor updates
await space.enter({
  username: 'Claire Lemons',
  avatar: 'https://slides-internal.com/users/clemons.png',
});

// Subscribe to events published on "mousemove" by all members
space.cursors.subscribe('update', (cursorUpdate) => {
  console.log(cursorUpdate);
});

// Publish a your cursor position on "mousemove" including optional data
window.addEventListener('mousemove', ({ clientX, clientY }) => {
  space.cursors.set({ position: { x: clientX, y: clientY }, data: { color: 'red' } });
});

The following is an example event payload received by subscribers when a member moves their cursor:

{
  "connectionId": "hd9743gjDc",
  "clientId": "clemons#142",
  "position": { "x": 864, "y": 32 },
  "data": { "color": "red" }
}

Getting a snapshot of member cursors

Member cursors has methods to get the current snapshot of member state:

// Get a snapshot of all the cursors
const allCursors = await space.cursors.getAll();

// Get a snapshot of my cursor
const myCursor = await space.cursors.getSelf();

// Get a snapshot of everyone else's cursors
const othersCursors = await space.cursors.getOthers();

Component Locking

Use the Component Locking API to lock stateful components whilst being edited by members to reduce the chances of conflicting changes being made.

Locks are identified using a unique string, and the Spaces SDK maintains that at most one member holds a lock with a given string at any given time.

The Component Locking API supports four operations: Query, Acquire, Release, and Subscribe.

Query

space.locks.get is used to query whether a lock identifier is currently locked and by whom. It returns a Lock type which has the following fields:

type Lock = {
  id: string;
  status: LockStatus;
  member: SpaceMember;
  timestamp: number;
  attributes?: LockAttributes;
  reason?: Types.ErrorInfo;
};

For example:

// check if the id is locked
const isLocked = space.locks.get(id) !== undefined;

// check which member has the lock
const { member } = space.locks.get(id);

// check the lock attributes assigned by the member holding the lock
const { attributes } = space.locks.get(id);
const value = attributes.get(key);

space.locks.getAll returns all lock identifiers which are currently locked as an array of Lock:

const allLocks = space.locks.getAll();

for (const lock of allLocks) {
  // ...
}

Acquire

space.locks.acquire sends a request to acquire a lock using presence.

It returns a Promise which resolves once the presence request has been sent.

const req = await space.locks.acquire(id);

// or with some attributes
const attributes = new Map();
attributes.set('key', 'value');
const req = await space.locks.acquire(id, { attributes });

It throws an error if a lock request already exists for the given identifier with a status of pending or locked.

Release

space.locks.release releases a previously requested lock by removing it from presence.

It returns a Promise which resolves once the presence request has been sent.

await space.locks.release(id);

Subscribe

space.locks.subscribe subscribes to changes in lock status across all members.

The callback is called with a value of type Lock.

space.locks.subscribe('update', (lock) => {
  // lock.member is the requesting member
  // lock.request is the request made by the member
});

// or with destructuring:
space.locks.subscribe('update', ({ member, request }) => {
  // request.status is the status of the request, one of PENDING, LOCKED, or UNLOCKED
  // request.reason is an ErrorInfo if the status is UNLOCKED
});

Such changes occur when:

  • a pending request transitions to locked because the requesting member now holds the lock
  • a pending request transitions to unlocked because the requesting member does not hold the lock since another member already does
  • a locked request transitions to unlocked because the lock was either released or invalidated by a concurrent request which took precedence
  • an unlocked request transitions to locked because the requesting member reacquired a lock

版本与发布记录

@ably/spaces 共发布 11 个版本,首次发布于 2023/09/05;过去 12 个月发布了 3 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.6.0latest2026/11/023 天前
0.0.0-canary.20261001T1221.ca08adcecanary2026/10/011 个月前
0.5.22025/12/2910 个月前
0.4.02024/07/182 年前
0.3.12024/05/032 年前
0.3.02023/11/092 年前

关于 @ably/spaces 的常见问题

@ably/spaces 是什么?

The Spaces SDK contains a purpose built set of APIs that help you build collaborative environments for your apps to quickly enable remote team collaboration. Try out a live demo of a slideshow application for an example of re

如何安装 @ably/spaces?

在项目目录运行 npm install @ably/spaces,或使用 pnpm add / yarn add / bun add。

@ably/spaces 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@ably/spaces 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@ably/spaces 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@ably/spaces 可以商用吗?

@ably/spaces 使用 ISC 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@ably/spaces 的下载量有多少?

根据 npm 官方下载统计,@ably/spaces 在 2026/10/05 – 2026/11/03 这 30 天内被下载 117,663 次,日均约 3,922 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@ably/spaces 还在维护吗?

最新版本 0.6.0 发布于 2026/11/02(3 天前);至今共发布 11 个版本,其中过去 12 个月发布了 3 个;首次发布于 2023/09/05。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。