diff --git a/.eslintrc.js b/.eslintrc.js
index 6ec70e9243..d7574f3ea6 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -19,19 +19,20 @@ module.exports = {
"plugin:security/recommended",
],
rules: {
- // comma-dangle used for browser compatibility for browsers that don't support trailing commas
- "comma-dangle": ["error", "always-multiline"],
"eol-last": "error",
// security/detect-object-injection just gives a lot of false positives
// see https://github.com/nodesecurity/eslint-plugin-security/issues/21
"security/detect-object-injection": "off",
"@typescript-eslint/no-var-requires": "error",
+ // Use typescript-eslint’s version of the no-redeclare rule, which isn’t triggered by overload signatures.
+ // TODO remove this once we start using the full @typescript-eslint/recommended ruleset in #958
+ 'no-redeclare': 'off',
+ '@typescript-eslint/no-redeclare': 'error',
},
overrides: [
{
files: ["**/*.{ts,tsx}"],
rules: {
- "comma-dangle": ["error", "only-multiline"],
"@typescript-eslint/no-unused-vars": ["error", { "varsIgnorePattern": "^_" }],
// TypeScript already enforces these rules better than any eslint setup can
"no-undef": "off",
@@ -40,7 +41,7 @@ module.exports = {
},
},
{
- files: 'ably.d.ts',
+ files: ['ably.d.ts', 'modular.d.ts'],
extends: [
'plugin:jsdoc/recommended',
],
@@ -54,9 +55,10 @@ module.exports = {
"test",
"tools",
"scripts",
- "docs",
+ "typedoc/generated",
"react",
"Gruntfile.js",
+ "grunt",
],
settings: {
jsdoc: {
diff --git a/.github/workflows/bundle-report.yml b/.github/workflows/bundle-report.yml
index 7866bb9dc3..67a81e6eee 100644
--- a/.github/workflows/bundle-report.yml
+++ b/.github/workflows/bundle-report.yml
@@ -17,16 +17,15 @@ jobs:
run: >
git config --global url."https://github.com/".insteadOf
ssh://git@github.com/
- - name: Use Node.js 14.x
+ - name: Use Node.js 20.x
uses: actions/setup-node@v1
with:
- node-version: 14.x
+ node-version: 20.x
- run: npm ci
- name: Build bundle reports
run: |
mkdir bundle-reports
npm run sourcemap -- --html bundle-reports/index.html
- npm run sourcemap:noencryption -- --html bundle-reports/noencryption.html
- uses: aws-actions/configure-aws-credentials@v1
with:
aws-region: eu-west-2
@@ -37,3 +36,5 @@ jobs:
sourcePath: bundle-reports
githubToken: ${{ secrets.GITHUB_TOKEN }}
artifactName: bundle-report
+ # This step performs some validation and may fail, so it should come after the steps that we want to always execute.
+ - run: npm run modulereport
diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml
index 97d2d52717..90d1e81ed6 100644
--- a/.github/workflows/check.yml
+++ b/.github/workflows/check.yml
@@ -14,16 +14,18 @@ jobs:
run: >
git config --global url."https://github.com/".insteadOf
ssh://git@github.com/
- - name: Use Node.js 14.x
+ - name: Use Node.js 20.x
uses: actions/setup-node@v1
with:
- node-version: 14.x
+ node-version: 20.x
- run: npm ci
- run: npm run lint
- run: npm run format:check
- - run: npm run check-closure-compiler
- - run: npx tsc --noEmit ably.d.ts build/ably-webworker.min.d.ts
+ - run: npx tsc --noEmit ably.d.ts modular.d.ts
# for some reason, this doesn't work in CI using `npx attw --pack .`
- run: npm pack
- - run: npx attw ably-$(node -e "console.log(require('./package.json').version)").tgz --summary
+ - run: npx attw ably-$(node -e "console.log(require('./package.json').version)").tgz --summary --exclude-entrypoints 'ably/modular'
+ # see https://github.com/ably/ably-js/issues/1546 for why we ignore 'false-cjs' currently.
+ # should remove when switched to auto-generated type declaration files for modular variant of the library.
+ - run: npx attw ably-$(node -e "console.log(require('./package.json').version)").tgz --summary --entrypoints 'ably/modular' --ignore-rules false-cjs
- run: npm audit --production
diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml
index 96023da288..f9e7184297 100644
--- a/.github/workflows/docs.yml
+++ b/.github/workflows/docs.yml
@@ -16,10 +16,10 @@ jobs:
steps:
- uses: actions/checkout@v3
- - name: Use Node.js 16.x
+ - name: Use Node.js 20.x
uses: actions/setup-node@v3
with:
- node-version: 16.x
+ node-version: 20.x
- name: Install Package Dependencies
run: npm ci
@@ -37,6 +37,6 @@ jobs:
- name: Upload Documentation
uses: ably/sdk-upload-action@v1
with:
- sourcePath: docs/generated
+ sourcePath: typedoc/generated
githubToken: ${{ secrets.GITHUB_TOKEN }}
artifactName: typedoc
diff --git a/.github/workflows/publish-cdn.yml b/.github/workflows/publish-cdn.yml
index a4fe17b64f..13e21c85fa 100644
--- a/.github/workflows/publish-cdn.yml
+++ b/.github/workflows/publish-cdn.yml
@@ -23,9 +23,9 @@ jobs:
aws-region: us-east-1
role-to-assume: arn:aws:iam::${{ secrets.ABLY_AWS_ACCOUNT_ID_SDK }}:role/prod-ably-sdk-cdn
role-session-name: "${{ github.run_id }}-${{ github.run_number }}"
- - name: Use Node.js 14.x
+ - name: Use Node.js 20.x
uses: actions/setup-node@v1
with:
- node-version: 14.x
+ node-version: 20.x
- run: npm ci
- run: node scripts/cdn_deploy.js --skipCheckout --tag=${{ github.event.inputs.version }}
diff --git a/.github/workflows/react.yml b/.github/workflows/react.yml
index 2c48513e7d..7802ab0f5c 100644
--- a/.github/workflows/react.yml
+++ b/.github/workflows/react.yml
@@ -14,7 +14,6 @@ jobs:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
- node-version: 16
+ node-version: 20
- run: npm ci
- - run: npm run format:check
- run: npm run test:react
diff --git a/.github/workflows/test-browser.yml b/.github/workflows/test-browser.yml
index eaa2f3be41..c434c2e582 100644
--- a/.github/workflows/test-browser.yml
+++ b/.github/workflows/test-browser.yml
@@ -20,10 +20,10 @@ jobs:
run: >
git config --global url."https://github.com/".insteadOf
ssh://git@github.com/
- - name: Use Node.js 16.x
+ - name: Use Node.js 20.x
uses: actions/setup-node@v1
with:
- node-version: 16.x
+ node-version: 20.x
- run: npm ci
- name: Install Playwright browsers and dependencies
run: npx playwright install --with-deps
diff --git a/.github/workflows/test-node.yml b/.github/workflows/test-node.yml
index 7efb047890..39ccf4d0e6 100644
--- a/.github/workflows/test-node.yml
+++ b/.github/workflows/test-node.yml
@@ -11,7 +11,7 @@ jobs:
strategy:
fail-fast: false
matrix:
- node-version: [12.x, 14.x, 16.x]
+ node-version: [16.x, 18.x, 20.x]
steps:
- uses: actions/checkout@v2
with:
diff --git a/.github/workflows/test-package.yml b/.github/workflows/test-package.yml
new file mode 100644
index 0000000000..8e622413a9
--- /dev/null
+++ b/.github/workflows/test-package.yml
@@ -0,0 +1,20 @@
+name: Test NPM package
+on:
+ pull_request:
+ push:
+ branches:
+ - main
+
+jobs:
+ test-npm-package:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ with:
+ submodules: true
+ - name: Use Node.js 20.x
+ uses: actions/setup-node@v1
+ with:
+ node-version: 20.x
+ - run: npm ci
+ - run: npm run test:package
diff --git a/.gitignore b/.gitignore
index b424979fdc..072dde41f2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -6,6 +6,6 @@ npm-debug.log
.tool-versions
build/
react/
-docs/generated/
+typedoc/generated/
junit/
test/support/mocha_junit_reporter/build/
diff --git a/.mocharc.js b/.mocharc.js
new file mode 100644
index 0000000000..fb2c98119c
--- /dev/null
+++ b/.mocharc.js
@@ -0,0 +1,19 @@
+const config = {
+ require: ['source-map-support/register', 'test/support/modules_helper.js', 'test/support/test_helper.js'],
+ file: ['test/support/root_hooks.js'],
+ reporter: 'test/support/mocha_reporter.js',
+};
+
+// mocha has a ridiculous issue (https://github.com/mochajs/mocha/issues/4100) that command line
+// specs don't override config specs; they are merged instead, so you can't run a single test file
+// if you've defined specs in your config. therefore we work around it by only adding specs to the
+// config if none are passed as arguments
+if (!process.argv.slice(2).some(isTestFile)) {
+ config.spec = ['test/realtime/*.test.js', 'test/rest/*.test.js'];
+}
+
+function isTestFile(arg) {
+ return arg.match(/\.test.js$/);
+}
+
+module.exports = config;
diff --git a/.prettierrc.json b/.prettierrc.json
index fc56e31458..489d21d22f 100644
--- a/.prettierrc.json
+++ b/.prettierrc.json
@@ -1,5 +1,5 @@
{
- "trailingComma": "es5",
+ "trailingComma": "all",
"tabWidth": 2,
"semi": true,
"singleQuote": true,
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ec8b215a5f..5430363b98 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,92 @@
This contains only the most important and/or user-facing changes; for a full changelog, see the commit history.
+## [2.0.0](https://github.com/ably/ably-js/tree/2.0.0) (2024-03-22)
+
+The 2.0.0 release introduces a number of new features and QoL improvements, including a new way to remove bloat and reduce the bundle size of your ably-js client, first-class support for Promises, a more idiomatic approach to using ably-js' React Hooks, enhancements to TypeScript typings, and more.
+
+Below is an overview of the major changes in this release.
+
+Please refer to the ably-js v2 [lib migration guide](./docs/migration-guides/v2/lib.md) and [React Hooks migration guide](./docs/migration-guides/v2/react-hooks.md) for the full details, including a list of all breaking changes and instructions on how to address them.
+
+### Bundle Size Reduction
+
+The default bundle size for the web has been reduced by ~32% compared to v1 - from 234.11 KiB to 159.32 KiB. When calculated with gzip compression, the reduction is ~30%, from 82.54 KiB to 57.9 KiB.
+
+Additionally, by utilizing the new modular variant of the library (see below) and JavaScript tree shaking, you can create your own minimal useful `Realtime` client and achieve a bundle size reduction of ~60.5% compared to v1 - from 234.11 KiB to 92.38 KiB (or ~66% for gzip: from 82.54 KiB to 28.18 KiB).
+
+### Modular variant of the library
+
+An ESM variant of the library is now available for browsers (but not for Node.js) via import from `ably/modular`. This modular variant of the library supports tree shaking, allowing for a reduction in the Ably bundle size within your application and improving the user experience. It can also be used by Web Workers.
+
+### React Hooks changes
+
+React Hooks, exported at `ably/react`, now require the new `ChannelProvider` component to define the channels you wish to use and the options for them. This addresses the complexities previously encountered with `useChannel` and `usePresence` hooks when attempting to dynamically change options for a channel and provides a more straightforward approach to set and manage these options.
+
+The functionality of the `usePresence` hook has been split into two separate hooks: `usePresence`, which is now used only to enter presence, and `usePresenceListener`, which is used to listen for presence updates. These new hooks offer better control over the desired presence behavior in your React components.
+
+### First-class support for Promises
+
+The callbacks API has been entirely removed, and the library now supports promises for all its asynchronous operations by default.
+
+### TypeScript typings
+
+The Types namespace has been removed. All types it contained are now exported at the top level.
+
+### Browser and Web Worker bundles
+
+- The browser bundle now relies on the native Web Crypto API instead of CryptoJS. The `ably/build/ably.noencryption` bundle has been removed, as it is no longer necessary.
+- The browser bundle can now be directly used by Web Workers. The `ably/build/ably-webworker` bundle has been removed, as it is no longer necessary.
+
+### Supported platforms changes
+
+- Support for Internet Explorer has been dropped.
+- Support for Node.js versions lower than 16 has been dropped. The supported Node.js versions are now 16, 18, and 20.
+- The minimum supported versions for major browsers are: Chrome 58, Firefox 52, Edge 79, Safari 11, and Opera 45.
+
+
+View merged Pull Requests
+
+### Breaking Changes
+
+- Add `ChannelProvider` component to React Hooks [\#1620](https://github.com/ably/ably-js/pull/1620), [\#1654](https://github.com/ably/ably-js/pull/1654)
+- Add untyped stats API [\#1522](https://github.com/ably/ably-js/pull/1522)
+- Add type definitions for key returned by `generateRandomKey` [\#1320](https://github.com/ably/ably-js/pull/1320)
+- Add mandatory `version` param to `Rest.request` [\#1231](https://github.com/ably/ably-js/pull/1231)
+- Change `id` field to be named `ablyId` in React Hooks [\#1676](https://github.com/ably/ably-js/pull/1676)
+- Change `usePresence` hook to two different hooks: for entering presence and subscribing to presence updates [\#1674](https://github.com/ably/ably-js/pull/1674)
+- Change naming for enum-like namespaces in type declarations and change meaning for public `ChannelModes` type [\#1601](https://github.com/ably/ably-js/pull/1601)
+- Change publishing methods to accept a `Message`-shaped object [\#1515](https://github.com/ably/ably-js/pull/1515)
+- Change `Crypto.generateRandomKey` API to use Promises [\#1351](https://github.com/ably/ably-js/pull/1351)
+- Change `fromEncoded()` and `fromEncodedArray()` methods on `Message` and `PresenceMessage` to be async [\#1311](https://github.com/ably/ably-js/pull/1311)
+- Remove `XHRStreaming` transport support [\#1645](https://github.com/ably/ably-js/pull/1645)
+- Remove code that's supporting older platforms [\#1629](https://github.com/ably/ably-js/pull/1629), [\#1633](https://github.com/ably/ably-js/pull/1633), [\#1641](https://github.com/ably/ably-js/pull/1641)
+- Remove `recoveryKey` in favour of `createRecoveryKey()` on `Connection` [\#1613](https://github.com/ably/ably-js/pull/1613)
+- Remove `any` from `stats()` param type [\#1561](https://github.com/ably/ably-js/pull/1561)
+- Remove the dedicated Web Worker bundle `ably/build/ably-webworker` and add support for using `ably` and `ably/modular` in Web Workers [\#1550](https://github.com/ably/ably-js/pull/1550)
+- Remove false class exports in type declarations [\#1524](https://github.com/ably/ably-js/pull/1524)
+- Remove the `Types` namespace [\#1518](https://github.com/ably/ably-js/pull/1518)
+- Remove `noencryption` variant of the library [\#1500](https://github.com/ably/ably-js/pull/1500)
+- Remove public callbacks API [\#1358](https://github.com/ably/ably-js/pull/1358)
+- Remove CryptoJS library and replace it with the Web Crypto API in web bundle [\#1299](https://github.com/ably/ably-js/pull/1299), [\#1325](https://github.com/ably/ably-js/pull/1325), [\#1333](https://github.com/ably/ably-js/pull/1333)
+- Remove `ably-commonjs*.js` files [\#1229](https://github.com/ably/ably-js/pull/1229)
+- Remove deprecated APIs [\#1227](https://github.com/ably/ably-js/pull/1227)
+- Remove deprecated `fromEncoded*` type declarations [\#1222](https://github.com/ably/ably-js/pull/1222)
+- Remove deprecated `ClientOptions` parameters [\#1221](https://github.com/ably/ably-js/pull/1221)
+- Remove the `ClientOptions.log` property and replace it with separate `logLevel` and `logHandler` properties [\#1216](https://github.com/ably/ably-js/pull/1216)
+- Remove support for JSONP [\#1215](https://github.com/ably/ably-js/pull/1215)
+- Fix `whenState` inconsistent behavior in `Connection` and `RealtimeChannel` [\#1640](https://github.com/ably/ably-js/pull/1640)
+- Fix the type definition of `Crypto.getDefaultParams` [\#1352](https://github.com/ably/ably-js/pull/1352)
+
+### Features
+
+- Add `publish` function to the `useChannel` hook [\#1658](https://github.com/ably/ably-js/pull/1658)
+- Add logs to all HTTP activity [\#1581](https://github.com/ably/ably-js/pull/1581)
+
+
+
+[Full Changelog](https://github.com/ably/ably-js/compare/1.2.50...2.0.0)
+
## [1.2.50](https://github.com/ably/ably-js/tree/1.2.50) (2024-03-21)
- Add new logging API to `ClientOptions` and add a deprecation warning for the old one [\#1671](https://github.com/ably/ably-js/pull/1671)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 4dce45af00..7cfdd46c47 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -8,9 +8,8 @@
4. Commit your changes (`git commit -am 'Add some feature'`)
5. Ensure you have added suitable tests and the test suite is passing(`npm test`)
6. Ensure the [type definitions](https://github.com/ably/ably-js/blob/main/ably.d.ts) have been updated if the public API has changed
-7. Ensure you stick to the version of JS used by the library (currently ES5). (The minfication task (`npm run grunt -- closureCompiler:ably.js`) will enforce that you stick to ES5 syntax, but will not enforce that you don't use, for example, new methods)
-8. Push the branch (`git push origin my-new-feature`)
-9. Create a new Pull Request
+7. Push the branch (`git push origin my-new-feature`)
+8. Create a new Pull Request
## Release Process
@@ -30,7 +29,7 @@
## Building the library
-To build the library, simply run `npm run build`. Building the library currently requires NodeJS <= v16.
+To build the library, simply run `npm run build`. Building the library currently requires NodeJS >= v16.
Since webpack builds are slow, commands are also available to only build the output for specific platforms (eg `npm run build:node`), see [package.json](./package.json) for the full list of available commands
@@ -46,27 +45,27 @@ Run the Mocha test suite
npm run test:node
-Or run just one test file
+You can pass any Mocha CLI arguments and flags to the test:node script after the `--` separator, for example running one test file:
- npm run test:node -- --file=test/realtime/auth.test.js
+ npm run test:node -- test/realtime/auth.test.js
Or run just one test
- npm run test:node -- --file=test/rest/status.test.js --grep=test_name_here
+ npm run test:node -- --grep=test_name_here
Or run test skipping the build
- npm run test:node:skip-build -- --file=test/rest/status.test.js --grep=test_name_here
+ npm run test:node:skip-build -- test/rest/status.test.js --grep=test_name_here
### Debugging the mocha tests locally with a debugger
Run the following command to launch tests with the debugger enabled. The tests will block until you attach a debugger.
- node --inspect-brk=9229 node_modules/.bin/grunt test:node
+ node --inspect-brk=9229 node_modules/.bin/mocha
Alternatively you can also run the tests for single file
- node --inspect-brk=9229 node_modules/.bin/grunt test:node --test=test/realtime/auth.test.js
+ node --inspect-brk=9229 node_modules/.bin/mocha test/realtime/auth.test.js
The included vscode launch config allows you to launch and attach the debugger in one step, simply open the test
file you want to run and start debugging. Note that breakpoint setting for realtime code will be within the
diff --git a/Gruntfile.js b/Gruntfile.js
index a29bac491e..a19bc21ea3 100644
--- a/Gruntfile.js
+++ b/Gruntfile.js
@@ -3,11 +3,12 @@
var fs = require('fs');
var path = require('path');
var webpackConfig = require('./webpack.config');
+var esbuild = require('esbuild');
+var process = require('process');
+var MochaServer = require('./test/web_server');
+var esbuildConfig = require('./grunt/esbuild/build');
module.exports = function (grunt) {
- grunt.loadNpmTasks('grunt-contrib-concat');
- grunt.loadNpmTasks('grunt-closure-tools');
- grunt.loadNpmTasks('grunt-bump');
grunt.loadNpmTasks('grunt-webpack');
var dirs = {
@@ -16,75 +17,40 @@ module.exports = function (grunt) {
fragments: 'src/platform/web/fragments',
static: 'build',
dest: 'build',
- crypto_js: 'node_modules/crypto-js/src',
- tools_compiler: __dirname + '/node_modules/google-closure-compiler/compiler.jar',
};
- function compilerSpec(src, dest) {
- return {
- src: src,
- dest: dest || src.replace(/\.js/, '.min.js'),
- };
- }
-
- function execExternal(cmd) {
- return function () {
- var done = this.async();
- grunt.log.ok('Executing ' + cmd);
+ async function execExternalPromises(cmd) {
+ grunt.log.ok('Executing ' + cmd);
+ return new Promise(function (resolve, reject) {
require('child_process').exec(cmd, function (err, stdout, stderr) {
if (err) {
- grunt.fatal('Error executing "' + cmd + '": ' + stderr);
+ grunt.fatal('Error executing "' + cmd + '":\nstderr:\n' + stderr + '\nstdout:\n' + stdout);
+ reject(err);
}
console.log(stdout);
stderr && console.error(stderr);
- done();
+ resolve();
});
+ });
+ }
+
+ function execExternal(cmd) {
+ return function () {
+ var done = this.async();
+ execExternalPromises(cmd)
+ .then(() => done())
+ .catch((error) => done(error));
};
}
var gruntConfig = {
dirs: dirs,
- pkgVersion: grunt.file.readJSON('package.json').version,
webpack: {
all: Object.values(webpackConfig),
- node: [webpackConfig.node, webpackConfig.mochaJUnitReporterNode],
browser: [webpackConfig.browser, webpackConfig.browserMin, webpackConfig.mochaJUnitReporterBrowser],
},
};
- gruntConfig['closureCompiler'] = {
- options: {
- compilerFile: dirs.tools_compiler,
- compilerOpts: {
- compilation_level: 'SIMPLE_OPTIMIZATIONS',
- /* By default, the compiler assumes you're using es6 and transpiles to
- * es5, adding various (unnecessary and undesired) polyfills. Specify
- * both in and out to es5 to avoid transpilation */
- language_in: 'ECMASCRIPT5',
- language_out: 'ECMASCRIPT5',
- strict_mode_input: true,
- checks_only: true,
- warning_level: 'QUIET',
- },
- },
- 'ably.js': compilerSpec('<%= dirs.static %>/ably.js'),
- };
-
- gruntConfig.bump = {
- options: {
- files: ['package.json', 'README.md'],
- globalReplace: true,
- commit: true,
- commitMessage: 'Regenerate and release version %VERSION%',
- commitFiles: [], // Add files manually as can't add new files with a commit flag
- createTag: true,
- tagName: '%VERSION%',
- tagMessage: 'Version %VERSION%',
- push: false,
- prereleaseName: 'beta',
- },
- };
-
grunt.initConfig(gruntConfig);
grunt.registerTask('checkGitSubmodules', 'Check, if git submodules are properly installed', function () {
@@ -107,24 +73,54 @@ module.exports = function (grunt) {
});
});
- grunt.registerTask('build', ['checkGitSubmodules', 'webpack:all']);
+ grunt.registerTask('build', ['checkGitSubmodules', 'webpack:all', 'build:browser', 'build:node']);
- grunt.registerTask('build:node', ['checkGitSubmodules', 'webpack:node']);
+ grunt.registerTask('all', ['build', 'requirejs']);
- grunt.registerTask('build:browser', ['checkGitSubmodules', 'webpack:browser']);
+ grunt.registerTask('mocha:webserver', 'Run the Mocha web server', function () {
+ const done = this.async();
+ const server = new MochaServer();
+ server.listen();
+
+ process.on('SIGTERM', () => {
+ server.close();
+ done();
+ });
+ process.on('SIGINT', () => {
+ server.close();
+ done();
+ });
+ });
- grunt.registerTask('check-closure-compiler', ['build', 'closureCompiler:ably.js']);
+ grunt.registerTask('build:node', function () {
+ const done = this.async();
- grunt.registerTask('all', ['build', 'check-closure-compiler', 'requirejs']);
+ esbuild
+ .build(esbuildConfig.nodeConfig)
+ .then(() => {
+ done(true);
+ })
+ .catch((err) => {
+ done(err);
+ });
+ });
- grunt.loadTasks('test/tasks');
+ grunt.registerTask('build:browser', function () {
+ var done = this.async();
- grunt.registerTask('test', ['test:node']);
- grunt.registerTask(
- 'test:node',
- 'Build the library and run the node test suite\nOptions\n --test [tests] e.g. --test test/rest/auth.js',
- ['build:node', 'mocha']
- );
+ Promise.all([
+ esbuild.build(esbuildConfig.webConfig),
+ esbuild.build(esbuildConfig.minifiedWebConfig),
+ esbuild.build(esbuildConfig.modularConfig),
+ ])
+ .then(() => {
+ console.log('esbuild succeeded');
+ done(true);
+ })
+ .catch((err) => {
+ done(err);
+ });
+ });
grunt.registerTask('test:webserver', 'Launch the Mocha test web server on http://localhost:3000/', [
'build:browser',
@@ -132,58 +128,71 @@ module.exports = function (grunt) {
'mocha:webserver',
]);
- grunt.registerTask('release:refresh-pkgVersion', 'Refreshes GruntConfig.pkgVersion', function () {
- grunt.config('pkgVersion', grunt.file.readJSON('package.json').version);
- grunt.log.ok('pkgVersion updated');
- });
+ (function () {
+ const baseDir = path.join(__dirname, 'test', 'package', 'browser');
+ const buildDir = path.join(baseDir, 'build');
+
+ grunt.registerTask(
+ 'test:package:browser:prepare-project',
+ 'Prepare an app to be used for testing the NPM package in a browser environment',
+ function () {
+ const done = this.async();
+
+ (async function () {
+ if (grunt.file.exists(buildDir)) {
+ grunt.file.delete(buildDir);
+ }
+
+ // Create an app based on the template
+ grunt.file.copy(path.join(baseDir, 'template'), buildDir);
+
+ // Use `npm pack` to generate a .tgz NPM package
+ await execExternalPromises('npm run build');
+ await execExternalPromises('npm pack --pack-destination test/package/browser/build');
+ const version = grunt.file.readJSON('package.json').version;
+ const packFileName = `ably-${version}.tgz`;
+
+ // Configure app to consume the generated .tgz file
+ const pwd = process.cwd();
+ process.chdir(buildDir);
+ await execExternalPromises(`npm install ${packFileName}`);
+
+ // Install further dependencies required for testing the app
+ await execExternalPromises('npm run test:install-deps');
+ process.chdir(pwd);
+ })()
+ .then(() => done(true))
+ .catch((error) => done(error));
+ },
+ );
- grunt.registerTask('release:git-add-generated', 'Adds generated files to the git staging area', function () {
- var done = this.async();
- var generatedFiles = [
- gruntConfig.dirs.common + '/lib/util/defaults.js',
- gruntConfig.dirs.fragments + '/license.js',
- 'package.json',
- 'package-lock.json',
- 'README.md',
- 'test/support/browser_file_list.js',
- ];
- var cmd = 'git add -A ' + generatedFiles.join(' ');
- grunt.log.ok('Executing ' + cmd);
+ grunt.registerTask('test:package:browser:test', 'Test the NPM package in a browser environment', function () {
+ const done = this.async();
- require('child_process').exec(cmd, function (err, stdout, stderr) {
- if (err) {
- grunt.fatal('git add . -A failed with ' + stderr);
- }
- done();
- });
- });
+ (async function () {
+ grunt.task.requires('test:package:browser:prepare-project');
- grunt.registerTask('release:git-push', 'Pushes to git', execExternal('git push origin main --follow-tags'));
+ const pwd = process.cwd();
+ process.chdir(buildDir);
- grunt.registerTask('release:ably-deploy', 'Deploys to ably CDN', function () {
- var version = grunt.file.readJSON('package.json').version,
- cmd = 'node scripts/cdn_deploy.js --skipCheckout --tag ' + version;
- console.log('Publishing version ' + version + ' of the library to the CDN');
- execExternal(cmd).call(this);
- });
+ // Perform type checking on TypeScript code that imports ably-js
+ await execExternalPromises('npm run typecheck');
- grunt.registerTask('release:deploy', 'Pushes a new release to github and then deploys to the Ably CDN', function () {
- grunt.task.run(['release:git-push', 'release:ably-deploy']);
- });
+ // Build bundle including ably-js
+ await execExternalPromises('npm run build');
+
+ // Test that the code which exercises ably-js behaves as expected
+ await execExternalPromises('npm run test');
+
+ process.chdir(pwd);
+ })()
+ .then(() => done(true))
+ .catch((error) => done(error));
+ });
+ })();
- grunt.registerTask(
- 'release',
- 'Increments the version, regenerates, and makes a tagged commit. Run as "grunt release:type", where "type" is "major", "minor", "patch", "prepatch", etc.)',
- function (versionType) {
- grunt.task.run([
- 'bump-only:' + versionType,
- 'release:refresh-pkgVersion',
- 'all',
- 'release:git-add-generated',
- 'bump-commit',
- ]);
- }
- );
+ grunt.registerTask('test:package:browser', ['test:package:browser:prepare-project', 'test:package:browser:test']);
+ grunt.registerTask('test:package', ['test:package:browser']);
grunt.registerTask('default', 'all');
};
diff --git a/README.md b/README.md
index b9fb92c9f7..bfb9de6659 100644
--- a/README.md
+++ b/README.md
@@ -14,13 +14,21 @@ This library currently targets the [Ably client library features spec](https://w
This SDK supports the following platforms:
-**Browsers:** All major desktop and mobile browsers, including (but not limited to) Chrome, Firefox, IE (only version 9 or newer), Safari on iOS and macOS, Opera, and Android browsers.
+**Browsers:** All major desktop and mobile browsers, including (but not limited to) Chrome, Firefox, Edge, Safari on iOS and macOS, Opera, and Android browsers. IE is not supported. See compatibility table below for more information on minimum supported versions for major browsers:
+
+| Browser | Minimum supported version | Release date |
+| ------- | :-----------------------: | -----------: |
+| Chrome | 58 | Apr 19, 2017 |
+| Firefox | 52 | Mar 7, 2017 |
+| Edge | 79 | Dec 15, 2020 |
+| Safari | 11 | Sep 19, 2017 |
+| Opera | 45 | May 10, 2017 |
**Webpack:** see [using Webpack in browsers](#using-webpack), or [our guide for serverside Webpack](#serverside-usage-with-webpack)
-**Node.js:** version 8.17 or newer. (1.1.x versions work on Node.js 4.5 or newer). We do not currently provide an ESM bundle, please [contact us](https://www.ably.com/contact) if you would would like to use ably-js in a NodeJS ESM project.
+**Node.js:** version 16.x or newer. (1.1.x versions work on Node.js 4.5 or newer, 1.2.x versions work on Node.js 8.17 or newer). We do not currently provide an ESM bundle, please [contact us](https://www.ably.com/contact) if you would would like to use ably-js in a NodeJS ESM project.
-**React (release candidate)** We offer a set of React Hooks which make it seamless to use ably-js in your React application. See the [React Hooks documentation](./docs/react.md) for more details.
+**React (release candidate):** We offer a set of React Hooks which make it seamless to use ably-js in your React application. See the [React Hooks documentation](./docs/react.md) for more details.
**React Native:** We aim to support all platforms supported by React Native. If you find any issues please raise an issue or [contact us](https://www.ably.com/contact).
@@ -28,18 +36,15 @@ This SDK supports the following platforms:
**TypeScript:** see [below](#typescript)
-**WebWorkers**: We build a separate bundle which supports running in a [Web Worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) context. You can import it like this:
+**WebWorkers:** The browser bundle supports running in a [Web Worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) context. You can also use the [modular variant](#modular-tree-shakable-variant) of the library in Web Workers.
-```js
-import Ably from 'ably/build/ably-webworker.min';
-```
+We test the library against a selection of browsers using their latest versions. Please refer to [the test-browser GitHub workflow](./.github/workflows/test-browser.yml) for the set of browsers that currently undergo CI testing.
-We regression-test the library against a selection of those (which will change over time, but usually consists of the versions that are supported upstream, plus old versions of IE).
+We regression-test the library against a selection of Node.js versions, which will change over time. We will always support and test against current LTS Node.js versions, and optionally some older versions that are still supported by upstream dependencies. We reserve the right to drop support for non-LTS versions in a non-major release. We will update the `engines` field in [package.json](./package.json) whenever we change the Node.js versions supported by the project. Please refer to [the test-node GitHub workflow](./.github/workflows/test-node.yml) for the set of versions that currently undergo CI testing.
However, we aim to be compatible with a much wider set of platforms and browsers than we can possibly test on. That means we'll happily support (and investigate reported problems with) any reasonably-widely-used browser. So if you find any compatibility issues, please do [raise an issue](https://github.com/ably/ably-js/issues) in this repository or [contact Ably customer support](https://support.ably.com) for advice.
-Ably-js has fallback mechanisms in order to be able to support older browsers; specifically it supports comet-based connections for browsers that do not support websockets, and this includes JSONP for browsers that do not support cross-origin XHR. Each of these fallback transport mechanisms is supported and tested on all the browsers we test against, even when those browsers do not themselves require those fallbacks. These mean that the library should be compatible with nearly any browser on most platforms.
-Known browser incompatibilities will be documented as an issue in this repository using the ["compatibility" label](https://github.com/ably/ably-js/issues?q=is%3Aissue+is%3Aopen+label%3A%22compatibility%22).
+If you require support for older browsers and Node.js, you can use the security-maintained version 1 of the library. Install version 1 via [CDN link](https://cdn.ably.com/lib/ably.min-1.js), or from npm with `npm install ably@1 --save`. It supports IE versions 9 or newer, older versions of major browsers, and Node.js 8.17 or newer. Note that version 1 will only receive security updates and critical bug fixes, and won't include any new features.
For complete API documentation, see the [Ably documentation](https://www.ably.com/docs).
@@ -55,8 +60,6 @@ and require as:
var Ably = require('ably');
```
-For the version of the library where async methods return promises, use `var Ably = require('ably/promises');` instead. For the explicitly-callback-based variant use `require('ably/callbacks')`– see [Async API style](#async-api-style).
-
For usage, jump to [Using the Realtime API](#using-the-realtime-api) or [Using the REST API](#using-the-rest-api).
#### Serverside usage with webpack
@@ -81,7 +84,47 @@ For usage, jump to [Using the Realtime API](#using-the-realtime-api) or [Using t
WebPack will search your `node_modules` folder by default, so if you include `ably` in your `package.json` file, when running Webpack the following will allow you to `require('ably')` (or if using typescript or ES6 modules, `import * as Ably from 'ably';`). If your webpack target is set to 'browser', this will automatically use the browser commonjs distribution.
-If that doesn't work for some reason (e.g. you are using a custom webpack target), you can reference the `ably-commonjs.js` static file directly: `require('ably/build/ably-commonjs.js');` (or `import * as Ably from 'ably/build/ably-commonjs.js'` for typescript / ES6 modules).
+If that doesn't work for some reason (e.g. you are using a custom webpack target), you can reference the `ably.js` static file directly: `require('ably/build/ably.js');` (or `import * as Ably from 'ably/build/ably.js'` for typescript / ES6 modules).
+
+#### Modular (tree-shakable) variant
+
+Aimed at those who are concerned about their app’s bundle size, the modular variant of the library allows you to create a client which has only the functionality that you choose. Unused functionality can then be tree-shaken by your module bundler.
+
+The modular variant of the library provides:
+
+- a `BaseRealtime` class;
+- various plugins that add functionality to a `BaseRealtime` instance, such as `Rest`, `RealtimePresence`, etc.
+
+To use this variant of the library, import the `BaseRealtime` class from `ably/modular`, along with the plugins that you wish to use. Then, pass these plugins to the `BaseRealtime` constructor as shown in the example below:
+
+```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,
+ },
+});
+```
+
+You must provide:
+
+- at least one HTTP request implementation; that is, one of `FetchRequest` or `XHRRequest`;
+- at least one realtime transport implementation; that is, one of `WebSocketTransport` or `XHRPolling`.
+
+`BaseRealtime` offers the same API as the `Realtime` class described in the rest of this `README`. This means that you can develop an application using the default variant of the SDK and switch to the modular version when you wish to optimize your bundle size.
+
+In order to further reduce bundle size, the modular variant of the SDK performs less logging than the default variant. It only logs:
+
+- messages that have a `logLevel` of 1 (that is, errors)
+- a small number of other network events
+
+If you need more verbose logging, use the default variant of the SDK.
+
+For more information about the modular variant of the SDK, see the [generated documentation](https://sdk.ably.com/builds/ably/ably-js/main/typedoc/modules/modular.html) (this link points to the documentation for the `main` branch).
### TypeScript
@@ -90,26 +133,16 @@ The TypeScript typings are included in the package and so all you have to do is:
```typescript
import * as Ably from 'ably';
-let options: Ably.Types.ClientOptions = { key: 'foo' };
+let options: Ably.ClientOptions = { key: 'foo' };
let client = new Ably.Realtime(options); /* inferred type Ably.Realtime */
-let channel = client.channels.get('feed'); /* inferred type Ably.Types.RealtimeChannel */
+let channel = client.channels.get('feed'); /* inferred type Ably.RealtimeChannel */
```
-For the version of the library where async methods return promises, use `import * as Ably from 'ably/promises';` instead. For the explicitly-callback-based variant use `import * as Ably from 'ably/callbacks'` – see [Async API style](#async-api-style).
-
Intellisense in IDEs with TypeScript support is supported:
![TypeScript suggestions](./resources/typescript-demo.gif)
-If you need to explicitly import the type definitions, see [ably.d.ts](./ably.d.ts) (or `promises.d.ts` if you're requiring the library as `ably/promises`).
-
-## Async API style
-
-This library exposes two API variants. Firstly, the original (and presently the default) callback-based API, which follows the usual Node.js error-first callback style. Second, a promises-based API. With the promises variant, you can still pass a callback to methods and the callback will work as expected, but if you do not pass a callback, the method will return a promise. The API in use can be selected explicitly by requiring that specific variant when requiring/importing the library (or in the case of the browser version, when instantiating it). The usage instructions below make reference to both variants.
-
-For this library version, and for all future 1.x versions, the callback-based API will be the default. This means that the promises-based variant will need to be explicitly selected, to avoid breaking backwards compatibility. A move to the promises-based variant as the default is likely at the next major release (i.e. 2.x onwards).
-
-For usage, jump to [Using the async API style](#using-the-async-api-style).
+If you need to explicitly import the type definitions, see [ably.d.ts](./ably.d.ts).
## NativeScript
@@ -131,13 +164,6 @@ var client = new Ably.Realtime(key: string);
// which must contain at least one auth option, i.e. at least
// one of: key, token, tokenDetails, authUrl, or authCallback
var client = new Ably.Realtime(options: ClientOptions);
-
-// For a version of the library where async methods return promises if
-// you don't pass a callback:
-var client = new Ably.Realtime.Promise(options: string | ClientOptions);
-
-// For the explicitly-callback-based variant (see 'Async API style' below):
-var client = new Ably.Rest.Callbacks(options: string | ClientOptions);
```
### Connection
@@ -198,36 +224,26 @@ If you would like to inspect the `Message` instances in order to identify whethe
```javascript
// Publish a single message with name and data
-channel.publish('greeting', 'Hello World!');
-
-// Optionally, you can use a callback to be notified of success or failure
-channel.publish('greeting', 'Hello World!', function(err) {
- if(err) {
- console.log('publish failed with error ' + err);
- } else {
- console.log('publish succeeded');
- }
-})
+await channel.publish('greeting', 'Hello World!');
// Publish several messages at once
-channel.publish([{name: 'greeting', data: 'Hello World!'}, ...], callback);
+await channel.publish([{name: 'greeting', data: 'Hello World!'}, ...]);
```
### Querying the History
```javascript
-channel.history(function(err, messagesPage) {
- messagesPage // PaginatedResult
- messagesPage.items // array of Message
- messagesPage.items[0].data // payload for first message
- messagesPage.items.length // number of messages in the current page of history
- messagesPage.hasNext() // true if there are further pages
- messagesPage.isLast() // true if this page is the last page
- messagesPage.next(function(nextPage) { ... }); // retrieves the next page as PaginatedResult
-});
+const messagesPage = channel.history()
+messagesPage // PaginatedResult
+messagesPage.items // array of Message
+messagesPage.items[0].data // payload for first message
+messagesPage.items.length // number of messages in the current page of history
+messagesPage.hasNext() // true if there are further pages
+messagesPage.isLast() // true if this page is the last page
+const nextPage = await messagesPage.next(); // retrieves the next page as PaginatedResult
// Can optionally take an options param, see https://www.ably.com/docs/rest-api/#message-history
-channel.history({start: ..., end: ..., limit: ..., direction: ...}, function(err, messagesPage) { ...});
+const messagesPage = await channel.history({start: ..., end: ..., limit: ..., direction: ...});
```
### Presence on a channel
@@ -235,9 +251,8 @@ channel.history({start: ..., end: ..., limit: ..., direction: ...}, function(err
Getting presence:
```javascript
-channel.presence.get(function (err, presenceSet) {
- presenceSet; // array of PresenceMessages
-});
+const presenceSet = channel.presence.get();
+presenceSet; // array of PresenceMessages
```
Note that presence#get on a realtime channel does not return a
@@ -246,17 +261,14 @@ PaginatedResult, as the library maintains a local copy of the presence set.
Entering (and leaving) the presence set:
```javascript
-channel.presence.enter('my status', function (err) {
- // now I am entered
-});
+await channel.presence.enter('my status');
+// now I am entered
-channel.presence.update('new status', function (err) {
- // my presence data is updated
-});
+await channel.presence.update('new status');
+// my presence data is updated
-channel.presence.leave(function (err) {
- // I've left the presence set
-});
+await channel.presence.leave()
+// I've left the presence set
```
If you are using a client which is allowed to use any clientId --
@@ -266,24 +278,23 @@ https://www.ably.com/docs/general/authentication for more information), you
can use
```javascript
-channel.presence.enterClient('myClientId', 'status', function(err) { ... });
+await channel.presence.enterClient('myClientId', 'status');
// and similarly, updateClient and leaveClient
```
### Querying the Presence History
```javascript
-channel.presence.history(function(err, messagesPage) { // PaginatedResult
- messagesPage.items // array of PresenceMessage
- messagesPage.items[0].data // payload for first message
- messagesPage.items.length // number of messages in the current page of history
- messagesPage.hasNext() // true if there are further pages
- messagesPage.isLast() // true if this page is the last page
- messagesPage.next(function(nextPage) { ... }); // retrieves the next page as PaginatedResult
-});
+const messagesPage = channel.presence.history(); // PaginatedResult
+messagesPage.items // array of PresenceMessage
+messagesPage.items[0].data // payload for first message
+messagesPage.items.length // number of messages in the current page of history
+messagesPage.hasNext() // true if there are further pages
+messagesPage.isLast() // true if this page is the last page
+const nextPage = await messagesPage.next(); // retrieves the next page as PaginatedResult
// Can optionally take an options param, see https://www.ably.com/docs/rest-api/#message-history
-channel.presence.history({start: ..., end: ..., limit: ..., direction: ...}, function(err, messagesPage) { ...});
+const messagesPage = await channel.presence.history({start: ..., end: ..., limit: ..., direction: ...);
```
### Symmetrical end-to-end encrypted payloads on a channel
@@ -293,24 +304,22 @@ When a 128 bit or 256 bit key is provided to the library, the `data` attributes
```javascript
// Generate a random 256-bit key for demonstration purposes (in
// practice you need to create one and distribute it to clients yourselves)
-Ably.Realtime.Crypto.generateRandomKey(function (err, key) {
- var channel = client.channels.get('channelName', { cipher: { key: key } });
-
- channel.subscribe(function (message) {
- message.name; // 'name is not encrypted'
- message.data; // 'sensitive data is encrypted'
- });
+const key = await Ably.Realtime.Crypto.generateRandomKey();
+var channel = client.channels.get('channelName', { cipher: { key: key } });
- channel.publish('name is not encrypted', 'sensitive data is encrypted');
+channel.subscribe(function (message) {
+ message.name; // 'name is not encrypted'
+ message.data; // 'sensitive data is encrypted'
});
+
+channel.publish('name is not encrypted', 'sensitive data is encrypted');
```
-You can also change the key on an existing channel using setOptions (which takes a callback which is called after the new encryption settings have taken effect):
+You can also change the key on an existing channel using setOptions (which completes after the new encryption settings have taken effect):
```javascript
-channel.setOptions({cipher: {key: }}, function() {
- // New encryption settings are in effect
-})
+await channel.setOptions({cipher: {key: }});
+// New encryption settings are in effect
```
### Message interactions
@@ -327,6 +336,14 @@ function sendReaction(emoji) {
See https://www.ably.com/docs/realtime/messages#message-interactions for more detail.
+### Fallback transport mechanisms
+
+Ably-js has fallback transport mechanisms to ensure its realtime capabilities can function in network conditions (such as firewalls or proxies) that might prevent the client from establishing a WebSocket connection.
+
+The default `Ably.Realtime` client includes these mechanisms by default. If you are using modular variant of the library, you may wish to provide the `BaseRealtime` instance with one or more alternative transport modules, namely `XHRStreaming` and/or `XHRPolling`, alongside `WebSocketTransport`, so your connection is less susceptible to these external conditions. For instructions on how to do this, refer to the [modular variant of the library](#modular-tree-shakable-variant) section.
+
+Each of these fallback transport mechanisms is supported and tested on all the browsers we test against, even when those browsers do not themselves require those fallbacks.
+
## Using the REST API
This readme gives some basic examples. For our full API documentation, please go to https://www.ably.com/docs .
@@ -343,13 +360,6 @@ var client = new Ably.Rest(key: string);
// which must contain at least one auth option, i.e. at least
// one of: key, token, tokenDetails, authUrl, or authCallback
var client = new Ably.Rest(options: ClientOptions);
-
-// For a version of the library where async methods return promises if
-// you don't pass a callback:
-var client = new Ably.Rest.Promise(options: string | ClientOptions);
-
-// For the explicitly-callback-based variant (see 'Async API style' above):
-var client = new Ably.Rest.Callbacks(options: string | ClientOptions);
```
Given:
@@ -362,75 +372,67 @@ var channel = client.channels.get('test');
```javascript
// Publish a single message with name and data
-channel.publish('greeting', 'Hello World!');
-
-// Optionally, you can use a callback to be notified of success or failure
-channel.publish('greeting', 'Hello World!', function(err) {
- if(err) {
- console.log('publish failed with error ' + err);
- } else {
- console.log('publish succeeded');
- }
-})
+try {
+ channel.publish('greeting', 'Hello World!');
+ console.log('publish succeeded');
+} catch (err) {
+ console.log('publish failed with error ' + err);
+}
// Publish several messages at once
-channel.publish([{name: 'greeting', data: 'Hello World!'}, ...], callback);
+await channel.publish([{name: 'greeting', data: 'Hello World!'}, ...]);
```
### Querying the History
```javascript
-channel.history(function(err, messagesPage) {
- messagesPage // PaginatedResult
- messagesPage.items // array of Message
- messagesPage.items[0].data // payload for first message
- messagesPage.items.length // number of messages in the current page of history
- messagesPage.hasNext() // true if there are further pages
- messagesPage.isLast() // true if this page is the last page
- messagesPage.next(function(nextPage) { ... }); // retrieves the next page as PaginatedResult
-});
+const messagesPage = await channel.history();
+messagesPage // PaginatedResult
+messagesPage.items // array of Message
+messagesPage.items[0].data // payload for first message
+messagesPage.items.length // number of messages in the current page of history
+messagesPage.hasNext() // true if there are further pages
+messagesPage.isLast() // true if this page is the last page
+const nextPage = await messagesPage.next(); // retrieves the next page as PaginatedResult
// Can optionally take an options param, see https://www.ably.com/docs/rest-api/#message-history
-channel.history({start: ..., end: ..., limit: ..., direction: ...}, function(err, messagesPage) { ...});
+await channel.history({start: ..., end: ..., limit: ..., direction: ...});
```
### Presence on a channel
```javascript
-channel.presence.get(function(err, presencePage) { // PaginatedResult
- presencePage.items // array of PresenceMessage
- presencePage.items[0].data // payload for first message
- presencePage.items.length // number of messages in the current page of members
- presencePage.hasNext() // true if there are further pages
- presencePage.isLast() // true if this page is the last page
- presencePage.next(function(nextPage) { ... }); // retrieves the next page as PaginatedResult
-});
+const presencePage = await channel.presence.get() // PaginatedResult
+presencePage.items // array of PresenceMessage
+presencePage.items[0].data // payload for first message
+presencePage.items.length // number of messages in the current page of members
+presencePage.hasNext() // true if there are further pages
+presencePage.isLast() // true if this page is the last page
+const nextPage = await presencePage.next(); // retrieves the next page as PaginatedResult
```
### Querying the Presence History
```javascript
-channel.presence.history(function(err, messagesPage) { // PaginatedResult
- messagesPage.items // array of PresenceMessage
- messagesPage.items[0].data // payload for first message
- messagesPage.items.length // number of messages in the current page of history
- messagesPage.hasNext() // true if there are further pages
- messagesPage.isLast() // true if this page is the last page
- messagesPage.next(function(nextPage) { ... }); // retrieves the next page as PaginatedResult
-});
+const messagesPage = channel.presence.history(); // PaginatedResult
+messagesPage.items // array of PresenceMessage
+messagesPage.items[0].data // payload for first message
+messagesPage.items.length // number of messages in the current page of history
+messagesPage.hasNext() // true if there are further pages
+messagesPage.isLast() // true if this page is the last page
+const nextPage = await messagesPage.next(); // retrieves the next page as PaginatedResult
// Can optionally take an options param, see https://www.ably.com/docs/rest-api/#message-history
-channel.history({start: ..., end: ..., limit: ..., direction: ...}, function(err, messagesPage) { ...});
+const messagesPage = channel.history({start: ..., end: ..., limit: ..., direction: ...});
```
### Getting the status of a channel
```javascript
-channel.status(function(err, channelDetails) {
- channelDetails.channelId // The name of the channel
- channelDetails.status.isActive // A boolean indicating whether the channel is active
- channelDetails.status.occupancy // Contains metadata relating to the occupants of the channel
-});
+const channelDetails = await channel.status();
+channelDetails.channelId // The name of the channel
+channelDetails.status.isActive // A boolean indicating whether the channel is active
+channelDetails.status.occupancy // Contains metadata relating to the occupants of the channel
```
### Generate Token and Token Request
@@ -441,134 +443,49 @@ explanation of Ably's authentication mechanism.
Requesting a token:
```javascript
-client.auth.requestToken(function(err, tokenDetails) {
- // tokenDetails is instance of TokenDetails
- // see https://www.ably.com/docs/rest/authentication/#token-details for its properties
+const tokenDetails = await client.auth.requestToken();
+// tokenDetails is instance of TokenDetails
+// see https://www.ably.com/docs/rest/authentication/#token-details for its properties
- // Now we have the token, we can send it to someone who can instantiate a client with it:
- var clientUsingToken = new Ably.Realtime(tokenDetails.token);
-});
+// Now we have the token, we can send it to someone who can instantiate a client with it:
+var clientUsingToken = new Ably.Realtime(tokenDetails.token);
// requestToken can take two optional params
// tokenParams: https://www.ably.com/docs/rest/authentication/#token-params
// authOptions: https://www.ably.com/docs/rest/authentication/#auth-options
-client.auth.requestToken(tokenParams, authOptions, function(err, tokenDetails) { ... });
+const tokenDetails = await client.auth.requestToken(tokenParams, authOptions);
```
Creating a token request (for example, on a server in response to a
request by a client using the `authCallback` or `authUrl` mechanisms):
```javascript
-client.auth.createTokenRequest(function(err, tokenRequest) {
- // now send the tokenRequest back to the client, which will
- // use it to request a token and connect to Ably
-});
+const tokenRequest = await client.auth.createTokenRequest();
+// now send the tokenRequest back to the client, which will
+// use it to request a token and connect to Ably
// createTokenRequest can take two optional params
// tokenParams: https://www.ably.com/docs/rest/authentication/#token-params
// authOptions: https://www.ably.com/docs/rest/authentication/#auth-options
-client.auth.createTokenRequest(tokenParams, authOptions, function(err, tokenRequest) { ... });
+const tokenRequest = await client.auth.createTokenRequest(tokenParams, authOptions);
```
### Fetching your application's stats
```javascript
-client.stats(function(err, statsPage) { // statsPage as PaginatedResult
- statsPage.items // array of Stats
- statsPage.items[0].inbound.rest.messages.count; // total messages published over REST
- statsPage.items.length; // number of stats in the current page of history
- statsPage.hasNext() // true if there are further pages
- statsPage.isLast() // true if this page is the last page
- statsPage.next(function(nextPage) { ... }); // retrieves the next page as PaginatedResult
-});
+const statsPage = await client.stats() // statsPage as PaginatedResult
+statsPage.items // array of Stats
+statsPage.items[0].inbound.rest.messages.count; // total messages published over REST
+statsPage.items.length; // number of stats in the current page of history
+statsPage.hasNext() // true if there are further pages
+statsPage.isLast() // true if this page is the last page
+const nextPage = await statsPage.next(); // retrieves the next page as PaginatedResult
```
### Fetching the Ably service time
```javascript
-client.time(function(err, time) { ... }); // time is in ms since epoch
-```
-
-## Using the async API style
-
-### Realtime Example
-
-```ts
-import * as Ably from 'ably/promises';
-
-const client = new Ably.Realtime.Promise(options);
-
-const ablyRealtimePromiseExample = async () => {
- const channel = client.channels.get('myChannel');
-
- // Attaching to a channel
- await channel.attach();
-
- // Getting presence on a channel
- const presenceMessage = await channel.presence.get();
- console.log(presenceMessage);
-
- // Updating presence on a client
- await channel.presence.enter();
- await channel.presence.update('new status');
- await channel.presence.leave();
-
- // Publishing a message
- await channel.publish('greeting', 'Hello, World!');
-
- // Querying history
- const history = await channel.history({ limit: 25 });
- console.log(history);
-
- client.close();
-};
-
-ablyRealtimePromiseExample();
-```
-
-### REST Example
-
-```ts
-import * as Ably from 'ably/promises';
-
-const client = new Ably.Rest.Promise(options);
-
-const ablyRestPromiseExample = async () => {
- const channel = client.channels.get('myChannel');
-
- // Publishing a message
- await channel.publish('greeting', 'Hello, World!');
-
- // Getting presence on a channel
- const presenceMessage = await channel.presence.get();
- console.log(presenceMessage);
-
- // Querying history
- const history = await channel.history({ limit: 25 });
- console.log(await history.current());
-
- // Getting the status of a channel
- const channelDetails = await channel.status();
- console.log(channelDetails);
-
- // Requesting a token
- const token = await client.auth.requestToken(tokenParams);
-
- // Creating a token request
- const tokenRequest = await client.auth.createTokenRequest();
-
- // Fetching your application's stats
- const stats = await client.stats();
- console.log(stats);
-
- // Fetching the Ably service time
- const time = await client.time();
- console.log(`Ably service time: ${time}`);
-
- client.close();
-};
-
-ablyRestPromiseExample();
+const time = await client.time(); // time is in ms since epoch
```
## Delta Plugin
diff --git a/ably.d.ts b/ably.d.ts
index a0f9bc8142..1b21c736ab 100644
--- a/ably.d.ts
+++ b/ably.d.ts
@@ -4,3812 +4,2781 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
- * Type definitions for Ably Realtime and REST client library.
+ * You are currently viewing the default variant of the Ably JavaScript Client Library SDK. View the modular variant {@link modular | here}.
+ *
+ * To get started with the Ably JavaScript Client Library SDK, follow the [Quickstart Guide](https://ably.com/docs/quick-start-guide) or view the introductions to the [realtime](https://ably.com/docs/realtime/usage) and [REST](https://ably.com/docs/rest/usage) interfaces.
+ *
+ * @module
*/
-declare namespace Types {
+
+/**
+ * The `ChannelStates` namespace describes the possible values of the {@link ChannelState} type.
+ */
+declare namespace ChannelStates {
/**
- * The `ChannelState` namespace describes the possible values of the {@link ChannelState:type} type.
+ * The channel has been initialized but no attach has yet been attempted.
*/
- namespace ChannelState {
- /**
- * The channel has been initialized but no attach has yet been attempted.
- */
- type INITIALIZED = 'initialized';
- /**
- * An attach has been initiated by sending a request to Ably. This is a transient state, followed either by a transition to `ATTACHED`, `SUSPENDED`, or `FAILED`.
- */
- type ATTACHING = 'attaching';
- /**
- * The attach has succeeded. In the `ATTACHED` state a client may publish and subscribe to messages, or be present on the channel.
- */
- type ATTACHED = 'attached';
- /**
- * A detach has been initiated on an `ATTACHED` channel by sending a request to Ably. This is a transient state, followed either by a transition to `DETACHED` or `FAILED`.
- */
- type DETACHING = 'detaching';
- /**
- * The channel, having previously been `ATTACHED`, has been detached by the user.
- */
- type DETACHED = 'detached';
- /**
- * The channel, having previously been `ATTACHED`, has lost continuity, usually due to the client being disconnected from Ably for longer than two minutes. It will automatically attempt to reattach as soon as connectivity is restored.
- */
- type SUSPENDED = 'suspended';
- /**
- * An indefinite failure condition. This state is entered if a channel error has been received from the Ably service, such as an attempt to attach without the necessary access rights.
- */
- type FAILED = 'failed';
- }
+ type INITIALIZED = 'initialized';
+ /**
+ * An attach has been initiated by sending a request to Ably. This is a transient state, followed either by a transition to `ATTACHED`, `SUSPENDED`, or `FAILED`.
+ */
+ type ATTACHING = 'attaching';
+ /**
+ * The attach has succeeded. In the `ATTACHED` state a client may publish and subscribe to messages, or be present on the channel.
+ */
+ type ATTACHED = 'attached';
+ /**
+ * A detach has been initiated on an `ATTACHED` channel by sending a request to Ably. This is a transient state, followed either by a transition to `DETACHED` or `FAILED`.
+ */
+ type DETACHING = 'detaching';
+ /**
+ * The channel, having previously been `ATTACHED`, has been detached by the user.
+ */
+ type DETACHED = 'detached';
+ /**
+ * The channel, having previously been `ATTACHED`, has lost continuity, usually due to the client being disconnected from Ably for longer than two minutes. It will automatically attempt to reattach as soon as connectivity is restored.
+ */
+ type SUSPENDED = 'suspended';
/**
- * Describes the possible states of a {@link ChannelBase} or {@link RealtimeChannelBase} object.
+ * An indefinite failure condition. This state is entered if a channel error has been received from the Ably service, such as an attempt to attach without the necessary access rights.
*/
- type ChannelState =
- | ChannelState.FAILED
- | ChannelState.INITIALIZED
- | ChannelState.SUSPENDED
- | ChannelState.ATTACHED
- | ChannelState.ATTACHING
- | ChannelState.DETACHED
- | ChannelState.DETACHING;
+ type FAILED = 'failed';
+}
+/**
+ * Describes the possible states of a {@link Channel} or {@link RealtimeChannel} object.
+ */
+export type ChannelState =
+ | ChannelStates.FAILED
+ | ChannelStates.INITIALIZED
+ | ChannelStates.SUSPENDED
+ | ChannelStates.ATTACHED
+ | ChannelStates.ATTACHING
+ | ChannelStates.DETACHED
+ | ChannelStates.DETACHING;
+/**
+ * The `ChannelEvents` namespace describes the possible values of the {@link ChannelEvent} type.
+ */
+declare namespace ChannelEvents {
/**
- * The `ChannelEvent` namespace describes the possible values of the {@link ChannelEvent:type} type.
+ * The channel has been initialized but no attach has yet been attempted.
*/
- namespace ChannelEvent {
- /**
- * The channel has been initialized but no attach has yet been attempted.
- */
- type INITIALIZED = 'initialized';
- /**
- * An attach has been initiated by sending a request to Ably. This is a transient state, followed either by a transition to `ATTACHED`, `SUSPENDED`, or `FAILED`.
- */
- type ATTACHING = 'attaching';
- /**
- * The attach has succeeded. In the `ATTACHED` state a client may publish and subscribe to messages, or be present on the channel.
- */
- type ATTACHED = 'attached';
- /**
- * A detach has been initiated on an `ATTACHED` channel by sending a request to Ably. This is a transient state, followed either by a transition to `DETACHED` or `FAILED`.
- */
- type DETACHING = 'detaching';
- /**
- * The channel, having previously been `ATTACHED`, has been detached by the user.
- */
- type DETACHED = 'detached';
- /**
- * The channel, having previously been `ATTACHED`, has lost continuity, usually due to the client being disconnected from Ably for longer than two minutes. It will automatically attempt to reattach as soon as connectivity is restored.
- */
- type SUSPENDED = 'suspended';
- /**
- * An indefinite failure condition. This state is entered if a channel error has been received from the Ably service, such as an attempt to attach without the necessary access rights.
- */
- type FAILED = 'failed';
- /**
- * An event for changes to channel conditions that do not result in a change in {@link ChannelState}.
- */
- type UPDATE = 'update';
- }
+ type INITIALIZED = 'initialized';
/**
- * Describes the events emitted by a {@link ChannelBase} or {@link RealtimeChannelBase} object. An event is either an `UPDATE` or a {@link ChannelState}.
+ * An attach has been initiated by sending a request to Ably. This is a transient state, followed either by a transition to `ATTACHED`, `SUSPENDED`, or `FAILED`.
*/
- type ChannelEvent =
- | ChannelEvent.FAILED
- | ChannelEvent.INITIALIZED
- | ChannelEvent.SUSPENDED
- | ChannelEvent.ATTACHED
- | ChannelEvent.ATTACHING
- | ChannelEvent.DETACHED
- | ChannelEvent.DETACHING
- | ChannelEvent.UPDATE;
+ type ATTACHING = 'attaching';
+ /**
+ * The attach has succeeded. In the `ATTACHED` state a client may publish and subscribe to messages, or be present on the channel.
+ */
+ type ATTACHED = 'attached';
+ /**
+ * A detach has been initiated on an `ATTACHED` channel by sending a request to Ably. This is a transient state, followed either by a transition to `DETACHED` or `FAILED`.
+ */
+ type DETACHING = 'detaching';
+ /**
+ * The channel, having previously been `ATTACHED`, has been detached by the user.
+ */
+ type DETACHED = 'detached';
+ /**
+ * The channel, having previously been `ATTACHED`, has lost continuity, usually due to the client being disconnected from Ably for longer than two minutes. It will automatically attempt to reattach as soon as connectivity is restored.
+ */
+ type SUSPENDED = 'suspended';
+ /**
+ * An indefinite failure condition. This state is entered if a channel error has been received from the Ably service, such as an attempt to attach without the necessary access rights.
+ */
+ type FAILED = 'failed';
+ /**
+ * An event for changes to channel conditions that do not result in a change in {@link ChannelState}.
+ */
+ type UPDATE = 'update';
+}
+/**
+ * Describes the events emitted by a {@link Channel} or {@link RealtimeChannel} object. An event is either an `UPDATE` or a {@link ChannelState}.
+ */
+export type ChannelEvent =
+ | ChannelEvents.FAILED
+ | ChannelEvents.INITIALIZED
+ | ChannelEvents.SUSPENDED
+ | ChannelEvents.ATTACHED
+ | ChannelEvents.ATTACHING
+ | ChannelEvents.DETACHED
+ | ChannelEvents.DETACHING
+ | ChannelEvents.UPDATE;
+/**
+ * The `ConnectionStates` namespace describes the possible values of the {@link ConnectionState} type.
+ */
+declare namespace ConnectionStates {
/**
- * The `ConnectionState` namespace describes the possible values of the {@link ConnectionState:type} type.
+ * A connection with this state has been initialized but no connection has yet been attempted.
*/
- namespace ConnectionState {
- /**
- * A connection with this state has been initialized but no connection has yet been attempted.
- */
- type INITIALIZED = 'initialized';
- /**
- * A connection attempt has been initiated. The connecting state is entered as soon as the library has completed initialization, and is reentered each time connection is re-attempted following disconnection.
- */
- type CONNECTING = 'connecting';
- /**
- * A connection exists and is active.
- */
- type CONNECTED = 'connected';
- /**
- * A temporary failure condition. No current connection exists because there is no network connectivity or no host is available. The disconnected state is entered if an established connection is dropped, or if a connection attempt was unsuccessful. In the disconnected state the library will periodically attempt to open a new connection (approximately every 15 seconds), anticipating that the connection will be re-established soon and thus connection and channel continuity will be possible. In this state, developers can continue to publish messages as they are automatically placed in a local queue, to be sent as soon as a connection is reestablished. Messages published by other clients while this client is disconnected will be delivered to it upon reconnection, so long as the connection was resumed within 2 minutes. After 2 minutes have elapsed, recovery is no longer possible and the connection will move to the `SUSPENDED` state.
- */
- type DISCONNECTED = 'disconnected';
- /**
- * A long term failure condition. No current connection exists because there is no network connectivity or no host is available. The suspended state is entered after a failed connection attempt if there has then been no connection for a period of two minutes. In the suspended state, the library will periodically attempt to open a new connection every 30 seconds. Developers are unable to publish messages in this state. A new connection attempt can also be triggered by an explicit call to {@link ConnectionBase.connect | `connect()`}. Once the connection has been re-established, channels will be automatically re-attached. The client has been disconnected for too long for them to resume from where they left off, so if it wants to catch up on messages published by other clients while it was disconnected, it needs to use the [History API](https://ably.com/docs/realtime/history).
- */
- type SUSPENDED = 'suspended';
- /**
- * An explicit request by the developer to close the connection has been sent to the Ably service. If a reply is not received from Ably within a short period of time, the connection is forcibly terminated and the connection state becomes `CLOSED`.
- */
- type CLOSING = 'closing';
- /**
- * The connection has been explicitly closed by the client. In the closed state, no reconnection attempts are made automatically by the library, and clients may not publish messages. No connection state is preserved by the service or by the library. A new connection attempt can be triggered by an explicit call to {@link ConnectionBase.connect | `connect()`}, which results in a new connection.
- */
- type CLOSED = 'closed';
- /**
- * This state is entered if the client library encounters a failure condition that it cannot recover from. This may be a fatal connection error received from the Ably service, for example an attempt to connect with an incorrect API key, or a local terminal error, for example the token in use has expired and the library does not have any way to renew it. In the failed state, no reconnection attempts are made automatically by the library, and clients may not publish messages. A new connection attempt can be triggered by an explicit call to {@link ConnectionBase.connect | `connect()`}.
- */
- type FAILED = 'failed';
- }
+ type INITIALIZED = 'initialized';
+ /**
+ * A connection attempt has been initiated. The connecting state is entered as soon as the library has completed initialization, and is reentered each time connection is re-attempted following disconnection.
+ */
+ type CONNECTING = 'connecting';
+ /**
+ * A connection exists and is active.
+ */
+ type CONNECTED = 'connected';
+ /**
+ * A temporary failure condition. No current connection exists because there is no network connectivity or no host is available. The disconnected state is entered if an established connection is dropped, or if a connection attempt was unsuccessful. In the disconnected state the library will periodically attempt to open a new connection (approximately every 15 seconds), anticipating that the connection will be re-established soon and thus connection and channel continuity will be possible. In this state, developers can continue to publish messages as they are automatically placed in a local queue, to be sent as soon as a connection is reestablished. Messages published by other clients while this client is disconnected will be delivered to it upon reconnection, so long as the connection was resumed within 2 minutes. After 2 minutes have elapsed, recovery is no longer possible and the connection will move to the `SUSPENDED` state.
+ */
+ type DISCONNECTED = 'disconnected';
+ /**
+ * A long term failure condition. No current connection exists because there is no network connectivity or no host is available. The suspended state is entered after a failed connection attempt if there has then been no connection for a period of two minutes. In the suspended state, the library will periodically attempt to open a new connection every 30 seconds. Developers are unable to publish messages in this state. A new connection attempt can also be triggered by an explicit call to {@link Connection.connect | `connect()`}. Once the connection has been re-established, channels will be automatically re-attached. The client has been disconnected for too long for them to resume from where they left off, so if it wants to catch up on messages published by other clients while it was disconnected, it needs to use the [History API](https://ably.com/docs/realtime/history).
+ */
+ type SUSPENDED = 'suspended';
+ /**
+ * An explicit request by the developer to close the connection has been sent to the Ably service. If a reply is not received from Ably within a short period of time, the connection is forcibly terminated and the connection state becomes `CLOSED`.
+ */
+ type CLOSING = 'closing';
+ /**
+ * The connection has been explicitly closed by the client. In the closed state, no reconnection attempts are made automatically by the library, and clients may not publish messages. No connection state is preserved by the service or by the library. A new connection attempt can be triggered by an explicit call to {@link Connection.connect | `connect()`}, which results in a new connection.
+ */
+ type CLOSED = 'closed';
/**
- * Describes the realtime {@link ConnectionBase} object states.
+ * This state is entered if the client library encounters a failure condition that it cannot recover from. This may be a fatal connection error received from the Ably service, for example an attempt to connect with an incorrect API key, or a local terminal error, for example the token in use has expired and the library does not have any way to renew it. In the failed state, no reconnection attempts are made automatically by the library, and clients may not publish messages. A new connection attempt can be triggered by an explicit call to {@link Connection.connect | `connect()`}.
*/
- type ConnectionState =
- | ConnectionState.INITIALIZED
- | ConnectionState.CONNECTED
- | ConnectionState.CONNECTING
- | ConnectionState.DISCONNECTED
- | ConnectionState.SUSPENDED
- | ConnectionState.CLOSED
- | ConnectionState.CLOSING
- | ConnectionState.FAILED;
+ type FAILED = 'failed';
+}
+/**
+ * Describes the realtime {@link Connection} object states.
+ */
+export type ConnectionState =
+ | ConnectionStates.INITIALIZED
+ | ConnectionStates.CONNECTED
+ | ConnectionStates.CONNECTING
+ | ConnectionStates.DISCONNECTED
+ | ConnectionStates.SUSPENDED
+ | ConnectionStates.CLOSED
+ | ConnectionStates.CLOSING
+ | ConnectionStates.FAILED;
+/**
+ * The `ConnectionEvents` namespace describes the possible values of the {@link ConnectionEvent} type.
+ */
+declare namespace ConnectionEvents {
/**
- * The `ConnectionEvent` namespace describes the possible values of the {@link ConnectionEvent:type} type.
+ * A connection with this state has been initialized but no connection has yet been attempted.
*/
- namespace ConnectionEvent {
- /**
- * A connection with this state has been initialized but no connection has yet been attempted.
- */
- type INITIALIZED = 'initialized';
- /**
- * A connection attempt has been initiated. The connecting state is entered as soon as the library has completed initialization, and is reentered each time connection is re-attempted following disconnection.
- */
- type CONNECTING = 'connecting';
- /**
- * A connection exists and is active.
- */
- type CONNECTED = 'connected';
- /**
- * A temporary failure condition. No current connection exists because there is no network connectivity or no host is available. The disconnected state is entered if an established connection is dropped, or if a connection attempt was unsuccessful. In the disconnected state the library will periodically attempt to open a new connection (approximately every 15 seconds), anticipating that the connection will be re-established soon and thus connection and channel continuity will be possible. In this state, developers can continue to publish messages as they are automatically placed in a local queue, to be sent as soon as a connection is reestablished. Messages published by other clients while this client is disconnected will be delivered to it upon reconnection, so long as the connection was resumed within 2 minutes. After 2 minutes have elapsed, recovery is no longer possible and the connection will move to the `SUSPENDED` state.
- */
- type DISCONNECTED = 'disconnected';
- /**
- * A long term failure condition. No current connection exists because there is no network connectivity or no host is available. The suspended state is entered after a failed connection attempt if there has then been no connection for a period of two minutes. In the suspended state, the library will periodically attempt to open a new connection every 30 seconds. Developers are unable to publish messages in this state. A new connection attempt can also be triggered by an explicit call to {@link ConnectionBase.connect | `connect()`}. Once the connection has been re-established, channels will be automatically re-attached. The client has been disconnected for too long for them to resume from where they left off, so if it wants to catch up on messages published by other clients while it was disconnected, it needs to use the [History API](https://ably.com/docs/realtime/history).
- */
- type SUSPENDED = 'suspended';
- /**
- * An explicit request by the developer to close the connection has been sent to the Ably service. If a reply is not received from Ably within a short period of time, the connection is forcibly terminated and the connection state becomes `CLOSED`.
- */
- type CLOSING = 'closing';
- /**
- * The connection has been explicitly closed by the client. In the closed state, no reconnection attempts are made automatically by the library, and clients may not publish messages. No connection state is preserved by the service or by the library. A new connection attempt can be triggered by an explicit call to {@link ConnectionBase.connect | `connect()`}, which results in a new connection.
- */
- type CLOSED = 'closed';
- /**
- * This state is entered if the client library encounters a failure condition that it cannot recover from. This may be a fatal connection error received from the Ably service, for example an attempt to connect with an incorrect API key, or a local terminal error, for example the token in use has expired and the library does not have any way to renew it. In the failed state, no reconnection attempts are made automatically by the library, and clients may not publish messages. A new connection attempt can be triggered by an explicit call to {@link ConnectionBase.connect | `connect()`}.
- */
- type FAILED = 'failed';
- /**
- * An event for changes to connection conditions for which the {@link ConnectionState} does not change.
- */
- type UPDATE = 'update';
- }
+ type INITIALIZED = 'initialized';
+ /**
+ * A connection attempt has been initiated. The connecting state is entered as soon as the library has completed initialization, and is reentered each time connection is re-attempted following disconnection.
+ */
+ type CONNECTING = 'connecting';
+ /**
+ * A connection exists and is active.
+ */
+ type CONNECTED = 'connected';
+ /**
+ * A temporary failure condition. No current connection exists because there is no network connectivity or no host is available. The disconnected state is entered if an established connection is dropped, or if a connection attempt was unsuccessful. In the disconnected state the library will periodically attempt to open a new connection (approximately every 15 seconds), anticipating that the connection will be re-established soon and thus connection and channel continuity will be possible. In this state, developers can continue to publish messages as they are automatically placed in a local queue, to be sent as soon as a connection is reestablished. Messages published by other clients while this client is disconnected will be delivered to it upon reconnection, so long as the connection was resumed within 2 minutes. After 2 minutes have elapsed, recovery is no longer possible and the connection will move to the `SUSPENDED` state.
+ */
+ type DISCONNECTED = 'disconnected';
+ /**
+ * A long term failure condition. No current connection exists because there is no network connectivity or no host is available. The suspended state is entered after a failed connection attempt if there has then been no connection for a period of two minutes. In the suspended state, the library will periodically attempt to open a new connection every 30 seconds. Developers are unable to publish messages in this state. A new connection attempt can also be triggered by an explicit call to {@link Connection.connect | `connect()`}. Once the connection has been re-established, channels will be automatically re-attached. The client has been disconnected for too long for them to resume from where they left off, so if it wants to catch up on messages published by other clients while it was disconnected, it needs to use the [History API](https://ably.com/docs/realtime/history).
+ */
+ type SUSPENDED = 'suspended';
+ /**
+ * An explicit request by the developer to close the connection has been sent to the Ably service. If a reply is not received from Ably within a short period of time, the connection is forcibly terminated and the connection state becomes `CLOSED`.
+ */
+ type CLOSING = 'closing';
+ /**
+ * The connection has been explicitly closed by the client. In the closed state, no reconnection attempts are made automatically by the library, and clients may not publish messages. No connection state is preserved by the service or by the library. A new connection attempt can be triggered by an explicit call to {@link Connection.connect | `connect()`}, which results in a new connection.
+ */
+ type CLOSED = 'closed';
/**
- * Describes the events emitted by a {@link ConnectionBase} object. An event is either an `UPDATE` or a {@link ConnectionState}.
+ * This state is entered if the client library encounters a failure condition that it cannot recover from. This may be a fatal connection error received from the Ably service, for example an attempt to connect with an incorrect API key, or a local terminal error, for example the token in use has expired and the library does not have any way to renew it. In the failed state, no reconnection attempts are made automatically by the library, and clients may not publish messages. A new connection attempt can be triggered by an explicit call to {@link Connection.connect | `connect()`}.
*/
- type ConnectionEvent =
- | ConnectionEvent.INITIALIZED
- | ConnectionEvent.CONNECTED
- | ConnectionEvent.CONNECTING
- | ConnectionEvent.DISCONNECTED
- | ConnectionEvent.SUSPENDED
- | ConnectionEvent.CLOSED
- | ConnectionEvent.CLOSING
- | ConnectionEvent.FAILED
- | ConnectionEvent.UPDATE;
+ type FAILED = 'failed';
+ /**
+ * An event for changes to connection conditions for which the {@link ConnectionState} does not change.
+ */
+ type UPDATE = 'update';
+}
+/**
+ * Describes the events emitted by a {@link Connection} object. An event is either an `UPDATE` or a {@link ConnectionState}.
+ */
+export type ConnectionEvent =
+ | ConnectionEvents.INITIALIZED
+ | ConnectionEvents.CONNECTED
+ | ConnectionEvents.CONNECTING
+ | ConnectionEvents.DISCONNECTED
+ | ConnectionEvents.SUSPENDED
+ | ConnectionEvents.CLOSED
+ | ConnectionEvents.CLOSING
+ | ConnectionEvents.FAILED
+ | ConnectionEvents.UPDATE;
+/**
+ * The `PresenceActions` namespace describes the possible values of the {@link PresenceAction} type.
+ */
+declare namespace PresenceActions {
/**
- * The `PresenceAction` namespace describes the possible values of the {@link PresenceAction:type} type.
+ * A member is not present in the channel.
*/
- namespace PresenceAction {
- /**
- * A member is not present in the channel.
- */
- type ABSENT = 'absent';
- /**
- * When subscribing to presence events on a channel that already has members present, this event is emitted for every member already present on the channel before the subscribe listener was registered.
- */
- type PRESENT = 'present';
- /**
- * A new member has entered the channel.
- */
- type ENTER = 'enter';
- /**
- * A member who was present has now left the channel. This may be a result of an explicit request to leave or implicitly when detaching from the channel. Alternatively, if a member's connection is abruptly disconnected and they do not resume their connection within a minute, Ably treats this as a leave event as the client is no longer present.
- */
- type LEAVE = 'leave';
- /**
- * An already present member has updated their member data. Being notified of member data updates can be very useful, for example, it can be used to update the status of a user when they are typing a message.
- */
- type UPDATE = 'update';
- }
+ type ABSENT = 'absent';
+ /**
+ * When subscribing to presence events on a channel that already has members present, this event is emitted for every member already present on the channel before the subscribe listener was registered.
+ */
+ type PRESENT = 'present';
+ /**
+ * A new member has entered the channel.
+ */
+ type ENTER = 'enter';
+ /**
+ * A member who was present has now left the channel. This may be a result of an explicit request to leave or implicitly when detaching from the channel. Alternatively, if a member's connection is abruptly disconnected and they do not resume their connection within a minute, Ably treats this as a leave event as the client is no longer present.
+ */
+ type LEAVE = 'leave';
/**
- * Describes the possible actions members in the presence set can emit.
+ * An already present member has updated their member data. Being notified of member data updates can be very useful, for example, it can be used to update the status of a user when they are typing a message.
*/
- type PresenceAction =
- | PresenceAction.ABSENT
- | PresenceAction.PRESENT
- | PresenceAction.ENTER
- | PresenceAction.LEAVE
- | PresenceAction.UPDATE;
+ type UPDATE = 'update';
+}
+/**
+ * Describes the possible actions members in the presence set can emit.
+ */
+export type PresenceAction =
+ | PresenceActions.ABSENT
+ | PresenceActions.PRESENT
+ | PresenceActions.ENTER
+ | PresenceActions.LEAVE
+ | PresenceActions.UPDATE;
+/**
+ * The `StatsIntervalGranularities` namespace describes the possible values of the {@link StatsIntervalGranularity} type.
+ */
+declare namespace StatsIntervalGranularities {
/**
- * The `StatsIntervalGranularity` namespace describes the possible values of the {@link StatsIntervalGranularity:type} type.
+ * Interval unit over which statistics are gathered as minutes.
*/
- namespace StatsIntervalGranularity {
- /**
- * Interval unit over which statistics are gathered as minutes.
- */
- type MINUTE = 'minute';
- /**
- * Interval unit over which statistics are gathered as hours.
- */
- type HOUR = 'hour';
- /**
- * Interval unit over which statistics are gathered as days.
- */
- type DAY = 'day';
- /**
- * Interval unit over which statistics are gathered as months.
- */
- type MONTH = 'month';
- }
+ type MINUTE = 'minute';
+ /**
+ * Interval unit over which statistics are gathered as hours.
+ */
+ type HOUR = 'hour';
+ /**
+ * Interval unit over which statistics are gathered as days.
+ */
+ type DAY = 'day';
/**
- * Describes the interval unit over which statistics are gathered.
+ * Interval unit over which statistics are gathered as months.
*/
- type StatsIntervalGranularity =
- | StatsIntervalGranularity.MINUTE
- | StatsIntervalGranularity.HOUR
- | StatsIntervalGranularity.DAY
- | StatsIntervalGranularity.MONTH;
+ type MONTH = 'month';
+}
+/**
+ * Describes the interval unit over which statistics are gathered.
+ */
+export type StatsIntervalGranularity =
+ | StatsIntervalGranularities.MINUTE
+ | StatsIntervalGranularities.HOUR
+ | StatsIntervalGranularities.DAY
+ | StatsIntervalGranularities.MONTH;
+/**
+ * HTTP Methods, used internally.
+ */
+declare namespace HTTPMethods {
/**
- * HTTP Methods, used internally.
+ * Represents a HTTP POST request.
*/
- namespace HTTPMethods {
- /**
- * Represents a HTTP POST request.
- */
- type POST = 'POST';
- /**
- * Represents a HTTP GET request.
- */
- type GET = 'GET';
- }
+ type POST = 'POST';
/**
- * HTTP Methods, used internally.
+ * Represents a HTTP GET request.
*/
- type HTTPMethods = HTTPMethods.GET | HTTPMethods.POST;
+ type GET = 'GET';
+}
+/**
+ * HTTP Methods, used internally.
+ */
+export type HTTPMethod = HTTPMethods.GET | HTTPMethods.POST;
+/**
+ * A type which specifies the valid transport names. [See here](https://faqs.ably.com/which-transports-are-supported) for more information.
+ */
+export type Transport = 'web_socket' | 'xhr_polling' | 'comet';
+
+/**
+ * Contains the details of a {@link Channel} or {@link RealtimeChannel} object such as its ID and {@link ChannelStatus}.
+ */
+export interface ChannelDetails {
+ /**
+ * The identifier of the channel.
+ */
+ channelId: string;
/**
- * A type which specifies the valid transport names. [See here](https://faqs.ably.com/which-transports-are-supported) for more information.
+ * A {@link ChannelStatus} object.
*/
- type Transport = 'web_socket' | 'xhr_streaming' | 'xhr_polling' | 'jsonp' | 'comet';
+ status: ChannelStatus;
+}
+/**
+ * Contains the status of a {@link Channel} or {@link RealtimeChannel} object such as whether it is active and its {@link ChannelOccupancy}.
+ */
+export interface ChannelStatus {
/**
- * Contains the details of a {@link ChannelBase} or {@link RealtimeChannelBase} object such as its ID and {@link ChannelStatus}.
+ * If `true`, the channel is active, otherwise `false`.
*/
- interface ChannelDetails {
- /**
- * The identifier of the channel.
- */
- channelId: string;
- /**
- * A {@link ChannelStatus} object.
- */
- status: ChannelStatus;
- }
+ isActive: boolean;
+ /**
+ * A {@link ChannelOccupancy} object.
+ */
+ occupancy: ChannelOccupancy;
+}
+/**
+ * Contains the metrics of a {@link Channel} or {@link RealtimeChannel} object.
+ */
+export interface ChannelOccupancy {
/**
- * Contains the status of a {@link ChannelBase} or {@link RealtimeChannelBase} object such as whether it is active and its {@link ChannelOccupancy}.
+ * A {@link ChannelMetrics} object.
*/
- interface ChannelStatus {
- /**
- * If `true`, the channel is active, otherwise `false`.
- */
- isActive: boolean;
- /**
- * A {@link ChannelOccupancy} object.
- */
- occupancy: ChannelOccupancy;
- }
+ metrics: ChannelMetrics;
+}
+/**
+ * Contains the metrics associated with a {@link Channel} or {@link RealtimeChannel}, such as the number of publishers, subscribers and connections it has.
+ */
+export interface ChannelMetrics {
/**
- * Contains the metrics of a {@link ChannelBase} or {@link RealtimeChannelBase} object.
+ * The number of realtime connections attached to the channel.
*/
- interface ChannelOccupancy {
- /**
- * A {@link ChannelMetrics} object.
- */
- metrics: ChannelMetrics;
- }
+ connections: number;
+ /**
+ * The number of realtime connections attached to the channel with permission to enter the presence set, regardless of whether or not they have entered it. This requires the `presence` capability and for a client to not have specified a {@link ChannelMode} flag that excludes {@link ChannelModes.PRESENCE}.
+ */
+ presenceConnections: number;
+ /**
+ * The number of members in the presence set of the channel.
+ */
+ presenceMembers: number;
+ /**
+ * The number of realtime attachments receiving presence messages on the channel. This requires the `subscribe` capability and for a client to not have specified a {@link ChannelMode} flag that excludes {@link ChannelModes.PRESENCE_SUBSCRIBE}.
+ */
+ presenceSubscribers: number;
+ /**
+ * The number of realtime attachments permitted to publish messages to the channel. This requires the `publish` capability and for a client to not have specified a {@link ChannelMode} flag that excludes {@link ChannelModes.PUBLISH}.
+ */
+ publishers: number;
+ /**
+ * The number of realtime attachments receiving messages on the channel. This requires the `subscribe` capability and for a client to not have specified a {@link ChannelMode} flag that excludes {@link ChannelModes.SUBSCRIBE}.
+ */
+ subscribers: number;
+}
+/**
+ * Passes additional client-specific properties to the REST constructor or the Realtime constructor.
+ */
+export interface ClientOptions extends AuthOptions {
/**
- * Contains the metrics associated with a {@link ChannelBase} or {@link RealtimeChannelBase}, such as the number of publishers, subscribers and connections it has.
+ * When `true`, the client connects to Ably as soon as it is instantiated. You can set this to `false` and explicitly connect to Ably using the {@link Connection.connect | `connect()`} method. The default is `true`.
+ *
+ * @defaultValue `true`
*/
- interface ChannelMetrics {
- /**
- * The number of realtime connections attached to the channel.
- */
- connections: number;
- /**
- * The number of realtime connections attached to the channel with permission to enter the presence set, regardless of whether or not they have entered it. This requires the `presence` capability and for a client to not have specified a {@link ChannelMode} flag that excludes {@link ChannelMode.PRESENCE}.
- */
- presenceConnections: number;
- /**
- * The number of members in the presence set of the channel.
- */
- presenceMembers: number;
- /**
- * The number of realtime attachments receiving presence messages on the channel. This requires the `subscribe` capability and for a client to not have specified a {@link ChannelMode} flag that excludes {@link ChannelMode.PRESENCE_SUBSCRIBE}.
- */
- presenceSubscribers: number;
- /**
- * The number of realtime attachments permitted to publish messages to the channel. This requires the `publish` capability and for a client to not have specified a {@link ChannelMode} flag that excludes {@link ChannelMode.PUBLISH}.
- */
- publishers: number;
- /**
- * The number of realtime attachments receiving messages on the channel. This requires the `subscribe` capability and for a client to not have specified a {@link ChannelMode} flag that excludes {@link ChannelMode.SUBSCRIBE}.
- */
- subscribers: number;
- }
+ autoConnect?: boolean;
/**
- * Passes additional client-specific properties to the REST {@link RestBase.constructor | `constructor()`} or the Realtime {@link RealtimeBase.constructor | `constructor()`}.
+ * When a {@link TokenParams} object is provided, it overrides the client library defaults when issuing new Ably Tokens or Ably {@link TokenRequest | `TokenRequest`s}.
*/
- interface ClientOptions extends AuthOptions {
- /**
- * When `true`, the client connects to Ably as soon as it is instantiated. You can set this to `false` and explicitly connect to Ably using the {@link ConnectionBase.connect | `connect()`} method. The default is `true`.
- *
- * @defaultValue `true`
- */
- autoConnect?: boolean;
+ defaultTokenParams?: TokenParams;
- /**
- * When a {@link TokenParams} object is provided, it overrides the client library defaults when issuing new Ably Tokens or Ably {@link TokenRequest | `TokenRequest`s}.
- */
- defaultTokenParams?: TokenParams;
+ /**
+ * If `false`, prevents messages originating from this connection being echoed back on the same connection. The default is `true`.
+ *
+ * @defaultValue `true`
+ */
+ echoMessages?: boolean;
- /**
- * If `false`, prevents messages originating from this connection being echoed back on the same connection. The default is `true`.
- *
- * @defaultValue `true`
- */
- echoMessages?: boolean;
+ /**
+ * Enables a [custom environment](https://ably.com/docs/platform-customization) to be used with the Ably service.
+ */
+ environment?: string;
- /**
- * Enables a [custom environment](https://ably.com/docs/platform-customization) to be used with the Ably service.
- */
- environment?: string;
+ /**
+ * Controls the verbosity of the logs output from the library. Valid values are: 0 (no logs), 1 (errors only), 2 (errors plus connection and channel state changes), 3 (high-level debug output), and 4 (full debug output).
+ */
+ logLevel?: number;
- /**
- * Controls the verbosity of the logs output from the library. Valid values are: 0 (no logs), 1 (errors only), 2 (errors plus connection and channel state changes), 3 (high-level debug output), and 4 (full debug output).
- */
- logLevel?: number;
+ /**
+ * Controls the log output of the library. This is a function to handle each line of log output. If you do not set this value, then `console.log` will be used.
+ *
+ * @param msg - The log message emitted by the library.
+ */
+ logHandler?: (msg: string) => void;
- /**
- * Controls the log output of the library. This is a function to handle each line of log output. If you do not set this value, then `console.log` will be used.
- *
- * @param msg - The log message emitted by the library.
- */
- logHandler?: (msg: string) => void;
-
- /**
- * Parameters to control the log output of the library, such as the log handler and log level.
- *
- * @deprecated This property is deprecated and will be removed in a future version. Use the {@link ClientOptions.logLevel} and {@link ClientOptions.logHandler} client options instead.
- */
- log?: LogInfo;
-
- /**
- * Enables a non-default Ably port to be specified. For development environments only. The default value is 80.
- *
- * @defaultValue 80
- */
- port?: number;
-
- /**
- * If `false`, this disables the default behavior whereby the library queues messages on a connection in the disconnected or connecting states. The default behavior enables applications to submit messages immediately upon instantiating the library without having to wait for the connection to be established. Applications may use this option to disable queueing if they wish to have application-level control over the queueing. The default is `true`.
- *
- * @defaultValue `true`
- */
- queueMessages?: boolean;
-
- /**
- * Enables a non-default Ably host to be specified. For development environments only. The default value is `rest.ably.io`.
- *
- * @defaultValue `"rest.ably.io"`
- */
- restHost?: string;
-
- /**
- * Enables a non-default Ably host to be specified for realtime connections. For development environments only. The default value is `realtime.ably.io`.
- *
- * @defaultValue `"realtime.ably.io"`
- */
- realtimeHost?: string;
-
- /**
- * An array of fallback hosts to be used in the case of an error necessitating the use of an alternative host. If you have been provided a set of custom fallback hosts by Ably, please specify them here.
- *
- * @defaultValue `['a.ably-realtime.com', 'b.ably-realtime.com', 'c.ably-realtime.com', 'd.ably-realtime.com', 'e.ably-realtime.com']``
- */
- fallbackHosts?: string[];
-
- /**
- * @deprecated This property is deprecated and will be removed in a future version. Enables default fallback hosts to be used.
- */
- fallbackHostsUseDefault?: boolean;
-
- /**
- * Set of configurable options to set on the HTTP(S) agent used for REST requests.
- *
- * See the [NodeJS docs](https://nodejs.org/api/http.html#new-agentoptions) for descriptions of these options.
- */
- restAgentOptions?: {
- /**
- * See [NodeJS docs](https://nodejs.org/api/http.html#new-agentoptions)
- */
- maxSockets?: number;
- /**
- * See [NodeJS docs](https://nodejs.org/api/http.html#new-agentoptions)
- */
- keepAlive?: boolean;
- };
-
- /**
- * Enables a connection to inherit the state of a previous connection that may have existed under a different instance of the Realtime library. This might typically be used by clients of the browser library to ensure connection state can be preserved when the user refreshes the page. A recovery key string can be explicitly provided, or alternatively if a callback function is provided, the client library will automatically persist the recovery key between page reloads and call the callback when the connection is recoverable. The callback is then responsible for confirming whether the connection should be recovered or not. See [connection state recovery](https://ably.com/docs/realtime/connection/#connection-state-recovery) for further information.
- */
- recover?: string | recoverConnectionCallback;
-
- /**
- * When `false`, the client will use an insecure connection. The default is `true`, meaning a TLS connection will be used to connect to Ably.
- *
- * @defaultValue `true`
- */
- tls?: boolean;
-
- /**
- * Enables a non-default Ably TLS port to be specified. For development environments only. The default value is 443.
- *
- * @defaultValue 443
- */
- tlsPort?: number;
-
- /**
- * When `true`, the more efficient MsgPack binary encoding is used. When `false`, JSON text encoding is used. The default is `true` for Node.js, and `false` for all other platforms.
- *
- * @defaultValue `true` for Node.js, `false` for all other platforms
- */
- useBinaryProtocol?: boolean;
-
- /**
- * Override the URL used by the realtime client to check if the internet is available.
- *
- * In the event of a failure to connect to the primary endpoint, the client will send a
- * GET request to this URL to check if the internet is available. If this request returns
- * a success response the client will attempt to connect to a fallback host.
- */
- connectivityCheckUrl?: string;
-
- /**
- * Disable the check used by the realtime client to check if the internet
- * is available before connecting to a fallback host.
- */
- disableConnectivityCheck?: boolean;
+ /**
+ * Enables a non-default Ably port to be specified. For development environments only. The default value is 80.
+ *
+ * @defaultValue 80
+ */
+ port?: number;
- /**
- * If the connection is still in the {@link ConnectionState.DISCONNECTED} state after this delay in milliseconds, the client library will attempt to reconnect automatically. The default is 15 seconds.
- *
- * @defaultValue 15s
- */
- disconnectedRetryTimeout?: number;
+ /**
+ * If `false`, this disables the default behavior whereby the library queues messages on a connection in the disconnected or connecting states. The default behavior enables applications to submit messages immediately upon instantiating the library without having to wait for the connection to be established. Applications may use this option to disable queueing if they wish to have application-level control over the queueing. The default is `true`.
+ *
+ * @defaultValue `true`
+ */
+ queueMessages?: boolean;
- /**
- * When the connection enters the {@link ConnectionState.SUSPENDED} state, after this delay in milliseconds, if the state is still {@link ConnectionState.SUSPENDED | `SUSPENDED`}, the client library attempts to reconnect automatically. The default is 30 seconds.
- *
- * @defaultValue 30s
- */
- suspendedRetryTimeout?: number;
+ /**
+ * Enables a non-default Ably host to be specified. For development environments only. The default value is `rest.ably.io`.
+ *
+ * @defaultValue `"rest.ably.io"`
+ */
+ restHost?: string;
- /**
- * When `true`, the client library will automatically send a close request to Ably whenever the `window` [`beforeunload` event](https://developer.mozilla.org/en-US/docs/Web/API/BeforeUnloadEvent) fires. By enabling this option, the close request sent to Ably ensures the connection state will not be retained and all channels associated with the channel will be detached. This is commonly used by developers who want presence leave events to fire immediately (that is, if a user navigates to another page or closes their browser, then enabling this option will result in the presence member leaving immediately). Without this option or an explicit call to the `close` method of the `Connection` object, Ably expects that the abruptly disconnected connection could later be recovered and therefore does not immediately remove the user from presence. Instead, to avoid “twitchy” presence behaviour an abruptly disconnected client is removed from channels in which they are present after 15 seconds, and the connection state is retained for two minutes. Defaults to `true`.
- */
- closeOnUnload?: boolean;
+ /**
+ * Enables a non-default Ably host to be specified for realtime connections. For development environments only. The default value is `realtime.ably.io`.
+ *
+ * @defaultValue `"realtime.ably.io"`
+ */
+ realtimeHost?: string;
- /**
- * When `true`, enables idempotent publishing by assigning a unique message ID client-side, allowing the Ably servers to discard automatic publish retries following a failure such as a network fault. The default is `true`.
- *
- * @defaultValue `true`
- */
- idempotentRestPublishing?: boolean;
+ /**
+ * An array of fallback hosts to be used in the case of an error necessitating the use of an alternative host. If you have been provided a set of custom fallback hosts by Ably, please specify them here.
+ *
+ * @defaultValue `['a.ably-realtime.com', 'b.ably-realtime.com', 'c.ably-realtime.com', 'd.ably-realtime.com', 'e.ably-realtime.com']``
+ */
+ fallbackHosts?: string[];
+ /**
+ * Set of configurable options to set on the HTTP(S) agent used for REST requests.
+ *
+ * See the [NodeJS docs](https://nodejs.org/api/http.html#new-agentoptions) for descriptions of these options.
+ */
+ restAgentOptions?: {
/**
- * A set of key-value pairs that can be used to pass in arbitrary connection parameters, such as [`heartbeatInterval`](https://ably.com/docs/realtime/connection#heartbeats) or [`remainPresentFor`](https://ably.com/docs/realtime/presence#unstable-connections).
+ * See [NodeJS docs](https://nodejs.org/api/http.html#new-agentoptions)
*/
- transportParams?: { [k: string]: string | number };
-
+ maxSockets?: number;
/**
- * An array of transports to use, in descending order of preference. In the browser environment the available transports are: `web_socket`, `xhr`, and `jsonp`.
+ * See [NodeJS docs](https://nodejs.org/api/http.html#new-agentoptions)
*/
- transports?: Transport[];
+ keepAlive?: boolean;
+ };
- /**
- * The maximum number of fallback hosts to use as a fallback when an HTTP request to the primary host is unreachable or indicates that it is unserviceable. The default value is 3.
- *
- * @defaultValue 3
- */
- httpMaxRetryCount?: number;
+ /**
+ * Enables a connection to inherit the state of a previous connection that may have existed under a different instance of the Realtime library. This might typically be used by clients of the browser library to ensure connection state can be preserved when the user refreshes the page. A recovery key string can be explicitly provided, or alternatively if a callback function is provided, the client library will automatically persist the recovery key between page reloads and call the callback when the connection is recoverable. The callback is then responsible for confirming whether the connection should be recovered or not. See [connection state recovery](https://ably.com/docs/realtime/connection/#connection-state-recovery) for further information.
+ */
+ recover?: string | recoverConnectionCallback;
- /**
- * The maximum elapsed time in milliseconds in which fallback host retries for HTTP requests will be attempted. The default is 15 seconds.
- *
- * @defaultValue 15s
- */
- httpMaxRetryDuration?: number;
+ /**
+ * When `false`, the client will use an insecure connection. The default is `true`, meaning a TLS connection will be used to connect to Ably.
+ *
+ * @defaultValue `true`
+ */
+ tls?: boolean;
- /**
- * Timeout in milliseconds for opening a connection to Ably to initiate an HTTP request. The default is 4 seconds.
- *
- * @defaultValue 4s
- */
- httpOpenTimeout?: number;
+ /**
+ * Enables a non-default Ably TLS port to be specified. For development environments only. The default value is 443.
+ *
+ * @defaultValue 443
+ */
+ tlsPort?: number;
- /**
- * Timeout in milliseconds for a client performing a complete HTTP request to Ably, including the connection phase. The default is 10 seconds.
- *
- * @defaultValue 10s
- */
- httpRequestTimeout?: number;
+ /**
+ * When `true`, the more efficient MsgPack binary encoding is used. When `false`, JSON text encoding is used. The default is `true` for Node.js, and `false` for all other platforms.
+ *
+ * @defaultValue `true` for Node.js, `false` for all other platforms
+ */
+ useBinaryProtocol?: boolean;
- /**
- * Timeout for the wait of acknowledgement for operations performed via a realtime connection, before the client library considers a request failed and triggers a failure condition. Operations include establishing a connection with Ably, or sending a `HEARTBEAT`, `CONNECT`, `ATTACH`, `DETACH` or `CLOSE` request. It is the equivalent of `httpRequestTimeout` but for realtime operations, rather than REST. The default is 10 seconds.
- *
- * @defaultValue 10s
- */
- realtimeRequestTimeout?: number;
+ /**
+ * Override the URL used by the realtime client to check if the internet is available.
+ *
+ * In the event of a failure to connect to the primary endpoint, the client will send a
+ * GET request to this URL to check if the internet is available. If this request returns
+ * a success response the client will attempt to connect to a fallback host.
+ */
+ connectivityCheckUrl?: string;
- /**
- * A map between a plugin type and a plugin object.
- */
- plugins?: {
- /**
- * A plugin capable of decoding `vcdiff`-encoded messages. For more information on how to configure a channel to use delta encoding, see the [documentation for the `@ably-forks/vcdiff-decoder` package](https://github.com/ably-forks/vcdiff-decoder#usage).
- */
- vcdiff?: any;
- };
+ /**
+ * Disable the check used by the realtime client to check if the internet
+ * is available before connecting to a fallback host.
+ */
+ disableConnectivityCheck?: boolean;
- /**
- * The maximum message size is an attribute of an Ably account which represents the largest permitted payload size of a single message or set of messages published in a single operation. Publish requests whose payload exceeds this limit are rejected by the server. `maxMessageSize` enables the client to enforce, or further restrict, the maximum size of a single message or set of messages published via REST. The default value is `65536` (64 KiB). In the case of a realtime connection, the server may indicate the associated maximum message size on connection establishment; this value takes precedence over the client's default `maxMessageSize`.
- *
- * @defaultValue 65536
- */
- maxMessageSize?: number;
- }
+ /**
+ * If the connection is still in the {@link ConnectionStates.DISCONNECTED} state after this delay in milliseconds, the client library will attempt to reconnect automatically. The default is 15 seconds.
+ *
+ * @defaultValue 15s
+ */
+ disconnectedRetryTimeout?: number;
/**
- * Passes authentication-specific properties in authentication requests to Ably. Properties set using `AuthOptions` are used instead of the default values set when the client library is instantiated, as opposed to being merged with them.
+ * When the connection enters the {@link ConnectionStates.SUSPENDED} state, after this delay in milliseconds, if the state is still {@link ConnectionStates.SUSPENDED | `SUSPENDED`}, the client library attempts to reconnect automatically. The default is 30 seconds.
+ *
+ * @defaultValue 30s
*/
- interface AuthOptions {
- /**
- * Called when a new token is required. The role of the callback is to obtain a fresh token, one of: an Ably Token string (in plain text format); a signed {@link TokenRequest}; a {@link TokenDetails} (in JSON format); an [Ably JWT](https://ably.com/docs/core-features/authentication.ably-jwt). See [the authentication documentation](https://ably.com/docs/realtime/authentication) for details of the Ably {@link TokenRequest} format and associated API calls.
- *
- * @param data - The parameters that should be used to generate the token.
- * @param callback - A function which, upon success, the `authCallback` should call with one of: an Ably Token string (in plain text format); a signed `TokenRequest`; a `TokenDetails` (in JSON format); an [Ably JWT](https://ably.com/docs/core-features/authentication#ably-jwt). Upon failure, the `authCallback` should call this function with information about the error.
- */
- authCallback?(
- data: TokenParams,
- /**
- * A function which, upon success, the `authCallback` should call with one of: an Ably Token string (in plain text format); a signed `TokenRequest`; a `TokenDetails` (in JSON format); an [Ably JWT](https://ably.com/docs/core-features/authentication#ably-jwt). Upon failure, the `authCallback` should call this function with information about the error.
- *
- * @param error - Should be `null` if the auth request completed successfully, or containing details of the error if not.
- * @param tokenRequestOrDetails - A valid `TokenRequest`, `TokenDetails` or Ably JWT to be used for authentication.
- */
- callback: (
- error: ErrorInfo | string | null,
- tokenRequestOrDetails: TokenDetails | TokenRequest | string | null
- ) => void
- ): void;
+ suspendedRetryTimeout?: number;
- /**
- * A set of key-value pair headers to be added to any request made to the `authUrl`. Useful when an application requires these to be added to validate the request or implement the response. If the `authHeaders` object contains an `authorization` key, then `withCredentials` is set on the XHR request.
- */
- authHeaders?: { [index: string]: string };
+ /**
+ * When `true`, the client library will automatically send a close request to Ably whenever the `window` [`beforeunload` event](https://developer.mozilla.org/en-US/docs/Web/API/BeforeUnloadEvent) fires. By enabling this option, the close request sent to Ably ensures the connection state will not be retained and all channels associated with the channel will be detached. This is commonly used by developers who want presence leave events to fire immediately (that is, if a user navigates to another page or closes their browser, then enabling this option will result in the presence member leaving immediately). Without this option or an explicit call to the `close` method of the `Connection` object, Ably expects that the abruptly disconnected connection could later be recovered and therefore does not immediately remove the user from presence. Instead, to avoid “twitchy” presence behaviour an abruptly disconnected client is removed from channels in which they are present after 15 seconds, and the connection state is retained for two minutes. Defaults to `true`.
+ */
+ closeOnUnload?: boolean;
- /**
- * The HTTP verb to use for any request made to the `authUrl`, either `GET` or `POST`. The default value is `GET`.
- *
- * @defaultValue `HTTPMethods.GET`
- */
- authMethod?: HTTPMethods;
+ /**
+ * When `true`, enables idempotent publishing by assigning a unique message ID client-side, allowing the Ably servers to discard automatic publish retries following a failure such as a network fault. The default is `true`.
+ *
+ * @defaultValue `true`
+ */
+ idempotentRestPublishing?: boolean;
- /**
- * A set of key-value pair params to be added to any request made to the `authUrl`. When the `authMethod` is `GET`, query params are added to the URL, whereas when `authMethod` is `POST`, the params are sent as URL encoded form data. Useful when an application requires these to be added to validate the request or implement the response.
- */
- authParams?: { [index: string]: string };
+ /**
+ * A set of key-value pairs that can be used to pass in arbitrary connection parameters, such as [`heartbeatInterval`](https://ably.com/docs/realtime/connection#heartbeats) or [`remainPresentFor`](https://ably.com/docs/realtime/presence#unstable-connections).
+ */
+ transportParams?: { [k: string]: string | number };
- /**
- * A URL that the library may use to obtain a token string (in plain text format), or a signed {@link TokenRequest} or {@link TokenDetails} (in JSON format) from.
- */
- authUrl?: string;
+ /**
+ * An array of transports to use, in descending order of preference. In the browser environment the available transports are: `web_socket` and `xhr`.
+ */
+ transports?: Transport[];
- /**
- * The full API key string, as obtained from the [Ably dashboard](https://ably.com/dashboard). Use this option if you wish to use Basic authentication, or wish to be able to issue Ably Tokens without needing to defer to a separate entity to sign Ably {@link TokenRequest | `TokenRequest`s}. Read more about [Basic authentication](https://ably.com/docs/core-features/authentication#basic-authentication).
- */
- key?: string;
+ /**
+ * The maximum number of fallback hosts to use as a fallback when an HTTP request to the primary host is unreachable or indicates that it is unserviceable. The default value is 3.
+ *
+ * @defaultValue 3
+ */
+ httpMaxRetryCount?: number;
- /**
- * If `true`, the library queries the Ably servers for the current time when issuing {@link TokenRequest | `TokenRequest`s} instead of relying on a locally-available time of day. Knowing the time accurately is needed to create valid signed Ably {@link TokenRequest | `TokenRequest`s}, so this option is useful for library instances on auth servers where for some reason the server clock cannot be kept synchronized through normal means, such as an [NTP daemon](https://en.wikipedia.org/wiki/Ntpd). The server is queried for the current time once per client library instance (which stores the offset from the local clock), so if using this option you should avoid instancing a new version of the library for each request. The default is `false`.
- *
- * @defaultValue `false`
- */
- queryTime?: boolean;
+ /**
+ * The maximum elapsed time in milliseconds in which fallback host retries for HTTP requests will be attempted. The default is 15 seconds.
+ *
+ * @defaultValue 15s
+ */
+ httpMaxRetryDuration?: number;
- /**
- * An authenticated token. This can either be a {@link TokenDetails} object or token string (obtained from the `token` property of a {@link TokenDetails} component of an Ably {@link TokenRequest} response, or a JSON Web Token satisfying [the Ably requirements for JWTs](https://ably.com/docs/core-features/authentication#ably-jwt)). This option is mostly useful for testing: since tokens are short-lived, in production you almost always want to use an authentication method that enables the client library to renew the token automatically when the previous one expires, such as `authUrl` or `authCallback`. Read more about [Token authentication](https://ably.com/docs/core-features/authentication#token-authentication).
- */
- token?: TokenDetails | string;
+ /**
+ * Timeout in milliseconds for opening a connection to Ably to initiate an HTTP request. The default is 4 seconds.
+ *
+ * @defaultValue 4s
+ */
+ httpOpenTimeout?: number;
- /**
- * An authenticated {@link TokenDetails} object (most commonly obtained from an Ably Token Request response). This option is mostly useful for testing: since tokens are short-lived, in production you almost always want to use an authentication method that enables the client library to renew the token automatically when the previous one expires, such as `authUrl` or `authCallback`. Use this option if you wish to use Token authentication. Read more about [Token authentication](https://ably.com/docs/core-features/authentication#token-authentication).
- */
- tokenDetails?: TokenDetails;
+ /**
+ * Timeout in milliseconds for a client performing a complete HTTP request to Ably, including the connection phase. The default is 10 seconds.
+ *
+ * @defaultValue 10s
+ */
+ httpRequestTimeout?: number;
- /**
- * When `true`, forces token authentication to be used by the library. If a `clientId` is not specified in the {@link ClientOptions} or {@link TokenParams}, then the Ably Token issued is [anonymous](https://ably.com/docs/core-features/authentication#identified-clients).
- */
- useTokenAuth?: boolean;
+ /**
+ * Timeout for the wait of acknowledgement for operations performed via a realtime connection, before the client library considers a request failed and triggers a failure condition. Operations include establishing a connection with Ably, or sending a `HEARTBEAT`, `CONNECT`, `ATTACH`, `DETACH` or `CLOSE` request. It is the equivalent of `httpRequestTimeout` but for realtime operations, rather than REST. The default is 10 seconds.
+ *
+ * @defaultValue 10s
+ */
+ realtimeRequestTimeout?: number;
- /**
- * A client ID, used for identifying this client when publishing messages or for presence purposes. The `clientId` can be any non-empty string, except it cannot contain a `*`. This option is primarily intended to be used in situations where the library is instantiated with a key. Note that a `clientId` may also be implicit in a token used to instantiate the library. An error will be raised if a `clientId` specified here conflicts with the `clientId` implicit in the token. Find out more about [client identities](https://ably.com/documentation/how-ably-works#client-identity).
- */
- clientId?: string;
- }
+ /**
+ * A map between a plugin type and a plugin object.
+ */
+ plugins?: Plugins;
/**
- * Capabilities which are available for use within {@link TokenParams}.
+ * The maximum message size is an attribute of an Ably account which represents the largest permitted payload size of a single message or set of messages published in a single operation. Publish requests whose payload exceeds this limit are rejected by the server. `maxMessageSize` enables the client to enforce, or further restrict, the maximum size of a single message or set of messages published via REST. The default value is `65536` (64 KiB). In the case of a realtime connection, the server may indicate the associated maximum message size on connection establishment; this value takes precedence over the client's default `maxMessageSize`.
+ *
+ * @defaultValue 65536
*/
- type capabilityOp =
- | 'publish'
- | 'subscribe'
- | 'presence'
- | 'history'
- | 'stats'
- | 'channel-metadata'
- | 'push-subscribe'
- | 'push-admin';
+ maxMessageSize?: number;
+}
+
+/**
+ * Describes the {@link ClientOptions.plugins | plugins} accepted by all variants of the SDK.
+ */
+export interface CorePlugins {
/**
- * Capabilities which are available for use within {@link TokenParams}.
+ * A plugin capable of decoding `vcdiff`-encoded messages. For more information on how to configure a channel to use delta encoding, see the [documentation for the `@ably-forks/vcdiff-decoder` package](https://github.com/ably-forks/vcdiff-decoder#usage).
*/
- type CapabilityOp = capabilityOp;
+ vcdiff?: any;
+}
+/**
+ * Passes authentication-specific properties in authentication requests to Ably. Properties set using `AuthOptions` are used instead of the default values set when the client library is instantiated, as opposed to being merged with them.
+ */
+export interface AuthOptions {
/**
- * Defines the properties of an Ably Token.
+ * Called when a new token is required. The role of the callback is to obtain a fresh token, one of: an Ably Token string (in plain text format); a signed {@link TokenRequest}; a {@link TokenDetails} (in JSON format); an [Ably JWT](https://ably.com/docs/core-features/authentication.ably-jwt). See [the authentication documentation](https://ably.com/docs/realtime/authentication) for details of the Ably {@link TokenRequest} format and associated API calls.
+ *
+ * @param data - The parameters that should be used to generate the token.
+ * @param callback - A function which, upon success, the `authCallback` should call with one of: an Ably Token string (in plain text format); a signed `TokenRequest`; a `TokenDetails` (in JSON format); an [Ably JWT](https://ably.com/docs/core-features/authentication#ably-jwt). Upon failure, the `authCallback` should call this function with information about the error.
*/
- interface TokenParams {
- /**
- * The capabilities associated with this Ably Token. The capabilities value is a JSON-encoded representation of the resource paths and associated operations. Read more about capabilities in the [capabilities docs](https://ably.com/docs/core-features/authentication/#capabilities-explained).
- *
- * @defaultValue `'{"*":["*"]}'`
- */
- capability?: { [key: string]: capabilityOp[] } | string;
- /**
- * A client ID, used for identifying this client when publishing messages or for presence purposes. The `clientId` can be any non-empty string, except it cannot contain a `*`. This option is primarily intended to be used in situations where the library is instantiated with a key. Note that a `clientId` may also be implicit in a token used to instantiate the library. An error is raised if a `clientId` specified here conflicts with the `clientId` implicit in the token. Find out more about [identified clients](https://ably.com/docs/core-features/authentication#identified-clients).
- */
- clientId?: string;
+ authCallback?(
+ data: TokenParams,
/**
- * A cryptographically secure random string of at least 16 characters, used to ensure the {@link TokenRequest} cannot be reused.
- */
- nonce?: string;
- /**
- * The timestamp of this request as milliseconds since the Unix epoch. Timestamps, in conjunction with the `nonce`, are used to prevent requests from being replayed. `timestamp` is a "one-time" value, and is valid in a request, but is not validly a member of any default token params such as `ClientOptions.defaultTokenParams`.
- */
- timestamp?: number;
- /**
- * Requested time to live for the token in milliseconds. The default is 60 minutes.
+ * A function which, upon success, the `authCallback` should call with one of: an Ably Token string (in plain text format); a signed `TokenRequest`; a `TokenDetails` (in JSON format); an [Ably JWT](https://ably.com/docs/core-features/authentication#ably-jwt). Upon failure, the `authCallback` should call this function with information about the error.
*
- * @defaultValue 60min
+ * @param error - Should be `null` if the auth request completed successfully, or containing details of the error if not.
+ * @param tokenRequestOrDetails - A valid `TokenRequest`, `TokenDetails` or Ably JWT to be used for authentication.
*/
- ttl?: number;
- }
+ callback: (
+ error: ErrorInfo | string | null,
+ tokenRequestOrDetails: TokenDetails | TokenRequest | string | null,
+ ) => void,
+ ): void;
/**
- * Sets the properties to configure encryption for a {@link ChannelBase} or {@link RealtimeChannelBase} object.
+ * A set of key-value pair headers to be added to any request made to the `authUrl`. Useful when an application requires these to be added to validate the request or implement the response. If the `authHeaders` object contains an `authorization` key, then `withCredentials` is set on the XHR request.
*/
- interface CipherParams {
- /**
- * The algorithm to use for encryption. Only `AES` is supported and is the default value.
- *
- * @defaultValue `"AES"`
- */
- algorithm: string;
- /**
- * The private key used to encrypt and decrypt payloads. You should not set this value directly; rather, you should pass a `key` of type {@link Types.CipherKeyParam} to {@link Crypto.getDefaultParams}.
- */
- key: CipherKey;
- /**
- * The length of the key in bits; either 128 or 256.
- */
- keyLength: number;
- /**
- * The cipher mode. Only `CBC` is supported and is the default value.
- *
- * @defaultValue `"CBC"`
- */
- mode: string;
- }
+ authHeaders?: { [index: string]: string };
/**
- * A generic Ably error object that contains an Ably-specific status code, and a generic status code. Errors returned from the Ably server are compatible with the `ErrorInfo` structure and should result in errors that inherit from `ErrorInfo`.
+ * The HTTP verb to use for any request made to the `authUrl`, either `GET` or `POST`. The default value is `GET`.
+ *
+ * @defaultValue `HTTPMethod.GET`
*/
- class ErrorInfo extends Error {
- /**
- * Ably [error code](https://github.com/ably/ably-common/blob/main/protocol/errors.json).
- */
- code: number;
- /**
- * Additional message information, where available.
- */
- message: string;
- /**
- * HTTP Status Code corresponding to this error, where applicable.
- */
- statusCode: number;
- /**
- * The underlying cause of the error, where applicable.
- */
- cause?: string | Error | ErrorInfo;
+ authMethod?: HTTPMethod;
- /**
- * Construct an ErrorInfo object.
- *
- * @param message - A string describing the error.
- * @param code - Ably [error code](https://github.com/ably/ably-common/blob/main/protocol/errors.json).
- * @param statusCode - HTTP Status Code corresponding to this error.
- * @param cause - The underlying cause of the error.
- */
- constructor(message: string, code: number, statusCode: number, cause?: string | Error | ErrorInfo);
- }
+ /**
+ * A set of key-value pair params to be added to any request made to the `authUrl`. When the `authMethod` is `GET`, query params are added to the URL, whereas when `authMethod` is `POST`, the params are sent as URL encoded form data. Useful when an application requires these to be added to validate the request or implement the response.
+ */
+ authParams?: { [index: string]: string };
/**
- * Contains the aggregate counts for messages and data transferred.
+ * A URL that the library may use to obtain a token string (in plain text format), or a signed {@link TokenRequest} or {@link TokenDetails} (in JSON format) from.
*/
- interface StatsMessageCount {
- /**
- * The count of all messages.
- */
- count: number;
- /**
- * The total number of bytes transferred for all messages.
- */
- data: number;
- }
+ authUrl?: string;
/**
- * Contains a breakdown of summary stats data for different (channel vs presence) message types.
+ * The full API key string, as obtained from the [Ably dashboard](https://ably.com/dashboard). Use this option if you wish to use Basic authentication, or wish to be able to issue Ably Tokens without needing to defer to a separate entity to sign Ably {@link TokenRequest | `TokenRequest`s}. Read more about [Basic authentication](https://ably.com/docs/core-features/authentication#basic-authentication).
*/
- interface StatsMessageTypes {
- /**
- * A {@link StatsMessageCount} object containing the count and byte value of messages and presence messages.
- */
- all: StatsMessageCount;
- /**
- * A {@link StatsMessageCount} object containing the count and byte value of messages.
- */
- messages: StatsMessageCount;
- /**
- * A {@link StatsMessageCount} object containing the count and byte value of presence messages.
- */
- presence: StatsMessageCount;
- }
+ key?: string;
/**
- * Contains the aggregate counts for requests made.
+ * If `true`, the library queries the Ably servers for the current time when issuing {@link TokenRequest | `TokenRequest`s} instead of relying on a locally-available time of day. Knowing the time accurately is needed to create valid signed Ably {@link TokenRequest | `TokenRequest`s}, so this option is useful for library instances on auth servers where for some reason the server clock cannot be kept synchronized through normal means, such as an [NTP daemon](https://en.wikipedia.org/wiki/Ntpd). The server is queried for the current time once per client library instance (which stores the offset from the local clock), so if using this option you should avoid instancing a new version of the library for each request. The default is `false`.
+ *
+ * @defaultValue `false`
*/
- interface StatsRequestCount {
- /**
- * The number of requests that failed.
- */
- failed: number;
- /**
- * The number of requests that were refused, typically as a result of permissions or a limit being exceeded.
- */
- refused: number;
- /**
- * The number of requests that succeeded.
- */
- succeeded: number;
- }
+ queryTime?: boolean;
/**
- * Contains the aggregate data for usage of a resource in a specific scope.
+ * An authenticated token. This can either be a {@link TokenDetails} object or token string (obtained from the `token` property of a {@link TokenDetails} component of an Ably {@link TokenRequest} response, or a JSON Web Token satisfying [the Ably requirements for JWTs](https://ably.com/docs/core-features/authentication#ably-jwt)). This option is mostly useful for testing: since tokens are short-lived, in production you almost always want to use an authentication method that enables the client library to renew the token automatically when the previous one expires, such as `authUrl` or `authCallback`. Read more about [Token authentication](https://ably.com/docs/core-features/authentication#token-authentication).
*/
- interface StatsResourceCount {
- /**
- * The average number of resources of this type used for this period.
- */
- mean: number;
- /**
- * The minimum total resources of this type used for this period.
- */
- min: number;
- /**
- * The total number of resources opened of this type.
- */
- opened: number;
- /**
- * The peak number of resources of this type used for this period.
- */
- peak: number;
- /**
- * The number of resource requests refused within this period.
- */
- refused: number;
- }
+ token?: TokenDetails | string;
/**
- * Contains a breakdown of summary stats data for different (TLS vs non-TLS) connection types.
+ * An authenticated {@link TokenDetails} object (most commonly obtained from an Ably Token Request response). This option is mostly useful for testing: since tokens are short-lived, in production you almost always want to use an authentication method that enables the client library to renew the token automatically when the previous one expires, such as `authUrl` or `authCallback`. Use this option if you wish to use Token authentication. Read more about [Token authentication](https://ably.com/docs/core-features/authentication#token-authentication).
*/
- interface StatsConnectionTypes {
- /**
- * A {@link StatsResourceCount} object containing a breakdown of usage by scope over TLS connections (both TLS and non-TLS).
- */
- all: StatsResourceCount;
- /**
- * A {@link StatsResourceCount} object containing a breakdown of usage by scope over non-TLS connections.
- */
- plain: StatsResourceCount;
- /**
- * A {@link StatsResourceCount} object containing a breakdown of usage by scope over TLS connections.
- */
- tls: StatsResourceCount;
- }
+ tokenDetails?: TokenDetails;
/**
- * Contains a breakdown of summary stats data for traffic over various transport types.
+ * When `true`, forces token authentication to be used by the library. If a `clientId` is not specified in the {@link ClientOptions} or {@link TokenParams}, then the Ably Token issued is [anonymous](https://ably.com/docs/core-features/authentication#identified-clients).
*/
- interface StatsMessageTraffic {
- /**
- * A {@link StatsMessageTypes} object containing a breakdown of usage by message type for all messages (includes `realtime`, `rest` and `webhook` messages).
- */
- all: StatsMessageTypes;
- /**
- * A {@link StatsMessageTypes} object containing a breakdown of usage by message type for messages transferred over a realtime transport such as WebSocket.
- */
- realtime: StatsMessageTypes;
- /**
- * A {@link StatsMessageTypes} object containing a breakdown of usage by message type for messages transferred over a rest transport such as WebSocket.
- */
- rest: StatsMessageTypes;
- /**
- * A {@link StatsMessageTypes} object containing a breakdown of usage by message type for messages delivered using webhooks.
- */
- webhook: StatsMessageTypes;
- }
+ useTokenAuth?: boolean;
/**
- * Contains an Ably Token and its associated metadata.
+ * A client ID, used for identifying this client when publishing messages or for presence purposes. The `clientId` can be any non-empty string, except it cannot contain a `*`. This option is primarily intended to be used in situations where the library is instantiated with a key. Note that a `clientId` may also be implicit in a token used to instantiate the library. An error will be raised if a `clientId` specified here conflicts with the `clientId` implicit in the token. Find out more about [client identities](https://ably.com/documentation/how-ably-works#client-identity).
*/
- interface TokenDetails {
- /**
- * The capabilities associated with this Ably Token. The capabilities value is a JSON-encoded representation of the resource paths and associated operations. Read more about capabilities in the [capabilities docs](https://ably.com/docs/core-features/authentication/#capabilities-explained).
- */
- capability: string;
- /**
- * The client ID, if any, bound to this Ably Token. If a client ID is included, then the Ably Token authenticates its bearer as that client ID, and the Ably Token may only be used to perform operations on behalf of that client ID. The client is then considered to be an [identified client](https://ably.com/docs/core-features/authentication#identified-clients).
- */
- clientId?: string;
- /**
- * The timestamp at which this token expires as milliseconds since the Unix epoch.
- */
- expires: number;
- /**
- * The timestamp at which this token was issued as milliseconds since the Unix epoch.
- */
- issued: number;
- /**
- * The [Ably Token](https://ably.com/docs/core-features/authentication#ably-tokens) itself. A typical Ably Token string appears with the form `xVLyHw.A-pwh7wicf3afTfgiw4k2Ku33kcnSA7z6y8FjuYpe3QaNRTEo4`.
- */
- token: string;
- }
+ clientId?: string;
+}
+/**
+ * Capabilities which are available for use within {@link TokenParams}.
+ */
+export type capabilityOp =
+ | 'publish'
+ | 'subscribe'
+ | 'presence'
+ | 'history'
+ | 'stats'
+ | 'channel-metadata'
+ | 'push-subscribe'
+ | 'push-admin';
+/**
+ * Capabilities which are available for use within {@link TokenParams}.
+ */
+export type CapabilityOp = capabilityOp;
+
+/**
+ * Defines the properties of an Ably Token.
+ */
+export interface TokenParams {
/**
- * Contains the properties of a request for a token to Ably. Tokens are generated using {@link AuthCallbacks.requestToken} or {@link AuthPromise.requestToken}.
+ * The capabilities associated with this Ably Token. The capabilities value is a JSON-encoded representation of the resource paths and associated operations. Read more about capabilities in the [capabilities docs](https://ably.com/docs/core-features/authentication/#capabilities-explained).
+ *
+ * @defaultValue `'{"*":["*"]}'`
*/
- interface TokenRequest {
- /**
- * Capability of the requested Ably Token. If the Ably `TokenRequest` is successful, the capability of the returned Ably Token will be the intersection of this capability with the capability of the issuing key. The capabilities value is a JSON-encoded representation of the resource paths and associated operations. Read more about capabilities in the [capabilities docs](https://ably.com/docs/realtime/authentication).
- */
- capability: string;
- /**
- * The client ID to associate with the requested Ably Token. When provided, the Ably Token may only be used to perform operations on behalf of that client ID.
- */
- clientId?: string;
- /**
- * The name of the key against which this request is made. The key name is public, whereas the key secret is private.
- */
- keyName: string;
- /**
- * The Message Authentication Code for this request.
- */
- mac: string;
- /**
- * A cryptographically secure random string of at least 16 characters, used to ensure the `TokenRequest` cannot be reused.
- */
- nonce: string;
- /**
- * The timestamp of this request as milliseconds since the Unix epoch.
- */
- timestamp: number;
- /**
- * Requested time to live for the Ably Token in milliseconds. If the Ably `TokenRequest` is successful, the TTL of the returned Ably Token is less than or equal to this value, depending on application settings and the attributes of the issuing key. The default is 60 minutes.
- *
- * @defaultValue 60min
- */
- ttl?: number;
- }
-
+ capability?: { [key: string]: capabilityOp[] } | string;
/**
- * [Channel Parameters](https://ably.com/docs/realtime/channels/channel-parameters/overview) used within {@link ChannelOptions}.
+ * A client ID, used for identifying this client when publishing messages or for presence purposes. The `clientId` can be any non-empty string, except it cannot contain a `*`. This option is primarily intended to be used in situations where the library is instantiated with a key. Note that a `clientId` may also be implicit in a token used to instantiate the library. An error is raised if a `clientId` specified here conflicts with the `clientId` implicit in the token. Find out more about [identified clients](https://ably.com/docs/core-features/authentication#identified-clients).
*/
- type ChannelParams = { [key: string]: string };
-
+ clientId?: string;
/**
- * The `ChannelMode` namespace describes the possible values of the {@link ChannelMode:type} type.
+ * A cryptographically secure random string of at least 16 characters, used to ensure the {@link TokenRequest} cannot be reused.
*/
- namespace ChannelMode {
- /**
- * The client can publish messages.
- */
- type PUBLISH = 'PUBLISH';
- /**
- * The client can subscribe to messages.
- */
- type SUBSCRIBE = 'SUBSCRIBE';
- /**
- * The client can enter the presence set.
- */
- type PRESENCE = 'PRESENCE';
- /**
- * The client can receive presence messages.
- */
- type PRESENCE_SUBSCRIBE = 'PRESENCE_SUBSCRIBE';
- /**
- * The client is resuming an existing connection.
- */
- type ATTACH_RESUME = 'ATTACH_RESUME';
- }
-
+ nonce?: string;
/**
- * Describes the possible flags used to configure client capabilities, using {@link ChannelOptions}.
+ * The timestamp of this request as milliseconds since the Unix epoch. Timestamps, in conjunction with the `nonce`, are used to prevent requests from being replayed. `timestamp` is a "one-time" value, and is valid in a request, but is not validly a member of any default token params such as `ClientOptions.defaultTokenParams`.
*/
- type ChannelMode =
- | ChannelMode.PUBLISH
- | ChannelMode.SUBSCRIBE
- | ChannelMode.PRESENCE
- | ChannelMode.PRESENCE_SUBSCRIBE
- | ChannelMode.ATTACH_RESUME;
+ timestamp?: number;
/**
- * Describes the possible flags used to configure client capabilities, using {@link ChannelOptions}.
+ * Requested time to live for the token in milliseconds. The default is 60 minutes.
+ *
+ * @defaultValue 60min
*/
- type ChannelModes = Array;
+ ttl?: number;
+}
+/**
+ * Sets the properties to configure encryption for a {@link Channel} or {@link RealtimeChannel} object.
+ */
+export interface CipherParams {
/**
- * Passes additional properties to a {@link ChannelBase} or {@link RealtimeChannelBase} object, such as encryption, {@link ChannelMode} and channel parameters.
+ * The algorithm to use for encryption. Only `AES` is supported and is the default value.
+ *
+ * @defaultValue `"AES"`
*/
- interface ChannelOptions {
- /**
- * Requests encryption for this channel when not null, and specifies encryption-related parameters (such as algorithm, chaining mode, key length and key). See [an example](https://ably.com/docs/realtime/encryption#getting-started).
- */
- cipher?: CipherParamOptions | CipherParams;
- /**
- * [Channel Parameters](https://ably.com/docs/realtime/channels/channel-parameters/overview) that configure the behavior of the channel.
- */
- params?: ChannelParams;
- /**
- * An array of {@link ChannelMode} objects.
- */
- modes?: ChannelModes;
- }
-
+ algorithm: string;
/**
- * Passes additional properties to a {@link RealtimeChannelBase} name to produce a new derived channel
+ * The private key used to encrypt and decrypt payloads. You should not set this value directly; rather, you should pass a `key` of type {@link CipherKeyParam} to {@link Crypto.getDefaultParams}.
*/
- interface DeriveOptions {
- /**
- * The JMESPath Query filter string to be used to derive new channel.
- */
- filter?: string;
- }
-
+ key: unknown;
/**
- * The `RestHistoryParams` interface describes the parameters accepted by the following methods:
- *
- * - {@link PresenceCallbacks.history}
- * - {@link PresencePromise.history}
- * - {@link ChannelCallbacks.history}
- * - {@link ChannelPromise.history}
+ * The length of the key in bits; either 128 or 256.
*/
- interface RestHistoryParams {
- /**
- * The time from which messages are retrieved, specified as milliseconds since the Unix epoch.
- */
- start?: number;
- /**
- * The time until messages are retrieved, specified as milliseconds since the Unix epoch.
- *
- * @defaultValue The current time.
- */
- end?: number;
- /**
- * The order for which messages are returned in. Valid values are `'backwards'` which orders messages from most recent to oldest, or `'forwards'` which orders messages from oldest to most recent. The default is `'backwards'`.
- *
- * @defaultValue `'backwards'`
- */
- direction?: 'forwards' | 'backwards';
- /**
- * An upper limit on the number of messages returned. The default is 100, and the maximum is 1000.
- *
- * @defaultValue 100
- */
- limit?: number;
- }
-
+ keyLength: number;
/**
- * The `RestPresenceParams` interface describes the parameters accepted by the following methods:
+ * The cipher mode. Only `CBC` is supported and is the default value.
*
- * - {@link PresenceCallbacks.get}
- * - {@link PresencePromise.get}
+ * @defaultValue `"CBC"`
*/
- interface RestPresenceParams {
- /**
- * An upper limit on the number of messages returned. The default is 100, and the maximum is 1000.
- *
- * @defaultValue 100
- */
- limit?: number;
- /**
- * Filters the list of returned presence members by a specific client using its ID.
- */
- clientId?: string;
- /**
- * Filters the list of returned presence members by a specific connection using its ID.
- */
- connectionId?: string;
- }
+ mode: string;
+}
+/**
+ * Contains an Ably Token and its associated metadata.
+ */
+export interface TokenDetails {
/**
- * The `RealtimePresenceParams` interface describes the parameters accepted by the following methods:
- *
- * - {@link RealtimePresenceCallbacks.get}
- * - {@link RealtimePresencePromise.get}
+ * The capabilities associated with this Ably Token. The capabilities value is a JSON-encoded representation of the resource paths and associated operations. Read more about capabilities in the [capabilities docs](https://ably.com/docs/core-features/authentication/#capabilities-explained).
*/
- interface RealtimePresenceParams {
- /**
- * Sets whether to wait for a full presence set synchronization between Ably and the clients on the channel to complete before returning the results. Synchronization begins as soon as the channel is {@link ChannelState.ATTACHED}. When set to `true` the results will be returned as soon as the sync is complete. When set to `false` the current list of members will be returned without the sync completing. The default is `true`.
- *
- * @defaultValue `true`
- */
- waitForSync?: boolean;
- /**
- * Filters the array of returned presence members by a specific client using its ID.
- */
- clientId?: string;
- /**
- * Filters the array of returned presence members by a specific connection using its ID.
- */
- connectionId?: string;
- }
-
+ capability: string;
/**
- * The `RealtimeHistoryParams` interface describes the parameters accepted by the following methods:
- *
- * - {@link RealtimePresenceCallbacks.history}
- * - {@link RealtimePresencePromise.history}
- * - {@link RealtimeChannelCallbacks.history}
- * - {@link RealtimeChannelPromise.history}
+ * The client ID, if any, bound to this Ably Token. If a client ID is included, then the Ably Token authenticates its bearer as that client ID, and the Ably Token may only be used to perform operations on behalf of that client ID. The client is then considered to be an [identified client](https://ably.com/docs/core-features/authentication#identified-clients).
*/
- interface RealtimeHistoryParams {
- /**
- * The time from which messages are retrieved, specified as milliseconds since the Unix epoch.
- */
- start?: number;
- /**
- * The time until messages are retrieved, specified as milliseconds since the Unix epoch.
- *
- * @defaultValue The current time.
- */
- end?: number;
- /**
- * The order for which messages are returned in. Valid values are `'backwards'` which orders messages from most recent to oldest, or `'forwards'` which orders messages from oldest to most recent. The default is `'backwards'`.
- *
- * @defaultValue `'backwards'`
- */
- direction?: 'forwards' | 'backwards';
- /**
- * An upper limit on the number of messages returned. The default is 100, and the maximum is 1000.
- *
- * @defaultValue 100
- */
- limit?: number;
- /**
- * When `true`, ensures message history is up until the point of the channel being attached. See [continuous history](https://ably.com/docs/realtime/history#continuous-history) for more info. Requires the `direction` to be `backwards`. If the channel is not attached, or if `direction` is set to `forwards`, this option results in an error.
- */
- untilAttach?: boolean;
- }
+ clientId?: string;
+ /**
+ * The timestamp at which this token expires as milliseconds since the Unix epoch.
+ */
+ expires: number;
+ /**
+ * The timestamp at which this token was issued as milliseconds since the Unix epoch.
+ */
+ issued: number;
+ /**
+ * The [Ably Token](https://ably.com/docs/core-features/authentication#ably-tokens) itself. A typical Ably Token string appears with the form `xVLyHw.A-pwh7wicf3afTfgiw4k2Ku33kcnSA7z6y8FjuYpe3QaNRTEo4`.
+ */
+ token: string;
+}
+/**
+ * Contains the properties of a request for a token to Ably. Tokens are generated using {@link Auth.requestToken}.
+ */
+export interface TokenRequest {
+ /**
+ * Capability of the requested Ably Token. If the Ably `TokenRequest` is successful, the capability of the returned Ably Token will be the intersection of this capability with the capability of the issuing key. The capabilities value is a JSON-encoded representation of the resource paths and associated operations. Read more about capabilities in the [capabilities docs](https://ably.com/docs/realtime/authentication).
+ */
+ capability: string;
+ /**
+ * The client ID to associate with the requested Ably Token. When provided, the Ably Token may only be used to perform operations on behalf of that client ID.
+ */
+ clientId?: string;
+ /**
+ * The name of the key against which this request is made. The key name is public, whereas the key secret is private.
+ */
+ keyName: string;
/**
- * Settings which control the log output of the library.
+ * The Message Authentication Code for this request.
+ */
+ mac: string;
+ /**
+ * A cryptographically secure random string of at least 16 characters, used to ensure the `TokenRequest` cannot be reused.
+ */
+ nonce: string;
+ /**
+ * The timestamp of this request as milliseconds since the Unix epoch.
+ */
+ timestamp: number;
+ /**
+ * Requested time to live for the Ably Token in milliseconds. If the Ably `TokenRequest` is successful, the TTL of the returned Ably Token is less than or equal to this value, depending on application settings and the attributes of the issuing key. The default is 60 minutes.
*
- * @deprecated This type is deprecated and will be removed in a future version. Use the {@link ClientOptions.logLevel} and {@link ClientOptions.logHandler} client options instead.
+ * @defaultValue 60min
*/
- interface LogInfo {
- /**
- * Controls the verbosity of the logs output from the library. Valid values are: 0 (no logs), 1 (errors only), 2 (errors plus connection and channel state changes), 3 (high-level debug output), and 4 (full debug output).
- *
- * @deprecated This property is deprecated and will be removed in a future version. Use the {@link ClientOptions.logLevel} client option instead.
- */
- level?: number;
+ ttl?: number;
+}
- /**
- * Controls the log output of the library. This is a function to handle each line of log output. If you do not set this value, then `console.log` will be used.
- *
- * @deprecated This property is deprecated and will be removed in a future version. Use the {@link ClientOptions.logHandler} client option instead.
- * @param msg - The log message emitted by the library.
- */
- handler?: (msg: string) => void;
- }
+/**
+ * [Channel Parameters](https://ably.com/docs/realtime/channels/channel-parameters/overview) used within {@link ChannelOptions}.
+ */
+export type ChannelParams = { [key: string]: string };
+/**
+ * The `ChannelModes` namespace describes the possible values of the {@link ChannelMode} type.
+ */
+declare namespace ChannelModes {
/**
- * Contains state change information emitted by {@link ChannelBase} and {@link RealtimeChannelBase} objects.
+ * The client can publish messages.
*/
- interface ChannelStateChange {
- /**
- * The new current {@link ChannelState}.
- */
- current: ChannelState;
- /**
- * The previous state. For the {@link ChannelEvent.UPDATE} event, this is equal to the `current` {@link ChannelState}.
- */
- previous: ChannelState;
- /**
- * An {@link ErrorInfo} object containing any information relating to the transition.
- */
- reason?: ErrorInfo;
- /**
- * Indicates whether message continuity on this channel is preserved, see [Nonfatal channel errors](https://ably.com/docs/realtime/channels#nonfatal-errors) for more info.
- */
- resumed: boolean;
- /**
- * Indicates whether the client can expect a backlog of messages from a rewind or resume.
- */
- hasBacklog?: boolean;
- }
-
+ type PUBLISH = 'PUBLISH';
/**
- * Contains {@link ConnectionState} change information emitted by the {@link ConnectionBase} object.
+ * The client can subscribe to messages.
*/
- interface ConnectionStateChange {
- /**
- * The new {@link ConnectionState}.
- */
- current: ConnectionState;
- /**
- * The previous {@link ConnectionState}. For the {@link ConnectionEvent.UPDATE} event, this is equal to the current {@link ConnectionState}.
- */
- previous: ConnectionState;
- /**
- * An {@link ErrorInfo} object containing any information relating to the transition.
- */
- reason?: ErrorInfo;
- /**
- * Duration in milliseconds, after which the client retries a connection where applicable.
- */
- retryIn?: number;
- }
-
+ type SUBSCRIBE = 'SUBSCRIBE';
/**
- * The `DevicePlatform` namespace describes the possible values of the {@link DevicePlatform:type} type.
+ * The client can enter the presence set.
*/
- namespace DevicePlatform {
- /**
- * The device platform is Android.
- */
- type ANDROID = 'android';
- /**
- * The device platform is iOS.
- */
- type IOS = 'ios';
- /**
- * The device platform is a web browser.
- */
- type BROWSER = 'browser';
- }
-
+ type PRESENCE = 'PRESENCE';
/**
- * Describes the device receiving push notifications.
+ * The client can receive presence messages.
*/
- type DevicePlatform = DevicePlatform.ANDROID | DevicePlatform.IOS | DevicePlatform.BROWSER;
-
+ type PRESENCE_SUBSCRIBE = 'PRESENCE_SUBSCRIBE';
/**
- * The `DeviceFormFactor` namespace describes the possible values of the {@link DeviceFormFactor:type} type.
+ * The client is resuming an existing connection.
*/
- namespace DeviceFormFactor {
- /**
- * The device is a phone.
- */
- type PHONE = 'phone';
- /**
- * The device is tablet.
- */
- type TABLET = 'tablet';
- /**
- * The device is a desktop.
- */
- type DESKTOP = 'desktop';
- /**
- * The device is a TV.
- */
- type TV = 'tv';
- /**
- * The device is a watch.
- */
- type WATCH = 'watch';
- /**
- * The device is a car.
- */
- type CAR = 'car';
- /**
- * The device is embedded.
- */
- type EMBEDDED = 'embedded';
- /**
- * The device is other.
- */
- type OTHER = 'other';
- }
+ type ATTACH_RESUME = 'ATTACH_RESUME';
+}
+
+/**
+ * Describes the possible flags used to configure client capabilities, using {@link ChannelOptions}.
+ */
+export type ChannelMode =
+ | ChannelModes.PUBLISH
+ | ChannelModes.SUBSCRIBE
+ | ChannelModes.PRESENCE
+ | ChannelModes.PRESENCE_SUBSCRIBE
+ | ChannelModes.ATTACH_RESUME;
+/**
+ * Passes additional properties to a {@link Channel} or {@link RealtimeChannel} object, such as encryption, {@link ChannelMode} and channel parameters.
+ */
+export interface ChannelOptions {
/**
- * Describes the type of device receiving a push notification.
+ * Requests encryption for this channel when not null, and specifies encryption-related parameters (such as algorithm, chaining mode, key length and key). See [an example](https://ably.com/docs/realtime/encryption#getting-started). When running in a browser, encryption is only available when the current environment is a [secure context](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts).
*/
- type DeviceFormFactor =
- | DeviceFormFactor.PHONE
- | DeviceFormFactor.TABLET
- | DeviceFormFactor.DESKTOP
- | DeviceFormFactor.TV
- | DeviceFormFactor.WATCH
- | DeviceFormFactor.CAR
- | DeviceFormFactor.EMBEDDED
- | DeviceFormFactor.OTHER;
-
+ cipher?: CipherParamOptions | CipherParams;
/**
- * Contains the properties of a device registered for push notifications.
+ * [Channel Parameters](https://ably.com/docs/realtime/channels/channel-parameters/overview) that configure the behavior of the channel.
*/
- interface DeviceDetails {
- /**
- * A unique ID generated by the device.
- */
- id: string;
- /**
- * The client ID the device is connected to Ably with.
- */
- clientId?: string;
- /**
- * The {@link DevicePlatform} associated with the device. Describes the platform the device uses, such as `android` or `ios`.
- */
- platform: DevicePlatform;
- /**
- * The {@link DeviceFormFactor} object associated with the device. Describes the type of the device, such as `phone` or `tablet`.
- */
- formFactor: DeviceFormFactor;
- /**
- * A JSON object of key-value pairs that contains metadata for the device.
- */
- metadata?: any;
- /**
- * A unique device secret generated by the Ably SDK.
- */
- deviceSecret?: string;
- /**
- * The {@link DevicePushDetails} object associated with the device. Describes the details of the push registration of the device.
- */
- push: DevicePushDetails;
- }
-
+ params?: ChannelParams;
/**
- * Contains the subscriptions of a device, or a group of devices sharing the same `clientId`, has to a channel in order to receive push notifications.
+ * An array of {@link ChannelMode} objects.
*/
- interface PushChannelSubscription {
- /**
- * The channel the push notification subscription is for.
- */
- channel: string;
- /**
- * The unique ID of the device.
- */
- deviceId?: string;
- /**
- * The ID of the client the device, or devices are associated to.
- */
- clientId?: string;
- }
+ modes?: ChannelMode[];
+}
+/**
+ * Passes additional properties to a {@link RealtimeChannel} name to produce a new derived channel
+ */
+export interface DeriveOptions {
/**
- * Valid states which a Push device may be in.
+ * The JMESPath Query filter string to be used to derive new channel.
*/
- type DevicePushState = 'ACTIVE' | 'FAILING' | 'FAILED';
+ filter?: string;
+}
+/**
+ * The `RestHistoryParams` interface describes the parameters accepted by the following methods:
+ *
+ * - {@link Presence.history}
+ * - {@link Channel.history}
+ */
+export interface RestHistoryParams {
/**
- * Contains the details of the push registration of a device.
+ * The time from which messages are retrieved, specified as milliseconds since the Unix epoch.
*/
- interface DevicePushDetails {
- /**
- * A JSON object of key-value pairs that contains of the push transport and address.
- */
- recipient: any;
- /**
- * The current state of the push registration.
- */
- state?: DevicePushState;
- /**
- * An {@link ErrorInfo} object describing the most recent error when the `state` is `Failing` or `Failed`.
- */
- error?: ErrorInfo;
- }
-
+ start?: number;
/**
- * The `DeviceRegistrationParams` interface describes the parameters accepted by the following methods:
+ * The time until messages are retrieved, specified as milliseconds since the Unix epoch.
*
- * - {@link PushDeviceRegistrationsCallbacks.list}
- * - {@link PushDeviceRegistrationsCallbacks.removeWhere}
- * - {@link PushDeviceRegistrationsPromise.list}
- * - {@link PushDeviceRegistrationsPromise.removeWhere}
+ * @defaultValue The current time.
*/
- interface DeviceRegistrationParams {
- /**
- * Filter to restrict to devices associated with a client ID.
- */
- clientId?: string;
- /**
- * Filter to restrict by the unique ID of the device.
- */
- deviceId?: string;
- /**
- * A limit on the number of devices returned, up to 1,000.
- */
- limit?: number;
- /**
- * Filter by the state of the device.
- */
- state?: DevicePushState;
- }
-
+ end?: number;
/**
- * The `PushChannelSubscriptionParams` interface describes the parameters accepted by the following methods:
+ * The order for which messages are returned in. Valid values are `'backwards'` which orders messages from most recent to oldest, or `'forwards'` which orders messages from oldest to most recent. The default is `'backwards'`.
*
- * - {@link PushChannelSubscriptionsCallbacks.list}
- * - {@link PushChannelSubscriptionsCallbacks.removeWhere}
- * - {@link PushChannelSubscriptionsPromise.list}
- * - {@link PushChannelSubscriptionsPromise.removeWhere}
+ * @defaultValue `'backwards'`
*/
- interface PushChannelSubscriptionParams {
- /**
- * Filter to restrict to subscriptions associated with the given channel.
- */
- channel?: string;
- /**
- * Filter to restrict to devices associated with the given client identifier. Cannot be used with a deviceId param.
- */
- clientId?: string;
- /**
- * Filter to restrict to devices associated with that device identifier. Cannot be used with a clientId param.
- */
- deviceId?: string;
- /**
- * A limit on the number of devices returned, up to 1,000.
- */
- limit?: number;
- }
-
+ direction?: 'forwards' | 'backwards';
/**
- * The `PushChannelsParams` interface describes the parameters accepted by the following methods:
+ * An upper limit on the number of messages returned. The default is 100, and the maximum is 1000.
*
- * - {@link PushChannelSubscriptionsCallbacks.listChannels}
- * - {@link PushChannelSubscriptionsPromise.listChannels}
+ * @defaultValue 100
*/
- interface PushChannelsParams {
- /**
- * A limit on the number of channels returned, up to 1,000.
- */
- limit?: number;
- }
+ limit?: number;
+}
+/**
+ * The `RestPresenceParams` interface describes the parameters accepted by {@link Presence.get}.
+ */
+export interface RestPresenceParams {
/**
- * The `StatsParams` interface describes the parameters accepted by the following methods:
+ * An upper limit on the number of messages returned. The default is 100, and the maximum is 1000.
*
- * - {@link RestCallbacks.stats}
- * - {@link RestPromise.stats}
- * - {@link RealtimeCallbacks.stats}
- * - {@link RealtimePromise.stats}
+ * @defaultValue 100
*/
- interface StatsParams {
- /**
- * The time from which stats are retrieved, specified as milliseconds since the Unix epoch.
- *
- * @defaultValue The Unix epoch.
- */
- start?: number;
- /**
- * The time until stats are retrieved, specified as milliseconds since the Unix epoch.
- *
- * @defaultValue The current time.
- */
- end?: number;
- /**
- * The order for which stats are returned in. Valid values are `'backwards'` which orders stats from most recent to oldest, or `'forwards'` which orders stats from oldest to most recent. The default is `'backwards'`.
- *
- * @defaultValue `'backwards'`
- */
- direction?: 'backwards' | 'forwards';
- /**
- * An upper limit on the number of stats returned. The default is 100, and the maximum is 1000.
- *
- * @defaultValue 100
- */
- limit?: number;
- /**
- * Based on the unit selected, the given `start` or `end` times are rounded down to the start of the relevant interval depending on the unit granularity of the query.
- *
- * @defaultValue `StatsIntervalGranularity.MINUTE`
- */
- unit?: StatsIntervalGranularity;
- }
-
+ limit?: number;
/**
- * Contains information about the results of a batch operation.
+ * Filters the list of returned presence members by a specific client using its ID.
*/
- interface BatchResult {
- /**
- * The number of successful operations in the request.
- */
- successCount: number;
- /**
- * The number of unsuccessful operations in the request.
- */
- failureCount: number;
- /**
- * An array of results for the batch operation.
- */
- results: T[];
- }
+ clientId?: string;
+ /**
+ * Filters the list of returned presence members by a specific connection using its ID.
+ */
+ connectionId?: string;
+}
+/**
+ * The `RealtimePresenceParams` interface describes the parameters accepted by {@link RealtimePresence.get}.
+ */
+export interface RealtimePresenceParams {
/**
- * Describes the messages that should be published by a batch publish operation, and the channels to which they should be published.
+ * Sets whether to wait for a full presence set synchronization between Ably and the clients on the channel to complete before returning the results. Synchronization begins as soon as the channel is {@link ChannelStates.ATTACHED}. When set to `true` the results will be returned as soon as the sync is complete. When set to `false` the current list of members will be returned without the sync completing. The default is `true`.
+ *
+ * @defaultValue `true`
*/
- interface BatchPublishSpec {
- /**
- * The names of the channels to publish the `messages` to.
- */
- channels: string[];
- /**
- * An array of {@link Message} objects.
- */
- messages: Message[];
- }
+ waitForSync?: boolean;
+ /**
+ * Filters the array of returned presence members by a specific client using its ID.
+ */
+ clientId?: string;
+ /**
+ * Filters the array of returned presence members by a specific connection using its ID.
+ */
+ connectionId?: string;
+}
+/**
+ * The `RealtimeHistoryParams` interface describes the parameters accepted by the following methods:
+ *
+ * - {@link RealtimePresence.history}
+ * - {@link RealtimeChannel.history}
+ */
+export interface RealtimeHistoryParams {
/**
- * Contains information about the result of successful publishes to a channel requested by a single {@link Types.BatchPublishSpec}.
+ * The time from which messages are retrieved, specified as milliseconds since the Unix epoch.
*/
- interface BatchPublishSuccessResult {
- /**
- * The name of the channel the message(s) was published to.
- */
- channel: string;
- /**
- * A unique ID prefixed to the {@link Message.id} of each published message.
- */
- messageId: string;
- }
+ start?: number;
+ /**
+ * The time until messages are retrieved, specified as milliseconds since the Unix epoch.
+ *
+ * @defaultValue The current time.
+ */
+ end?: number;
+ /**
+ * The order for which messages are returned in. Valid values are `'backwards'` which orders messages from most recent to oldest, or `'forwards'` which orders messages from oldest to most recent. The default is `'backwards'`.
+ *
+ * @defaultValue `'backwards'`
+ */
+ direction?: 'forwards' | 'backwards';
+ /**
+ * An upper limit on the number of messages returned. The default is 100, and the maximum is 1000.
+ *
+ * @defaultValue 100
+ */
+ limit?: number;
+ /**
+ * When `true`, ensures message history is up until the point of the channel being attached. See [continuous history](https://ably.com/docs/realtime/history#continuous-history) for more info. Requires the `direction` to be `backwards`. If the channel is not attached, or if `direction` is set to `forwards`, this option results in an error.
+ */
+ untilAttach?: boolean;
+}
+/**
+ * Contains state change information emitted by {@link Channel} and {@link RealtimeChannel} objects.
+ */
+export interface ChannelStateChange {
/**
- * Contains information about the result of unsuccessful publishes to a channel requested by a single {@link Types.BatchPublishSpec}.
+ * The new current {@link ChannelState}.
*/
- interface BatchPublishFailureResult {
- /**
- * The name of the channel the message(s) failed to be published to.
- */
- channel: string;
- /**
- * Describes the reason for which the message(s) failed to publish to the channel as an {@link ErrorInfo} object.
- */
- error: ErrorInfo;
- }
+ current: ChannelState;
+ /**
+ * The previous state. For the {@link ChannelEvents.UPDATE} event, this is equal to the `current` {@link ChannelState}.
+ */
+ previous: ChannelState;
+ /**
+ * An {@link ErrorInfo} object containing any information relating to the transition.
+ */
+ reason?: ErrorInfo;
+ /**
+ * Indicates whether message continuity on this channel is preserved, see [Nonfatal channel errors](https://ably.com/docs/realtime/channels#nonfatal-errors) for more info.
+ */
+ resumed: boolean;
+ /**
+ * Indicates whether the client can expect a backlog of messages from a rewind or resume.
+ */
+ hasBacklog?: boolean;
+}
+/**
+ * Contains {@link ConnectionState} change information emitted by the {@link Connection} object.
+ */
+export interface ConnectionStateChange {
/**
- * Contains information about the result of a successful batch presence request for a single channel.
+ * The new {@link ConnectionState}.
*/
- interface BatchPresenceSuccessResult {
- /**
- * The channel name the presence state was retrieved for.
- */
- channel: string;
- /**
- * An array of {@link PresenceMessage}s describing members present on the channel.
- */
- presence: PresenceMessage[];
- }
+ current: ConnectionState;
+ /**
+ * The previous {@link ConnectionState}. For the {@link ConnectionEvents.UPDATE} event, this is equal to the current {@link ConnectionState}.
+ */
+ previous: ConnectionState;
+ /**
+ * An {@link ErrorInfo} object containing any information relating to the transition.
+ */
+ reason?: ErrorInfo;
+ /**
+ * Duration in milliseconds, after which the client retries a connection where applicable.
+ */
+ retryIn?: number;
+}
+/**
+ * The `DevicePlatforms` namespace describes the possible values of the {@link DevicePlatform} type.
+ */
+declare namespace DevicePlatforms {
/**
- * Contains information about the result of an unsuccessful batch presence request for a single channel.
+ * The device platform is Android.
*/
- interface BatchPresenceFailureResult {
- /**
- * The channel name the presence state failed to be retrieved for.
- */
- channel: string;
- /**
- * Describes the reason for which presence state could not be retrieved for the channel as an {@link ErrorInfo} object.
- */
- error: ErrorInfo;
- }
+ type ANDROID = 'android';
+ /**
+ * The device platform is iOS.
+ */
+ type IOS = 'ios';
+ /**
+ * The device platform is a web browser.
+ */
+ type BROWSER = 'browser';
+}
+
+/**
+ * Describes the device receiving push notifications.
+ */
+export type DevicePlatform = DevicePlatforms.ANDROID | DevicePlatforms.IOS | DevicePlatforms.BROWSER;
+/**
+ * The `DeviceFormFactors` namespace describes the possible values of the {@link DeviceFormFactor} type.
+ */
+declare namespace DeviceFormFactors {
/**
- * The `TokenRevocationOptions` interface describes the additional options accepted by the following methods:
- *
- * - {@link AuthCallbacks.revokeTokens}
- * - {@link AuthPromise.revokeTokens}
+ * The device is a phone.
*/
- interface TokenRevocationOptions {
- /**
- * A Unix timestamp in milliseconds where only tokens issued before this time are revoked. The default is the current time. Requests with an `issuedBefore` in the future, or more than an hour in the past, will be rejected.
- */
- issuedBefore?: number;
- /**
- * If true, permits a token renewal cycle to take place without needing established connections to be dropped, by postponing enforcement to 30 seconds in the future, and sending any existing connections a hint to obtain (and upgrade the connection to use) a new token. The default is `false`, meaning that the effect is near-immediate.
- */
- allowReauthMargin?: boolean;
- }
+ type PHONE = 'phone';
+ /**
+ * The device is tablet.
+ */
+ type TABLET = 'tablet';
+ /**
+ * The device is a desktop.
+ */
+ type DESKTOP = 'desktop';
+ /**
+ * The device is a TV.
+ */
+ type TV = 'tv';
+ /**
+ * The device is a watch.
+ */
+ type WATCH = 'watch';
+ /**
+ * The device is a car.
+ */
+ type CAR = 'car';
+ /**
+ * The device is embedded.
+ */
+ type EMBEDDED = 'embedded';
+ /**
+ * The device is other.
+ */
+ type OTHER = 'other';
+}
+/**
+ * Describes the type of device receiving a push notification.
+ */
+export type DeviceFormFactor =
+ | DeviceFormFactors.PHONE
+ | DeviceFormFactors.TABLET
+ | DeviceFormFactors.DESKTOP
+ | DeviceFormFactors.TV
+ | DeviceFormFactors.WATCH
+ | DeviceFormFactors.CAR
+ | DeviceFormFactors.EMBEDDED
+ | DeviceFormFactors.OTHER;
+
+/**
+ * Contains the properties of a device registered for push notifications.
+ */
+export interface DeviceDetails {
/**
- * Describes which tokens should be affected by a token revocation request.
+ * A unique ID generated by the device.
*/
- interface TokenRevocationTargetSpecifier {
- /**
- * The type of token revocation target specifier. Valid values include `clientId`, `revocationKey` and `channel`.
- */
- type: string;
- /**
- * The value of the token revocation target specifier.
- */
- value: string;
- }
+ id: string;
+ /**
+ * The client ID the device is connected to Ably with.
+ */
+ clientId?: string;
+ /**
+ * The {@link DevicePlatform} associated with the device. Describes the platform the device uses, such as `android` or `ios`.
+ */
+ platform: DevicePlatform;
+ /**
+ * The {@link DeviceFormFactor} object associated with the device. Describes the type of the device, such as `phone` or `tablet`.
+ */
+ formFactor: DeviceFormFactor;
+ /**
+ * A JSON object of key-value pairs that contains metadata for the device.
+ */
+ metadata?: any;
+ /**
+ * A unique device secret generated by the Ably SDK.
+ */
+ deviceSecret?: string;
+ /**
+ * The {@link DevicePushDetails} object associated with the device. Describes the details of the push registration of the device.
+ */
+ push: DevicePushDetails;
+}
+/**
+ * Contains the subscriptions of a device, or a group of devices sharing the same `clientId`, has to a channel in order to receive push notifications.
+ */
+export interface PushChannelSubscription {
/**
- * Contains information about the result of a successful token revocation request for a single target specifier.
+ * The channel the push notification subscription is for.
*/
- interface TokenRevocationSuccessResult {
- /**
- * The target specifier.
- */
- target: string;
- /**
- * The time at which the token revocation will take effect, as a Unix timestamp in milliseconds.
- */
- appliesAt: number;
- /**
- * A Unix timestamp in milliseconds. Only tokens issued earlier than this time will be revoked.
- */
- issuedBefore: number;
- }
+ channel: string;
+ /**
+ * The unique ID of the device.
+ */
+ deviceId?: string;
+ /**
+ * The ID of the client the device, or devices are associated to.
+ */
+ clientId?: string;
+}
+
+/**
+ * Valid states which a Push device may be in.
+ */
+export type DevicePushState = 'ACTIVE' | 'FAILING' | 'FAILED';
+/**
+ * Contains the details of the push registration of a device.
+ */
+export interface DevicePushDetails {
/**
- * Contains information about the result of an unsuccessful token revocation request for a single target specifier.
+ * A JSON object of key-value pairs that contains of the push transport and address.
*/
- interface TokenRevocationFailureResult {
- /**
- * The target specifier.
- */
- target: string;
- /**
- * Describes the reason for which token revocation failed for the given `target` as an {@link ErrorInfo} object.
- */
- error: ErrorInfo;
- }
+ recipient: any;
+ /**
+ * The current state of the push registration.
+ */
+ state?: DevicePushState;
+ /**
+ * An {@link ErrorInfo} object describing the most recent error when the `state` is `Failing` or `Failed`.
+ */
+ error?: ErrorInfo;
+}
- // Common Listeners
+/**
+ * The `DeviceRegistrationParams` interface describes the parameters accepted by the following methods:
+ *
+ * - {@link PushDeviceRegistrations.list}
+ * - {@link PushDeviceRegistrations.removeWhere}
+ */
+export interface DeviceRegistrationParams {
/**
- * A standard callback format used in most areas of the callback API.
- *
- * @param err - An error object if the request failed.
- * @param result - The result of the request, if any.
+ * Filter to restrict to devices associated with a client ID.
*/
- type StandardCallback = (err: ErrorInfo | null, result?: T) => void;
+ clientId?: string;
/**
- * A {@link StandardCallback} which returns a {@link PaginatedResult}.
+ * Filter to restrict by the unique ID of the device.
*/
- type paginatedResultCallback = StandardCallback>;
+ deviceId?: string;
/**
- * A callback which returns only a single argument, used for {@link RealtimeChannelBase} subscriptions.
- *
- * @param message - The message which triggered the callback.
+ * A limit on the number of devices returned, up to 1,000.
*/
- type messageCallback = (message: T) => void;
+ limit?: number;
/**
- * A callback which returns only an error, or null, when complete.
- *
- * @param error - The error if the request failed, or null not.
+ * Filter by the state of the device.
*/
- type errorCallback = (error?: ErrorInfo | null) => void;
+ state?: DevicePushState;
+}
+
+/**
+ * The `PushChannelSubscriptionParams` interface describes the parameters accepted by the following methods:
+ *
+ * - {@link PushChannelSubscriptions.list}
+ * - {@link PushChannelSubscriptions.removeWhere}
+ */
+export interface PushChannelSubscriptionParams {
/**
- * The callback used by {@link RealtimeChannelCallbacks.whenState}.
- *
- * @param changeStateChange - The state change that occurred.
+ * Filter to restrict to subscriptions associated with the given channel.
*/
- type channelEventCallback = (changeStateChange: ChannelStateChange) => void;
+ channel?: string;
/**
- * The callback used by {@link ConnectionCallbacks.whenState}.
- *
- * @param connectionStateChange - The state change that occurred.
+ * Filter to restrict to devices associated with the given client identifier. Cannot be used with a deviceId param.
*/
- type connectionEventCallback = (connectionStateChange: ConnectionStateChange) => void;
+ clientId?: string;
/**
- * The callback used by {@link RestCallbacks.time} and {@link RealtimeCallbacks.time}.
- *
- * @param timeCallback - The time in milliseconds since the Unix epoch.
+ * Filter to restrict to devices associated with that device identifier. Cannot be used with a clientId param.
+ */
+ deviceId?: string;
+ /**
+ * A limit on the number of devices returned, up to 1,000.
+ */
+ limit?: number;
+}
+
+/**
+ * The `PushChannelsParams` interface describes the parameters accepted by {@link PushChannelSubscriptions.listChannels}.
+ */
+export interface PushChannelsParams {
+ /**
+ * A limit on the number of channels returned, up to 1,000.
*/
- type timeCallback = StandardCallback;
+ limit?: number;
+}
+
+/**
+ * The `StatsParams` interface describes the parameters accepted by the following methods:
+ *
+ * - {@link RestClient.stats}
+ * - {@link RealtimeClient.stats}
+ */
+export interface StatsParams {
/**
- * The callback used by {@link RealtimePresenceCallbacks.get}.
+ * The time from which stats are retrieved, specified as milliseconds since the Unix epoch.
*
- * @param realtimePresenceGetCallback - An array of {@link PresenceMessage} objects.
+ * @defaultValue The Unix epoch.
*/
- type realtimePresenceGetCallback = StandardCallback;
+ start?: number;
/**
- * The callback used by {@link AuthCallbacks.authorize}.
+ * The time until stats are retrieved, specified as milliseconds since the Unix epoch.
*
- * @param tokenDetailsCallback - A {@link TokenDetails} object.
+ * @defaultValue The current time.
*/
- type tokenDetailsCallback = StandardCallback;
+ end?: number;
/**
- * The callback used by {@link AuthCallbacks.createTokenRequest}.
+ * The order for which stats are returned in. Valid values are `'backwards'` which orders stats from most recent to oldest, or `'forwards'` which orders stats from oldest to most recent. The default is `'backwards'`.
*
- * @param tokenRequestCallback - A {@link TokenRequest} object
+ * @defaultValue `'backwards'`
*/
- type tokenRequestCallback = StandardCallback;
+ direction?: 'backwards' | 'forwards';
/**
- * The callback used by {@link recoverConnectionCallback}.
+ * An upper limit on the number of stats returned. The default is 100, and the maximum is 1000.
*
- * @param shouldRecover - Whether the connection should be recovered.
+ * @defaultValue 100
*/
- type recoverConnectionCompletionCallback = (shouldRecover: boolean) => void;
+ limit?: number;
/**
- * Used in {@link ClientOptions} to configure connection recovery behaviour.
+ * Based on the unit selected, the given `start` or `end` times are rounded down to the start of the relevant interval depending on the unit granularity of the query.
*
- * @param lastConnectionDetails - Details of the connection used by the connection recovery process.
- * @param callback - A callback which is called when a connection recovery attempt is complete.
+ * @defaultValue `StatsIntervalGranularity.MINUTE`
+ */
+ unit?: StatsIntervalGranularity;
+}
+
+/**
+ * Contains information about the results of a batch operation.
+ */
+export interface BatchResult {
+ /**
+ * The number of successful operations in the request.
*/
- type recoverConnectionCallback = (
- lastConnectionDetails: {
- /**
- * The recovery key can be used by another client to recover this connection’s state in the `recover` client options property. See [connection state recover options](https://ably.com/documentation/realtime/connection/#connection-state-recover-options) for more information.
- */
- recoveryKey: string;
- /**
- * The time at which the previous client was abruptly disconnected before the page was unloaded. This is represented as milliseconds since Unix epoch.
- */
- disconnectedAt: number;
- /**
- * A clone of the `location` object of the previous page’s document object before the page was unloaded. A common use case for this attribute is to ensure that the previous page URL is the same as the current URL before allowing the connection to be recovered. For example, you may want the connection to be recovered only for page reloads, but not when a user navigates to a different page.
- */
- location: string;
- /**
- * The `clientId` of the client’s `Auth` object before the page was unloaded. A common use case for this attribute is to ensure that the current logged in user’s `clientId` matches the previous connection’s `clientId` before allowing the connection to be recovered. Ably prohibits changing a `clientId` for an existing connection, so any mismatch in `clientId` during a recover will result in the connection moving to the failed state.
- */
- clientId: string | null;
- },
- callback: recoverConnectionCompletionCallback
- ) => void;
+ successCount: number;
/**
- * @ignore
- * @deprecated No longer used by this library - kept here since it used to be part of our public API. Will be removed in next major version release.
+ * The number of unsuccessful operations in the request.
*/
- type fromEncoded = (JsonObject: any, channelOptions?: ChannelOptions) => T;
+ failureCount: number;
/**
- * @ignore
- * @deprecated No longer used by this library - kept here since it used to be part of our public API. Will be removed in next major version release.
+ * An array of results for the batch operation.
*/
- type fromEncodedArray = (JsonArray: any[], channelOptions?: ChannelOptions) => T[];
-
- // Internal Classes
+ results: T[];
+}
- // To allow a uniform (callback) interface between on and once even in the
- // promisified version of the lib, but still allow once to be used in a way
- // that returns a Promise if desired, EventEmitter uses method overloading to
- // present both methods
+/**
+ * Describes the messages that should be published by a batch publish operation, and the channels to which they should be published.
+ */
+export interface BatchPublishSpec {
/**
- * A generic interface for event registration and delivery used in a number of the types in the Realtime client library. For example, the {@link ConnectionBase} object emits events for connection state using the `EventEmitter` pattern.
+ * The names of the channels to publish the `messages` to.
*/
- class EventEmitter {
- /**
- * Registers the provided listener for the specified event. If `on()` is called more than once with the same listener and event, the listener is added multiple times to its listener registry. Therefore, as an example, assuming the same listener is registered twice using `on()`, and an event is emitted once, the listener would be invoked twice.
- *
- * @param event - The named event to listen for.
- * @param callback - The event listener.
- */
- on(event: EventType, callback: CallbackType): void;
- /**
- * Registers the provided listener for the specified events. If `on()` is called more than once with the same listener and event, the listener is added multiple times to its listener registry. Therefore, as an example, assuming the same listener is registered twice using `on()`, and an event is emitted once, the listener would be invoked twice.
- *
- * @param events - The named events to listen for.
- * @param callback - The event listener.
- */
- on(events: EventType[], callback: CallbackType): void;
- /**
- * Registers the provided listener all events. If `on()` is called more than once with the same listener and event, the listener is added multiple times to its listener registry. Therefore, as an example, assuming the same listener is registered twice using `on()`, and an event is emitted once, the listener would be invoked twice.
- *
- * @param callback - The event listener.
- */
- on(callback: CallbackType): void;
- /**
- * Registers the provided listener for the first occurrence of a single named event specified as the `Event` argument. If `once` is called more than once with the same listener, the listener is added multiple times to its listener registry. Therefore, as an example, assuming the same listener is registered twice using `once`, and an event is emitted once, the listener would be invoked twice. However, all subsequent events emitted would not invoke the listener as `once` ensures that each registration is only invoked once.
- *
- * @param event - The named event to listen for.
- * @param callback - The event listener.
- */
- once(event: EventType, callback: CallbackType): void;
- /**
- * Registers the provided listener for the first event that is emitted. If `once()` is called more than once with the same listener, the listener is added multiple times to its listener registry. Therefore, as an example, assuming the same listener is registered twice using `once()`, and an event is emitted once, the listener would be invoked twice. However, all subsequent events emitted would not invoke the listener as `once()` ensures that each registration is only invoked once.
- *
- * @param callback - The event listener.
- */
- once(callback: CallbackType): void;
- /**
- * Returns a promise which resolves upon the first occurrence of a single named event specified as the `Event` argument.
- *
- * @param event - The named event to listen for.
- * @returns A promise which resolves upon the first occurrence of the named event.
- */
- once(event: EventType): Promise;
- /**
- * Returns a promise which resolves upon the first occurrence of an event.
- *
- * @returns A promise which resolves upon the first occurrence of an event.
- */
- once(): Promise;
- /**
- * Removes all registrations that match both the specified listener and the specified event.
- *
- * @param event - The named event.
- * @param callback - The event listener.
- */
- off(event: EventType, callback: CallbackType): void;
- /**
- * Deregisters the specified listener. Removes all registrations matching the given listener, regardless of whether they are associated with an event or not.
- *
- * @param callback - The event listener.
- */
- off(callback: CallbackType): void;
- /**
- * Deregisters all registrations, for all events and listeners.
- */
- off(): void;
- /**
- * Returns the listeners for a specified `EventType`.
- *
- * @param eventName - The event name to retrieve the listeners for.
- */
- listeners(eventName?: EventType): CallbackType[] | null;
- }
+ channels: string[];
+ /**
+ * An array of {@link Message} objects.
+ */
+ messages: Message[];
+}
- // Classes
+/**
+ * Contains information about the result of successful publishes to a channel requested by a single {@link BatchPublishSpec}.
+ */
+export interface BatchPublishSuccessResult {
/**
- * The `RestBase` class acts as a base class for the {@link RestCallbacks} and {@link RestPromise} classes.
+ * The name of the channel the message(s) was published to.
*/
- class RestBase {
- /**
- * Construct a client object using an Ably {@link Types.ClientOptions} object.
- *
- * @param options - A {@link Types.ClientOptions} object to configure the client connection to Ably.
- */
- constructor(options: Types.ClientOptions);
- /**
- * Constructs a client object using an Ably API key or token string.
- *
- * @param keyOrToken - The Ably API key or token string used to validate the client.
- */
- constructor(keyOrToken: string);
- /**
- * The cryptographic functions available in the library.
- */
- static Crypto: Types.Crypto;
- /**
- * Static utilities related to messages.
- */
- static Message: Types.MessageStatic;
- /**
- * Static utilities related to presence messages.
- */
- static PresenceMessage: Types.PresenceMessageStatic;
- }
+ channel: string;
+ /**
+ * A unique ID prefixed to the {@link Message.id} of each published message.
+ */
+ messageId: string;
+}
+/**
+ * Contains information about the result of unsuccessful publishes to a channel requested by a single {@link BatchPublishSpec}.
+ */
+export interface BatchPublishFailureResult {
/**
- * A client that offers a simple stateless API to interact directly with Ably's REST API.
+ * The name of the channel the message(s) failed to be published to.
*/
- class RestCallbacks extends RestBase {
- /**
- * A promisified version of the library (use this if you prefer to use Promises or async/await instead of callbacks)
- */
- static Promise: typeof Types.RestPromise;
- /**
- * A callback based version of the library
- */
- static Callbacks: typeof Types.RestCallbacks;
- /**
- * An {@link Types.AuthCallbacks} object.
- */
- auth: Types.AuthCallbacks;
- /**
- * A {@link Types.Channels} object.
- */
- channels: Types.Channels;
- /**
- * Makes a REST request to a provided path. This is provided as a convenience for developers who wish to use REST API functionality that is either not documented or is not yet included in the public API, without having to directly handle features such as authentication, paging, fallback hosts, MsgPack and JSON support.
- *
- * @param method - The request method to use, such as `GET`, `POST`.
- * @param path - The request path.
- * @param params - The parameters to include in the URL query of the request. The parameters depend on the endpoint being queried. See the [REST API reference](https://ably.com/docs/api/rest-api) for the available parameters of each endpoint.
- * @param body - The JSON body of the request.
- * @param headers - Additional HTTP headers to include in the request.
- * @param callback - A function which, upon success, will be called with an {@link Types.HttpPaginatedResponse} response object returned by the HTTP request. This response object will contain an empty or JSON-encodable object. Upon failure, the function will be called with information about the error.
- */
- request(
- method: string,
- path: string,
- params?: any,
- body?: any[] | any,
- headers?: any,
- callback?: Types.StandardCallback>
- ): void;
- /**
- * Queries the REST `/stats` API and retrieves your application's usage statistics. Returns a {@link Types.PaginatedResult} object, containing an array of {@link Types.Stats} objects. See the [Stats docs](https://ably.com/docs/general/statistics).
- *
- * @param params - A set of parameters which are used to specify which statistics should be retrieved. This parameter should be a {@link Types.StatsParams} object. For reasons of backwards compatibility this parameter will also accept `any`; this ability will be removed in the next major release of this SDK. If you do not provide this argument, then this method will use the default parameters described in the {@link Types.StatsParams} interface.
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link Types.Stats} objects. Upon failure, the function will be called with information about the error.
- */
- stats(params?: StatsParams | any, callback?: Types.paginatedResultCallback): void;
- /**
- * Queries the REST `/stats` API and retrieves your application's usage statistics, using the default parameters described in the {@link Types.StatsParams} interface. Returns a {@link Types.PaginatedResult} object, containing an array of {@link Types.Stats} objects. See the [Stats docs](https://ably.com/docs/general/statistics).
- *
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link Types.Stats} objects. Upon failure, the function will be called with information about the error.
- */
- stats(callback?: Types.paginatedResultCallback): void;
- /**
- * Retrieves the time from the Ably service as milliseconds since the Unix epoch. Clients that do not have access to a sufficiently well maintained time source and wish to issue Ably {@link Types.TokenRequest | `TokenRequest`s} with a more accurate timestamp should use the {@link Types.ClientOptions.queryTime} property instead of this method.
- *
- * @param callback - A function which, upon success, will be called with the time as milliseconds since the Unix epoch. Upon failure, the function will be called with information about the error.
- */
- time(callback?: Types.timeCallback): void;
- /**
- * Publishes a {@link Types.BatchPublishSpec} object to one or more channels, up to a maximum of 100 channels.
- *
- * @param spec - A {@link Types.BatchPublishSpec} object.
- * @param callback - A function which, upon success, will be called with a {@link Types.BatchResult} object containing information about the result of the batch publish for each requested channel. Upon failure, the function will be called with information about the error.
- */
- batchPublish(
- spec: BatchPublishSpec,
- callback: StandardCallback>
- ): void;
- /**
- * Publishes one or more {@link Types.BatchPublishSpec} objects to one or more channels, up to a maximum of 100 channels.
- *
- * @param specs - An array of {@link Types.BatchPublishSpec} objects.
- * @param callback - A function which, upon success, will be called with an array of {@link Types.BatchResult} objects containing information about the result of the batch publish for each requested channel for each provided {@link Types.BatchPublishSpec}. This array is in the same order as the provided {@link Types.BatchPublishSpec} array. Upon failure, the function will be called with information about the error.
- */
- batchPublish(
- specs: BatchPublishSpec[],
- callback: StandardCallback[]>
- ): void;
- /**
- * Retrieves the presence state for one or more channels, up to a maximum of 100 channels. Presence state includes the `clientId` of members and their current {@link Types.PresenceAction}.
- *
- * @param channels - An array of one or more channel names, up to a maximum of 100 channels.
- * @param callback - A function which, upon success, will be called with a {@link Types.BatchResult} object containing information about the result of the batch presence request for each requested channel. Upon failure, the function will be called with information about the error.
- */
- batchPresence(
- channels: string[],
- callback: StandardCallback>
- ): void;
- /**
- * A {@link Types.PushCallbacks} object.
- */
- push: Types.PushCallbacks;
- }
-
+ channel: string;
/**
- * A client that offers a simple stateless API to interact directly with Ably's REST API.
+ * Describes the reason for which the message(s) failed to publish to the channel as an {@link ErrorInfo} object.
*/
- class RestPromise extends RestBase {
- /**
- * A promisified version of the library (use this if you prefer to use Promises or async/await instead of callbacks)
- */
- static Promise: typeof Types.RestPromise;
- /**
- * A callback based version of the library
- */
- static Callbacks: typeof Types.RestCallbacks;
- /**
- * An {@link Types.AuthPromise} object.
- */
- auth: Types.AuthPromise;
- /**
- * A {@link Types.Channels} object.
- */
- channels: Types.Channels;
- /**
- * Makes a REST request to a provided path. This is provided as a convenience for developers who wish to use REST API functionality that is either not documented or is not yet included in the public API, without having to directly handle features such as authentication, paging, fallback hosts, MsgPack and JSON support.
- *
- * @param method - The request method to use, such as `GET`, `POST`.
- * @param path - The request path.
- * @param params - The parameters to include in the URL query of the request. The parameters depend on the endpoint being queried. See the [REST API reference](https://ably.com/docs/api/rest-api) for the available parameters of each endpoint.
- * @param body - The JSON body of the request.
- * @param headers - Additional HTTP headers to include in the request.
- * @returns A promise which, upon success, will be fulfilled with an {@link Types.HttpPaginatedResponse} response object returned by the HTTP request. This response object will contain an empty or JSON-encodable object. Upon failure, the promise will be rejected with an {@link Types.ErrorInfo} object which explains the error.
- */
- request(
- method: string,
- path: string,
- params?: any,
- body?: any[] | any,
- headers?: any
- ): Promise>;
- /**
- * Queries the REST `/stats` API and retrieves your application's usage statistics. Returns a {@link Types.PaginatedResult} object, containing an array of {@link Types.Stats} objects. See the [Stats docs](https://ably.com/docs/general/statistics).
- *
- * @param params - A set of parameters which are used to specify which statistics should be retrieved. This parameter should be a {@link Types.StatsParams} object. For reasons of backwards compatibility this parameter will also accept `any`; this ability will be removed in the next major release of this SDK. If you do not provide this argument, then this method will use the default parameters described in the {@link Types.StatsParams} interface.
- * @returns A promise which, upon success, will be fulfilled with a {@link Types.PaginatedResult} object containing an array of {@link Types.Stats} objects. Upon failure, the promise will be rejected with an {@link Types.ErrorInfo} object which explains the error.
- */
- stats(params?: StatsParams | any): Promise>;
- /**
- * Retrieves the time from the Ably service as milliseconds since the Unix epoch. Clients that do not have access to a sufficiently well maintained time source and wish to issue Ably {@link Types.TokenRequest | `TokenRequest`s} with a more accurate timestamp should use the {@link Types.ClientOptions.queryTime} property instead of this method.
- *
- * @returns A promise which, upon success, will be fulfilled with the time as milliseconds since the Unix epoch. Upon failure, the promise will be rejected with an {@link Types.ErrorInfo} object which explains the error.
- */
- time(): Promise;
-
- /**
- * Publishes a {@link Types.BatchPublishSpec} object to one or more channels, up to a maximum of 100 channels.
- *
- * @param spec - A {@link Types.BatchPublishSpec} object.
- * @returns A promise which, upon success, will be fulfilled with a {@link Types.BatchResult} object containing information about the result of the batch publish for each requested channel. Upon failure, the promise will be rejected with an {@link Types.ErrorInfo} object which explains the error.
- */
- batchPublish(spec: BatchPublishSpec): Promise>;
- /**
- * Publishes one or more {@link Types.BatchPublishSpec} objects to one or more channels, up to a maximum of 100 channels.
- *
- * @param specs - An array of {@link Types.BatchPublishSpec} objects.
- * @returns A promise which, upon success, will be fulfilled with an array of {@link Types.BatchResult} objects containing information about the result of the batch publish for each requested channel for each provided {@link Types.BatchPublishSpec}. This array is in the same order as the provided {@link Types.BatchPublishSpec} array. Upon failure, the promise will be rejected with an {@link Types.ErrorInfo} object which explains the error.
- */
- batchPublish(
- specs: BatchPublishSpec[]
- ): Promise[]>;
- /**
- * Retrieves the presence state for one or more channels, up to a maximum of 100 channels. Presence state includes the `clientId` of members and their current {@link Types.PresenceAction}.
- *
- * @param channels - An array of one or more channel names, up to a maximum of 100 channels.
- * @returns A promise which, upon success, will be fulfilled with a {@link Types.BatchResult} object containing information about the result of the batch presence request for each requested channel. Upon failure, the promise will be rejected with an {@link Types.ErrorInfo} object which explains the error.
- */
- batchPresence(channels: string[]): Promise[]>;
- /**
- * A {@link Types.PushPromise} object.
- */
- push: Types.PushPromise;
- }
+ error: ErrorInfo;
+}
+/**
+ * Contains information about the result of a successful batch presence request for a single channel.
+ */
+export interface BatchPresenceSuccessResult {
/**
- * A base class used internally for Realtime APIs.
+ * The channel name the presence state was retrieved for.
*/
- class RealtimeBase extends RestBase {
- /**
- * A promisified version of the library (use this if you prefer to use Promises or async/await instead of callbacks)
- */
- static Promise: typeof Types.RealtimePromise;
- /**
- * A callback based version of the library
- */
- static Callbacks: typeof Types.RealtimeCallbacks;
- /**
- * A client ID, used for identifying this client when publishing messages or for presence purposes. The `clientId` can be any non-empty string, except it cannot contain a `*`. This option is primarily intended to be used in situations where the library is instantiated with a key. A `clientId` may also be implicit in a token used to instantiate the library; an error will be raised if a `clientId` specified here conflicts with the `clientId` implicit in the token.
- */
- clientId: string;
- /**
- * Calls {@link Types.ConnectionBase.close | `connection.close()`} and causes the connection to close, entering the closing state. Once closed, the library will not attempt to re-establish the connection without an explicit call to {@link Types.ConnectionBase.connect | `connect()`}.
- */
- close(): void;
- /**
- * Calls {@link Types.ConnectionBase.connect | `connection.connect()`} and causes the connection to open, entering the connecting state. Explicitly calling `connect()` is unnecessary unless the {@link Types.ClientOptions.autoConnect} property is disabled.
- */
- connect(): void;
- }
-
+ channel: string;
/**
- * A client that extends the functionality of {@link RestCallbacks} and provides additional realtime-specific features.
+ * An array of {@link PresenceMessage}s describing members present on the channel.
*/
- class RealtimeCallbacks extends RealtimeBase {
- /**
- * An {@link Types.AuthCallbacks} object.
- */
- auth: Types.AuthCallbacks;
- /**
- * A {@link Types.Channels} object.
- */
- channels: Types.Channels;
- /**
- * A {@link Types.ConnectionCallbacks} object.
- */
- connection: Types.ConnectionCallbacks;
- /**
- * Makes a REST request to a provided path. This is provided as a convenience for developers who wish to use REST API functionality that is either not documented or is not yet included in the public API, without having to directly handle features such as authentication, paging, fallback hosts, MsgPack and JSON support.
- *
- * @param method - The request method to use, such as `GET`, `POST`.
- * @param path - The request path.
- * @param params - The parameters to include in the URL query of the request. The parameters depend on the endpoint being queried. See the [REST API reference](https://ably.com/docs/api/rest-api) for the available parameters of each endpoint.
- * @param body - The JSON body of the request.
- * @param headers - Additional HTTP headers to include in the request.
- * @param callback - A function which, upon success, will be called with the {@link Types.HttpPaginatedResponse} response object returned by the HTTP request. This response object will contain an empty or JSON-encodable object. Upon failure, the function will be called with information about the error.
- */
- request(
- method: string,
- path: string,
- params?: any,
- body?: any[] | any,
- headers?: any,
- callback?: Types.StandardCallback>
- ): void;
- /**
- * Queries the REST `/stats` API and retrieves your application's usage statistics. Returns a {@link Types.PaginatedResult} object, containing an array of {@link Types.Stats} objects. See the [Stats docs](https://ably.com/docs/general/statistics).
- *
- * @param params - A set of parameters which are used to specify which statistics should be retrieved. This parameter should be a {@link Types.StatsParams} object. For reasons of backwards compatibility this parameter will also accept `any`; this ability will be removed in the next major release of this SDK.
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link Types.Stats} objects. Upon failure, the function will be called with information about the error.
- */
- stats(params: StatsParams | any, callback: Types.paginatedResultCallback): void;
- /**
- * Queries the REST `/stats` API and retrieves your application's usage statistics, using the default parameters described in the {@link Types.StatsParams} interface. Returns a {@link Types.PaginatedResult} object, containing an array of {@link Types.Stats} objects. See the [Stats docs](https://ably.com/docs/general/statistics).
- *
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link Types.Stats} objects. Upon failure, the function will be called with information about the error.
- */
- stats(callback: Types.paginatedResultCallback): void;
- /**
- * Retrieves the time from the Ably service as milliseconds since the Unix epoch. Clients that do not have access to a sufficiently well maintained time source and wish to issue Ably {@link Types.TokenRequest | `TokenRequest`s} with a more accurate timestamp should use the {@link Types.ClientOptions.queryTime} property instead of this method.
- *
- * @param callback - A function which, upon success, will be called with the time as milliseconds since the Unix epoch. Upon failure, the function will be called with information about the error.
- */
- time(callback?: Types.timeCallback): void;
- /**
- * Publishes a {@link Types.BatchPublishSpec} object to one or more channels, up to a maximum of 100 channels.
- *
- * @param spec - A {@link Types.BatchPublishSpec} object.
- * @param callback - A function which, upon success, will be called with a {@link Types.BatchResult} object containing information about the result of the batch publish for each requested channel. Upon failure, the function will be called with information about the error.
- */
- batchPublish(
- spec: BatchPublishSpec,
- callback: StandardCallback>
- ): void;
- /**
- * Publishes one or more {@link Types.BatchPublishSpec} objects to one or more channels, up to a maximum of 100 channels.
- *
- * @param specs - An array of {@link Types.BatchPublishSpec} objects.
- * @param callback - A function which, upon success, will be called with an array of {@link Types.BatchResult} objects containing information about the result of the batch publish for each requested channel for each provided {@link Types.BatchPublishSpec}. This array is in the same order as the provided {@link Types.BatchPublishSpec} array. Upon failure, the function will be called with information about the error.
- */
- batchPublish(
- specs: BatchPublishSpec[],
- callback: StandardCallback[]>
- ): void;
- /**
- * Retrieves the presence state for one or more channels, up to a maximum of 100 channels. Presence state includes the `clientId` of members and their current {@link Types.PresenceAction}.
- *
- * @param channels - An array of one or more channel names, up to a maximum of 100 channels.
- * @param callback - A function which, upon success, will be called with a {@link Types.BatchResult} object containing information about the result of the batch presence request for each requested channel. Upon failure, the function will be called with information about the error.
- */
- batchPresence(
- channels: string[],
- callback: StandardCallback[]>
- ): void;
- /**
- * A {@link Types.PushCallbacks} object.
- */
- push: Types.PushCallbacks;
- }
+ presence: PresenceMessage[];
+}
+/**
+ * Contains information about the result of an unsuccessful batch presence request for a single channel.
+ */
+export interface BatchPresenceFailureResult {
/**
- * A client that extends the functionality of {@link RestPromise} and provides additional realtime-specific features.
+ * The channel name the presence state failed to be retrieved for.
*/
- class RealtimePromise extends RealtimeBase {
- /**
- * An {@link Types.AuthPromise} object.
- */
- auth: Types.AuthPromise;
- /**
- * A {@link Types.Channels} object.
- */
- channels: Types.Channels;
- /**
- * A {@link Types.ConnectionPromise} object.
- */
- connection: Types.ConnectionPromise;
- /**
- * Makes a REST request to a provided path. This is provided as a convenience for developers who wish to use REST API functionality that is either not documented or is not yet included in the public API, without having to directly handle features such as authentication, paging, fallback hosts, MsgPack and JSON support.
- *
- * @param method - The request method to use, such as `GET`, `POST`.
- * @param path - The request path.
- * @param params - The parameters to include in the URL query of the request. The parameters depend on the endpoint being queried. See the [REST API reference](https://ably.com/docs/api/rest-api) for the available parameters of each endpoint.
- * @param body - The JSON body of the request.
- * @param headers - Additional HTTP headers to include in the request.
- * @returns A promise which, upon success, will be fulfilled with the {@link Types.HttpPaginatedResponse} response object returned by the HTTP request. This response object will contain an empty or JSON-encodable object. Upon failure, the promise will be rejected with an {@link Types.ErrorInfo} object which explains the error.
- */
- request(
- method: string,
- path: string,
- params?: any,
- body?: any[] | any,
- headers?: any
- ): Promise>;
- /**
- * Queries the REST `/stats` API and retrieves your application's usage statistics. Returns a {@link Types.PaginatedResult} object, containing an array of {@link Types.Stats} objects. See the [Stats docs](https://ably.com/docs/general/statistics).
- *
- * @param params - A set of parameters which are used to specify which statistics should be retrieved. This parameter should be a {@link Types.StatsParams} object. For reasons of backwards compatibility this parameter will also accept `any`; this ability will be removed in the next major release of this SDK. If you do not provide this argument, then this method will use the default parameters described in the {@link Types.StatsParams} interface.
- * @returns A promise which, upon success, will be fulfilled with a {@link Types.PaginatedResult} object containing an array of {@link Types.Stats} objects. Upon failure, the promise will be rejected with an {@link Types.ErrorInfo} object which explains the error.
- */
- stats(params?: StatsParams | any): Promise>;
- /**
- * Retrieves the time from the Ably service as milliseconds since the Unix epoch. Clients that do not have access to a sufficiently well maintained time source and wish to issue Ably {@link Types.TokenRequest | `TokenRequest`s} with a more accurate timestamp should use the {@link Types.ClientOptions.queryTime} property instead of this method.
- *
- * @returns A promise which, upon success, will be fulfilled with the time as milliseconds since the Unix epoch. Upon failure, the promise will be rejected with an {@link Types.ErrorInfo} object which explains the error.
- */
- time(): Promise;
- /**
- * Publishes a {@link Types.BatchPublishSpec} object to one or more channels, up to a maximum of 100 channels.
- *
- * @param spec - A {@link Types.BatchPublishSpec} object.
- * @returns A promise which, upon success, will be fulfilled with a {@link Types.BatchResult} object containing information about the result of the batch publish for each requested channel. Upon failure, the promise will be rejected with an {@link Types.ErrorInfo} object which explains the error.
- */
- batchPublish(spec: BatchPublishSpec): Promise>;
- /**
- * Publishes one or more {@link Types.BatchPublishSpec} objects to one or more channels, up to a maximum of 100 channels.
- *
- * @param specs - An array of {@link Types.BatchPublishSpec} objects.
- * @returns A promise which, upon success, will be fulfilled with an array of {@link Types.BatchResult} objects containing information about the result of the batch publish for each requested channel for each provided {@link Types.BatchPublishSpec}. This array is in the same order as the provided {@link Types.BatchPublishSpec} array. Upon failure, the promise will be rejected with an {@link Types.ErrorInfo} object which explains the error.
- */
- batchPublish(
- specs: BatchPublishSpec[]
- ): Promise[]>;
- /**
- * Retrieves the presence state for one or more channels, up to a maximum of 100 channels. Presence state includes the `clientId` of members and their current {@link Types.PresenceAction}.
- *
- * @param channels - An array of one or more channel names, up to a maximum of 100 channels.
- * @returns A promise which, upon success, will be fulfilled with a {@link Types.BatchResult} object containing information about the result of the batch presence request for each requested channel. Upon failure, the promise will be rejected with an {@link Types.ErrorInfo} object which explains the error.
- */
- batchPresence(channels: string[]): Promise[]>;
- /**
- * A {@link Types.PushPromise} object.
- */
- push: Types.PushPromise;
- }
-
+ channel: string;
/**
- * The `AuthBase` class acts as a base class for the {@link AuthCallbacks} and {@link AuthPromise} classes.
+ * Describes the reason for which presence state could not be retrieved for the channel as an {@link ErrorInfo} object.
*/
- class AuthBase {
- /**
- * A client ID, used for identifying this client when publishing messages or for presence purposes. The `clientId` can be any non-empty string, except it cannot contain a `*`. This option is primarily intended to be used in situations where the library is instantiated with a key. Note that a `clientId` may also be implicit in a token used to instantiate the library. An error is raised if a `clientId` specified here conflicts with the `clientId` implicit in the token. Find out more about [identified clients](https://ably.com/docs/core-features/authentication#identified-clients).
- */
- clientId: string;
- }
+ error: ErrorInfo;
+}
+/**
+ * The `TokenRevocationOptions` interface describes the additional options accepted by {@link Auth.revokeTokens}.
+ */
+export interface TokenRevocationOptions {
/**
- * Creates Ably {@link TokenRequest} objects and obtains Ably Tokens from Ably to subsequently issue to less trusted clients.
+ * A Unix timestamp in milliseconds where only tokens issued before this time are revoked. The default is the current time. Requests with an `issuedBefore` in the future, or more than an hour in the past, will be rejected.
*/
- class AuthCallbacks extends AuthBase {
- /**
- * Instructs the library to get a new token immediately. When using the realtime client, it upgrades the current realtime connection to use the new token, or if not connected, initiates a connection to Ably, once the new token has been obtained. Also stores any {@link TokenParams} and {@link AuthOptions} passed in as the new defaults, to be used for all subsequent implicit or explicit token requests. Any {@link TokenParams} and {@link AuthOptions} objects passed in entirely replace, as opposed to being merged with, the current client library saved values.
- *
- * @param tokenParams - A {@link TokenParams} object.
- * @param authOptions - An {@link AuthOptions} object.
- * @param callback - A function which, upon success, will be called with a {@link TokenDetails} object. Upon failure, the function will be called with information about the error.
- */
- authorize(tokenParams?: TokenParams, authOptions?: AuthOptions, callback?: tokenDetailsCallback): void;
- /**
- * Instructs the library to get a new token immediately. When using the realtime client, it upgrades the current realtime connection to use the new token, or if not connected, initiates a connection to Ably, once the new token has been obtained. Also stores any {@link TokenParams} passed in as the new default, to be used for all subsequent implicit or explicit token requests. Any {@link TokenParams} object passed in entirely replaces, as opposed to being merged with, the current client library saved value.
- *
- * @param tokenParams - A {@link TokenParams} object.
- * @param callback - A function which, upon success, will be called with a {@link TokenDetails} object. Upon failure, the function will be called with information about the error.
- */
- authorize(tokenParams?: TokenParams, callback?: tokenDetailsCallback): void;
- /**
- * Instructs the library to get a new token immediately. When using the realtime client, it upgrades the current realtime connection to use the new token, or if not connected, initiates a connection to Ably, once the new token has been obtained.
- *
- * @param callback - A function which, upon success, will be called with a {@link TokenDetails} object. Upon failure, the function will be called with information about the error.
- */
- authorize(callback?: tokenDetailsCallback): void;
- /**
- * Creates and signs an Ably {@link TokenRequest} based on the specified (or if none specified, the client library stored) {@link TokenParams} and {@link AuthOptions}. Note this can only be used when the API `key` value is available locally. Otherwise, the Ably {@link TokenRequest} must be obtained from the key owner. Use this to generate an Ably {@link TokenRequest} in order to implement an Ably Token request callback for use by other clients. Both {@link TokenParams} and {@link AuthOptions} are optional. When omitted or `null`, the default token parameters and authentication options for the client library are used, as specified in the {@link ClientOptions} when the client library was instantiated, or later updated with an explicit `authorize` request. Values passed in are used instead of, rather than being merged with, the default values. To understand why an Ably {@link TokenRequest} may be issued to clients in favor of a token, see [Token Authentication explained](https://ably.com/docs/core-features/authentication/#token-authentication).
- *
- * @param tokenParams - A {@link TokenParams} object.
- * @param authOptions - An {@link AuthOptions} object.
- * @param callback - A function which, upon success, will be called with a {@link TokenRequest} object. Upon failure, the function will be called with information about the error.
- */
- createTokenRequest(
- tokenParams?: TokenParams | null,
- authOptions?: AuthOptions | null,
- callback?: tokenRequestCallback
- ): void;
- /**
- * Creates and signs an Ably {@link TokenRequest} based on the specified (or if none specified, the client library stored) {@link TokenParams}. Note this can only be used when the API `key` value is available locally. Otherwise, the Ably {@link TokenParams} must be obtained from the key owner. Use this to generate an Ably {@link TokenRequest} in order to implement an Ably Token request callback for use by other clients. When the {@link TokenRequest} is omitted or `null`, the default token parameters for the client library are used, as specified in the {@link ClientOptions} when the client library was instantiated, or later updated with an explicit `authorize` request. Values passed in are used instead of, rather than being merged with, the default values. To understand why an Ably {@link TokenRequest} may be issued to clients in favor of a token, see [Token Authentication explained](https://ably.com/docs/core-features/authentication/#token-authentication).
- *
- * @param tokenParams - A {@link TokenParams} object.
- * @param callback - A function which, upon success, will be called with a {@link TokenRequest} object. Upon failure, the function will be called with information about the error.
- */
- createTokenRequest(tokenParams?: TokenParams | null, callback?: tokenRequestCallback): void;
- /**
- * Creates and signs an Ably {@link TokenRequest} based on the the client library stored {@link TokenParams} and {@link AuthOptions}. Note this can only be used when the API `key` value is available locally. Otherwise, the Ably {@link TokenRequest} must be obtained from the key owner. Use this to generate an Ably {@link TokenRequest} in order to implement an Ably Token request callback for use by other clients. The default token parameters and authentication options for the client library are used, as specified in the {@link ClientOptions} when the client library was instantiated, or later updated with an explicit `authorize` request. To understand why an Ably {@link TokenRequest} may be issued to clients in favor of a token, see [Token Authentication explained](https://ably.com/docs/core-features/authentication/#token-authentication).
- *
- * @param callback - A function which, upon success, will be called with a {@link TokenRequest} object. Upon failure, the function will be called with information about the error.
- */
- createTokenRequest(callback?: tokenRequestCallback): void;
- /**
- * Calls the `requestToken` REST API endpoint to obtain an Ably Token according to the specified {@link TokenParams} and {@link AuthOptions}. Both {@link TokenParams} and {@link AuthOptions} are optional. When omitted or `null`, the default token parameters and authentication options for the client library are used, as specified in the {@link ClientOptions} when the client library was instantiated, or later updated with an explicit `authorize` request. Values passed in are used instead of, rather than being merged with, the default values. To understand why an Ably {@link TokenRequest} may be issued to clients in favor of a token, see [Token Authentication explained](https://ably.com/docs/core-features/authentication/#token-authentication).
- *
- * @param TokenParams - A {@link TokenParams} object.
- * @param authOptions - An {@link AuthOptions} object.
- * @param callback - A function which, upon success, will be called with a {@link TokenDetails} object. Upon failure, the function will be called with information about the error.
- */
- requestToken(
- TokenParams?: TokenParams | null,
- authOptions?: AuthOptions | null,
- callback?: tokenDetailsCallback
- ): void;
- /**
- * Calls the `requestToken` REST API endpoint to obtain an Ably Token according to the specified {@link TokenParams}. When omitted or `null`, the default token parameters and authentication options for the client library are used, as specified in the {@link ClientOptions} when the client library was instantiated, or later updated with an explicit `authorize` request. Values passed in are used instead of, rather than being merged with, the default values. To understand why an Ably {@link TokenRequest} may be issued to clients in favor of a token, see [Token Authentication explained](https://ably.com/docs/core-features/authentication/#token-authentication).
- *
- * @param TokenParams - A {@link TokenParams} object.
- * @param callback - A function which, upon success, will be called with a {@link TokenDetails} object. Upon failure, the function will be called with information about the error.
- */
- requestToken(TokenParams?: TokenParams | null, callback?: tokenDetailsCallback): void;
- /**
- * Calls the `requestToken` REST API endpoint to obtain an Ably Token. The default token parameters and authentication options for the client library are used, as specified in the {@link ClientOptions} when the client library was instantiated, or later updated with an explicit `authorize` request. To understand why an Ably {@link TokenRequest} may be issued to clients in favor of a token, see [Token Authentication explained](https://ably.com/docs/core-features/authentication/#token-authentication).
- *
- * @param callback - A function which, upon success, will be called with a {@link TokenDetails} object. Upon failure, the function will be called with information about the error.
- */
- requestToken(callback?: tokenDetailsCallback): void;
- /**
- * Revokes the tokens specified by the provided array of {@link TokenRevocationTargetSpecifier}s. Only tokens issued by an API key that had revocable tokens enabled before the token was issued can be revoked. See the [token revocation docs](https://ably.com/docs/core-features/authentication#token-revocation) for more information.
- *
- * @param specifiers - An array of {@link TokenRevocationTargetSpecifier} objects.
- * @param options - A set of options which are used to modify the revocation request.
- * @param callback - A function which, upon success, will be called with a {@link Types.BatchResult} containing information about the result of the token revocation request for each provided [`TokenRevocationTargetSpecifier`]{@link TokenRevocationTargetSpecifier}. Upon failure, the function will be called with information about the error.
- */
- revokeTokens(
- specifiers: TokenRevocationTargetSpecifier[],
- options?: TokenRevocationOptions,
- callback?: StandardCallback>
- ): void;
- }
-
+ issuedBefore?: number;
/**
- * Creates Ably {@link TokenRequest} objects and obtains Ably Tokens from Ably to subsequently issue to less trusted clients.
+ * If true, permits a token renewal cycle to take place without needing established connections to be dropped, by postponing enforcement to 30 seconds in the future, and sending any existing connections a hint to obtain (and upgrade the connection to use) a new token. The default is `false`, meaning that the effect is near-immediate.
*/
- class AuthPromise extends AuthBase {
- /**
- * Instructs the library to get a new token immediately. When using the realtime client, it upgrades the current realtime connection to use the new token, or if not connected, initiates a connection to Ably, once the new token has been obtained. Also stores any {@link TokenParams} and {@link AuthOptions} passed in as the new defaults, to be used for all subsequent implicit or explicit token requests. Any {@link TokenParams} and {@link AuthOptions} objects passed in entirely replace, as opposed to being merged with, the current client library saved values.
- *
- * @param tokenParams - A {@link TokenParams} object.
- * @param authOptions - An {@link AuthOptions} object.
- * @returns A promise which, upon success, will be fulfilled with a {@link TokenDetails} object. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
- */
- authorize(tokenParams?: TokenParams, authOptions?: AuthOptions): Promise;
- /**
- * Creates and signs an Ably {@link TokenRequest} based on the specified (or if none specified, the client library stored) {@link TokenParams} and {@link AuthOptions}. Note this can only be used when the API `key` value is available locally. Otherwise, the Ably {@link TokenRequest} must be obtained from the key owner. Use this to generate an Ably {@link TokenRequest} in order to implement an Ably Token request callback for use by other clients. Both {@link TokenParams} and {@link AuthOptions} are optional. When omitted or `null`, the default token parameters and authentication options for the client library are used, as specified in the {@link ClientOptions} when the client library was instantiated, or later updated with an explicit `authorize` request. Values passed in are used instead of, rather than being merged with, the default values. To understand why an Ably {@link TokenRequest} may be issued to clients in favor of a token, see [Token Authentication explained](https://ably.com/docs/core-features/authentication/#token-authentication).
- *
- * @param tokenParams - A {@link TokenParams} object.
- * @param authOptions - An {@link AuthOptions} object.
- * @returns A promise which, upon success, will be fulfilled with a {@link TokenRequest} object. Upon failure, the promise will be rejected with an {@link Types.ErrorInfo} object which explains the error.
- */
- createTokenRequest(tokenParams?: TokenParams, authOptions?: AuthOptions): Promise;
- /**
- * Calls the `requestToken` REST API endpoint to obtain an Ably Token according to the specified {@link TokenParams} and {@link AuthOptions}. Both {@link TokenParams} and {@link AuthOptions} are optional. When omitted or `null`, the default token parameters and authentication options for the client library are used, as specified in the {@link ClientOptions} when the client library was instantiated, or later updated with an explicit `authorize` request. Values passed in are used instead of, rather than being merged with, the default values. To understand why an Ably {@link TokenRequest} may be issued to clients in favor of a token, see [Token Authentication explained](https://ably.com/docs/core-features/authentication/#token-authentication).
- *
- * @param TokenParams - A {@link TokenParams} object.
- * @param authOptions - An {@link AuthOptions} object.
- * @returns A promise which, upon success, will be fulfilled with a {@link TokenDetails} object. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
- */
- requestToken(TokenParams?: TokenParams, authOptions?: AuthOptions): Promise;
- /**
- * Revokes the tokens specified by the provided array of {@link TokenRevocationTargetSpecifier}s. Only tokens issued by an API key that had revocable tokens enabled before the token was issued can be revoked. See the [token revocation docs](https://ably.com/docs/core-features/authentication#token-revocation) for more information.
- *
- * @param specifiers - An array of {@link TokenRevocationTargetSpecifier} objects.
- * @param options - A set of options which are used to modify the revocation request.
- * @returns A promise which, upon success, will be fulfilled with a {@link Types.BatchResult} containing information about the result of the token revocation request for each provided [`TokenRevocationTargetSpecifier`]{@link TokenRevocationTargetSpecifier}. Upon failure, the promise will be rejected with an {@link Types.ErrorInfo} object which explains the error.
- */
- revokeTokens(
- specifiers: TokenRevocationTargetSpecifier[],
- options?: TokenRevocationOptions
- ): Promise>;
- }
+ allowReauthMargin?: boolean;
+}
+/**
+ * Describes which tokens should be affected by a token revocation request.
+ */
+export interface TokenRevocationTargetSpecifier {
/**
- * Enables the retrieval of the current and historic presence set for a channel.
+ * The type of token revocation target specifier. Valid values include `clientId`, `revocationKey` and `channel`.
*/
- class PresenceCallbacks {
- /**
- * Retrieves the current members present on the channel and the metadata for each member, such as their {@link PresenceAction} and ID. Returns a {@link Types.PaginatedResult} object, containing an array of {@link PresenceMessage} objects.
- *
- * @param params - A set of parameters which are used to specify which presence members should be retrieved.
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link PresenceMessage} objects. Upon failure, the function will be called with information about the error.
- */
- get(params?: RestPresenceParams, callback?: paginatedResultCallback): void;
- /**
- * Retrieves the current members present on the channel and the metadata for each member, such as their [PresenceAction]{@link PresenceAction} and ID.
- *
- * @param callback - A function which, upon success, will be called with a [PaginatedResult]{@link PaginatedResult} object, containing an array of [PresenceMessage]{@link PresenceMessage} objects. Upon failure, the function will be called with information about the error.
- */
- get(callback?: paginatedResultCallback): void;
- /**
- * Retrieves a {@link Types.PaginatedResult} object, containing an array of historical {@link PresenceMessage} objects for the channel. If the channel is configured to persist messages, then presence messages can be retrieved from history for up to 72 hours in the past. If not, presence messages can only be retrieved from history for up to two minutes in the past.
- *
- * @param params - A set of parameters which are used to specify which messages should be retrieved.
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link PresenceMessage} objects. Upon failure, the function will be called with information about the error.
- */
- history(params: RestHistoryParams, callback?: paginatedResultCallback): void;
- /**
- * Retrieves a {@link Types.PaginatedResult} object, containing an array of historical {@link PresenceMessage} objects for the channel. If the channel is configured to persist messages, then presence messages can be retrieved from history for up to 72 hours in the past. If not, presence messages can only be retrieved from history for up to two minutes in the past.
- *
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link PresenceMessage} objects. Upon failure, the function will be called with information about the error.
- */
- history(callback: paginatedResultCallback): void;
- }
+ type: string;
+ /**
+ * The value of the token revocation target specifier.
+ */
+ value: string;
+}
+/**
+ * Contains information about the result of a successful token revocation request for a single target specifier.
+ */
+export interface TokenRevocationSuccessResult {
/**
- * Enables the retrieval of the current and historic presence set for a channel.
+ * The target specifier.
*/
- class PresencePromise {
- /**
- * Retrieves the current members present on the channel and the metadata for each member, such as their {@link PresenceAction} and ID. Returns a {@link Types.PaginatedResult} object, containing an array of {@link PresenceMessage} objects.
- *
- * @param params - A set of parameters which are used to specify which presence members should be retrieved.
- * @returns A promise which, upon success, will be fulfilled with a {@link Types.PaginatedResult} object containing an array of {@link PresenceMessage} objects. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
- */
- get(params?: RestPresenceParams): Promise>;
- /**
- * Retrieves a {@link Types.PaginatedResult} object, containing an array of historical {@link PresenceMessage} objects for the channel. If the channel is configured to persist messages, then presence messages can be retrieved from history for up to 72 hours in the past. If not, presence messages can only be retrieved from history for up to two minutes in the past.
- *
- * @param params - A set of parameters which are used to specify which messages should be retrieved.
- * @returns A promise which, upon success, will be fulfilled with a {@link Types.PaginatedResult} object containing an array of {@link PresenceMessage} objects. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
- */
- history(params?: RestHistoryParams): Promise>;
- }
+ target: string;
+ /**
+ * The time at which the token revocation will take effect, as a Unix timestamp in milliseconds.
+ */
+ appliesAt: number;
+ /**
+ * A Unix timestamp in milliseconds. Only tokens issued earlier than this time will be revoked.
+ */
+ issuedBefore: number;
+}
+/**
+ * Contains information about the result of an unsuccessful token revocation request for a single target specifier.
+ */
+export interface TokenRevocationFailureResult {
/**
- * The `RealtimePresenceBase` class acts as a base class for the {@link RealtimePresenceCallbacks} and {@link RealtimePresencePromise} classes.
+ * The target specifier.
*/
- class RealtimePresenceBase {
- /**
- * Indicates whether the presence set synchronization between Ably and the clients on the channel has been completed. Set to `true` when the sync is complete.
- */
- syncComplete: boolean;
- /**
- * Deregisters a specific listener that is registered to receive {@link PresenceMessage} on the channel for a given {@link PresenceAction}.
- *
- * @param presence - A specific {@link PresenceAction} to deregister the listener for.
- * @param listener - An event listener function.
- */
- unsubscribe(presence: PresenceAction, listener: messageCallback): void;
- /**
- * Deregisters a specific listener that is registered to receive {@link PresenceMessage} on the channel for a given array of {@link PresenceAction} objects.
- *
- * @param presence - An array of {@link PresenceAction} objects to deregister the listener for.
- * @param listener - An event listener function.
- */
- unsubscribe(presence: Array, listener: messageCallback): void;
+ target: string;
+ /**
+ * Describes the reason for which token revocation failed for the given `target` as an {@link ErrorInfo} object.
+ */
+ error: ErrorInfo;
+}
+
+// Common Listeners
+/**
+ * A callback which returns only a single argument, used for {@link RealtimeChannel} subscriptions.
+ *
+ * @param message - The message which triggered the callback.
+ */
+export type messageCallback = (message: T) => void;
+/**
+ * The callback used for the events emitted by {@link RealtimeChannel}.
+ *
+ * @param changeStateChange - The state change that occurred.
+ */
+export type channelEventCallback = (changeStateChange: ChannelStateChange) => void;
+/**
+ * The callback used for the events emitted by {@link Connection}.
+ *
+ * @param connectionStateChange - The state change that occurred.
+ */
+export type connectionEventCallback = (connectionStateChange: ConnectionStateChange) => void;
+/**
+ * The callback used by {@link recoverConnectionCallback}.
+ *
+ * @param shouldRecover - Whether the connection should be recovered.
+ */
+export type recoverConnectionCompletionCallback = (shouldRecover: boolean) => void;
+/**
+ * Used in {@link ClientOptions} to configure connection recovery behaviour.
+ *
+ * @param lastConnectionDetails - Details of the connection used by the connection recovery process.
+ * @param callback - A callback which is called when a connection recovery attempt is complete.
+ */
+export type recoverConnectionCallback = (
+ lastConnectionDetails: {
/**
- * Deregisters any listener that is registered to receive {@link PresenceMessage} on the channel for a specific {@link PresenceAction}
- *
- * @param presence - A specific {@link PresenceAction} to deregister the listeners for.
+ * The recovery key can be used by another client to recover this connection’s state in the `recover` client options property. See [connection state recover options](https://ably.com/documentation/realtime/connection/#connection-state-recover-options) for more information.
*/
- unsubscribe(presence: PresenceAction): void;
+ recoveryKey: string;
/**
- * Deregisters any listener that is registered to receive {@link PresenceMessage} on the channel for an array of {@link PresenceAction} objects
- *
- * @param presence - An array of {@link PresenceAction} objects to deregister the listeners for.
+ * The time at which the previous client was abruptly disconnected before the page was unloaded. This is represented as milliseconds since Unix epoch.
*/
- unsubscribe(presence: Array): void;
+ disconnectedAt: number;
/**
- * Deregisters a specific listener that is registered to receive {@link PresenceMessage} on the channel.
- *
- * @param listener - An event listener function.
+ * A clone of the `location` object of the previous page’s document object before the page was unloaded. A common use case for this attribute is to ensure that the previous page URL is the same as the current URL before allowing the connection to be recovered. For example, you may want the connection to be recovered only for page reloads, but not when a user navigates to a different page.
*/
- unsubscribe(listener: messageCallback): void;
+ location: string;
/**
- * Deregisters all listeners currently receiving {@link PresenceMessage} for the channel.
+ * The `clientId` of the client’s `Auth` object before the page was unloaded. A common use case for this attribute is to ensure that the current logged in user’s `clientId` matches the previous connection’s `clientId` before allowing the connection to be recovered. Ably prohibits changing a `clientId` for an existing connection, so any mismatch in `clientId` during a recover will result in the connection moving to the failed state.
*/
- unsubscribe(): void;
- }
+ clientId: string | null;
+ },
+ callback: recoverConnectionCompletionCallback,
+) => void;
+
+// Internal Interfaces
+// To allow a uniform (callback) interface between on and once even in the
+// promisified version of the lib, but still allow once to be used in a way
+// that returns a Promise if desired, EventEmitter uses method overloading to
+// present both methods
+/**
+ * A generic interface for event registration and delivery used in a number of the types in the Realtime client library. For example, the {@link Connection} object emits events for connection state using the `EventEmitter` pattern.
+ */
+export declare interface EventEmitter {
/**
- * Enables the presence set to be entered and subscribed to, and the historic presence set to be retrieved for a channel.
+ * Registers the provided listener for the specified event. If `on()` is called more than once with the same listener and event, the listener is added multiple times to its listener registry. Therefore, as an example, assuming the same listener is registered twice using `on()`, and an event is emitted once, the listener would be invoked twice.
+ *
+ * @param event - The named event to listen for.
+ * @param callback - The event listener.
*/
- class RealtimePresenceCallbacks extends RealtimePresenceBase {
- /**
- * Retrieves the current members present on the channel and the metadata for each member, such as their {@link PresenceAction} and ID. Returns an array of {@link PresenceMessage} objects.
- *
- * @param params - A set of parameters which are used to specify which presence members should be retrieved.
- * @param callback - A function which, upon success, will be called with an array of {@link PresenceMessage} objects. Upon failure, the function will be called with information about the error.
- */
- get(params?: RealtimePresenceParams, callback?: realtimePresenceGetCallback): void;
- /**
- * Retrieves the current members present on the channel and the metadata for each member, such as their {@link PresenceAction} and ID. Returns an array of {@link PresenceMessage} objects.
- *
- * @param callback - A function which, upon success, will be called with an array of {@link PresenceMessage} objects. Upon failure, the function will be called with information about the error.
- */
- get(callback?: realtimePresenceGetCallback): void;
- /**
- * Retrieves a {@link Types.PaginatedResult} object, containing an array of historical {@link PresenceMessage} objects for the channel. If the channel is configured to persist messages, then presence messages can be retrieved from history for up to 72 hours in the past. If not, presence messages can only be retrieved from history for up to two minutes in the past.
- *
- * @param params - A set of parameters which are used to specify which presence messages should be retrieved.
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link PresenceMessage} objects. Upon failure, the function will be called with information about the error.
- */
- history(params?: RealtimeHistoryParams, callback?: paginatedResultCallback): void;
- /**
- * Retrieves a {@link Types.PaginatedResult} object, containing an array of historical {@link PresenceMessage} objects for the channel. If the channel is configured to persist messages, then presence messages can be retrieved from history for up to 72 hours in the past. If not, presence messages can only be retrieved from history for up to two minutes in the past.
- *
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link PresenceMessage} objects. Upon failure, the function will be called with information about the error.
- */
- history(callback?: paginatedResultCallback): void;
- /**
- * Registers a listener that is called each time a {@link PresenceMessage} matching a given {@link PresenceAction}, or an action within an array of {@link PresenceAction | `PresenceAction`s}, is received on the channel, such as a new member entering the presence set.
- *
- * @param presence - A {@link PresenceAction} or an array of {@link PresenceAction | `PresenceAction`s} to register the listener for.
- * @param listener - An event listener function.
- * @param callbackWhenAttached - A function which will be called upon completion of the channel {@link RealtimeChannelCallbacks.attach | `attach()`} operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- subscribe(
- presence: PresenceAction | Array,
- listener?: messageCallback,
- callbackWhenAttached?: errorCallback
- ): void;
- /**
- * Registers a listener that is called each time a {@link PresenceMessage} is received on the channel, such as a new member entering the presence set.
- *
- * @param listener - An event listener function.
- * @param callbackWhenAttached - A function which will be called upon completion of the channel {@link RealtimeChannelCallbacks.attach | `attach()`} operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- subscribe(listener: messageCallback, callbackWhenAttached?: errorCallback): void;
- /**
- * Enters the presence set for the channel, passing a `data` payload. A `clientId` is required to be present on a channel.
- *
- * @param data - The data payload or {@link PresenceMessage} associated with the presence member.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- enter(data?: any, callback?: errorCallback): void;
- /**
- * Enters the presence set for the channel. A `clientId` is required to be present on a channel.
- *
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- enter(callback?: errorCallback): void;
- /**
- * Updates the `data` payload for a presence member. If called before entering the presence set, this is treated as an {@link PresenceAction.ENTER} event.
- *
- * @param data - The data payload or {@link PresenceMessage} object to update for the presence member.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- update(data?: any, callback?: errorCallback): void;
- /**
- * Leaves the presence set for the channel. A client must have previously entered the presence set before they can leave it.
- *
- * @param data - The data payload or {@link PresenceMessage} associated with the presence member.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- leave(data?: any, callback?: errorCallback): void;
- /**
- * Leaves the presence set for the channel. A client must have previously entered the presence set before they can leave it.
- *
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- leave(callback?: errorCallback): void;
- /**
- * Enters the presence set of the channel for a given `clientId`. Enables a single client to update presence on behalf of any number of clients using a single connection. The library must have been instantiated with an API key or a token bound to a wildcard `clientId`.
- *
- * @param clientId - The ID of the client to enter into the presence set.
- * @param data - The data payload or {@link PresenceMessage} associated with the presence member.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- enterClient(clientId: string, data?: any, callback?: errorCallback): void;
- /**
- * Enters the presence set of the channel for a given `clientId`. Enables a single client to update presence on behalf of any number of clients using a single connection. The library must have been instantiated with an API key or a token bound to a wildcard `clientId`.
- *
- * @param clientId - The ID of the client to enter into the presence set.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- enterClient(clientId: string, callback?: errorCallback): void;
- /**
- * Updates the `data` payload for a presence member using a given `clientId`. Enables a single client to update presence on behalf of any number of clients using a single connection. The library must have been instantiated with an API key or a token bound to a wildcard `clientId`.
- *
- * @param clientId - The ID of the client to update in the presence set.
- * @param data - The data payload or {@link PresenceMessage} object to update for the presence member.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- updateClient(clientId: string, data?: any, callback?: errorCallback): void;
- /**
- * Leaves the presence set of the channel for a given `clientId`. Enables a single client to update presence on behalf of any number of clients using a single connection. The library must have been instantiated with an API key or a token bound to a wildcard `clientId`.
- *
- * @param clientId - The ID of the client to leave the presence set for.
- * @param data - The data payload or {@link PresenceMessage} associated with the presence member.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- leaveClient(clientId: string, data?: any, callback?: errorCallback): void;
- /**
- * Leaves the presence set of the channel for a given `clientId`. Enables a single client to update presence on behalf of any number of clients using a single connection. The library must have been instantiated with an API key or a token bound to a wildcard `clientId`.
- *
- * @param clientId - The ID of the client to leave the presence set for.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- leaveClient(clientId: string, callback?: errorCallback): void;
- }
+ on(event: EventType, callback: CallbackType): void;
+ /**
+ * Registers the provided listener for the specified events. If `on()` is called more than once with the same listener and event, the listener is added multiple times to its listener registry. Therefore, as an example, assuming the same listener is registered twice using `on()`, and an event is emitted once, the listener would be invoked twice.
+ *
+ * @param events - The named events to listen for.
+ * @param callback - The event listener.
+ */
+ on(events: EventType[], callback: CallbackType): void;
+ /**
+ * Registers the provided listener all events. If `on()` is called more than once with the same listener and event, the listener is added multiple times to its listener registry. Therefore, as an example, assuming the same listener is registered twice using `on()`, and an event is emitted once, the listener would be invoked twice.
+ *
+ * @param callback - The event listener.
+ */
+ on(callback: CallbackType): void;
+ /**
+ * Registers the provided listener for the first occurrence of a single named event specified as the `Event` argument. If `once` is called more than once with the same listener, the listener is added multiple times to its listener registry. Therefore, as an example, assuming the same listener is registered twice using `once`, and an event is emitted once, the listener would be invoked twice. However, all subsequent events emitted would not invoke the listener as `once` ensures that each registration is only invoked once.
+ *
+ * @param event - The named event to listen for.
+ * @param callback - The event listener.
+ */
+ once(event: EventType, callback: CallbackType): void;
+ /**
+ * Registers the provided listener for the first event that is emitted. If `once()` is called more than once with the same listener, the listener is added multiple times to its listener registry. Therefore, as an example, assuming the same listener is registered twice using `once()`, and an event is emitted once, the listener would be invoked twice. However, all subsequent events emitted would not invoke the listener as `once()` ensures that each registration is only invoked once.
+ *
+ * @param callback - The event listener.
+ */
+ once(callback: CallbackType): void;
+ /**
+ * Returns a promise which resolves upon the first occurrence of a single named event specified as the `Event` argument.
+ *
+ * @param event - The named event to listen for.
+ * @returns A promise which resolves upon the first occurrence of the named event.
+ */
+ once(event: EventType): Promise;
+ /**
+ * Returns a promise which resolves upon the first occurrence of an event.
+ *
+ * @returns A promise which resolves upon the first occurrence of an event.
+ */
+ once(): Promise;
+ /**
+ * Removes all registrations that match both the specified listener and the specified event.
+ *
+ * @param event - The named event.
+ * @param callback - The event listener.
+ */
+ off(event: EventType, callback: CallbackType): void;
+ /**
+ * Deregisters the specified listener. Removes all registrations matching the given listener, regardless of whether they are associated with an event or not.
+ *
+ * @param callback - The event listener.
+ */
+ off(callback: CallbackType): void;
+ /**
+ * Deregisters all registrations, for all events and listeners.
+ */
+ off(): void;
+ /**
+ * Returns the listeners for a specified `EventType`.
+ *
+ * @param eventName - The event name to retrieve the listeners for.
+ */
+ listeners(eventName?: EventType): CallbackType[] | null;
+}
+// Interfaces
+/**
+ * A client that offers a simple stateless API to interact directly with Ably's REST API.
+ */
+export declare interface RestClient {
/**
- * Enables the presence set to be entered and subscribed to, and the historic presence set to be retrieved for a channel.
+ * An {@link Auth} object.
*/
- class RealtimePresencePromise extends RealtimePresenceBase {
- /**
- * Retrieves the current members present on the channel and the metadata for each member, such as their {@link PresenceAction} and ID. Returns an array of {@link PresenceMessage} objects.
- *
- * @param params - A set of parameters which are used to specify which presence members should be retrieved.
- * @returns A promise which, upon success, will be fulfilled with an array of {@link PresenceMessage} objects. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
- */
- get(params?: RealtimePresenceParams): Promise;
- /**
- * Retrieves a {@link Types.PaginatedResult} object, containing an array of historical {@link PresenceMessage} objects for the channel. If the channel is configured to persist messages, then presence messages can be retrieved from history for up to 72 hours in the past. If not, presence messages can only be retrieved from history for up to two minutes in the past.
- *
- * @param params - A set of parameters which are used to specify which presence messages should be retrieved.
- * @returns A promise which, upon success, will be fulfilled with a {@link Types.PaginatedResult} object containing an array of {@link PresenceMessage} objects. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
- */
- history(params?: RealtimeHistoryParams): Promise>;
- /**
- * Registers a listener that is called each time a {@link PresenceMessage} matching a given {@link PresenceAction}, or an action within an array of {@link PresenceAction | `PresenceAction`s}, is received on the channel, such as a new member entering the presence set.
- *
- * @param action - A {@link PresenceAction} or an array of {@link PresenceAction | `PresenceAction`s} to register the listener for.
- * @param listener - An event listener function.
- * @returns A promise which resolves upon success of the channel {@link RealtimeChannelPromise.attach | `attach()`} operation and rejects with an {@link ErrorInfo} object upon its failure.
- */
- subscribe(
- action: PresenceAction | Array,
- listener?: messageCallback
- ): Promise;
- /**
- * Registers a listener that is called each time a {@link PresenceMessage} is received on the channel, such as a new member entering the presence set.
- *
- * @param listener - An event listener function.
- * @returns A promise which resolves upon success of the channel {@link RealtimeChannelPromise.attach | `attach()`} operation and rejects with an {@link ErrorInfo} object upon its failure.
- */
- subscribe(listener?: messageCallback): Promise;
- /**
- * Enters the presence set for the channel, optionally passing a `data` payload. A `clientId` is required to be present on a channel.
- *
- * @param data - The payload associated with the presence member.
- * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
- */
- enter(data?: any): Promise;
- /**
- * Updates the `data` payload for a presence member. If called before entering the presence set, this is treated as an {@link PresenceAction.ENTER} event.
- *
- * @param data - The payload to update for the presence member.
- * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
- */
- update(data?: any): Promise;
- /**
- * Leaves the presence set for the channel. A client must have previously entered the presence set before they can leave it.
- *
- * @param data - The payload associated with the presence member.
- * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
- */
- leave(data?: any): Promise;
- /**
- * Enters the presence set of the channel for a given `clientId`. Enables a single client to update presence on behalf of any number of clients using a single connection. The library must have been instantiated with an API key or a token bound to a wildcard `clientId`.
- *
- * @param clientId - The ID of the client to enter into the presence set.
- * @param data - The payload associated with the presence member.
- * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
- */
- enterClient(clientId: string, data?: any): Promise;
- /**
- * Updates the `data` payload for a presence member using a given `clientId`. Enables a single client to update presence on behalf of any number of clients using a single connection. The library must have been instantiated with an API key or a token bound to a wildcard `clientId`.
- *
- * @param clientId - The ID of the client to update in the presence set.
- * @param data - The payload to update for the presence member.
- * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
- */
- updateClient(clientId: string, data?: any): Promise;
- /**
- * Leaves the presence set of the channel for a given `clientId`. Enables a single client to update presence on behalf of any number of clients using a single connection. The library must have been instantiated with an API key or a token bound to a wildcard `clientId`.
- *
- * @param clientId - The ID of the client to leave the presence set for.
- * @param data - The payload associated with the presence member.
- * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
- */
- leaveClient(clientId: string, data?: any): Promise;
- }
+ auth: Auth;
+ /**
+ * A {@link Channels} object.
+ */
+ channels: Channels;
+ /**
+ * Makes a REST request to a provided path. This is provided as a convenience for developers who wish to use REST API functionality that is either not documented or is not yet included in the public API, without having to directly handle features such as authentication, paging, fallback hosts, MsgPack and JSON support.
+ *
+ * @param method - The request method to use, such as `GET`, `POST`.
+ * @param path - The request path.
+ * @param version - The version of the Ably REST API to use. See the [REST API reference](https://ably.com/docs/api/rest-api#versioning) for information on versioning.
+ * @param params - The parameters to include in the URL query of the request. The parameters depend on the endpoint being queried. See the [REST API reference](https://ably.com/docs/api/rest-api) for the available parameters of each endpoint.
+ * @param body - The JSON body of the request.
+ * @param headers - Additional HTTP headers to include in the request.
+ * @returns A promise which, upon success, will be fulfilled with an {@link HttpPaginatedResponse} response object returned by the HTTP request. This response object will contain an empty or JSON-encodable object. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
+ */
+ request(
+ method: string,
+ path: string,
+ version: number,
+ params?: any,
+ body?: any[] | any,
+ headers?: any,
+ ): Promise>;
+ /**
+ * Queries the REST `/stats` API and retrieves your application's usage statistics. Returns a {@link PaginatedResult} object, containing an array of {@link Stats} objects. See the [Stats docs](https://ably.com/docs/general/statistics).
+ *
+ * @param params - A set of parameters which are used to specify which statistics should be retrieved. If you do not provide this argument, then this method will use the default parameters described in the {@link StatsParams} interface.
+ * @returns A promise which, upon success, will be fulfilled with a {@link PaginatedResult} object containing an array of {@link Stats} objects. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
+ */
+ stats(params?: StatsParams): Promise>;
+ /**
+ * Retrieves the time from the Ably service as milliseconds since the Unix epoch. Clients that do not have access to a sufficiently well maintained time source and wish to issue Ably {@link TokenRequest | `TokenRequest`s} with a more accurate timestamp should use the {@link ClientOptions.queryTime} property instead of this method.
+ *
+ * @returns A promise which, upon success, will be fulfilled with the time as milliseconds since the Unix epoch. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
+ */
+ time(): Promise;
/**
- * The `ChannelBase` class acts as a base class for the {@link ChannelCallbacks} and {@link ChannelPromise} classes.
+ * Publishes a {@link BatchPublishSpec} object to one or more channels, up to a maximum of 100 channels.
+ *
+ * @param spec - A {@link BatchPublishSpec} object.
+ * @returns A promise which, upon success, will be fulfilled with a {@link BatchResult} object containing information about the result of the batch publish for each requested channel. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
*/
- class ChannelBase {
- /**
- * The channel name.
- */
- name: string;
- }
+ batchPublish(spec: BatchPublishSpec): Promise>;
+ /**
+ * Publishes one or more {@link BatchPublishSpec} objects to one or more channels, up to a maximum of 100 channels.
+ *
+ * @param specs - An array of {@link BatchPublishSpec} objects.
+ * @returns A promise which, upon success, will be fulfilled with an array of {@link BatchResult} objects containing information about the result of the batch publish for each requested channel for each provided {@link BatchPublishSpec}. This array is in the same order as the provided {@link BatchPublishSpec} array. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
+ */
+ batchPublish(
+ specs: BatchPublishSpec[],
+ ): Promise[]>;
+ /**
+ * Retrieves the presence state for one or more channels, up to a maximum of 100 channels. Presence state includes the `clientId` of members and their current {@link PresenceAction}.
+ *
+ * @param channels - An array of one or more channel names, up to a maximum of 100 channels.
+ * @returns A promise which, upon success, will be fulfilled with a {@link BatchResult} object containing information about the result of the batch presence request for each requested channel. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
+ */
+ batchPresence(channels: string[]): Promise[]>;
+ /**
+ * A {@link Push} object.
+ */
+ push: Push;
+}
+/**
+ * A client that extends the functionality of {@link RestClient} and provides additional realtime-specific features.
+ */
+export declare interface RealtimeClient {
/**
- * Enables messages to be published and historic messages to be retrieved for a channel.
+ * A client ID, used for identifying this client when publishing messages or for presence purposes. The `clientId` can be any non-empty string, except it cannot contain a `*`. This option is primarily intended to be used in situations where the library is instantiated with a key. A `clientId` may also be implicit in a token used to instantiate the library; an error will be raised if a `clientId` specified here conflicts with the `clientId` implicit in the token.
*/
- class ChannelCallbacks extends ChannelBase {
- /**
- * A {@link PresenceCallbacks} object.
- */
- presence: PresenceCallbacks;
- /**
- * Retrieves a {@link Types.PaginatedResult} object, containing an array of historical {@link Message} objects for the channel. If the channel is configured to persist messages, then messages can be retrieved from history for up to 72 hours in the past. If not, messages can only be retrieved from history for up to two minutes in the past.
- *
- * @param params - A set of parameters which are used to specify which messages should be retrieved.
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link Message} objects. Upon failure, the function will be called with information about the error.
- */
- history(params?: RestHistoryParams, callback?: paginatedResultCallback): void;
- /**
- * Retrieves a {@link Types.PaginatedResult} object, containing an array of historical {@link Message} objects for the channel. If the channel is configured to persist messages, then messages can be retrieved from history for up to 72 hours in the past. If not, messages can only be retrieved from history for up to two minutes in the past.
- *
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link Message} objects. Upon failure, the function will be called with information about the error.
- */
- history(callback?: paginatedResultCallback): void;
- /**
- * Publishes a single message to the channel with the given event name and payload.
- *
- * @param name - The name of the message.
- * @param data - The payload of the message.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- publish(name: string, data: any, callback?: errorCallback): void;
- /**
- * Publishes an array of messages to the channel.
- *
- * @param messages - An array of {@link Message} objects.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- publish(messages: any[], callback?: errorCallback): void;
- /**
- * Publishes a message to the channel.
- *
- * @param message - A {@link Message} object.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- publish(message: any, callback?: errorCallback): void;
- /**
- * Publishes a single message to the channel with the given event name and payload.
- *
- * @param name - The name of the message.
- * @param data - The payload of the message.
- * @param options - Optional parameters, such as [`quickAck`](https://faqs.ably.com/why-are-some-rest-publishes-on-a-channel-slow-and-then-typically-faster-on-subsequent-publishes) sent as part of the query string.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- publish(name: string, data: any, options?: PublishOptions, callback?: errorCallback): void;
- /**
- * Retrieves a {@link ChannelDetails} object for the channel, which includes status and occupancy metrics.
- *
- * @param callback - A function which, upon success, will be called a {@link ChannelDetails} object. Upon failure, the function will be called with information about the error.
- */
- status(callback: StandardCallback): void;
- }
+ clientId: string;
+ /**
+ * Calls {@link Connection.close | `connection.close()`} and causes the connection to close, entering the closing state. Once closed, the library will not attempt to re-establish the connection without an explicit call to {@link Connection.connect | `connect()`}.
+ */
+ close(): void;
+ /**
+ * Calls {@link Connection.connect | `connection.connect()`} and causes the connection to open, entering the connecting state. Explicitly calling `connect()` is unnecessary unless the {@link ClientOptions.autoConnect} property is disabled.
+ */
+ connect(): void;
/**
- * Enables messages to be published and historic messages to be retrieved for a channel.
+ * An {@link Auth} object.
*/
- class ChannelPromise extends ChannelBase {
- /**
- * A {@link PresencePromise} object.
- */
- presence: PresencePromise;
- /**
- * Retrieves a {@link Types.PaginatedResult} object, containing an array of historical {@link Message} objects for the channel. If the channel is configured to persist messages, then messages can be retrieved from history for up to 72 hours in the past. If not, messages can only be retrieved from history for up to two minutes in the past.
- *
- * @param params - A set of parameters which are used to specify which messages should be retrieved.
- * @returns A promise which, upon success, will be fulfilled with a {@link Types.PaginatedResult} object containing an array of {@link Message} objects. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
- */
- history(params?: RestHistoryParams): Promise>;
- /**
- * Publishes an array of messages to the channel.
- *
- * @param messages - An array of {@link Message} objects.
- * @param options - Optional parameters, such as [`quickAck`](https://faqs.ably.com/why-are-some-rest-publishes-on-a-channel-slow-and-then-typically-faster-on-subsequent-publishes) sent as part of the query string.
- * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
- */
- publish(messages: any[], options?: PublishOptions): Promise;
- /**
- * Publishes a message to the channel.
- *
- * @param message - A {@link Message} object.
- * @param options - Optional parameters, such as [`quickAck`](https://faqs.ably.com/why-are-some-rest-publishes-on-a-channel-slow-and-then-typically-faster-on-subsequent-publishes) sent as part of the query string.
- * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
- */
- publish(message: any, options?: PublishOptions): Promise;
- /**
- * Publishes a single message to the channel with the given event name and payload.
- *
- * @param name - The name of the message.
- * @param data - The payload of the message.
- * @param options - Optional parameters, such as [`quickAck`](https://faqs.ably.com/why-are-some-rest-publishes-on-a-channel-slow-and-then-typically-faster-on-subsequent-publishes) sent as part of the query string.
- * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
- */
- publish(name: string, data: any, options?: PublishOptions): Promise;
- /**
- * Retrieves a {@link ChannelDetails} object for the channel, which includes status and occupancy metrics.
- *
- * @returns A promise which, upon success, will be fulfilled a {@link ChannelDetails} object. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
- */
- status(): Promise;
- }
+ auth: Auth;
+ /**
+ * A {@link Channels} object.
+ */
+ channels: Channels;
+ /**
+ * A {@link Connection} object.
+ */
+ connection: Connection;
+ /**
+ * Makes a REST request to a provided path. This is provided as a convenience for developers who wish to use REST API functionality that is either not documented or is not yet included in the public API, without having to directly handle features such as authentication, paging, fallback hosts, MsgPack and JSON support.
+ *
+ * @param method - The request method to use, such as `GET`, `POST`.
+ * @param path - The request path.
+ * @param version - The version of the Ably REST API to use. See the [REST API reference](https://ably.com/docs/api/rest-api#versioning) for information on versioning.
+ * @param params - The parameters to include in the URL query of the request. The parameters depend on the endpoint being queried. See the [REST API reference](https://ably.com/docs/api/rest-api) for the available parameters of each endpoint.
+ * @param body - The JSON body of the request.
+ * @param headers - Additional HTTP headers to include in the request.
+ * @returns A promise which, upon success, will be fulfilled with the {@link HttpPaginatedResponse} response object returned by the HTTP request. This response object will contain an empty or JSON-encodable object. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
+ */
+ request(
+ method: string,
+ path: string,
+ version: number,
+ params?: any,
+ body?: any[] | any,
+ headers?: any,
+ ): Promise>;
+ /**
+ * Queries the REST `/stats` API and retrieves your application's usage statistics. Returns a {@link PaginatedResult} object, containing an array of {@link Stats} objects. See the [Stats docs](https://ably.com/docs/general/statistics).
+ *
+ * @param params - A set of parameters which are used to specify which statistics should be retrieved. If you do not provide this argument, then this method will use the default parameters described in the {@link StatsParams} interface.
+ * @returns A promise which, upon success, will be fulfilled with a {@link PaginatedResult} object containing an array of {@link Stats} objects. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
+ */
+ stats(params?: StatsParams): Promise>;
+ /**
+ * Retrieves the time from the Ably service as milliseconds since the Unix epoch. Clients that do not have access to a sufficiently well maintained time source and wish to issue Ably {@link TokenRequest | `TokenRequest`s} with a more accurate timestamp should use the {@link ClientOptions.queryTime} property instead of this method.
+ *
+ * @returns A promise which, upon success, will be fulfilled with the time as milliseconds since the Unix epoch. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
+ */
+ time(): Promise;
+ /**
+ * Publishes a {@link BatchPublishSpec} object to one or more channels, up to a maximum of 100 channels.
+ *
+ * @param spec - A {@link BatchPublishSpec} object.
+ * @returns A promise which, upon success, will be fulfilled with a {@link BatchResult} object containing information about the result of the batch publish for each requested channel. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
+ */
+ batchPublish(spec: BatchPublishSpec): Promise>;
+ /**
+ * Publishes one or more {@link BatchPublishSpec} objects to one or more channels, up to a maximum of 100 channels.
+ *
+ * @param specs - An array of {@link BatchPublishSpec} objects.
+ * @returns A promise which, upon success, will be fulfilled with an array of {@link BatchResult} objects containing information about the result of the batch publish for each requested channel for each provided {@link BatchPublishSpec}. This array is in the same order as the provided {@link BatchPublishSpec} array. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
+ */
+ batchPublish(
+ specs: BatchPublishSpec[],
+ ): Promise[]>;
+ /**
+ * Retrieves the presence state for one or more channels, up to a maximum of 100 channels. Presence state includes the `clientId` of members and their current {@link PresenceAction}.
+ *
+ * @param channels - An array of one or more channel names, up to a maximum of 100 channels.
+ * @returns A promise which, upon success, will be fulfilled with a {@link BatchResult} object containing information about the result of the batch presence request for each requested channel. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
+ */
+ batchPresence(channels: string[]): Promise[]>;
+ /**
+ * A {@link Push} object.
+ */
+ push: Push;
+}
+/**
+ * Creates Ably {@link TokenRequest} objects and obtains Ably Tokens from Ably to subsequently issue to less trusted clients.
+ */
+export declare interface Auth {
/**
- * The `RealtimeChannelBase` class acts as a base class for the {@link RealtimeChannelCallbacks} and {@link RealtimeChannelPromise} classes.
+ * A client ID, used for identifying this client when publishing messages or for presence purposes. The `clientId` can be any non-empty string, except it cannot contain a `*`. This option is primarily intended to be used in situations where the library is instantiated with a key. Note that a `clientId` may also be implicit in a token used to instantiate the library. An error is raised if a `clientId` specified here conflicts with the `clientId` implicit in the token. Find out more about [identified clients](https://ably.com/docs/core-features/authentication#identified-clients).
*/
- class RealtimeChannelBase extends EventEmitter {
- /**
- * The channel name.
- */
- readonly name: string;
- /**
- * An {@link ErrorInfo} object describing the last error which occurred on the channel, if any.
- */
- errorReason: ErrorInfo;
- /**
- * The current {@link ChannelState} of the channel.
- */
- readonly state: ChannelState;
- /**
- * Optional [channel parameters](https://ably.com/docs/realtime/channels/channel-parameters/overview) that configure the behavior of the channel.
- */
- params: ChannelParams;
- /**
- * An array of {@link ChannelMode} objects.
- */
- modes: ChannelModes;
- /**
- * Deregisters the given listener for the specified event name. This removes an earlier event-specific subscription.
- *
- * @param event - The event name.
- * @param listener - An event listener function.
- */
- unsubscribe(event: string, listener: messageCallback): void;
- /**
- * Deregisters the given listener from all event names in the array.
- *
- * @param events - An array of event names.
- * @param listener - An event listener function.
- */
- unsubscribe(events: Array, listener: messageCallback): void;
- /**
- * Deregisters all listeners for the given event name.
- *
- * @param event - The event name.
- */
- unsubscribe(event: string): void;
- /**
- * Deregisters all listeners for all event names in the array.
- *
- * @param events - An array of event names.
- */
- unsubscribe(events: Array): void;
- /**
- * Deregisters all listeners to messages on this channel that match the supplied filter.
- *
- * @param filter - A {@link MessageFilter}.
- * @param listener - An event listener function.
- */
- unsubscribe(filter: MessageFilter, listener?: messageCallback): void;
- /**
- * Deregisters the given listener (for any/all event names). This removes an earlier subscription.
- *
- * @param listener - An event listener function.
- */
- unsubscribe(listener: messageCallback): void;
- /**
- * Deregisters all listeners to messages on this channel. This removes all earlier subscriptions.
- */
- unsubscribe(): void;
- }
+ clientId: string;
+
+ /**
+ * Instructs the library to get a new token immediately. When using the realtime client, it upgrades the current realtime connection to use the new token, or if not connected, initiates a connection to Ably, once the new token has been obtained. Also stores any {@link TokenParams} and {@link AuthOptions} passed in as the new defaults, to be used for all subsequent implicit or explicit token requests. Any {@link TokenParams} and {@link AuthOptions} objects passed in entirely replace, as opposed to being merged with, the current client library saved values.
+ *
+ * @param tokenParams - A {@link TokenParams} object.
+ * @param authOptions - An {@link AuthOptions} object.
+ * @returns A promise which, upon success, will be fulfilled with a {@link TokenDetails} object. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
+ */
+ authorize(tokenParams?: TokenParams, authOptions?: AuthOptions): Promise;
+ /**
+ * Creates and signs an Ably {@link TokenRequest} based on the specified (or if none specified, the client library stored) {@link TokenParams} and {@link AuthOptions}. Note this can only be used when the API `key` value is available locally. Otherwise, the Ably {@link TokenRequest} must be obtained from the key owner. Use this to generate an Ably {@link TokenRequest} in order to implement an Ably Token request callback for use by other clients. Both {@link TokenParams} and {@link AuthOptions} are optional. When omitted or `null`, the default token parameters and authentication options for the client library are used, as specified in the {@link ClientOptions} when the client library was instantiated, or later updated with an explicit `authorize` request. Values passed in are used instead of, rather than being merged with, the default values. To understand why an Ably {@link TokenRequest} may be issued to clients in favor of a token, see [Token Authentication explained](https://ably.com/docs/core-features/authentication/#token-authentication).
+ *
+ * @param tokenParams - A {@link TokenParams} object.
+ * @param authOptions - An {@link AuthOptions} object.
+ * @returns A promise which, upon success, will be fulfilled with a {@link TokenRequest} object. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
+ */
+ createTokenRequest(tokenParams?: TokenParams, authOptions?: AuthOptions): Promise;
+ /**
+ * Calls the `requestToken` REST API endpoint to obtain an Ably Token according to the specified {@link TokenParams} and {@link AuthOptions}. Both {@link TokenParams} and {@link AuthOptions} are optional. When omitted or `null`, the default token parameters and authentication options for the client library are used, as specified in the {@link ClientOptions} when the client library was instantiated, or later updated with an explicit `authorize` request. Values passed in are used instead of, rather than being merged with, the default values. To understand why an Ably {@link TokenRequest} may be issued to clients in favor of a token, see [Token Authentication explained](https://ably.com/docs/core-features/authentication/#token-authentication).
+ *
+ * @param TokenParams - A {@link TokenParams} object.
+ * @param authOptions - An {@link AuthOptions} object.
+ * @returns A promise which, upon success, will be fulfilled with a {@link TokenDetails} object. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
+ */
+ requestToken(TokenParams?: TokenParams, authOptions?: AuthOptions): Promise;
+ /**
+ * Revokes the tokens specified by the provided array of {@link TokenRevocationTargetSpecifier}s. Only tokens issued by an API key that had revocable tokens enabled before the token was issued can be revoked. See the [token revocation docs](https://ably.com/docs/core-features/authentication#token-revocation) for more information.
+ *
+ * @param specifiers - An array of {@link TokenRevocationTargetSpecifier} objects.
+ * @param options - A set of options which are used to modify the revocation request.
+ * @returns A promise which, upon success, will be fulfilled with a {@link BatchResult} containing information about the result of the token revocation request for each provided [`TokenRevocationTargetSpecifier`]{@link TokenRevocationTargetSpecifier}. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
+ */
+ revokeTokens(
+ specifiers: TokenRevocationTargetSpecifier[],
+ options?: TokenRevocationOptions,
+ ): Promise>;
+}
+
+/**
+ * Enables the retrieval of the current and historic presence set for a channel.
+ */
+export declare interface Presence {
+ /**
+ * Retrieves the current members present on the channel and the metadata for each member, such as their {@link PresenceAction} and ID. Returns a {@link PaginatedResult} object, containing an array of {@link PresenceMessage} objects.
+ *
+ * @param params - A set of parameters which are used to specify which presence members should be retrieved.
+ * @returns A promise which, upon success, will be fulfilled with a {@link PaginatedResult} object containing an array of {@link PresenceMessage} objects. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
+ */
+ get(params?: RestPresenceParams): Promise>;
+ /**
+ * Retrieves a {@link PaginatedResult} object, containing an array of historical {@link PresenceMessage} objects for the channel. If the channel is configured to persist messages, then presence messages can be retrieved from history for up to 72 hours in the past. If not, presence messages can only be retrieved from history for up to two minutes in the past.
+ *
+ * @param params - A set of parameters which are used to specify which messages should be retrieved.
+ * @returns A promise which, upon success, will be fulfilled with a {@link PaginatedResult} object containing an array of {@link PresenceMessage} objects. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
+ */
+ history(params?: RestHistoryParams): Promise>;
+}
+
+/**
+ * Enables the presence set to be entered and subscribed to, and the historic presence set to be retrieved for a channel.
+ */
+export declare interface RealtimePresence {
+ /**
+ * Indicates whether the presence set synchronization between Ably and the clients on the channel has been completed. Set to `true` when the sync is complete.
+ */
+ syncComplete: boolean;
+ /**
+ * Deregisters a specific listener that is registered to receive {@link PresenceMessage} on the channel for a given {@link PresenceAction}.
+ *
+ * @param presence - A specific {@link PresenceAction} to deregister the listener for.
+ * @param listener - An event listener function.
+ */
+ unsubscribe(presence: PresenceAction, listener: messageCallback): void;
+ /**
+ * Deregisters a specific listener that is registered to receive {@link PresenceMessage} on the channel for a given array of {@link PresenceAction} objects.
+ *
+ * @param presence - An array of {@link PresenceAction} objects to deregister the listener for.
+ * @param listener - An event listener function.
+ */
+ unsubscribe(presence: Array, listener: messageCallback): void;
+ /**
+ * Deregisters any listener that is registered to receive {@link PresenceMessage} on the channel for a specific {@link PresenceAction}
+ *
+ * @param presence - A specific {@link PresenceAction} to deregister the listeners for.
+ */
+ unsubscribe(presence: PresenceAction): void;
+ /**
+ * Deregisters any listener that is registered to receive {@link PresenceMessage} on the channel for an array of {@link PresenceAction} objects
+ *
+ * @param presence - An array of {@link PresenceAction} objects to deregister the listeners for.
+ */
+ unsubscribe(presence: Array): void;
+ /**
+ * Deregisters a specific listener that is registered to receive {@link PresenceMessage} on the channel.
+ *
+ * @param listener - An event listener function.
+ */
+ unsubscribe(listener: messageCallback): void;
+ /**
+ * Deregisters all listeners currently receiving {@link PresenceMessage} for the channel.
+ */
+ unsubscribe(): void;
+
+ /**
+ * Retrieves the current members present on the channel and the metadata for each member, such as their {@link PresenceAction} and ID. Returns an array of {@link PresenceMessage} objects.
+ *
+ * @param params - A set of parameters which are used to specify which presence members should be retrieved.
+ * @returns A promise which, upon success, will be fulfilled with an array of {@link PresenceMessage} objects. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
+ */
+ get(params?: RealtimePresenceParams): Promise;
+ /**
+ * Retrieves a {@link PaginatedResult} object, containing an array of historical {@link PresenceMessage} objects for the channel. If the channel is configured to persist messages, then presence messages can be retrieved from history for up to 72 hours in the past. If not, presence messages can only be retrieved from history for up to two minutes in the past.
+ *
+ * @param params - A set of parameters which are used to specify which presence messages should be retrieved.
+ * @returns A promise which, upon success, will be fulfilled with a {@link PaginatedResult} object containing an array of {@link PresenceMessage} objects. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
+ */
+ history(params?: RealtimeHistoryParams): Promise>;
+ /**
+ * Registers a listener that is called each time a {@link PresenceMessage} matching a given {@link PresenceAction}, or an action within an array of {@link PresenceAction | `PresenceAction`s}, is received on the channel, such as a new member entering the presence set.
+ *
+ * @param action - A {@link PresenceAction} or an array of {@link PresenceAction | `PresenceAction`s} to register the listener for.
+ * @param listener - An event listener function.
+ * @returns A promise which resolves upon success of the channel {@link RealtimeChannel.attach | `attach()`} operation and rejects with an {@link ErrorInfo} object upon its failure.
+ */
+ subscribe(action: PresenceAction | Array, listener?: messageCallback): Promise;
+ /**
+ * Registers a listener that is called each time a {@link PresenceMessage} is received on the channel, such as a new member entering the presence set.
+ *
+ * @param listener - An event listener function.
+ * @returns A promise which resolves upon success of the channel {@link RealtimeChannel.attach | `attach()`} operation and rejects with an {@link ErrorInfo} object upon its failure.
+ */
+ subscribe(listener?: messageCallback): Promise;
+ /**
+ * Enters the presence set for the channel, optionally passing a `data` payload. A `clientId` is required to be present on a channel.
+ *
+ * @param data - The payload associated with the presence member.
+ * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
+ */
+ enter(data?: any): Promise;
+ /**
+ * Updates the `data` payload for a presence member. If called before entering the presence set, this is treated as an {@link PresenceActions.ENTER} event.
+ *
+ * @param data - The payload to update for the presence member.
+ * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
+ */
+ update(data?: any): Promise;
+ /**
+ * Leaves the presence set for the channel. A client must have previously entered the presence set before they can leave it.
+ *
+ * @param data - The payload associated with the presence member.
+ * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
+ */
+ leave(data?: any): Promise;
+ /**
+ * Enters the presence set of the channel for a given `clientId`. Enables a single client to update presence on behalf of any number of clients using a single connection. The library must have been instantiated with an API key or a token bound to a wildcard `clientId`.
+ *
+ * @param clientId - The ID of the client to enter into the presence set.
+ * @param data - The payload associated with the presence member.
+ * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
+ */
+ enterClient(clientId: string, data?: any): Promise;
+ /**
+ * Updates the `data` payload for a presence member using a given `clientId`. Enables a single client to update presence on behalf of any number of clients using a single connection. The library must have been instantiated with an API key or a token bound to a wildcard `clientId`.
+ *
+ * @param clientId - The ID of the client to update in the presence set.
+ * @param data - The payload to update for the presence member.
+ * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
+ */
+ updateClient(clientId: string, data?: any): Promise;
+ /**
+ * Leaves the presence set of the channel for a given `clientId`. Enables a single client to update presence on behalf of any number of clients using a single connection. The library must have been instantiated with an API key or a token bound to a wildcard `clientId`.
+ *
+ * @param clientId - The ID of the client to leave the presence set for.
+ * @param data - The payload associated with the presence member.
+ * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
+ */
+ leaveClient(clientId: string, data?: any): Promise;
+}
+
+/**
+ * Enables messages to be published and historic messages to be retrieved for a channel.
+ */
+export declare interface Channel {
+ /**
+ * The channel name.
+ */
+ name: string;
+
+ /**
+ * A {@link Presence} object.
+ */
+ presence: Presence;
+ /**
+ * Retrieves a {@link PaginatedResult} object, containing an array of historical {@link InboundMessage} objects for the channel. If the channel is configured to persist messages, then messages can be retrieved from history for up to 72 hours in the past. If not, messages can only be retrieved from history for up to two minutes in the past.
+ *
+ * @param params - A set of parameters which are used to specify which messages should be retrieved.
+ * @returns A promise which, upon success, will be fulfilled with a {@link PaginatedResult} object containing an array of {@link InboundMessage} objects. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
+ */
+ history(params?: RestHistoryParams): Promise>;
+ /**
+ * Publishes an array of messages to the channel.
+ *
+ * @param messages - An array of {@link Message} objects.
+ * @param options - Optional parameters, such as [`quickAck`](https://faqs.ably.com/why-are-some-rest-publishes-on-a-channel-slow-and-then-typically-faster-on-subsequent-publishes) sent as part of the query string.
+ * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
+ */
+ publish(messages: Message[], options?: PublishOptions): Promise;
+ /**
+ * Publishes a message to the channel.
+ *
+ * @param message - A {@link Message} object.
+ * @param options - Optional parameters, such as [`quickAck`](https://faqs.ably.com/why-are-some-rest-publishes-on-a-channel-slow-and-then-typically-faster-on-subsequent-publishes) sent as part of the query string.
+ * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
+ */
+ publish(message: Message, options?: PublishOptions): Promise;
+ /**
+ * Publishes a single message to the channel with the given event name and payload.
+ *
+ * @param name - The name of the message.
+ * @param data - The payload of the message.
+ * @param options - Optional parameters, such as [`quickAck`](https://faqs.ably.com/why-are-some-rest-publishes-on-a-channel-slow-and-then-typically-faster-on-subsequent-publishes) sent as part of the query string.
+ * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
+ */
+ publish(name: string, data: any, options?: PublishOptions): Promise;
+ /**
+ * Retrieves a {@link ChannelDetails} object for the channel, which includes status and occupancy metrics.
+ *
+ * @returns A promise which, upon success, will be fulfilled a {@link ChannelDetails} object. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
+ */
+ status(): Promise;
+}
+
+/**
+ * Enables messages to be published and subscribed to. Also enables historic messages to be retrieved and provides access to the {@link RealtimePresence} object of a channel.
+ */
+export declare interface RealtimeChannel extends EventEmitter {
+ /**
+ * The channel name.
+ */
+ readonly name: string;
+ /**
+ * An {@link ErrorInfo} object describing the last error which occurred on the channel, if any.
+ */
+ errorReason: ErrorInfo;
+ /**
+ * The current {@link ChannelState} of the channel.
+ */
+ readonly state: ChannelState;
+ /**
+ * Optional [channel parameters](https://ably.com/docs/realtime/channels/channel-parameters/overview) that configure the behavior of the channel.
+ */
+ params: ChannelParams;
+ /**
+ * An array of {@link ChannelMode} objects.
+ */
+ modes: ChannelMode[];
+ /**
+ * Deregisters the given listener for the specified event name. This removes an earlier event-specific subscription.
+ *
+ * @param event - The event name.
+ * @param listener - An event listener function.
+ */
+ unsubscribe(event: string, listener: messageCallback): void;
+ /**
+ * Deregisters the given listener from all event names in the array.
+ *
+ * @param events - An array of event names.
+ * @param listener - An event listener function.
+ */
+ unsubscribe(events: Array, listener: messageCallback): void;
+ /**
+ * Deregisters all listeners for the given event name.
+ *
+ * @param event - The event name.
+ */
+ unsubscribe(event: string): void;
+ /**
+ * Deregisters all listeners for all event names in the array.
+ *
+ * @param events - An array of event names.
+ */
+ unsubscribe(events: Array): void;
+ /**
+ * Deregisters all listeners to messages on this channel that match the supplied filter.
+ *
+ * @param filter - A {@link MessageFilter}.
+ * @param listener - An event listener function.
+ */
+ unsubscribe(filter: MessageFilter, listener?: messageCallback): void;
+ /**
+ * Deregisters the given listener (for any/all event names). This removes an earlier subscription.
+ *
+ * @param listener - An event listener function.
+ */
+ unsubscribe(listener: messageCallback): void;
+ /**
+ * Deregisters all listeners to messages on this channel. This removes all earlier subscriptions.
+ */
+ unsubscribe(): void;
+
+ /**
+ * A {@link RealtimePresence} object.
+ */
+ presence: RealtimePresence;
+ /**
+ * Attach to this channel ensuring the channel is created in the Ably system and all messages published on the channel are received by any channel listeners registered using {@link RealtimeChannel.subscribe | `subscribe()`}. Any resulting channel state change will be emitted to any listeners registered using the {@link EventEmitter.on | `on()`} or {@link EventEmitter.once | `once()`} methods. As a convenience, `attach()` is called implicitly if {@link RealtimeChannel.subscribe | `subscribe()`} for the channel is called, or {@link RealtimePresence.enter | `enter()`} or {@link RealtimePresence.subscribe | `subscribe()`} are called on the {@link RealtimePresence} object for this channel.
+ *
+ * @returns A promise which, upon success, if the channel became attached will be fulfilled with a {@link ChannelStateChange} object. If the channel was already attached the promise will be fulfilled with `null`. Upon failure, the promise will be rejected with an {@link ErrorInfo} object.
+ */
+ attach(): Promise;
+ /**
+ * Detach from this channel. Any resulting channel state change is emitted to any listeners registered using the {@link EventEmitter.on | `on()`} or {@link EventEmitter.once | `once()`} methods. Once all clients globally have detached from the channel, the channel will be released in the Ably service within two minutes.
+ *
+ * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
+ */
+ detach(): Promise;
+ /**
+ * Retrieves a {@link PaginatedResult} object, containing an array of historical {@link InboundMessage} objects for the channel. If the channel is configured to persist messages, then messages can be retrieved from history for up to 72 hours in the past. If not, messages can only be retrieved from history for up to two minutes in the past.
+ *
+ * @param params - A set of parameters which are used to specify which presence members should be retrieved.
+ * @returns A promise which, upon success, will be fulfilled with a {@link PaginatedResult} object containing an array of {@link InboundMessage} objects. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
+ */
+ history(params?: RealtimeHistoryParams): Promise>;
+ /**
+ * Sets the {@link ChannelOptions} for the channel.
+ *
+ * @param options - A {@link ChannelOptions} object.
+ * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
+ */
+ setOptions(options: ChannelOptions): Promise;
+ /**
+ * Registers a listener for messages with a given event name on this channel. The caller supplies a listener function, which is called each time one or more matching messages arrives on the channel.
+ *
+ * @param event - The event name.
+ * @param listener - An event listener function.
+ * @returns A promise which, upon successful attachment to the channel, will be fulfilled with a {@link ChannelStateChange} object. If the channel was already attached the promise will be resolved with `null`. Upon failure, the promise will be rejected with an {@link ErrorInfo} object.
+ */
+ subscribe(event: string, listener?: messageCallback): Promise;
+ /**
+ * Registers a listener for messages on this channel for multiple event name values.
+ *
+ * @param events - An array of event names.
+ * @param listener - An event listener function.
+ * @returns A promise which, upon successful attachment to the channel, will be fulfilled with a {@link ChannelStateChange} object. If the channel was already attached the promise will be resolved with `null`. Upon failure, the promise will be rejected with an {@link ErrorInfo} object.
+ */
+ subscribe(events: Array, listener?: messageCallback): Promise;
+ /**
+ * {@label WITH_MESSAGE_FILTER}
+ *
+ * Registers a listener for messages on this channel that match the supplied filter.
+ *
+ * @param filter - A {@link MessageFilter}.
+ * @param listener - An event listener function.
+ * @returns A promise which, upon successful attachment to the channel, will be fulfilled with a {@link ChannelStateChange} object. If the channel was already attached the promise will be resolved with `null`. Upon failure, the promise will be rejected with an {@link ErrorInfo} object.
+ */
+ subscribe(filter: MessageFilter, listener?: messageCallback): Promise;
+ /**
+ * Registers a listener for messages on this channel. The caller supplies a listener function, which is called each time one or more messages arrives on the channel.
+ *
+ * @param callback - An event listener function.
+ * @returns A promise which, upon successful attachment to the channel, will be fulfilled with a {@link ChannelStateChange} object. If the channel was already attached the promise will be resolved with `null`. Upon failure, the promise will be rejected with an {@link ErrorInfo} object.
+ */
+ subscribe(callback: messageCallback): Promise;
+ /**
+ * Publishes a single message to the channel with the given event name and payload. When publish is called with this client library, it won't attempt to implicitly attach to the channel, so long as [transient publishing](https://ably.com/docs/realtime/channels#transient-publish) is available in the library. Otherwise, the client will implicitly attach.
+ *
+ * @param name - The event name.
+ * @param data - The message payload.
+ * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
+ */
+ publish(name: string, data: any): Promise;
+ /**
+ * Publishes an array of messages to the channel. When publish is called with this client library, it won't attempt to implicitly attach to the channel.
+ *
+ * @param messages - An array of {@link Message} objects.
+ * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
+ */
+ publish(messages: Message[]): Promise;
+ /**
+ * Publish a message to the channel. When publish is called with this client library, it won't attempt to implicitly attach to the channel.
+ *
+ * @param message - A {@link Message} object.
+ * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
+ */
+ publish(message: Message): Promise;
+ /**
+ * If the channel is already in the given state, returns a promise which immediately resolves to `null`. Else, calls {@link EventEmitter.once | `once()`} to return a promise which resolves the next time the channel transitions to the given state.
+ *
+ * @param targetState - The channel state to wait for.
+ */
+ whenState(targetState: ChannelState): Promise;
+}
+
+/**
+ * Optional parameters for message publishing.
+ */
+export type PublishOptions = {
+ /**
+ * See [here](https://faqs.ably.com/why-are-some-rest-publishes-on-a-channel-slow-and-then-typically-faster-on-subsequent-publishes).
+ */
+ quickAck?: boolean;
+};
+
+/**
+ * Contains properties to filter messages with when calling {@link RealtimeChannel.subscribe | `RealtimeChannel.subscribe()`}.
+ */
+export type MessageFilter = {
+ /**
+ * Filters messages by a specific message `name`.
+ */
+ name?: string;
+ /**
+ * Filters messages by a specific `extras.ref.timeserial` value.
+ */
+ refTimeserial?: string;
+ /**
+ * Filters messages by a specific `extras.ref.type` value.
+ */
+ refType?: string;
+ /**
+ * Filters messages based on whether they contain an `extras.ref`.
+ */
+ isRef?: boolean;
+ /**
+ * Filters messages by a specific message `clientId`.
+ */
+ clientId: string;
+};
+
+/**
+ * Creates and destroys {@link Channel} and {@link RealtimeChannel} objects.
+ */
+export declare interface Channels {
+ /**
+ * Creates a new {@link Channel} or {@link RealtimeChannel} object, with the specified {@link ChannelOptions}, or returns the existing channel object.
+ *
+ * @param name - The channel name.
+ * @param channelOptions - A {@link ChannelOptions} object.
+ * @returns A {@link Channel} or {@link RealtimeChannel} object.
+ */
+ get(name: string, channelOptions?: ChannelOptions): T;
+ /**
+ * Creates a new {@link Channel} or {@link RealtimeChannel} object, with the specified channel {@link DeriveOptions}
+ * and {@link ChannelOptions}, or returns the existing channel object.
+ *
+ * @experimental This is a preview feature and may change in a future non-major release.
+ * This experimental method allows you to create custom realtime data feeds by selectively subscribing
+ * to receive only part of the data from the channel.
+ * See the [announcement post](https://pages.ably.com/subscription-filters-preview) for more information.
+ *
+ * @param name - The channel name.
+ * @param deriveOptions - A {@link DeriveOptions} object.
+ * @param channelOptions - A {@link ChannelOptions} object.
+ * @returns A {@link RealtimeChannel} object.
+ */
+ getDerived(name: string, deriveOptions: DeriveOptions, channelOptions?: ChannelOptions): T;
+ /**
+ * Releases a {@link Channel} or {@link RealtimeChannel} object, deleting it, and enabling it to be garbage collected. It also removes any listeners associated with the channel. To release a channel, the {@link ChannelState} must be `INITIALIZED`, `DETACHED`, or `FAILED`.
+ *
+ * @param name - The channel name.
+ */
+ release(name: string): void;
+}
+
+/**
+ * Contains an individual message that is sent to, or received from, Ably.
+ */
+export interface Message {
+ /**
+ * The client ID of the publisher of this message.
+ */
+ clientId?: string;
+ /**
+ * The connection ID of the publisher of this message.
+ */
+ connectionId?: string;
+ /**
+ * The message payload, if provided.
+ */
+ data?: any;
+ /**
+ * This is typically empty, as all messages received from Ably are automatically decoded client-side using this value. However, if the message encoding cannot be processed, this attribute contains the remaining transformations not applied to the `data` payload.
+ */
+ encoding?: string;
+ /**
+ * A JSON object of arbitrary key-value pairs that may contain metadata, and/or ancillary payloads. Valid payloads include `push`, `delta`, `ref` and `headers`.
+ */
+ extras?: any;
+ /**
+ * Unique ID assigned by Ably to this message.
+ */
+ id?: string;
+ /**
+ * The event name.
+ */
+ name?: string;
+ /**
+ * Timestamp of when the message was received by Ably, as milliseconds since the Unix epoch.
+ */
+ timestamp?: number;
+}
+
+/**
+ * A message received from Ably.
+ */
+export type InboundMessage = Message & Required>;
+
+/**
+ * Static utilities related to messages.
+ */
+export interface MessageStatic {
+ /**
+ * A static factory method to create an `InboundMessage` object from a deserialized InboundMessage-like object encoded using Ably's wire protocol.
+ *
+ * @param JsonObject - A `InboundMessage`-like deserialized object.
+ * @param channelOptions - A {@link ChannelOptions} object. If you have an encrypted channel, use this to allow the library to decrypt the data.
+ * @returns A promise which will be fulfilled with an `InboundMessage` object.
+ */
+ fromEncoded: (JsonObject: any, channelOptions?: ChannelOptions) => Promise;
+ /**
+ * A static factory method to create an array of `InboundMessage` objects from an array of deserialized InboundMessage-like object encoded using Ably's wire protocol.
+ *
+ * @param JsonArray - An array of `InboundMessage`-like deserialized objects.
+ * @param channelOptions - A {@link ChannelOptions} object. If you have an encrypted channel, use this to allow the library to decrypt the data.
+ * @returns A promise which will be fulfilled with an array of {@link InboundMessage} objects.
+ */
+ fromEncodedArray: (JsonArray: any[], channelOptions?: ChannelOptions) => Promise;
+}
+
+/**
+ * Contains an individual presence update sent to, or received from, Ably.
+ */
+export declare interface PresenceMessage {
+ /**
+ * The type of {@link PresenceAction} the `PresenceMessage` is for.
+ */
+ action: PresenceAction;
+ /**
+ * The ID of the client that published the `PresenceMessage`.
+ */
+ clientId: string;
+ /**
+ * The ID of the connection associated with the client that published the `PresenceMessage`.
+ */
+ connectionId: string;
+ /**
+ * The payload of the `PresenceMessage`.
+ */
+ data: any;
+ /**
+ * This will typically be empty as all presence messages received from Ably are automatically decoded client-side using this value. However, if the message encoding cannot be processed, this attribute will contain the remaining transformations not applied to the data payload.
+ */
+ encoding: string;
+ /**
+ * A JSON object of arbitrary key-value pairs that may contain metadata, and/or ancillary payloads. Valid payloads include `headers`.
+ */
+ extras: any;
+ /**
+ * A unique ID assigned to each `PresenceMessage` by Ably.
+ */
+ id: string;
+ /**
+ * The time the `PresenceMessage` was received by Ably, as milliseconds since the Unix epoch.
+ */
+ timestamp: number;
+}
+
+/**
+ * Static utilities related to presence messages.
+ */
+export interface PresenceMessageStatic {
+ /**
+ * Decodes and decrypts a deserialized `PresenceMessage`-like object using the cipher in {@link ChannelOptions}. Any residual transforms that cannot be decoded or decrypted will be in the `encoding` property. Intended for users receiving messages from a source other than a REST or Realtime channel (for example a queue) to avoid having to parse the encoding string.
+ *
+ * @param JsonObject - The deserialized `PresenceMessage`-like object to decode and decrypt.
+ * @param channelOptions - A {@link ChannelOptions} object containing the cipher.
+ */
+ fromEncoded: (JsonObject: any, channelOptions?: ChannelOptions) => Promise;
+ /**
+ * Decodes and decrypts an array of deserialized `PresenceMessage`-like object using the cipher in {@link ChannelOptions}. Any residual transforms that cannot be decoded or decrypted will be in the `encoding` property. Intended for users receiving messages from a source other than a REST or Realtime channel (for example a queue) to avoid having to parse the encoding string.
+ *
+ * @param JsonArray - An array of deserialized `PresenceMessage`-like objects to decode and decrypt.
+ * @param channelOptions - A {@link ChannelOptions} object containing the cipher.
+ */
+ fromEncodedArray: (JsonArray: any[], channelOptions?: ChannelOptions) => Promise;
+
+ /**
+ * Initialises a `PresenceMessage` from a `PresenceMessage`-like object.
+ *
+ * @param values - The values to intialise the `PresenceMessage` from.
+ * @param stringifyAction - Whether to convert the `action` field from a number to a string.
+ */
+ fromValues(values: PresenceMessage | Record, stringifyAction?: boolean): PresenceMessage;
+}
+
+/**
+ * Cipher Key used in {@link CipherParamOptions}. If set to a `string`, the value must be base64 encoded.
+ */
+export type CipherKeyParam = ArrayBuffer | Uint8Array | string; // if string must be base64-encoded
+/**
+ * The type of the key returned by {@link Crypto.generateRandomKey}. Typed differently depending on platform (`Buffer` in Node.js, `ArrayBuffer` elsewhere).
+ */
+export type CipherKey = ArrayBuffer | Buffer;
+/**
+ * Contains the properties used to generate a {@link CipherParams} object.
+ */
+export type CipherParamOptions = {
/**
- * Optional parameters for message publishing.
+ * The private key used to encrypt and decrypt payloads.
*/
- type PublishOptions = {
- /**
- * See [here](https://faqs.ably.com/why-are-some-rest-publishes-on-a-channel-slow-and-then-typically-faster-on-subsequent-publishes).
- */
- quickAck?: boolean;
- };
-
+ key: CipherKeyParam;
/**
- * Contains properties to filter messages with when calling {@link RealtimeChannelCallbacks.subscribe | `RealtimeChannelCallbacks.subscribe()`} or {@link RealtimeChannelPromise.subscribe | `RealtimeChannelPromise.subscribe()`}.
+ * The algorithm to use for encryption. Only `AES` is supported.
*/
- type MessageFilter = {
- /**
- * Filters messages by a specific message `name`.
- */
- name?: string;
- /**
- * Filters messages by a specific `extras.ref.timeserial` value.
- */
- refTimeserial?: string;
- /**
- * Filters messages by a specific `extras.ref.type` value.
- */
- refType?: string;
- /**
- * Filters messages based on whether they contain an `extras.ref`.
- */
- isRef?: boolean;
- /**
- * Filters messages by a specific message `clientId`.
- */
- clientId: string;
- };
-
+ algorithm?: 'aes';
/**
- * Enables messages to be published and subscribed to. Also enables historic messages to be retrieved and provides access to the {@link RealtimePresenceCallbacks} object of a channel.
+ * The length of the key in bits; for example 128 or 256.
*/
- class RealtimeChannelCallbacks extends RealtimeChannelBase {
- /**
- * A {@link RealtimePresenceCallbacks} object.
- */
- presence: RealtimePresenceCallbacks;
- /**
- * Attach to this channel ensuring the channel is created in the Ably system and all messages published on the channel are received by any channel listeners registered using {@link RealtimeChannelCallbacks.subscribe | `subscribe()`}. Any resulting channel state change will be emitted to any listeners registered using the {@link EventEmitter.on | `on()`} or {@link EventEmitter.once | `once()`} methods. As a convenience, `attach()` is called implicitly if {@link RealtimeChannelCallbacks.subscribe | `subscribe()`} for the channel is called, or {@link RealtimePresenceCallbacks.enter | `enter()`} or {@link RealtimePresenceCallbacks.subscribe | `subscribe()`} are called on the {@link RealtimePresenceCallbacks} object for this channel.
- *
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded and the channel became attached, then the function will be called with a {@link ChannelStateChange} object. If the channel was already attached the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- attach(callback?: StandardCallback): void;
- /**
- * Detach from this channel. Any resulting channel state change is emitted to any listeners registered using the {@link EventEmitter.on | `on()`} or {@link EventEmitter.once | `once()`} methods. Once all clients globally have detached from the channel, the channel will be released in the Ably service within two minutes.
- *
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- detach(callback?: errorCallback): void;
- /**
- * Retrieves a {@link Types.PaginatedResult} object, containing an array of historical {@link Message} objects for the channel. If the channel is configured to persist messages, then messages can be retrieved from history for up to 72 hours in the past. If not, messages can only be retrieved from history for up to two minutes in the past.
- *
- * @param params - A set of parameters which are used to specify which presence members should be retrieved.
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link Message} objects. Upon failure, the function will be called with information about the error.
- */
- history(params?: RealtimeHistoryParams, callback?: paginatedResultCallback): void;
- /**
- * Retrieves a {@link Types.PaginatedResult} object, containing an array of historical {@link Message} objects for the channel. If the channel is configured to persist messages, then messages can be retrieved from history for up to 72 hours in the past. If not, messages can only be retrieved from history for up to two minutes in the past.
- *
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link Message} objects. Upon failure, the function will be called with information about the error.
- */
- history(callback?: paginatedResultCallback): void;
- /**
- * Sets the {@link ChannelOptions} for the channel.
- *
- * @param options - A {@link ChannelOptions} object.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- setOptions(options: ChannelOptions, callback?: errorCallback): void;
- /**
- * Registers a listener for messages with a given event name on this channel. The caller supplies a listener function, which is called each time one or more matching messages arrives on the channel.
- *
- * @param event - The event name.
- * @param listener - An event listener function.
- * @param callbackWhenAttached - A function which will be called upon completion of the channel {@link RealtimeChannelCallbacks.attach | `attach()`} operation. If the operation succeeded and the channel became attached, then the function will be called with a {@link ChannelStateChange} object. If the channel was already attached the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- subscribe(
- event: string,
- listener?: messageCallback,
- callbackWhenAttached?: StandardCallback
- ): void;
- /**
- * Registers a listener for messages on this channel for multiple event name values.
- *
- * @param events - An array of event names.
- * @param listener - An event listener function.
- * @param callbackWhenAttached - A function which will be called upon completion of the channel {@link RealtimeChannelCallbacks.attach | `attach()`} operation. If the operation succeeded and the channel became attached, then the function will be called with a {@link ChannelStateChange} object. If the channel was already attached the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- subscribe(
- events: Array,
- listener?: messageCallback,
- callbackWhenAttached?: StandardCallback
- ): void;
- /**
- * Registers a listener for messages on this channel that match the supplied filter.
- *
- * @param filter - A {@link MessageFilter}.
- * @param listener - An event listener function.
- * @param callbackWhenAttached - A function which will be called upon completion of the channel {@link RealtimeChannelCallbacks.attach | `attach()`} operation. If the operation succeeded and the channel became attached, then the function will be called with a {@link ChannelStateChange} object. If the channel was already attached the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- subscribe(
- filter: MessageFilter,
- listener?: messageCallback,
- callbackWhenAttached?: StandardCallback
- ): void;
- /**
- * Registers a listener for messages on this channel. The caller supplies a listener function, which is called each time one or more messages arrives on the channel.
- *
- * @param listener - An event listener function.
- * @param callbackWhenAttached - A function which will be called upon completion of the channel {@link RealtimeChannelCallbacks.attach | `attach()`} operation. If the operation succeeded and the channel became attached, then the function will be called with a {@link ChannelStateChange} object. If the channel was already attached the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- subscribe(listener: messageCallback, callbackWhenAttached?: StandardCallback): void;
- /**
- * Publishes a single message to the channel with the given event name and payload. When publish is called with this client library, it won't attempt to implicitly attach to the channel, so long as [transient publishing](https://ably.com/docs/realtime/channels#transient-publish) is available in the library. Otherwise, the client will implicitly attach.
- *
- * @param name - The event name.
- * @param data - The message payload.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- publish(name: string, data: any, callback?: errorCallback): void;
- /**
- * Publishes an array of messages to the channel. When publish is called with this client library, it won't attempt to implicitly attach to the channel.
- *
- * @param messages - An array of {@link Message} objects.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- publish(messages: any[], callback?: errorCallback): void;
- /**
- * Publish a message to the channel. When publish is called with this client library, it won't attempt to implicitly attach to the channel.
- *
- * @param message - A {@link Message} object.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- publish(message: any, callback?: errorCallback): void;
- /**
- * Publishes a single message to the channel with the given event name and payload. When publish is called with this client library, it won't attempt to implicitly attach to the channel, so long as [transient publishing](https://ably.com/docs/realtime/channels#transient-publish) is available in the library. Otherwise, the client will implicitly attach.
- *
- * @param name - The event name.
- * @param data - The message payload.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- publish(name: string, data: any, callback?: errorCallback): void;
- /**
- * Calls the supplied function when the channel reaches the specified {@link ChannelState}. If the channel is already in the specified state, the callback is called immediately.
- *
- * @param targetState - The state which should be reached.
- * @param callback - A function which will be called when the channel has reached the specified {@link ChannelState} with a {@link ChannelStateChange} object as the first argument.
- */
- whenState(targetState: ChannelState, callback: channelEventCallback): void;
- }
-
+ keyLength?: number;
/**
- * Enables messages to be published and subscribed to. Also enables historic messages to be retrieved and provides access to the {@link RealtimePresencePromise} object of a channel.
+ * The cipher mode. Only `CBC` is supported.
*/
- class RealtimeChannelPromise extends RealtimeChannelBase {
- /**
- * A {@link RealtimePresencePromise} object.
- */
- presence: RealtimePresencePromise;
- /**
- * Attach to this channel ensuring the channel is created in the Ably system and all messages published on the channel are received by any channel listeners registered using {@link RealtimeChannelPromise.subscribe | `subscribe()`}. Any resulting channel state change will be emitted to any listeners registered using the {@link EventEmitter.on | `on()`} or {@link EventEmitter.once | `once()`} methods. As a convenience, `attach()` is called implicitly if {@link RealtimeChannelPromise.subscribe | `subscribe()`} for the channel is called, or {@link RealtimePresencePromise.enter | `enter()`} or {@link RealtimePresencePromise.subscribe | `subscribe()`} are called on the {@link RealtimePresencePromise} object for this channel.
- *
- * @returns A promise which, upon success, if the channel became attached will be fulfilled with a {@link ChannelStateChange} object. If the channel was already attached the promise will be fulfilled with `null`. Upon failure, the promise will be rejected with an {@link ErrorInfo} object.
- */
- attach(): Promise;
- /**
- * Detach from this channel. Any resulting channel state change is emitted to any listeners registered using the {@link EventEmitter.on | `on()`} or {@link EventEmitter.once | `once()`} methods. Once all clients globally have detached from the channel, the channel will be released in the Ably service within two minutes.
- *
- * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
- */
- detach(): Promise;
- /**
- * Retrieves a {@link Types.PaginatedResult} object, containing an array of historical {@link Message} objects for the channel. If the channel is configured to persist messages, then messages can be retrieved from history for up to 72 hours in the past. If not, messages can only be retrieved from history for up to two minutes in the past.
- *
- * @param params - A set of parameters which are used to specify which presence members should be retrieved.
- * @returns A promise which, upon success, will be fulfilled with a {@link Types.PaginatedResult} object containing an array of {@link Message} objects. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
- */
- history(params?: RealtimeHistoryParams): Promise>;
- /**
- * Sets the {@link ChannelOptions} for the channel.
- *
- * @param options - A {@link ChannelOptions} object.
- * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
- */
- setOptions(options: ChannelOptions): Promise;
- /**
- * Registers a listener for messages with a given event name on this channel. The caller supplies a listener function, which is called each time one or more matching messages arrives on the channel.
- *
- * @param event - The event name.
- * @param listener - An event listener function.
- * @returns A promise which, upon successful attachment to the channel, will be fulfilled with a {@link ChannelStateChange} object. If the channel was already attached the promise will be resolved with `null`. Upon failure, the promise will be rejected with an {@link ErrorInfo} object.
- */
- subscribe(event: string, listener?: messageCallback): Promise;
- /**
- * Registers a listener for messages on this channel for multiple event name values.
- *
- * @param events - An array of event names.
- * @param listener - An event listener function.
- * @returns A promise which, upon successful attachment to the channel, will be fulfilled with a {@link ChannelStateChange} object. If the channel was already attached the promise will be resolved with `null`. Upon failure, the promise will be rejected with an {@link ErrorInfo} object.
- */
- subscribe(events: Array, listener?: messageCallback): Promise;
- /**
- * Registers a listener for messages on this channel that match the supplied filter.
- *
- * @param filter - A {@link MessageFilter}.
- * @param listener - An event listener function.
- * @returns A promise which, upon successful attachment to the channel, will be fulfilled with a {@link ChannelStateChange} object. If the channel was already attached the promise will be resolved with `null`. Upon failure, the promise will be rejected with an {@link ErrorInfo} object.
- */
- subscribe(filter: MessageFilter, listener?: messageCallback): Promise;
- /**
- * Registers a listener for messages on this channel. The caller supplies a listener function, which is called each time one or more messages arrives on the channel.
- *
- * @param callback - An event listener function.
- * @returns A promise which, upon successful attachment to the channel, will be fulfilled with a {@link ChannelStateChange} object. If the channel was already attached the promise will be resolved with `null`. Upon failure, the promise will be rejected with an {@link ErrorInfo} object.
- */
- subscribe(callback: messageCallback): Promise;
- /**
- * Publishes a single message to the channel with the given event name and payload. When publish is called with this client library, it won't attempt to implicitly attach to the channel, so long as [transient publishing](https://ably.com/docs/realtime/channels#transient-publish) is available in the library. Otherwise, the client will implicitly attach.
- *
- * @param name - The event name.
- * @param data - The message payload.
- * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
- */
- publish(name: string, data: any): Promise;
- /**
- * Publishes an array of messages to the channel. When publish is called with this client library, it won't attempt to implicitly attach to the channel.
- *
- * @param messages - An array of {@link Message} objects.
- * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
- */
- publish(messages: any[]): Promise;
- /**
- * Publish a message to the channel. When publish is called with this client library, it won't attempt to implicitly attach to the channel.
- *
- * @param message - A {@link Message} object.
- * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
- */
- publish(message: any): Promise;
- /**
- * Returns a promise which is resolved when the channel reaches the specified {@link ChannelState}. If the channel is already in the specified state, the promise is resolved immediately.
- *
- * @param targetState - The state which should be reached.
- */
- whenState(targetState: ChannelState): Promise;
- }
+ mode?: 'cbc';
+};
+/**
+ * Contains the properties required to configure the encryption of {@link Message} payloads.
+ */
+export interface Crypto {
/**
- * Creates and destroys {@link ChannelBase} and {@link RealtimeChannelBase} objects.
+ * Generates a random key to be used in the encryption of the channel. If the language cryptographic randomness primitives are blocking or async, a callback is used. The callback returns a generated binary key.
+ *
+ * @param keyLength - The length of the key, in bits, to be generated. If not specified, this is equal to the default `keyLength` of the default algorithm: for AES this is 256 bits.
+ * @returns A promise which, upon success, will be fulfilled with the generated key as a binary, for example, a byte array. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
*/
- class Channels {
- /**
- * Creates a new {@link ChannelBase} or {@link RealtimeChannelBase} object, with the specified {@link ChannelOptions}, or returns the existing channel object.
- *
- * @param name - The channel name.
- * @param channelOptions - A {@link ChannelOptions} object.
- * @returns A {@link ChannelBase} or {@link RealtimeChannelBase} object.
- */
- get(name: string, channelOptions?: ChannelOptions): T;
- /**
- * Creates a new {@link ChannelBase} or {@link RealtimeChannelBase} object, with the specified channel {@link DeriveOptions}
- * and {@link ChannelOptions}, or returns the existing channel object.
- *
- * @experimental This is a preview feature and may change in a future non-major release.
- * This experimental method allows you to create custom realtime data feeds by selectively subscribing
- * to receive only part of the data from the channel.
- * See the [announcement post](https://pages.ably.com/subscription-filters-preview) for more information.
- * @param name - The channel name.
- * @param deriveOptions - A {@link DeriveOptions} object.
- * @param channelOptions - A {@link ChannelOptions} object.
- * @returns A {@link RealtimeChannelBase} object.
- */
- getDerived(name: string, deriveOptions: DeriveOptions, channelOptions?: ChannelOptions): T;
- /**
- * Releases a {@link ChannelBase} or {@link RealtimeChannelBase} object, deleting it, and enabling it to be garbage collected. It also removes any listeners associated with the channel. To release a channel, the {@link ChannelState} must be `INITIALIZED`, `DETACHED`, or `FAILED`.
- *
- * @param name - The channel name.
- */
- release(name: string): void;
- }
-
+ generateRandomKey(keyLength?: number): Promise;
/**
- * Contains an individual message that is sent to, or received from, Ably.
+ * Returns a {@link CipherParams} object, using the default values for any fields not supplied by the {@link CipherParamOptions} object.
+ *
+ * @param params - A {@link CipherParamOptions} object.
+ * @returns A {@link CipherParams} object, using the default values for any fields not supplied.
*/
- class Message {
- /**
- * Constructor for internal use.
- *
- * @internal
- */
- constructor();
- /**
- * A static factory method to create a `Message` object from a deserialized Message-like object encoded using Ably's wire protocol.
- *
- * @param JsonObject - A `Message`-like deserialized object.
- * @param channelOptions - A {@link ChannelOptions} object. If you have an encrypted channel, use this to allow the library to decrypt the data.
- * @returns A `Message` object.
- */
- static fromEncoded: (JsonObject: any, channelOptions?: ChannelOptions) => Message;
- /**
- * A static factory method to create an array of `Message` objects from an array of deserialized Message-like object encoded using Ably's wire protocol.
- *
- * @param JsonArray - An array of `Message`-like deserialized objects.
- * @param channelOptions - A {@link ChannelOptions} object. If you have an encrypted channel, use this to allow the library to decrypt the data.
- * @returns An array of {@link Message} objects.
- */
- static fromEncodedArray: (JsonArray: any[], channelOptions?: ChannelOptions) => Message[];
- /**
- * The client ID of the publisher of this message.
- */
- clientId: string;
- /**
- * The connection ID of the publisher of this message.
- */
- connectionId?: string;
- /**
- * The message payload, if provided.
- */
- data: any;
- /**
- * This is typically empty, as all messages received from Ably are automatically decoded client-side using this value. However, if the message encoding cannot be processed, this attribute contains the remaining transformations not applied to the `data` payload.
- */
- encoding: string;
- /**
- * A JSON object of arbitrary key-value pairs that may contain metadata, and/or ancillary payloads. Valid payloads include `push`, `delta`, `ref` and `headers`.
- */
- extras: any;
- /**
- * Unique ID assigned by Ably to this message.
- */
- id: string;
- /**
- * The event name.
- */
- name: string;
- /**
- * Timestamp of when the message was received by Ably, as milliseconds since the Unix epoch.
- */
- timestamp: number;
- }
+ getDefaultParams(params: CipherParamOptions): CipherParams;
+}
+/**
+ * Enables the management of a connection to Ably.
+ */
+export declare interface Connection
+ extends EventEmitter {
/**
- * Static utilities related to messages.
+ * An {@link ErrorInfo} object describing the last error received if a connection failure occurs.
*/
- interface MessageStatic {
- /**
- * A static factory method to create a `Message` object from a deserialized Message-like object encoded using Ably's wire protocol.
- *
- * @param JsonObject - A `Message`-like deserialized object.
- * @param channelOptions - A {@link ChannelOptions} object. If you have an encrypted channel, use this to allow the library to decrypt the data.
- * @returns A `Message` object.
- */
- fromEncoded: (JsonObject: any, channelOptions?: ChannelOptions) => Message;
- /**
- * A static factory method to create an array of `Message` objects from an array of deserialized Message-like object encoded using Ably's wire protocol.
- *
- * @param JsonArray - An array of `Message`-like deserialized objects.
- * @param channelOptions - A {@link ChannelOptions} object. If you have an encrypted channel, use this to allow the library to decrypt the data.
- * @returns An array of {@link Message} objects.
- */
- fromEncodedArray: (JsonArray: any[], channelOptions?: ChannelOptions) => Message[];
- }
-
+ errorReason: ErrorInfo;
/**
- * Contains an individual presence update sent to, or received from, Ably.
+ * A unique public identifier for this connection, used to identify this member.
*/
- class PresenceMessage {
- /**
- * Constructor for internal use.
- *
- * @internal
- */
- constructor();
- /**
- * Decodes and decrypts a deserialized `PresenceMessage`-like object using the cipher in {@link ChannelOptions}. Any residual transforms that cannot be decoded or decrypted will be in the `encoding` property. Intended for users receiving messages from a source other than a REST or Realtime channel (for example a queue) to avoid having to parse the encoding string.
- *
- * @param JsonObject - The deserialized `PresenceMessage`-like object to decode and decrypt.
- * @param channelOptions - A {@link ChannelOptions} object containing the cipher.
- */
- static fromEncoded: (JsonObject: any, channelOptions?: ChannelOptions) => PresenceMessage;
- /**
- * Decodes and decrypts an array of deserialized `PresenceMessage`-like object using the cipher in {@link ChannelOptions}. Any residual transforms that cannot be decoded or decrypted will be in the `encoding` property. Intended for users receiving messages from a source other than a REST or Realtime channel (for example a queue) to avoid having to parse the encoding string.
- *
- * @param JsonArray - An array of deserialized `PresenceMessage`-like objects to decode and decrypt.
- * @param channelOptions - A {@link ChannelOptions} object containing the cipher.
- */
- static fromEncodedArray: (JsonArray: any[], channelOptions?: ChannelOptions) => PresenceMessage[];
- /**
- * The type of {@link PresenceAction} the `PresenceMessage` is for.
- */
- action: PresenceAction;
- /**
- * The ID of the client that published the `PresenceMessage`.
- */
- clientId: string;
- /**
- * The ID of the connection associated with the client that published the `PresenceMessage`.
- */
- connectionId: string;
- /**
- * The payload of the `PresenceMessage`.
- */
- data: any;
- /**
- * This will typically be empty as all presence messages received from Ably are automatically decoded client-side using this value. However, if the message encoding cannot be processed, this attribute will contain the remaining transformations not applied to the data payload.
- */
- encoding: string;
- /**
- * A JSON object of arbitrary key-value pairs that may contain metadata, and/or ancillary payloads. Valid payloads include `headers`.
- */
- extras: any;
- /**
- * A unique ID assigned to each `PresenceMessage` by Ably.
- */
- id: string;
- /**
- * The time the `PresenceMessage` was received by Ably, as milliseconds since the Unix epoch.
- */
- timestamp: number;
- }
+ id?: string;
+ /**
+ * A unique private connection key used to recover or resume a connection, assigned by Ably. This private connection key can also be used by other REST clients to publish on behalf of this client. See the [publishing over REST on behalf of a realtime client docs](https://ably.com/docs/rest/channels#publish-on-behalf) for more info. (If you want to explicitly recover a connection in a different SDK instance, see createRecoveryKey() instead)
+ */
+ key?: string;
+ /**
+ * createRecoveryKey method returns a string that can be used by another client to recover this connection's state in the recover client options property. See [connection state recover options](https://ably.com/docs/connect/states?lang=javascript#connection-state-recovery) for more information.
+ */
+ createRecoveryKey(): string | null;
+ /**
+ * The current {@link ConnectionState} of the connection.
+ */
+ readonly state: ConnectionState;
+ /**
+ * Causes the connection to close, entering the {@link ConnectionStates.CLOSING} state. Once closed, the library does not attempt to re-establish the connection without an explicit call to {@link Connection.connect | `connect()`}.
+ */
+ close(): void;
+ /**
+ * Explicitly calling `connect()` is unnecessary unless the `autoConnect` attribute of the {@link ClientOptions} object is `false`. Unless already connected or connecting, this method causes the connection to open, entering the {@link ConnectionStates.CONNECTING} state.
+ */
+ connect(): void;
/**
- * Static utilities related to presence messages.
+ * When connected, sends a heartbeat ping to the Ably server and executes the callback with any error and the response time in milliseconds when a heartbeat ping request is echoed from the server. This can be useful for measuring true round-trip latency to the connected Ably server.
+ *
+ * @returns A promise which, upon success, will be fulfilled with the response time in milliseconds. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
*/
- interface PresenceMessageStatic {
- /**
- * Decodes and decrypts a deserialized `PresenceMessage`-like object using the cipher in {@link ChannelOptions}. Any residual transforms that cannot be decoded or decrypted will be in the `encoding` property. Intended for users receiving messages from a source other than a REST or Realtime channel (for example a queue) to avoid having to parse the encoding string.
- *
- * @param JsonObject - The deserialized `PresenceMessage`-like object to decode and decrypt.
- * @param channelOptions - A {@link ChannelOptions} object containing the cipher.
- */
- fromEncoded: (JsonObject: any, channelOptions?: ChannelOptions) => PresenceMessage;
- /**
- * Decodes and decrypts an array of deserialized `PresenceMessage`-like object using the cipher in {@link ChannelOptions}. Any residual transforms that cannot be decoded or decrypted will be in the `encoding` property. Intended for users receiving messages from a source other than a REST or Realtime channel (for example a queue) to avoid having to parse the encoding string.
- *
- * @param JsonArray - An array of deserialized `PresenceMessage`-like objects to decode and decrypt.
- * @param channelOptions - A {@link ChannelOptions} object containing the cipher.
- */
- fromEncodedArray: (JsonArray: any[], channelOptions?: ChannelOptions) => PresenceMessage[];
+ ping(): Promise;
+ /**
+ * If the connection is already in the given state, returns a promise which immediately resolves to `null`. Else, calls {@link EventEmitter.once | `once()`} to return a promise which resolves the next time the connection transitions to the given state.
+ *
+ * @param targetState - The connection state to wait for.
+ */
+ whenState(targetState: ConnectionState): Promise;
+}
- /**
- * Initialises a `PresenceMessage` from a `PresenceMessage`-like object.
- *
- * @param values - The values to intialise the `PresenceMessage` from.
- * @param stringifyAction - Whether to convert the `action` field from a number to a string.
- */
- fromValues(values: PresenceMessage | Record, stringifyAction?: boolean): PresenceMessage;
- }
+/**
+ * Contains application statistics for a specified time interval and time period.
+ */
+export declare interface Stats {
+ /**
+ * The UTC time at which the time period covered begins. If `unit` is set to `minute` this will be in the format `YYYY-mm-dd:HH:MM`, if `hour` it will be `YYYY-mm-dd:HH`, if `day` it will be `YYYY-mm-dd:00` and if `month` it will be `YYYY-mm-01:00`.
+ */
+ intervalId: string;
+ /**
+ * For entries that are still in progress, such as the current month: the last sub-interval included in this entry (in format yyyy-mm-dd:hh:mm:ss), else undefined.
+ */
+ inProgress?: string;
+ /**
+ * The statistics for this time interval and time period. See the JSON schema which the {@link Stats.schema | `schema`} property points to for more information.
+ */
+ entries: Partial>;
+ /**
+ * The URL of a [JSON Schema](https://json-schema.org/) which describes the structure of this `Stats` object.
+ */
+ schema: string;
+ /**
+ * The ID of the Ably application the statistics are for.
+ */
+ appId: string;
+}
+/**
+ * Contains a page of results for message or presence history, stats, or REST presence requests. A `PaginatedResult` response from a REST API paginated query is also accompanied by metadata that indicates the relative queries available to the `PaginatedResult` object.
+ */
+export declare interface PaginatedResult {
+ /**
+ * Contains the current page of results; for example, an array of {@link InboundMessage} or {@link PresenceMessage} objects for a channel history request.
+ */
+ items: T[];
+ /**
+ * Returns a new `PaginatedResult` for the first page of results.
+ *
+ * @returns A promise which, upon success, will be fulfilled with a page of results for message and presence history, stats, and REST presence requests. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
+ */
+ first(): Promise>;
+ /**
+ * Returns a new `PaginatedResult` loaded with the next page of results. If there are no further pages, then `null` is returned.
+ *
+ * @returns A promise which, upon success, will be fulfilled with a page of results for message and presence history, stats, and REST presence requests. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
+ */
+ next(): Promise | null>;
+ /**
+ * Returns the `PaginatedResult` for the current page of results.
+ */
+ current(): Promise>;
/**
- * Cipher Key used in {@link CipherParamOptions}. If set to a `string`, the value must be base64 encoded.
+ * Returns `true` if there are more pages available by calling next and returns `false` if this page is the last page available.
+ *
+ * @returns Whether or not there are more pages of results.
*/
- type CipherKeyParam = ArrayBuffer | Uint8Array | string; // if string must be base64-encoded
+ hasNext(): boolean;
/**
- * Typed differently depending on platform. (`WordArray` in browser, `Buffer` in node)
+ * Returns `true` if this page is the last page and returns `false` if there are more pages available by calling next available.
*
- * @internal
+ * @returns Whether or not this is the last page of results.
*/
- type CipherKey = unknown; // WordArray on browsers, Buffer on node, using unknown as
- // user should not be interacting with it - output of getDefaultParams should be used opaquely
+ isLast(): boolean;
+}
+/**
+ * A superset of {@link PaginatedResult} which represents a page of results plus metadata indicating the relative queries available to it. `HttpPaginatedResponse` additionally carries information about the response to an HTTP request.
+ */
+export declare interface HttpPaginatedResponse extends PaginatedResult {
/**
- * Contains the properties used to generate a {@link CipherParams} object.
+ * The HTTP status code of the response.
*/
- type CipherParamOptions = {
- /**
- * The private key used to encrypt and decrypt payloads.
- */
- key: CipherKeyParam;
- /**
- * The algorithm to use for encryption. Only `AES` is supported.
- */
- algorithm?: 'aes';
- /**
- * The length of the key in bits; for example 128 or 256.
- */
- keyLength?: number;
- /**
- * The cipher mode. Only `CBC` is supported.
- */
- mode?: 'cbc';
- };
+ statusCode: number;
+ /**
+ * Whether `statusCode` indicates success. This is equivalent to `200 <= statusCode < 300`.
+ */
+ success: boolean;
+ /**
+ * The error code if the `X-Ably-Errorcode` HTTP header is sent in the response.
+ */
+ errorCode: number;
+ /**
+ * The error message if the `X-Ably-Errormessage` HTTP header is sent in the response.
+ */
+ errorMessage: string;
+ /**
+ * The headers of the response.
+ */
+ headers: any;
+}
+/**
+ * Enables a device to be registered and deregistered from receiving push notifications.
+ */
+export declare interface Push {
/**
- * Contains the properties required to configure the encryption of {@link Message} payloads.
+ * A {@link PushAdmin} object.
*/
- interface Crypto {
- /**
- * Generates a random key to be used in the encryption of the channel. If the language cryptographic randomness primitives are blocking or async, a callback is used. The callback returns a generated binary key.
- *
- * @param keyLength - The length of the key, in bits, to be generated. If not specified, this is equal to the default `keyLength` of the default algorithm: for AES this is 256 bits.
- * @param callback - A function which, upon success, will be called with the generated key as a binary, for example, a byte array. Upon failure, the function will be called with information about the error.
- */
- generateRandomKey(keyLength?: number, callback?: Types.StandardCallback): void;
- /**
- * Returns a {@link CipherParams} object, using the default values for any fields not supplied by the {@link CipherParamOptions} object.
- *
- * @param params - A {@link CipherParamOptions} object.
- * @returns A {@link CipherParams} object, using the default values for any fields not supplied.
- */
- getDefaultParams(params: CipherParamOptions): CipherParams;
- }
+ admin: PushAdmin;
+}
+/**
+ * Enables the management of device registrations and push notification subscriptions. Also enables the publishing of push notifications to devices.
+ */
+export declare interface PushAdmin {
/**
- * The `ConnectionBase` class acts as a base class for the {@link ChannelCallbacks} and {@link ChannelPromise} classes.
+ * A {@link PushDeviceRegistrations} object.
*/
- class ConnectionBase extends EventEmitter {
- /**
- * An {@link ErrorInfo} object describing the last error received if a connection failure occurs.
- */
- errorReason: ErrorInfo;
- /**
- * A unique public identifier for this connection, used to identify this member.
- */
- id?: string;
- /**
- * A unique private connection key used to recover or resume a connection, assigned by Ably. When recovering a connection explicitly, the `recoveryKey` is used in the recover client options as it contains both the key and the last message serial. This private connection key can also be used by other REST clients to publish on behalf of this client. See the [publishing over REST on behalf of a realtime client docs](https://ably.com/docs/rest/channels#publish-on-behalf) for more info.
- */
- key?: string;
- /**
- * The recovery key string can be used by another client to recover this connection's state in the recover client options property. See [connection state recover options](https://ably.com/docs/realtime/connection#connection-state-recover-options) for more information.
- */
- recoveryKey: string | null;
- /**
- * The serial number of the last message to be received on this connection, used automatically by the library when recovering or resuming a connection. When recovering a connection explicitly, the `recoveryKey` is used in the recover client options as it contains both the key and the last message serial.
- */
- serial: number;
- /**
- * The current {@link ConnectionState} of the connection.
- */
- readonly state: ConnectionState;
- /**
- * Causes the connection to close, entering the {@link ConnectionState.CLOSING} state. Once closed, the library does not attempt to re-establish the connection without an explicit call to {@link ConnectionBase.connect | `connect()`}.
- */
- close(): void;
- /**
- * Explicitly calling `connect()` is unnecessary unless the `autoConnect` attribute of the {@link ClientOptions} object is `false`. Unless already connected or connecting, this method causes the connection to open, entering the {@link ConnectionState.CONNECTING} state.
- */
- connect(): void;
- }
-
+ deviceRegistrations: PushDeviceRegistrations;
/**
- * Enables the management of a connection to Ably.
+ * A {@link PushChannelSubscriptions} object.
*/
- class ConnectionCallbacks extends ConnectionBase {
- /**
- * When connected, sends a heartbeat ping to the Ably server and executes the callback with any error and the response time in milliseconds when a heartbeat ping request is echoed from the server. This can be useful for measuring true round-trip latency to the connected Ably server.
- *
- * @param callback - A function which, upon success, will be called with the response time in milliseconds. Upon failure, the function will be called with information about the error.
- */
- ping(callback?: Types.StandardCallback): void;
- /**
- * Calls the supplied function when the connection reaches the specified {@link ConnectionState}. If the connection is already in the specified state, the callback is called immediately.
- *
- * @param targetState - The state which should be reached.
- * @param callback - A function which will be called when the connection has reached the specified {@link ConnectionState} with a {@link ConnectionStateChange} object as the first argument.
- */
- whenState(targetState: ConnectionState, callback: connectionEventCallback): void;
- }
-
+ channelSubscriptions: PushChannelSubscriptions;
/**
- * Enables the management of a connection to Ably.
+ * Sends a push notification directly to a device, or a group of devices sharing the same `clientId`.
+ *
+ * @param recipient - A JSON object containing the recipient details using `clientId`, `deviceId` or the underlying notifications service.
+ * @param payload - A JSON object containing the push notification payload.
+ * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
*/
- class ConnectionPromise extends ConnectionBase {
- /**
- * When connected, sends a heartbeat ping to the Ably server and executes the callback with any error and the response time in milliseconds when a heartbeat ping request is echoed from the server. This can be useful for measuring true round-trip latency to the connected Ably server.
- *
- * @returns A promise which, upon success, will be fulfilled with the response time in milliseconds. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
- */
- ping(): Promise;
- /**
- * Returns a promise which is resolved when the connection reaches the specified {@link ConnectionState}. If the connection is already in the specified state, the promise is resolved immediately.
- *
- * @param targetState - The state which should be reached.
- */
- whenState(targetState: ConnectionState): Promise;
- }
+ publish(recipient: any, payload: any): Promise;
+}
+/**
+ * Enables the management of push notification registrations with Ably.
+ */
+export declare interface PushDeviceRegistrations {
/**
- * Contains application statistics for a specified time interval and time period.
+ * Registers or updates a {@link DeviceDetails} object with Ably. Returns the new, or updated {@link DeviceDetails} object.
+ *
+ * @param deviceDetails - The {@link DeviceDetails} object to create or update.
+ * @returns A promise which, upon success, will be fulfilled with a {@link DeviceDetails} object. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
*/
- class Stats {
- /**
- * A {@link StatsMessageTypes} object containing the aggregate count of all message stats.
- */
- all: StatsMessageTypes;
- /**
- * A {@link StatsRequestCount} object containing a breakdown of API Requests.
- */
- apiRequests: StatsRequestCount;
- /**
- * A {@link StatsResourceCount} object containing a breakdown of channels.
- */
- channels: StatsResourceCount;
- /**
- * A {@link StatsConnectionTypes} object containing a breakdown of connection related stats, such as min, mean and peak connections.
- */
- connections: StatsConnectionTypes;
- /**
- * A {@link StatsMessageTraffic} object containing the aggregate count of inbound message stats.
- */
- inbound: StatsMessageTraffic;
- /**
- * The UTC time at which the time period covered begins. If `unit` is set to `minute` this will be in the format `YYYY-mm-dd:HH:MM`, if `hour` it will be `YYYY-mm-dd:HH`, if `day` it will be `YYYY-mm-dd:00` and if `month` it will be `YYYY-mm-01:00`.
- */
- intervalId: string;
- /**
- * A {@link StatsMessageTraffic} object containing the aggregate count of outbound message stats.
- */
- outbound: StatsMessageTraffic;
- /**
- * A {@link StatsMessageTypes} object containing the aggregate count of persisted message stats.
- */
- persisted: StatsMessageTypes;
- /**
- * A {@link StatsRequestCount} object containing a breakdown of Ably Token requests.
- */
- tokenRequests: StatsRequestCount;
- }
-
+ save(deviceDetails: DeviceDetails): Promise;
/**
- * Contains a page of results for message or presence history, stats, or REST presence requests. A `PaginatedResult` response from a REST API paginated query is also accompanied by metadata that indicates the relative queries available to the `PaginatedResult` object.
+ * Retrieves the {@link DeviceDetails} of a device registered to receive push notifications using its `deviceId`.
+ *
+ * @param deviceId - The unique ID of the device.
+ * @returns A promise which, upon success, will be fulfilled with a {@link DeviceDetails} object. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
*/
- class PaginatedResult {
- /**
- * Contains the current page of results; for example, an array of {@link Message} or {@link PresenceMessage} objects for a channel history request.
- */
- items: T[];
- /**
- * Returns a new `PaginatedResult` for the first page of results.
- *
- * @param results - A function which, upon success, will be called with a page of results for message and presence history, stats, and REST presence requests. Upon failure, the function will be called with information about the error.
- */
- first(results: paginatedResultCallback): void;
- /**
- * Returns a new `PaginatedResult` for the first page of results.
- *
- * @returns A promise which, upon success, will be fulfilled with a page of results for message and presence history, stats, and REST presence requests. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
- */
- first(): Promise>;
- /**
- * Returns a new `PaginatedResult` loaded with the next page of results. If there are no further pages, then `null` is returned.
- *
- * @param results - A function which, upon success, will be fulfilled with a page of results for message and presence history, stats, and REST presence requests. Upon failure, the function will be called with information about the error.
- */
- next(results: StandardCallback | null>): void;
- /**
- * Returns a new `PaginatedResult` loaded with the next page of results. If there are no further pages, then `null` is returned.
- *
- * @returns A promise which, upon success, will be fulfilled with a page of results for message and presence history, stats, and REST presence requests. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
- */
- next(): Promise | null>;
- /**
- * Returns the `PaginatedResult` for the current page of results.
- *
- * @param results - A function which, upon success, will be fulfilled with a page of results for message and presence history, stats, and REST presence requests. Upon failure, the function will be called with information about the error.
- */
- current(results: paginatedResultCallback): void;
- /**
- * Returns the `PaginatedResult` for the current page of results.
- */
- current(): Promise>;
- /**
- * Returns `true` if there are more pages available by calling next and returns `false` if this page is the last page available.
- *
- * @returns Whether or not there are more pages of results.
- */
- hasNext(): boolean;
- /**
- * Returns `true` if this page is the last page and returns `false` if there are more pages available by calling next available.
- *
- * @returns Whether or not this is the last page of results.
- */
- isLast(): boolean;
- }
-
+ get(deviceId: string): Promise;
/**
- * A superset of {@link Types.PaginatedResult} which represents a page of results plus metadata indicating the relative queries available to it. `HttpPaginatedResponse` additionally carries information about the response to an HTTP request.
+ * Retrieves the {@link DeviceDetails} of a device registered to receive push notifications using the `id` property of a {@link DeviceDetails} object.
+ *
+ * @param deviceDetails - The {@link DeviceDetails} object containing the `id` property of the device.
+ * @returns A promise which, upon success, will be fulfilled with a {@link DeviceDetails} object. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
*/
- class HttpPaginatedResponse extends PaginatedResult {
- /**
- * The HTTP status code of the response.
- */
- statusCode: number;
- /**
- * Whether `statusCode` indicates success. This is equivalent to `200 <= statusCode < 300`.
- */
- success: boolean;
- /**
- * The error code if the `X-Ably-Errorcode` HTTP header is sent in the response.
- */
- errorCode: number;
- /**
- * The error message if the `X-Ably-Errormessage` HTTP header is sent in the response.
- */
- errorMessage: string;
- /**
- * The headers of the response.
- */
- headers: any;
- }
-
+ get(deviceDetails: DeviceDetails): Promise;
/**
- * Enables a device to be registered and deregistered from receiving push notifications.
+ * Retrieves all devices matching the filter `params` provided. Returns a {@link PaginatedResult} object, containing an array of {@link DeviceDetails} objects.
+ *
+ * @param params - An object containing key-value pairs to filter devices by.
+ * @returns A promise which, upon success, will be fulfilled with a {@link PaginatedResult} object containing an array of {@link DeviceDetails} objects. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
*/
- class PushCallbacks {
- /**
- * A {@link PushAdminCallbacks} object.
- */
- admin: PushAdminCallbacks;
- }
-
+ list(params: DeviceRegistrationParams): Promise>;
/**
- * Enables a device to be registered and deregistered from receiving push notifications.
+ * Removes a device registered to receive push notifications from Ably using its `deviceId`.
+ *
+ * @param deviceId - The unique ID of the device.
+ * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
*/
- class PushPromise {
- /**
- * A {@link PushAdminPromise | `PushAdmin`} object.
- */
- admin: PushAdminPromise;
- }
-
+ remove(deviceId: string): Promise;
/**
- * Enables the management of device registrations and push notification subscriptions. Also enables the publishing of push notifications to devices.
+ * Removes a device registered to receive push notifications from Ably using the `id` property of a {@link DeviceDetails} object.
+ *
+ * @param deviceDetails - The {@link DeviceDetails} object containing the `id` property of the device.
+ * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
*/
- class PushAdminCallbacks {
- /**
- * A {@link PushDeviceRegistrationsCallbacks} object.
- */
- deviceRegistrations: PushDeviceRegistrationsCallbacks;
- /**
- * A {@link PushChannelSubscriptionsCallbacks} object.
- */
- channelSubscriptions: PushChannelSubscriptionsCallbacks;
- /**
- * Sends a push notification directly to a device, or a group of devices sharing the same `clientId`.
- *
- * @param recipient - A JSON object containing the recipient details using `clientId`, `deviceId` or the underlying notifications service.
- * @param payload - A JSON object containing the push notification payload.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- publish(recipient: any, payload: any, callback?: errorCallback): void;
- }
-
+ remove(deviceDetails: DeviceDetails): Promise;
/**
- * Enables the management of device registrations and push notification subscriptions. Also enables the publishing of push notifications to devices.
+ * Removes all devices registered to receive push notifications from Ably matching the filter `params` provided.
+ *
+ * @param params - An object containing key-value pairs to filter devices by. This object’s {@link DeviceRegistrationParams.limit} property will be ignored.
+ * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
*/
- class PushAdminPromise {
- /**
- * A {@link PushDeviceRegistrationsPromise} object.
- */
- deviceRegistrations: PushDeviceRegistrationsPromise;
- /**
- * A {@link PushChannelSubscriptionsPromise} object.
- */
- channelSubscriptions: PushChannelSubscriptionsPromise;
- /**
- * Sends a push notification directly to a device, or a group of devices sharing the same `clientId`.
- *
- * @param recipient - A JSON object containing the recipient details using `clientId`, `deviceId` or the underlying notifications service.
- * @param payload - A JSON object containing the push notification payload.
- * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
- */
- publish(recipient: any, payload: any): Promise;
- }
+ removeWhere(params: DeviceRegistrationParams): Promise;
+}
+/**
+ * Enables device push channel subscriptions.
+ */
+export declare interface PushChannelSubscriptions {
/**
- * Enables the management of push notification registrations with Ably.
+ * Subscribes a device, or a group of devices sharing the same `clientId` to push notifications on a channel. Returns a {@link PushChannelSubscription} object.
+ *
+ * @param subscription - A {@link PushChannelSubscription} object.
+ * @returns A promise which, upon success, will be fulfilled with a {@link PushChannelSubscription} object describing the new or updated subscriptions. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
*/
- class PushDeviceRegistrationsCallbacks {
- /**
- * Registers or updates a {@link DeviceDetails} object with Ably. Returns the new, or updated {@link DeviceDetails} object.
- *
- * @param deviceDetails - The {@link DeviceDetails} object to create or update.
- * @param callback - A function which, upon success, will be called with a {@link DeviceDetails} object. Upon failure, the function will be called with information about the error.
- */
- save(deviceDetails: DeviceDetails, callback?: Types.StandardCallback): void;
- /**
- * Retrieves the {@link DeviceDetails} of a device registered to receive push notifications using its `deviceId`.
- *
- * @param deviceId - The unique ID of the device.
- * @param callback - A function which, upon success, will be called with a {@link DeviceDetails} object. Upon failure, the function will be called with information about the error.
- */
- get(deviceId: string, callback: Types.StandardCallback): void;
- /**
- * Retrieves the {@link DeviceDetails} of a device registered to receive push notifications using the `id` property of a {@link DeviceDetails} object.
- *
- * @param deviceDetails - The {@link DeviceDetails} object containing the `id` property of the device.
- * @param callback - A function which, upon success, will be called with a {@link DeviceDetails} object. Upon failure, the function will be called with information about the error.
- */
- get(deviceDetails: DeviceDetails, callback: Types.StandardCallback): void;
- /**
- * Retrieves all devices matching the filter `params` provided. Returns a {@link Types.PaginatedResult} object, containing an array of {@link DeviceDetails} objects.
- *
- * @param params - An object containing key-value pairs to filter devices by.
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link DeviceDetails} objects. Upon failure, the function will be called with information about the error.
- */
- list(params: DeviceRegistrationParams, callback: paginatedResultCallback): void;
- /**
- * Removes a device registered to receive push notifications from Ably using its `deviceId`.
- *
- * @param deviceId - The unique ID of the device.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- remove(deviceId: string, callback?: errorCallback): void;
- /**
- * Removes a device registered to receive push notifications from Ably using the `id` property of a {@link DeviceDetails} object.
- *
- * @param deviceDetails - The {@link DeviceDetails} object containing the `id` property of the device.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- remove(deviceDetails: DeviceDetails, callback?: errorCallback): void;
- /**
- * Removes all devices registered to receive push notifications from Ably matching the filter `params` provided.
- *
- * @param params - An object containing key-value pairs to filter devices by. This object’s {@link DeviceRegistrationParams.limit} property will be ignored.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- removeWhere(params: DeviceRegistrationParams, callback?: errorCallback): void;
- }
-
+ save(subscription: PushChannelSubscription): Promise;
/**
- * Enables the management of push notification registrations with Ably.
+ * Retrieves all push channel subscriptions matching the filter `params` provided. Returns a {@link PaginatedResult} object, containing an array of {@link PushChannelSubscription} objects.
+ *
+ * @param params - An object containing key-value pairs to filter subscriptions by.
+ * @returns A promise which, upon success, will be fulfilled with a {@link PaginatedResult} object containing an array of {@link PushChannelSubscription} objects. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
*/
- class PushDeviceRegistrationsPromise {
- /**
- * Registers or updates a {@link DeviceDetails} object with Ably. Returns the new, or updated {@link DeviceDetails} object.
- *
- * @param deviceDetails - The {@link DeviceDetails} object to create or update.
- * @returns A promise which, upon success, will be fulfilled with a {@link DeviceDetails} object. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
- */
- save(deviceDetails: DeviceDetails): Promise;
- /**
- * Retrieves the {@link DeviceDetails} of a device registered to receive push notifications using its `deviceId`.
- *
- * @param deviceId - The unique ID of the device.
- * @returns A promise which, upon success, will be fulfilled with a {@link DeviceDetails} object. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
- */
- get(deviceId: string): Promise;
- /**
- * Retrieves the {@link DeviceDetails} of a device registered to receive push notifications using the `id` property of a {@link DeviceDetails} object.
- *
- * @param deviceDetails - The {@link DeviceDetails} object containing the `id` property of the device.
- * @returns A promise which, upon success, will be fulfilled with a {@link DeviceDetails} object. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
- */
- get(deviceDetails: DeviceDetails): Promise;
- /**
- * Retrieves all devices matching the filter `params` provided. Returns a {@link Types.PaginatedResult} object, containing an array of {@link DeviceDetails} objects.
- *
- * @param params - An object containing key-value pairs to filter devices by.
- * @returns A promise which, upon success, will be fulfilled with a {@link Types.PaginatedResult} object containing an array of {@link DeviceDetails} objects. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
- */
- list(params: DeviceRegistrationParams): Promise>;
- /**
- * Removes a device registered to receive push notifications from Ably using its `deviceId`.
- *
- * @param deviceId - The unique ID of the device.
- * @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
- */
- remove(deviceId: string): Promise