bởi pip

A flexible JavaScript SDK for building realtime experiences with pub-sub messaging, presence, message history, and push notifications. Supports Node.js, React, Web Workers, and all modern browsers.
This block provides the Ably Pub/Sub JavaScript SDK source (user@example.com) with full Node.js platform wiring. It exposes Realtime and Rest clients for pub/sub messaging, presence, message history, and push notifications. The typical buyer is a Node.js / TypeScript backend or server-side service that needs production-grade realtime messaging without a browser environment.
common/ - Platform-agnostic core: client logic, transport layer, types, utilitiescommon/lib/client/ - DefaultRealtime, DefaultRest, Auth, channel, presence, push implementationscommon/lib/transport/ - Connection manager, WebSocket transport, Comet transport, protocol layercommon/lib/types/ - Wire types: Message, PresenceMessage, ProtocolMessage, ErrorInfo, Annotationcommon/lib/util/ - Logger, EventEmitter, Defaults, Utils, Multicastercommon/types/ - TypeScript interfaces: ClientOptions, ICipher, ICryptoStatic, IBufferUtilscommon/constants/ - TransportName, HttpMethods, HttpStatusCodes, XHRStatesplatform/nodejs/ - Node.js-specific BufferUtils, Crypto, Http, Transports (WebSocket + Comet)platform/react-native/ - React Native platform wiring (if targeting RN)platform/nativescript/ - NativeScript platform wiringplatform/react-hooks/ - React hooks (useChannel, usePresence, useAbly, etc.)fragments/ably.d.ts - Top-level TypeScript declarationsnpm install @ably/msgpack-js dequal fastestsmallesttextencoderdecoder got ulid ws
npm install --save-dev @types/ws @types/node typescript
No native iOS/Android build steps are required for the Node.js platform target. If you are using , you must run:
Khởi chạy sandbox cách ly và chạy phía máy chủ — không cần cài đặt cục bộ.
Tetrees AI Review cho phiên bản này
This TypeScript cli / script completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
Quy trình avcp-2026-08-04.1 · SHA-256 8c584c6f4c1a568d…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
Đã đánh giá 4 thg 8, 2026
Đưa sản phẩm này thẳng vào AI IDE, trình tạo web hoặc cloud IDE của bạn.
Kết nối Tetrees với AI IDE tương thích để liệt kê sản phẩm bạn sở hữu và nhận ZIP đã xác minh mà không cấp quyền tải lên của người bán.
Chưa có đánh giá.
Sign in to join the discussion
Loading discussion…
platform/react-nativenpx expo prebuild # if using Expo
# or
npx react-native-clean-project # bare RN
Copy the source/ directory into your project, e.g. src/ably-source/.
Update tsconfig.json to add path aliases so the SDK's internal cross-package imports resolve:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"common/*": ["src/ably-source/common/*"]
},
"module": "commonjs",
"target": "ES2017",
"esModuleInterop": true,
"resolveJsonModule": true
}
}
ts-node or tsconfig-paths, register the paths at startup:ts-node -r tsconfig-paths/register src/index.ts
export ABLY_API_KEY="your-app.key:secret"
import Ably from './ably-source/platform/nodejs/index';
const { Realtime, Rest, ErrorInfo } = Ably;
import { DefaultRealtime } from './ably-source/common/lib/client/defaultrealtime';
const client = new DefaultRealtime({ key: process.env.ABLY_API_KEY });
Full-featured realtime client. Use when you need persistent connections, pub/sub channels, presence, and connection state management. Internally wires up WebSocket and Comet transports.
import { DefaultRest } from './ably-source/common/lib/client/defaultrest';
const client = new DefaultRest({ key: process.env.ABLY_API_KEY });
Stateless HTTP REST client. Use for publish-only workloads, querying history, managing presence, or any server-side operation where a persistent connection is unnecessary.
import ErrorInfo from './ably-source/common/lib/types/errorinfo';
// ErrorInfo is thrown / returned by SDK methods on failure
// statusCode: number, code: number, message: string
Ably's structured error type. Always check err instanceof ErrorInfo in catch blocks to access err.code (Ably error code) and err.statusCode (HTTP status) for programmatic error handling.
import { makeFromDeserializedWithDependencies as makeProtocolMessageFromDeserialized }
from './ably-source/common/lib/types/protocolmessage';
Reconstructs a ProtocolMessage from a raw deserialized object (e.g., received over a custom transport or from msgpack). Use in custom transport or testing scenarios where you control the wire layer.
Connect with the Realtime client, subscribe to an event, and publish a message.
import Ably from './ably-source/platform/nodejs/index';
const client = new Ably.Realtime({ key: process.env.ABLY_API_KEY!, clientId: 'server-1' });
async function run() {
await client.connection.once('connected');
console.log('Connected');
const channel = client.channels.get('orders');
await channel.subscribe('new-order', (msg) => {
console.log('Received:', msg.data);
});
await channel.publish('new-order', { id: 42, item: 'widget' });
}
run().catch(console.error);
Use the REST client to publish a message from a stateless serverless function.
import Ably from './ably-source/platform/nodejs/index';
const rest = new Ably.Rest({ key: process.env.ABLY_API_KEY! });
async function publishEvent(orderId: string) {
const channel = rest.channels.get('orders');
await channel.publish('new-order', { id: orderId });
console.log('Published order', orderId);
}
publishEvent('abc-123').catch(console.error);
Use the Realtime client to join a presence set and list current members.
import Ably from './ably-source/platform/nodejs/index';
const client = new Ably.Realtime({
key: process.env.ABLY_API_KEY!,
clientId: 'worker-node-1',
});
async function managePresence() {
await client.connection.once('connected');
const channel = client.channels.get('workers');
await channel.presence.enter({ role: 'processor' });
const members = await channel.presence.get();
console.log('Current members:', members.map((m) => m.clientId));
// Clean up
await channel.presence.leave();
client.close();
}
managePresence().catch(console.error);
Distinguish Ably errors from generic errors.
import Ably from './ably-source/platform/nodejs/index';
import ErrorInfo from './ably-source/common/lib/types/errorinfo';
const rest = new Ably.Rest({ key: 'invalid.key:bad' });
async function safeFetch() {
try {
const channel = rest.channels.get('test');
await channel.publish('evt', 'hello');
} catch (err) {
if (err instanceof ErrorInfo) {
console.error(`Ably error ${err.code} (HTTP ${err.statusCode}): ${err.message}`);
} else {
throw err;
}
}
}
safeFetch();
common/lib/client/defaultrealtime.ts - Assembles the full Realtime client with all features enabled.common/lib/client/defaultrest.ts - Assembles the full Rest client with all features enabled.common/lib/client/baseclient.ts - Shared base: auth, options parsing, HTTP dispatch.common/lib/client/auth.ts - Token auth, API key auth, requestToken, authorize.common/lib/client/realtimechannel.ts - Channel attach/detach, subscribe/unsubscribe, state machine.common/lib/client/restchannel.ts - REST channel: publish and history.common/lib/client/realtimepresence.ts - Realtime presence: enter, leave, update, get, subscribe.common/lib/transport/connectionmanager.ts - Manages transport lifecycle and reconnection strategy.common/lib/transport/websockettransport.ts - WebSocket transport implementation.common/lib/transport/comettransport.ts - Comet (long-poll) fallback transport.common/lib/types/errorinfo.ts - ErrorInfo structured error class.common/lib/types/message.ts - Message type with encode/decode helpers.common/lib/types/protocolmessage.ts - Wire-level protocol message; makeFromDeserializedWithDependencies factory.common/lib/util/logger.ts - Configurable logger with log-level support.common/lib/util/eventemitter.ts - Internal typed event emitter used by channels and connection.common/lib/util/defaults.ts - getDefaults() merges platform defaults with user options.platform/nodejs/index.ts - Node.js platform entry point; wires Crypto, Http, transports, msgpack.platform/nodejs/lib/transport/index.ts - Exports transport order and bundled WebSocket + Comet implementations.platform/react-native/index.ts - React Native entry point (same shape, different platform modules).platform/nativescript/index.ts - NativeScript entry point.platform/react-hooks/src/index.ts - React hooks: useChannel, usePresence, useAbly, usePresenceListener, etc.fragments/ably.d.ts - Aggregated TypeScript type declarations for the whole SDK.Cannot find module 'common/...' at runtime - Add tsconfig-paths and register it before entry (-r tsconfig-paths/register); the SDK uses bare common/ imports internally.ws is not installed - The Node.js WebSocket transport requires ws; it is not bundled. Run npm install ws.msgpack is null on Node.js - The Node.js platform exports msgpack: null; do not pass useBinaryProtocol: true unless you wire msgpack yourself.ErrorInfo instanceof check fails across module copies - Ensure only one copy of ably-source exists in the dependency tree; duplicate copies break instanceof.TextEncoder not defined - The RN platform index imports fastestsmallesttextencoderdecoder as a polyfill; ensure this runs before any SDK code.client.close() or the Node.js process will hang due to open WebSocket/TCP handles.I have the Ably Pub/Sub JavaScript SDK source at `src/ably-source/` (upstream package: user@example.com)
and a USAGE.md integration guide at `src/ably-source/USAGE.md`.
Please integrate this SDK into my existing Node.js / TypeScript project step by step:
1. Read USAGE.md fully before writing any code.
2. Add the required tsconfig path aliases for `common/*` as shown in USAGE.md.
3. Install all runtime dependencies listed in the "Required dependencies" section.
4. Create a singleton Ably Realtime client (using `platform/nodejs/index.ts`) that reads
the API key from the `ABLY_API_KEY` environment variable.
5. Wire up a channel subscription for the channel name I specify, and export a `publish`
helper function.
6. Add proper error handling using `ErrorInfo` from `common/lib/types/errorinfo.ts`.
7. Ensure `client.close()` is called on process SIGTERM/SIGINT.
8. Only use exports that are visible in USAGE.md - do not invent new APIs.
The Ably Pub/Sub JavaScript SDK is released under the Apache 2.0 license. See source/LICENSE if present, or refer to the upstream repository.
Upstream package: ably on npm - version 2.21.0.
Source repository: https://github.com/ably/ably-js.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
Hướng dẫn cài đặt đầy đủ và prompt tích hợp sẽ mở khóa sau khi mua.
Automation, Utilities & Developer Tools
Miễn phí