### Writing a New Test File Source: https://github.com/ably/ably-pubsub-js/blob/main/test/uts/README.md Example test file structure using Mocha, Chai, and MockHttpClient. Install mock HTTP in beforeEach and restore in afterEach. Use Ably.Rest client to test features. ```typescript import { expect } from 'chai'; import { MockHttpClient } from '../mock_http'; import { Ably, installMockHttp, restoreAll } from '../helpers'; describe('uts/rest/my-feature', function () { let mock: MockHttpClient; beforeEach(function () { mock = new MockHttpClient({ onConnectionAttempt: (conn) => conn.respond_with_success(), onRequest: (req) => req.respond_with(200, {}), }); installMockHttp(mock); }); afterEach(function () { restoreAll(); }); it('RSC99 - does something', async function () { const client = new Ably.Rest({ key: 'app.key:secret' }); // ... test ... }); }); ``` -------------------------------- ### Install Ably JavaScript SDK with npm install ably Source: https://github.com/ably/ably-pubsub-js/blob/main/README.md Use this command to install the Ably JavaScript SDK as a dependency in your project. This is the standard NPM installation method and is the first step to using the SDK. ```sh npm install ably ``` -------------------------------- ### Start Mocha test runner web server Source: https://github.com/ably/ably-pubsub-js/blob/main/CONTRIBUTING.md Starts a local Mocha test runner web server; open http://localhost:3000 in a browser. ```bash npm run test:webserver ``` -------------------------------- ### Run React hooks sample app Source: https://github.com/ably/ably-pubsub-js/blob/main/CONTRIBUTING.md Starts the Vite dev server for the React hooks sample application. Requires an API key to be set in the environment file, otherwise the app will render a white page with console errors. ```bash npm run start:react ``` -------------------------------- ### Replace getRoot() with get() and use PathObject Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/liveobjects.md Shows the before and after for replacing getRoot() with get() and using PathObject. The new object.get() returns a PathObject representing the entrypoint for the channel's object hierarchy. ```typescript // root is a LiveMap instance const root = await channel.objects.getRoot(); const childEntry = root.get('child'); // returns a LiveMap, LiveCounter, or a Primitive value ``` ```typescript // myObject is a PathObject const myObject = await channel.object.get(); const childPathObject = myObject.get('child'); // returns a PathObject for a "child" path ``` -------------------------------- ### Connect, subscribe, and publish with Ably Realtime Source: https://github.com/ably/ably-pubsub-js/blob/main/README.md This example shows how to connect to Ably's realtime messaging service, subscribe to a channel to receive messages, and publish a test message to the same channel. It uses the Realtime client (use Ably.Rest for the REST client). Ensure your API key is valid; the clientId 'me' is provided. The code waits for the connection to be established before performing channel operations. ```javascript // Initialize Ably Realtime client // (for the REST client use new Ably.Rest({...}) instead) const realtimeClient = new Ably.Realtime({ key: 'your-ably-api-key', clientId: 'me' }); // Wait for connection to be established await realtimeClient.connection.once('connected'); console.log('Connected to Ably'); // Get a reference to the 'test-channel' channel const channel = realtimeClient.channels.get('test-channel'); // Subscribe to all messages published to this channel await channel.subscribe((message) => { console.log(`Received message: ${message.data}`); }); // Publish a test message to the channel await channel.publish('test-event', 'hello world'); ``` -------------------------------- ### Type-safe PathObject API example Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/liveobjects.md Example showing how the new PathObject API uses TypeScript generics to provide type safety, with a UserProfile type and usage of get() and compact() methods. ```typescript type UserProfile = { name: string; age: number; settings: LiveMap<{ theme: string; notifications: boolean; }>; loginCount: LiveCounter; }; const myObject = await channel.object.get(); // TypeScript knows the structure const name: string = myObject.get('name').value(); const settings = myObject.get('settings'); // PathObject> const theme: string = settings.get('theme').value(); const loginCount = myObject.get('loginCount'); // PathObject const settingsCompact = settings.compact(); // { theme: string; notifications: boolean } ``` -------------------------------- ### Error message and remediation example Source: https://github.com/ably/ably-pubsub-js/blob/main/CLAUDE.md Example of an SDK-constructed error object with message and remediation fields. The message states the failure declaratively, while the remediation gives an imperative fix, naming the exact header and acceptable values. ```javascript message: 'authUrl response is missing a Content-Type header', remediation: 'Set a Content-Type response header on your authUrl endpoint: application/json for a TokenDetails/TokenRequest object, text/plain for a token string, or application/jwt for a JWT.', ``` -------------------------------- ### Mock HTTP client await pattern with MockHttpClient Source: https://github.com/ably/ably-pubsub-js/blob/main/test/uts/README.md Await pattern for advanced scenarios where you need to control the sequence of connection and request events. Uses await_connection_attempt() and await_request() to get pending objects and respond manually. Requires installMockHttp before client creation and uninstallMockHttp at the end. ```typescript import { MockHttpClient } from '../mock_http'; import { installMockHttp, uninstallMockHttp, Ably } from '../helpers'; const mock = new MockHttpClient(); installMockHttp(mock); const client = new Ably.Rest({ key: 'app.key:secret' }); const timePromise = client.time(); const conn = await mock.await_connection_attempt(); conn.respond_with_success(); const req = await mock.await_request(); assert(req.headers['X-Ably-Version']); req.respond_with(200, [1704067200000]); const time = await timePromise; uninstallMockHttp(); ``` -------------------------------- ### Change usage of objects.batch() to PathObject.batch()/Instance.batch() (After) Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/liveobjects.md Shows the new batch API available on any PathObject or Instance, with support for object creation inside the batch function. Includes examples for PathObject, Instance, and object creation. ```typescript const myObject = await channel.object.get(); // Batch is available on any PathObject or Instance - operations execute in that object's context await myObject .get('shape') .get('colour') .batch((ctx) => { ctx.set('border', 'green'); ctx.set('fill', 'yellow'); }); // Batch on Instance const shape = myObject.get('shape').instance(); if (shape) { await shape.batch((ctx) => { ctx.set('name', 'square'); ctx.set('size', 50); }); } await myObject.batch((ctx) => { // Object creation is now supported inside a batch ctx.set('score', LiveCounter.create(100)); ctx.set( 'metadata', LiveMap.create({ timestamp: Date.now().toString(), version: '1.0', }), ); }); ``` -------------------------------- ### Stop using global AblyObjectsTypes interface Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/liveobjects.md Before and after examples showing the removal of the global AblyObjectsTypes interface and the new explicit type parameter usage with channel.object.get(). The after example also shows the resulting PathObject type. ```typescript import { LiveCounter, LiveMap } from 'ably'; declare global { interface AblyObjectsTypes { root: { players: LiveMap<{ name: string; score: LiveCounter }>; status: string; }; } } const root = await channel.objects.getRoot(); // Automatically typed ``` ```typescript import { LiveCounter, LiveMap } from 'ably/liveobjects'; type GameState = { players: LiveMap<{ name: string; score: LiveCounter }>; status: string; }; const myObject = await channel.object.get(); // myObject is now PathObject> ``` -------------------------------- ### Update imports for LiveObjects types Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/liveobjects.md Before and after examples showing the change from importing LiveObjects types from 'ably' to 'ably/liveobjects'. The 'Objects' type is renamed to 'RealtimeObject'. ```typescript import { Objects, LiveCounter, LiveMap } from 'ably'; ``` ```typescript import { RealtimeObject, LiveCounter, LiveMap } from 'ably/liveobjects'; ``` -------------------------------- ### Retrieve primitive values using .value() - Before Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/liveobjects.md Old API using channel.objects.getRoot() and direct get() returning the primitive value directly. ```typescript const root = await channel.objects.getRoot(); const name = root.get('name'); // 'Alice' ``` -------------------------------- ### usePresenceListener hook: TypeScript type hints Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/react.md TypeScript example showing type hints for usePresenceListener. The generic type parameter MyPresenceType ensures presenceData is typed correctly. If omitted, any is the default. ```tsx const TypedUsePresenceListenerComponent = () => { // In this example MyPresenceType will be used for presenceData type hints. // If that's omitted, `any` will be the default. const { presenceData } = usePresenceListener('testChannelName'); const membersData = presenceData.map((presenceMsg, index) => { return (
  • {/* you will have Intellisense for presenceMsg.data of type MyPresenceType here */} {presenceMsg.clientId} - {presenceMsg.data.foo}
  • ); }); return
      {membersData}
    ; }; interface MyPresenceType { foo: string; } ``` -------------------------------- ### Run UTS tests with npm run test:uts Source: https://github.com/ably/ably-pubsub-js/blob/main/test/uts/README.md Builds the Node.js bundle and runs all UTS tests via mocha. UTS tests are isolated from the main test suite, with no shared_helper or sandbox setup. ```bash npm run test:uts ``` -------------------------------- ### Use .compact() to get in-memory object representation Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/liveobjects.md Converts a LiveObject to a plain in-memory JavaScript object. Binary data appears as buffers (Buffer in Node.js, ArrayBuffer elsewhere) and cyclic structures use direct object references. ```typescript const myObject = await channel.object.get(); await myObject.set( 'gameState', LiveMap.create({ playerName: 'Alice', score: LiveCounter.create(100), avatar: new ArrayBuffer(8), }) ); const compact = myObject.compact(); console.log(compact); // Output: { gameState: { playerName: 'Alice', score: 100, avatar: } } ``` -------------------------------- ### Reading values: channel.objects.getRoot() to channel.object.get() Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/liveobjects.md Migrate reading values from the old channel.objects.getRoot() API to the new channel.object.get() API. The new API returns a PathObject whose get() calls return values directly, so the extra .value() call on the root is no longer needed. ```typescript const root = await channel.objects.getRoot(); const username = root.get('user').get('name'); // 'Alice' const visits = root.get('visits').value(); // 42 ``` ```typescript const myObject = await channel.object.get(); const username = myObject.get('user').get('name').value(); // 'Alice' const visits = myObject.get('visits').value(); // 42 ``` -------------------------------- ### Access nested paths with PathObject Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/liveobjects.md Shows how to access nested paths with PathObject. Chain .get() calls to navigate nested structures, use .at() for a fully-qualified string path, and .path() to get the fully-qualified string path. ```typescript // Chain .get() calls to navigate nested structures const shape = myObject.get('shape'); const colour = myObject.get('shape').get('colour'); const border = myObject.get('shape').get('colour').get('border'); // Or use .at() to get a PathObject for a fully-qualified string path const border = myObject.at('shape.colour.border'); // Call .path() to get a fully-qualified string path for a location const path = myObject.get('shape').get('colour').get('border').path(); // shape.colour.border ``` -------------------------------- ### usePresence hook: TypeScript type hints Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/react.md TypeScript example showing type hints for usePresence. The generic type parameter MyPresenceType ensures the value passed to updateStatus matches the type. If omitted, the shape of the initial value is used, otherwise any. ```tsx const TypedUsePresenceComponent = () => { // In this example MyPresenceType will be used for type checking updateStatus function. // If omitted, the shape of the initial value will be used, and if that's omitted, `any` will be the default. const { updateStatus } = usePresence('testChannelName', { foo: 'bar' }); return ( ); }; interface MyPresenceType { foo: string; } ``` -------------------------------- ### PathObject runtime resolution: access methods return empty defaults Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/liveobjects.md Shows that access methods return empty defaults when the path doesn't resolve to an appropriate object at runtime. For example, .value() returns undefined and .entries() returns an empty iterator. ```typescript // If 'visits' doesn't exist or isn't a primitive or a LiveCounter const visits = myObject.get('visits').value(); // undefined // If 'players' doesn't exist or isn't a LiveMap for (const [key, player] of myObject.get('players').entries()) { // Empty iterator - loop body never executes } ``` -------------------------------- ### Create client with BaseRealtime and plugins from ably/modular Source: https://github.com/ably/ably-pubsub-js/blob/main/README.md Use this modular, tree-shakable variant of the SDK to reduce bundle size. You must provide at least one HTTP request implementation (FetchRequest or XHRRequest) and at least one realtime transport implementation (WebSocketTransport or XHRPolling). The plugins are passed to the BaseRealtime constructor. Replace the key with a real key. This variant offers the same API as the Realtime class but performs less logging. ```javascript import { BaseRealtime, WebSocketTransport, FetchRequest, RealtimePresence } from 'ably/modular'; const client = new BaseRealtime({ key: 'YOUR_ABLY_API_KEY', // Replace with a real key from the Ably dashboard plugins: { WebSocketTransport, FetchRequest, RealtimePresence, }, }); ``` -------------------------------- ### Lint, format, and docs commands Source: https://github.com/ably/ably-pubsub-js/blob/main/CLAUDE.md Commands for linting, formatting, and generating documentation from ably.d.ts. ```bash npm run lint # ESLint (lint:fix to autofix) ``` ```bash npm run format # Prettier write (format:check to verify) ``` ```bash npm run docs # Generate TypeDoc from ably.d.ts ``` -------------------------------- ### Run a test file with grep and skip build Source: https://github.com/ably/ably-pubsub-js/blob/main/CONTRIBUTING.md Runs a single test file with a grep pattern, skipping the build step. ```bash npm run test:node:skip-build -- test/rest/status.test.js --grep=test_name_here ``` -------------------------------- ### Mock HTTP client handler pattern with MockHttpClient Source: https://github.com/ably/ably-pubsub-js/blob/main/test/uts/README.md Recommended handler pattern for most tests. Uses onConnectionAttempt and onRequest callbacks to respond to connection and HTTP requests, capturing requests for assertions. Must call installMockHttp before creating the client and uninstallMockHttp after. ```typescript import { MockHttpClient } from '../mock_http'; import { installMockHttp, uninstallMockHttp, Ably } from '../helpers'; const captured: any[] = []; const mock = new MockHttpClient({ onConnectionAttempt: (conn) => conn.respond_with_success(), onRequest: (req) => { captured.push(req); req.respond_with(200, [1704067200000]); }, }); installMockHttp(mock); const client = new Ably.Rest({ key: 'app.key:secret' }); const time = await client.time(); // captured[0].method === 'GET' // captured[0].path === '/time' uninstallMockHttp(); ``` -------------------------------- ### Create objects using static LiveCounter.create() and LiveMap.create() - After Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/liveobjects.md New API using static factory methods and passing value types directly to set(). Requires importing LiveCounter and LiveMap from 'ably/liveobjects'. ```typescript import { LiveCounter, LiveMap } from 'ably/liveobjects'; const myObject = await channel.object.get(); await myObject.set('visits', LiveCounter.create(0)); await myObject.set('user', LiveMap.create({ name: 'Alice' })); ``` -------------------------------- ### Import useObject Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/react.md Import the useObject hook from the specific entry point. ```javascript import { useObject } from 'ably/liveobjects/react'; ``` -------------------------------- ### Create objects using static LiveCounter.create() and LiveMap.create() - Before Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/liveobjects.md Old API using channel.objects.createCounter() and createMap() to create objects before setting them on the root. ```typescript const root = await channel.objects.getRoot(); const counter = await channel.objects.createCounter(0); const map = await channel.objects.createMap({ name: 'Alice' }); await root.set('visits', counter); await root.set('user', map); ``` -------------------------------- ### Configure ChannelProvider Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/react.md Configure the ChannelProvider with the required LiveObjects modes. ```jsx ``` -------------------------------- ### Run React hooks unit tests Source: https://github.com/ably/ably-pubsub-js/blob/main/CONTRIBUTING.md Runs the unit tests for the React hooks sample application. ```bash npm run test:react ``` -------------------------------- ### npm run build - Full build Source: https://github.com/ably/ably-pubsub-js/blob/main/CLAUDE.md Runs the full webpack build. Platform-specific builds are available via build:node, build:browser, etc. ```bash npm run build # Full build (webpack; slow). Platform-specific: build:node, build:browser, ... ``` -------------------------------- ### Format and lint files Source: https://github.com/ably/ably-pubsub-js/blob/main/CONTRIBUTING.md Fixes linting and formatting issues. ```bash npm run format ``` -------------------------------- ### Directory Structure Source: https://github.com/ably/ably-pubsub-js/blob/main/test/uts/README.md Shows the layout of the test/uts directory, including helper files, mock implementations, and test subdirectories for REST and Realtime APIs. ```text test/uts/ README.md # This file helpers.ts # install/uninstall, FakeClock, Ably re-export mock_http.ts # MockHttpClient (PendingConnection, PendingRequest) mock_websocket.ts # MockWebSocket (PendingWSConnection, MockWSInstance) deviations.md # Known spec/implementation deviations rest/ # REST API tests time.test.ts # RSC16 — time() tests ... # (37 test files) realtime/ # Realtime API tests time.test.ts # RTC6a — RealtimeClient#time proxy tests client/ # Realtime client tests client_options.test.ts # RSC1, RTC12 realtime_client.test.ts # RTC1a-f, RTC2-4, RTC13-17 realtime_request.test.ts # RTC9 realtime_stats.test.ts # RTC5 realtime_timeouts.test.ts # RTC7 ``` -------------------------------- ### Before: Access LiveMap instance via channel.objects.getRoot() Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/liveobjects.md Shows the previous approach for accessing a LiveMap instance before the v2 migration. Retrieves the root object, then the 'player1' LiveMap under 'players', and calls set() on it. ```typescript const root = await channel.objects.getRoot(); const player = root.get('players').get('player1'); // player is a LiveMap instance await player.set('score', 100); ``` -------------------------------- ### Usage with Multiple Clients Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/react.md Explains how to use multiple Ably clients on the same page by nesting AblyProvider components with unique ablyId props and passing the ablyId to hooks. ```APIDOC ## Usage with Multiple Clients ### Description Explains how to use multiple Ably clients on the same page by nesting AblyProvider components with unique ablyId props and passing the ablyId to hooks. ### Method Provider and Hooks ### Parameters - **ablyId** (string) - Required for nested providers - A unique identifier for each Ably client. ### Usage Example (Nested Providers) ```jsx root.render( , ); ``` ### Usage Example (Passing ablyId to Hooks) ```javascript const ablyId = 'providerOne'; const client = useAbly(ablyId); useChannel({ channelName: 'your-channel-name', ablyId }, (message) => { console.log(message); }); usePresence({ channelName: 'your-channel-name', ablyId }, 'initial state'); usePresenceListener({ channelName: 'your-channel-name', ablyId }, (presenceUpdate) => { // ... }); ``` ``` -------------------------------- ### Access explicit object instances using .instance() Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/liveobjects.md Shows the recommended approach for accessing LiveMap and LiveCounter instances. Use PathObject for path-based operations, or `.instance()` when you need the object ID or instance subscriptions. ```typescript const myObject = await channel.object.get(); // Option 1: Use PathObject for path-based operations (recommended for most cases) await myObject.get('players').get('player1').set('score', 100); // Option 2: Get the explicit instance when you need the object ID or instance subscriptions const player = myObject.get('players').get('player1').instance(); // player is an Instance | undefined if (player) { // ... } ``` -------------------------------- ### useChannel basic subscription Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/react.md Subscribe to a channel and receive messages. The hook returns the channel instance and the Ably SDK instance. ```javascript const { channel, ably } = useChannel('your-channel-name', (message) => { console.log(message); }); ``` -------------------------------- ### Set AWS credentials with ably-env Source: https://github.com/ably/ably-pubsub-js/blob/main/scripts/README.md Run this command to set temporary AWS credentials as environment variables using ably-env before running cdn_deploy.js locally. ```bash source <(ably-env secrets print-aws) ``` -------------------------------- ### Migrate Crypto.generateRandomKey() to promise-based API Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/lib.md In v1, Crypto.generateRandomKey() required a callback. In v2, it returns a promise, so use await instead. ```javascript Ably.Realtime.Crypto.generateRandomKey((err, key) => { … }) ``` ```javascript const key = await Ably.Realtime.Crypto.generateRandomKey(); ``` -------------------------------- ### npm test - Run Mocha test suite Source: https://github.com/ably/ably-pubsub-js/blob/main/CLAUDE.md Builds and runs the Mocha test suite. ```bash npm test # Build + run the Mocha test suite ``` -------------------------------- ### Update entrypoint: channel.objects to channel.object Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/liveobjects.md Shows the before and after for the entrypoint change from plural channel.objects to singular channel.object, reflecting the single entry object per channel model. ```typescript const channelObjects = channel.objects; ``` ```typescript const channelObject = channel.object; ``` -------------------------------- ### Error Handling with useChannel, usePresence, usePresenceListener Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/react.md Describes how to handle connection and channel errors when using the useChannel, usePresence, and usePresenceListener hooks. Errors are returned from the hooks or can be handled via callbacks. ```APIDOC ## Error Handling with useChannel, usePresence, usePresenceListener ### Description Describes how to handle connection and channel errors when using the useChannel, usePresence, and usePresenceListener hooks. Errors are returned from the hooks or can be handled via callbacks. ### Method Hook ### Parameters - **connectionError** (Error) - Returned by the hooks - The connection error, if any. - **channelError** (Error) - Returned by the hooks - The channel error, if any. - **onConnectionError** (function) - Optional - Callback to be called when a connection error occurs. - **onChannelError** (function) - Optional - Callback to be called when a channel error occurs. ### Usage Example (Returned Errors) ```jsx const { connectionError, channelError } = useChannel('my_channel', messageHandler); if (connectionError) { // TODO: handle connection errors } else if (channelError) { // TODO: handle channel errors } else { return ; } ``` ### Usage Example (Callbacks) ```js useChannel( { channelName: 'my_channel', onConnectionError: (err) => { /* handle connection error */ }, onChannelError: (err) => { /* handle channel error */ }, }, messageHandler, ); ``` ``` -------------------------------- ### usePresence hook: support for objects, numbers, and strings Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/react.md usePresence supports objects, numbers, and strings as presence data. The first argument is the channel name, the second is the initial presence data. ```javascript usePresence('your-channel-name', { foo: 'bar' }); usePresence('another-channel-name', 123); usePresence('third-channel-name', 'initial status'); ``` -------------------------------- ### useAbly Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/react.md Accesses the Ably client used by the AblyProvider context. Optionally accepts an ablyId to specify which client to use when multiple clients are nested. ```APIDOC ## useAbly ### Description Accesses the Ably client used by the AblyProvider context. Optionally accepts an ablyId to specify which client to use when multiple clients are nested. ### Method Hook ### Parameters - **ablyId** (string) - Optional - The identifier of the Ably client to retrieve. Used when multiple AblyProvider components are nested. ### Usage Example ```javascript const client = useAbly(); client.authorize(); ``` ### Usage with ablyId ```javascript const ablyId = 'providerOne'; const client = useAbly(ablyId); ``` ``` -------------------------------- ### Set Ably API key in .env Source: https://github.com/ably/ably-pubsub-js/blob/main/CONTRIBUTING.md Sets the Ably API key for the Vite dev server. Must be placed in the file ./src/platform/react-hooks/sample-app/.env. The key is loaded at build time. ```.env VITE_ABLY_API_KEY= ``` -------------------------------- ### useObject Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/react.md Documentation for the useObject hook from the ably-pubsub-js library, covering its usage, parameters, return values, and TypeScript support. ```APIDOC ## useObject ### Description Subscribes to the LiveObjects state on a channel and re-renders the component when it changes. It is exported from its own entry point, `ably/liveobjects/react`. ### Import ```javascript import { useObject } from 'ably/liveobjects/react'; ``` ### Usage Called with no arguments, `useObject` subscribes to the channel's object. `value` is a plain-data snapshot of the object (the result of `compact()`), and `object` is the live `PathObject` for the subscribed node, which you can use to navigate and to write. ```jsx const Scoreboard = () => { const { value, object } = useObject(); if (!object) return

    Loading…

    ; return ; }; ``` ### Parameters #### Selector (optional) - **selector** (function) - Optional - A function that receives the channel's object as a `PathObject` and must navigate to a descendant using `get`/`at`. The hook subscribes to the node it returns, so the component only re-renders for changes within that node. #### Options (optional) - **channelName** (string) - Optional - The name of the channel to subscribe to. - **ablyId** (string) - Optional - The ID of the Ably client to use. - **skip** (boolean) - Optional - If true, the hook does not subscribe. - **onConnectionError** (function) - Optional - Callback for connection errors. - **onChannelError** (function) - Optional - Callback for channel errors. ### Return Value Returns an object with the following properties: - **value** (any) - The plain-data snapshot of the subscribed node. It is a cached snapshot: its identity only changes when the subscribed node changes, so it is safe to use in dependency arrays. It is a by-value copy: the same logical node reached through two different hooks is not reference-equal. - **object** (PathObject | undefined) - The live `PathObject` for the subscribed node. `undefined` while loading. - **error** (ErrorInfo | null) - An error if the object could not be resolved (e.g., missing LiveObjects plugin or channel lacks object modes). `null` while loading or when ready. - **connectionError** (ErrorInfo | null) - Connection error, if any. - **channelError** (ErrorInfo | null) - Channel error, if any. ### Readiness - `object === undefined && error === null` means loading. - `error !== null` means the object could not be resolved. - A defined `object` means ready, with `value` carrying the data once the node exists. ### Example with Selector ```jsx const AliceScore = () => { const { value, object } = useObject((obj) => obj.get('scores').get('alice')); return ; }; ``` ### TypeScript Usage If using TypeScript, annotate the selector's parameter with the shape of your channel's object and the whole navigation chain is checked at compile time — `value` and `object` are then typed from the chain with no further annotation. ```tsx import { LiveCounter, LiveMap, PathObject } from 'ably/liveobjects'; type Game = { scores: LiveMap<{ alice: LiveCounter; bob: LiveCounter }>; title: string; }; const AliceScore = () => { // value: number | undefined, object: PathObject | undefined const { value, object } = useObject((obj: PathObject>) => obj.get('scores').get('alice')); return ; }; ``` For the no-selector form, provide the shape of the channel's object as a type parameter instead — `useObject()` — the same type parameter that `channel.object.get()` takes. ### Error Handling If the object cannot be resolved — for example the `LiveObjects` plugin is missing from the client, or the channel lacks the object modes — the hook reports this through the `error` return value, which carries ably-js's own `ErrorInfo` describing the failure. ```jsx const Scoreboard = () => { const { value, object, error } = useObject(); if (error) return

    Objects failed to load: {error.message}

    ; if (!object) return

    Loading…

    ; return

    Alice: {value.scores.alice}

    ; }; ``` ### Requirements - The `LiveObjects` plugin passed to the Ably client. - The `OBJECT_SUBSCRIBE` channel mode (plus `OBJECT_PUBLISH` if you write to objects), set via `ChannelProvider`'s channel options. - React 18 or later (the hook is built on `useSyncExternalStore`). ### Example with ChannelProvider ```jsx ``` ``` -------------------------------- ### ChannelProvider with subscription filter (deriveOptions) Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/react.md Use deriveOptions with a filter expression to create a derived channel that only receives messages matching the filter. Note that publishing to a derived channel via the channel instance fails; use the publish function from useChannel instead. ```jsx const deriveOptions = { filter: 'headers.email == `"rob.pike@domain.com"` || headers.company == `"domain"`' } return ( ) ``` -------------------------------- ### Run one test file Source: https://github.com/ably/ably-pubsub-js/blob/main/CLAUDE.md Runs a single test file using the Mocha test runner. ```bash npm run test:node -- test/realtime/auth.test.js # Run one test file ``` -------------------------------- ### Replace channel.publish() with useChannel publish function Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/react-hooks.md Shows the old pattern of calling channel.publish() on the channel object returned by useChannel, and the new pattern using the dedicated publish function. Use the new function to send messages to derived channels without attaching. The new function is recommended over channel.publish(). ```jsx const { channel } = useChannel({ channelName: 'your-channel-name' }); channel.publish('test-message', { text: 'message text', }); ``` ```jsx const { publish } = useChannel({ channelName: 'your-channel-name' }); publish('test-message', { text: 'message text', }); ``` -------------------------------- ### ChannelProvider with rewind option Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/react.md Use the options prop with params.rewind to rewind the channel by a specified amount when subscribing. ```jsx ``` -------------------------------- ### usePresenceListener hook: configure callback Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/react.md Configure a callback instead of using the returned presenceData. The callback receives each presence update as a PresenceMessage instance. ```javascript usePresenceListener('your-channel-name', (presenceUpdate) => { console.log(presenceUpdate); }); ``` -------------------------------- ### Run Node.js Mocha tests Source: https://github.com/ably/ably-pubsub-js/blob/main/CONTRIBUTING.md Runs the Mocha test suite for Node.js. ```bash npm run test:node ``` -------------------------------- ### Replace options in usePresence with ChannelProvider Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/react-hooks.md In v2, channel options are provided via the ChannelProvider component instead of the options parameter in usePresence. The old code passes options directly to usePresence; the new code wraps children in ChannelProvider and uses usePresence without options. ```jsx const { updateStatus } = usePresence( { channelName: 'presence-channel-name', options: { modes: ['PRESENCE'] } }, { foo: 'bar' }, ); ``` ```jsx // in a parent component: return ( {children} ); // in a child component: const { updateStatus } = usePresence({ channelName: 'presence-channel-name' }, { foo: 'bar' }); ``` -------------------------------- ### Replace options in useChannel with ChannelProvider Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/react-hooks.md In v2, channel options are provided via the ChannelProvider component instead of the options parameter in useChannel. The old code passes options directly to useChannel; the new code wraps children in ChannelProvider and uses useChannel without options. ```jsx const { channel } = useChannel( { channelName: 'your-channel-name', options: { params: { rewind: '1' } } }, (message) => { console.log(message); }, ); ``` ```jsx // in a parent component: return ( {children} ); // in a child component: const { channel } = useChannel({ channelName: 'your-channel-name' }, (message) => { console.log(message); }); ``` -------------------------------- ### Replace offAll() with individual listener management (After) Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/liveobjects.md Shows the new approach using channel.object and either the subscription object returned by .on() or .off(event, callback) with a callback reference. ```typescript const channelObject = channel.object; // Option 1: Use the subscription object returned by .on() const subscription1 = channelObject.on('synced', () => console.log('Synced 1')); subscription1.off(); // Option 2: Use .off(event, callback) with a callback reference const onSynced2 = () => console.log('Synced 2'); channelObject.on('synced', onSynced2); channelObject.off('synced', onSynced2); ``` -------------------------------- ### Load Ably JavaScript SDK v2 via CDN Source: https://github.com/ably/ably-pubsub-js/blob/main/README.md Use this script tag to include the Ably JavaScript SDK directly in your HTML page. This URL points to the latest version of v2 of the SDK, the current major version, avoiding breaking changes per semver. ```html ``` -------------------------------- ### Use useObject with standard options Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/react.md Pass standard channel options to the useObject hook. ```javascript const { value, error, connectionError, channelError } = useObject((obj) => obj.get('scores'), { channelName: 'your-channel-name', }); ``` -------------------------------- ### Before: subscribe callback with partial update object Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/liveobjects.md Shows the previous subscription callback signature that received a partial update object with limited operation metadata. Use this to compare with the new signature when migrating existing code. ```typescript const root = await channel.objects.getRoot(); const counter = root.get('visits'); counter.subscribe((update) => { // update: { update: { amount: 5 }, clientId: 'my-client-id', connectionId: '...' } console.log('Counter changed by:', update.update.amount); }); const shape = root.get('shape'); shape.subscribe((update) => { // update: { update: { ``` -------------------------------- ### Before: explicit channel.attach() before objects.getRoot() Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/liveobjects.md Shows the old pattern where an explicit `await channel.attach()` was required before accessing objects. Forgetting this call would cause `channel.objects.getRoot()` to hang indefinitely. ```typescript await channel.attach(); // Explicit attach required - forgetting this would cause hangs const root = await channel.objects.getRoot(); ``` -------------------------------- ### usePresence hook: set initial presence data Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/react.md Optionally provide a second parameter to usePresence to set an initial presence data value. The new state is sent to the channel and all clients subscribed to the channel are notified immediately. ```javascript const { updateStatus } = usePresence('your-channel-name', 'initial state'); // The `updateStatus` function can be used to update the presence data for the current client updateStatus('new status'); ``` -------------------------------- ### Run Mocha tests Source: https://github.com/ably/ably-pubsub-js/blob/main/CONTRIBUTING.md Runs the Mocha test suite. ```bash npm test ``` -------------------------------- ### Add version argument to request() Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/lib.md In v2, request() requires a version argument. Pass 2 for compatibility with v1. ```javascript const time = await rest.request('get', '/time'); ``` ```javascript const time = await rest.request('get', '/time', 2); ``` -------------------------------- ### Update LiveObjects plugin import Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/liveobjects.md Shows the before and after for the LiveObjects plugin import change. The import path changes from 'ably/objects' to 'ably/liveobjects', the plugin becomes a named export, and the plugin name changes from Objects to LiveObjects, affecting the plugins client option key. ```typescript import * as Ably from 'ably'; import Objects from 'ably/objects'; const client = new Ably.Realtime({ key: 'your-api-key', plugins: { Objects }, }); ``` ```typescript import * as Ably from 'ably'; import { LiveObjects } from 'ably/liveobjects'; const client = new Ably.Realtime({ key: 'your-api-key', plugins: { LiveObjects }, }); ``` -------------------------------- ### Configure serverComponentsExternalPackages to include 'ably' in next.config.js Source: https://github.com/ably/ably-pubsub-js/blob/main/README.md Adds 'ably' to the serverComponentsExternalPackages list in the Next.js configuration file to prevent bundling issues with the Ably Pub/Sub JavaScript SDK when using App Router with Turbopack. This resolves 'Failed to compile Module not found' errors or warnings related to the 'keyv' package. ```javascript const nextConfig = { // ... experimental: { serverComponentsExternalPackages: ['ably'], }, }; ``` -------------------------------- ### useConnectionStateListener: listen to all connection state changes Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/react.md Attaches a listener that is called on every connection state change. The callback receives a stateChange object with current, previous, and reason properties. Useful for detecting when the client has lost connection. ```javascript useConnectionStateListener((stateChange) => { console.log(stateChange.current); // the new connection state console.log(stateChange.previous); // the previous connection state console.log(stateChange.reason); // if applicable, an error indicating the reason for the connection state change }); ``` -------------------------------- ### Change usage of objects.batch() to PathObject.batch()/Instance.batch() (Before) Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/liveobjects.md Shows the old batch API on channel.objects, which did not support object creation inside the batch function. ```typescript // Object creation was not supported in batch, objects had to be created before calling the .batch() method const counter = await channel.objects.createCounter(100); // Batch can only be called on channel.objects await channel.objects.batch((ctx) => { const root = ctx.getRoot(); root.set('name', 'Alice'); root.set('score', counter); }); ``` -------------------------------- ### useConnectionStateListener Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/react.md Attaches a listener to be notified of connection state changes. Optionally accepts a filter to listen only to specific connection states. ```APIDOC ## useConnectionStateListener ### Description Attaches a listener to be notified of connection state changes. Optionally accepts a filter to listen only to specific connection states. ### Method Hook ### Parameters - **listener** (function) - Required - A callback that receives a stateChange object with `current`, `previous`, and `reason` properties. - **filter** (string or array of strings) - Optional - A connection state or array of connection states to filter the listener. The listener is only called when the connection state changes to one of the specified states. ### Usage Example ```javascript useConnectionStateListener((stateChange) => { console.log(stateChange.current); // the new connection state console.log(stateChange.previous); // the previous connection state console.log(stateChange.reason); // if applicable, an error indicating the reason for the connection state change }); ``` ### Filtered Usage Example ```javascript useConnectionStateListener('failed', listener); // the listener only gets called when the connection state becomes failed useConnectionStateListener(['failed', 'suspended'], listener); // the listener only gets called when the connection state becomes failed or suspended ``` ``` -------------------------------- ### Record private API usage with helper.recordPrivateApi Source: https://github.com/ably/ably-pubsub-js/blob/main/CONTRIBUTING.md Use this JavaScript snippet to record usage of a private API in a test. It sabotages the reattach attempt and simulates a server-sent detach. The identifier 'replace.channel.send' must be added to the private API usage list in test/common/modules/private_api_recorder.js if not already present. ```javascript /* Sabotage the reattach attempt, then simulate a server-sent detach */ helper.recordPrivateApi('replace.channel.send'); channel.send = function () {}; ``` -------------------------------- ### Create deeply nested structures - Before Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/liveobjects.md Old API creating nested maps separately and then setting them on the root. ```typescript const root = await channel.objects.getRoot(); const colour = await channel.objects.createMap({ border: 'red', fill: 'blue' }); const shape = await channel.objects.createMap({ name: 'circle', radius: 10, colour }); await root.set('shape', shape); ``` -------------------------------- ### Debug a single test file Source: https://github.com/ably/ably-pubsub-js/blob/main/CONTRIBUTING.md Launches Mocha tests for a single file with the debugger enabled. ```bash node --inspect-brk=9229 node_modules/.bin/mocha test/realtime/auth.test.js ``` -------------------------------- ### Create deeply nested structures - After Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/liveobjects.md New API using nested LiveMap.create() calls in a single set() operation. ```typescript const myObject = await channel.object.get(); await myObject.set( 'shape', LiveMap.create({ name: 'circle', radius: 10, colour: LiveMap.create({ border: 'red', fill: 'blue', }), }), ); ``` -------------------------------- ### useChannel with skip parameter Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/react.md Use the skip parameter to prevent useChannel from attaching to a channel on mount. Set skip to true when authentication is asynchronous or the feature is conditionally accessible, avoiding attach errors and unnecessary message consumption. The hook accepts a boolean; true skips attaching. ```tsx const [skip, setSkip] = useState(true); const { channel, publish } = useChannel({ channelName: 'your-channel-name', skip }, (message) => { updateMessages((prev) => [...prev, message]); }); ``` -------------------------------- ### Replace deriveOptions in useChannel with ChannelProvider Source: https://github.com/ably/ably-pubsub-js/blob/main/docs/migration-guides/v2/react-hooks.md In v2, deriveOptions are provided via the ChannelProvider component instead of the deriveOptions parameter in useChannel. The old code passes deriveOptions directly to useChannel; the new code wraps children in ChannelProvider and uses useChannel without deriveOptions. ```jsx useChannel( { channelName: 'your-derived-channel-name', deriveOptions: { filter: 'headers.role == `"marketing"`' }, }, (message) => { console.log(message); }, ); ``` ```jsx // in a parent component: return ( {children} ); // in a child component: useChannel({ channelName: 'your-derived-channel-name' }, (message) => { console.log(message); }); ``` -------------------------------- ### Run tests matching a pattern Source: https://github.com/ably/ably-pubsub-js/blob/main/CLAUDE.md Runs tests matching a given pattern using Mocha's grep option. ```bash npm run test:node -- --grep=test_name_here # Run tests matching a pattern ```