diff --git a/.eslintrc b/.eslintrc index 41c6158e..f1891db5 100644 --- a/.eslintrc +++ b/.eslintrc @@ -14,6 +14,7 @@ "plugin:jest-formatting/recommended", "prettier" ], + "ignorePatterns": ["**/__tests__/**"], "parser": "@typescript-eslint/parser", "parserOptions": { "ecmaVersion": "latest", @@ -62,10 +63,11 @@ "error", { "code": 80, + "comments": 120, "ignoreUrls": true, "ignoreTemplateLiterals": true, "ignoreRegExpLiterals": true, - "ignorePattern": "^import.+|test" + "ignorePattern": "^import.+|test|@" } ] } diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 00000000..b5da0626 --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,36 @@ +--- +name: Documentation + +on: + push: + branches: + - 3.x + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v1 + + - name: Setup node + uses: actions/setup-node@v3 + with: + node-version: 18.x + + - name: Install packages + run: npm install + + - name: Build Typedoc + run: npm run typedoc + + - name: Build example markdown + run: node scripts/generateExample.mjs + + + - name: Upload Documentation to Wiki + uses: SwiftDocOrg/github-wiki-publish-action@v1 + with: + path: "docs" + env: + GH_PERSONAL_ACCESS_TOKEN: ${{ secrets.GH_WIKI_PERSONAL_ACCESS_TOKEN }} diff --git a/.gitignore b/.gitignore index e10541d6..076e795b 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,4 @@ packages/**/dist tsconfig.tsbuildinfo lerna-debug.log package-lock.json +docs diff --git a/jest.config.ts b/jest.config.ts index 03b1a956..065b53ce 100644 --- a/jest.config.ts +++ b/jest.config.ts @@ -116,11 +116,6 @@ const config: Config.InitialOptions = { testMatch: ['/packages/verify2/__tests__/**/*.test.ts'], coveragePathIgnorePatterns: ['node_modules', '__tests__'], }, - { - displayName: 'VETCH', - testMatch: ['/packages/vetch/__tests__/**/*.test.ts'], - coveragePathIgnorePatterns: ['node_modules', '__tests__'], - }, { displayName: 'VIDEO', testMatch: ['/packages/video/__tests__/**/*.test.ts'], diff --git a/package.json b/package.json index 7db2705d..883086ca 100644 --- a/package.json +++ b/package.json @@ -1,90 +1,113 @@ { - "name": "@vonage/server-sdk-monorepo", - "private": true, - "description": "Vonage Server SDK for Node.js. API support for SMS, Voice Calls, Text-to-Speech, Numbers, Verify (2FA) and more.", - "keywords": [ - "sms", - "voice", - "vonage", - "verify", - "2fa", - "phone numbers" - ], - "homepage": "https://github.com/vonage/vonage-node-sdk", - "repository": { - "type": "git", - "url": "git://github.com/vonage/vonage-node-sdk.git" - }, - "license": "Apache 2.0", - "author": "vonage", - "contributors": [ - "kellyjandrews" - ], - "workspaces": [ - "packages/*" - ], - "scripts": { - "bootstrap": "npx lerna bootstrap", - "build": "lerna run build", - "clean": "lerna run clean", - "compile": "lerna run compile", - "depcheck": "lerna exec --no-bail --stream --prefix npx depcheck -- --ignore-dirs=dist", - "eslint": "eslint", - "format": "prettier -- -w", - "jest": "jest", - "lerna": "lerna", - "lint": "eslint .", - "lint:fix": "eslint -- . --fix", - "prepare": "is-ci || husky install", - "publish": "lerna publish", - "test": "jest", - "test:watch": "jest --watch", - "tsc": "tsc" + "$schema": "https://json.schemastore.org/package.json", + "name": "@vonage/server-sdk-monorepo", + "private": true, + "description": "Vonage Server SDK for Node.js. API support for SMS, Voice Calls, Text-to-Speech, Numbers, Verify (2FA) and more.", + "keywords": [ + "sms", + "voice", + "vonage", + "verify", + "2fa", + "phone numbers" + ], + "homepage": "https://github.com/vonage/vonage-node-sdk", + "repository": { + "type": "git", + "url": "git://github.com/vonage/vonage-node-sdk.git" + }, + "license": "Apache 2.0", + "author": "vonage", + "contributors": [ + { + "name": "Kelly Andrews", + "url": "https://github.com/kellyjandrews" }, - "lint-staged": { - "package.json": [ - "npx sort-package-json" - ], - "*.js": [ - "prettier -w", - "eslint --fix" - ], - "*.ts": [ - "prettier -w", - "eslint --fix" - ] + { + "name": "Chuck \"MANCHUCK\" Reeves", + "url": "https://github.com/manchuck" }, - "devDependencies": { - "@babel/core": "7.23.2", - "@babel/plugin-transform-modules-commonjs": "^7.23.0", - "@babel/plugin-transform-typescript": "7.22.15", - "@babel/preset-env": "7.23.2", - "@babel/preset-typescript": "7.23.2", - "@babel/types": "^7.23.0", - "@types/jest": "^29.5.5", - "@types/node": "^20.8.4", - "@typescript-eslint/eslint-plugin": "6.7.5", - "@typescript-eslint/parser": "6.7.5", - "babel-jest": "29.7.0", - "babel-plugin-module-resolver": "5.0.0", - "eslint": "8.51.0", - "eslint-config-google": "0.14.0", - "eslint-config-prettier": "9.0.0", - "eslint-plugin-deprecation": "2.0.0", - "eslint-plugin-jest": "27.4.2", - "eslint-plugin-jest-extended": "2.0.0", - "eslint-plugin-jest-formatting": "3.1.0", - "eslint-plugin-prettier": "5.0.1", - "husky": "^8.0.3", - "is-ci": "3.0.1", - "jest": "^29.7.0", - "lerna": "^7.3.1", - "lerna-changelog": "^2.2.0", - "lint-staged": "14.0.1", - "nock": "^13.3.4", - "prettier": "3.0.3", - "prettier-eslint": "15.0.1", - "ts-node-dev": "^2.0.0", - "typescript": "^5.2.2" + { + "name": "Chris Tankersley", + "url": "https://github.com/dragonmantank" } + ], + "workspaces": [ + "packages/*" + ], + "scripts": { + "bootstrap": "npx lerna bootstrap", + "build": "lerna run build", + "clean": "lerna run clean", + "compile": "lerna run compile", + "depcheck": "lerna exec --no-bail --stream --prefix npx depcheck -- --ignore-dirs=dist", + "eslint": "eslint", + "format": "prettier -- -w", + "jest": "jest", + "lerna": "lerna", + "lint": "eslint .", + "lint:fix": "eslint --fix .", + "prepare": "is-ci || husky install", + "publish": "lerna publish", + "test": "jest", + "test:watch": "jest --watch", + "tsc": "tsc", + "typedoc": "typedoc" + }, + "lint-staged": { + "package.json": [ + "npx sort-package-json" + ], + "*.js": [ + "prettier -w", + "eslint --fix" + ], + "*.ts": [ + "prettier -w", + "eslint --fix" + ] + }, + "dependencies": { + "@droppedcode/typedoc-plugin-copy-assets": "1.0.10" + }, + "devDependencies": { + "@babel/core": "7.22.5", + "@babel/plugin-transform-modules-commonjs": "^7.22.5", + "@babel/plugin-transform-typescript": "7.22.15", + "@babel/preset-env": "7.22.5", + "@babel/preset-typescript": "7.22.5", + "@babel/types": "^7.22.5", + "@mxssfd/typedoc-theme": "1.1.3", + "@tsconfig/node16": "16.1.1", + "@types/jest": "^29.5.5", + "@types/node": "^20.8.4", + "@typescript-eslint/eslint-plugin": "6.7.5", + "@typescript-eslint/parser": "6.7.5", + "babel-jest": "29.7.0", + "babel-plugin-module-resolver": "5.0.0", + "eslint": "8.51.0", + "eslint-config-google": "0.14.0", + "eslint-config-prettier": "9.0.0", + "eslint-plugin-deprecation": "2.0.0", + "eslint-plugin-jest": "27.4.2", + "eslint-plugin-jest-extended": "2.0.0", + "eslint-plugin-jest-formatting": "3.1.0", + "eslint-plugin-prettier": "5.0.1", + "husky": "^8.0.3", + "is-ci": "3.0.1", + "jest": "^29.7.0", + "lerna": "^7.3.1", + "lerna-changelog": "^2.2.0", + "lint-staged": "14.0.1", + "nock": "^13.3.4", + "prettier": "3.0.3", + "prettier-eslint": "15.0.1", + "recursive-iterator": "3.3.0", + "ts-node-dev": "^2.0.0", + "typedoc": "0.25.2", + "typedoc-github-wiki-theme": "1.1.0", + "typedoc-plugin-markdown": "3.17.1", + "typedoc-plugin-merge-modules": "5.1.0", + "typescript": "^5.1.3" + } } diff --git a/packages/accounts/__tests__/accounts.test.ts b/packages/accounts/__tests__/accounts.test.ts index 46abd7f2..b08c4932 100644 --- a/packages/accounts/__tests__/accounts.test.ts +++ b/packages/accounts/__tests__/accounts.test.ts @@ -1,22 +1,22 @@ import nock from 'nock'; -import { Accounts } from '../lib/index' +import { Accounts } from '../lib/index'; import { Auth } from '@vonage/auth'; describe('accounts', () => { let client; beforeEach(() => { - client = new Accounts(new Auth({ apiKey: 'abcd', apiSecret: '1234' })); + client = new Accounts(new Auth({ apiKey: 'abcd', apiSecret: '1234' })); }); afterEach(() => { - client = null; + client = null; }); test("get balance", async () => { const expectedResponse = { "value": 10.28, - "autoReload": false + "autoReload": false, }; nock("https://rest.nexmo.com") @@ -33,7 +33,7 @@ describe('accounts', () => { test("top up balance", async () => { const expectedResponse = { "error-code": "200", - "error-code-label": "success" + "error-code-label": "success", }; nock("https://rest.nexmo.com") @@ -42,21 +42,28 @@ describe('accounts', () => { .query({ api_key: 'abcd', api_secret: '1234' }) .reply(200, expectedResponse); - const lookup = await client.topUpBalance('8ef2447e69604f642ae59363aa5f781b'); + const lookup = await client.topUpBalance( + '8ef2447e69604f642ae59363aa5f781b', + ); expect(lookup['error-code']).toEqual(expectedResponse['error-code']); - expect(lookup['error-code-label']).toEqual(expectedResponse['error-code-label']); + expect( + lookup['error-code-label'], + ).toEqual(expectedResponse['error-code-label']); }); test("update callbacks", async () => { const expectedResponse = { - "mo-callback-url": "https://example.com/webhooks/inbound-sms", "dr-callback-url": "https://example.com/webhooks/delivery-receipt", + "mo-callback-url": "https://example.com/webhooks/inbound-sms", "max-outbound-request": 30, "max-inbound-request": 30, - "max-calls-per-second": 30 + "max-calls-per-second": 30, }; - const callbacks = {moCallBackUrl: "https://example.com/webhooks/inbound-sms", drCallBackUrl: "https://example.com/webhooks/delivery-receipt"}; + const callbacks = { + drCallBackUrl: "https://example.com/webhooks/delivery-receipt", + moCallBackUrl: "https://example.com/webhooks/inbound-sms", + }; const queryString = new URLSearchParams(callbacks); const re = new RegExp(queryString.toString(), "g"); @@ -67,7 +74,11 @@ describe('accounts', () => { .reply(200, expectedResponse); const lookup = await client.updateAccountCallbacks(callbacks); - expect(lookup['mo-callback-url']).toEqual(expectedResponse['mo-callback-url']); - expect(lookup['dr-callback-url']).toEqual(expectedResponse['dr-callback-url']); + expect( + lookup['mo-callback-url'], + ).toEqual(expectedResponse['mo-callback-url']); + expect( + lookup['dr-callback-url'], + ).toEqual(expectedResponse['dr-callback-url']); }); }); diff --git a/packages/accounts/__tests__/secrets.test.ts b/packages/accounts/__tests__/secrets.test.ts index 6af2e0b3..07e2c60f 100644 --- a/packages/accounts/__tests__/secrets.test.ts +++ b/packages/accounts/__tests__/secrets.test.ts @@ -1,41 +1,41 @@ import nock from 'nock'; -import { Secrets } from '../lib/index' +import { Secrets } from '../lib/index'; import { Auth } from '@vonage/auth'; describe('secrets', () => { let client; beforeEach(() => { - client = new Secrets(new Auth({ apiKey: 'abcd', apiSecret: '1234' })); + client = new Secrets(new Auth({ apiKey: 'abcd', apiSecret: '1234' })); }); afterEach(() => { - client = null; + client = null; }); test("list secrets", async () => { const expectedResponse = { "_links": { "self": { - "href": "abc123" - } + "href": "abc123", + }, }, "_embedded": { "secrets": [ { "_links": { "self": { - "href": "abc123" - } + "href": "abc123", + }, }, "id": "ad6dc56f-07b5-46e1-a527-85530e625800", - "created_at": "2017-03-02T16:34:49Z" - } - ] - } + "created_at": "2017-03-02T16:34:49Z", + }, + ], + }, }; - nock("https://api.nexmo.com", {reqheaders: {'Authorization': 'Basic YWJjZDoxMjM0'} }) + nock("https://api.nexmo.com", { reqheaders: { 'Authorization': 'Basic YWJjZDoxMjM0' } }) .persist() .get('/accounts/abcd/secrets') .reply(200, expectedResponse); @@ -49,16 +49,16 @@ describe('secrets', () => { const expectedResponse = { "_links": { "self": { - "href": "abc123" - } + "href": "abc123", + }, }, "id": "ad6dc56f-07b5-46e1-a527-85530e625800", - "created_at": "2017-03-02T16:34:49Z" + "created_at": "2017-03-02T16:34:49Z", }; - nock("https://api.nexmo.com", {reqheaders: {'Authorization': 'Basic YWJjZDoxMjM0'} }) + nock("https://api.nexmo.com", { reqheaders: { 'Authorization': 'Basic YWJjZDoxMjM0' } }) .persist() - .post('/accounts/abcd/secrets', {secret: 'te5ts3cret!'}) + .post('/accounts/abcd/secrets', { secret: 'te5ts3cret!' }) .reply(200, expectedResponse); const lookup = await client.createSecret('abcd', 'te5ts3cret!'); @@ -71,30 +71,34 @@ describe('secrets', () => { const expectedResponse = { "_links": { "self": { - "href": "abc123" - } + "href": "abc123", + }, }, "id": "ad6dc56f-07b5-46e1-a527-85530e625800", - "created_at": "2017-03-02T16:34:49Z" + "created_at": "2017-03-02T16:34:49Z", }; - nock("https://api.nexmo.com", {reqheaders: {'Authorization': 'Basic YWJjZDoxMjM0'} }) + nock("https://api.nexmo.com", { reqheaders: { 'Authorization': 'Basic YWJjZDoxMjM0' } }) .persist() .get('/accounts/abcd/secrets/ad6dc56f-07b5-46e1-a527-85530e625800') .reply(200, expectedResponse); - const lookup = await client.getSecret('abcd', 'ad6dc56f-07b5-46e1-a527-85530e625800'); + const lookup = await client.getSecret( + 'abcd', + 'ad6dc56f-07b5-46e1-a527-85530e625800', + ); expect(lookup._links).toEqual(expectedResponse._links); expect(lookup.id).toEqual(expectedResponse.id); expect(lookup.created_at).toEqual(expectedResponse.created_at); }); - test("get a secret", async () => { - nock("https://api.nexmo.com", {reqheaders: {'Authorization': 'Basic YWJjZDoxMjM0'} }) + test("delete a secret", async () => { + nock("https://api.nexmo.com", { reqheaders: { 'Authorization': 'Basic YWJjZDoxMjM0' } }) .persist() .delete('/accounts/abcd/secrets/ad6dc56f-07b5-46e1-a527-85530e625800') .reply(204); await client.deleteSecret('abcd', 'ad6dc56f-07b5-46e1-a527-85530e625800'); + expect(nock.isDone()).toBeTruthy(); }); }); diff --git a/packages/accounts/lib/accounts.ts b/packages/accounts/lib/accounts.ts index fcb3ea78..a3b5f36d 100644 --- a/packages/accounts/lib/accounts.ts +++ b/packages/accounts/lib/accounts.ts @@ -1,35 +1,121 @@ -import { AuthenticationType, Client } from '@vonage/server-client' -import { AccountCallbacks } from './interfaces/AccountCallbacks' -import { AccountUpdateResponse } from './interfaces/Response/AccountUpdateResponse' -import { GetBalanceResponse } from './interfaces/Response/GetBalanceResponse' -import { TopUpBalanceResponse } from './interfaces/Response/TopUpBalanceResponse' +import { AuthenticationType, Client } from '@vonage/server-client'; +import { + AccountCallbacks, + AccountUpdateResponse, + GetBalanceResponse, + TopUpBalanceResponse, +} from './types'; +/** + * Client class to interact with the Account API which enables users to manage + * their Vonage API Account programmatically. + * @see {@link https://developer.nexmo.com/en/account/overview} + * + * @example + * Create a standalone Account client + * + * ```ts + * import { Accounts } from '@vonage/account'; + * + * const accountClient = new Accounts({ + * apiKey: VONAGE_API_KEY, + * apiSecret: VONAGE_API_SECRET + * }); + * ``` + * + * @example + * Create an Account client from the Vonage client + * + * ```ts + * import { Vonage } from '@vonage/server-client'; + * + * const vonage = new Vonage({ + * apiKey: VONAGE_API_KEY, + * apiSecret: VONAGE_API_SECRET + * }); + * + * const accountClient = vonage.account; + * ``` + */ export class Accounts extends Client { - protected authType = AuthenticationType.QUERY_KEY_SECRET + /** + * @see {@link Client.authType} + */ + protected authType = AuthenticationType.QUERY_KEY_SECRET; - public async getBalance(): Promise { - const response = await this.sendGetRequest( - `${this.config.restHost}/account/get-balance` - ) - return response.data - } + /** + * Retrieves the current balance of the Vonage API account. + * @see {@link https://rest.nexmo.com/account/get-balance} + * @return {Promise} The current balance of the account in EUR. + * + * @example + * + * const balance = await accontClient.getBalance(); + * + * console.log(`The current account balance is ${balance.value} ${balance.currency}`); + * console.log(`Auto-reload is ${balance.autoReload ? 'enabled' : 'disabled'}`); + */ + public async getBalance(): Promise { + const response = await this.sendGetRequest( + `${this.config.restHost}/account/get-balance`, + ); + return response.data; + } - public async topUpBalance(trx: string): Promise { - const response = await this.sendFormSubmitRequest( - `${this.config.restHost}/account/top-up`, - { trx } - ) - return response.data - } + /** + * Tops up the account balance when auto-reload is enabled. + * The top-up amount corresponds to the amount added when auto-reload was enabled. + * @see {@link https://rest.nexmo.com/account/top-up} + * @param {string} trx - The transaction reference for the balance addition and auto-reload activation. + * @return {Promise} Response indicating the success of the operation. + * + * @example + * + * const response = await accountClient.topUpBalance('00X123456Y7890123Z'); + * + * if (response['error-code'] === '200') { + * console.log(`The account balance has been topped up`); + * } else { + * console.log(`The account balance could not be topped up`); + * } + * + */ + public async topUpBalance(trx: string): Promise { + const response = await this.sendFormSubmitRequest( + `${this.config.restHost}/account/top-up`, + { trx }, + ); + return response.data; + } - public async updateAccountCallbacks( - callbacks: AccountCallbacks - ): Promise { - const response = - await this.sendFormSubmitRequest( - `${this.config.restHost}/account/settings`, - callbacks - ) - return response.data - } + /** + * Updates the default webhook URLs associated with the account for: + * - Inbound SMS messages + * - Delivery receipts + * @see {@link https://rest.nexmo.com/account/settings} + * @param {AccountCallbacks} callbacks - The new callback URLs for the account. + * @return {Promise} Details of the updated or current settings. + * + * @example + * + * const callbacks = { + * moCallBackUrl: 'https://example.com/webhooks/inbound-sms', + * drCallBackUrl: 'https://example.com/webhooks/delivery-receipts', + * }; + * + * const response = await accountClient.updateAccountCallbacks(callbacks); + * + * for (const [key, value] of Object.entries(response)) { + * console.log(`New ${key}: ${value}`); + * } + */ + public async updateAccountCallbacks( + callbacks: AccountCallbacks, + ): Promise { + const response = await this.sendFormSubmitRequest( + `${this.config.restHost}/account/settings`, + callbacks as Record, + ); + return response.data; + } } diff --git a/packages/accounts/lib/index.ts b/packages/accounts/lib/index.ts index 6665af00..a338f08d 100644 --- a/packages/accounts/lib/index.ts +++ b/packages/accounts/lib/index.ts @@ -1,2 +1,3 @@ -export { Accounts } from './accounts' -export { Secrets } from './secrets' +export { Accounts } from './accounts'; +export { Secrets } from './secrets'; +export * from './types'; diff --git a/packages/accounts/lib/interfaces/AccountCallbacks.ts b/packages/accounts/lib/interfaces/AccountCallbacks.ts deleted file mode 100644 index 54d1a848..00000000 --- a/packages/accounts/lib/interfaces/AccountCallbacks.ts +++ /dev/null @@ -1,4 +0,0 @@ -export interface AccountCallbacks { - moCallBackUrl?: string - drCallBackUrl?: string -} diff --git a/packages/accounts/lib/interfaces/Response/APISecretResponse.ts b/packages/accounts/lib/interfaces/Response/APISecretResponse.ts deleted file mode 100644 index 92c546f8..00000000 --- a/packages/accounts/lib/interfaces/Response/APISecretResponse.ts +++ /dev/null @@ -1,9 +0,0 @@ -export interface APISecretResponse { - _links: { - self: { - href: string - } - } - id: string - created_at: string -} diff --git a/packages/accounts/lib/interfaces/Response/AccountUpdateResponse.ts b/packages/accounts/lib/interfaces/Response/AccountUpdateResponse.ts deleted file mode 100644 index e287c0d4..00000000 --- a/packages/accounts/lib/interfaces/Response/AccountUpdateResponse.ts +++ /dev/null @@ -1,7 +0,0 @@ -export interface AccountUpdateResponse { - 'mo-callback-url': string - 'dr-callback-url': string - 'max-outbound-request': number - 'max-inbound-request': number - 'max-calls-per-second': number -} diff --git a/packages/accounts/lib/interfaces/Response/GetBalanceResponse.ts b/packages/accounts/lib/interfaces/Response/GetBalanceResponse.ts deleted file mode 100644 index f49f8740..00000000 --- a/packages/accounts/lib/interfaces/Response/GetBalanceResponse.ts +++ /dev/null @@ -1,4 +0,0 @@ -export interface GetBalanceResponse { - value: number - autoReload: boolean -} diff --git a/packages/accounts/lib/interfaces/Response/ListAPISecretsResponse.ts b/packages/accounts/lib/interfaces/Response/ListAPISecretsResponse.ts deleted file mode 100644 index af109b0d..00000000 --- a/packages/accounts/lib/interfaces/Response/ListAPISecretsResponse.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { APISecretResponse } from './APISecretResponse' - -export interface ListAPISecretsResponse { - _links: { - self: { - href: string - } - } - _embedded: { - secrets: APISecretResponse[] - } -} diff --git a/packages/accounts/lib/interfaces/Response/TopUpBalanceResponse.ts b/packages/accounts/lib/interfaces/Response/TopUpBalanceResponse.ts deleted file mode 100644 index 5617626d..00000000 --- a/packages/accounts/lib/interfaces/Response/TopUpBalanceResponse.ts +++ /dev/null @@ -1,4 +0,0 @@ -export interface TopUpBalanceResponse { - 'error-code': string - 'error-code-label': string -} diff --git a/packages/accounts/lib/secrets.ts b/packages/accounts/lib/secrets.ts index 9e9463b6..830ecf71 100644 --- a/packages/accounts/lib/secrets.ts +++ b/packages/accounts/lib/secrets.ts @@ -1,41 +1,118 @@ -import { AuthenticationType, Client } from '@vonage/server-client' -import { APISecretResponse } from './interfaces/Response/APISecretResponse' -import { ListAPISecretsResponse } from './interfaces/Response/ListAPISecretsResponse' +import { AuthenticationType, Client } from '@vonage/server-client'; +import { APISecretResponse, ListAPISecretsResponse } from './types'; +/** + * Client class to interact with the Account API to create secrets in + * their Vonage API Account programmatically. + * + * @remarks + * This client is only available as a standalone client. It cannot be + * instantiated from the server-sdk package. + * + * @example + * Create a standalone Secret client + * + * ```ts + * import { Secrets } from '@vonage/account'; + * + * const secretClient = new Secrets({ + * apiKey: VONAGE_API_KEY, + * apiSecret: VONAGE_API_SECRET + * }); + * ``` + * + */ export class Secrets extends Client { - protected authType = AuthenticationType.BASIC + protected authType = AuthenticationType.BASIC; - public async createSecret( - apiKey: string, - secret: string - ): Promise { - const response = await this.sendPostRequest( - `${this.config.apiHost}/accounts/${apiKey}/secrets`, - { secret } - ) - return response.data - } + /** + * Create a new API secret for a given API key. + * + * @param {string} apiKey - The API key to manage secrets for. + * @param {string} secret - The new secret. It must follow the provided rules: + * - Minimum 8 characters. + * - Maximum 25 characters. + * - At least 1 lowercase character. + * - At least 1 uppercase character. + * - At least 1 digit. + * + * @return {Promise} A promise that resolves to an object representing the created API secret. + * + * @example + * const { id } = await secretClient.createSecret( + * 'new-api-key', + * 'SuperSecret123!' + * ); + * + * console.log(`Created secret with ID ${id}`); + */ + public async createSecret( + apiKey: string, + secret: string, + ): Promise { + const response = await this.sendPostRequest( + `${this.config.apiHost}/accounts/${apiKey}/secrets`, + { secret }, + ); + return response.data; + } - public async deleteSecret(apiKey: string, id: string): Promise { - await this.sendDeleteRequest( - `${this.config.apiHost}/accounts/${apiKey}/secrets/${id}` - ) - } + /** + * Revoke (delete) an existing API secret for a given API key. + * + * @param {string} apiKey - The API key to manage secrets for. + * @param {string} id - The ID of the API secret to revoke. + * @return {Promise} A promise that resolves when the secret has been revoked. + * + * @example + * await secretClient.deleteSecret('my-api-key', 'my-secret-id'); + */ + public async deleteSecret(apiKey: string, id: string): Promise { + await this.sendDeleteRequest( + `${this.config.apiHost}/accounts/${apiKey}/secrets/${id}`, + ); + } - public async getSecret( - apiKey: string, - id: string - ): Promise { - const response = await this.sendGetRequest( - `${this.config.apiHost}/accounts/${apiKey}/secrets/${id}` - ) - return response.data - } + /** + * Retrieve the details of a specific API secret for a given API key. + * + * @param {string} apiKey - The API key to manage secrets for. + * @param {string} id - The ID of the API secret to retrieve. + * @return {Promise} A promise that resolves to an object representing the API secret. + * + * @example + * const { id } = await secretClient.getSecret('my-api-key', 'my-secret-id'); + * console.log(`Secret with ID ${id} has been retrieved`); + * + */ + public async getSecret( + apiKey: string, + id: string, + ): Promise { + const response = await this.sendGetRequest( + `${this.config.apiHost}/accounts/${apiKey}/secrets/${id}`, + ); + return response.data; + } - public async listSecrets(apiKey: string): Promise { - const response = await this.sendGetRequest( - `${this.config.apiHost}/accounts/${apiKey}/secrets` - ) - return response.data - } + /** + * List all the secrets associated with a particular API key. + * + * @param {string} apiKey - The API key for which to list secrets. + * + * @return {Promise} A promise that resolves to an object containing a list of API secrets. + * + * @example + * const response = await secretClient.listSecrets('my-api-key'); + * + * for (const secret of response._embedded.secrets) { + * console.log(`Secret with ID ${secret.id} has been retrieved`); + * } + */ + public async listSecrets(apiKey: string): Promise { + const response = await this.sendGetRequest( + `${this.config.apiHost}/accounts/${apiKey}/secrets`, + ); + return response.data; + } } diff --git a/packages/accounts/lib/types/AccountCallbacks.ts b/packages/accounts/lib/types/AccountCallbacks.ts new file mode 100644 index 00000000..72f25fc7 --- /dev/null +++ b/packages/accounts/lib/types/AccountCallbacks.ts @@ -0,0 +1,23 @@ +/** + * Represents the callbacks associated with an account. + */ +export type AccountCallbacks = { + /** + * The default webhook URL for inbound SMS. If an SMS is received at a Vonage + * number that does not have its own inboud SMS webhook configured, Vonage + * makes a request here. + * + * @remarks + * Send an empty string to unset this value. + */ + moCallBackUrl?: string; + + /** + * The webhook URL that Vonage makes a request to when a + * delivery receipt is available for an SMS sent by one of your Vonage numbers. + * + * @remarks + * Send an empty string to unset this value. + */ + drCallBackUrl?: string; +}; diff --git a/packages/accounts/lib/types/Response/APISecretResponse.ts b/packages/accounts/lib/types/Response/APISecretResponse.ts new file mode 100644 index 00000000..c7951f87 --- /dev/null +++ b/packages/accounts/lib/types/Response/APISecretResponse.ts @@ -0,0 +1,23 @@ +import { APILinks } from '@vonage/server-client'; + +/** + * Represents the response structure for an individual API secret. + * + * @remarks + * Many of the Vonage APIs are accessed using an API key and secret. It is recommended to manage + * and occasionally rotate these secrets for security purposes. This structure provides details + * for a single API secret. + * + * @see {@link APILinks} + */ +export type APISecretResponse = APILinks & { + /** + * The unique identifier for the API secret. + */ + id: string; + + /** + * The timestamp indicating when the API secret was created. + */ + created_at: string; +} diff --git a/packages/accounts/lib/types/Response/AccountUpdateResponse.ts b/packages/accounts/lib/types/Response/AccountUpdateResponse.ts new file mode 100644 index 00000000..58718cc0 --- /dev/null +++ b/packages/accounts/lib/types/Response/AccountUpdateResponse.ts @@ -0,0 +1,32 @@ +/** + * Represents the response structure when updating account settings. + * + * @remarks + * Settings were updated if supplied; the details of the current settings are included in the response. + */ +export type AccountUpdateResponse = { + /** + * The current or updated inbound message webhook URI. + */ + 'mo-callback-url': string; + + /** + * The current or updated delivery receipt webhook URI. + */ + 'dr-callback-url': string; + + /** + * The maximum number of outbound messages per second. + */ + 'max-outbound-request': number; + + /** + * The maximum number of inbound messages per second. + */ + 'max-inbound-request': number; + + /** + * The maximum number of API calls per second. + */ + 'max-calls-per-second': number; +}; diff --git a/packages/accounts/lib/types/Response/GetBalanceResponse.ts b/packages/accounts/lib/types/Response/GetBalanceResponse.ts new file mode 100644 index 00000000..81ba7e8a --- /dev/null +++ b/packages/accounts/lib/types/Response/GetBalanceResponse.ts @@ -0,0 +1,14 @@ +/** + * Represents the response structure when querying for account balance. + */ +export type GetBalanceResponse = { + /** + * The current balance value. + */ + value: number; + + /** + * Indicates if the auto-reload feature is enabled. + */ + autoReload: boolean; +} diff --git a/packages/accounts/lib/types/Response/ListAPISecretsResponse.ts b/packages/accounts/lib/types/Response/ListAPISecretsResponse.ts new file mode 100644 index 00000000..8e35eed8 --- /dev/null +++ b/packages/accounts/lib/types/Response/ListAPISecretsResponse.ts @@ -0,0 +1,28 @@ +import { APISecretResponse } from './APISecretResponse'; +import { APILinks } from '@vonage/server-client'; + +/** + * Represents the response structure when listing API secrets. + * + * @remarks + * + * Many of the Vonage APIs are accessed using an API key and secret. It is recommended that you + * change or "rotate" your secrets from time to time for security purposes. This section provides + * the API interface for achieving this. Note: to work on secrets for your secondary accounts, + * you may authenticate with your primary credentials and supply the secondary API keys as URL + * parameters to these API endpoints. + * + */ +export type ListAPISecretsResponse = APILinks & { + /** + * Contains the embedded secrets information. + */ + _embedded: { + + /** + * An array of API secrets. + * @see {@link APISecretResponse} + */ + secrets: APISecretResponse[]; + }; +} diff --git a/packages/accounts/lib/types/Response/TopUpBalanceResponse.ts b/packages/accounts/lib/types/Response/TopUpBalanceResponse.ts new file mode 100644 index 00000000..b49b1e6f --- /dev/null +++ b/packages/accounts/lib/types/Response/TopUpBalanceResponse.ts @@ -0,0 +1,22 @@ +/** + * Represents the response structure when performing a top-up operation for account balance. + * + * @remarks + * You can top up your account using this API when you have enabled auto-reload in the dashboard. + * The amount added by the top-up operation will be the same amount as was added in the payment when + * auto-reload was enabled. Your account balance is checked every 5-10 minutes and if it falls below + * the threshold and auto-reload is enabled, then it will be topped up automatically. Use this endpoint + * if you need to top up at times when your credit may be exhausted more quickly than the auto-reload + * may occur. + */ +export type TopUpBalanceResponse = { + /** + * The code associated with any potential errors during the top-up process. + */ + 'error-code': string; + + /** + * A descriptive label for the error code. + */ + 'error-code-label': string; +} diff --git a/packages/accounts/lib/types/Response/index.ts b/packages/accounts/lib/types/Response/index.ts new file mode 100644 index 00000000..026af431 --- /dev/null +++ b/packages/accounts/lib/types/Response/index.ts @@ -0,0 +1,5 @@ +export * from './APISecretResponse'; +export * from './AccountUpdateResponse'; +export * from './GetBalanceResponse'; +export * from './ListAPISecretsResponse'; +export * from './TopUpBalanceResponse'; diff --git a/packages/accounts/lib/types/index.ts b/packages/accounts/lib/types/index.ts new file mode 100644 index 00000000..b42a04ad --- /dev/null +++ b/packages/accounts/lib/types/index.ts @@ -0,0 +1,2 @@ +export * from './AccountCallbacks'; +export * from './Response'; diff --git a/packages/accounts/package.json b/packages/accounts/package.json index 4e5d63da..9bfe740d 100644 --- a/packages/accounts/package.json +++ b/packages/accounts/package.json @@ -1,4 +1,5 @@ { + "$schema": "https://json.schemastore.org/package.json", "name": "@vonage/accounts", "version": "1.9.0", "description": "Vonage Account Management API", @@ -11,7 +12,16 @@ "url": "git+https://github.com/Vonage/vonage-node-sdk.git" }, "license": "Apache-2.0", - "author": "Chris Tankersley ", + "contributors": [ + { + "name": "Chris Tankersley", + "url": "https://github.com/dragonmantank" + }, + { + "name": "Chuck \"MANCHUCK\" Reeves", + "url": "https://github.com/manchuck" + } + ], "main": "dist/index.js", "types": "dist/index.d.ts", "directories": { @@ -24,7 +34,8 @@ "scripts": { "build": "npm run clean && npm run compile", "clean": "npx shx rm -rf dist tsconfig.tsbuildinfo", - "compile": "npx tsc --build --verbose" + "compile": "npx tsc --build --verbose", + "prepublishOnly": "npm run build" }, "dependencies": { "@vonage/server-client": "^1.9.0" @@ -35,6 +46,5 @@ }, "publishConfig": { "directory": "dist" - }, - "gitHead": "328f18e5c8a458cb4d06d7955ec2399a6ce6f5d8" + } } diff --git a/packages/accounts/tsconfig.json b/packages/accounts/tsconfig.json index caf8c2ea..cd40b0e3 100644 --- a/packages/accounts/tsconfig.json +++ b/packages/accounts/tsconfig.json @@ -1,23 +1,24 @@ { - "extends": "../../tsconfig.json", + "$schema": "https://json.schemastore.org/tsconfig", - "compilerOptions": { - "rootDir": "lib", - "outDir": "dist" - }, + "extends": "../../tsconfig.json", - "exclude": [ - "__tests__", - "jest.config.js", - "dist" - ], + "compilerOptions": { + "rootDir": "lib", + "outDir": "dist" + }, - "references": [ - { "path": "../server-client" }, - { "path": "../auth" } - ], + "exclude": [ + "__tests__", + "dist" + ], - "ts-node": { - "esm": true - } + "references": [ + { "path": "../server-client" }, + { "path": "../auth" } + ], + + "ts-node": { + "esm": true + } } diff --git a/packages/accounts/typedoc.json b/packages/accounts/typedoc.json new file mode 100644 index 00000000..c218c2fa --- /dev/null +++ b/packages/accounts/typedoc.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "extends": ["../../typedoc.base.json"], + "entryPoints": ["lib/index.ts"], + "name": "Vonage Accounts" +} diff --git a/packages/applications/__tests__/__dataSets__/list.ts b/packages/applications/__tests__/__dataSets__/list.ts index 1b344e6f..de6cd884 100644 --- a/packages/applications/__tests__/__dataSets__/list.ts +++ b/packages/applications/__tests__/__dataSets__/list.ts @@ -2,7 +2,6 @@ import { Client } from '@vonage/server-client'; import { ApplicationResponse, Application, - ApplicationPageList, ApplicationPageResponse, } from '../../lib'; @@ -11,7 +10,6 @@ import { testApplication, testApplicationOne, testApplicationTwo, - capabilitiesToTest, } from '../common'; const appToApi = (application: Application): ApplicationResponse => ({ @@ -68,12 +66,12 @@ export default [ Client.transformers.snakeCaseObjectKeys( testApplicationOne, true, - true, + true ), Client.transformers.snakeCaseObjectKeys( testApplicationTwo, true, - true, + true ), ], }, diff --git a/packages/applications/lib/applications.ts b/packages/applications/lib/applications.ts index f59910b0..64e3b6f1 100644 --- a/packages/applications/lib/applications.ts +++ b/packages/applications/lib/applications.ts @@ -7,35 +7,147 @@ import { ApplicationPageList, } from './types'; -const apiToApplication = (response: ApplicationResponse) => { - delete response?._links; - return Client.transformers.camelCaseObjectKeys(response, true, true); +/** + * Represents the application with both the `snake_case` and the `camelCase` keys. + * + * @remarks + * This is used for backward compatibility with an earlier release of the SDK + * which was not transforming the application correctly. + * Using `snake_case` is considered deprecated + * + * @example + * Create a standalone Application client + * + * ```ts + * import { Applications } from '@vonage/application'; + * + * const applicationClient = new Applications({ + * apiKey: VONAGE_API_KEY, + * apiSecret: VONAGE_API_SECRET + * }); + * ``` + * + * @example + * Create an Application client from the Vonage client + * + * ```ts + * import { Vonage } from '@vonage/server-client'; + * + * const vonage = new Vonage({ + * apiKey: VONAGE_API_KEY, + * apiSecret: VONAGE_API_SECRET + * }); + * + * const applicationClient = vonage.application + * ``` + */ +export type MergedApplication = Application | ApplicationResponse; + +const apiToApplication = ( + response: MergedApplication, +): MergedApplication => { + delete (response as ApplicationResponse)._links; + return Client.transformers.camelCaseObjectKeys( + response, + true, + true, + ) as MergedApplication; }; export class Applications extends Client { - protected authType = AuthenticationType.BASIC; + authType = AuthenticationType.BASIC; - public async listApplications(filter: { - page_size?: number; - page?: number; - }): Promise { - return this.getApplicationPage(filter); + /** + * Retrieves a list of applications with optional pagination parameters. + * + * @remarks + * This is used to get a specific page of applications. This will + * return the `snake_case` and the `camelCase` response. Using `snake_case` + * is considered deprecated + * + * @see API Specification {@link https://developer.vonage.com/en/api/application.v2#listApplication} + * + * @param {ListApplicationParams} params - The filter parameters. + * @return {Promise} - A promise resolving to the list of applications. + * + * @example + * List a single page of applications + * + * ```ts + * const applications = await applicationClient.listApplications({}); + * + * applications.applications.forEach(application => { + * console.log(application.name); + * }); + * ``` + */ + public async listApplications( + params: ListApplicationParams, + ): Promise { + return this.getApplicationPage(params); } + /** + * Retrieves all applications, iterating over paginated results. + * + * @remarks + * This will keep calling the API until there are no pages left. This will + * return the `snake_case` and the `camelCase` response. Using `snake_case` + * is considered deprecated + * + * @param {ListApplicationParams} [params={}] - Optional filter parameters. + * @yields {MergedApplication} - Yields application items. + * @return {AsyncGenerator} - An asynchronous generator. + * + * @example + * List applications with pagination using an iterator + * + * ```ts + * for await (const application of applicationClient.listAllApplications()) { + * console.log(application.name); + * } + * ``` + */ public async *listAllApplications( params: ListApplicationParams = {}, - ): AsyncGenerator { + ): AsyncGenerator { let next = null; params.page = params?.page || 1; do { const resp = await this.getApplicationPage(params); - yield* resp._embedded?.applications; + yield* resp._embedded?.applications || []; next = resp._links?.next; params.page++; } while (next); } + /** + * Retrieves a page of applications based on filter parameters. + * + * @param {ListApplicationParams} filter - The filter parameters for pagination. + * @return {Promise} - A promise resolving to a page of applications. + * + * @remarks + * This will return the `snake_case` and the `camelCase` response. Using + * `snake_case` is considered deprecated + * + * @see API Specification {@link https://developer.vonage.com/en/api/application.v2#listApplication} + * + * @example + * Get a single page of applications + * + * ```ts + * const applications = await applicationClient.getApplicationPage({ + * page: 1, + * size: 10 + * }); + * + * applications.applications.forEach(application => { + * console.log(application.name); + * }); + * ``` + */ public async getApplicationPage( filter: ListApplicationParams, ): Promise { @@ -57,9 +169,42 @@ export class Applications extends Client { }; } + /** + * Creates a new application with the provided details. + * + * @see API Specification {@link https://developer.vonage.com/en/api/application.v2#createApplication} + * + * @param {Application} application - The application details to be created. + * @return {Promise} - A promise resolving to the created application. + * + * @example + * Create a new application + * + * ```ts + * const application = await applicationClient.createApplication({ + * name: 'My Application', + * capabilities: { + * voice: { + * webhooks: { + * answerUrl: { + * address: 'https://example.com/answer', + * httpMethod: 'GET' + * }, + * eventUrl: { + * address: 'https://example.com/event', + * httpMethod: 'POST' + * } + * } + * } + * } + * }); + * + * console.log(application.id); + * ``` + */ public async createApplication( application: Application, - ): Promise { + ): Promise { const resp = await this.sendPostRequest( `${this.config.apiHost}/v2/applications`, Client.transformers.snakeCaseObjectKeys(application, true), @@ -68,7 +213,25 @@ export class Applications extends Client { return apiToApplication(resp.data); } - public async getApplication(applicationId: string): Promise { + /** + * Retrieves an application by its unique identifier. + * + * @see API Specification {@link https://developer.vonage.com/en/api/application.v2#getApplication} + * + * @param {string} applicationId - The unique identifier of the application to retrieve. + * @return {Promise} - A promise resolving to the retrieved application. + * + * @example + * Retrieve an application + * + * ```ts + * const application = await applicationClient.getApplication(APPLICATION_ID); + * console.log(application.name); + * ``` + */ + public async getApplication( + applicationId: string, + ): Promise { const resp = await this.sendGetRequest( `${this.config.apiHost}/v2/applications/${applicationId}`, ); @@ -76,9 +239,28 @@ export class Applications extends Client { return apiToApplication(resp.data); } + /** + * Updates an existing application with the provided details. + * + * @see API Specification {@link https://developer.vonage.com/en/api/application.v2#updateApplication} + * + * @param {Application} application - The application details to be updated. + * @return {Promise} - A promise resolving to the updated application. + * + * @example + * Update an application + * + * ```ts + * const application = await applicationClient.updateApplication({ + * id: APPLICATION_ID, + * name: 'My Application', + * }); + * console.log(application.name); + * ``` + */ public async updateApplication( application: Application, - ): Promise { + ): Promise { const resp = await this.sendPutRequest( `${this.config.apiHost}/v2/applications/${application.id}`, Client.transformers.snakeCaseObjectKeys(application, true), @@ -86,6 +268,21 @@ export class Applications extends Client { return apiToApplication(resp.data); } + /** + * Deletes an application by its unique identifier. + * + * @see API Specification {@link https://developer.vonage.com/en/api/application.v2#deleteApplication} + * + * @param {string} applicationId - The unique identifier of the application to delete. + * @return {Promise} - A promise indicating the successful deletion of the application. + * + * @example + * Delete an application + * + * ```ts + * await applicationClient.deleteApplication(APPLICATION_ID); + * ``` + */ public async deleteApplication(applicationId: string): Promise { await this.sendDeleteRequest( `${this.config.apiHost}/v2/applications/${applicationId}`, diff --git a/packages/applications/lib/enums/VoiceRegions.ts b/packages/applications/lib/enums/VoiceRegions.ts index fede038b..2778aaac 100644 --- a/packages/applications/lib/enums/VoiceRegions.ts +++ b/packages/applications/lib/enums/VoiceRegions.ts @@ -1,8 +1,39 @@ +/** + * Enumeration representing different voice regions. + * + * @remarks + * Selecting a region means all inbound, programmable SIP and SIP connect calls + * will be sent to the selected region unless the call is sent to a regional endpoint. + * If the call is using a regional endpoint this will override the application setting. + */ export enum VoiceRegions { + /** + * @description North America - East region + */ NA_EAST = 'na-east', + + /** + * @description North America - West region + */ NA_WEST = 'na-west', + + /** + * @description Europe - West region + */ EU_WEST = 'eu-west', + + /** + * @description Europe - East region + */ EU_EAST = 'eu-east', + + /** + * @description Asia-Pacific - Singapore region + */ APAC_SNG = 'apac-sng', + + /** + * @description Asia-Pacific - Australia region + */ APAC_AUSTRALIA = 'apac-australia', } diff --git a/packages/applications/lib/index.ts b/packages/applications/lib/index.ts index 843d9bc2..403e268f 100644 --- a/packages/applications/lib/index.ts +++ b/packages/applications/lib/index.ts @@ -1,3 +1,16 @@ +/** + * A library to allow management of your Vonage Applications. + * + * @remarks + * A Vonage API application contains the security and configuration information + * you need to connect to Vonage endpoints and use the Vonage APIs. Each Vonage + * application created can support multiple capabilities - for example you can + * create an Application that supports using the Voice, Messages and RTC APIs. + * + * @link https://developer.vonage.com/en/application/overview + * + * @packageDocumentation + */ export * from './types'; export * from './enums'; -export { Applications } from './applications'; +export * from './applications'; diff --git a/packages/applications/lib/interfaces/Application.ts b/packages/applications/lib/interfaces/Application.ts deleted file mode 100644 index 9427f308..00000000 --- a/packages/applications/lib/interfaces/Application.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { Application as ApplicationType } from '../types'; - -/** - * @deprecated Please use the type instead - */ -export type Application = ApplicationType; diff --git a/packages/applications/lib/interfaces/ApplicationResponse.ts b/packages/applications/lib/interfaces/ApplicationResponse.ts deleted file mode 100644 index 46854c34..00000000 --- a/packages/applications/lib/interfaces/ApplicationResponse.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { VetchResponse } from '@vonage/vetch'; - -/** - * @deprecated.Please use the type instead - */ -export type ApplicationResponse = VetchResponse; diff --git a/packages/applications/lib/interfaces/MessagesCapabilities.ts b/packages/applications/lib/interfaces/MessagesCapabilities.ts deleted file mode 100644 index 08f63730..00000000 --- a/packages/applications/lib/interfaces/MessagesCapabilities.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { CapabilityMessages } from '../types'; - -/** - * @deprecated Please use CapabilityMessages instead - */ -export type MessagesCapabilities = CapabilityMessages; diff --git a/packages/applications/lib/interfaces/RTCCapabilities.ts b/packages/applications/lib/interfaces/RTCCapabilities.ts deleted file mode 100644 index 1145de15..00000000 --- a/packages/applications/lib/interfaces/RTCCapabilities.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { CapabilityRTC } from '../types'; - -/** - * @deprecated Please use CapabilityRTC instead - */ -export type RTCCapabilities = CapabilityRTC; diff --git a/packages/applications/lib/interfaces/Response/ListApplicationResponse.ts b/packages/applications/lib/interfaces/Response/ListApplicationResponse.ts deleted file mode 100644 index 01ad07f4..00000000 --- a/packages/applications/lib/interfaces/Response/ListApplicationResponse.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { ApplicationPageResponse } from '../../types'; - -/** - * @deprecated please use ApplicationPageResponse - */ -export type ListApplicationResponse = ApplicationPageResponse; diff --git a/packages/applications/lib/interfaces/VoiceCapabilities.ts b/packages/applications/lib/interfaces/VoiceCapabilities.ts deleted file mode 100644 index 226f1a1f..00000000 --- a/packages/applications/lib/interfaces/VoiceCapabilities.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { CapabilityVoice } from '../types'; - -/** - * @deprecated please use CapabilityVoice instead - */ -export type VoiceCapabilities = CapabilityVoice; diff --git a/packages/applications/lib/types/Application.ts b/packages/applications/lib/types/Application.ts index 411230f7..55975e8d 100644 --- a/packages/applications/lib/types/Application.ts +++ b/packages/applications/lib/types/Application.ts @@ -5,23 +5,90 @@ import { CapabilityRTC } from './CapabilityRTC'; import { CapabilityVerify } from './CapabilityVerify'; import { CapabilityVoice } from './CapabilityVoice'; +/** + * Represents an application configuration. + */ export type Application = { + /** + * The application's unique ID. + */ id?: string; + + /** + * Friendly identifier for the application. + * + * @remarks + * This is not unique. + */ name: string; + /** + * Represents the keys associated with an application. + * + + */ keys?: { + /** + * The public key for the application. + * + * @remarks + * You can find this value in your Vonage developer dashboard [https://dashboard.nexmo.com/applications] + * + */ publicKey?: string; - privateKey?: string; }; + + /** + * Represents the privacy configuration for an application + */ privacy?: { + /** + * Share content + * + * @remarks + * If set to true, Vonage may store and use your content and data for the + * improvement of Vonage's AI-based services and technologies. + */ improveAi: boolean; }; + + /** + * Represents the capabilities configuration for an application. + */ capabilities: { + /** + * Bulk related configuration. + */ bulk?: CapabilityBulk; + + /** + * Meetings related configuration. + */ meetings?: CapabilityMeetings; + + /** + * Messages/Dispatch related configuration. + */ messages?: CapabilityMessages; + + /** + * RTC/Conversation Service related configuration. + */ rtc?: CapabilityRTC; + + /** + * Specify the vbc capability to enable zero-rated calls for VBC number + * programmability service applications. This is always an empty object. + */ vbc?: unknown; + + /** + * Verify related configuration. + */ verify?: CapabilityVerify; + + /** + * Voice related configuration. + */ voice?: CapabilityVoice; }; }; diff --git a/packages/applications/lib/types/ApplicationClassParameters.ts b/packages/applications/lib/types/ApplicationClassParameters.ts deleted file mode 100644 index c2825ebc..00000000 --- a/packages/applications/lib/types/ApplicationClassParameters.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { AuthOpts } from '@vonage/auth'; -import { AuthInterface } from '@vonage/auth'; -import { VetchOptions } from '@vonage/vetch'; - -/** - * @deprecated - */ -export type ApplicationClassParameters = AuthOpts & - VetchOptions & { - auth?: AuthInterface; - }; diff --git a/packages/applications/lib/types/ApplicationPageList.ts b/packages/applications/lib/types/ApplicationPageList.ts index f36adcf3..c1d69297 100644 --- a/packages/applications/lib/types/ApplicationPageList.ts +++ b/packages/applications/lib/types/ApplicationPageList.ts @@ -1,7 +1,21 @@ import { ApplicationPageResponse } from './Response'; +/** + * Represents a paginated list of applications. + */ export type ApplicationPageList = { + /** + * The total number of applications. + */ totalItems: number; + + /** + * The total number of pages returned. + */ totalPages: number; + + /** + * The number of applications per page. + */ pageSize: number; } & ApplicationPageResponse; diff --git a/packages/applications/lib/types/CapabilityBulk.ts b/packages/applications/lib/types/CapabilityBulk.ts index d15b84d4..aaf9e87a 100644 --- a/packages/applications/lib/types/CapabilityBulk.ts +++ b/packages/applications/lib/types/CapabilityBulk.ts @@ -1,8 +1,21 @@ import { CapabilityWebhook } from './CapabilityWebhook'; +/** + * Represents a bulk capability configuration containing webhooks. + */ export type CapabilityBulk = { + /** + * Webhook configuration for proactive-connect related events. + */ webhooks: { + /** + * URL for listing status related to bulk operations. + */ listStatusUrl: CapabilityWebhook; + + /** + * URL for running status related to bulk operations. + */ runStatusUrl: CapabilityWebhook; }; }; diff --git a/packages/applications/lib/types/CapabilityMeetings.ts b/packages/applications/lib/types/CapabilityMeetings.ts index e837e591..c7fe4f6a 100644 --- a/packages/applications/lib/types/CapabilityMeetings.ts +++ b/packages/applications/lib/types/CapabilityMeetings.ts @@ -1,9 +1,26 @@ import { CapabilityWebhook } from './CapabilityWebhook'; +/** + * Represents the meetings-related capabilities configuration for an application. + */ export type CapabilityMeetings = { + /** + * Webhook configuration for meetings-related events. + */ webhooks: { + /** + * Webhook for events related to changes in meeting rooms. + */ roomChanged: CapabilityWebhook; + + /** + * Webhook for events related to changes in meeting sessions. + */ sessionChanged: CapabilityWebhook; + + /** + * Webhook for events related to changes in meeting recording. + */ recordingChanged: CapabilityWebhook; }; }; diff --git a/packages/applications/lib/types/CapabilityMessages.ts b/packages/applications/lib/types/CapabilityMessages.ts index dc67b8bd..ed60e398 100644 --- a/packages/applications/lib/types/CapabilityMessages.ts +++ b/packages/applications/lib/types/CapabilityMessages.ts @@ -1,10 +1,31 @@ import { CapabilityWebhook } from './CapabilityWebhook'; +/** + * Represents a configuration for messaging capabilities. + */ export type CapabilityMessages = { + /** + * Webhook configuration for inbound messages. + */ webhooks: { + /** + * URL for handling inbound messages. + */ inboundUrl: CapabilityWebhook; + + /** + * URL for handling message status events. + */ statusUrl: CapabilityWebhook; }; + + /** + * The version of messaging capabilities ('v1' or 'v0.1'). + */ version: 'v1' | 'v0.1'; + + /** + * Whether to authenticate inbound media. + */ authenticateInboundMedia: boolean; }; diff --git a/packages/applications/lib/types/CapabilityRTC.ts b/packages/applications/lib/types/CapabilityRTC.ts index 9380f185..8cda228b 100644 --- a/packages/applications/lib/types/CapabilityRTC.ts +++ b/packages/applications/lib/types/CapabilityRTC.ts @@ -1,9 +1,26 @@ import { CapabilityWebhook } from './CapabilityWebhook'; +/** + * Represents a configuration for RTC (Real-Time Communication) capabilities. + */ export type CapabilityRTC = { + /** + * Webhook configuration for RTC events. + */ webhooks: { + /** + * URL for handling RTC events. + */ eventUrl: CapabilityWebhook; }; + + /** + * Whether to use signed callbacks for RTC. + */ signedCallbacks: boolean; + + /** + * The leg persistence time for RTC in milliseconds. + */ legPersistenceTime: number; }; diff --git a/packages/applications/lib/types/CapabilityVerify.ts b/packages/applications/lib/types/CapabilityVerify.ts index fbb5697b..9debd2db 100644 --- a/packages/applications/lib/types/CapabilityVerify.ts +++ b/packages/applications/lib/types/CapabilityVerify.ts @@ -1,8 +1,21 @@ import { CapabilityWebhook } from './CapabilityWebhook'; +/** + * Represents a configuration for verification capabilities. + */ export type CapabilityVerify = { + /** + * Webhook configuration for verification status events. + */ webhooks: { + /** + * URL for handling verification status events. + */ statusUrl: CapabilityWebhook; }; + + /** + * The version of verification capabilities ('v2'). + */ version: 'v2'; }; diff --git a/packages/applications/lib/types/CapabilityVoice.ts b/packages/applications/lib/types/CapabilityVoice.ts index 4baa170f..27d5f423 100644 --- a/packages/applications/lib/types/CapabilityVoice.ts +++ b/packages/applications/lib/types/CapabilityVoice.ts @@ -1,25 +1,123 @@ import { CapabilityWebhook } from './CapabilityWebhook'; +import { VoiceRegions } from "../enums"; +/** + * Vonage numbers that are linked to Vonage applications will use the answer_url + * to retrieve an NCCO + */ +export type AnswerCallbackUrl = { + /** + * Socket timeout in milliseconds. + */ + socketTimeout?: number; + + /** + * Connection timeout in milliseconds. + */ + connectTimeout?: number; +} & CapabilityWebhook; + +/** + * Vonage numbers that are linked to Vonage applications will use the answer_url + * to retrieve an NCCO, and the event url to send call status information to you + * + * @link https://developer.vonage.com/en/getting-started/concepts/webhooks?lang=voice + */ +export type EventCallbackUrl = { + /** + * Socket timeout in milliseconds. + */ + socketTimeout?: number; + + /** + * Connection timeout in milliseconds. + */ + connectTimeout?: number; +} & CapabilityWebhook; + + +/** + * The fallback answer url can optionally be configured. This is used when + * answer url is offline or returning an HTTP error code. + * + * @link https://developer.vonage.com/en/getting-started/concepts/webhooks?lang=voice + */ +export type FallbackAnswerUrl = { + /** + * Socket timeout in milliseconds. + */ + socketTimeout?: number; + + /** + * Connection timeout in milliseconds. + */ + connectTimeout?: number; +} & CapabilityWebhook; + +/** + * Represents the voice-related capabilities configuration for an application. + * + * @link https://developer.vonage.com/en/getting-started/concepts/webhooks?lang=voice + */ export type CapabilityVoice = { + /** + * Webhook configuration for voice events. + */ webhooks: { - eventUrl: { - socketTimeout?: number; - connectTimeout?: number; - } & CapabilityWebhook; - answerUrl: { - socketTimeout?: number; - connectTimeout?: number; - } & CapabilityWebhook; - fallbackAnswerUrl: { - socketTimeout?: number; - connectTimeout?: number; - } & CapabilityWebhook; + /** + * Webhook for events related to voice calls. + */ + eventUrl: EventCallbackUrl + + /** + * Webhook for voice call answer events. + */ + answerUrl: AnswerCallbackUrl + + /** + * Webhook for fallback voice call answer events. + */ + fallbackAnswerUrl: FallbackAnswerUrl }; + + /** + * Indicates whether payment is enabled. + */ paymentEnabled: boolean; + + /** + * Whether to use signed webhooks for voice events. + * + * @remarks Refer to {@link https://developer.vonage.com/en/getting-started/concepts/webhooks#decoding-signed-webhooks} for more information. + */ signedCallbacks: boolean; + + /** + * Conversation TTL + * + * @remarks The length of time named conversations will remain active for after + * creation, in hours. 0 means infinite. Maximum value is 744 (i.e., 31 days). + */ conversationsTTL: number; - region: string; + + /** + * Region to round calls + * + * @remarks + * Selecting a region means all inbound, programmable SIP and SIP connect + * calls will be sent to the selected region unless the call is sent to a + * regional endpoint. If the call is using a regional endpoint, this will + * override the application setting. + */ + region: VoiceRegions | string; + + /** + * Payment gateway configuration. + */ payments: { + /** + * List of payment gateways. + */ gateways: Array; }; }; diff --git a/packages/applications/lib/types/CapabilityWebhook.ts b/packages/applications/lib/types/CapabilityWebhook.ts index af4c410c..291072fb 100644 --- a/packages/applications/lib/types/CapabilityWebhook.ts +++ b/packages/applications/lib/types/CapabilityWebhook.ts @@ -1,4 +1,15 @@ +/** + * Represents the base properties for a capability webhook configuration. + */ export type CapabilityWebhook = { + /** + * The URL endpoint to which the webhook data will be sent. + */ address: string; + + /** + * The HTTP method to be used when sending data to the webhook endpoint. + * It can be either 'POST' or 'GET'. + */ httpMethod: 'POST' | 'GET'; }; diff --git a/packages/applications/lib/types/ListApplicationParams.ts b/packages/applications/lib/types/ListApplicationParams.ts index 87191ae0..a88b6348 100644 --- a/packages/applications/lib/types/ListApplicationParams.ts +++ b/packages/applications/lib/types/ListApplicationParams.ts @@ -1,8 +1,20 @@ +/** + * Parameters for listing applications with pagination. + */ export type ListApplicationParams = { + /** + * The size of the page for pagination. + */ pageSize?: number; + /** * @deprecated please use pageSize instead + * The deprecated size of the page for pagination. */ page_size?: number; + + /** + * The specific page number for pagination. + */ page?: number; }; diff --git a/packages/applications/lib/types/Response/ApplicationPageResponse.ts b/packages/applications/lib/types/Response/ApplicationPageResponse.ts index 60462642..72c253da 100644 --- a/packages/applications/lib/types/Response/ApplicationPageResponse.ts +++ b/packages/applications/lib/types/Response/ApplicationPageResponse.ts @@ -1,12 +1,50 @@ +import { Application } from '..'; import { ApplicationResponse } from './ApplicationResponse'; import { APILinks } from '@vonage/server-client'; +/** + * Represents the response for a paginated list of applications. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase` + * + * @link https://developer.vonage.com/en/api/application.v2#listApplication + */ export type ApplicationPageResponse = { + /** + * The number of applications per page. + */ page_size: number; + + /** + * The current page number (starts at 1). + */ page: number; + + /** + * The total number of applications. + */ total_items: number; + + /** + * The total number of pages returned. + */ total_pages: number; + + /** + * A list of applications matching your existing filters. + */ + applications: ApplicationResponse[]; + + /** + * An object containing a list of applications. + */ _embedded: { - applications: ApplicationResponse[]; + + /** + * A list of applications matching your existing filters. + */ + applications: Array; }; } & APILinks; diff --git a/packages/applications/lib/types/Response/ApplicationResponse.ts b/packages/applications/lib/types/Response/ApplicationResponse.ts index 2bb9c1a5..a896be0c 100644 --- a/packages/applications/lib/types/Response/ApplicationResponse.ts +++ b/packages/applications/lib/types/Response/ApplicationResponse.ts @@ -7,21 +7,79 @@ import { CapabilityMeetingsResponse } from './CapabilityMeetingsResponse'; import { CapabilityBulkResponse } from './CapabilityBulkResponse'; import { CapabilityMessagesResponse } from './CapabilityMessagesResponse'; +/** + * Represents a response containing application information. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase` + * + * @link https://developer.vonage.com/en/api/application.v2#getApplication + * + * @see {@link Application} + */ export type ApplicationResponse = { + /** + * Keys associated with the application. + */ keys: { - public_key: string; + /** + * The public key for the application. + */ + public_key?: string | undefined }; + /** + * Privacy configuration for the application. + */ privacy: { - improve_ai: boolean; + /** + * If set to true, Vonage may store and use your content and data for the + * improvement of Vonage's AI-based services and technologies. + */ + improve_ai?: boolean; }; + + /** + * Capabilities configuration for the application. + */ capabilities: { + + /** + * RTC/Conversation Service related configuration. + */ rtc: CapabilityRTCResponse; + + /** + * Voice related configuration. + */ voice: CapabilityVoiceResponse; + + /** + * Meetings related configuration. + */ meetings: CapabilityMeetingsResponse; + + /** + * Bulk related configuration. + */ bulk: CapabilityBulkResponse; + + /** + * Messages/Dispatch related configuration. + */ messages: CapabilityMessagesResponse; + + /** + * Verify related configuration. + */ verify: CapabilityVerifyResponse; + + /** + * Specify the vbc capability to enable zero-rated calls for VBC number + * programmability service applications. This is always an empty object. + */ vbc: unknown; + }; -} & Application & - APILinks; + _links?: Pick +} & Application; diff --git a/packages/applications/lib/types/Response/CapabilityBulkResponse.ts b/packages/applications/lib/types/Response/CapabilityBulkResponse.ts index d5ab6fc0..3449b7ed 100644 --- a/packages/applications/lib/types/Response/CapabilityBulkResponse.ts +++ b/packages/applications/lib/types/Response/CapabilityBulkResponse.ts @@ -1,8 +1,26 @@ import { CapabilityWebhookResponse } from './CapabilityWebhookResponse'; +/** + * Represents the response for bulk-related capabilities configuration. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase` + */ export type CapabilityBulkResponse = { + /** + * Webhook configuration for bulk events. + */ webhooks: { + + /** + * Webhook for events related to bulk list status. + */ list_status_url: CapabilityWebhookResponse; + + /** + * Webhook for events related to bulk run status. + */ run_status_url: CapabilityWebhookResponse; }; }; diff --git a/packages/applications/lib/types/Response/CapabilityMeetingsResponse.ts b/packages/applications/lib/types/Response/CapabilityMeetingsResponse.ts index 95ccef44..c41649c7 100644 --- a/packages/applications/lib/types/Response/CapabilityMeetingsResponse.ts +++ b/packages/applications/lib/types/Response/CapabilityMeetingsResponse.ts @@ -1,9 +1,30 @@ import { CapabilityWebhookResponse } from './CapabilityWebhookResponse'; +/** + * Represents the response for meetings-related capabilities configuration. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase` + */ export type CapabilityMeetingsResponse = { + /** + * Webhook configuration for meetings-related events. + */ webhooks: { + /** + * Webhook for events related to changes in meeting rooms. + */ room_changed: CapabilityWebhookResponse; + + /** + * Webhook for events related to changes in meeting sessions. + */ session_changed: CapabilityWebhookResponse; + + /** + * Webhook for events related to changes in meeting recording. + */ recording_changed: CapabilityWebhookResponse; }; }; diff --git a/packages/applications/lib/types/Response/CapabilityMessagesResponse.ts b/packages/applications/lib/types/Response/CapabilityMessagesResponse.ts index f73ad834..3728185a 100644 --- a/packages/applications/lib/types/Response/CapabilityMessagesResponse.ts +++ b/packages/applications/lib/types/Response/CapabilityMessagesResponse.ts @@ -1,11 +1,32 @@ import { CapabilityWebhookResponse } from './CapabilityWebhookResponse'; import { CapabilityMessages } from '../CapabilityMessages'; +/** + * Represents the response for messages-related capabilities configuration. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase` + */ export type CapabilityMessagesResponse = { + /** + * Webhook configuration for messages-related events. + */ webhooks: { + /** + * Webhook for inbound messages. + */ inbound_url: CapabilityWebhookResponse; + + /** + * Webhook for events related to message status. + */ status_url: CapabilityWebhookResponse; }; + + /** + * Whether to authenticate inbound media for messages. + */ authenticate_inbound_media: boolean; } & Omit< CapabilityMessages, diff --git a/packages/applications/lib/types/Response/CapabilityRTCResponse.ts b/packages/applications/lib/types/Response/CapabilityRTCResponse.ts index 3c4ed323..9acddd49 100644 --- a/packages/applications/lib/types/Response/CapabilityRTCResponse.ts +++ b/packages/applications/lib/types/Response/CapabilityRTCResponse.ts @@ -1,9 +1,30 @@ import { CapabilityWebhookResponse } from './CapabilityWebhookResponse'; +/** + * Represents the response for RTC-related capabilities configuration. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase` + */ export type CapabilityRTCResponse = { + /** + * Webhook configuration for RTC events. + */ webhooks: { + /** + * Webhook for events related to RTC. + */ event_url: CapabilityWebhookResponse; }; + + /** + * Whether to use signed webhooks for RTC events. + */ signed_callbacks: boolean; + + /** + * The leg persistence time for RTC events. + */ leg_persistence_time: number; }; diff --git a/packages/applications/lib/types/Response/CapabilityVerifyResponse.ts b/packages/applications/lib/types/Response/CapabilityVerifyResponse.ts index 91bee18d..8eaffaad 100644 --- a/packages/applications/lib/types/Response/CapabilityVerifyResponse.ts +++ b/packages/applications/lib/types/Response/CapabilityVerifyResponse.ts @@ -1,8 +1,21 @@ import { CapabilityWebhookResponse } from './CapabilityWebhookResponse'; import { CapabilityVerify } from '../CapabilityVerify'; +/** + * Represents the response for verification-related capabilities configuration. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase` + */ export type CapabilityVerifyResponse = { + /** + * Webhook configuration for verification events. + */ webhooks: { + /** + * Webhook for events related to verification status. + */ status_url: CapabilityWebhookResponse; }; } & Omit; diff --git a/packages/applications/lib/types/Response/CapabilityVoiceResponse.ts b/packages/applications/lib/types/Response/CapabilityVoiceResponse.ts index 01866b66..97172ff7 100644 --- a/packages/applications/lib/types/Response/CapabilityVoiceResponse.ts +++ b/packages/applications/lib/types/Response/CapabilityVoiceResponse.ts @@ -1,23 +1,106 @@ import { CapabilityWebhookResponse } from './CapabilityWebhookResponse'; import { CapabilityVoice } from '../CapabilityVoice'; +/** + * Event URL configuration response + * + * @see {@link EventCallbackUrl} + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase` + */ +export type EventUrlResponse = { + /** + * Socket timeout in milliseconds. + */ + socketTimeout?: number; + /** + * Connection timeout in milliseconds. + */ + connectTimeout?: number; +} & CapabilityWebhookResponse; + +/** + * Answer URL configuration response + * + * @see {@link AnswerCallbackUrl} + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase` + */ +export type AnswerUrlResponse = { + /** + * Socket timeout in milliseconds. + */ + socket_timeout?: number; + /** + * Connection timeout in milliseconds. + */ + connect_timeout?: number; +} & CapabilityWebhookResponse; + +/** + * Fallback URL configuration response + * + * @see {@link FallbackAnswerUrlResponse} + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase` + */ +export type FallbackAnswerUrlResponse = { + /** + * Socket timeout in milliseconds. + */ + socket_timeout?: number; + /** + * Connection timeout in milliseconds. + */ + connect_timeout?: number; +} & CapabilityWebhookResponse; + +/** + * Represents the response for voice-related capabilities configuration. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase` + */ export type CapabilityVoiceResponse = { + /** + * Webhook configuration for voice events. + */ webhooks: { - eventUrl: { - socketTimeout?: number; - connectTimeout?: number; - } & CapabilityWebhookResponse; - answerUrl: { - socketTimeout?: number; - connectTimeout?: number; - } & CapabilityWebhookResponse; - fallbackAnswerUrl: { - socketTimeout?: number; - connectTimeout?: number; - } & CapabilityWebhookResponse; + /** + * Webhook for events related to voice calls. + */ + event_url: EventUrlResponse + + /** + * Webhook for voice call answer events. + */ + answer_url: AnswerUrlResponse + /** + * Webhook for fallback voice call answer events. + */ + fallback_answer_url: FallbackAnswerUrlResponse }; + + /** + * Indicates whether payment is enabled. + */ payment_enabled: boolean; + /** + * Whether to use signed webhooks for voice events. + * Refer to [the Webhooks documentation](https://developer.vonage.com/en/getting-started/concepts/webhooks#decoding-signed-webhooks) for more information. + */ signed_callbacks: boolean; + /** + * The length of time named conversations will remain active for after creation, in hours. + * 0 means infinite. Maximum value is 744 (i.e., 31 days). + */ conversations_ttl: number; } & Omit< CapabilityVoice, diff --git a/packages/applications/lib/types/Response/CapabilityWebhookResponse.ts b/packages/applications/lib/types/Response/CapabilityWebhookResponse.ts index c0d7aa5a..dfb58ef0 100644 --- a/packages/applications/lib/types/Response/CapabilityWebhookResponse.ts +++ b/packages/applications/lib/types/Response/CapabilityWebhookResponse.ts @@ -1,5 +1,17 @@ import { CapabilityWebhook } from '../CapabilityWebhook'; +/** + * Represents the response for a capability webhook configuration. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase` + * + * @see {@link CapabilityWebhook} + */ export type CapabilityWebhookResponse = { + /** + * The HTTP method to be used when sending data to the webhook endpoint. It can be either 'POST' or 'GET'. + */ http_method: 'POST' | 'GET'; } & Omit; diff --git a/packages/applications/lib/types/index.ts b/packages/applications/lib/types/index.ts index 80f85155..b98f4027 100644 --- a/packages/applications/lib/types/index.ts +++ b/packages/applications/lib/types/index.ts @@ -1,5 +1,4 @@ export * from './Application'; -export * from './ApplicationClassParameters'; export * from './ApplicationPageList'; export * from './CapabilityBulk'; export * from './CapabilityMeetings'; diff --git a/packages/applications/package.json b/packages/applications/package.json index 4b1c1eef..6f6245ed 100644 --- a/packages/applications/package.json +++ b/packages/applications/package.json @@ -1,4 +1,5 @@ { + "$schema": "https://json.schemastore.org/package.json", "name": "@vonage/applications", "version": "1.9.0", "description": "Vonage Applications API", @@ -14,7 +15,16 @@ "url": "git+https://github.com/Vonage/vonage-node-sdk.git" }, "license": "Apache-2.0", - "author": "Chris Tankersley ", + "contributors": [ + { + "name": "Chris Tankersley", + "url": "https://github.com/dragonmantank" + }, + { + "name": "Chuck \"MANCHUCK\" Reeves", + "url": "https://github.com/manchuck" + } + ], "main": "dist/index.js", "types": "dist/index.d.ts", "directories": { @@ -27,18 +37,17 @@ "scripts": { "build": "npm run clean && npm run compile", "clean": "npx shx rm -rf dist tsconfig.tsbuildinfo", - "compile": "npx tsc --build --verbose" + "compile": "npx tsc --build --verbose", + "prepublishOnly": "npm run build" }, "dependencies": { "@vonage/auth": "^1.7.0", - "@vonage/server-client": "^1.9.0", - "@vonage/vetch": "^1.6.0" + "@vonage/server-client": "^1.9.0" }, "devDependencies": { "nock": "^13.3.4" }, "publishConfig": { "directory": "dist" - }, - "gitHead": "328f18e5c8a458cb4d06d7955ec2399a6ce6f5d8" + } } diff --git a/packages/applications/tsconfig.json b/packages/applications/tsconfig.json index 662ba079..3a26a455 100644 --- a/packages/applications/tsconfig.json +++ b/packages/applications/tsconfig.json @@ -1,22 +1,24 @@ { - "extends": "../../tsconfig.json", + "$schema": "https://json.schemastore.org/tsconfig", - "compilerOptions": { - "rootDir": "lib", - "outDir": "dist" - }, + "extends": "../../tsconfig.json", - "exclude": [ - "__tests__", - "jest.config.js", - "dist" - ], + "compilerOptions": { + "rootDir": "lib", + "outDir": "dist" + }, - "references": [ - { "path": "../server-client" } - ], + "exclude": [ + "__tests__", + "jest.config.js", + "dist" + ], - "ts-node": { - "esm": true - } + "references": [ + { "path": "../server-client" } + ], + + "ts-node": { + "esm": true + } } diff --git a/packages/applications/typedoc.json b/packages/applications/typedoc.json new file mode 100644 index 00000000..756762f7 --- /dev/null +++ b/packages/applications/typedoc.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "extends": ["../../typedoc.base.json"], + "entryPoints": ["lib/index.ts"], + "name": "Vonage JWT" +} diff --git a/packages/audit/__tests__/audit.test.ts b/packages/audit/__tests__/audit.test.ts index 97368b90..1a58dba6 100644 --- a/packages/audit/__tests__/audit.test.ts +++ b/packages/audit/__tests__/audit.test.ts @@ -132,27 +132,12 @@ describe('Audit Events', () => { }); test('Throws exception when request fails', async () => { - const events = []; const scope = nock(BASE_URL, { reqheaders: { authorization: 'Basic MTIzNDU6QUJDREU=', }, }) .intercept(`/beta/audit/events?page=1`, 'GET') - .reply(200, { - _embedded: { - events: [createEvent({ id: '1' })].map( - Client.transformers.snakeCaseObjectKeys, - ), - }, - page: { - size: 20, - totalElements: 2, - totalPages: 2, - page: 1, - }, - }) - .intercept(`/beta/audit/events?page=2`, 'GET') .reply(401, { status: 401, error: 'Unauthorized', @@ -161,9 +146,6 @@ describe('Audit Events', () => { const results = client.getEvents({}); - const eventIter = await results.next(); - expect(eventIter.value.id).toBe('1'); - await expect(results.next()).rejects.toThrow( 'Request failed with status code 401', ); diff --git a/packages/audit/lib/audit.ts b/packages/audit/lib/audit.ts index 50af5f4d..4b90a6a7 100644 --- a/packages/audit/lib/audit.ts +++ b/packages/audit/lib/audit.ts @@ -1,12 +1,70 @@ import { AuthenticationType, Client } from '@vonage/server-client'; -import { AuditParams } from './types/auditParams'; -import { AuditEvent } from './types/auditEvent'; -import { AuditEventListResponse } from './interfaces/auditEventListResponse'; +import { + AuditEventListResponse, + AuditEvent, + AuditParams, + AuditEventResponse, +} from './types'; +/** + * Represents an SDK client for interacting with audit-related functionality. + * + * @remarks + * This client is only available as a standalone client. It cannot be + * instantiated from a Vonage client. + * + * @example + * Create a standalone Audit client + * + * ```ts + * import { Audit } from '@vonage/audit'; + * + * const auditClient = new Audit({ + * apiKey: VONAGE_API_KEY, + * apiSecret: VONAGE_API_SECRET + * }); + * ``` + */ export class Audit extends Client { + // The base path for audit-related API endpoints protected BASE_PATH = 'beta'; - protected authType = AuthenticationType.BASIC; + // Authentication type for the client + authType = AuthenticationType.BASIC; + + /** + * Retrieves a list of audit events based on specified parameters. + * + * @param {AuditParams} params - The query parameters for filtering audit events. + * @return { AsyncGenerator} An async generator that yields audit events. + * + * @example + * Retrieve a list of audit events + * + * ```ts + * const auditEvents = auditClient.getEvents({ + * page: 1, + * size: 10, + * dateFrom: '2021-01-01T00:00:00Z', + * dateTo: '2021-01-31T23:59:59Z', + * eventType: 'message', + * search: 'search term' + * }); + * + * for await (const event of auditEvents) { + * console.log(event.id); + * console.log(event.type); + * console.log(event.created); + * console.log(event.accountId); + * console.log(event.requestId); + * console.log(event.request); + * console.log(event.response); + * console.log(event.ipAddress); + * console.log(event.country); + * console.log(event.msisdn); + * } + * ``` + */ async *getEvents( params: AuditParams, ): AsyncGenerator { @@ -19,21 +77,38 @@ export class Audit extends Client { Client.transformers.snakeCaseObjectKeys(params), ); - const events = (resp.data?._embedded.events || []).map((event) => + const events = (resp.data?._embedded?.events || []).map((event) => Client.transformers.camelCaseObjectKeys(event, true), ); totalPages = resp.data?.page?.totalPages || 0; - yield* events; + yield* events as AuditEvent[]; page++; } while (page <= totalPages); } - public async getEvent(eventId: string): Promise { - const resp = await this.sendGetRequest( + /** + * Retrieves a specific audit event by its ID. + * + * @param {string} eventId - The ID of the audit event to retrieve. + * @return {Promise} A promise that resolves to the retrieved audit event. + * + * @example + * Retrieve a specific audit event + * + * ```ts + * const auditEvent = await auditClient.getEvent('event-id'); + * console.log(auditEvent.id); + * ``` + */ + async getEvent(eventId: string): Promise { + const resp = await this.sendGetRequest( `${this.config.apiHost}/${this.BASE_PATH}/audit/events/${eventId}`, ); - return Client.transformers.camelCaseObjectKeys(resp.data, true); + return Client.transformers.camelCaseObjectKeys( + resp.data, + true, + ) as AuditEvent; } } diff --git a/packages/audit/lib/enums.ts b/packages/audit/lib/enums.ts index 862c1e92..567daff2 100644 --- a/packages/audit/lib/enums.ts +++ b/packages/audit/lib/enums.ts @@ -1,29 +1,149 @@ +/** + * Audit Events are generated automatically by Vonage as the user interacts with + * either a Vonage API or the Vonage Dashboard. Each Audit Event object has a + * type and associated metadata. + * + * @remarks + * + * The list of supported event types does change from time to time. For + * this reason the OPTIONS method is provided to return event types. You can + * see how to return the definitive list of event types from the {@link https://developer.vonage.com/en/audit/code-snippets/get-event-types} + * + * @see Documentation {@link https://developer.vonage.com/en/audit/concepts/audit-events} + */ export enum AuditEventTypes { - 'USER_STATUS' = 'USER_STATUS', - 'USER_UPDATE' = 'USER_UPDATE', - 'USER_BILLING_UPDATE' = 'USER_BILLING_UPDATE', - 'USER_CREATE' = 'USER_CREATE', - 'USER_LOGIN' = 'USER_LOGIN', - 'USER_LOGOUT' = 'USER_LOGOUT', - 'USER_PRODUCT_SEARCH' = 'USER_PRODUCT_SEARCH', - 'USER_API_KEYS_UPDATE' = 'USER_API_KEYS_UPDATE', - 'ACCOUNT_SECRET_DELETE' = 'ACCOUNT_SECRET_DELETE', - 'ACCOUNT_SECRET_CREATE' = 'ACCOUNT_SECRET_CREATE', - 'ACCOUNT_UPDATE_SPAMMER' = 'ACCOUNT_UPDATE_SPAMMER', - 'ACCOUNT_UPDATE_SETTINGS_API' = 'ACCOUNT_UPDATE_SETTINGS_API', - 'NUMBER_ASSIGN' = 'NUMBER_ASSIGN', - 'NUMBER_UPDATED' = 'NUMBER_UPDATED', - 'NUMBER_RELEASE' = 'NUMBER_RELEASE', - 'NUMBER_LINKED' = 'NUMBER_LINKED', - 'NUMBER_UNLINKED' = 'NUMBER_UNLINKED', - 'APP_CREATE' = 'APP_CREATE', - 'APP_UPDATE' = 'APP_UPDATE', - 'APP_DELETE' = 'APP_DELETE', - 'APP_DISABLE' = 'APP_DISABLE', - 'APP_ENABLE' = 'APP_ENABLE', - 'IP_WHITELIST_CREATE' = 'IP_WHITELIST_CREATE', - 'IP_WHITELIST_DELETE' = 'IP_WHITELIST_DELETE', - 'AUTORELOAD_ENABLE' = 'AUTORELOAD_ENABLE', - 'AUTORELOAD_UPDATE' = 'AUTORELOAD_UPDATE', - 'AUTORELOAD_DISABLE' = 'AUTORELOAD_DISABLE', + /** + * User status updated. + */ + USER_STATUS = 'USER_STATUS', + + /** + * User updated. + */ + USER_UPDATE = 'USER_UPDATE', + + /** + * User billing updated. + */ + USER_BILLING_UPDATE = 'USER_BILLING_UPDATE', + + /** + * User created. + */ + USER_CREATE = 'USER_CREATE', + + /** + * User login (Premium Support only). + */ + USER_LOGIN = 'USER_LOGIN', + + /** + * User logout (Premium Support only). + */ + USER_LOGOUT = 'USER_LOGOUT', + + /** + * Relates to searching for CDRs or logs in Dashboard. + */ + USER_PRODUCT_SEARCH = 'USER_PRODUCT_SEARCH', + + /** + * Sub-accounts for user updated. + */ + USER_API_KEYS_UPDATE = 'USER_API_KEYS_UPDATE', + + /** + * Secret Rotation operation. + */ + ACCOUNT_SECRET_DELETE = 'ACCOUNT_SECRET_DELETE', + + /** + * Secret Rotation operation. + */ + ACCOUNT_SECRET_CREATE = 'ACCOUNT_SECRET_CREATE', + + /** + * Account Settings updated via API. + */ + ACCOUNT_UPDATE_SPAMMER = 'ACCOUNT_UPDATE_SPAMMER', + + /** + * Account Settings updated via API. + */ + ACCOUNT_UPDATE_SETTINGS_API = 'ACCOUNT_UPDATE_SETTINGS_API', + + /** + * Number assigned. + */ + NUMBER_ASSIGN = 'NUMBER_ASSIGN', + + /** + * Number updated. + */ + NUMBER_UPDATED = 'NUMBER_UPDATED', + + /** + * Number released. + */ + NUMBER_RELEASE = 'NUMBER_RELEASE', + + /** + * Number linked to Vonage application. + */ + NUMBER_LINKED = 'NUMBER_LINKED', + + /** + * Number unlinked from Vonage application. + */ + NUMBER_UNLINKED = 'NUMBER_UNLINKED', + + /** + * App created. + */ + APP_CREATE = 'APP_CREATE', + + /** + * App updated. + */ + APP_UPDATE = 'APP_UPDATE', + + /** + * App deleted. + */ + APP_DELETE = 'APP_DELETE', + + /** + * App disabled. + */ + APP_DISABLE = 'APP_DISABLE', + + /** + * App enabled. + */ + APP_ENABLE = 'APP_ENABLE', + + /** + * Whitelist IP added. + */ + IP_WHITELIST_CREATE = 'IP_WHITELIST_CREATE', + + /** + * Whitelist IP deleted. + */ + IP_WHITELIST_DELETE = 'IP_WHITELIST_DELETE', + + /** + * Automatic reload enabled. + */ + AUTORELOAD_ENABLE = 'AUTORELOAD_ENABLE', + + /** + * Automatic reload settings updated. + */ + AUTORELOAD_UPDATE = 'AUTORELOAD_UPDATE', + + /** + * Automatic reload disabled. + */ + AUTORELOAD_DISABLE = 'AUTORELOAD_DISABLE', } diff --git a/packages/audit/lib/index.ts b/packages/audit/lib/index.ts index 3715b861..684bc798 100644 --- a/packages/audit/lib/index.ts +++ b/packages/audit/lib/index.ts @@ -1,9 +1,3 @@ -export { Audit } from './audit'; - +export * from './audit'; export * from './enums'; - -export * from './interfaces/auditResponse'; -export { AuditParams } from './types/auditParams'; -export { AuditEvent } from './types/auditEvent'; -export { AuditEventPage } from './interfaces/auditEventPage'; -export { AuditEventListResponse } from './interfaces/auditEventListResponse'; +export * from './types'; diff --git a/packages/audit/lib/interfaces/auditEventListResponse.ts b/packages/audit/lib/interfaces/auditEventListResponse.ts deleted file mode 100644 index f7978f84..00000000 --- a/packages/audit/lib/interfaces/auditEventListResponse.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { APILinks } from '@vonage/server-client'; -import { AuditEvent } from '../types/auditEvent'; -import { AuditEventPage } from './auditEventPage'; - -export interface AuditEventListResponse { - _embedded?: { - events: AuditEvent[] - } - _links: APILinks - page: AuditEventPage -} diff --git a/packages/audit/lib/interfaces/auditEventPage.ts b/packages/audit/lib/interfaces/auditEventPage.ts deleted file mode 100644 index 56caf26f..00000000 --- a/packages/audit/lib/interfaces/auditEventPage.ts +++ /dev/null @@ -1,6 +0,0 @@ -export interface AuditEventPage { - size: number - totalElements: number - totalPages: number - number: number -} diff --git a/packages/audit/lib/types/auditEvent.ts b/packages/audit/lib/types/auditEvent.ts index bea3af87..f84e9510 100644 --- a/packages/audit/lib/types/auditEvent.ts +++ b/packages/audit/lib/types/auditEvent.ts @@ -1,14 +1,56 @@ import { AuditEventTypes } from '../enums'; - +/** + * Represents an Audit Event. + */ export type AuditEvent = { - id: string - eventType: AuditEventTypes - createdAt: string - userEmail?: string - userId?: string - accountId: string - source: string - sourceDescription: string - sourceCountry: string - context?: object -} + /** + * UUID of the audit event. + */ + id: string; + + /** + * The type of the audit event. + * + */ + eventType: AuditEventTypes | string; + + /** + * The date when the audit event was created. + */ + createdAt: string; + + /** + * Email of the user whose account the audit event is associated with. + */ + userEmail?: string; + + /** + * The ID of the user that the audit event is associated with. + */ + userId?: string; + + /** + * The API_KEY of the Vonage API account that the audit event is associated with. + */ + accountId: string; + + /** + * The source of the event. + */ + source: 'CD' | 'DEVAPI'; + + /** + * Description of the audit event source. + */ + sourceDescription: 'Customer Dashboard' | 'Developer API'; + + /** + * ISO 3166-1 Alpha-2 country code recorded for the event. + */ + sourceCountry: string; + + /** + * Additional context information for the audit event. + */ + context?: unknown; +}; diff --git a/packages/audit/lib/types/auditEventListResponse.ts b/packages/audit/lib/types/auditEventListResponse.ts new file mode 100644 index 00000000..ac1963d1 --- /dev/null +++ b/packages/audit/lib/types/auditEventListResponse.ts @@ -0,0 +1,29 @@ +import { APILinks } from '@vonage/server-client'; +import { AuditEvent } from './auditEvent'; +import { AuditEventPage } from './auditEventPage'; + +/** + * Represents the response containing a list of audit events. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase` + */ +export type AuditEventListResponse = { + /** + * An object containing an array of audit events. + */ + _embedded?: { + events: AuditEvent[]; + }; + + /** + * Links associated with the API response. + */ + _links: APILinks; + + /** + * Information about the pagination and page details. + */ + page: AuditEventPage; +}; diff --git a/packages/audit/lib/types/auditEventPage.ts b/packages/audit/lib/types/auditEventPage.ts new file mode 100644 index 00000000..c7c9c961 --- /dev/null +++ b/packages/audit/lib/types/auditEventPage.ts @@ -0,0 +1,24 @@ +/** + * Represents information about the pagination of audit events. + */ +export type AuditEventPage = { + /** + * The number of items per page. + */ + size: number; + + /** + * The total number of elements across all pages. + */ + totalElements: number; + + /** + * The total number of pages available. + */ + totalPages: number; + + /** + * The current page number. + */ + number: number; +}; diff --git a/packages/audit/lib/types/auditEventResponse.ts b/packages/audit/lib/types/auditEventResponse.ts new file mode 100644 index 00000000..056a09dc --- /dev/null +++ b/packages/audit/lib/types/auditEventResponse.ts @@ -0,0 +1,47 @@ +import { AuditEventTypes } from '../enums'; +import { AuditEvent } from './auditEvent'; + +/** + * Represents an Audit Event. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase` + */ +export type AuditEventResponse = { + /** + * The type of the audit event. + * + */ + event_type: AuditEventTypes | string; + + /** + * The date when the audit event was created. + */ + created_at: string; + + /** + * Email of the user whose account the audit event is associated with. + */ + user_email?: string; + + /** + * The ID of the user that the audit event is associated with. + */ + user_id?: string; + + /** + * The API_KEY of the Vonage API account that the audit event is associated with. + */ + account_id: string; + + /** + * Description of the audit event source. + */ + source_description: Pick; + + /** + * ISO 3166-1 Alpha-2 country code recorded for the event. + */ + source_country: string; +} & Pick; diff --git a/packages/audit/lib/types/auditParams.ts b/packages/audit/lib/types/auditParams.ts index 92736d16..9f583119 100644 --- a/packages/audit/lib/types/auditParams.ts +++ b/packages/audit/lib/types/auditParams.ts @@ -1,10 +1,36 @@ import { AuditEventTypes } from '../enums'; +/** + * Represents parameters for querying audit events. + */ export type AuditParams = { - eventType?: AuditEventTypes - dateFrom?: string - dateTo?: string - searchText?: string - page?: number - size?: number -} + /** + * The type of the audit event to filter by. + */ + eventType?: AuditEventTypes | string; + + /** + * The start date for the audit event query. + */ + dateFrom?: string; + + /** + * The end date for the audit event query. + */ + dateTo?: string; + + /** + * Text to search within audit event descriptions. + */ + searchText?: string; + + /** + * The page number for paginated results. + */ + page?: number; + + /** + * The number of items per page. + */ + size?: number; +}; diff --git a/packages/audit/lib/interfaces/auditResponse.ts b/packages/audit/lib/types/auditResponse.ts similarity index 70% rename from packages/audit/lib/interfaces/auditResponse.ts rename to packages/audit/lib/types/auditResponse.ts index 332681b9..c62ce487 100644 --- a/packages/audit/lib/interfaces/auditResponse.ts +++ b/packages/audit/lib/types/auditResponse.ts @@ -1,3 +1,6 @@ import { VetchResponse } from '@vonage/vetch'; +/** + * @deprecated this is not used + */ export type AuditResponse = VetchResponse diff --git a/packages/audit/lib/types/index.ts b/packages/audit/lib/types/index.ts new file mode 100644 index 00000000..3b683f51 --- /dev/null +++ b/packages/audit/lib/types/index.ts @@ -0,0 +1,6 @@ +export * from './auditEvent'; +export * from './auditEventListResponse'; +export * from './auditEventPage'; +export * from './auditParams'; +export * from './auditResponse'; +export * from './auditEventResponse'; diff --git a/packages/audit/package.json b/packages/audit/package.json index 2cb904f2..5d2c52bc 100644 --- a/packages/audit/package.json +++ b/packages/audit/package.json @@ -1,4 +1,5 @@ { + "$schema": "https://json.schemastore.org/package.json", "name": "@vonage/audit", "version": "1.9.0", "description": "Vonage Audit SDK Package", @@ -11,7 +12,12 @@ "url": "git+https://github.com/Vonage/vonage-node-sdk.git" }, "license": "Apache-2.0", - "author": "Chuck \"MANCHUCK\" Reeves", + "contributors": [ + { + "name": "Chuck \"MANCHUCK\" Reeves", + "url": "https://github.com/manchuck" + } + ], "main": "dist/index.js", "types": "dist/index.d.ts", "directories": { @@ -24,7 +30,8 @@ "scripts": { "build": "npm run clean && npm run compile", "clean": "npx shx rm -rf dist tsconfig.tsbuildinfo", - "compile": "npx tsc --build --verbose" + "compile": "npx tsc --build --verbose", + "prepublishOnly": "npm run build" }, "dependencies": { "@vonage/auth": "^1.7.0", diff --git a/packages/audit/tsconfig.json b/packages/audit/tsconfig.json index e9b438f7..50fe752c 100644 --- a/packages/audit/tsconfig.json +++ b/packages/audit/tsconfig.json @@ -1,24 +1,25 @@ { - "extends": "../../tsconfig.json", + "$schema": "https://json.schemastore.org/tsconfig", + "extends": "../../tsconfig.json", - "compilerOptions": { - "rootDir": "lib", - "outDir": "dist" - }, + "compilerOptions": { + "rootDir": "lib", + "outDir": "dist" + }, - "exclude": [ - "__tests__", - "jest.config.js", - "dist" - ], + "exclude": [ + "__tests__", + "jest.config.js", + "dist" + ], - "references": [ - { "path": "../auth" }, - { "path": "../server-client" }, - { "path": "../vetch" } - ], + "references": [ + { "path": "../auth" }, + { "path": "../server-client" }, + { "path": "../vetch" } + ], - "ts-node": { - "esm": true - } + "ts-node": { + "esm": true + } } diff --git a/packages/audit/typedoc.json b/packages/audit/typedoc.json new file mode 100644 index 00000000..0eea3a25 --- /dev/null +++ b/packages/audit/typedoc.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "extends": ["../../typedoc.base.json"], + "entryPoints": ["lib/index.ts"], + "name": "Vonage Audit" +} diff --git a/packages/auth/__tests__/__dataSets__/jwt.ts b/packages/auth/__tests__/__dataSets__/jwt.ts index 90cd0f97..462c33ad 100644 --- a/packages/auth/__tests__/__dataSets__/jwt.ts +++ b/packages/auth/__tests__/__dataSets__/jwt.ts @@ -1,6 +1,7 @@ import { tokenGenerate } from '@vonage/jwt'; import { AuthParams } from '../../lib/types/index'; import { applicationId, privateKeyString, privateKeyPath } from '../common'; +import { readFileSync } from 'fs'; jest.useFakeTimers({ now: 10907902800000, @@ -26,7 +27,7 @@ export default [ label: 'create bearer header with private key file', method: 'createBearerHeader', authParameters: { - privateKey: privateKeyPath, + privateKey: readFileSync(privateKeyPath), applicationId: applicationId, jwtOptions: { jti: 'foo', @@ -41,7 +42,7 @@ export default [ label: 'create bearer header with custom claims', method: 'createBearerHeader', authParameters: { - privateKey: privateKeyPath, + privateKey: readFileSync(privateKeyPath), applicationId: applicationId, jwtOptions: { jti: 'foo', diff --git a/packages/auth/lib/auth.ts b/packages/auth/lib/auth.ts index 0d24a037..5e125f89 100644 --- a/packages/auth/lib/auth.ts +++ b/packages/auth/lib/auth.ts @@ -1,13 +1,13 @@ import { tokenGenerate, GeneratorOptions } from '@vonage/jwt'; import { createHash, createHmac } from 'crypto'; -import { existsSync, readFileSync } from 'fs'; +import { PathLike, existsSync, readFileSync } from 'fs'; import { AuthParams, AuthQueryParams, SignedHashParams, AuthSignedParams, -} from './types/index'; -import { AuthInterface } from './interfaces/index'; +} from './types'; +import { AuthInterface } from './interfaces'; import { AlgorithmTypes } from './enums'; import { MissingApiKeyError, @@ -16,17 +16,64 @@ import { InvalidApiSecretError, MissingSignatureError, InvalidSignatureAlgorithmError, -} from './errors/index'; +} from './errors'; import debug from 'debug'; const log = debug('vonage:auth'); +/** + * Authentication class used for generating Authentication headers and query parameters. + * + * @remarks + * This client is only available as a standalone client. It cannot be + * instantiated from the server-sdk package. + * + * @example + * Create a standard authentication object. + * + * ```ts + * import { Auth } from '@vonage/auth'; + * + * const auth = new Auth({ + * apiKey: VONAGE_API_KEY, + * apiSecret: VONAGE_API_SECRET, + * applicationId: VONAGE_APPLICATION_ID, + * privateKey: VONAGE_APPLICATION_PRIVATE_KEY_PATH, + * }); + * ``` + */ export class Auth implements AuthInterface { + /** + * @property {string} apiKey - The API key used for authentication. + */ apiKey: string; + + /** + * @property {string} apiSecret - The API secret used for authentication. + */ apiSecret: string; - privateKey?: string; - applicationId?: string; - signature: SignedHashParams; + + /** + * @property {string | null} [privateKey] - The private key used for JWT + * authentication, either as a string or read from a file. + */ + privateKey?: string | null; + + /** + * @property {string | null} [applicationId] - The application ID used for + * JWT authentication. + */ + applicationId?: string | null; + + /** + * @property {SignedHashParams | null} [signature] - The signature parameters + * used for signature authentication. + */ + signature?: SignedHashParams | null; + + /** + * @property {GeneratorOptions} jwtOptions - Options used for generating JWTs. + */ jwtOptions: GeneratorOptions; constructor(opts?: AuthParams) { @@ -36,17 +83,52 @@ export class Auth implements AuthInterface { this.applicationId = opts?.applicationId || null; this.jwtOptions = opts?.jwtOptions || {}; - if (existsSync(opts.privateKey)) { + let privateKey = opts?.privateKey; + if (existsSync(opts?.privateKey as PathLike)) { log('Reading private key file'); - opts.privateKey = readFileSync(opts.privateKey).toString(); + privateKey = readFileSync(opts?.privateKey as PathLike).toString(); } this.privateKey - = opts.privateKey instanceof Buffer - ? opts.privateKey.toString() - : opts.privateKey; + = privateKey instanceof Buffer + ? privateKey.toString() + : (opts?.privateKey as string); } + /** + * Generates query parameters for authentication, optionally merging with + * provided parameters. + * + * + * @param {T} [params] - Additional parameters to merge with the + * generated authentication query parameters. + * + * @return {Promise} - A promise that resolves + * with the merged authentication query parameters. + * + * @throws {MissingApiKeyError} - Thrown when the API key is missing. + * @throws {MissingApiSecretError} - Thrown when the API secret is missing. + * @throws {InvalidApiKeyError} - Thrown when the API key is not a valid string. + * @throws {InvalidApiSecretError} - Thrown when the API secret is not a valid string. + * + * @example + * Generate query parameters + * + * ```ts + * const queryParams = await auth.getQueryParams(); + * ``` + * + * @example + * Generate query parameters and merge with additional Parameters + * + * ```ts + * const queryParams = await auth.getQueryParams({ + * to: '15555555555', + * from: '15555555556', + * text: 'Hello from Vonage SMS API' + * }); + * ``` + */ getQueryParams = async ( params?: AuthQueryParams & T, ): Promise => { @@ -70,9 +152,27 @@ export class Auth implements AuthInterface { ...params, api_key: this.apiKey, api_secret: this.apiSecret, - }; + } as AuthQueryParams & T; }; + /** + * Generates a basic authentication header. + * + * @return {Promise} - A promise that resolves with the + * generated basic authentication header. + * + * @throws {MissingApiKeyError} - Thrown when the API key is missing. + * @throws {MissingApiSecretError} - Thrown when the API secret is missing. + * @throws {InvalidApiKeyError} - Thrown when the API key is not a valid string. + * @throws {InvalidApiSecretError} - Thrown when the API secret is not a valid string. + * + * @example + * Generate a basic authentication headers + * + * ```ts + * const basicAuthHeader = await auth.createBasicHeader(); + * ``` + */ createBasicHeader = async (): Promise => { log('Creating basic auth header'); if (!this.apiKey) { @@ -95,15 +195,58 @@ export class Auth implements AuthInterface { return `Basic ${buf.toString('base64')}`; }; + /** + * Generates a bearer authentication header. + * + * @return {Promise} - A promise that resolves with the + * generated bearer authentication header. + * + * @example + * Generate a bearer authentication headers + * + * ```ts + * const bearerAuthHeader = await auth.createBearerHeader(); + * ``` + */ createBearerHeader = async (): Promise => { log('Creating bearer header'); return `Bearer ${tokenGenerate( - this.applicationId, - this.privateKey, + this.applicationId || '', + this.privateKey || '', this.jwtOptions, )}`; }; + /** + * Generates a signature hash for authentication, merging it with + * provided parameters. + * + * @template T - Type of the parameters to merge with. + * @param {T} params - Parameters to merge with the generated + * signature hash. + * @return {Promise} - A promise that resolves + * with the merged signature hash and parameters. + * + * @throws {MissingApiKeyError} - Thrown when the API key is missing. + * @throws {InvalidApiKeyError} - Thrown when the API key is not a valid string. + * @throws {MissingSignatureError} - Thrown when the signature algorithm is missing. + * @throws {MissingApiSecretError} - Thrown when the API secret is missing. + * @throws {InvalidApiSecretError} - Thrown when the API secret is not a valid string. + * @throws {InvalidSignatureAlgorithmError} - Thrown when an invalid signature algorithm is provided. + * + * @example + * Generate a signature hash + * + * ```ts + * const signatureHash = await auth.createSignatureHash({ + * to: '15555555555', + * from: '15555555556', + * text: 'Hello from Vonage SMS API', + * timestamp: '1516878400', + * sig: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6', + * }); + * ``` + */ createSignatureHash = async ( params: AuthSignedParams & T, ): Promise => { @@ -116,15 +259,15 @@ export class Auth implements AuthInterface { throw new InvalidApiKeyError(); } - if (!this.signature.algorithm) { + if (!this.signature?.algorithm) { throw new MissingSignatureError(); } - if (!this.signature.secret) { + if (!this.signature?.secret) { throw new MissingApiSecretError(); } - if (typeof this.signature.secret !== 'string') { + if (typeof this.signature?.secret !== 'string') { throw new InvalidApiSecretError(); } @@ -150,9 +293,7 @@ export class Auth implements AuthInterface { switch (this.signature.algorithm) { case AlgorithmTypes.md5hash: returnParams.sig = createHash('md5') - .update( - `${stringifiedParamsforSigning}${this.signature.secret}`, - ) + .update(`${stringifiedParamsforSigning}${this.signature.secret}`) .digest('hex'); break; diff --git a/packages/auth/lib/enums/AlgroithmTypes.ts b/packages/auth/lib/enums/AlgroithmTypes.ts index fa0cda8f..7bf9da02 100644 --- a/packages/auth/lib/enums/AlgroithmTypes.ts +++ b/packages/auth/lib/enums/AlgroithmTypes.ts @@ -1,7 +1,23 @@ +/** + * Enumeration of supported algorithm types for HMAC hashing. + * + * @remarks + * Ensure to select an algorithm that adheres to your security + * requirements and is supported by the API endpoint you're interacting with. + */ export enum AlgorithmTypes { - md5hash = 'MD5HASH', - md5hmac = 'MD5HMAC', - sha1hmac = 'SHA1HMAC', - sha256hmac = 'SHA256HMAC', - sha512hmac = 'SHA512HMAC', + /** Represents the MD5 hash algorithm */ + md5hash = 'MD5HASH', + + /** Represents the HMAC-MD5 hash algorithm, which uses a secret key for hashing. */ + md5hmac = 'MD5HMAC', + + /** Represents the HMAC-SHA1 hash algorithm, which uses a secret key for hashing. */ + sha1hmac = 'SHA1HMAC', + + /** Represents the HMAC-SHA256 hash algorithm, which uses a secret key for hashing. */ + sha256hmac = 'SHA256HMAC', + + /** Represents the HMAC-SHA512 hash algorithm, which uses a secret key for hashing. */ + sha512hmac = 'SHA512HMAC', } diff --git a/packages/auth/lib/errors/InvalidApiKeyError.ts b/packages/auth/lib/errors/InvalidApiKeyError.ts index d5d128dd..904cae5e 100644 --- a/packages/auth/lib/errors/InvalidApiKeyError.ts +++ b/packages/auth/lib/errors/InvalidApiKeyError.ts @@ -1,3 +1,12 @@ +/** + * Error class representing a specific error scenario where an API key is + * provided but is not a valid string. + * + * This error is thrown when an API request is made with an API key that + * does not meet the expected format or type (string). + * + * @extends {Error} + */ export class InvalidApiKeyError extends Error { constructor() { super('API Key must be a string'); diff --git a/packages/auth/lib/errors/InvalidApiSecretError.ts b/packages/auth/lib/errors/InvalidApiSecretError.ts index 5b4f44ea..9609523c 100644 --- a/packages/auth/lib/errors/InvalidApiSecretError.ts +++ b/packages/auth/lib/errors/InvalidApiSecretError.ts @@ -1,3 +1,12 @@ +/** + * Error class representing a specific error scenario where an API secret is + * provided but is not a valid string. + * + * This error is thrown when an API request is made with an API secret that + * does not meet the expected format or type (string). + * + * @extends {Error} + */ export class InvalidApiSecretError extends Error { constructor() { super('API Secret must be a string'); diff --git a/packages/auth/lib/errors/InvalidSignatureAlgroithmError.ts b/packages/auth/lib/errors/InvalidSignatureAlgroithmError.ts index 8e5077a6..7dc43e25 100644 --- a/packages/auth/lib/errors/InvalidSignatureAlgroithmError.ts +++ b/packages/auth/lib/errors/InvalidSignatureAlgroithmError.ts @@ -1,3 +1,12 @@ +/** + * Error class representing a specific error scenario where an invalid + * signature algorithm is provided. + * + * This error is thrown when an API request is made with a signature + * algorithm that is not supported or recognized. + * + * @extends {Error} + */ export class InvalidSignatureAlgorithmError extends Error { constructor() { super('Invalid Signature algorithm'); diff --git a/packages/auth/lib/errors/InvalidSignatureError.ts b/packages/auth/lib/errors/InvalidSignatureError.ts index 8e5077a6..60f45f35 100644 --- a/packages/auth/lib/errors/InvalidSignatureError.ts +++ b/packages/auth/lib/errors/InvalidSignatureError.ts @@ -1,4 +1,13 @@ -export class InvalidSignatureAlgorithmError extends Error { +/** + * Error class representing a specific error scenario where a user selects + * an invalid or unsupported signature algorithm. + * + * This error is thrown when an API request is made with a signature + * algorithm that is not present in the AlgorithmTypes enum. + * + * @extends {Error} + */ +export class InvalidSignatureError extends Error { constructor() { super('Invalid Signature algorithm'); } diff --git a/packages/auth/lib/errors/MissingApiKeyError.ts b/packages/auth/lib/errors/MissingApiKeyError.ts index fbcc5059..771823dd 100644 --- a/packages/auth/lib/errors/MissingApiKeyError.ts +++ b/packages/auth/lib/errors/MissingApiKeyError.ts @@ -1,3 +1,12 @@ +/** + * Error class representing a specific error scenario where an API key is + * missing in the request. + * + * This error is thrown when an API request is made without providing the + * necessary API key for authentication. + * + * @extends {Error} + */ export class MissingApiKeyError extends Error { constructor() { super('Missing API Key'); diff --git a/packages/auth/lib/errors/MissingApiSecretError.ts b/packages/auth/lib/errors/MissingApiSecretError.ts index 04c116bc..22571bc9 100644 --- a/packages/auth/lib/errors/MissingApiSecretError.ts +++ b/packages/auth/lib/errors/MissingApiSecretError.ts @@ -1,3 +1,12 @@ +/** + * Error class representing a specific error scenario where an API secret is + * missing in the request. + * + * This error is thrown when an API request is made without providing the + * necessary API secret for authentication. + * + * @extends {Error} + */ export class MissingApiSecretError extends Error { constructor() { super('Missing API Secret'); diff --git a/packages/auth/lib/errors/MissingSignatureError.ts b/packages/auth/lib/errors/MissingSignatureError.ts index 8a3eb024..ba63d788 100644 --- a/packages/auth/lib/errors/MissingSignatureError.ts +++ b/packages/auth/lib/errors/MissingSignatureError.ts @@ -1,3 +1,14 @@ +/** + * Error class representing a specific error scenario where a signature + * algorithm is expected but missing in the request. + * + * This error is thrown when an API request is made without providing the + * necessary signature algorithm for authentication. + * + * Users should select a value from the AlgorithmTypes enum. + * + * @extends {Error} + */ export class MissingSignatureError extends Error { constructor() { super('Missing signature algorithm'); diff --git a/packages/auth/lib/interfaces/AuthConstructor.ts b/packages/auth/lib/interfaces/AuthConstructor.ts deleted file mode 100644 index f0194bd6..00000000 --- a/packages/auth/lib/interfaces/AuthConstructor.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { AuthParams } from '../types/index'; -import { AuthInterface } from './AuthInterface'; - -/** - * @deprecated - */ -export type AuthConstructor = new (opts?: AuthParams) => AuthInterface diff --git a/packages/auth/lib/interfaces/AuthInterface.ts b/packages/auth/lib/interfaces/AuthInterface.ts index 8ceb78cc..ae9b4e43 100644 --- a/packages/auth/lib/interfaces/AuthInterface.ts +++ b/packages/auth/lib/interfaces/AuthInterface.ts @@ -1,8 +1,50 @@ -import { AuthQueryParams, AuthSignedParams, AuthParams } from '../types/index'; +import { AuthQueryParams, AuthSignedParams, AuthParams } from '../types'; +/** + * Interface defining the methods for handling various authentication + * mechanisms and parameter generation. + * + * @interface + * @extends {AuthParams} + */ export interface AuthInterface extends AuthParams { - getQueryParams(params?: T): Promise - createSignatureHash(params: T): Promise - createBasicHeader(): Promise - createBearerHeader(): Promise + /** + * Asynchronously generates query parameters for authentication, + * optionally merging with provided parameters. + * + * @template T - Type of the additional parameters to merge with. + * @param {T} [params] - Additional parameters to merge with the + * generated authentication query parameters. + * @returns {Promise} - A promise that resolves + * with the merged authentication query parameters. + */ + getQueryParams(params?: T): Promise; + + /** + * Asynchronously generates a signature hash for authentication, + * merging it with provided parameters. + * + * @template T - Type of the parameters to merge with. + * @param {T} params - Parameters to merge with the generated + * signature hash. + * @returns {Promise} - A promise that resolves + * with the merged signature hash and parameters. + */ + createSignatureHash(params: T): Promise; + + /** + * Asynchronously generates a basic authentication header. + * + * @returns {Promise} - A promise that resolves with the + * generated basic authentication header. + */ + createBasicHeader(): Promise; + + /** + * Asynchronously generates a bearer authentication header. + * + * @returns {Promise} - A promise that resolves with the + * generated bearer authentication header. + */ + createBearerHeader(): Promise; } diff --git a/packages/auth/lib/interfaces/index.ts b/packages/auth/lib/interfaces/index.ts index 9d66168d..1cfbd77c 100644 --- a/packages/auth/lib/interfaces/index.ts +++ b/packages/auth/lib/interfaces/index.ts @@ -1,2 +1 @@ -export * from './AuthConstructor'; export * from './AuthInterface'; diff --git a/packages/auth/lib/types.ts b/packages/auth/lib/types.ts deleted file mode 100644 index 36a5e2c3..00000000 --- a/packages/auth/lib/types.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from './enums'; -export * from './interfaces'; -export * from './types'; diff --git a/packages/auth/lib/types/AuthParams.ts b/packages/auth/lib/types/AuthParams.ts index ee65290a..68bd8a09 100644 --- a/packages/auth/lib/types/AuthParams.ts +++ b/packages/auth/lib/types/AuthParams.ts @@ -1,16 +1,50 @@ import { GeneratorOptions } from '@vonage/jwt'; import { SignedHashParams } from './SignedHashParams'; -export type AuthParams = { - apiKey?: string - apiSecret?: string - privateKey?: string | Buffer - applicationId?: string - signature?: SignedHashParams - jwtOptions?: GeneratorOptions -} - /** - * @deprecated please use AuthParams + * Represents the authentication parameters required for API requests. */ -export type AuthOpts = AuthParams +export type AuthParams = { + /** + * The API key used to authenticate requests. It may be omitted if using JWT + * or signature authentication. This value can be found in your Vonage + * Developer Dashboard. + */ + apiKey?: string | null; + + /** + * The API secret used to authenticate requests. It may be omitted if using + * JWT or signature authentication. This value can be found in your Vonage + * Developer Dashboard. + */ + apiSecret?: string | null; + + /** + * The private key used for JWT authentication. It can be provided as a string + * (read from a file) or as a Buffer (opened directly from a file). This key + * is downloaded when you create an application in your Vonage Developer + * Dashboard and may be omitted if using API key/secret or signature + * authentication. + */ + privateKey?: string | Buffer | null; + + /** + * The application ID used in conjunction with the private key for JWT + * authentication. It may be omitted if using API key/secret or signature + * authentication. This value can be found in your Vonage Developer Dashboard. + */ + applicationId?: string | null; + + /** + * An object containing parameters for signature authentication, including the + * secret and algorithm. It may be omitted if using API key/secret or JWT + * authentication. + */ + signature?: SignedHashParams | null; + + /** + * Options for generating JWTs, including the JWT issuer (application ID) + * and subject (user ID). + */ + jwtOptions?: GeneratorOptions; +}; diff --git a/packages/auth/lib/types/AuthQueryParams.ts b/packages/auth/lib/types/AuthQueryParams.ts index ca7c5c47..e15a2dbd 100644 --- a/packages/auth/lib/types/AuthQueryParams.ts +++ b/packages/auth/lib/types/AuthQueryParams.ts @@ -1,4 +1,21 @@ +/** + * Represents the query parameters used for API request authentication. + * + * @deprecated This method of authentication, using API credentials in query + * parameters, is outdated and not recommended due to security concerns. + * Consider using more secure authentication methods, such as JWT or + * signature authentication. + */ export type AuthQueryParams = { - api_key: string - api_secret: string -} + /** + * The API key used to authenticate requests. This value can be found in your + * Vonage Developer Dashboard. + */ + api_key: string; + + /** + * The API secret used to authenticate requests. This value can also be found + * in your Vonage Developer Dashboard. + */ + api_secret: string; +}; diff --git a/packages/auth/lib/types/AuthSignedParams.ts b/packages/auth/lib/types/AuthSignedParams.ts index 4369ed6a..20245d74 100644 --- a/packages/auth/lib/types/AuthSignedParams.ts +++ b/packages/auth/lib/types/AuthSignedParams.ts @@ -1,5 +1,31 @@ +/** + * Represents the parameters used for HMAC signature-based API request + * authentication. + * + * Note: Not all API endpoints support this method of authentication. + * Please refer to the specific API documentation to determine if HMAC + * signature authentication is supported. + * + * For more information on signing requests, visit: + * https://developer.vonage.com/en/getting-started/concepts/signing-messages + */ export type AuthSignedParams = { - api_key: string - sig?: string - timestamp?: string -} + /** + * The API key used to authenticate requests. This value can be found in + * your Vonage Developer Dashboard. + */ + api_key: string; + + /** + * The generated signature, used to verify the authenticity of the request. + * It's typically generated by hashing the request parameters with a + * secret key. + */ + sig?: string; + + /** + * The UNIX timestamp when the request is made. Utilized to prevent replay + * attacks by making each signature unique to a specific time window. + */ + timestamp?: string; +}; diff --git a/packages/auth/lib/types/SignedHashParams.ts b/packages/auth/lib/types/SignedHashParams.ts index 068d170c..9d3d4388 100644 --- a/packages/auth/lib/types/SignedHashParams.ts +++ b/packages/auth/lib/types/SignedHashParams.ts @@ -1,6 +1,19 @@ import { AlgorithmTypes } from '../enums'; +/** + * Represents the parameters required for generating a signed hash. + * + */ export type SignedHashParams = { - secret: string - algorithm: AlgorithmTypes -} + /** + * The secret key used to sign the hash, ensuring the integrity and + * authenticity of the message. It should be kept private and secure. + */ + secret: string; + + /** + * Specifies the algorithm type used for signing the hash. Utilizes the + * algorithm types defined in the `AlgorithmTypes` enum. + */ + algorithm: AlgorithmTypes; +}; diff --git a/packages/auth/package.json b/packages/auth/package.json index e947299d..a5f9b636 100644 --- a/packages/auth/package.json +++ b/packages/auth/package.json @@ -1,4 +1,5 @@ { + "$schema": "https://json.schemastore.org/package.json", "name": "@vonage/auth", "version": "1.7.0", "description": "Vonage Auth Package adds the correct authentication headers to requests to Vonage API's", @@ -11,7 +12,20 @@ "url": "git+https://github.com/Vonage/vonage-node-sdk.git" }, "license": "Apache-2.0", - "author": "Kelly J Andrews ", + "contributors": [ + { + "name": "Kelly J Andrews", + "url": "https://github.com/kellyjandrews" + }, + { + "name": "Chris Tankersley", + "url": "https://github.com/dragonmantank" + }, + { + "name": "Chuck 'MANCHUCK' Reeves", + "url": "https://github.com/manchuck" + } + ], "main": "dist/index.js", "types": "dist/index.d.ts", "files": [ @@ -20,7 +34,8 @@ "scripts": { "build": "npm run clean && npm run compile", "clean": "npx shx rm -rf dist tsconfig.tsbuildinfo", - "compile": "npx tsc --build --verbose" + "compile": "npx tsc --build --verbose", + "prepublishOnly": "npm run build" }, "dependencies": { "@vonage/jwt": "^1.7.0", @@ -31,6 +46,5 @@ }, "publishConfig": { "directory": "dist" - }, - "gitHead": "328f18e5c8a458cb4d06d7955ec2399a6ce6f5d8" + } } diff --git a/packages/auth/tsconfig.json b/packages/auth/tsconfig.json index 00a7d974..dd1979a0 100644 --- a/packages/auth/tsconfig.json +++ b/packages/auth/tsconfig.json @@ -1,22 +1,23 @@ { - "extends": "../../tsconfig.json", + "$schema": "https://json.schemastore.org/tsconfig", + "extends": "../../tsconfig.json", - "compilerOptions": { - "rootDir": "lib", - "outDir": "dist" - }, + "compilerOptions": { + "rootDir": "lib", + "outDir": "dist" + }, - "exclude": [ - "__tests__", - "jest.config.js", - "dist" - ], + "exclude": [ + "__tests__", + "jest.config.js", + "dist" + ], - "references": [ - { "path": "../jwt" } - ], + "references": [ + { "path": "../jwt" } + ], - "ts-node": { - "esm": true - } + "ts-node": { + "esm": true + } } diff --git a/packages/auth/typedoc.json b/packages/auth/typedoc.json new file mode 100644 index 00000000..f0042e10 --- /dev/null +++ b/packages/auth/typedoc.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "extends": ["../../typedoc.base.json"], + "entryPoints": ["lib/index.ts"], + "name": "Vonage Auth" +} diff --git a/packages/jwt/lib/acl.ts b/packages/jwt/lib/acl.ts deleted file mode 100644 index e8a31a25..00000000 --- a/packages/jwt/lib/acl.ts +++ /dev/null @@ -1 +0,0 @@ -import { JWT } from '.' diff --git a/packages/jwt/lib/common.ts b/packages/jwt/lib/common.ts deleted file mode 100644 index 96480d9d..00000000 --- a/packages/jwt/lib/common.ts +++ /dev/null @@ -1,32 +0,0 @@ -export interface Token { - config: GeneratorOptions - token: string -} - -export interface GeneratorOptions { - ttl?: number - issued_at?: number - subject?: string - jti?: string - notBefore?: number - acl?: any - [key: string]: any -} - -export interface Claims { - exp?: number - sub?: string - jti?: string - nbf?: number - acl?: object - iat?: number - application_id?: string -} - -export interface JWTInterface { - tokenGenerate( - applicationId: string, - privateKey: string | Buffer, - opts?: GeneratorOptions - ): void -} diff --git a/packages/jwt/lib/errors/invalidApplicationIdError.ts b/packages/jwt/lib/errors/invalidApplicationIdError.ts index a9252a65..a380ce8a 100644 --- a/packages/jwt/lib/errors/invalidApplicationIdError.ts +++ b/packages/jwt/lib/errors/invalidApplicationIdError.ts @@ -1,3 +1,11 @@ +/** + * InvalidMissingApplicationIdError` class for throwing an error when the + * application id is not a valid string. You can get the application ID from + * your developer dashboard. The ID will be a UUID that was generated when you + * created the application. + * + * @extends {Error} + */ export class InvalidApplicationIdError extends Error { constructor() { super('Invalid Application Id'); diff --git a/packages/jwt/lib/errors/invalidPrivateKeyError.ts b/packages/jwt/lib/errors/invalidPrivateKeyError.ts index 1b46a39e..9c72f980 100644 --- a/packages/jwt/lib/errors/invalidPrivateKeyError.ts +++ b/packages/jwt/lib/errors/invalidPrivateKeyError.ts @@ -1,3 +1,12 @@ +/** + * `InvalidPrivateKeyError` class for throwing an error when the private key + * is invalid. The private key must either be the string of the key or a buffer + * from the key file. When you created the application, the private key would + * have been downloaded then. If you lost the key, you will need to regenrate + * the key. + * + * @extends {Error} + */ export class InvalidPrivateKeyError extends Error { constructor() { super('Private key must be a string or buffer'); diff --git a/packages/jwt/lib/errors/missingApplicationIdError.ts b/packages/jwt/lib/errors/missingApplicationIdError.ts index fe799658..45b116c9 100644 --- a/packages/jwt/lib/errors/missingApplicationIdError.ts +++ b/packages/jwt/lib/errors/missingApplicationIdError.ts @@ -1,3 +1,11 @@ +/** + * `MissingApplicationIdError` class for throwing an error when the + * application id is missing. You can get the application ID from your developer + * dashboard. The ID will be a UUID that was generated when you created the + * application. + * + * @extends {Error} + */ export class MissingApplicationIdError extends Error { constructor() { super('Missing application id'); diff --git a/packages/jwt/lib/errors/missingPrivateKeyError.ts b/packages/jwt/lib/errors/missingPrivateKeyError.ts index 86bfa382..4d393053 100644 --- a/packages/jwt/lib/errors/missingPrivateKeyError.ts +++ b/packages/jwt/lib/errors/missingPrivateKeyError.ts @@ -1,3 +1,12 @@ +/** + * `MissingPrivateKeyError` class for throwing an error when the private key + * is missing. The private key must either be the string of the key or a buffer + * from the key file. When you created the application, the private key would + * have been downloaded then. If you lost the key, you will need to regenrate + * the key. + * + * @extends {Error} + */ export class MissingPrivateKeyError extends Error { constructor() { super('Missing private key'); diff --git a/packages/jwt/lib/index.ts b/packages/jwt/lib/index.ts index b63c8119..dd30a6f2 100644 --- a/packages/jwt/lib/index.ts +++ b/packages/jwt/lib/index.ts @@ -1,21 +1,5 @@ -import { JWT } from './jwt'; -import { GeneratorOptions } from './common'; - -export * from './errors/index'; - -export { JWT, GeneratorOptions }; -export * from './acl'; - -const instance = new JWT(); - -export function tokenGenerate( - applicationId: string, - privateKey: string | Buffer, - opts?: GeneratorOptions, -) { - return instance.tokenGenerate(applicationId, privateKey, opts); -} - -export function verifySignature(token: string, privateKey: string | Buffer) { - return instance.verifySignature(token, privateKey); -} +export * from './errors'; +export * from './tokenGenerate'; +export * from './verifySignature'; +export * from './types'; +export * from './jwt'; diff --git a/packages/jwt/lib/jwt.ts b/packages/jwt/lib/jwt.ts index db505d1e..ce95e7e8 100644 --- a/packages/jwt/lib/jwt.ts +++ b/packages/jwt/lib/jwt.ts @@ -1,93 +1,69 @@ -import { JWTInterface, GeneratorOptions, Claims } from './common'; -import { sign, verify } from 'jsonwebtoken'; -import { v4 as uuidv4 } from 'uuid'; -import { - MissingApplicationIdError, - MissingPrivateKeyError, - InvalidPrivateKeyError, - InvalidApplicationIdError, -} from './errors/index'; -import debug from 'debug'; - -const log = debug('vonage:jwt'); +import { tokenGenerate, validateOptions } from './tokenGenerate'; +import { verifySignature } from './verifySignature'; +import { GeneratorOptions, Claims } from './types'; + +/** + * Interface defining the methods for JWT generation. + * + * @ignore + * @deprecated Using the class is no longer needed + */ +export interface JWTInterface { + /** + * Generates a JWT token. + * + * @param {string} applicationId - The application ID. + * @param {string | Buffer} privateKey - The private key for signing the JWT. + * @param {GeneratorOptions} [opts] - Optional parameters for token generation. + * @returns {void} + */ + tokenGenerate( + applicationId: string, + privateKey: string | Buffer, + opts?: GeneratorOptions + ): void; +} +/** + * Class implementing the JWTInterface for JWT operations. + * + * @ignore + * @deprecated Using the class is no longer needed + */ export class JWT implements JWTInterface { + /** + * Generates a JWT token. + * + * @param {string} applicationId - The application ID. + * @param {string | Buffer} privateKey - The private key for signing the JWT. + * @param {GeneratorOptions} [opts] - Optional parameters for token generation. + * @return {string} - The generated JWT token. + */ tokenGenerate( applicationId: string, privateKey: string | Buffer, opts?: GeneratorOptions, ): string { - log(`Application id: ${applicationId}`); - log(`Private key: ${privateKey}`); - if (!applicationId) { - throw new MissingApplicationIdError(); - } - - if (!privateKey) { - throw new MissingPrivateKeyError(); - } - - if (typeof applicationId !== 'string') { - throw new InvalidApplicationIdError(); - } - - if (typeof privateKey !== 'string' && !(privateKey instanceof Buffer)) { - throw new InvalidPrivateKeyError(); - } - - const claims = this.validateOptions(opts); - log('Claims', claims); - claims.application_id = applicationId; - - return sign(claims, privateKey, { - algorithm: 'RS256', - header: { typ: 'JWT', alg: 'RS256' }, - }); + return tokenGenerate(applicationId, privateKey, opts); } - + /** + * Verifies the signature of a JWT token. + * + * @param {string} jwt - The JWT token to verify. + * @param {string | Buffer} privateKey - The private key used for verification. + * @return {boolean} - True if the signature is valid, false otherwise. + */ verifySignature(jwt: string, privateKey: string | Buffer): boolean { - try { - verify(jwt, privateKey, { - algorithms: ['RS256'], - }); - return true; - } catch (error) { - log('Error when verifying token', error); - } - - return false; + return verifySignature(jwt, privateKey); } + /** + * Validates the options provided for JWT generation. + * + * @param {GeneratorOptions} [opts] - The options to validate. + * @return {Claims} - The validated claims. + */ private validateOptions(opts?: GeneratorOptions): Claims { - const now = parseInt((Date.now() / 1000).toString(), 10); - - const ttl = opts?.ttl || 900; - if (opts?.ttl) { - delete opts.ttl; - } - - const claims: Claims = { - ...opts, - jti: opts?.jti || uuidv4(), - iat: opts?.issued_at || now, - exp: now + ttl, - }; - - if (opts?.subject) { - claims.sub = opts.subject; - } - - if (opts?.acl) { - claims.acl = opts.acl; - } - - for (const property in opts) { - // eslint-disable-next-line - if (opts.hasOwnProperty(property)) { - claims[property] = opts[property]; - } - } - - return claims; + return validateOptions(opts); } } diff --git a/packages/jwt/lib/tokenGenerate.ts b/packages/jwt/lib/tokenGenerate.ts new file mode 100644 index 00000000..ff0e1121 --- /dev/null +++ b/packages/jwt/lib/tokenGenerate.ts @@ -0,0 +1,118 @@ +import { GeneratorOptions, Claims } from './types'; +import jsonwebtoken from 'jsonwebtoken'; +import { v4 as uuidv4 } from 'uuid'; +import { + MissingApplicationIdError, + MissingPrivateKeyError, + InvalidPrivateKeyError, + InvalidApplicationIdError, +} from './errors'; +import debug from 'debug'; + +const { sign } = jsonwebtoken; + +const log = debug('vonage:jwt:tokenGenerate'); + +/** + * Validates the generator options and constructs the claims object. + * + * @param {GeneratorOptions} [opts] - The generator options. + * @return {Claims} - The claims object. + * @private + */ +export const validateOptions = (opts?: GeneratorOptions): Claims => { + const now = parseInt((Date.now() / 1000).toString(), 10); + + const ttl = opts?.ttl || 900; + if (opts?.ttl) { + delete opts.ttl; + } + + const claims: Claims = { + ...opts, + jti: opts?.jti || uuidv4(), + iat: opts?.issued_at || now, + exp: opts?.exp && opts?.exp > now ? opts.exp : now + ttl, + }; + + if (opts?.subject) { + claims.sub = opts.subject; + } + + if (opts?.acl) { + claims.acl = opts.acl; + } + + return claims; +}; + +/** + * Generates a JWT token. + * + * @param {string} applicationId - The application id. + * @param {string | Buffer} privateKey - The private key as a string or buffer. + * @param {GeneratorOptions} [opts] - Optional generator options. + * @return {string} - Returns the signed JWT token. + * @throws {MissingApplicationIdError} Throws an error if applicationId is missing. + * @throws {MissingPrivateKeyError} Throws an error if privateKey is missing. + * @throws {InvalidApplicationIdError} Throws an error if applicationId is not a string. + * @throws {InvalidPrivateKeyError} Throws an error if privateKey is not a string or buffer. + * @see {@link https://developer.vonage.com/en/getting-started/concepts/authentication#json-web-tokens} + * + * @example + * Generate a JWT token with default claims. + * + * ```js + * const privateKey = fs.readFileSync(__dirname + '/private.key'); + * const token = tokenGenerate(applicationId, privateKey); + * ``` + * + * @example + * Generate a JWT token with custom claims. + * + * ```js + * const privateKey = fs.readFileSync(__dirname + '/private.key'); + * const token = tokenGenerate(applicationId, privateKey, { + * subject: 'my-subject', + * acl: { + * paths: { + * '/*\/users\/**': {}, + * '/*\/conversations\/**': {}, + * '/*\/sessions\/**': {}, + * }, + * }, + * }); + * ``` + */ +export const tokenGenerate = ( + applicationId: string, + privateKey: string | Buffer, + opts?: GeneratorOptions, +): string => { + log(`Application id: ${applicationId}`); + log(`Private key: ${privateKey}`); + if (!applicationId) { + throw new MissingApplicationIdError(); + } + + if (!privateKey) { + throw new MissingPrivateKeyError(); + } + + if (typeof applicationId !== 'string') { + throw new InvalidApplicationIdError(); + } + + if (typeof privateKey !== 'string' && !(privateKey instanceof Buffer)) { + throw new InvalidPrivateKeyError(); + } + + const claims = validateOptions(opts); + log('Claims', claims); + claims.application_id = applicationId; + + return sign(claims, privateKey, { + algorithm: 'RS256', + header: { typ: 'JWT', alg: 'RS256' }, + }); +}; diff --git a/packages/jwt/lib/types/acl.ts b/packages/jwt/lib/types/acl.ts new file mode 100644 index 00000000..119fcaa9 --- /dev/null +++ b/packages/jwt/lib/types/acl.ts @@ -0,0 +1,24 @@ +/** + * Represents a rule for Access Control List (ACL). + */ +export type ACLRule = { + /** + * An array of HTTP methods allowed by this rule. + */ + methods?: Array<'POST' | 'PUT' | 'PATCH' | 'GET' | 'DELETE'>; + + /** + * Filters associated with this rule for more fine-grained control. + */ + filters?: Record>; +}; + +/** + * Represents an Access Control List (ACL) with rules for different paths. + */ +export type ACL = { + /** + * Rules associated with different paths. + */ + paths: Record; +}; diff --git a/packages/jwt/lib/types/claims.ts b/packages/jwt/lib/types/claims.ts new file mode 100644 index 00000000..9043155b --- /dev/null +++ b/packages/jwt/lib/types/claims.ts @@ -0,0 +1,45 @@ +import { ACL } from './acl'; + +/** + * JWT claims. + * + * @see {@link https://developer.vonage.com/en/getting-started/concepts/authentication#claims} + */ +export type Claims = { + /** + * Expiration time of the JWT. + */ + exp?: number; + + /** + * Subject claim, identifies the principal that is the subject of the JWT. + */ + sub?: string; + + /** + * JWT ID claim, provides a unique identifier for the JWT. + */ + jti?: string; + + /** + * Not Before claim, identifies the time before which the JWT must not be + * accepted for processing. + */ + nbf?: number; + + /** + * Access Control List claim, provides access control information. + */ + acl?: ACL; + + /** + * Issued At claim, identifies the time at which the JWT was issued. + */ + iat?: number; + + /** + * Application ID claim, identifies the application that is the subject of + * the JWT. + */ + application_id?: string; +}; diff --git a/packages/jwt/lib/types/generatorOptions.ts b/packages/jwt/lib/types/generatorOptions.ts new file mode 100644 index 00000000..4adb0c7a --- /dev/null +++ b/packages/jwt/lib/types/generatorOptions.ts @@ -0,0 +1,52 @@ +import { ACL } from './acl'; + +/** + * Claims to pass in for the token generator. + */ +export type GeneratorOptions = { + /** + * Time to live in seconds. + */ + ttl?: number; + + /** + * The time at which the JWT was issued. + */ + issued_at?: number; + + /** + * Subject of the token. + */ + subject?: string; + + /** + * JSON Web Token ID. + */ + jti?: string; + + /** + * The time before which the JWT is not yet valid. + */ + notBefore?: number; + + /** + * Access control list. + */ + acl?: ACL; + + /** + * Additional properties and values. + */ + key?: string; + + /** + * The time at which the JWT expires. + * + * If set to a time less than issued_at, the token will expire in 15 minutes. + */ + exp?: number; + /** + * Additional custom properties and values. + */ + [key: string]: unknown | number | string; +}; diff --git a/packages/jwt/lib/types/index.ts b/packages/jwt/lib/types/index.ts new file mode 100644 index 00000000..bfafc099 --- /dev/null +++ b/packages/jwt/lib/types/index.ts @@ -0,0 +1,3 @@ +export * from './claims'; +export * from './generatorOptions'; +export * from './acl'; diff --git a/packages/jwt/lib/verifySignature.ts b/packages/jwt/lib/verifySignature.ts new file mode 100644 index 00000000..4cdb0147 --- /dev/null +++ b/packages/jwt/lib/verifySignature.ts @@ -0,0 +1,56 @@ +import jsonwebtoken from 'jsonwebtoken'; +import debug from 'debug'; +import { MissingPrivateKeyError, InvalidPrivateKeyError } from './errors'; + +const { verify } = jsonwebtoken; +const log = debug('vonage:jwt:verifySignature'); + +/** + * Verifies a JWT token + * + * @function + * @param {string} jwt - The JSON Web Token to verify. + * @param {string | Buffer} privateKey - The private key used to verify the JWT + * signature. + * @return {boolean} Returns true if the JWT signature is verified successfully, + * otherwise returns false. + * @throws {MissingPrivateKeyError} Throws an error if the private key is + * missing. + * @throws {InvalidPrivateKeyError} Throws an error if the private key is not + * a string or buffer. + * + * @example + * Validate a JWT token + * + * ```js + * const privateKey = fs.readFileSync('./private.key'); + * if (verifySignature(token, privateKey)) { + * console.log('JWT signature verified.'); + * } else { + * console.log('JWT signature verification failed.'); + * } + * ``` + */ +export const verifySignature = ( + jwt: string, + privateKey: string | Buffer, +): boolean => { + if (!privateKey) { + throw new MissingPrivateKeyError(); + } + + if (typeof privateKey !== 'string' && !(privateKey instanceof Buffer)) { + throw new InvalidPrivateKeyError(); + } + + try { + verify(jwt, privateKey, { + algorithms: ['RS256'], + }); + return true; + } catch (error) { + log('Error when verifying token', error); + } + + return false; +}; diff --git a/packages/jwt/package.json b/packages/jwt/package.json index 4bbd52a3..b90a2d57 100644 --- a/packages/jwt/package.json +++ b/packages/jwt/package.json @@ -1,4 +1,5 @@ { + "$schema": "https://json.schemastore.org/package.json", "name": "@vonage/jwt", "version": "1.7.0", "description": "Vonage JWT package. Creates JWT tokens for Vonage API's", @@ -11,16 +12,30 @@ "url": "git+https://github.com/Vonage/vonage-node-sdk.git" }, "license": "Apache-2.0", - "author": "Kelly J Andrews ", - "main": "dist/index.js", - "types": "dist/index.d.ts", + "contributors": [ + { + "name": "Kelly J Andrews", + "url": "https://github.com/kellyjandrews" + }, + { + "name": "Chris Tankersley", + "url": "https://github.com/dragonmantank" + }, + { + "name": "Chuck \"MANCHUCK\" Reeves", + "url": "https://github.com/manchuck" + } + ], + "main": "./dist/index.js", + "types": "./dist/index.d.ts", "files": [ - "/dist" + "dist/**" ], "scripts": { "build": "npm run clean && npm run compile", "clean": "npx shx rm -rf dist tsconfig.tsbuildinfo", - "compile": "npx tsc --build --verbose" + "compile": "npx tsc --build --verbose", + "prepublishOnly": "npm run build" }, "dependencies": { "debug": "^4.3.4", @@ -28,10 +43,10 @@ "uuid": "^9.0.1" }, "devDependencies": { + "@types/jsonwebtoken": "9.0.3", "@types/uuid": "^9.0.5" }, "publishConfig": { "directory": "dist" - }, - "gitHead": "328f18e5c8a458cb4d06d7955ec2399a6ce6f5d8" + } } diff --git a/packages/jwt/tsconfig.json b/packages/jwt/tsconfig.json index d6934c67..3b1aba9b 100644 --- a/packages/jwt/tsconfig.json +++ b/packages/jwt/tsconfig.json @@ -1,18 +1,19 @@ { - "extends": "../../tsconfig.json", + "$schema": "https://json.schemastore.org/tsconfig", - "compilerOptions": { - "rootDir": "lib", - "outDir": "dist" - }, + "extends": "../../tsconfig.json", - "exclude": [ - "__tests__", - "jest.config.js", - "dist" - ], + "compilerOptions": { + "rootDir": "lib", + "outDir": "dist" + }, - "ts-node": { - "esm": true - } + "exclude": [ + "__tests__", + "dist" + ], + + "ts-node": { + "esm": true + } } diff --git a/packages/jwt/typedoc.json b/packages/jwt/typedoc.json new file mode 100644 index 00000000..756762f7 --- /dev/null +++ b/packages/jwt/typedoc.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "extends": ["../../typedoc.base.json"], + "entryPoints": ["lib/index.ts"], + "name": "Vonage JWT" +} diff --git a/packages/media/lib/media.ts b/packages/media/lib/media.ts index b8d12395..7d66fbe0 100644 --- a/packages/media/lib/media.ts +++ b/packages/media/lib/media.ts @@ -4,19 +4,65 @@ import { MediaParameters, MediaItemPageResponse, MediaItemResponse, -} from './types/index'; +} from './types'; const apiToSdk = (media: MediaItemResponse): MediaItem => Client.transformers.camelCaseObjectKeys(media); +/** + * Client class to interact with the Media API which enables users to manage + * their media items programmatically. + * + * @remarks + * This client is only available as a standalone client. It cannot be + * instantiated from the server-sdk package. + * + * @example + * Create a standalone Secret client + * + * ```ts + * import { Media } from '@vonage/media'; + * + * const mediaClient = new Media({ + * apiKey: VONAGE_API_KEY, + * apiSecret: VONAGE_API_SECRET + * }); + * ``` + */ export class Media extends Client { protected authType = AuthenticationType.JWT; + /** + * Retrieves a paginated list of media items, yielding each item sequentially. + * + * @param {MediaParameters} params - Optional parameters for customizing the media list request. + * @return {AsyncGenerator} An asynchronous generator that yields {@link MediaItem} objects. + * + * @example + * List all media items + * ```ts + * for await (const media of mediaClient.listAllMediaItems()) { + * console.log(`Media item ${media.id} is ${media.public ? 'public' : 'private'}`); + * console.log(` - Title: ${media.title}`); + * console.log(` - Description: ${media.description}`); + * }; + * ``` + * + * @example + * List all public media items + * ```ts + * for await (const media of mediaClient.listAllMediaItems({ public: true })) { + * console.log(`Media item ${media.id} is public`); + * console.log(` - Title: ${media.title}`); + * console.log(` - Description: ${media.description}`); + * }; + * ``` + */ async *listAllMediaItems( params: MediaParameters = {}, ): AsyncGenerator { let pageIndex = params.pageIndex || 0; - let next: APILink; + let next: APILink | undefined; do { params.pageIndex = pageIndex; const resp = await this.getMediaPage(params); @@ -24,10 +70,26 @@ export class Media extends Client { yield* resp._embedded?.media?.map(apiToSdk); pageIndex++; - next = resp._links?.next; + next = resp?._links?.next; } while (next); } + /** + * Retrieves a page of media items based on the specified parameters. + * + * @param {MediaParameters} params - Optional parameters for customizing the media page request. + * @return {Promise} A promise that resolves to a {@link MediaItemPageResponse} object representing the page of media items. + * + * @example + * List the first page of media items + * + * ```ts + * const resp = await mediaClient.getMediaPage(); + * + * console.log(`There are ${resp.count} media items in total`); + * console.log(`Showing ${resp._embedded.media.length} media items on this page`); + * ``` + */ async getMediaPage( params: MediaParameters = {}, ): Promise { @@ -39,6 +101,22 @@ export class Media extends Client { return resp.data; } + /** + * Retrieves information about a specific media item by its unique identifier. + * + * @param {string} mediaId - The unique identifier of the media item. + * @return {Promise} A promise that resolves to a {@link MediaItem} object representing the retrieved media item. + * + * @example + * Retrieve a media item by its ID + * + * ```ts + * const media = await mediaClient.getMediaItem('my-media-id'); + * console.log(`Media item ${media.id} is ${media.public ? 'public' : 'private'}`); + * console.log(` - Title: ${media.title}`); + * console.log(` - Description: ${media.description}`); + * ``` + */ async getMediaItem(mediaId: string): Promise { const resp = await this.sendGetRequest( `${this.config.apiHost}/v3/media/${mediaId}/info`, @@ -47,6 +125,22 @@ export class Media extends Client { return apiToSdk(resp.data); } + /** + * Updates the information of a specific media item based on the provided data. + * + * @param {MediaItem} media - The updated media item data. + * @return {Promise} A promise that resolves once the media item is successfully updated. + * + * @example + * Update a media item + * + * ```ts + * const media = await mediaClient.getMediaItem('my-media-id'); + * media.title = 'My new title'; + * media.description = 'My new description'; + * await mediaClient.updateMediaItem(media); + * ``` + */ async updateMediaItem(media: MediaItem): Promise { await this.sendPutRequest( `${this.config.apiHost}/v3/media/${media.id}`, @@ -59,10 +153,22 @@ export class Media extends Client { mime_type: media.mimeType, max_downloads_allowed: media.maxDownloadsAllowed, }, - 'PUT', ); } + /** + * Deletes a specific media item by its unique identifier. + * + * @param {string} mediaId - The unique identifier of the media item to be deleted. + * @return {Promise} A promise that resolves once the media item is successfully deleted. + * + * @example + * Delete a media item + * + * ```ts + * await mediaClient.deleteMediaItem('my-media-id'); + * ``` + */ async deleteMediaItem(mediaId: string): Promise { await this.sendDeleteRequest(`${this.config.apiHost}/v3/media/${mediaId}`); } diff --git a/packages/media/lib/types/Responses/mediaItemResponse.ts b/packages/media/lib/types/Responses/mediaItemResponse.ts index 3e2537e3..453231e1 100644 --- a/packages/media/lib/types/Responses/mediaItemResponse.ts +++ b/packages/media/lib/types/Responses/mediaItemResponse.ts @@ -1,16 +1,79 @@ -import { MediaItem } from '../mediaItem'; - +/** + * Represents the response data for a media item. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type MediaItemResponse = { - original_file_name: string; - mime_type: string; - account_id: string; - store_id: string; - max_downloads_allowed: number; - times_downloaded: number; - media_size: number; - time_created: string; - time_last_updated: string; + /** + * The filename of the object as it was originally uploaded. + */ + originalFileName: string; + + /** + * The IETF MIME type of the file. + */ + mimeType: string; + + /** + * The ID of your Nexmo account. This is the same as your API key. + */ + accountId: string; + + /** + * An internal identifier of how the file is stored. + */ + storeId: string; + + /** + * The maximum number of times the file may be downloaded. + */ + maxDownloadsAllowed: number; + + /** + * The number of times the file has been downloaded. + */ + timesDownloaded: number; + + /** + * The size of the file in bytes. + */ + mediaSize: number; + + /** + * A timestamp for the time that the file was created. + */ + timeCreated: string; + + /** + * A timestamp for the time that the file was last modified. + */ + timeLastUpdated: string; + + /** + * Whether the item is available for download without authentication. + */ public: boolean; - metadata_primary: string; - metadata_secondary: string; -} & Pick; + + /** + * A user-set string containing metadata about the media file. + */ + metadataPrimary: string; + + /** + * A user-set string containing further metadata about the media file. + */ + metadataSecondary: string; + + /** + * A UUID representing the object. + */ + id: string; + + /** + * An identifier for the content. This will change if the content of the file has been changed + * (i.e., if you upload a new version of the file). For more information, see Wikipedia: HTTP ETag. + */ + etag: string; +}; diff --git a/packages/media/lib/types/Responses/mediaItemResponsePage.ts b/packages/media/lib/types/Responses/mediaItemResponsePage.ts index 9c618fab..40082eda 100644 --- a/packages/media/lib/types/Responses/mediaItemResponsePage.ts +++ b/packages/media/lib/types/Responses/mediaItemResponsePage.ts @@ -1,18 +1,63 @@ import { APILinks, APILink } from '@vonage/server-client'; import { MediaItemResponse } from './mediaItemResponse'; +/** + * Represents the response data for a page of media items. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type MediaItemPageResponse = { + /** + * The amount of records returned in this response. + */ page_size: number; + + /** + * The page_index used in your request. + */ page_index: number; + + /** + * The total number of records returned by your request. + */ count: number; + + /** + * A collection of media items. + */ _embedded: { media: Array; }; + + /** + * Links to navigate through pages. + */ _links: { + /** + * Link to the first page. + */ first?: APILink; + + /** + * Link to the last page. + */ last?: APILink; + + /** + * Link to the next page. + */ next?: APILink; + + /** + * Link to the previous page. + */ prev?: APILink; + + /** + * Link to the start page. + */ start?: APILink; - }; -} & APILinks; + } & APILinks; +}; diff --git a/packages/media/lib/types/mediaItem.ts b/packages/media/lib/types/mediaItem.ts index 521e3404..172c88aa 100644 --- a/packages/media/lib/types/mediaItem.ts +++ b/packages/media/lib/types/mediaItem.ts @@ -1,18 +1,85 @@ +/** + * Represents a media item. + */ export type MediaItem = { + /** + * A UUID representing the object. + */ id: string; + + /** + * An optional title for the media file. + */ title?: string; + + /** + * An optional description of the media file. + */ description?: string; + + /** + * The filename of the object as it was originally uploaded. + */ originalFileName: string; + + /** + * The IETF MIME type of the file. + */ mimeType: string; + + /** + * The ID of your Nexmo account. This is the same as your API key. + */ accountId: string; + + /** + * An internal identifier of how the file is stored. + */ storeId: string; + + /** + * The maximum number of times the file may be downloaded. + */ maxDownloadsAllowed: number; + + /** + * The number of times the file has been downloaded. + */ timesDownloaded: number; + + /** + * An identifier for the content. This will change if the content of the file has been changed + * (i.e., if you upload a new version of the file). For more information, see Wikipedia: HTTP ETag. + */ etag: string; + + /** + * The size of the file in bytes. + */ mediaSize: number; + + /** + * A timestamp for the time that the file was created. + */ timeCreated: string; + + /** + * A timestamp for the time that the file was last modified. + */ timeLastUpdated: string; + + /** + * Whether the item is available for download without authentication. + */ public: boolean; + + /** + * A user-set string containing metadata about the media file. + */ metadataPrimary: string; + + /** + * A user-set string containing further metadata about the media file. + */ metadataSecondary: string; }; diff --git a/packages/media/lib/types/mediaParameters.ts b/packages/media/lib/types/mediaParameters.ts index 7e6173a6..a88a0dbc 100644 --- a/packages/media/lib/types/mediaParameters.ts +++ b/packages/media/lib/types/mediaParameters.ts @@ -1,7 +1,29 @@ +/** + * Represents parameters for querying media items. + */ export type MediaParameters = { + /** + * The order of search results. Must be one of 'ascending' or 'descending'. + */ order?: 'ascending' | 'descending'; + + /** + * Which page to retrieve in pagination. + */ pageIndex?: number; + + /** + * How many items at most per page. + */ pageSize?: number; + + /** + * Retrieve results created on or after this timestamp. + */ startTime?: string; + + /** + * Retrieve results created on or before this timestamp. + */ endTime?: string; }; diff --git a/packages/media/package.json b/packages/media/package.json index 17a47ec6..6cd047a5 100644 --- a/packages/media/package.json +++ b/packages/media/package.json @@ -1,4 +1,5 @@ { + "$schema": "https://json.schemastore.org/package.json", "name": "@vonage/media", "version": "1.1.0", "description": "The Media API can be used to query, download and delete media items such as audio files for use with other Vonage APIs.", @@ -11,7 +12,12 @@ "url": "git+https://github.com/Vonage/vonage-node-sdk.git" }, "license": "Apache-2.0", - "author": "Chuck MANCHUCK Reeves ", + "contributors": [ + { + "name": "Chuck \"MANCHUCK\" Reeves", + "url": "https://github.com/manchuck" + } + ], "main": "dist/index.js", "directories": { "lib": "lib", @@ -21,6 +27,8 @@ "lib" ], "scripts": { + "build": "echo 'Build steps not defined'", + "prepublishOnly": "npm run build", "test": "node ./__tests__/media.test.js" }, "dependencies": { diff --git a/packages/media/tsconfig.json b/packages/media/tsconfig.json new file mode 100644 index 00000000..8e8615aa --- /dev/null +++ b/packages/media/tsconfig.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + + "extends": "../../tsconfig.json", + + "compilerOptions": { + "rootDir": "lib", + "outDir": "dist" + }, + + "exclude": [ + "__tests__", + "dist" + ], + + "references": [ + { "path": "../auth" }, + { "path": "../server-client" }, + { "path": "../vetch" } + ], + + "ts-node": { + "esm": true + } +} diff --git a/packages/media/typedoc.json b/packages/media/typedoc.json new file mode 100644 index 00000000..1e14f0fe --- /dev/null +++ b/packages/media/typedoc.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "extends": ["../../typedoc.base.json"], + "entryPoints": ["lib/index.ts"], + "name": "Vonage Media" +} diff --git a/packages/meetings/__tests__/file.test.ts b/packages/meetings/__tests__/file.test.ts index da1ffe8b..576807b2 100644 --- a/packages/meetings/__tests__/file.test.ts +++ b/packages/meetings/__tests__/file.test.ts @@ -195,22 +195,4 @@ describe('Meetings > File uploads', () => { expect(nock.isDone()).toBeTruthy(); }); - - test('Will throw error when apply fails with no message', async () => { - scope - .get(`/v1/meetings/themes/logos-upload-urls`) - .reply(200, urlResponses) - .put(`/v1/meetings/themes/${themeOne.themeId}/finalizeLogos`, { - keys: [urlResponses[0].fields.key], - }) - .reply(400); - - const awsUrl = new URL(urlResponses[0].url); - awsScope.post(awsUrl.pathname, () => true).reply(204); - await expect(() => - client.uploadIcon(themeOne.themeId, LogoType.WHITE, file), - ).rejects.toThrow(`Could not attach image to theme: FATAL ERROR`); - - expect(nock.isDone()).toBeTruthy(); - }); }); diff --git a/packages/meetings/lib/enums/eventTypes.ts b/packages/meetings/lib/enums/eventTypes.ts index 5fbe3ff6..f3451631 100644 --- a/packages/meetings/lib/enums/eventTypes.ts +++ b/packages/meetings/lib/enums/eventTypes.ts @@ -1,10 +1,44 @@ +/** + * Enum representing different event types. + */ export enum EventType { - 'ROOM_EXPIRED' = 'room:expired', - 'SESSION_STARTED' = 'session:started', - 'SESSION_ENDED' = 'session:ended', - 'RECORDING_STARTED' = 'recording:started', - 'RECORDING_ENDED' = 'recording:ended', - 'RECORDING_READY' = 'recording:ready', - 'SESSION_PARTICIPANT_JOINED' = 'session:participant:joined', - 'SESSION_PARTICIPANT_LEFT' = 'session:participant:left', + /** + * Event type for a room that has expired. + */ + ROOM_EXPIRED = 'room:expired', + + /** + * Event type for the start of a session. + */ + SESSION_STARTED = 'session:started', + + /** + * Event type for the end of a session. + */ + SESSION_ENDED = 'session:ended', + + /** + * Event type for the start of recording. + */ + RECORDING_STARTED = 'recording:started', + + /** + * Event type for the end of recording. + */ + RECORDING_ENDED = 'recording:ended', + + /** + * Event type for a recording that is ready. + */ + RECORDING_READY = 'recording:ready', + + /** + * Event type for a participant joining a session. + */ + SESSION_PARTICIPANT_JOINED = 'session:participant:joined', + + /** + * Event type for a participant leaving a session. + */ + SESSION_PARTICIPANT_LEFT = 'session:participant:left', } diff --git a/packages/meetings/lib/enums/joinType.ts b/packages/meetings/lib/enums/joinType.ts index 76c16d0c..1fc8d5ed 100644 --- a/packages/meetings/lib/enums/joinType.ts +++ b/packages/meetings/lib/enums/joinType.ts @@ -1,5 +1,19 @@ +/** + * Enum representing different join approval levels for a meeting room. + */ export enum JoinType { - 'NONE' = 'none', - 'AFTER_OWNER_ONLY' = 'after_owner_only', - 'EXPLICT_APPROVAL' = 'explicit_approval', + /** + * No approval is required for participants to join. + */ + NONE = 'none', + + /** + * Participants can join only after the owner has joined. + */ + AFTER_OWNER_ONLY = 'after_owner_only', + + /** + * Participants need explicit approval from the host to join. + */ + EXPLICIT_APPROVAL = 'explicit_approval', } diff --git a/packages/meetings/lib/enums/logoType.ts b/packages/meetings/lib/enums/logoType.ts index 0669472f..768155c3 100644 --- a/packages/meetings/lib/enums/logoType.ts +++ b/packages/meetings/lib/enums/logoType.ts @@ -1,5 +1,19 @@ +/** + * Enum representing different types of logos. + */ export enum LogoType { - 'WHITE' = 'white', - 'COLORED' = 'colored', - 'FAVICON' = 'favicon', + /** + * White logo. + */ + WHITE = 'white', + + /** + * Colored logo. + */ + COLORED = 'colored', + + /** + * Favicon logo. + */ + FAVICON = 'favicon', } diff --git a/packages/meetings/lib/enums/meetingType.ts b/packages/meetings/lib/enums/meetingType.ts index f1d32205..2d0f1a0e 100644 --- a/packages/meetings/lib/enums/meetingType.ts +++ b/packages/meetings/lib/enums/meetingType.ts @@ -1,4 +1,16 @@ +/** + * Enum representing different types of meetings. + */ export enum MeetingType { - 'INSTANT' = 'instant', - 'LONG_TERM' = 'long_term', + /** + * Instant meeting type. + * An instant meeting is active for a limited duration. + */ + INSTANT = 'instant', + + /** + * Long-term meeting type. + * A long-term meeting can last for an extended period. + */ + LONG_TERM = 'long_term', } diff --git a/packages/meetings/lib/enums/microphoneState.ts b/packages/meetings/lib/enums/microphoneState.ts index 4ff31f64..eda853d6 100644 --- a/packages/meetings/lib/enums/microphoneState.ts +++ b/packages/meetings/lib/enums/microphoneState.ts @@ -1,5 +1,19 @@ +/** + * Enum representing different states for a microphone. + */ export enum MicrophoneSate { - 'ON' = 'on', - 'OFF' = 'off', - 'DEFAULT' = 'default', + /** + * Microphone is turned on. + */ + ON = 'on', + + /** + * Microphone is turned off. + */ + OFF = 'off', + + /** + * Default microphone state. + */ + DEFAULT = 'default', } diff --git a/packages/meetings/lib/enums/recordingStatus.ts b/packages/meetings/lib/enums/recordingStatus.ts index 89b7946a..999f59c2 100644 --- a/packages/meetings/lib/enums/recordingStatus.ts +++ b/packages/meetings/lib/enums/recordingStatus.ts @@ -1,6 +1,24 @@ +/** + * Enum representing different recording statuses. + */ export enum RecordingStatus { - 'STARTED' = 'started', - 'STOPPED' = 'stopped', - 'PAUSED' = 'paused', - 'UPLOADED' = 'uploaded', + /** + * Recording has started. + */ + STARTED = 'started', + + /** + * Recording has stopped. + */ + STOPPED = 'stopped', + + /** + * Recording is paused. + */ + PAUSED = 'paused', + + /** + * Recording has been uploaded. + */ + UPLOADED = 'uploaded', } diff --git a/packages/meetings/lib/enums/roomLanguage.ts b/packages/meetings/lib/enums/roomLanguage.ts index a5587448..3dcdad9a 100644 --- a/packages/meetings/lib/enums/roomLanguage.ts +++ b/packages/meetings/lib/enums/roomLanguage.ts @@ -1,8 +1,34 @@ +/** + * Enum representing different room languages. + */ export enum RoomLanguage { - 'DEFAULT' = 'default', - 'EN' = 'en', - 'HE' = 'he', - 'ES' = 'es', - 'PT' = 'pt', - 'IT' = 'it', + /** + * Default language for the room. + */ + DEFAULT = 'default', + + /** + * English language. + */ + EN = 'en', + + /** + * Hebrew language. + */ + HE = 'he', + + /** + * Spanish language. + */ + ES = 'es', + + /** + * Portuguese language. + */ + PT = 'pt', + + /** + * Italian language. + */ + IT = 'it', } diff --git a/packages/meetings/lib/enums/themeDomain.ts b/packages/meetings/lib/enums/themeDomain.ts index 972369b3..287bb062 100644 --- a/packages/meetings/lib/enums/themeDomain.ts +++ b/packages/meetings/lib/enums/themeDomain.ts @@ -1,4 +1,14 @@ +/** + * Enum representing different theme domains. + */ export enum ThemeDomain { - 'VCP' = 'VCP', - 'VBC' = 'VBC', + /** + * Theme domain for Vonage Cloud Platform + */ + VCP = 'VCP', + + /** + * Theme domain for Vonage Business Communications + */ + VBC = 'VBC', } diff --git a/packages/meetings/lib/meetings.ts b/packages/meetings/lib/meetings.ts index d7691446..57451f88 100644 --- a/packages/meetings/lib/meetings.ts +++ b/packages/meetings/lib/meetings.ts @@ -1,7 +1,7 @@ import { XMLParser } from 'fast-xml-parser'; import FormData from 'form-data'; import { AuthenticationType, Client } from '@vonage/server-client'; -import { VetchError, HTTPMethods } from '@vonage/vetch'; +import { HTTPMethods, VetchError, VetchOptions } from '@vonage/vetch'; import pick from 'lodash.pick'; import { MeetingRoomPageResponse, @@ -15,30 +15,81 @@ import { Recording, DialInNumber, Theme, -} from './types/index'; +} from './types'; import { LogoType } from './enums'; import { existsSync, readFileSync } from 'fs'; +type MeetingError = { + status: number; + name: string; + message: string; + errors: Array<{ code: string; message: string }>; +}; + +/** + * Converts an API response for a meeting room to the SDK format. + * + * @param {MeetingRoomResponse} room - The meeting room response from the API. + * @return {MeetingRoom} A meeting room object in the SDK format. + */ const apiRoomToSdk = (room: MeetingRoomResponse): MeetingRoom => { + const links = room._links; + delete room._links; + const sdkRoom = { ...Client.transformers.camelCaseObjectKeys(room, true), - hostUrl: room._links?.host_url?.href, - guestUrl: room?._links?.guest_url?.href, + hostUrl: links?.host_url?.href, + guestUrl: links?.guest_url?.href, }; - delete sdkRoom.links; - return sdkRoom; -}; -const apiRecordingToSdk = (recording: RecordingResponse): Recording => ({ - ...Client.transformers.camelCaseObjectKeys(recording), - url: recording?._links?.url?.href, -}); + return sdkRoom as MeetingRoom; +}; +/** + * Converts an API response for a recording to the SDK format. + * + * @param {RecordingResponse} recording - The recording response from the API. + * @return {Recording} A recording object in the SDK format. + */ +const apiRecordingToSdk = (recording: RecordingResponse): Recording => + ({ + ...Client.transformers.camelCaseObjectKeys(recording), + url: recording?._links?.url?.href, + }) as Recording; + +/** + * Client class to interact with the Meetings API to create and manage meeting rooms. + * + * @remarks + * This client is only available as a standalone client. It cannot be + * instantiated from the server-sdk package. + * + * @example + * Create a standalone Meetings Client + * + * ```ts + * import { Meetings } from '@vonage/meetings'; + * + * const meetingsClient = new Meetings({ + * apiKey: VONAGE_API_KEY, + * apiSecret: VONAGE_API_SECRET, + * applicationId: VONAGE_APPLICATION_ID, + * privateKey: VONAGE_APPLICATION_PRIVATE_KEY_PATH + * }); + * ``` + */ export class Meetings extends Client { - protected authType = AuthenticationType.JWT; - public FORM_BOUNDARY = '-------------------------Vonage-Node_SDK'; + authType = AuthenticationType.JWT; + + /** + * Used to keep the form boundary consistent when uploading files + */ + FORM_BOUNDARY = '-------------------------Vonage-Node_SDK'; - public ROOM_WRITE_KEYS = [ + /** + * List of properties from the room that can be written + */ + ROOM_WRITE_KEYS = [ 'display_name', 'metadata', 'type', @@ -57,13 +108,35 @@ export class Meetings extends Client { 'available_features.is_whiteboard_available', ]; - public THEME_WRITE_KEYS = [ + /** + * List of properties from the theme that can be written + */ + THEME_WRITE_KEYS = [ 'theme_name', 'main_color', 'brand_text', 'short_company_url', ]; + /** + * Retrieves a list of meeting rooms until there are no more pages + * + * @param {MeetingRoomParams} params - Optional parameters for pagination. + * @return {AsyncGenerator} An async generator of meeting rooms. + * + * @example + * Generate a list of meeting rooms + * + * ```ts + * + * for await (const room of meetingsClient.getRooms()) { + * console.log(`Room ${room.id} has ${room.participants} participants`); + * console.log(`Room ${room.id} has ${room.sessions} sessions`); + * console.log(`Room ${room.id} has ${room.recordings} recordings`); + * console.log(`Room ${room.id} has ${room.members} members`); + * } + * ``` + */ async *getRooms( params: MeetingRoomParams = {}, ): AsyncGenerator { @@ -89,6 +162,31 @@ export class Meetings extends Client { } while (startId); } + /** + * Retrieves a page of meeting rooms based on the provided parameters. + * + * @param {MeetingRoomParams} params - Optional parameters for pagination. + * @return {Promise} A promise that resolves to a page of meeting rooms. + * + * @example + * Get a page of meeting rooms + * + * ```ts + * const resp = await meetingsClient.getRoomPage(); + * console.log(`There are ${resp.totalItems} meeting rooms`); + * console.log(`There are ${resp.pageSize} meeting rooms per page`); + * ``` + * + * @example + * Get a specific page of meeting rooms + * + * ```ts + * const resp = await meetingsClient.getRoomPage({pageSize: 10, pageNumber: 2}); + * console.log(`There are ${resp.totalItems} meeting rooms`); + * console.log(`There are ${resp.pageSize} meeting rooms per page`); + * ``` + * + */ async getRoomPage( params: MeetingRoomParams = {}, ): Promise { @@ -100,6 +198,23 @@ export class Meetings extends Client { return resp.data; } + /** + * Retrieves a meeting room by its ID. + * + * @param {string} roomId - The ID of the meeting room to retrieve. + * @return {Promise} A promise that resolves to the meeting room. + * + * @example + * Get a meeting room by ID + * + * ```ts + * const room = await meetingsClient.getRoom('my-room-id'); + * console.log(`Room ${room.id} has ${room.participants} participants`); + * console.log(`Room ${room.id} has ${room.members} members`); + * console.log(`Room ${room.id} has ${room.sessions} sessions`); + * console.log(`Room ${room.id} has ${room.recordings} recordings`); + * ``` + */ async getRoom(roomId: string): Promise { const resp = await this.sendGetRequest( `${this.config.meetingsHost}/v1/meetings/rooms/${roomId}`, @@ -108,6 +223,25 @@ export class Meetings extends Client { return apiRoomToSdk(resp.data); } + /** + * Creates a new meeting room. + * + * @param {MeetingRoom} room - The meeting room object to create. + * @return {Promise} A promise that resolves to the created meeting room. + * + * @example + * Create a new meeting room + * + * ```ts + * const room = await meetingsClient.createRoom({ + * displayName: 'My Room', + * metadata: { + * my_data: 'my_value' + * } + * }); + * console.log(`Created room with ID ${room.id}`); + * ``` + */ async createRoom(room: MeetingRoom): Promise { const resp = await this.sendPostRequest( `${this.config.meetingsHost}/v1/meetings/rooms`, @@ -120,6 +254,26 @@ export class Meetings extends Client { return apiRoomToSdk(resp.data); } + /** + * Updates an existing meeting room. + * + * @param {string} roomId - The ID of the meeting room to update. + * @param {MeetingRoom} room - The meeting room object with updated information. + * @return {Promise} A promise that resolves to the updated meeting room. + * + * @example + * Update a meeting room + * + * ```ts + * const room = await meetingsClient.updateRoom('my-room-id', { + * displayName: 'My Room', + * metadata: { + * my_data: 'my_value' + * } + * }); + * console.log(`Updated room with ID ${room.id}`); + * ``` + */ async updateRoom(roomId: string, room: MeetingRoom): Promise { const resp = await this.sendPatchRequest( `${this.config.meetingsHost}/v1/meetings/rooms/${roomId}`, @@ -134,6 +288,21 @@ export class Meetings extends Client { return apiRoomToSdk(resp.data); } + /** + * Retrieves a recording by its ID. + * + * @param {string} recordingId - The ID of the recording to retrieve. + * @return {Promise} A promise that resolves to the recording. + * + * @example + * Get a recording by ID + * + * ```ts + * const recording = await meetingsClient.getRecording('my-recording-id'); + * console.log(`Recording ${recording.id} started at ${recording.startedAt}`); + * console.log(`Recording ${recording.id} ended at ${recording.endedAt}`); + * ``` + */ async getRecording(recordingId: string): Promise { const resp = await this.sendGetRequest( `${this.config.meetingsHost}/v1/meetings/recordings/${recordingId}`, @@ -142,6 +311,27 @@ export class Meetings extends Client { return apiRecordingToSdk(resp.data); } + /** + * Retrieves recordings associated with a session by its ID until there are no + * more recordings + * + * @remarks + * All the recordings will be returned in one request. There could be a large + * number of recordings. + * + * @param {string} sessionId - The ID of the session for which to retrieve recordings. + * @return {AsyncGenerator} An async generator that yields recordings associated with the session. + * + * @example + * Get recordings for a session + * + * ```ts + * for await (const recording of meetingsClient.getSessionRecordings('my-session-id')) { + * console.log(`Recording ${recording.id} started at ${recording.startedAt}`); + * console.log(`Recording ${recording.id} ended at ${recording.endedAt}`); + * } + * ``` + */ async *getSessionRecordings( sessionId: string, ): AsyncGenerator { @@ -156,12 +346,43 @@ export class Meetings extends Client { yield* recordings; } + /** + * Deletes a recording by its ID. + * + * @param {string} recordingId - The ID of the recording to delete. + * @return {Promise} A promise that resolves when the recording is successfully deleted. + * + * @example + * Delete a recording by ID + * + * ```ts + * await meetingsClient.deleteRecording('my-recording-id'); + * console.log(`Recording with ID ${recordingId} has been deleted`); + * ``` + */ async deleteRecording(recordingId: string): Promise { await this.sendDeleteRequest( `${this.config.meetingsHost}/v1/meetings/recordings/${recordingId}`, ); } + /** + * Retrieves a list of dial-in numbers. + * + * @remarks + * All numbers will be returned in one request + * + * @return {AsyncGenerator} An asynchronous generator that yields dial-in numbers. + * + * @example + * Get a list of dial-in numbers + * + * ```ts + * for await (const number of meetingsClient.getDialInNumbers()) { + * console.log(`Dial-in number ${number.number} is in ${number.country}`); + * } + * ``` + */ async *getDialInNumbers(): AsyncGenerator< DialInNumber, void & DialInNumber, @@ -171,41 +392,107 @@ export class Meetings extends Client { `${this.config.meetingsHost}/v1/meetings/dial-in-numbers`, ); - const numbers = (resp.data || []).map((number) => - Client.transformers.camelCaseObjectKeys(number, false), + const numbers = (resp.data || []).map( + (number: DialInNumber): DialInNumber => + Client.transformers.camelCaseObjectKeys(number, false) as DialInNumber, ); yield* numbers; } + /** + * Retrieves a list of themes. + * + * @remarks + * All themes are returned in one request + * + * @return {AsyncGenerator} An asynchronous generator that yields themes. + * + * @example + * Get a list of getThemes + * ```ts + * for await (const theme of meetingsClient.getThemes()) { + * console.log(`Theme ${theme.themeName} has ID ${theme.id}`); + * } + * ``` + */ async *getThemes(): AsyncGenerator { const resp = await this.sendGetRequest( `${this.config.meetingsHost}/v1/meetings/themes`, ); - const themes = (resp.data || []).map((theme) => - Client.transformers.camelCaseObjectKeys(theme, false), + const themes = (resp.data || []).map( + (theme: ThemeResponse): Theme => + Client.transformers.camelCaseObjectKeys(theme, false) as Theme, ); yield* themes; } + /** + * Retrieves a theme by its theme ID. + * + * @param {string} themeId - The ID of the theme to retrieve. + * @return {Promise} A Promise that resolves to the retrieved theme. + * + * @example + * Get a theme by ID + * + * ```ts + * const theme = await meetingsClient.getTheme('my-theme-id'); + * console.log(`Theme ${theme.themeName} has ID ${theme.id}`); + * ``` + */ async getTheme(themeId: string): Promise { const resp = await this.sendGetRequest( `${this.config.meetingsHost}/v1/meetings/themes/${themeId}`, ); - return Client.transformers.camelCaseObjectKeys(resp.data); + return Client.transformers.camelCaseObjectKeys(resp.data) as Theme; } - async deleteTheme(themeId: string, force = false): Promise { + /** + * Deletes a theme by its theme ID. + * + * @param {string} themeId - The ID of the theme to delete. + * @param {boolean} [force=false] - Whether to force the deletion even if it's associated with rooms. + * @return {Promise} A Promise that resolves when the theme is successfully deleted. + * + * @example + * Delete a theme by ID + * + * ```ts + * await meetingsClient.deleteTheme('my-theme-id'); + * console.log(`Theme with ID ${themeId} has been deleted`); + * ``` + */ + async deleteTheme(themeId: string, force: boolean = false): Promise { await this.sendRequest({ url: `${this.config.meetingsHost}/v1/meetings/themes/${themeId}`, - params: force ? { force: true } : null, method: HTTPMethods.DELETE, - }); + ...(force ? { params: { force: 'true' } } : {}), + } as VetchOptions); } + /** + * Creates a new theme with the provided theme details. + * + * @param {Theme} theme - The theme details to create. + * @return {Promise} A Promise that resolves with the created theme. + * + * @example + * Create a new themes + * + * ```ts + * const theme = await meetingsClient.createTheme({ + * themeName: 'My Theme', + * mainColor: '#C0FFEE', + * brandText: 'My Brand', + * shortCompanyUrl: 'my-brand' + * }); + * console.log(`Created theme with ID ${theme.id}`); + * ``` + */ async createTheme(theme: Theme): Promise { const resp = await this.sendPostRequest( `${this.config.meetingsHost}/v1/meetings/themes`, @@ -215,9 +502,29 @@ export class Meetings extends Client { ), ); - return Client.transformers.camelCaseObjectKeys(resp.data); + return Client.transformers.camelCaseObjectKeys(resp.data) as Theme; } + /** + * Updates an existing theme with the provided theme details. + * + * @param {string} themeId - The ID of the theme to update. + * @param {Theme} theme - The updated theme details. + * @return {Promise} A Promise that resolves with the updated theme. + * + * @example + * Update a theme + * + * ```ts + * const theme = await meetingsClient.updateTheme('my-theme-id', { + * themeName: 'My Theme', + * mainColor: '#C0FFEE', + * brandText: 'My Brand', + * shortCompanyUrl: 'my-brand' + * }); + * console.log(`Updated theme with ID ${theme.id}`); + * ``` + */ async updateTheme(themeId: string, theme: Theme): Promise { const resp = await this.sendPatchRequest( `${this.config.meetingsHost}/v1/meetings/themes/${themeId}`, @@ -229,9 +536,31 @@ export class Meetings extends Client { }, ); - return Client.transformers.camelCaseObjectKeys(resp.data); + return Client.transformers.camelCaseObjectKeys(resp.data) as Theme; } + /** + * Retrieves a list of meeting rooms associated with a specific theme. This will + * keep calling the API until there are no more pages + * + * @param {string} themeId - The ID of the theme for which to retrieve meeting rooms. + * @param {MeetingRoomParams} params - Optional parameters to filter and paginate the results. + * @return {AsyncGenerator} An async generator that yields meeting rooms associated with the theme. + * + * @example + * Get meeting rooms for a theme + * + * ```ts + * for await (const room of meetingsClient.getRoomsForTheme('my-theme-id')) { + * console.log(`Room ${room.id} has ${room.participants} participants`); + * console.log(`Room ${room.id} has ${room.sessions} sessions`); + * console.log(`Room ${room.id} has ${room.recordings} recordings`); + * console.log(`Room ${room.id} has ${room.members} members`); + * } + * ``` + * + * + */ async *getRoomsForTheme( themeId: string, params: MeetingRoomParams = {}, @@ -256,6 +585,31 @@ export class Meetings extends Client { } while (startId); } + /** + * Retrieves a page of meeting rooms associated with a specific theme. + * + * @param {string} themeId - The ID of the theme for which to retrieve meeting rooms. + * @param {MeetingRoomParams} params - Optional parameters to filter and paginate the results. + * @return {Promise} A promise that resolves to a page of meeting rooms associated with the theme. + * + * @example + * Get a page of meeting rooms for a theme + * + * ```ts + * const resp = await meetingsClient.getRoomsForThemePage('my-theme-id'); + * console.log(`There are ${resp.totalItems} meeting rooms`); + * console.log(`There are ${resp.pageSize} meeting rooms per page`); + * ``` + * + * @example + * Get a specific page of meeting rooms for a theme + * + * ```ts + * const resp = await meetingsClient.getRoomsForThemePage('my-theme-id', {pageSize: 10, pageNumber: 2}); + * console.log(`There are ${resp.totalItems} meeting rooms`); + * console.log(`There are ${resp.pageSize} meeting rooms per page`); + * ``` + */ async getRoomsForThemePage( themeId: string, params: MeetingRoomParams = {}, @@ -268,6 +622,20 @@ export class Meetings extends Client { return resp.data; } + /** + * Sets the default theme for the application. + * + * @param {string} themeId - The ID of the theme to set as the default theme. + * @return {Promise} A promise that resolves to `true` when the default theme is set successfully. + * + * @example + * Set the default theme + * + * ```ts + * await meetingsClient.setDefaultTheme('my-theme-id'); + * console.log(`Default theme has been set`); + * ``` + */ async setDefaultTheme(themeId: string): Promise { await this.sendPatchRequest( `${this.config.meetingsHost}/v1/meetings/applications`, @@ -281,6 +649,30 @@ export class Meetings extends Client { return true; } + /** + * Uploads an icon (logo) to a theme. + * + * @remarks + * To add icons and logos to a theme, they first need to be uploaded to the + * Meetings API AWS bucket, and then paired with the respective theme. You + * should also ensure that your Logos and Favicons adhere to the Image. + * + * @see Uploading Icons and Logos {@link https://developer.vonage.com/en/meetings/guides/upload-icons-logo} + * + * @param {string} themeId - The ID of the theme to which the icon will be attached. + * @param {LogoType} logo - The type of logo to upload (e.g., LogoType.WHITE, LogoType.COLORED). + * @param {string} logoFile - The file path of the logo to upload. + * @return {Promise} A promise that resolves to `true` when the icon is uploaded and attached to the theme successfully. + * @throws {Error} If the file specified by `logoFile` does not exist or if the upload fails. + * + * @example + * Upload an icon to a theme + * + * ```ts + * await meetingsClient.uploadIcon('my-theme-id', LogoType.WHITE, '/path/to/white-logo.png'); + * console.log(`Icon has been uploaded`); + * ``` + */ async uploadIcon( themeId: string, logo: LogoType, @@ -294,7 +686,7 @@ export class Meetings extends Client { await this._uploadToAws(urlResponse, logoFile); - let error; + let message = 'FATAL ERROR'; try { await this.sendPutRequest( `${this.config.meetingsHost}/v1/meetings/themes/${themeId}/finalizeLogos`, @@ -304,15 +696,29 @@ export class Meetings extends Client { ); return true; - } catch (apiError: unknown | VetchError) { - error = apiError; + } catch (apiError: VetchError | unknown) { + if (apiError instanceof Error) { + message = apiError.message; + } + + if (apiError instanceof VetchError) { + const errorJson = (await apiError?.response?.json()) as MeetingError; + const errors = errorJson?.errors || []; + message = errors[0]?.code || 'FATAL ERROR'; + } } - const errors = error?.response?.data?.errors || []; - const message = errors[0]?.code || 'FATAL ERROR'; throw new Error(`Could not attach image to theme: ${message}`); } + /** + * Uploads a file to an AWS S3 bucket using the provided URL and fields. + * + * @param {UrlResponse} urlResponse - The URL and fields required for the AWS S3 upload. + * @param {string} logoFile - The file path of the file to upload. + * @return {Promise} A promise that resolves to `true` when the file is successfully uploaded to AWS S3. + * @throws {Error} If the upload fails or encounters an error. + */ protected async _uploadToAws( { url, fields }: UrlResponse, logoFile: string, @@ -324,24 +730,38 @@ export class Meetings extends Client { } awsForm.append('file', readFileSync(logoFile)); - let error; + let message; try { await this.sendRequest({ url: url, - body: awsForm, + data: awsForm.toString(), method: HTTPMethods.POST, - }); + } as VetchOptions); return true; - } catch (apiError: unknown | VetchError) { - error = apiError; + } catch (apiError: VetchError | unknown) { + if (apiError instanceof Error) { + message = apiError.message; + } + + if (apiError instanceof VetchError) { + const errorResponse + = ((await apiError?.response?.text()) as string) || ''; + const parser = new XMLParser(); + const output = parser.parse(errorResponse); + message = output?.Error?.Message; + } } - const errorResponse = error?.response?.data; - const parser = new XMLParser(); - const output = parser.parse(errorResponse); - throw new Error(`Failed to upload to AWS: ${output?.Error?.Message}`); + throw new Error(`Failed to upload to AWS: ${message}`); } + /** + * Retrieves the URL for uploading an icon (logo) to the specified LogoType. + * + * @param {LogoType} logo - The LogoType for which the upload URL is requested. + * @return {Promise} A promise that resolves to the URLResponse containing the upload URL and fields. + * @throws {Error} If the upload URL retrieval fails or encounters an error. + */ protected async _getIconUploadUrl(logo: LogoType): Promise { const resp = await this.sendGetRequest( `${this.config.meetingsHost}/v1/meetings/themes/logos-upload-urls`, diff --git a/packages/meetings/lib/types/availableFeatures.ts b/packages/meetings/lib/types/availableFeatures.ts index 7914a957..ffc34184 100644 --- a/packages/meetings/lib/types/availableFeatures.ts +++ b/packages/meetings/lib/types/availableFeatures.ts @@ -1,7 +1,29 @@ +/** + * Represents available features for a meeting room. + */ export type AvailableFeatures = { + /** + * Indicates if recording feature is available in the UI. + */ isRecordingAvailable?: boolean; + + /** + * Indicates if chat feature is available in the UI. + */ isChatAvailable?: boolean; + + /** + * Indicates if whiteboard feature is available in the UI. + */ isWhiteboardAvailable?: boolean; + + /** + * Indicates if the locale switcher is available in the UI. + */ isLocaleSwitcherAvailable?: boolean; + + /** + * Indicates if captions are available in the UI. + */ isCaptionsAvailable?: boolean; }; diff --git a/packages/meetings/lib/types/dialInNumber.ts b/packages/meetings/lib/types/dialInNumber.ts index 23341a47..517bf429 100644 --- a/packages/meetings/lib/types/dialInNumber.ts +++ b/packages/meetings/lib/types/dialInNumber.ts @@ -1,5 +1,19 @@ +/** + * Represents a dial-in number with associated information. + */ export type DialInNumber = { - number: string - locale: string - displayName: string -} + /** + * The phone number for dialing in. + */ + number: string; + + /** + * The locale or region associated with the dial-in number. + */ + locale: string; + + /** + * The display name or label for the dial-in number. + */ + displayName: string; +}; diff --git a/packages/meetings/lib/types/events/index.ts b/packages/meetings/lib/types/events/index.ts new file mode 100644 index 00000000..73d245b3 --- /dev/null +++ b/packages/meetings/lib/types/events/index.ts @@ -0,0 +1,6 @@ +export * from './recordingEndedEvent'; +export * from './recordingReadyEvent'; +export * from './recordingStartedEvent'; +export * from './roomExpiredEvent'; +export * from './sessionEndedEvent'; +export * from './sessionStartedEvent'; diff --git a/packages/meetings/lib/types/events/recordingEndedEvent.ts b/packages/meetings/lib/types/events/recordingEndedEvent.ts new file mode 100644 index 00000000..264f73ff --- /dev/null +++ b/packages/meetings/lib/types/events/recordingEndedEvent.ts @@ -0,0 +1,45 @@ +import { EventType } from '../../enums'; + +/** + * Represents an event for recording ended. + * + * @remarks + * The SDK does not have any functionality for process incoming webhook events. + * The types are provided here to help with code completion and TS Compiling + */ +export type RecordingEnded = { + /** + * The type of event, which is 'recording:ended'. + */ + event: EventType.RECORDING_ENDED; + + /** + * The unique identifier for the recording. + */ + recording_id: string; + + /** + * The unique identifier for the session associated with the recording. + */ + session_id: string; + + /** + * The date and time when the recording started. + */ + started_at: string; + + /** + * The date and time when the recording ended. + */ + ended_at: string; + + /** + * The duration of the recording in seconds. + */ + duration: number; +} + +/** + * @deprecated Exported as interface in error. Please use RecordingEnded + */ +export interface RecordingEndedInterface extends RecordingEnded {} diff --git a/packages/meetings/lib/types/events/recordingReadyEvent.ts b/packages/meetings/lib/types/events/recordingReadyEvent.ts new file mode 100644 index 00000000..5d7bf3a4 --- /dev/null +++ b/packages/meetings/lib/types/events/recordingReadyEvent.ts @@ -0,0 +1,55 @@ +import { EventType } from '../../enums'; + +/** + * Represents an event type for recording readiness. + * + * @remarks + * The SDK does not have any functionality for process incoming webhook events. + * The types are provided here to help with code completion and TS Compiling + */ +export type RecordingReady = { + /** + * The type of event, which is 'recording:ready'. + */ + event: EventType.RECORDING_READY; + + /** + * The unique identifier for the recording. + */ + recording_id: string; + + /** + * The unique identifier for the session associated with the recording. + */ + session_id: string; + + /** + * The unique identifier for the room associated with the recording. + */ + room_id: string; + + /** + * The date and time when the recording started. + */ + started_at: string; + + /** + * The date and time when the recording ended. + */ + ended_at: string; + + /** + * The duration of the recording in seconds. + */ + duration: number; + + /** + * The URL where the recording can be accessed. + */ + url: string; +} + +/** + * @deprecated Exported as interface in error. Please use RecordingReady + */ +export interface RecordingReadyInterface extends RecordingReady {} diff --git a/packages/meetings/lib/types/events/recordingStartedEvent.ts b/packages/meetings/lib/types/events/recordingStartedEvent.ts new file mode 100644 index 00000000..8e5846e8 --- /dev/null +++ b/packages/meetings/lib/types/events/recordingStartedEvent.ts @@ -0,0 +1,30 @@ +import { EventType } from '../../enums'; + +/** + * Represents an event for recording started. + * + * @remarks + * The SDK does not have any functionality for process incoming webhook events. + * The types are provided here to help with code completion and TS Compiling + */ +export type RecordingStarted = { + /** + * The type of event, which is 'recording:started'. + */ + event: EventType.RECORDING_STARTED; + + /** + * The unique identifier for the recording. + */ + recording_id: string; + + /** + * The unique identifier for the session associated with the recording. + */ + session_id: string; +} + +/** + * @deprecated Exported as interface in error. Please use RecordingStarted + */ +export interface RecordingStartedInterface extends RecordingStarted {} diff --git a/packages/meetings/lib/types/events/roomExpiredEvent.ts b/packages/meetings/lib/types/events/roomExpiredEvent.ts new file mode 100644 index 00000000..c35a984c --- /dev/null +++ b/packages/meetings/lib/types/events/roomExpiredEvent.ts @@ -0,0 +1,41 @@ +import { EventType, MeetingType } from '../../enums'; + +/** + * Represents an event for a room expiration. + * + * @remarks + * The SDK does not have any functionality for process incoming webhook events. + * The types are provided here to help with code completion and TS Compiling + */ +export type RoomExpired = { + /** + * The type of event, which is 'room:expired'. + */ + event: EventType.ROOM_EXPIRED; + + /** + * The unique identifier for the room. + */ + room_id: string; + + /** + * The type of meeting associated with the room. + */ + room_type: MeetingType; + + /** + * The date and time when the room will expire, expressed in ISO 8601 format. + * The value must be greater than 10 minutes from now. + */ + expires_at: string; + + /** + * The date and time when the room was created, expressed in ISO 8601 format. + */ + created_at: string; +} + +/** + * @deprecated Exported as interface in error. Please use RoomExpired + */ +export interface RoomExpiredInterface extends RoomExpired {} diff --git a/packages/meetings/lib/types/events/sessionEndedEvent.ts b/packages/meetings/lib/types/events/sessionEndedEvent.ts new file mode 100644 index 00000000..ac5e1275 --- /dev/null +++ b/packages/meetings/lib/types/events/sessionEndedEvent.ts @@ -0,0 +1,40 @@ +import { EventType } from '../../enums'; + +/** + * Represents an event for a session ending. + * + * @remarks + * The SDK does not have any functionality for process incoming webhook events. + * The types are provided here to help with code completion and TS Compiling + */ +export type SessionEnded = { + /** + * The type of event, which is 'session:ended'. + */ + event: EventType.SESSION_ENDED; + + /** + * The unique identifier for the session. + */ + session_id: string; + + /** + * The unique identifier for the room associated with the session. + */ + room_id: string; + + /** + * The date and time when the session started. + */ + started_at: string; + + /** + * The date and time when the session ended. + */ + ended_at: string; +} + +/** + * @deprecated Exported as interface in error. Please use SessionEnded + */ +export interface SessionEndedInterface extends SessionEnded {} diff --git a/packages/meetings/lib/types/events/sessionStartedEvent.ts b/packages/meetings/lib/types/events/sessionStartedEvent.ts new file mode 100644 index 00000000..31de3fe3 --- /dev/null +++ b/packages/meetings/lib/types/events/sessionStartedEvent.ts @@ -0,0 +1,35 @@ +import { EventType } from '../../enums'; + +/** + * Represents an event for a session starting. + * + * @remarks + * The SDK does not have any functionality for process incoming webhook events. + * The types are provided here to help with code completion and TS Compiling + */ +export type SessionStarted = { + /** + * The type of event, which is 'session:started'. + */ + event: EventType.SESSION_STARTED; + + /** + * The unique identifier for the session. + */ + session_id: string; + + /** + * The unique identifier for the room associated with the session. + */ + room_id: string; + + /** + * The date and time when the session started. + */ + started_at: string; +} + +/** + * @deprecated Exported as interface in error. Please use SessionStarted + */ +export interface SessionStartedInterface extends SessionStarted {} diff --git a/packages/meetings/lib/types/index.ts b/packages/meetings/lib/types/index.ts index f489906f..afce6d4b 100644 --- a/packages/meetings/lib/types/index.ts +++ b/packages/meetings/lib/types/index.ts @@ -3,13 +3,8 @@ export * from './dialInNumber'; export * from './meetingRoom'; export * from './meetingRoomParams'; export * from './recording'; -export * from './recordingEndedEvent'; +export * from './events'; export * from './recordingOptions'; -export * from './recordingReadyEvent'; -export * from './recordingStartedEvent'; export * from './response/index'; export * from './roomCallbackURLS'; -export * from './roomExpiredEvent'; -export * from './sessionEndedEvent'; -export * from './sessionStartedEvent'; export * from './theme'; diff --git a/packages/meetings/lib/types/meetingRoom.ts b/packages/meetings/lib/types/meetingRoom.ts index 4031f639..2aa22efd 100644 --- a/packages/meetings/lib/types/meetingRoom.ts +++ b/packages/meetings/lib/types/meetingRoom.ts @@ -5,30 +5,110 @@ import { MeetingType, JoinType, RoomLanguage, -} from '../enums/index'; -import { RoomCallbackURLS } from '../types/roomCallbackURLS'; +} from '../enums'; +import { RoomCallbackURLS } from './roomCallbackURLS'; +/** + * Represents a meeting room with associated properties. + */ export type MeetingRoom = { + /** + * The unique identifier for the meeting room. + */ id?: string; + + /** + * The display name or label for the meeting room. + */ displayName: string; + + /** + * Additional metadata or information about the meeting room. + */ metadata?: string; + + /** + * The type of meeting, which can be instant or long term. + */ type: MeetingType; + + /** + * Options related to recording meetings in the room. + */ recordingOptions?: RecordingOptions; + + /** + * The meeting PIN number or code. + */ meetingCode?: string; + + /** + * Indicates whether the meeting room is available for use. + */ isAvailable?: boolean; + + /** + * The unique identifier for the theme associated with the meeting room. + */ themeId?: string; + + /** + * The date and time when the meeting room was created. + */ createdAt?: string; + + /** + * The date and time when the meeting room will expire. + */ expiresAt?: string; + + /** + * Indicates whether the room should expire after use (only relevant for long-term rooms). + */ expireAfterUse?: boolean; + + /** + * The level of approval needed to join the meeting in the room. + */ joinApprovalLevel?: JoinType; + + /** + * Options for participants when they initially join the room. + */ initialJoinOptions?: { + /** + * The default microphone state for users in the pre-join screen of this room. + */ microphoneState?: MicrophoneSate; }; + + /** + * Callback URLs for various room-related events. + */ callbackUrls?: RoomCallbackURLS; + + /** + * Available features for the meeting room's user interface. + */ availableFeatures: AvailableFeatures; + + /** + * User interface settings for the meeting room. + */ uiSettings?: { + /** + * The desired language of the UI. + */ language?: RoomLanguage; }; + + /** + * The URL for joining the meeting room as a host. + */ hostUrl?: string; + + /** + * The URL for joining the meeting room as a guest. + */ guestUrl?: string; }; diff --git a/packages/meetings/lib/types/meetingRoomParams.ts b/packages/meetings/lib/types/meetingRoomParams.ts index e935610d..5b17a6a2 100644 --- a/packages/meetings/lib/types/meetingRoomParams.ts +++ b/packages/meetings/lib/types/meetingRoomParams.ts @@ -1,5 +1,19 @@ +/** + * Represents parameters for querying meeting rooms. + */ export type MeetingRoomParams = { - pageSize?: number - startId?: string - endId?: string -} + /** + * The maximum number of items to retrieve per page. + */ + pageSize?: number; + + /** + * The starting identifier for filtering meeting rooms. + */ + startId?: string; + + /** + * The ending identifier for filtering meeting rooms. + */ + endId?: string; +}; diff --git a/packages/meetings/lib/types/recording.ts b/packages/meetings/lib/types/recording.ts index aa7d9b7b..2282b02e 100644 --- a/packages/meetings/lib/types/recording.ts +++ b/packages/meetings/lib/types/recording.ts @@ -1,10 +1,36 @@ -import { RecordingStatus } from '../enums/index'; +import { RecordingStatus } from '../enums'; +/** + * Represents a recording with associated properties. + */ export type Recording = { - id: string - sessionId: string - startedAt: string - endedAt: string - status: RecordingStatus - url: string -} + /** + * The unique identifier for the recording. + */ + id: string; + + /** + * The unique identifier for the session associated with the recording. + */ + sessionId: string; + + /** + * The date and time when the recording started. + */ + startedAt: string; + + /** + * The date and time when the recording ended. + */ + endedAt: string; + + /** + * The status of the recording. + */ + status: RecordingStatus; + + /** + * The URL where the recording can be accessed. + */ + url: string; +}; diff --git a/packages/meetings/lib/types/recordingEndedEvent.ts b/packages/meetings/lib/types/recordingEndedEvent.ts deleted file mode 100644 index a8f5db86..00000000 --- a/packages/meetings/lib/types/recordingEndedEvent.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { EventType } from '../enums'; - -export interface RecordingEndedInterface { - event: EventType.RECORDING_ENDED - recording_id: string - session_id: string - started_at: string - ended_at: string - duration: number -} diff --git a/packages/meetings/lib/types/recordingOptions.ts b/packages/meetings/lib/types/recordingOptions.ts index 1820d7ee..029a25e3 100644 --- a/packages/meetings/lib/types/recordingOptions.ts +++ b/packages/meetings/lib/types/recordingOptions.ts @@ -1,4 +1,14 @@ +/** + * Represents options for recording a meeting. + */ export type RecordingOptions = { - autoRecord: boolean - recordOnlyOwner: boolean -} + /** + * Indicates whether recording should be automatically started for all sessions. + */ + autoRecord: boolean; + + /** + * Indicates whether recording should be limited to the owner's screen or any shared screen. + */ + recordOnlyOwner: boolean; +}; diff --git a/packages/meetings/lib/types/recordingReadyEvent.ts b/packages/meetings/lib/types/recordingReadyEvent.ts deleted file mode 100644 index fe5446f5..00000000 --- a/packages/meetings/lib/types/recordingReadyEvent.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { EventType } from '../enums'; - -export interface RecordingReadyInterface { - event: EventType.RECORDING_ENDED - recording_id: string - session_id: string - room_id: string - started_at: string - ended_at: string - duration: number - url: string -} diff --git a/packages/meetings/lib/types/recordingStartedEvent.ts b/packages/meetings/lib/types/recordingStartedEvent.ts deleted file mode 100644 index eb778984..00000000 --- a/packages/meetings/lib/types/recordingStartedEvent.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { EventType } from '../enums'; - -export interface RecordingStartedInterface { - event: EventType.RECORDING_STARTED - recording_id: string - session_id: string -} diff --git a/packages/meetings/lib/types/response/defaultThemeResponse.ts b/packages/meetings/lib/types/response/defaultThemeResponse.ts index ced4e1e0..1f731313 100644 --- a/packages/meetings/lib/types/response/defaultThemeResponse.ts +++ b/packages/meetings/lib/types/response/defaultThemeResponse.ts @@ -1,5 +1,19 @@ +/** + * Represents the response containing default theme information. + */ export type DefaultThemeResponse = { - application_id: string - account_id: string - default_theme_id: string -} + /** + * The application ID associated with the default theme. + */ + application_id: string; + + /** + * The account ID associated with the default theme. + */ + account_id: string; + + /** + * The ID of the default theme. + */ + default_theme_id: string; +}; diff --git a/packages/meetings/lib/types/response/meetingRoomPageResponse.ts b/packages/meetings/lib/types/response/meetingRoomPageResponse.ts index 76ae5ad4..b45a06ba 100644 --- a/packages/meetings/lib/types/response/meetingRoomPageResponse.ts +++ b/packages/meetings/lib/types/response/meetingRoomPageResponse.ts @@ -1,9 +1,22 @@ -import { APILinks, APILink } from '@vonage/server-client'; +import { APILinks } from '@vonage/server-client'; import { MeetingRoomResponse } from './meetingRoomResponse'; +/** + * Represents the response for a page of meeting rooms. + */ export type MeetingRoomPageResponse = { - page_size: number - total_items: number - _embedded: Array - _links: APILinks & { next?: APILink; prev?: APILink; start?: APILink } -} + /** + * The number of meeting rooms on the page. + */ + page_size: number; + + /** + * The total number of meeting rooms across all pages. + */ + total_items: number; + + /** + * An array of meeting room responses embedded within the page. + */ + _embedded: Array; +} & APILinks; diff --git a/packages/meetings/lib/types/response/meetingRoomResponse.ts b/packages/meetings/lib/types/response/meetingRoomResponse.ts index 5ff0c1a9..de117cae 100644 --- a/packages/meetings/lib/types/response/meetingRoomResponse.ts +++ b/packages/meetings/lib/types/response/meetingRoomResponse.ts @@ -2,42 +2,192 @@ import { APILink, APILinks } from '@vonage/server-client'; import { MeetingRoom } from '../../types'; import { JoinType, MicrophoneSate, RoomLanguage } from '../../enums'; +/** + * Represents recording options for a meeting room. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase` + */ +export type RecordingOptionsResponse = { + /** + * Indicates whether to automatically record all sessions in this room. + */ + auto_record: boolean; + + /** + * Indicates whether to record only the owner's screen or any shared screen during video. + */ + record_owner_only: boolean; +}; + +/** + * Represents the default options for participants when joining a meeting room. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase` + */ +export type InitialJoinOptionsResponse = { + /** + * The default microphone state for users in the pre-join screen of this room. + */ + microphone_state: MicrophoneSate; +}; + +/** + * Represents callback URLs for events related to a meeting room. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase` + */ +export type CallbackUrlsResponse = { + /** + * Callback URL for rooms events, overrides application-level rooms callback URL. + */ + rooms_callback_url: string; + + /** + * Callback URL for sessions events, overrides application-level sessions callback URL. + */ + sessions_callback_url: string; + + /** + * Callback URL for recordings events, overrides application-level recordings callback URL. + */ + recordings_callback_url: string; +}; + +/** + * Represents available features in the user interface of a meeting room. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase` + */ +export type AvailableFeaturesResponse = { + /** + * Determine if the recording feature is available in the UI. + */ + is_recording_available: boolean; + + /** + * Determine if the chat feature is available in the UI. + */ + is_chat_available: boolean; + + /** + * Determine if the whiteboard feature is available in the UI. + */ + is_whiteboard_available: boolean; + + /** + * Determine if the locale switcher is available in the UI. + */ + is_locale_switcher_available: boolean; + + /** + * Determine if captions are available in the UI. + */ + is_captions_available: boolean; +}; + +/** + * Represents user interface settings for a meeting room. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase` + */ +export type UiSettingsResponse = { + /** + * The desired language of the user interface. + */ + language: RoomLanguage; +}; + +/** + * Represents the response structure for a meeting room. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase` + */ export type MeetingRoomResponse = { + /** + * The display name of the meeting room. + */ display_name: string; - recording_options: { - auto_record: boolean; - record_owner_only: boolean; - }; + + /** + * Recording options for the meeting room. + */ + recording_options: RecordingOptionsResponse; + + /** + * The meeting PIN. + */ meeting_code: string; + + /** + * Indicates whether the meeting room is available. + */ is_available: boolean; + + /** + * The theme UUID associated with the meeting room. + */ theme_id: string; + + /** + * The time when the meeting room was created, expressed in ISO 8601 format. + */ created_at: string; + + /** + * The time for when the room will expire, expressed in ISO 8601 format. + */ expires_at: string; + + /** + * Indicates whether to expire the room after a session ends. + */ expire_after_use: string; + + /** + * The level of approval needed to join the meeting in the room. + */ join_approval_level: JoinType; - initial_join_options: { - microphone_state: MicrophoneSate; - }; - callback_urls: { - rooms_callback_url: string; - sessions_callback_url: string; - recordings_callback_url: string; - }; - available_features: { - is_recording_available: boolean; - is_chat_available: boolean; - is_whiteboard_available: boolean; - is_locale_switcher_available: boolean; - is_captions_available: boolean; - }; - ui_settings: { - language: RoomLanguage; - }; - _links: { + + /** + * Default options for participants joining the room. + */ + initial_join_options: InitialJoinOptionsResponse; + + /** + * Callback URLs for events related to the room. + */ + callback_urls: CallbackUrlsResponse; + + /** + * Available features in the meeting room's user interface. + */ + available_features: AvailableFeaturesResponse; + + /** + * User interface settings for the meeting room. + */ + ui_settings: UiSettingsResponse; + + /** + * Links for guest and host URLs to join the meeting room. + */ + _links?: { guest_url: APILink; host_url: APILink; }; -} & Omit< +} & APILinks & Omit< MeetingRoom, | 'displayName' | 'recordingOptions' @@ -52,4 +202,4 @@ export type MeetingRoomResponse = { | 'callbackUrls' | 'availableFeatures' | 'uiSettings' ->; + >; diff --git a/packages/meetings/lib/types/response/recordingResponse.ts b/packages/meetings/lib/types/response/recordingResponse.ts index 02848a61..e03b8e80 100644 --- a/packages/meetings/lib/types/response/recordingResponse.ts +++ b/packages/meetings/lib/types/response/recordingResponse.ts @@ -1,13 +1,46 @@ import { APILink } from '@vonage/server-client'; -import { RecordingStatus } from '../../enums/index'; +import { RecordingStatus } from '../../enums'; +/** + * Represents a response for a recording. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase` + */ export type RecordingResponse = { - id: string - session_id: string - started_at: string - ended_at: string - status: RecordingStatus - _links: { - url: APILink - } -} + /** + * The ID of the recording. + */ + id: string; + + /** + * The session ID corresponding to the recording. + */ + session_id: string; + + /** + * The date when the recording started, expressed in ISO 8601 format. + */ + started_at: string; + + /** + * The date when the recording ended, expressed in ISO 8601 format. + */ + ended_at: string; + + /** + * The current status of the recording. + */ + status: RecordingStatus; + + /** + * Links for accessing the recording URL. + */ + _links: { + /** + * The URL to access the recording. + */ + url: APILink; + }; +}; diff --git a/packages/meetings/lib/types/response/recordingResponsePage.ts b/packages/meetings/lib/types/response/recordingResponsePage.ts index d694c4f3..7ed31dae 100644 --- a/packages/meetings/lib/types/response/recordingResponsePage.ts +++ b/packages/meetings/lib/types/response/recordingResponsePage.ts @@ -1,7 +1,16 @@ import { RecordingResponse } from './recordingResponse'; +/** + * Represents a response page containing an array of recording responses. + */ export type RecordingResponsePage = { - _embedded: { - recordings: RecordingResponse[] - } -} + /** + * An object containing an array of recording responses embedded within the page. + */ + _embedded: { + /** + * An array of recording responses. + */ + recordings: RecordingResponse[]; + }; +}; diff --git a/packages/meetings/lib/types/response/themeResponse.ts b/packages/meetings/lib/types/response/themeResponse.ts index e33e94b4..880bab56 100644 --- a/packages/meetings/lib/types/response/themeResponse.ts +++ b/packages/meetings/lib/types/response/themeResponse.ts @@ -1,3 +1,3 @@ -import { Theme } from '../../types/index'; +import { Theme } from '../theme'; export type ThemeResponse = Theme diff --git a/packages/meetings/lib/types/response/urlResponse.ts b/packages/meetings/lib/types/response/urlResponse.ts index e2872766..79a041db 100644 --- a/packages/meetings/lib/types/response/urlResponse.ts +++ b/packages/meetings/lib/types/response/urlResponse.ts @@ -1,17 +1,71 @@ -import { LogoType } from '../../enums/index'; +import { LogoType } from '../../enums'; +/** + * Represents a response containing URL and associated fields for an image. + * + * @remarks + * Uploading a theme requires fetching a singed URL form AWS. The SDK handles + * this process for you so there should be no need to use the type. It is included + * for convenience. + */ export type UrlResponse = { - url: string - fields: { - 'Content-Type': 'image/png' - key: string - logoType: LogoType - bucket: string - 'X-Amz-Algorithm': string - 'X-Amz-Credential': string - 'X-Amz-Date': string - 'X-Amz-Security-Token': string - Policy: string - 'X-Amz-Signature': string - } -} + /** + * The URL for the image. + */ + url: string; + + /** + * Fields related to the image URL. + */ + fields: { + /** + * The content type of the image, typically 'image/png'. + */ + 'Content-Type': 'image/png'; + + /** + * The key associated with the image. + */ + key: string; + + /** + * The logo type of the image. + */ + logoType: LogoType; + + /** + * The bucket where the image is stored. + */ + bucket: string; + + /** + * The AWS S3 algorithm used for access. + */ + 'X-Amz-Algorithm': string; + + /** + * The AWS S3 credential for access. + */ + 'X-Amz-Credential': string; + + /** + * The date associated with the image access. + */ + 'X-Amz-Date': string; + + /** + * The security token for AWS access. + */ + 'X-Amz-Security-Token': string; + + /** + * The policy associated with image access. + */ + Policy: string; + + /** + * The AWS S3 signature for image access. + */ + 'X-Amz-Signature': string; + }; +}; diff --git a/packages/meetings/lib/types/roomCallbackURLS.ts b/packages/meetings/lib/types/roomCallbackURLS.ts index dda6d201..73c4165b 100644 --- a/packages/meetings/lib/types/roomCallbackURLS.ts +++ b/packages/meetings/lib/types/roomCallbackURLS.ts @@ -1,5 +1,19 @@ +/** + * Represents callback URLs for various room-related events. + */ export type RoomCallbackURLS = { - roomsCallbackUrl: string - sessionsCallbackUrl: string - recordingsCallbackUrl: string -} + /** + * The callback URL for rooms events. + */ + roomsCallbackUrl: string; + + /** + * The callback URL for sessions events. + */ + sessionsCallbackUrl: string; + + /** + * The callback URL for recordings events. + */ + recordingsCallbackUrl: string; +}; diff --git a/packages/meetings/lib/types/roomExpiredEvent.ts b/packages/meetings/lib/types/roomExpiredEvent.ts deleted file mode 100644 index 9c2bfc1f..00000000 --- a/packages/meetings/lib/types/roomExpiredEvent.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { EventType, MeetingType } from '../enums'; - -export interface RoomExpiredInterface { - event: EventType.ROOM_EXPIRED - room_id: string - room_type: MeetingType - expires_at: string - created_at: string -} diff --git a/packages/meetings/lib/types/sessionEndedEvent.ts b/packages/meetings/lib/types/sessionEndedEvent.ts deleted file mode 100644 index 020009fe..00000000 --- a/packages/meetings/lib/types/sessionEndedEvent.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { EventType } from '../enums'; - -export interface SessionEndedInterface { - event: EventType.SESSION_ENDED - session_id: string - room_id: string - started_at: string - ended_at: string -} diff --git a/packages/meetings/lib/types/sessionStartedEvent.ts b/packages/meetings/lib/types/sessionStartedEvent.ts deleted file mode 100644 index 2613c789..00000000 --- a/packages/meetings/lib/types/sessionStartedEvent.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { EventType } from '../enums'; - -export interface SessionStartedInterface { - event: EventType.SESSION_STARTED - session_id: string - room_id: string - started_at: string -} diff --git a/packages/meetings/lib/types/theme.ts b/packages/meetings/lib/types/theme.ts index 9cd88f59..68f4d55e 100644 --- a/packages/meetings/lib/types/theme.ts +++ b/packages/meetings/lib/types/theme.ts @@ -1,18 +1,76 @@ -import { ThemeDomain } from '../enums/index'; +import { ThemeDomain } from '../enums'; +/** + * Represents a theme configuration for meeting rooms. + */ export type Theme = { - themeId?: string - themeName?: string - domain?: ThemeDomain - accountId?: string - applicationId?: string - mainColor: string - shortCompanyUrl?: string - brandText: string - brandImageColored?: string - brandImageWhite?: string - brandedFavicon?: string - brandImageWhiteUrl?: string - brandImageColoredUrl?: string - brandedFaviconUrl?: string -} + /** + * The unique identifier for the theme. + */ + themeId?: string; + + /** + * The name of the theme (must be unique). If null, a UUID will automatically be generated. + */ + themeName?: string; + + /** + * The domain of the theme, which must be one of 'VCP' or 'VBC'. + */ + domain?: ThemeDomain; + + /** + * The application's account ID (ApiKey). + */ + accountId?: string; + + /** + * The application ID. + */ + applicationId?: string; + + /** + * The main color that will be used for the meeting room. + */ + mainColor: string; + + /** + * The URL that will represent every meeting room with this theme. The value must be unique across Vonage. + */ + shortCompanyUrl?: string; + + /** + * The text that will appear on the meeting homepage, in the case that there is no brand image. + */ + brandText: string; + + /** + * Colored logo's key in the storage system. + */ + brandImageColored?: string; + + /** + * White logo's key in the storage system. + */ + brandImageWhite?: string; + + /** + * Favicon key in the storage system. + */ + brandedFavicon?: string; + + /** + * Colored logo's link. + */ + brandImageColoredUrl?: string; + + /** + * White logo's link. + */ + brandImageWhiteUrl?: string; + + /** + * Favicon link. + */ + brandedFaviconUrl?: string; +}; diff --git a/packages/meetings/package.json b/packages/meetings/package.json index 8c085a28..95865983 100644 --- a/packages/meetings/package.json +++ b/packages/meetings/package.json @@ -1,4 +1,5 @@ { + "$schema": "https://json.schemastore.org/package.json", "name": "@vonage/meetings", "version": "1.5.0", "description": "Vonage Meetings Management API", @@ -11,7 +12,16 @@ "url": "git+https://github.com/Vonage/vonage-node-sdk.git" }, "license": "Apache-2.0", - "author": "Chuck MANCHUCK Reeves ", + "contributors": [ + { + "name": "Chuck \"MANCHUCK\" Reeves", + "url": "https://github.com/manchuck" + }, + { + "name": "Chris Tankersley", + "url": "https://github.com/dragonmantank" + } + ], "main": "dist/index.js", "types": "dist/index.d.ts", "directories": { @@ -24,18 +34,20 @@ "scripts": { "build": "npm run clean && npm run compile", "clean": "npx shx rm -rf dist tsconfig.tsbuildinfo", - "compile": "npx tsc --build --verbose" + "compile": "npx tsc --build --verbose", + "prepublishOnly": "npm run build" }, "dependencies": { + "@types/lodash.pick": "4.4.8", "@vonage/server-client": "^1.9.0", "@vonage/vetch": "^1.6.0", "fast-xml-parser": "^4.3.2", - "form-data": "^4.0.0", - "lodash.pick": "^4.4.0" + "form-data": "^4.0.0" }, "devDependencies": { "@amvijay/multipart-parser": "^1.0.2", "@vonage/auth": "^1.7.0", + "lodash.pick": "4.4.0", "nock": "^13.3.4" } } diff --git a/packages/meetings/tsconfig.json b/packages/meetings/tsconfig.json index e9b438f7..8e8615aa 100644 --- a/packages/meetings/tsconfig.json +++ b/packages/meetings/tsconfig.json @@ -1,24 +1,25 @@ { - "extends": "../../tsconfig.json", + "$schema": "https://json.schemastore.org/tsconfig", - "compilerOptions": { - "rootDir": "lib", - "outDir": "dist" - }, + "extends": "../../tsconfig.json", - "exclude": [ - "__tests__", - "jest.config.js", - "dist" - ], + "compilerOptions": { + "rootDir": "lib", + "outDir": "dist" + }, - "references": [ - { "path": "../auth" }, - { "path": "../server-client" }, - { "path": "../vetch" } - ], + "exclude": [ + "__tests__", + "dist" + ], - "ts-node": { - "esm": true - } + "references": [ + { "path": "../auth" }, + { "path": "../server-client" }, + { "path": "../vetch" } + ], + + "ts-node": { + "esm": true + } } diff --git a/packages/meetings/typedoc.json b/packages/meetings/typedoc.json new file mode 100644 index 00000000..4866345c --- /dev/null +++ b/packages/meetings/typedoc.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "extends": ["../../typedoc.base.json"], + "entryPoints": ["lib/index.ts"], + "name": "Vonage Meetings" +} diff --git a/packages/messages/__tests__/__dataSets__/viber.ts b/packages/messages/__tests__/__dataSets__/viber.ts index 0604c789..c62f5932 100644 --- a/packages/messages/__tests__/__dataSets__/viber.ts +++ b/packages/messages/__tests__/__dataSets__/viber.ts @@ -139,7 +139,7 @@ export default [ '14152739164', // to '12126875309', // from { - category: MessageCategory.PROMOTINO, + category: MessageCategory.PROMOTION, ttl: 42, type: 'type', }, diff --git a/packages/messages/lib/classes/AbstractAudioMessage.ts b/packages/messages/lib/classes/AbstractAudioMessage.ts index 768bcd14..992bbd26 100644 --- a/packages/messages/lib/classes/AbstractAudioMessage.ts +++ b/packages/messages/lib/classes/AbstractAudioMessage.ts @@ -1,15 +1,22 @@ import { AbstractMessage } from './AbstractMessage'; -import { MessageAudioInterface } from '../interfaces'; import { MessageParamsAudio } from '../types'; import { MessageAudioType } from '../types'; +/** + * An abstract base class for audio messages. + */ export abstract class AbstractAudioMessage extends AbstractMessage - implements MessageAudioInterface + implements MessageParamsAudio { public messageType: 'audio'; public audio: MessageAudioType; + /** + * Constructs a new `AbstractAudioMessage` instance. + * + * @param {MessageParamsAudio} params - The parameters for creating an audio message. + */ public constructor(params: MessageParamsAudio) { super(params); this.audio = params.audio; diff --git a/packages/messages/lib/classes/AbstractFileMessage.ts b/packages/messages/lib/classes/AbstractFileMessage.ts index 78234015..bd86bb83 100644 --- a/packages/messages/lib/classes/AbstractFileMessage.ts +++ b/packages/messages/lib/classes/AbstractFileMessage.ts @@ -1,14 +1,21 @@ import { AbstractMessage } from './AbstractMessage'; -import { MessageFileInterface } from '../interfaces'; import { MessageFileType, MessageParamsFile } from '../types'; +/** + * An abstract base class for file messages. + */ export abstract class AbstractFileMessage extends AbstractMessage - implements MessageFileInterface + implements MessageParamsFile { public messageType: 'file'; public file: MessageFileType; + /** + * Constructs a new `AbstractFileMessage` instance. + * + * @param {MessageParamsFile} params - The parameters for creating a file message. + */ protected constructor(params: MessageParamsFile) { super(params); this.file = params.file; diff --git a/packages/messages/lib/classes/AbstractImageMessage.ts b/packages/messages/lib/classes/AbstractImageMessage.ts index e714bbd1..173e42df 100644 --- a/packages/messages/lib/classes/AbstractImageMessage.ts +++ b/packages/messages/lib/classes/AbstractImageMessage.ts @@ -1,15 +1,22 @@ -import { MessageImageInterface } from '../interfaces'; import { AbstractMessage } from './AbstractMessage'; import { MessageImageType } from '../types'; import { MessageParamsImage } from '../types'; +/** + * An abstract base class for image messages. + */ export abstract class AbstractImageMessage extends AbstractMessage - implements MessageImageInterface + implements MessageParamsImage { public messageType: 'image'; public image: MessageImageType; + /** + * Constructs a new `AbstractImageMessage` instance. + * + * @param {MessageParamsImage} params - The parameters for creating an image message. + */ constructor(params: MessageParamsImage) { super(params); this.image = params.image; diff --git a/packages/messages/lib/classes/AbstractMessage.ts b/packages/messages/lib/classes/AbstractMessage.ts index 4d1556c7..d4a72477 100644 --- a/packages/messages/lib/classes/AbstractMessage.ts +++ b/packages/messages/lib/classes/AbstractMessage.ts @@ -1,11 +1,29 @@ -import { MessageInterface } from '../interfaces'; import { MessageParams } from '../types'; -export abstract class AbstractMessage implements MessageInterface { +/** + * An abstract base class for message objects. + */ +export abstract class AbstractMessage implements MessageParams { + /** + * The recipient of the message. + */ public to: string; + + /** + * The sender of the message. + */ public from: string; + + /** + * An optional client reference for the message. + */ public clientRef?: string; + /** + * Constructs a new `AbstractMessage` instance. + * + * @param {MessageParams} params - The parameters for creating a message. + */ public constructor(params: MessageParams) { this.to = params.to; this.from = params.from; diff --git a/packages/messages/lib/classes/AbstractTextMessage.ts b/packages/messages/lib/classes/AbstractTextMessage.ts index f8254ba3..0c60c6dc 100644 --- a/packages/messages/lib/classes/AbstractTextMessage.ts +++ b/packages/messages/lib/classes/AbstractTextMessage.ts @@ -1,14 +1,28 @@ import { AbstractMessage } from './AbstractMessage'; -import { MessageTextInterface } from '../interfaces'; import { MessageParamsText } from '../types'; +/** + * An abstract base class for text message objects. + */ export abstract class AbstractTextMessage extends AbstractMessage - implements MessageTextInterface + implements MessageParamsText { + /** + * The type of message, which is 'text' for text messages. + */ public messageType: 'text'; + + /** + * The text content of the message. + */ public text: string; + /** + * Constructs a new `AbstractTextMessage` instance for text messages. + * + * @param {MessageParamsText} params - The parameters for creating a text message. + */ constructor(params: MessageParamsText) { super(params); this.text = params.text; diff --git a/packages/messages/lib/classes/AbstractVcardMessage.ts b/packages/messages/lib/classes/AbstractVcardMessage.ts index cae2796b..61de51cb 100644 --- a/packages/messages/lib/classes/AbstractVcardMessage.ts +++ b/packages/messages/lib/classes/AbstractVcardMessage.ts @@ -1,15 +1,29 @@ import { AbstractMessage } from './AbstractMessage'; -import { MessageVCardInterface } from '../interfaces'; import { MessageVcardType } from '../types'; import { MessageParamsVcard } from '../types'; +/** + * An abstract base class for vCard (contact card) message objects. + */ export abstract class AbstractVcardMessage extends AbstractMessage - implements MessageVCardInterface + implements MessageParamsVcard { - public vcard: MessageVcardType; + /** + * The type of message, which is 'vcard' for vCard messages. + */ public messageType: 'vcard'; + /** + * The vCard (contact card) content of the message. + */ + public vcard: MessageVcardType; + + /** + * Constructs a new `AbstractVcardMessage` instance for vCard messages. + * + * @param {MessageParamsVcard} params - The parameters for creating a vCard message. + */ constructor(params: MessageParamsVcard) { super(params); this.vcard = params.vcard; diff --git a/packages/messages/lib/classes/AbstractVideoMessage.ts b/packages/messages/lib/classes/AbstractVideoMessage.ts index b838b1af..58aaa399 100644 --- a/packages/messages/lib/classes/AbstractVideoMessage.ts +++ b/packages/messages/lib/classes/AbstractVideoMessage.ts @@ -1,15 +1,29 @@ import { AbstractMessage } from './AbstractMessage'; import { MessageVideoType } from '../types'; -import { MessageVideoInterface } from '../interfaces'; import { MessageParamsVideo } from '../types'; +/** + * An abstract base class for video message objects. + */ export abstract class AbstractVideoMessage extends AbstractMessage - implements MessageVideoInterface + implements MessageParamsVideo { + /** + * The type of message, which is 'video' for video messages. + */ public messageType: 'video'; + + /** + * The video content of the message. + */ public video: MessageVideoType; + /** + * Constructs a new `AbstractVideoMessage` instance for video messages. + * + * @param {MessageParamsVideo} params - The parameters for creating a video message. + */ constructor(params: MessageParamsVideo) { super(params); this.video = params.video; diff --git a/packages/messages/lib/classes/MMS/Audio.ts b/packages/messages/lib/classes/MMS/Audio.ts index 5a0d0c00..95f43425 100644 --- a/packages/messages/lib/classes/MMS/Audio.ts +++ b/packages/messages/lib/classes/MMS/Audio.ts @@ -6,9 +6,21 @@ import debug from 'debug'; const log = debug('vonage:messages:mms'); /** - * @deprecated please use MMSAudio instead + * Represents an audio message for the MMS channel. + * + * @deprecated Please use the MMSAudio class instead. + * + * @group MMS */ export class Audio extends MMSAudio { + /** + * Constructs a new `Audio` instance for the MMS channel. + * + * @param {AudioObject} audio - The audio content of the message. + * @param {string} to - The recipient of the message. + * @param {string} from - The sender of the message. + * @param {string} clientRef - The client reference for the message. + */ public constructor( audio: AudioObject, to?: string, diff --git a/packages/messages/lib/classes/MMS/Image.ts b/packages/messages/lib/classes/MMS/Image.ts index a393eeae..e694e448 100644 --- a/packages/messages/lib/classes/MMS/Image.ts +++ b/packages/messages/lib/classes/MMS/Image.ts @@ -6,9 +6,21 @@ import debug from 'debug'; const log = debug('vonage:messages:mms'); /** - * @deprecated please use MMSImage instead + * Represents an image message for the MMS channel. + * + * @deprecated Please use the MMSImage class instead. + * + * @group MMS */ export class Image extends MMSImage { + /** + * Constructs a new `Image` instance for the MMS channel. + * + * @param {ImageObject} image - The image content of the message. + * @param {string} to - The recipient of the message. + * @param {string} from - The sender of the message. + * @param {string} clientRef - The client reference for the message. + */ constructor( image: ImageObject, to?: string, diff --git a/packages/messages/lib/classes/MMS/MMSAudio.ts b/packages/messages/lib/classes/MMS/MMSAudio.ts index 1539d519..9305b4b0 100644 --- a/packages/messages/lib/classes/MMS/MMSAudio.ts +++ b/packages/messages/lib/classes/MMS/MMSAudio.ts @@ -1,13 +1,38 @@ import { AbstractAudioMessage } from '../AbstractAudioMessage'; -import { MMSAudioInterface } from '../../interfaces'; import { MessageParamsAudio } from '../../types'; +/** + * Represents an audio message for the MMS channel. + * + * @group MMS + */ export class MMSAudio extends AbstractAudioMessage - implements MMSAudioInterface + implements MessageParamsAudio { public channel: 'mms'; + /** + * Send an MMS audio message. + * + * @param {MessageParamsAudio} params - The parameters for creating the audio message. + * + * @example + * ```ts + * import { MMSAudio } from '@vonage/messages'; + * + * const { messageUUID } = await messagesClient.send(new MMSAudio({ + * to: TO_NUMBER, + * from: FROM_NUMBER, + * audio: { + * url: 'https://example.com/audio.mp3', + * }, + * clientRef: 'my-personal-reference', + * })); + * + * console.log(`Message sent successfully with UUID ${messageUUID}`); + * ``` + */ public constructor(params: MessageParamsAudio) { super(params); this.channel = 'mms'; diff --git a/packages/messages/lib/classes/MMS/MMSImage.ts b/packages/messages/lib/classes/MMS/MMSImage.ts index 590731f6..57241af3 100644 --- a/packages/messages/lib/classes/MMS/MMSImage.ts +++ b/packages/messages/lib/classes/MMS/MMSImage.ts @@ -1,13 +1,38 @@ -import { MMSImageInterface } from '../../interfaces'; import { AbstractImageMessage } from '../AbstractImageMessage'; import { MessageParamsImage } from '../../types'; +/** + * Represents an image message for the MMS channel. + * + * @group MMS + */ export class MMSImage extends AbstractImageMessage - implements MMSImageInterface + implements MessageParamsImage { public channel: 'mms'; + /** + * Send an MMS image message. + * + * @param {MessageParamsImage} params - The parameters for creating the image message. + * @example + * ```ts + * import { MMSImage } from '@vonage/messages'; + * + * const { messageUUID } = await messagesClient.send(new MMSImage({ + * to: TO_NUMBER, + * from: FROM_NUMBER, + * image: { + * url: 'https://example.com/image.jpg', + * caption: 'This is an example image', + * }, + * clientRef: 'my-personal-reference', + * })); + * + * console.log(`Message sent successfully with UUID ${messageUUID}`); + * ``` + */ constructor(params: MessageParamsImage) { super(params); this.channel = 'mms'; diff --git a/packages/messages/lib/classes/MMS/MMSVcard.ts b/packages/messages/lib/classes/MMS/MMSVcard.ts index 11894744..d87329b6 100644 --- a/packages/messages/lib/classes/MMS/MMSVcard.ts +++ b/packages/messages/lib/classes/MMS/MMSVcard.ts @@ -1,13 +1,38 @@ import { AbstractVcardMessage } from '../AbstractVcardMessage'; -import { MMSVcardInterface } from '../../interfaces'; import { MessageParamsVcard } from '../../types'; +/** + * Represents a vCard message for the MMS channel. + * + * @group MMS + */ export class MMSVcard extends AbstractVcardMessage - implements MMSVcardInterface + implements MessageParamsVcard { public channel: 'mms'; + /** + * Send an MMS vCard message. + * + * @param {MessageParamsVcard} params - The parameters for creating the vCard message. + * @example + * ```ts + * import { MMSVcard } from '@vonage/messages'; + * + * const { messageUUID } = await messagesClient.send(new MMSVcard({ + * to: TO_NUMBER, + * from: FROM_NUMBER, + * vcard: { + * name: 'John Doe', + * phoneNumber: '15555555555', + * }, + * clientRef: 'my-personal-reference', + * })); + * + * console.log(`Message sent successfully with UUID ${messageUUID}`); + * ``` + */ constructor(params: MessageParamsVcard) { super(params); this.channel = 'mms'; diff --git a/packages/messages/lib/classes/MMS/MMSVideo.ts b/packages/messages/lib/classes/MMS/MMSVideo.ts index ca722e6b..d1909c2a 100644 --- a/packages/messages/lib/classes/MMS/MMSVideo.ts +++ b/packages/messages/lib/classes/MMS/MMSVideo.ts @@ -1,13 +1,37 @@ import { AbstractVideoMessage } from '../AbstractVideoMessage'; -import { MMSVideoInterface } from '../../interfaces'; import { MessageParamsVideo } from '../../types'; +/** + * Represents a video message for the MMS channel. + * + * @group MMS + */ export class MMSVideo extends AbstractVideoMessage - implements MMSVideoInterface + implements MessageParamsVideo { public channel: 'mms'; + /** + * Send an MMS video message. + * + * @param {MessageParamsVideo} params - The parameters for creating the video message. + * @example + * ```ts + * import { MMSVideo } from '@vonage/messages'; + * + * const { messageUUID } = await messagesClient.send(new MMSVideo({ + * to: TO_NUMBER, + * from: FROM_NUMBER, + * video: { + * url: 'https://example.com/video.mp4', + * }, + * clientRef: 'my-personal-reference', + * })); + * + * console.log(`Message sent successfully with UUID ${messageUUID}`); + * ``` + */ constructor(params: MessageParamsVideo) { super(params); this.channel = 'mms'; diff --git a/packages/messages/lib/classes/MMS/Vcard.ts b/packages/messages/lib/classes/MMS/Vcard.ts index eca0770c..fbe670cc 100644 --- a/packages/messages/lib/classes/MMS/Vcard.ts +++ b/packages/messages/lib/classes/MMS/Vcard.ts @@ -4,9 +4,19 @@ import debug from 'debug'; const log = debug('vonage:messages:mms'); /** - * @deprecated Please use MMSVcard intead + * @deprecated Please use MMSVcard instead + * + * @group MMS */ export class Vcard extends MMSVcard { + /** + * Constructs a new `Vcard` instance for the MMS channel. + * + * @param {string} vcardUrl - The URL of the vCard. + * @param {string} to - The recipient of the message. + * @param {string} from - The sender of the message. + * @param {string} clientRef - The client reference for the message. + */ constructor( vcardUrl: string, to: string, diff --git a/packages/messages/lib/classes/MMS/Video.ts b/packages/messages/lib/classes/MMS/Video.ts index 125a27fd..ad0e4696 100644 --- a/packages/messages/lib/classes/MMS/Video.ts +++ b/packages/messages/lib/classes/MMS/Video.ts @@ -7,6 +7,8 @@ const log = debug('vonage:messages:mms'); /** * @deprecated please use MMSVideo instead + * + * @group MMS */ export class Video extends MMSVideo { constructor( diff --git a/packages/messages/lib/classes/Messenger/Audio.ts b/packages/messages/lib/classes/Messenger/Audio.ts index 7dbd6e31..9f94708b 100644 --- a/packages/messages/lib/classes/Messenger/Audio.ts +++ b/packages/messages/lib/classes/Messenger/Audio.ts @@ -1,5 +1,4 @@ -import { MessengerCategory } from '../../enums'; -import { AudioObject } from '../../interfaces/AudioObject'; +import { AudioObject } from '../../interfaces'; import { MessageType } from '../../interfaces/Messenger/MessageType'; import { MessageAudioType, @@ -12,9 +11,21 @@ import debug from 'debug'; const log = debug('vonage:messages:messenger'); /** - * @deprecated please use MessengerAudio instead + * @deprecated please use the MessengerAudio class instead + * + * @group Messenger */ export class Audio extends MessengerAudio { + /** + * @deprecated Please use MessengerAudio instead. + * Represents an audio message for the Messenger platform. + * + * @param {AudioObject} audio - The audio object containing the audio URL and an optional caption. + * @param {string} to - The recipient's ID. + * @param {string} from - The sender's ID. + * @param {MessageType} messenger - The Messenger message type and category. + * @param {string} clientRef - An optional client reference. + */ constructor( audio: AudioObject, to: string, @@ -28,8 +39,8 @@ export class Audio extends MessengerAudio { to: to, from: from, messenger: { - category: messenger.category as unknown as MessengerCategory, - tag: messenger.tag, + category: messenger?.category, + tag: messenger?.tag, } as MessengerType, clientRef: clientRef, } as MessengerAudioParams); diff --git a/packages/messages/lib/classes/Messenger/File.ts b/packages/messages/lib/classes/Messenger/File.ts index 50a34e20..34e6f8af 100644 --- a/packages/messages/lib/classes/Messenger/File.ts +++ b/packages/messages/lib/classes/Messenger/File.ts @@ -1,4 +1,3 @@ -import { MessengerCategory } from '../../enums'; import { FileObject } from '../../interfaces/FileObject'; import { MessageType } from '../../interfaces/Messenger/MessageType'; import { MessengerType } from '../../types'; @@ -8,9 +7,20 @@ import debug from 'debug'; const log = debug('vonage:messages:messenger'); /** - * @deprecated please use MessengerFile instead + * @deprecated please use the MessengerFile class instead + * + * @group Messenger */ export class File extends MessengerFile { + /** + * Constructs a new `File` instance. + * + * @param {FileObject} file - The file object containing the URL and optional caption. + * @param {string} to - The recipient's ID. + * @param {string} from - The sender's ID. + * @param {MessageType} messenger - The messenger object specifying the message category and tag. + * @param {string} clientRef - The client reference. + */ constructor( file: FileObject, to: string, @@ -24,8 +34,8 @@ export class File extends MessengerFile { to: to, from: from, messenger: { - category: messenger.category as unknown as MessengerCategory, - tag: messenger.tag, + category: messenger?.category, + tag: messenger?.tag, } as MessengerType, clientRef: clientRef, }); diff --git a/packages/messages/lib/classes/Messenger/Image.ts b/packages/messages/lib/classes/Messenger/Image.ts index ca6f5ba6..e5878150 100644 --- a/packages/messages/lib/classes/Messenger/Image.ts +++ b/packages/messages/lib/classes/Messenger/Image.ts @@ -1,17 +1,26 @@ -import { MessengerCategory } from '../../enums'; -import { ImageObject } from '../../interfaces/ImageObject'; +import { ImageObject } from '../../interfaces'; import { MessageType } from '../../interfaces/Messenger/MessageType'; import { MessengerType } from '../../types'; -import { AbstractImageMessage } from '../AbstractImageMessage'; import { MessengerImage } from './MessengerImage'; import debug from 'debug'; const log = debug('vonage:messages:messenger'); /** - * @deprecated please use MessengerImage instead + * @deprecated please use MessengerImage class instead + * + * @group Messenger */ export class Image extends MessengerImage { + /** + * Constructs a new `Image` instance. + * + * @param {ImageObject} image - The image object containing the URL and optional caption. + * @param {string} to - The recipient's ID. + * @param {string} from - The sender's ID. + * @param {MessageType} messenger - The messenger object specifying the message category and tag. + * @param {string} clientRef - The client reference. + */ constructor( image: ImageObject, to: string, @@ -25,8 +34,8 @@ export class Image extends MessengerImage { to: to, from: from, messenger: { - category: messenger.category as unknown as MessengerCategory, - tag: messenger.tag, + category: messenger?.category, + tag: messenger?.tag, } as MessengerType, clientRef: clientRef, }); diff --git a/packages/messages/lib/classes/Messenger/MessengerAudio.ts b/packages/messages/lib/classes/Messenger/MessengerAudio.ts index bb7c31d4..a84e4eaf 100644 --- a/packages/messages/lib/classes/Messenger/MessengerAudio.ts +++ b/packages/messages/lib/classes/Messenger/MessengerAudio.ts @@ -1,14 +1,45 @@ import { AbstractAudioMessage } from '../AbstractAudioMessage'; -import { MessengerAudioInterface } from '../../interfaces'; import { MessengerAudioParams, MessengerType } from '../../types'; +/** + * Represents an audio message for the Messenger channel. + * + * @group Messenger + */ export class MessengerAudio extends AbstractAudioMessage - implements MessengerAudioInterface + implements MessengerAudioParams { + /** + * The channel for this message (always 'messenger'). + */ public channel: 'messenger'; + + /** + * The messenger information for this message. + */ public messenger: MessengerType; + /** + * Sends an audio message to the Facebook Messenger channel. + * + * @param {MessengerAudioParams} params - The parameters for creating a Messenger audio message. + * @example + * ```ts + * import { MessengerAudio } from '@vonage/messages'; + * + * const { messageUUID } = await messagesClient.send(new MessengerAudio({ + * to: TO_NUMBER, + * from: FROM_NUMBER, + * audio: { + * url: 'https://example.com/audio.mp3', + * }, + * clientRef: 'my-personal-reference', + * })); + * + * console.log(`Message sent successfully with UUID ${messageUUID}`); + * ``` + */ public constructor(params: MessengerAudioParams) { super(params); this.messenger = params.messenger; diff --git a/packages/messages/lib/classes/Messenger/MessengerFile.ts b/packages/messages/lib/classes/Messenger/MessengerFile.ts index d5f9b5dc..a63a0724 100644 --- a/packages/messages/lib/classes/Messenger/MessengerFile.ts +++ b/packages/messages/lib/classes/Messenger/MessengerFile.ts @@ -1,14 +1,47 @@ import { AbstractFileMessage } from '../AbstractFileMessage'; -import { MessengerFileInterface } from '../../interfaces'; -import { MessengerFileParams } from '../../types'; +import { MessageParamsFile, MessengerFileParams } from '../../types'; +/** + * Represents a file message for the Messenger channel. + * + * @group Messenger + */ export class MessengerFile extends AbstractFileMessage - implements MessengerFileInterface + implements MessageParamsFile { + /** + * The channel for this message (always 'messenger'). + */ public channel: 'messenger'; + + /** + * The messenger information for this message. + */ public messenger; + /** + * Sends a file message to the Facebook Messenger channel. + * + * @param {MessengerFileParams} params - The parameters for creating a Messenger file message. + * + * @example + * ```ts + * import { MessengerFile } from '@vonage/messages'; + * + * const { messageUUID } = await messagesClient.send(new MessengerFile({ + * to: TO_NUMBER, + * from: FROM_NUMBER, + * file: { + * url: 'https://example.com/image.jpg', + * caption: 'This is an image', + * }, + * clientRef: 'my-personal-reference', + * })); + * + * console.log(`Message sent successfully with UUID ${messageUUID}`); + * ``` + */ public constructor(params: MessengerFileParams) { super(params); this.messenger = params.messenger; diff --git a/packages/messages/lib/classes/Messenger/MessengerImage.ts b/packages/messages/lib/classes/Messenger/MessengerImage.ts index 0f130900..ea56c25b 100644 --- a/packages/messages/lib/classes/Messenger/MessengerImage.ts +++ b/packages/messages/lib/classes/Messenger/MessengerImage.ts @@ -1,14 +1,49 @@ import { AbstractImageMessage } from '../AbstractImageMessage'; -import { MessengerImageInterface } from '../../interfaces'; import { MessengerImageParams } from '../../types'; +/** + * Represents an image message for the Messenger channel. + * + * This class extends the `AbstractImageMessage` class and implements the `MessengerImageParams` interface. + * It is used for sending image messages on the Messenger channel. + * + * @group Messenger + */ export class MessengerImage extends AbstractImageMessage - implements MessengerImageInterface + implements MessengerImageParams { + /** + * The channel for sending the message, which is set to 'messenger'. + */ public channel: 'messenger'; + + /** + * Additional Messenger-specific parameters for the image message. + */ public messenger; + /** + * Send an image message using the Facebook Messenger channel. + * + * @param {MessengerImageParams} params - The parameters for the image message. + * @example + * ```ts + * import { MessengerImage } from '@vonage/messages'; + * + * const { messageUUID } = await messagesClient.send(new MessengerImage({ + * to: TO_NUMBER, + * from: FROM_NUMBER, + * image: { + * url: 'https://example.com/image.jpg', + * caption: 'This is an image', + * }, + * clientRef: 'my-personal-reference', + * })); + * + * console.log(`Message sent successfully with UUID ${messageUUID}`); + * ``` + */ public constructor(params: MessengerImageParams) { super(params); this.messenger = params.messenger; diff --git a/packages/messages/lib/classes/Messenger/MessengerText.ts b/packages/messages/lib/classes/Messenger/MessengerText.ts index c3cb9f8f..1a262199 100644 --- a/packages/messages/lib/classes/Messenger/MessengerText.ts +++ b/packages/messages/lib/classes/Messenger/MessengerText.ts @@ -1,14 +1,44 @@ import { AbstractTextMessage } from '../AbstractTextMessage'; -import { MessengerTextInterface } from '../../interfaces'; import { MessengerTextParams, MessengerType } from '../../types'; +/** + * Represents a text message for the Messenger channel. + * + * @group Messenger + */ export class MessengerText extends AbstractTextMessage - implements MessengerTextInterface + implements MessengerTextParams { + /** + * The channel for this message (always 'messenger'). + */ public channel: 'messenger'; + + /** + * The messenger information for this message. + */ public messenger: MessengerType; + /** + * Sends a text message to the Facebook Messenger channel. + * + * @param {MessengerTextParams} params - The parameters for creating a Messenger text message. + * + * @example + * ```ts + * import { MessengerText } from '@vonage/messages'; + * + * const { messageUUID } = await messagesClient.send(new MessengerText({ + * to: TO_NUMBER, + * from: FROM_NUMBER, + * text: 'Hello world', + * clientRef: 'my-personal-reference', + * })); + * + * console.log(`Message sent successfully with UUID ${messageUUID}`); + * ``` + */ public constructor(params: MessengerTextParams) { super(params); this.messenger = params.messenger; diff --git a/packages/messages/lib/classes/Messenger/MessengerVideo.ts b/packages/messages/lib/classes/Messenger/MessengerVideo.ts index b0107ceb..f459a5e7 100644 --- a/packages/messages/lib/classes/Messenger/MessengerVideo.ts +++ b/packages/messages/lib/classes/Messenger/MessengerVideo.ts @@ -1,14 +1,46 @@ import { AbstractVideoMessage } from '../AbstractVideoMessage'; -import { MessengerVideoInterface } from '../../interfaces'; import { MessengerType, MessengerVideoParams } from '../../types'; +/** + * Represents a video message for the Messenger channel. + * + * @group Messenger + */ export class MessengerVideo extends AbstractVideoMessage - implements MessengerVideoInterface + implements MessengerVideoParams { + /** + * The channel for this message (always 'messenger'). + */ public channel: 'messenger'; + + /** + * The messenger information for this message. + */ public messenger: MessengerType; + /** + * Send a video message using the Facebook Messenger channel. + * + * @param {MessengerVideoParams} params - The parameters for creating a Messenger video message. + * @example + * ```ts + * import { MessagengerVideo } from '@vonage/messages'; + * + * const { messageUUID } = await messagesClient.send(new MessagengerVideo({ + * to: TO_NUMBER, + * from: FROM_NUMBER, + * video: { + * url: 'https://example.com/video.mp4', + * caption: 'This is a video', + * }, + * clientRef: 'my-personal-reference', + * })); + * + * console.log(`Message sent successfully with UUID ${messageUUID}`); + * ``` + */ public constructor(params: MessengerVideoParams) { super(params); this.messenger = params.messenger; diff --git a/packages/messages/lib/classes/Messenger/Text.ts b/packages/messages/lib/classes/Messenger/Text.ts index 3b10dc34..4486d8ab 100644 --- a/packages/messages/lib/classes/Messenger/Text.ts +++ b/packages/messages/lib/classes/Messenger/Text.ts @@ -1,4 +1,3 @@ -import { MessengerCategory } from '../../enums'; import { MessageType } from '../../interfaces/Messenger/MessageType'; import { MessengerType } from '../../types'; import { MessengerText } from './MessengerText'; @@ -7,9 +6,22 @@ import debug from 'debug'; const log = debug('vonage:messages:messenger'); /** - * @deprecated please use MessengerText instead + * Represents a text message for the Messenger channel. + * + * @deprecated Please use the MessengerText Class instead. + * + * @group Messenger */ export class Text extends MessengerText { + /** + * Constructs a new `Text` instance. + * + * @param {string} text - The text content of the message. + * @param {string} to - The recipient of the message. + * @param {string} from - The sender of the message. + * @param {MessageType} messenger - The messenger information for the message. + * @param {string} clientRef - The client reference for the message. + */ constructor( text: string, to: string, @@ -23,8 +35,8 @@ export class Text extends MessengerText { to: to, from: from, messenger: { - category: messenger.category as unknown as MessengerCategory, - tag: messenger.tag, + category: messenger?.category, + tag: messenger?.tag, } as MessengerType, clientRef: clientRef, }); diff --git a/packages/messages/lib/classes/Messenger/Video.ts b/packages/messages/lib/classes/Messenger/Video.ts index 48184f8d..45e137a5 100644 --- a/packages/messages/lib/classes/Messenger/Video.ts +++ b/packages/messages/lib/classes/Messenger/Video.ts @@ -8,9 +8,22 @@ import debug from 'debug'; const log = debug('vonage:messages:messenger'); /** - * @deprecated please use MessengerVideo instead + * Represents a text message for the Messenger channel. + * + * @deprecated Please use the MessengerText class instead. + * + * @group Messenger */ export class Video extends MessengerVideo { + /** + * Constructs a new `Text` instance. + * + * @param {VideoObject} video - The text content of the message. + * @param {string} to - The recipient of the message. + * @param {string} from - The sender of the message. + * @param {MessageType} messenger - The messenger information for the message. + * @param {string} clientRef - The client reference for the message. + */ constructor( video: VideoObject, to: string, @@ -24,8 +37,8 @@ export class Video extends MessengerVideo { to: to, from: from, messenger: { - category: messenger.category as unknown as MessengerCategory, - tag: messenger.tag, + category: messenger?.category as unknown as MessengerCategory, + tag: messenger?.tag, } as MessengerType, clientRef: clientRef, }); diff --git a/packages/messages/lib/classes/SMS/SMS.ts b/packages/messages/lib/classes/SMS/SMS.ts index de01ecc7..d106bc87 100644 --- a/packages/messages/lib/classes/SMS/SMS.ts +++ b/packages/messages/lib/classes/SMS/SMS.ts @@ -1,13 +1,39 @@ import { AbstractTextMessage } from '../AbstractTextMessage'; -import { SMSTextInterface } from '../../interfaces'; -import { MessageParamsText } from '../../types'; +import { MessageParamsText, SMSParams } from '../../types'; import debug from 'debug'; const log = debug('vonage:messages:sms'); -export class SMS extends AbstractTextMessage implements SMSTextInterface { +/** + * Send a text message using the SMS channel. + * + * @group SMS + */ +export class SMS extends AbstractTextMessage implements SMSParams { public channel: 'sms'; + /** + * Send an SMS message + * + * @param {MessageParamsText | string} params - The message parameters or text message. + * @param {string} to - The recipient's phone number. + * @param {string} from - The sender's phone number. + * @param {string} clientRef - The client reference for the message. + * + * @example + * ```ts + * import { SMS } from '@vonage/messages'; + * + * const { messageUUID } = await messagesClient.send(new SMS({ + * to: TO_NUMBER, + * from: FROM_NUMBER, + * text: 'Hello world', + * clientRef: 'my-personal-reference', + * })); + * + * console.log(`Message sent successfully with UUID ${messageUUID}`); + * ``` + */ constructor( params: MessageParamsText | string, to?: string, @@ -18,11 +44,12 @@ export class SMS extends AbstractTextMessage implements SMSTextInterface { log('Please update the call to use MessageParamsText instead'); params = { text: params as string, - to: to, - from: from, + to: to as string, + from: from as string, clientRef: clientRef, }; } + super(params as MessageParamsText); this.channel = 'sms'; } diff --git a/packages/messages/lib/classes/Viber/Image.ts b/packages/messages/lib/classes/Viber/Image.ts index b4097e82..8e1f4ca3 100644 --- a/packages/messages/lib/classes/Viber/Image.ts +++ b/packages/messages/lib/classes/Viber/Image.ts @@ -1,4 +1,4 @@ -import { ImageObject } from '../../interfaces/ImageObject'; +import { ImageObject } from '../../interfaces'; import { MessageConfig } from '../../interfaces/Viber/MessageConfig'; import { ViberImageParams, ViberService } from '../../types'; import { ViberImage } from './ViberImage'; @@ -7,9 +7,22 @@ import debug from 'debug'; const log = debug('vonage:messages:viber'); /** - * @deprecated please use ViberImage instead + * Represents an image message for the Viber channel. + * + * @deprecated Please use the ViberImage class instead. + * + * @group Viber */ export class Image extends ViberImage { + /** + * Constructs a new `Image` instance for the Viber channel. + * + * @param {ImageObject} image - The image content of the message. + * @param {string} to - The recipient's Viber ID. + * @param {string} from - The sender's Viber ID. + * @param {MessageConfig} viberService - The Viber service configuration. + * @param {string} clientRef - The client reference for the message. + */ constructor( image: ImageObject, to: string, diff --git a/packages/messages/lib/classes/Viber/Text.ts b/packages/messages/lib/classes/Viber/Text.ts index 8b65e8fa..06ee1418 100644 --- a/packages/messages/lib/classes/Viber/Text.ts +++ b/packages/messages/lib/classes/Viber/Text.ts @@ -6,9 +6,22 @@ import debug from 'debug'; const log = debug('vonage:messages:viber'); /** - * @deprecated Please use ViberText + * Represents a text message for the Viber channel. + * + * @deprecated Please use the ViberText class instead. + * + * @group Viber */ export class Text extends ViberText { + /** + * Constructs a new `Text` instance for the Viber channel. + * + * @param {string} text - The text content of the message. + * @param {string} to - The recipient's Viber ID. + * @param {string} from - The sender's Viber ID. + * @param {MessageConfig} viberService - The Viber service configuration. + * @param {string} clientRef - The client reference for the message. + */ constructor( text: string, to: string, diff --git a/packages/messages/lib/classes/Viber/ViberFile.ts b/packages/messages/lib/classes/Viber/ViberFile.ts index e0ca4d81..3f16ac57 100644 --- a/packages/messages/lib/classes/Viber/ViberFile.ts +++ b/packages/messages/lib/classes/Viber/ViberFile.ts @@ -1,14 +1,44 @@ -import { ViberFileInterface } from '../../interfaces'; import { AbstractFileMessage } from '../AbstractFileMessage'; import { ViberFileParams } from '../../types'; +/** + * Represents a file message for the Viber Service channel. + * + * @group Viber + */ export class ViberFile extends AbstractFileMessage - implements ViberFileInterface + implements ViberFileParams { public channel: 'viber_service'; public viberService; + /** + * Send a file message using the Viber Service channel. + * + * @param {ViberFileParams} params - The parameters for the ViberFile message. + * @example + * ```ts + * import { ViberFile } from '@vonage/messages'; + * + * const { messageUUID } = await messagesClient.send(new ViberFile({ + * to: TO_NUMBER, + * from: FROM_NUMBER, + * file: { + * url: 'https://my-host.com/my-file.pdf', + * }, + * viberService: { + * action: { + * url: 'https://my-host.com/my-path', + * text: 'My button text', + * }, + * }, + * clientRef: 'my-personal-reference', + * })); + * + * console.log(`Message sent successfully with UUID ${messageUUID}`); + * ``` + */ constructor(params: ViberFileParams) { super(params); this.viberService = params.viberService; diff --git a/packages/messages/lib/classes/Viber/ViberImage.ts b/packages/messages/lib/classes/Viber/ViberImage.ts index 26567f19..0f1d2c74 100644 --- a/packages/messages/lib/classes/Viber/ViberImage.ts +++ b/packages/messages/lib/classes/Viber/ViberImage.ts @@ -1,15 +1,45 @@ import { AbstractImageMessage } from '../AbstractImageMessage'; -import { ViberImageInterface } from '../../interfaces'; import { ViberImageParams } from '../../types'; import { ViberActionParams } from '../../types'; +/** + * Represents an image message for the Viber Service channel. + * + * @group Viber + */ export class ViberImage extends AbstractImageMessage - implements ViberImageInterface + implements ViberImageParams { public channel: 'viber_service'; public viberService: ViberActionParams; + /** + * Send an image message using the Viber Service channel. + * + * @param {ViberImageParams} params - The parameters for the ViberImage message. + * @example + * ```ts + * import { ViberImage } from '@vonage/messages'; + * + * const { messageUUID } = await messagesClient.send(new ViberImage({ + * to: TO_NUMBER, + * from: FROM_NUMBER, + * image: { + * url: 'https://my-host.com/my-image.jpg', + * }, + * viberService: { + * action: { + * url: 'https://my-host.com/my-path', + * text: 'My button text', + * }, + * }, + * clientRef: 'my-personal-reference', + * })); + * + * console.log(`Message sent successfully with UUID ${messageUUID}`); + * ``` + */ constructor(params: ViberImageParams) { super(params); this.viberService = params.viberService; diff --git a/packages/messages/lib/classes/Viber/ViberText.ts b/packages/messages/lib/classes/Viber/ViberText.ts index 136c2824..81e3f6e8 100644 --- a/packages/messages/lib/classes/Viber/ViberText.ts +++ b/packages/messages/lib/classes/Viber/ViberText.ts @@ -1,15 +1,44 @@ -import { ViberTextInterface } from '../../interfaces'; import { AbstractTextMessage } from '../AbstractTextMessage'; import { ViberActionParams } from '../../types'; import { ViberTextParams } from '../../types'; +/** + * Represents a text message for the Viber Service channel. + * + * @group Viber + */ export class ViberText extends AbstractTextMessage - implements ViberTextInterface + implements ViberTextParams { public channel: 'viber_service'; public viberService: ViberActionParams; + /** + * Send a text message using the Viber Service channel. + * + * @param {ViberTextParams} params - The parameters for the ViberText message. + * + * @example + * ```ts + * import { ViberText } from '@vonage/messages'; + * + * const { messageUUID } = await messagesClient.send(new ViberText({ + * to: TO_NUMBER, + * from: FROM_NUMBER, + * text: 'Hello world', + * viberService: { + * action: { + * url: 'https://my-host.com/my-path', + * text: 'My button text', + * }, + * }, + * clientRef: 'my-personal-reference', + * })); + * + * console.log(`Message sent successfully with UUID ${messageUUID}`); + * ``` + */ constructor(params: ViberTextParams) { super(params); this.viberService = params.viberService; diff --git a/packages/messages/lib/classes/Viber/ViberVideo.ts b/packages/messages/lib/classes/Viber/ViberVideo.ts index 3e8ae985..8f2b62ac 100644 --- a/packages/messages/lib/classes/Viber/ViberVideo.ts +++ b/packages/messages/lib/classes/Viber/ViberVideo.ts @@ -1,14 +1,45 @@ import { AbstractVideoMessage } from '../AbstractVideoMessage'; -import { ViberVideoInterface } from '../../interfaces'; import { ViberVideoParams } from '../../types'; +/** + * Represents a video message for the Viber Service channel. + * + * @group Viber + */ export class ViberVideo extends AbstractVideoMessage - implements ViberVideoInterface + implements ViberVideoParams { public channel: 'viber_service'; public viberService; + /** + * Send a video message using the Viber Service channel. + * + * @param {ViberVideoParams} params - The parameters for the ViberVideo message. + * @example + * ```ts + * import { ViberVideo } from '@vonage/messages'; + * + * const { messageUUID } = await messagesClient.send(new ViberVideo({ + * to: TO_NUMBER, + * from: FROM_NUMBER, + * text: 'Hello world', + * video: { + * url: 'https://my-host.com/my-video.mp4', + * }, + * viberService: { + * action: { + * url: 'https://my-host.com/my-path', + * text: 'My button text', + * }, + * }, + * clientRef: 'my-personal-reference', + * })); + * + * console.log(`Message sent successfully with UUID ${messageUUID}`); + * ``` + */ constructor(params: ViberVideoParams) { super(params); this.viberService = params.viberService; diff --git a/packages/messages/lib/classes/WhatsApp/Audio.ts b/packages/messages/lib/classes/WhatsApp/Audio.ts index eca5238c..5510b579 100644 --- a/packages/messages/lib/classes/WhatsApp/Audio.ts +++ b/packages/messages/lib/classes/WhatsApp/Audio.ts @@ -1,13 +1,23 @@ -import { AudioObject } from '../../interfaces/AudioObject'; +import { AudioObject } from '../../interfaces'; import { WhatsAppAudio } from './WhatsAppAudio'; import debug from 'debug'; const log = debug('vonage:messages:whatsapp'); /** - * @deprecated please use WhatsAppAudio instead + * @deprecated please use the WhatsAppAudio class instead + * + * @group WhatsApp */ export class Audio extends WhatsAppAudio { + /** + * Constructs a new `Audio` instance for WhatsApp. + * + * @param {AudioObject} audio - The audio content of the message. + * @param {string} to - The recipient's WhatsApp number. + * @param {string} from - The sender's WhatsApp number. + * @param {string} clientRef - (Optional) A unique client reference for the message. + */ constructor( audio: AudioObject, to: string, diff --git a/packages/messages/lib/classes/WhatsApp/CustomMessage.ts b/packages/messages/lib/classes/WhatsApp/CustomMessage.ts index f42b0276..98ae8f84 100644 --- a/packages/messages/lib/classes/WhatsApp/CustomMessage.ts +++ b/packages/messages/lib/classes/WhatsApp/CustomMessage.ts @@ -6,9 +6,19 @@ import debug from 'debug'; const log = debug('vonage:messages:whatsapp'); /** - * @deprecated please use WhatsAppCustom instead + * @deprecated Please use WhatsAppCustom class instead + * + * @group WhatsApp */ export class CustomMessage extends WhatsAppCustom { + /** + * Constructs a new `CustomMessage` instance for WhatsApp. + * + * @param {CustomPayload} custom - The custom payload for the message. + * @param {string} to - The recipient's WhatsApp number. + * @param {string} from - The sender's WhatsApp number. + * @param {string} clientRef - (Optional) A unique client reference for the message. + */ constructor( custom: CustomPayload, to: string, diff --git a/packages/messages/lib/classes/WhatsApp/File.ts b/packages/messages/lib/classes/WhatsApp/File.ts index 886eae68..d46d1e89 100644 --- a/packages/messages/lib/classes/WhatsApp/File.ts +++ b/packages/messages/lib/classes/WhatsApp/File.ts @@ -5,9 +5,19 @@ import debug from 'debug'; const log = debug('vonage:messages:whatsapp'); /** - * @deprecated please use WhatsAppFile instead + * @deprecated please use the WhatsAppFile class instead + * + * @group WhatsApp */ export class File extends WhatsAppFile { + /** + * Constructs a new `File` instance for WhatsApp. + * + * @param {FileObject} file - The file object for the message. + * @param {string} to - The recipient's WhatsApp number. + * @param {string} from - The sender's WhatsApp number. + * @param {string} clientRef - (Optional) A unique client reference for the message. + */ constructor( file: FileObject, to: string, diff --git a/packages/messages/lib/classes/WhatsApp/Image.ts b/packages/messages/lib/classes/WhatsApp/Image.ts index 150b5d11..61c81bb3 100644 --- a/packages/messages/lib/classes/WhatsApp/Image.ts +++ b/packages/messages/lib/classes/WhatsApp/Image.ts @@ -1,13 +1,23 @@ -import { ImageObject } from '../../interfaces/ImageObject'; +import { ImageObject } from '../../interfaces'; import { WhatsAppImage } from './WhatsAppImage'; import debug from 'debug'; const log = debug('vonage:messages:whatsapp'); /** - * @deprecated please use WhatsAppImage instead + * @deprecated Please use the WhatsAppImage class instead + * + * @group WhatsApp */ export class Image extends WhatsAppImage { + /** + * Constructs a new `Image` instance for WhatsApp. + * + * @param {ImageObject} image - The image object for the message. + * @param {string} to - The recipient's WhatsApp number. + * @param {string} from - The sender's WhatsApp number. + * @param {string} clientRef - (Optional) A unique client reference for the message. + */ constructor( image: ImageObject, to: string, diff --git a/packages/messages/lib/classes/WhatsApp/TemplateMessage.ts b/packages/messages/lib/classes/WhatsApp/TemplateMessage.ts index ce5176eb..fe88b0a9 100644 --- a/packages/messages/lib/classes/WhatsApp/TemplateMessage.ts +++ b/packages/messages/lib/classes/WhatsApp/TemplateMessage.ts @@ -2,13 +2,25 @@ import { WhatsAppLanguageCode } from '../../enums'; import { MessageTemplate } from '../../interfaces/WhatsApp/MessageTemplate'; import { WhatsAppTemplate } from './WhatsAppTemplate'; import debug from 'debug'; +import { WhatsAppTemplateParams } from "../../types"; const log = debug('vonage:messages:whatsapp'); /** - * @deprecated please use WhatsAppTemplate instead + * @deprecated please use the WhatsAppTemplate class instead + * + * @group WhatsApp */ export class TemplateMessage extends WhatsAppTemplate { + /** + * Constructs a new `TemplateMessage` instance for WhatsApp. + * + * @param {MessageTemplate} template - The template object for the message. + * @param {string} to - The recipient's WhatsApp number. + * @param {string} from - The sender's WhatsApp number. + * @param {string} locale - The locale or language code for the message. + * @param {string} clientRef - (Optional) A unique client reference for the message. + */ constructor( template: MessageTemplate, to: string, @@ -26,6 +38,6 @@ export class TemplateMessage extends WhatsAppTemplate { policy: 'deterministic', locale: locale as WhatsAppLanguageCode, }, - }); + } as WhatsAppTemplateParams); } } diff --git a/packages/messages/lib/classes/WhatsApp/Text.ts b/packages/messages/lib/classes/WhatsApp/Text.ts index f4514e1e..17300252 100644 --- a/packages/messages/lib/classes/WhatsApp/Text.ts +++ b/packages/messages/lib/classes/WhatsApp/Text.ts @@ -4,9 +4,19 @@ import debug from 'debug'; const log = debug('vonage:messages:whatsapp'); /** - * @deprecated please use WhatsAppText instead + * @deprecated please use the WhatsAppText class instead + * + * @group WhatsApp */ export class Text extends WhatsAppText { + /** + * Constructs a new `Text` instance for WhatsApp. + * + * @param {string} text - The text message content. + * @param {string} to - The recipient's WhatsApp number. + * @param {string} from - The sender's WhatsApp number. + * @param {string} clientRef - (Optional) A unique client reference for the message. + */ constructor(text: string, to: string, from: string, clientRef?: string) { log('Please update to use the WhatsAppText class instead'); super({ diff --git a/packages/messages/lib/classes/WhatsApp/Video.ts b/packages/messages/lib/classes/WhatsApp/Video.ts index edad5873..442c6f5c 100644 --- a/packages/messages/lib/classes/WhatsApp/Video.ts +++ b/packages/messages/lib/classes/WhatsApp/Video.ts @@ -1,13 +1,23 @@ -import { VideoObject } from '../../interfaces/VideoObject'; +import { VideoObject } from '../../interfaces'; import { WhatsAppVideo } from './WhatsAppVideo'; import debug from 'debug'; const log = debug('vonage:messages:whatsapp'); /** - * @deprecated please use WhatsAppVideo instead + * @deprecated please use the WhatsAppVideo class instead + * + * @group WhatsApp */ export class Video extends WhatsAppVideo { + /** + * Constructs a new `Video` instance for WhatsApp. + * + * @param {VideoObject} video - The video message content. + * @param {string} to - The recipient's WhatsApp number. + * @param {string} from - The sender's WhatsApp number. + * @param {string} clientRef - (Optional) A unique client reference for the message. + */ constructor( video: VideoObject, to: string, diff --git a/packages/messages/lib/classes/WhatsApp/WhatsAppAudio.ts b/packages/messages/lib/classes/WhatsApp/WhatsAppAudio.ts index 27c59f0b..65ae5e57 100644 --- a/packages/messages/lib/classes/WhatsApp/WhatsAppAudio.ts +++ b/packages/messages/lib/classes/WhatsApp/WhatsAppAudio.ts @@ -1,13 +1,38 @@ import { AbstractAudioMessage } from '../AbstractAudioMessage'; -import { WhatsAppAudioInterface } from '../../interfaces'; import { WhatsAppAudioParams } from '../../types'; +/** + * Represents an audio message for WhatsApp. + * + * @group WhatsApp + */ export class WhatsAppAudio extends AbstractAudioMessage - implements WhatsAppAudioInterface + implements WhatsAppAudioParams { public channel: 'whatsapp'; + /** + * Sends an audio message to a WhatsApp user. + * + * @param {WhatsAppAudioParams} params - The parameters for creating a WhatsApp audio message. + * @example + * ```ts + * import { WhatsAppAudio } from '@vonage/messages'; + * + * const { messageUUID } = await messagesClient.send(new WhatsAppAudio({ + * to: TO_NUMBER, + * from: FROM_NUMBER, + * audio: { + * url: 'https://example.com/audio.mp3', + * caption: 'This is an audio message', + * }, + * clientRef: 'my-personal-reference', + * })); + * + * console.log(`Message sent successfully with UUID ${messageUUID}`); + * ``` + */ public constructor(params: WhatsAppAudioParams) { super(params); this.channel = 'whatsapp'; diff --git a/packages/messages/lib/classes/WhatsApp/WhatsAppCustom.ts b/packages/messages/lib/classes/WhatsApp/WhatsAppCustom.ts index 49b8bdef..04e90301 100644 --- a/packages/messages/lib/classes/WhatsApp/WhatsAppCustom.ts +++ b/packages/messages/lib/classes/WhatsApp/WhatsAppCustom.ts @@ -1,15 +1,43 @@ import { AbstractMessage } from '../AbstractMessage'; -import { WhatsAppCustomInterface } from '../../interfaces'; import { WhatsAppCustomType, WhatsAppCustomParams } from '../../types'; +/** + * Represents a custom message for WhatsApp. + * + * @group WhatsApp + */ export class WhatsAppCustom extends AbstractMessage - implements WhatsAppCustomInterface + implements WhatsAppCustomParams { public channel: 'whatsapp'; public messageType: 'custom'; public custom: WhatsAppCustomType; + /** + * Sends a custom message to a WhatsApp user. + * + * @param {WhatsAppCustomParams} params - The parameters for creating a WhatsApp custom message. + * @example + * ```ts + * import { WhatsAppCustom } from '@vonage/messages'; + * + * const { messageUUID } = await messagesClient.send(new WhatsAppCustom({ + * to: TO_NUMBER, + * from: FROM_NUMBER, + * custom: { + * type: 'template', + * template: { + * namespace: 'your-namespace', + * name: 'your-template-name', + * }, + * } + * clientRef: 'my-personal-reference', + * })); + * + * console.log(`Message sent successfully with UUID ${messageUUID}`); + * ``` + */ public constructor(params: WhatsAppCustomParams) { super(params); this.custom = params.custom; diff --git a/packages/messages/lib/classes/WhatsApp/WhatsAppFile.ts b/packages/messages/lib/classes/WhatsApp/WhatsAppFile.ts index 3eb7cbde..ce5fe3bd 100644 --- a/packages/messages/lib/classes/WhatsApp/WhatsAppFile.ts +++ b/packages/messages/lib/classes/WhatsApp/WhatsAppFile.ts @@ -1,13 +1,37 @@ import { AbstractFileMessage } from '../AbstractFileMessage'; -import { WhatsAppFileInterface } from '../../interfaces'; import { WhatsAppFileParams } from '../../types'; +/** + * Represents a file message for WhatsApp. + * + * @group WhatsApp + */ export class WhatsAppFile extends AbstractFileMessage - implements WhatsAppFileInterface + implements WhatsAppFileParams { public channel: 'whatsapp'; + /** + * Send a WhatsApp file message. + * + * @param {WhatsAppFileParams} params - The parameters for creating a WhatsApp file message. + * @example + * ```ts + * import { WhatsAppFile } from '@vonage/messages'; + * + * const { messageUUID } = await messagesClient.send(new WhatsAppFile({ + * to: TO_NUMBER, + * from: FROM_NUMBER, + * file: { + * url: 'https://example.com/image.jpg', + * }, + * clientRef: 'my-personal-reference', + * })); + * + * console.log(`Message sent successfully with UUID ${messageUUID}`); + * ``` + */ public constructor(params: WhatsAppFileParams) { super(params); this.channel = 'whatsapp'; diff --git a/packages/messages/lib/classes/WhatsApp/WhatsAppImage.ts b/packages/messages/lib/classes/WhatsApp/WhatsAppImage.ts index 5f5920fd..a8af9e20 100644 --- a/packages/messages/lib/classes/WhatsApp/WhatsAppImage.ts +++ b/packages/messages/lib/classes/WhatsApp/WhatsAppImage.ts @@ -1,13 +1,38 @@ import { AbstractImageMessage } from '../AbstractImageMessage'; -import { WhatsAppImageInterface } from '../../interfaces'; import { WhatsAppImageParams } from '../../types'; +/** + * Represents an image message for WhatsApp. + * + * @group WhatsApp + */ export class WhatsAppImage extends AbstractImageMessage - implements WhatsAppImageInterface + implements WhatsAppImageParams { public channel: 'whatsapp'; + /** + * Sends an image message to a WhatsApp user. + * + * @param {WhatsAppImageParams} params - The parameters for creating a WhatsApp image message. + * @example + * ```ts + * import { WhatsAppImage } from '@vonage/messages'; + * + * const { messageUUID } = await messagesClient.send(new WhatsAppImage({ + * to: TO_NUMBER, + * from: FROM_NUMBER, + * image: { + * url: 'https://example.com/image.jpg', + * caption: 'This is an image message', + * }, + * clientRef: 'my-personal-reference', + * })); + * + * console.log(`Message sent successfully with UUID ${messageUUID}`); + * ``` + */ public constructor(params: WhatsAppImageParams) { super(params); this.channel = 'whatsapp'; diff --git a/packages/messages/lib/classes/WhatsApp/WhatsAppSticker.ts b/packages/messages/lib/classes/WhatsApp/WhatsAppSticker.ts index 715189f0..38c4be2b 100644 --- a/packages/messages/lib/classes/WhatsApp/WhatsAppSticker.ts +++ b/packages/messages/lib/classes/WhatsApp/WhatsAppSticker.ts @@ -1,17 +1,59 @@ import { AbstractMessage } from '../AbstractMessage'; -import { WhatsAppStickerInterface } from '../../interfaces'; import { WhatsAppStickerParams } from '../../types'; import { WhatsAppStickerIdType } from '../../types'; import { WhatsAppStickerUrlType } from '../../types'; +/** + * Represents a sticker message for WhatsApp. + * + * @group WhatsApp + */ export class WhatsAppSticker extends AbstractMessage - implements WhatsAppStickerInterface + implements WhatsAppStickerParams { public channel: 'whatsapp'; public messageType: 'sticker'; public sticker: WhatsAppStickerIdType | WhatsAppStickerUrlType; + /** + * Send a sticker message to a WhatsApp user. + * + * @param {WhatsAppStickerParams} params - The parameters for creating a WhatsApp sticker message. + * @example + * Send a sticker message with a sticker ID: + * ```ts + * import { WhatsAppSticker } from '@vonage/messages'; + * + * const { messageUUID } = await messagesClient.send(new WhatsAppSticker({ + * to: TO_NUMBER, + * from: FROM_NUMBER, + * sticker: { + * id: '0-0', + * }, + * clientRef: 'my-personal-reference', + * })); + * + * console.log(`Message sent successfully with UUID ${messageUUID}`); + * ``` + * + * @example + * Send a sticker message with a sticker URL: + * ```ts + * import { WhatsAppSticker } from '@vonage/messages'; + * + * const { messageUUID } = await messagesClient.send(new WhatsAppSticker({ + * to: TO_NUMBER, + * from: FROM_NUMBER, + * sticker: { + * url: 'https://example.com/sticker.png', + * }, + * clientRef: 'my-personal-reference', + * })); + * + * console.log(`Message sent successfully with UUID ${messageUUID}`); + * ``` + */ public constructor(params: WhatsAppStickerParams) { super(params); this.sticker = params.sticker; diff --git a/packages/messages/lib/classes/WhatsApp/WhatsAppTemplate.ts b/packages/messages/lib/classes/WhatsApp/WhatsAppTemplate.ts index 1d7081a5..485bc9d7 100644 --- a/packages/messages/lib/classes/WhatsApp/WhatsAppTemplate.ts +++ b/packages/messages/lib/classes/WhatsApp/WhatsAppTemplate.ts @@ -1,18 +1,51 @@ import { AbstractMessage } from '../AbstractMessage'; -import { WhatsAppTemplateInterface } from '../../interfaces'; import { WhatsAppTemplateParams } from '../../types'; import { WhatsAppPolicyType } from '../../types'; import { WhatsAppTemplateType } from '../../types'; +/** + * Represents a template message for WhatsApp. + * + * @group WhatsApp + */ export class WhatsAppTemplate extends AbstractMessage - implements WhatsAppTemplateInterface + implements WhatsAppTemplateParams { public channel: 'whatsapp'; public messageType: 'template'; public whatsapp: WhatsAppPolicyType; public template: WhatsAppTemplateType; + /** + * Send a template message to a WhatsApp user. + * + * @param {WhatsAppTemplateParams} params - The parameters for creating a WhatsApp template message. + * + * @example + * ```ts + * import { WhatsAppTemplate, WhatsAppLanguageCode } from '@vonage/messages'; + * + * const { messageUUID } = await messagesClient.send(new WhatsAppTemplate({ + * to: TO_NUMBER, + * from: FROM_NUMBER, + * whatsapp: { + * policy: 'deterministic', + * locale: WhatsAppLanguageCode.EN, + * }, + * template: { + * name: 'your-template-name', + * parameters: [ + * 'foo', + * 'bar', + * ], + * }, + * clientRef: 'my-personal-reference', + * })); + * + * console.log(`Message sent successfully with UUID ${messageUUID}`); + * ``` + */ public constructor(params: WhatsAppTemplateParams) { super(params); this.whatsapp = params.whatsapp; diff --git a/packages/messages/lib/classes/WhatsApp/WhatsAppText.ts b/packages/messages/lib/classes/WhatsApp/WhatsAppText.ts index 9d80592b..e4b7cbf2 100644 --- a/packages/messages/lib/classes/WhatsApp/WhatsAppText.ts +++ b/packages/messages/lib/classes/WhatsApp/WhatsAppText.ts @@ -1,13 +1,35 @@ import { AbstractTextMessage } from '../AbstractTextMessage'; -import { WhatsAppTextInterface } from '../../interfaces'; import { WhatsAppTextParams } from '../../types'; +/** + * Represents a text message for WhatsApp. + * + * @group WhatsApp + */ export class WhatsAppText extends AbstractTextMessage - implements WhatsAppTextInterface + implements WhatsAppTextParams { public channel: 'whatsapp'; + /** + * Send a WhatsApp text message. + * + * @param {WhatsAppTextParams} params - The parameters for creating a WhatsApp text message. + * @example + * ```ts + * import { WhatsAppText } from '@vonage/messages'; + * + * const { messageUUID } = await messagesClient.send(new WhatsAppText({ + * to: TO_NUMBER, + * from: FROM_NUMBER, + * text: 'Hello world', + * clientRef: 'my-personal-reference', + * })); + * + * console.log(`Message sent successfully with UUID ${messageUUID}`); + * ``` + */ public constructor(params: WhatsAppTextParams) { super(params); this.channel = 'whatsapp'; diff --git a/packages/messages/lib/classes/WhatsApp/WhatsAppVideo.ts b/packages/messages/lib/classes/WhatsApp/WhatsAppVideo.ts index 394e7c56..ae22e1ec 100644 --- a/packages/messages/lib/classes/WhatsApp/WhatsAppVideo.ts +++ b/packages/messages/lib/classes/WhatsApp/WhatsAppVideo.ts @@ -1,13 +1,39 @@ import { AbstractVideoMessage } from '../AbstractVideoMessage'; -import { WhatsAppVideoInterface } from '../../interfaces'; import { WhatsAppVideoParams } from '../../types'; +/** + * Represents a video message for WhatsApp. + * + * @group WhatsApp + */ export class WhatsAppVideo extends AbstractVideoMessage - implements WhatsAppVideoInterface + implements WhatsAppVideoParams { public channel: 'whatsapp'; + /** + * Sends a video message to a WhatsApp user. + * + * @param {WhatsAppVideoParams} params - The parameters for creating a WhatsApp video message. + * + * @example + * ```ts + * import { WhatsAppVideo } from '@vonage/messages'; + * + * const { messageUUID } = await messagesClient.send(new WhatsAppVideo({ + * to: TO_NUMBER, + * from: FROM_NUMBER, + * video: { + * url: 'https://example.com/video.mp4', + * caption: 'This is a video message', + * }, + * clientRef: 'my-personal-reference', + * })); + * + * console.log(`Message sent successfully with UUID ${messageUUID}`); + * ``` + */ public constructor(params: WhatsAppVideoParams) { super(params); this.channel = 'whatsapp'; diff --git a/packages/messages/lib/enums/Channels.ts b/packages/messages/lib/enums/Channels.ts new file mode 100644 index 00000000..b661182f --- /dev/null +++ b/packages/messages/lib/enums/Channels.ts @@ -0,0 +1,7 @@ +export enum Channels { + MESSENGER = 'messenger', + MMS = 'mms', + SMS = 'sms', + WHATSAPP = 'whatsapp', + VIBER = 'viber_service', +} diff --git a/packages/messages/lib/enums/Messenger/MessageCategory.ts b/packages/messages/lib/enums/Messenger/MessageCategory.ts index 28731c3e..98b36976 100644 --- a/packages/messages/lib/enums/Messenger/MessageCategory.ts +++ b/packages/messages/lib/enums/Messenger/MessageCategory.ts @@ -1,8 +1,21 @@ /** - * @deprecated please use MessengerCategory + * @deprecated Please use MessengerCategory instead. + * + * @group Messenger */ export enum MessageCategory { - RESPONSE = 'response', - UPDATE = 'update', - MESSAGE_TAG = 'message_tag', + /** + * Represents a response message category. + */ + RESPONSE = 'response', + + /** + * Represents an update message category. + */ + UPDATE = 'update', + + /** + * Represents a message tag message category. + */ + MESSAGE_TAG = 'message_tag', } diff --git a/packages/messages/lib/enums/Messenger/MessengerCategory.ts b/packages/messages/lib/enums/Messenger/MessengerCategory.ts index 1e9b02e6..0e34c8b9 100644 --- a/packages/messages/lib/enums/Messenger/MessengerCategory.ts +++ b/packages/messages/lib/enums/Messenger/MessengerCategory.ts @@ -1,5 +1,21 @@ +/** + * Enum representing categories for Facebook Messenger messages. + * + * @group Messenger + */ export enum MessengerCategory { + /** + * Represents a response message category. + */ RESPONSE = 'response', + + /** + * Represents an update message category. + */ UPDATE = 'update', + + /** + * Represents a message tag message category. + */ MESSAGE_TAG = 'message_tag', } diff --git a/packages/messages/lib/enums/Messenger/MessengerTags.ts b/packages/messages/lib/enums/Messenger/MessengerTags.ts index 7ae2a4ba..8499dd43 100644 --- a/packages/messages/lib/enums/Messenger/MessengerTags.ts +++ b/packages/messages/lib/enums/Messenger/MessengerTags.ts @@ -1,16 +1,78 @@ +/** + * Enum representing message tags for Facebook Messenger messages. + * + * These tags are used to categorize the purpose and relevance of the message. + * + * @group Messenger + */ export enum MessengerTags { - CONFIRMED_EVENT_UPDATE = 'CONFIRMED_EVENT_UPDATE', - POST_PURCHASE_UPDATE = 'POST_PURCHASE_UPDATE', - ACCOUNT_UPDATE = 'ACCOUNT_UPDATE', - HUMAN_AGENT = 'HUMAN_AGENT', - SHIPPING_UPDATE = 'SHIPPING_UPDATE', - RESERVATION_UPDATE = 'RESERVATION_UPDATE', - ISSUE_RESOLUTION = 'ISSUE_RESOLUTION', - APPOINTMENT_UPDATE = 'APPOINTMENT_UPDATE', - GAME_EVENT = 'GAME_EVENT', - TRANSPORTATION_UPDATE = 'TRANSPORTATION_UPDATE', - FEATURE_FUNCTIONALITY_UPDATE = 'FEATURE_FUNCTIONALITY_UPDATE', - TICKET_UPDATE = 'TICKET_UPDATE', - PAYMENT_UPDATE = 'PAYMENT_UPDATE', - PERSONAL_FINANCE_UPDATE = 'PERSONAL_FINANCE_UPDATE', + /** + * Represents a confirmed event update message tag. + */ + CONFIRMED_EVENT_UPDATE = 'CONFIRMED_EVENT_UPDATE', + + /** + * Represents a post-purchase update message tag. + */ + POST_PURCHASE_UPDATE = 'POST_PURCHASE_UPDATE', + + /** + * Represents an account update message tag. + */ + ACCOUNT_UPDATE = 'ACCOUNT_UPDATE', + + /** + * Represents a message tag for human agent communication. + */ + HUMAN_AGENT = 'HUMAN_AGENT', + + /** + * Represents a shipping update message tag. + */ + SHIPPING_UPDATE = 'SHIPPING_UPDATE', + + /** + * Represents a reservation update message tag. + */ + RESERVATION_UPDATE = 'RESERVATION_UPDATE', + + /** + * Represents a message tag for issue resolution. + */ + ISSUE_RESOLUTION = 'ISSUE_RESOLUTION', + + /** + * Represents an appointment update message tag. + */ + APPOINTMENT_UPDATE = 'APPOINTMENT_UPDATE', + + /** + * Represents a game event message tag. + */ + GAME_EVENT = 'GAME_EVENT', + + /** + * Represents a transportation update message tag. + */ + TRANSPORTATION_UPDATE = 'TRANSPORTATION_UPDATE', + + /** + * Represents a feature functionality update message tag. + */ + FEATURE_FUNCTIONALITY_UPDATE = 'FEATURE_FUNCTIONALITY_UPDATE', + + /** + * Represents a ticket update message tag. + */ + TICKET_UPDATE = 'TICKET_UPDATE', + + /** + * Represents a payment update message tag. + */ + PAYMENT_UPDATE = 'PAYMENT_UPDATE', + + /** + * Represents a personal finance update message tag. + */ + PERSONAL_FINANCE_UPDATE = 'PERSONAL_FINANCE_UPDATE', } diff --git a/packages/messages/lib/enums/Viber/MessageCategory.ts b/packages/messages/lib/enums/Viber/MessageCategory.ts index aa069752..e8349758 100644 --- a/packages/messages/lib/enums/Viber/MessageCategory.ts +++ b/packages/messages/lib/enums/Viber/MessageCategory.ts @@ -1,7 +1,19 @@ /** - * @deprecated please use ViberCategory + * @deprecated Please use ViberCategory + * Enum representing message categories for Viber messages. + * + * These categories are used to classify the type and purpose of Viber messages. + * + * @group Viber */ export enum MessageCategory { - TRANSACTION = 'transaction', - PROMOTINO = 'promotion', + /** + * Represents the transaction message category. + */ + TRANSACTION = 'transaction', + + /** + * Represents the promotion message category. + */ + PROMOTION = 'promotion', } diff --git a/packages/messages/lib/enums/Viber/ViberCategory.ts b/packages/messages/lib/enums/Viber/ViberCategory.ts index 635f027e..a57a0c0f 100644 --- a/packages/messages/lib/enums/Viber/ViberCategory.ts +++ b/packages/messages/lib/enums/Viber/ViberCategory.ts @@ -1,4 +1,18 @@ +/** + * Enum representing message categories for Viber messages. + * + * These categories are used to classify the type and purpose of Viber messages. + * + * @group Viber + */ export enum ViberCategory { - TRANSACTION = 'transaction', - PROMOTION = 'promotion', + /** + * Represents the transaction message category. + */ + TRANSACTION = 'transaction', + + /** + * Represents the promotion message category. + */ + PROMOTION = 'promotion', } diff --git a/packages/messages/lib/enums/WhatsApp/WhatsAppLanguageCodes.ts b/packages/messages/lib/enums/WhatsApp/WhatsAppLanguageCodes.ts index 27e8f6b4..946db544 100644 --- a/packages/messages/lib/enums/WhatsApp/WhatsAppLanguageCodes.ts +++ b/packages/messages/lib/enums/WhatsApp/WhatsAppLanguageCodes.ts @@ -1,73 +1,80 @@ +/** + * Enum representing language codes for WhatsApp messages. + * + * These language codes are used to specify the language of WhatsApp messages. + * + * @group WhatsApp + */ export enum WhatsAppLanguageCode { - AFRIKAANS = 'af', - ALBANIAN = 'sq', - ARABIC = 'ar', - AZERBAIJANI = 'az', - BENGALI = 'bn', - BULGARIAN = 'bg', - CATALAN = 'ca', - CHINESE_CHN = 'zh_CN', - CHINESE_HKG = 'zh_HK', - CHINESE_TAI = 'zh_TW', - CROATIAN = 'hr', - CZECH = 'cs', - DANISH = 'da', - DUTCH = 'nl', - ENGLISH = 'en', - ENGLISH_UK = 'en_GB', - ENGLISH_US = 'en_US', - ESTONIAN = 'et', - FILIPINO = 'fil', - FINNISH = 'fi', - FRENCH = 'fr', - GEORGIAN = 'ka', - GERMAN = 'de', - GREEK = 'el', - GUJARATI = 'gu', - HAUSA = 'ha', - HEBREW = 'he', - HINDI = 'hi', - HUNGARIAN = 'hu', - INDONESIAN = 'id', - IRISH = 'ga', - ITALIAN = 'it', - JAPANESE = 'ja', - KANNADA = 'kn', - KAZAKH = 'kk', - KINYARWANDA = 'rw_RW', - KOREAN = 'ko', - KYRGYZ_KYRGYZSTAN = 'ky_KG', - LAO = 'lo', - LATVIAN = 'lv', - LITHUANIAN = 'lt', - MACEDONIAN = 'mk', - MALAY = 'ms', - MALAYALAM = 'ml', - MARATHI = 'mr', - NORWEGIAN = 'nb', - PERSIAN = 'fa', - POLISH = 'pl', - PORTUGUESE_BR = 'pt_BR', - PORTUGUESE_POR = 'pt_PT', - PUNJABI = 'pa', - ROMANIAN = 'ro', - RUSSIAN = 'ru', - SERBIAN = 'sr', - SLOVAK = 'sk', - SLOVENIAN = 'sl', - SPANISH = 'es', - SPANISH_ARG = 'es_AR', - SPANISH_SPA = 'es_ES', - SPANISH_MEX = 'es_MX', - SWAHILI = 'sw', - SWEDISH = 'sv', - TAMIL = 'ta', - TELUGU = 'te', - THAI = 'th', - TURKISH = 'tr', - UKRAINIAN = 'uk', - URDU = 'ur', - UZBEK = 'uz', - VIETNAMESE = 'vi', - ZULU = 'zu', + AFRIKAANS = 'af', + ALBANIAN = 'sq', + ARABIC = 'ar', + AZERBAIJANI = 'az', + BENGALI = 'bn', + BULGARIAN = 'bg', + CATALAN = 'ca', + CHINESE_CHN = 'zh_CN', + CHINESE_HKG = 'zh_HK', + CHINESE_TAI = 'zh_TW', + CROATIAN = 'hr', + CZECH = 'cs', + DANISH = 'da', + DUTCH = 'nl', + ENGLISH = 'en', + ENGLISH_UK = 'en_GB', + ENGLISH_US = 'en_US', + ESTONIAN = 'et', + FILIPINO = 'fil', + FINNISH = 'fi', + FRENCH = 'fr', + GEORGIAN = 'ka', + GERMAN = 'de', + GREEK = 'el', + GUJARATI = 'gu', + HAUSA = 'ha', + HEBREW = 'he', + HINDI = 'hi', + HUNGARIAN = 'hu', + INDONESIAN = 'id', + IRISH = 'ga', + ITALIAN = 'it', + JAPANESE = 'ja', + KANNADA = 'kn', + KAZAKH = 'kk', + KINYARWANDA = 'rw_RW', + KOREAN = 'ko', + KYRGYZ_KYRGYZSTAN = 'ky_KG', + LAO = 'lo', + LATVIAN = 'lv', + LITHUANIAN = 'lt', + MACEDONIAN = 'mk', + MALAY = 'ms', + MALAYALAM = 'ml', + MARATHI = 'mr', + NORWEGIAN = 'nb', + PERSIAN = 'fa', + POLISH = 'pl', + PORTUGUESE_BR = 'pt_BR', + PORTUGUESE_POR = 'pt_PT', + PUNJABI = 'pa', + ROMANIAN = 'ro', + RUSSIAN = 'ru', + SERBIAN = 'sr', + SLOVAK = 'sk', + SLOVENIAN = 'sl', + SPANISH = 'es', + SPANISH_ARG = 'es_AR', + SPANISH_SPA = 'es_ES', + SPANISH_MEX = 'es_MX', + SWAHILI = 'sw', + SWEDISH = 'sv', + TAMIL = 'ta', + TELUGU = 'te', + THAI = 'th', + TURKISH = 'tr', + UKRAINIAN = 'uk', + URDU = 'ur', + UZBEK = 'uz', + VIETNAMESE = 'vi', + ZULU = 'zu', } diff --git a/packages/messages/lib/enums/index.ts b/packages/messages/lib/enums/index.ts index 824d0fd2..74969f5f 100644 --- a/packages/messages/lib/enums/index.ts +++ b/packages/messages/lib/enums/index.ts @@ -1,3 +1,4 @@ -export * from './Messenger/index'; -export * from './Viber/index'; -export * from './WhatsApp/index'; +export * from './Messenger'; +export * from './Viber'; +export * from './WhatsApp'; +export * from './Channels'; diff --git a/packages/messages/lib/interfaces/AudioObject.ts b/packages/messages/lib/interfaces/AudioObject.ts index 86b1914a..6485a517 100644 --- a/packages/messages/lib/interfaces/AudioObject.ts +++ b/packages/messages/lib/interfaces/AudioObject.ts @@ -1,7 +1,20 @@ + /** - * @deprecated please use approiate paramters type + * Represents an audio object. + * + * An audio object typically includes a URL pointing to an audio file and an optional caption. + * + * @deprecated Please use types instead of interfaces. + * @ignore */ export interface AudioObject { - url: string - caption?: string + /** + * The URL of the audio file. + */ + url: string; + + /** + * An optional caption to accompany the audio. + */ + caption?: string; } diff --git a/packages/messages/lib/interfaces/FileObject.ts b/packages/messages/lib/interfaces/FileObject.ts index da791cab..939c5862 100644 --- a/packages/messages/lib/interfaces/FileObject.ts +++ b/packages/messages/lib/interfaces/FileObject.ts @@ -1,7 +1,19 @@ /** - * @deprecated please use file params + * Represents a file object. + * + * A file object typically includes a URL pointing to a file and an optional caption. + * + * @deprecated Please use types instead of interfaces. + * @ignore */ export interface FileObject { - url: string - caption?: string + /** + * The URL of the file. + */ + url: string; + + /** + * An optional caption to accompany the file. + */ + caption?: string; } diff --git a/packages/messages/lib/interfaces/ImageObject.ts b/packages/messages/lib/interfaces/ImageObject.ts index 457e9574..56cba529 100644 --- a/packages/messages/lib/interfaces/ImageObject.ts +++ b/packages/messages/lib/interfaces/ImageObject.ts @@ -1,7 +1,20 @@ /** - * @deprecated use message params type instead + * Represents an image object. + * + * An image object typically includes a URL pointing to an image and an optional caption. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore */ export interface ImageObject { - url: string - caption?: string + /** + * The URL of the image. + */ + url: string; + + /** + * An optional caption to accompany the image. + */ + caption?: string; } diff --git a/packages/messages/lib/interfaces/MMS/MMSAudioInterface.ts b/packages/messages/lib/interfaces/MMS/MMSAudioInterface.ts index 16b04de8..26824059 100644 --- a/packages/messages/lib/interfaces/MMS/MMSAudioInterface.ts +++ b/packages/messages/lib/interfaces/MMS/MMSAudioInterface.ts @@ -1,6 +1,13 @@ import { MessageAudioInterface } from '../MessageAudioInterface'; import { MMSChannelInterface } from './MMSChannelInterface'; +/** + * Represents an interface for defining MMS audio messages. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface MMSAudioInterface - extends MessageAudioInterface, - MMSChannelInterface {} + extends MessageAudioInterface, + MMSChannelInterface {} diff --git a/packages/messages/lib/interfaces/MMS/MMSChannelInterface.ts b/packages/messages/lib/interfaces/MMS/MMSChannelInterface.ts index fcafd456..e3d5874b 100644 --- a/packages/messages/lib/interfaces/MMS/MMSChannelInterface.ts +++ b/packages/messages/lib/interfaces/MMS/MMSChannelInterface.ts @@ -1,3 +1,10 @@ +/** + * Represents an interface for defining MMS channel messages. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface MMSChannelInterface { - channel: 'mms' + channel: 'mms'; } diff --git a/packages/messages/lib/interfaces/MMS/MMSImageInterface.ts b/packages/messages/lib/interfaces/MMS/MMSImageInterface.ts index d860665d..9c79fc23 100644 --- a/packages/messages/lib/interfaces/MMS/MMSImageInterface.ts +++ b/packages/messages/lib/interfaces/MMS/MMSImageInterface.ts @@ -1,6 +1,11 @@ import { MessageImageInterface } from '../MessageImageInterface'; import { MMSChannelInterface } from './MMSChannelInterface'; -export interface MMSImageInterface - extends MessageImageInterface, - MMSChannelInterface {} +/** + * Represents an interface for defining MMS channel messages with images. + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ +export interface MMSImageInterface extends + MessageImageInterface, MMSChannelInterface {} diff --git a/packages/messages/lib/interfaces/MMS/MMSVcardInterface.ts b/packages/messages/lib/interfaces/MMS/MMSVcardInterface.ts index 0c0a55aa..fbd1391a 100644 --- a/packages/messages/lib/interfaces/MMS/MMSVcardInterface.ts +++ b/packages/messages/lib/interfaces/MMS/MMSVcardInterface.ts @@ -1,6 +1,13 @@ import { MMSChannelInterface } from './MMSChannelInterface'; import { MessageVCardInterface } from '../MessageVCardInterface'; +/** + * Represents an interface for defining MMS channel messages with vCards. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface MMSVcardInterface - extends MessageVCardInterface, - MMSChannelInterface {} + extends MessageVCardInterface, + MMSChannelInterface {} diff --git a/packages/messages/lib/interfaces/MMS/MMSVideoInterface.ts b/packages/messages/lib/interfaces/MMS/MMSVideoInterface.ts index 18059298..67720556 100644 --- a/packages/messages/lib/interfaces/MMS/MMSVideoInterface.ts +++ b/packages/messages/lib/interfaces/MMS/MMSVideoInterface.ts @@ -1,6 +1,12 @@ import { MessageVideoInterface } from '../MessageVideoInterface'; import { MMSChannelInterface } from './MMSChannelInterface'; +/** + * Represents an interface for defining MMS channel messages with video. + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface MMSVideoInterface - extends MessageVideoInterface, - MMSChannelInterface {} + extends MessageVideoInterface, + MMSChannelInterface {} diff --git a/packages/messages/lib/interfaces/MessageAudioInterface.ts b/packages/messages/lib/interfaces/MessageAudioInterface.ts index 4e3811f2..2102626f 100644 --- a/packages/messages/lib/interfaces/MessageAudioInterface.ts +++ b/packages/messages/lib/interfaces/MessageAudioInterface.ts @@ -1,7 +1,23 @@ import { MessageInterface } from './MessageInterface'; import { MessageAudioType } from '../types'; +/** + * Represents a message interface for audio messages. + * + * This interface is used for defining audio messages and includes the message type 'audio' and the audio content. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface MessageAudioInterface extends MessageInterface { - messageType: 'audio' - audio: MessageAudioType + /** + * Specifies the message type as 'audio'. + */ + messageType: 'audio'; + + /** + * The audio content of the message, including the URL to the audio file. + */ + audio: MessageAudioType; } diff --git a/packages/messages/lib/interfaces/MessageFileInterface.ts b/packages/messages/lib/interfaces/MessageFileInterface.ts index 234e6db9..1249d8c9 100644 --- a/packages/messages/lib/interfaces/MessageFileInterface.ts +++ b/packages/messages/lib/interfaces/MessageFileInterface.ts @@ -1,7 +1,24 @@ import { MessageInterface } from './MessageInterface'; import { MessageFileType } from '../types'; - +/** + * Represents a message interface for file attachments. + * + * This interface is used for defining messages with file attachments and + * includes the message type 'file' and the file content. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface MessageFileInterface extends MessageInterface { - messageType: 'file' - file: MessageFileType + /** + * Specifies the message type as 'file'. + */ + messageType: 'file'; + + /** + * The file content of the message, including the URL to the file and an + * optional caption. + */ + file: MessageFileType; } diff --git a/packages/messages/lib/interfaces/MessageImageInterface.ts b/packages/messages/lib/interfaces/MessageImageInterface.ts index b21a19b8..88f15512 100644 --- a/packages/messages/lib/interfaces/MessageImageInterface.ts +++ b/packages/messages/lib/interfaces/MessageImageInterface.ts @@ -1,7 +1,24 @@ import { MessageInterface } from './MessageInterface'; import { MessageImageType } from '../types'; +/** + * Represents a message interface for image attachments. + * + * This interface is used for defining messages with image attachments and + * includes the message type 'image' and the image content. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface MessageImageInterface extends MessageInterface { - messageType: 'image' - image: MessageImageType + /** + * Specifies the message type as 'image'. + */ + messageType: 'image'; + + /** + * The image content of the message, including the URL to the image. + */ + image: MessageImageType; } diff --git a/packages/messages/lib/interfaces/MessageInterface.ts b/packages/messages/lib/interfaces/MessageInterface.ts index f2a4eca5..27c08fc7 100644 --- a/packages/messages/lib/interfaces/MessageInterface.ts +++ b/packages/messages/lib/interfaces/MessageInterface.ts @@ -1,5 +1,26 @@ +/** + * Represents a message interface for defining common message properties. + * + * This interface includes essential properties shared by various message types, + * such as the recipient's phone number, sender's ID, and an optional client reference. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface MessageInterface { - to: string - from: string - clientRef?: string + /** + * The phone number of the message recipient in E.164 format. + */ + to: string; + + /** + * The ID of the message sender. + */ + from: string; + + /** + * An optional client reference of up to 100 characters, which can be included in every message status. + */ + clientRef?: string; } diff --git a/packages/messages/lib/interfaces/MessageSuccess.ts b/packages/messages/lib/interfaces/MessageSuccess.ts deleted file mode 100644 index 910d6d02..00000000 --- a/packages/messages/lib/interfaces/MessageSuccess.ts +++ /dev/null @@ -1,3 +0,0 @@ -export interface MessageSuccess { - messageUUID: string -} diff --git a/packages/messages/lib/interfaces/MessageSuccessInterface.ts b/packages/messages/lib/interfaces/MessageSuccessInterface.ts new file mode 100644 index 00000000..57ddfc40 --- /dev/null +++ b/packages/messages/lib/interfaces/MessageSuccessInterface.ts @@ -0,0 +1,16 @@ +/** + * Represents a successful message delivery response. + * + * This interface includes a property for the message UUID, which uniquely + * identifies the sent message. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ +export interface MessageSuccessInterface { + /** + * The unique identifier (UUID) assigned to the sent message. + */ + messageUUID: string; +} diff --git a/packages/messages/lib/interfaces/MessageTextInterface.ts b/packages/messages/lib/interfaces/MessageTextInterface.ts index 8cf8ccd7..dc7ee020 100644 --- a/packages/messages/lib/interfaces/MessageTextInterface.ts +++ b/packages/messages/lib/interfaces/MessageTextInterface.ts @@ -1,6 +1,23 @@ import { MessageInterface } from './MessageInterface'; +/** + * Represents a text message type. + * + * This interface extends the base `MessageInterface` and includes a `text` property + * for the text message content and a `messageType` property indicating it as a text message. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface MessageTextInterface extends MessageInterface { - text: string - messageType: 'text' + /** + * The text content of the message. + */ + text: string; + + /** + * The message type, which is set to 'text' for text messages. + */ + messageType: 'text'; } diff --git a/packages/messages/lib/interfaces/MessageVCardInterface.ts b/packages/messages/lib/interfaces/MessageVCardInterface.ts index a6807e1c..4b1d57ee 100644 --- a/packages/messages/lib/interfaces/MessageVCardInterface.ts +++ b/packages/messages/lib/interfaces/MessageVCardInterface.ts @@ -1,7 +1,23 @@ import { MessageInterface } from './MessageInterface'; import { MessageVcardType } from '../types'; - +/** + * Represents a VCard message type. + * + * This interface extends the base `MessageInterface` and includes a `vcard` property + * for the VCard message content and a `messageType` property indicating it as a VCard message. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface MessageVCardInterface extends MessageInterface { - messageType: 'vcard' - vcard: MessageVcardType + /** + * The VCard content of the message. + */ + vcard: MessageVcardType; + + /** + * The message type, which is set to 'vcard' for VCard messages. + */ + messageType: 'vcard'; } diff --git a/packages/messages/lib/interfaces/MessageVideoInterface.ts b/packages/messages/lib/interfaces/MessageVideoInterface.ts index ca75ab24..b27269ca 100644 --- a/packages/messages/lib/interfaces/MessageVideoInterface.ts +++ b/packages/messages/lib/interfaces/MessageVideoInterface.ts @@ -1,7 +1,24 @@ import { MessageInterface } from './MessageInterface'; import { MessageVideoType } from '../types'; +/** + * Represents a video message type. + * + * This interface extends the base `MessageInterface` and includes a `video` property + * for the video message content and a `messageType` property indicating it as a video message. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface MessageVideoInterface extends MessageInterface { - messageType: 'video' - video: MessageVideoType + /** + * The video content of the message. + */ + video: MessageVideoType; + + /** + * The message type, which is set to 'video' for video messages. + */ + messageType: 'video'; } diff --git a/packages/messages/lib/interfaces/Messenger/MessageType.ts b/packages/messages/lib/interfaces/Messenger/MessageType.ts index b76d43f1..ae389a70 100644 --- a/packages/messages/lib/interfaces/Messenger/MessageType.ts +++ b/packages/messages/lib/interfaces/Messenger/MessageType.ts @@ -1,9 +1,10 @@ -import { MessageCategory } from '../../enums/Messenger/MessageCategory'; +import { MessengerType } from "../../types"; /** - * @deprecated please use messenger interfaces + * Represents a message type for the Messenger category. + * + * @deprecated Please use messenger types. + * + * @ignore */ -export interface MessageType { - category: MessageCategory - tag?: string -} +export interface MessageType extends MessengerType {} diff --git a/packages/messages/lib/interfaces/Messenger/MessengerAudioInterface.ts b/packages/messages/lib/interfaces/Messenger/MessengerAudioInterface.ts index 98a3ddda..55e909c1 100644 --- a/packages/messages/lib/interfaces/Messenger/MessengerAudioInterface.ts +++ b/packages/messages/lib/interfaces/Messenger/MessengerAudioInterface.ts @@ -1,6 +1,13 @@ import { MessengerChannelInterface } from './MessengerChannelInterface'; import { MessageAudioInterface } from '../MessageAudioInterface'; +/** + * Represents an interface for sending audio messages via Messenger. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface MessengerAudioInterface extends MessengerChannelInterface, MessageAudioInterface {} diff --git a/packages/messages/lib/interfaces/Messenger/MessengerChannelInterface.ts b/packages/messages/lib/interfaces/Messenger/MessengerChannelInterface.ts index 63978cd6..0f5b912d 100644 --- a/packages/messages/lib/interfaces/Messenger/MessengerChannelInterface.ts +++ b/packages/messages/lib/interfaces/Messenger/MessengerChannelInterface.ts @@ -1,6 +1,20 @@ import { MessengerType } from '../../types'; +/** + * Represents an interface for defining the Messenger channel and MessengerType. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface MessengerChannelInterface { - channel: 'messenger' - messenger: MessengerType + /** + * The channel type, which should be 'messenger'. + */ + channel: 'messenger'; + + /** + * Details about the Messenger type. + */ + messenger: MessengerType; } diff --git a/packages/messages/lib/interfaces/Messenger/MessengerFileInterface.ts b/packages/messages/lib/interfaces/Messenger/MessengerFileInterface.ts index cc15ad6c..f646941b 100644 --- a/packages/messages/lib/interfaces/Messenger/MessengerFileInterface.ts +++ b/packages/messages/lib/interfaces/Messenger/MessengerFileInterface.ts @@ -1,6 +1,13 @@ import { MessengerChannelInterface } from './MessengerChannelInterface'; import { MessageFileInterface } from '../MessageFileInterface'; +/** + * Represents an interface for defining Messenger file messages. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface MessengerFileInterface - extends MessengerChannelInterface, - MessageFileInterface {} + extends MessengerChannelInterface, + MessageFileInterface {} diff --git a/packages/messages/lib/interfaces/Messenger/MessengerImageInterface.ts b/packages/messages/lib/interfaces/Messenger/MessengerImageInterface.ts index 01340242..f25300e0 100644 --- a/packages/messages/lib/interfaces/Messenger/MessengerImageInterface.ts +++ b/packages/messages/lib/interfaces/Messenger/MessengerImageInterface.ts @@ -1,6 +1,13 @@ import { MessengerChannelInterface } from './MessengerChannelInterface'; import { MessageImageInterface } from '../MessageImageInterface'; +/** + * Represents an interface for defining Messenger image messages. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface MessengerImageInterface - extends MessengerChannelInterface, - MessageImageInterface {} + extends MessengerChannelInterface, + MessageImageInterface {} diff --git a/packages/messages/lib/interfaces/Messenger/MessengerTextInterface.ts b/packages/messages/lib/interfaces/Messenger/MessengerTextInterface.ts index f425e6cd..b8d05844 100644 --- a/packages/messages/lib/interfaces/Messenger/MessengerTextInterface.ts +++ b/packages/messages/lib/interfaces/Messenger/MessengerTextInterface.ts @@ -1,6 +1,13 @@ import { MessengerChannelInterface } from './MessengerChannelInterface'; import { MessageTextInterface } from '../MessageTextInterface'; +/** + * Represents an interface for defining Messenger text messages. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface MessengerTextInterface - extends MessengerChannelInterface, - MessageTextInterface {} + extends MessengerChannelInterface, + MessageTextInterface {} diff --git a/packages/messages/lib/interfaces/Messenger/MessengerVideoInterface.ts b/packages/messages/lib/interfaces/Messenger/MessengerVideoInterface.ts index 63e61a77..1573449f 100644 --- a/packages/messages/lib/interfaces/Messenger/MessengerVideoInterface.ts +++ b/packages/messages/lib/interfaces/Messenger/MessengerVideoInterface.ts @@ -1,6 +1,13 @@ import { MessengerChannelInterface } from './MessengerChannelInterface'; import { MessageVideoInterface } from '../MessageVideoInterface'; +/** + * Represents an interface for defining Messenger video messages. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface MessengerVideoInterface - extends MessengerChannelInterface, - MessageVideoInterface {} + extends MessengerChannelInterface, + MessageVideoInterface {} diff --git a/packages/messages/lib/interfaces/SMS/SMSTextInterface.ts b/packages/messages/lib/interfaces/SMS/SMSTextInterface.ts index 850aaa85..cafa2df9 100644 --- a/packages/messages/lib/interfaces/SMS/SMSTextInterface.ts +++ b/packages/messages/lib/interfaces/SMS/SMSTextInterface.ts @@ -1,5 +1,15 @@ import { MessageTextInterface } from '../MessageTextInterface'; +/** + * Represents an interface for defining SMS channel text messages. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface SMSTextInterface extends MessageTextInterface { - channel: 'sms' + /** + * The channel for SMS, which is always 'sms'. + */ + channel: 'sms'; } diff --git a/packages/messages/lib/interfaces/Viber/MessageConfig.ts b/packages/messages/lib/interfaces/Viber/MessageConfig.ts index 1b60ec63..8eb07d35 100644 --- a/packages/messages/lib/interfaces/Viber/MessageConfig.ts +++ b/packages/messages/lib/interfaces/Viber/MessageConfig.ts @@ -1,10 +1,26 @@ import { MessageCategory } from '../../enums/Viber/MessageCategory'; /** - * @deprecated please use Viber Service instead + * Represents a message configuration. for Viber + * + * @deprecated Please use types instead of interfaces. + * + * @ignore */ export interface MessageConfig { - category: MessageCategory - ttl?: number - type?: string + /** + * The category of the message. + */ + category: MessageCategory; + + /** + * The time-to-live (TTL) of the message in seconds. + */ + ttl?: number; + + /** + * The type of the message. + */ + type?: string; } + diff --git a/packages/messages/lib/interfaces/Viber/ViberChannelInterface.ts b/packages/messages/lib/interfaces/Viber/ViberChannelInterface.ts index f16ddea3..50445e8c 100644 --- a/packages/messages/lib/interfaces/Viber/ViberChannelInterface.ts +++ b/packages/messages/lib/interfaces/Viber/ViberChannelInterface.ts @@ -1,3 +1,13 @@ +/** + * Represents the Viber channel interface. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface ViberChannelInterface { - channel: 'viber_service' + /** + * Specifies the channel type, which is 'viber_service'. + */ + channel: 'viber_service'; } diff --git a/packages/messages/lib/interfaces/Viber/ViberFileInterface.ts b/packages/messages/lib/interfaces/Viber/ViberFileInterface.ts index 53911d90..21b8b247 100644 --- a/packages/messages/lib/interfaces/Viber/ViberFileInterface.ts +++ b/packages/messages/lib/interfaces/Viber/ViberFileInterface.ts @@ -2,8 +2,19 @@ import { ViberChannelInterface } from './ViberChannelInterface'; import { MessageFileInterface } from '../MessageFileInterface'; import { ViberService } from '../../types'; +/** + * Represents the Viber file interface. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + * + */ export interface ViberFileInterface - extends ViberChannelInterface, - MessageFileInterface { - viberService: ViberService + extends ViberChannelInterface, + MessageFileInterface { + /** + * Represents Viber-specific service information. + */ + viberService: ViberService; } diff --git a/packages/messages/lib/interfaces/Viber/ViberImageInterface.ts b/packages/messages/lib/interfaces/Viber/ViberImageInterface.ts index ebc49075..bfa5eddf 100644 --- a/packages/messages/lib/interfaces/Viber/ViberImageInterface.ts +++ b/packages/messages/lib/interfaces/Viber/ViberImageInterface.ts @@ -2,8 +2,19 @@ import { ViberChannelInterface } from './ViberChannelInterface'; import { MessageImageInterface } from '../MessageImageInterface'; import { ViberActionParams } from '../../types'; +/** + * Represents the Viber image interface. + * + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface ViberImageInterface - extends ViberChannelInterface, - MessageImageInterface { - viberService: ViberActionParams + extends ViberChannelInterface, + MessageImageInterface { + /** + * Represents Viber-specific action parameters. + */ + viberService: ViberActionParams; } diff --git a/packages/messages/lib/interfaces/Viber/ViberTextInterface.ts b/packages/messages/lib/interfaces/Viber/ViberTextInterface.ts index ce9d0705..0a635e7a 100644 --- a/packages/messages/lib/interfaces/Viber/ViberTextInterface.ts +++ b/packages/messages/lib/interfaces/Viber/ViberTextInterface.ts @@ -2,8 +2,18 @@ import { MessageTextInterface } from '../MessageTextInterface'; import { ViberChannelInterface } from './ViberChannelInterface'; import { ViberActionParams } from '../../types'; +/** + * Represents the Viber text interface. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface ViberTextInterface - extends MessageTextInterface, - ViberChannelInterface { - viberService: ViberActionParams + extends MessageTextInterface, + ViberChannelInterface { + /** + * Represents Viber-specific action parameters. + */ + viberService: ViberActionParams; } diff --git a/packages/messages/lib/interfaces/Viber/ViberVideoInterface.ts b/packages/messages/lib/interfaces/Viber/ViberVideoInterface.ts index 8626d012..a0fc3e2a 100644 --- a/packages/messages/lib/interfaces/Viber/ViberVideoInterface.ts +++ b/packages/messages/lib/interfaces/Viber/ViberVideoInterface.ts @@ -2,11 +2,27 @@ import { ViberChannelInterface } from './ViberChannelInterface'; import { MessageVideoInterface } from '../MessageVideoInterface'; import { ViberService } from '../../types'; +/** + * Represents the Viber video interface. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface ViberVideoInterface - extends ViberChannelInterface, - MessageVideoInterface { - viberService: { - duration: string - fileSize: string - } & ViberService + extends ViberChannelInterface, + MessageVideoInterface { + /** + * Represents Viber-specific video service parameters. + */ + viberService: { + /** + * The duration of the video in seconds. + */ + duration: string; + /** + * The file size of the video in MB. + */ + fileSize: string; + } & ViberService; } diff --git a/packages/messages/lib/interfaces/VideoObject.ts b/packages/messages/lib/interfaces/VideoObject.ts index 9c704e05..d78bd669 100644 --- a/packages/messages/lib/interfaces/VideoObject.ts +++ b/packages/messages/lib/interfaces/VideoObject.ts @@ -1,7 +1,18 @@ /** - * @deprecated use message params type instead + * Represents a video object with an optional caption. + * + * @deprecated Please use types instead of interfaces + * + * @ignore */ export interface VideoObject { - url: string - caption?: string + /** + * The URL of the video. + */ + url: string; + + /** + * An optional caption for the video. + */ + caption?: string; } diff --git a/packages/messages/lib/interfaces/WhatsApp/CustomPayload.ts b/packages/messages/lib/interfaces/WhatsApp/CustomPayload.ts index 491c675c..d77548fc 100644 --- a/packages/messages/lib/interfaces/WhatsApp/CustomPayload.ts +++ b/packages/messages/lib/interfaces/WhatsApp/CustomPayload.ts @@ -1,6 +1,13 @@ /** - * @deprecated + * Represents a custom payload. + * + * @deprecated Please note that this interface is deprecated. + * + * @ignore */ export interface CustomPayload { - [key: string]: any + /** + * The payload content, which can be of any type. + */ + [key: string]: unknown; } diff --git a/packages/messages/lib/interfaces/WhatsApp/MessageTemplate.ts b/packages/messages/lib/interfaces/WhatsApp/MessageTemplate.ts index f065d2dc..2264fe56 100644 --- a/packages/messages/lib/interfaces/WhatsApp/MessageTemplate.ts +++ b/packages/messages/lib/interfaces/WhatsApp/MessageTemplate.ts @@ -1,7 +1,10 @@ +import { WhatsAppTemplateType } from "../../types"; + /** - * @deprecated please use WhatsAppTemplate instead + * Represents a message template. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore */ -export interface MessageTemplate { - name: string - parameters: string[] -} +export interface MessageTemplate extends WhatsAppTemplateType {} diff --git a/packages/messages/lib/interfaces/WhatsApp/WhatsAppAudioInterface.ts b/packages/messages/lib/interfaces/WhatsApp/WhatsAppAudioInterface.ts index 22df992b..49b399b1 100644 --- a/packages/messages/lib/interfaces/WhatsApp/WhatsAppAudioInterface.ts +++ b/packages/messages/lib/interfaces/WhatsApp/WhatsAppAudioInterface.ts @@ -1,6 +1,13 @@ import { WhatsAppChannelInterface } from './WhatsAppChannelInterface'; import { MessageAudioInterface } from '../MessageAudioInterface'; +/** + * Represents an audio message type for WhatsApp. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface WhatsAppAudioInterface - extends WhatsAppChannelInterface, - MessageAudioInterface {} + extends WhatsAppChannelInterface, + MessageAudioInterface {} diff --git a/packages/messages/lib/interfaces/WhatsApp/WhatsAppChannelInterface.ts b/packages/messages/lib/interfaces/WhatsApp/WhatsAppChannelInterface.ts index ea4d01b3..dc7a67eb 100644 --- a/packages/messages/lib/interfaces/WhatsApp/WhatsAppChannelInterface.ts +++ b/packages/messages/lib/interfaces/WhatsApp/WhatsAppChannelInterface.ts @@ -1,3 +1,10 @@ +/** + * Represents a WhatsApp channel interface. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface WhatsAppChannelInterface { - channel: 'whatsapp' + channel: 'whatsapp' } diff --git a/packages/messages/lib/interfaces/WhatsApp/WhatsAppCustomInterface.ts b/packages/messages/lib/interfaces/WhatsApp/WhatsAppCustomInterface.ts index 8763bbe5..4300b34e 100644 --- a/packages/messages/lib/interfaces/WhatsApp/WhatsAppCustomInterface.ts +++ b/packages/messages/lib/interfaces/WhatsApp/WhatsAppCustomInterface.ts @@ -2,8 +2,18 @@ import { MessageInterface } from '../MessageInterface'; import { WhatsAppChannelInterface } from './WhatsAppChannelInterface'; import { WhatsAppCustomType } from '../../types'; +/** + * Represents a WhatsApp custom message interface. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface WhatsAppCustomInterface - extends MessageInterface, - WhatsAppChannelInterface { - custom: WhatsAppCustomType + extends MessageInterface, + WhatsAppChannelInterface { + /** + * Custom data for the WhatsApp message. + */ + custom: WhatsAppCustomType; } diff --git a/packages/messages/lib/interfaces/WhatsApp/WhatsAppFileInterface.ts b/packages/messages/lib/interfaces/WhatsApp/WhatsAppFileInterface.ts index f8bee920..d0f5f245 100644 --- a/packages/messages/lib/interfaces/WhatsApp/WhatsAppFileInterface.ts +++ b/packages/messages/lib/interfaces/WhatsApp/WhatsAppFileInterface.ts @@ -1,6 +1,13 @@ import { WhatsAppChannelInterface } from './WhatsAppChannelInterface'; import { MessageFileInterface } from '../MessageFileInterface'; +/** + * Represents an interface for WhatsApp file messages. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface WhatsAppFileInterface - extends WhatsAppChannelInterface, - MessageFileInterface {} + extends WhatsAppChannelInterface, + MessageFileInterface {} diff --git a/packages/messages/lib/interfaces/WhatsApp/WhatsAppImageInterface.ts b/packages/messages/lib/interfaces/WhatsApp/WhatsAppImageInterface.ts index 21a384f5..4303d759 100644 --- a/packages/messages/lib/interfaces/WhatsApp/WhatsAppImageInterface.ts +++ b/packages/messages/lib/interfaces/WhatsApp/WhatsAppImageInterface.ts @@ -1,6 +1,13 @@ import { WhatsAppChannelInterface } from './WhatsAppChannelInterface'; import { MessageImageInterface } from '../MessageImageInterface'; +/** + * Represents an interface for WhatsApp image messages. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface WhatsAppImageInterface - extends WhatsAppChannelInterface, - MessageImageInterface {} + extends WhatsAppChannelInterface, + MessageImageInterface {} diff --git a/packages/messages/lib/interfaces/WhatsApp/WhatsAppStickerInterface.ts b/packages/messages/lib/interfaces/WhatsApp/WhatsAppStickerInterface.ts index 012e502b..044aa475 100644 --- a/packages/messages/lib/interfaces/WhatsApp/WhatsAppStickerInterface.ts +++ b/packages/messages/lib/interfaces/WhatsApp/WhatsAppStickerInterface.ts @@ -3,9 +3,24 @@ import { MessageInterface } from '../MessageInterface'; import { WhatsAppStickerUrlType } from '../../types'; import { WhatsAppStickerIdType } from '../../types'; +/** + * Represents an interface for WhatsApp sticker messages. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface WhatsAppStickerInterface - extends WhatsAppChannelInterface, - MessageInterface { - messageType: 'sticker' - sticker: WhatsAppStickerUrlType | WhatsAppStickerIdType + extends WhatsAppChannelInterface, + MessageInterface { + /** + * Specifies the type of message, which is "sticker" for sticker messages. + */ + messageType: 'sticker'; + + /** + * The sticker to be sent. It can be either a sticker URL or a sticker ID. + */ + sticker: WhatsAppStickerUrlType | WhatsAppStickerIdType; } + diff --git a/packages/messages/lib/interfaces/WhatsApp/WhatsAppTemplateInterface.ts b/packages/messages/lib/interfaces/WhatsApp/WhatsAppTemplateInterface.ts index ea5b08ce..def98b5b 100644 --- a/packages/messages/lib/interfaces/WhatsApp/WhatsAppTemplateInterface.ts +++ b/packages/messages/lib/interfaces/WhatsApp/WhatsAppTemplateInterface.ts @@ -3,10 +3,28 @@ import { MessageInterface } from '../MessageInterface'; import { WhatsAppPolicyType } from '../../types'; import { WhatsAppTemplateType } from '../../types'; +/** + * Represents an interface for WhatsApp template messages. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface WhatsAppTemplateInterface - extends WhatsAppChannelInterface, - MessageInterface { - messageType: 'template' - whatsapp: WhatsAppPolicyType - template: WhatsAppTemplateType + extends WhatsAppChannelInterface, + MessageInterface { + /** + * Specifies the type of message, which is "template" for template messages. + */ + messageType: 'template'; + + /** + * Defines the WhatsApp policy type for the template message. + */ + whatsapp: WhatsAppPolicyType; + + /** + * Specifies the details of the template to be sent, including its name and parameters. + */ + template: WhatsAppTemplateType; } diff --git a/packages/messages/lib/interfaces/WhatsApp/WhatsAppTextInterface.ts b/packages/messages/lib/interfaces/WhatsApp/WhatsAppTextInterface.ts index 4d7743b2..6f57261b 100644 --- a/packages/messages/lib/interfaces/WhatsApp/WhatsAppTextInterface.ts +++ b/packages/messages/lib/interfaces/WhatsApp/WhatsAppTextInterface.ts @@ -1,6 +1,13 @@ import { MessageTextInterface } from '../MessageTextInterface'; import { WhatsAppChannelInterface } from './WhatsAppChannelInterface'; +/** + * Represents an interface for WhatsApp text messages. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface WhatsAppTextInterface - extends MessageTextInterface, - WhatsAppChannelInterface {} + extends MessageTextInterface, + WhatsAppChannelInterface {} diff --git a/packages/messages/lib/interfaces/WhatsApp/WhatsAppVideoInterface.ts b/packages/messages/lib/interfaces/WhatsApp/WhatsAppVideoInterface.ts index 1f2e2e2c..aab7f2ac 100644 --- a/packages/messages/lib/interfaces/WhatsApp/WhatsAppVideoInterface.ts +++ b/packages/messages/lib/interfaces/WhatsApp/WhatsAppVideoInterface.ts @@ -1,6 +1,13 @@ import { WhatsAppChannelInterface } from './WhatsAppChannelInterface'; import { MessageVideoInterface } from '../MessageVideoInterface'; +/** + * Represents an interface for WhatsApp video messages. + * + * @deprecated Please use types instead of interfaces. + * + * @ignore + */ export interface WhatsAppVideoInterface - extends WhatsAppChannelInterface, - MessageVideoInterface {} + extends WhatsAppChannelInterface, + MessageVideoInterface {} diff --git a/packages/messages/lib/interfaces/index.ts b/packages/messages/lib/interfaces/index.ts index 996d4cab..6a5b6ea4 100644 --- a/packages/messages/lib/interfaces/index.ts +++ b/packages/messages/lib/interfaces/index.ts @@ -5,7 +5,7 @@ export * from './MessageAudioInterface'; export * from './MessageFileInterface'; export * from './MessageImageInterface'; export * from './MessageInterface'; -export * from './MessageSuccess'; +export * from './MessageSuccessInterface'; export * from './MessageTextInterface'; export * from './MessageVCardInterface'; export * from './MessageVideoInterface'; diff --git a/packages/messages/lib/messages.ts b/packages/messages/lib/messages.ts index 640b61f2..06b9c0e4 100644 --- a/packages/messages/lib/messages.ts +++ b/packages/messages/lib/messages.ts @@ -1,22 +1,60 @@ import { Client, AuthenticationType } from '@vonage/server-client'; import { VetchOptions } from '@vonage/vetch'; -import { MessageSuccess } from './interfaces'; -import { SendMessageParams, MessageSuccessResponse } from './types'; +import { + MessageSuccess, + SendMessageParams, + MessageSuccessResponse, AnyChannel, +} from './types'; import debug from 'debug'; const log = debug('vonage:messages'); +/** + * Client class to interact with the Messages API which enables users to manage + * send messages through various channels programmatically. + * @see {@link https://developer.nexmo.com/en/messages/overview} + + * @group Client + * + * @example + * Create a standalone Messages client + * + * ```ts + * import { Messages } from '@vonage/messages'; + * + * const messagesClient = new Messages({ + * apiKey: VONAGE_API_KEY, + * apiSecret: VONAGE_API_SECRET + * }); + * ``` + * + * @example + * Create an Messages client from the Vonage client + * + * ```ts + * import { Vonage } from '@vonage/server-client'; + * + * const vonage = new Vonage({ + * apiKey: VONAGE_API_KEY, + * apiSecret: VONAGE_API_SECRET + * }); + * + * const messagesClient = vonage.messages; + * ``` + */ export class Messages extends Client { /** - * Handle various ways the Messages API handles auth - * The Messages API handles both JWT (preferred) as well as Basic so we - * cannot just set a local authType - * - * @param {any} request - Object containing request data - */ + * Adds authentication details to the given request based on the configured + * authentication type. Handle various ways the Messages API handles auth + * The Messages API handles both JWT (preferred) as well as Basic so we + * cannot just set a local authType + * + * @param {VetchOptions} request - The request to which authentication should be added. + * @return {Promise} A promise that resolves to the request with added authentication. + */ public async addAuthenticationToRequest( request: VetchOptions, - ): Promise { + ): Promise { log('Auth config', this.auth); this.authType = AuthenticationType.KEY_SECRET; @@ -33,7 +71,15 @@ export class Messages extends Client { return super.addAuthenticationToRequest(request); } - public async send(message: SendMessageParams): Promise { + /** + * Sends a message using the Vonage API. + * + * @param {SendMessageParams} message - The message to be sent. + * @return {Promise} A promise that resolves to a success response with a message UUID. + */ + public async send( + message: SendMessageParams | AnyChannel, + ): Promise { const resp = await this.sendPostRequest( `${this.config.apiHost}/v1/messages`, JSON.parse( @@ -44,7 +90,7 @@ export class Messages extends Client { ); return { - messageUUID: resp.data?.message_uuid, + messageUUID: resp.data.message_uuid, }; } } diff --git a/packages/messages/lib/types/Channels/MMS/MMSAudioParams.ts b/packages/messages/lib/types/Channels/MMS/MMSAudioParams.ts new file mode 100644 index 00000000..3f2671db --- /dev/null +++ b/packages/messages/lib/types/Channels/MMS/MMSAudioParams.ts @@ -0,0 +1,13 @@ +import { MessageParams } from "../../MessageParams"; +import { MessageAudioType } from "../../MessageAudioType"; + +/** + * Represents the parameters for sending an audio message on the MMS channel. + * + * This type combines the common message parameters from `MessageParams` with audio-specific parameters + * defined in `MessageAudioType`. It is used when creating an audio message for the MMS channel. + * + * @group MMS + * @category Parameters + */ +export type MMSAudioParams = MessageParams & MessageAudioType; diff --git a/packages/messages/lib/types/Channels/MMS/MMSImageParams.ts b/packages/messages/lib/types/Channels/MMS/MMSImageParams.ts new file mode 100644 index 00000000..7cb20b2a --- /dev/null +++ b/packages/messages/lib/types/Channels/MMS/MMSImageParams.ts @@ -0,0 +1,13 @@ +import { MessageParams } from "../../MessageParams"; +import { MessageImageType } from "../../MessageImageType"; + +/** + * Represents the parameters for sending an image message on the MMS channel. + * + * This type combines the common message parameters from `MessageParams` with image-specific parameters + * defined in `MessageImageType`. It is used when creating an image message for the MMS channel. + * + * @group MMS + * @category Parameters + */ +export type MMSImageParams = MessageParams & MessageImageType; diff --git a/packages/messages/lib/types/Channels/MMS/MMSVcardParams.ts b/packages/messages/lib/types/Channels/MMS/MMSVcardParams.ts new file mode 100644 index 00000000..d6f12315 --- /dev/null +++ b/packages/messages/lib/types/Channels/MMS/MMSVcardParams.ts @@ -0,0 +1,13 @@ +import { MessageParams } from "../../MessageParams"; +import { MessageVcardType } from "../../MessageVcardType"; + +/** + * Represents the parameters for sending a vCard message on the MMS channel. + * + * This type combines the common message parameters from `MessageParams` with vCard-specific parameters + * defined in `MessageVcardType`. It is used when creating a vCard message for the MMS channel. + * + * @group MMS + * @category Parameters + */ +export type MMSVcardParams = MessageParams & MessageVcardType; diff --git a/packages/messages/lib/types/Channels/MMS/MMSVideoParams.ts b/packages/messages/lib/types/Channels/MMS/MMSVideoParams.ts new file mode 100644 index 00000000..d83967f5 --- /dev/null +++ b/packages/messages/lib/types/Channels/MMS/MMSVideoParams.ts @@ -0,0 +1,13 @@ +import { MessageParams } from "../../MessageParams"; +import { MessageVideoType } from "../../MessageVideoType"; + +/** + * Represents the parameters for sending a video message on the MMS channel. + * + * This type combines the common message parameters from `MessageParams` with video-specific parameters + * defined in `MessageVideoType`. It is used when creating a video message for the MMS channel. + * + * @group MMS + * @category Parameters + */ +export type MMSVideoParams = MessageParams & MessageVideoType; diff --git a/packages/messages/lib/types/Channels/MMS/index.ts b/packages/messages/lib/types/Channels/MMS/index.ts new file mode 100644 index 00000000..6ffc78e0 --- /dev/null +++ b/packages/messages/lib/types/Channels/MMS/index.ts @@ -0,0 +1,35 @@ +import { MMSAudioParams } from './MMSAudioParams'; +import { MMSImageParams } from './MMSImageParams'; +import { MMSVcardParams } from './MMSVcardParams'; +import { MMSVideoParams } from './MMSVideoParams'; +import { Channels } from "../../../enums"; + +export * from './MMSAudioParams'; +export * from './MMSImageParams'; +export * from './MMSVcardParams'; +export * from './MMSVideoParams'; + +/** + * Represents a union type that can be any of the MMS-specific message parameters. + * + * @group MMS + * @category Parameters + */ +export type AnyMMSParams = + | MMSAudioParams + | MMSImageParams + | MMSVcardParams + | MMSVideoParams; + +/** + * Represents a union type that includes the 'channel' property set to 'mms' + * along with any of the MMS-specific message parameters. + * + * @group MMS + */ +export type AnyMMSChannel = { + /** + * The channel through which the message will be sent, which is 'mms' for MMS. + */ + channel: Channels.MMS; +} & AnyMMSParams; diff --git a/packages/messages/lib/types/Channels/Messenger/MessengerAudioParams.ts b/packages/messages/lib/types/Channels/Messenger/MessengerAudioParams.ts new file mode 100644 index 00000000..66eb7166 --- /dev/null +++ b/packages/messages/lib/types/Channels/Messenger/MessengerAudioParams.ts @@ -0,0 +1,11 @@ +import { MessageParamsAudio } from '../../MessageParamsAudio'; +import { MessengerParams } from './MessengerParams'; + +/** + * Represents parameters for sending an audio message via the Messenger platform. + * Combines parameters from both MessengerParams and MessageParamsAudio. + * + * @group Messenger + * @category Parameters + */ +export type MessengerAudioParams = MessengerParams & MessageParamsAudio diff --git a/packages/messages/lib/types/Channels/Messenger/MessengerFileParams.ts b/packages/messages/lib/types/Channels/Messenger/MessengerFileParams.ts new file mode 100644 index 00000000..92c0d16d --- /dev/null +++ b/packages/messages/lib/types/Channels/Messenger/MessengerFileParams.ts @@ -0,0 +1,11 @@ +import { MessageParamsFile } from '../../MessageParamsFile'; +import { MessengerParams } from './MessengerParams'; + +/** + * Represents parameters for sending a file message via the Messenger platform. + * Combines parameters from both MessengerParams and MessageParamsFile. + * + * @group Messenger + * @category Parameters + */ +export type MessengerFileParams = MessengerParams & MessageParamsFile diff --git a/packages/messages/lib/types/Channels/Messenger/MessengerImageParams.ts b/packages/messages/lib/types/Channels/Messenger/MessengerImageParams.ts new file mode 100644 index 00000000..f503c51e --- /dev/null +++ b/packages/messages/lib/types/Channels/Messenger/MessengerImageParams.ts @@ -0,0 +1,11 @@ +import { MessageParamsImage } from '../../MessageParamsImage'; +import { MessengerParams } from './MessengerParams'; + +/** + * Represents parameters for sending an image message via the Messenger platform. + * Combines parameters from both MessengerParams and MessageParamsImage. + * + * @group Messenger + * @category Parameters + */ +export type MessengerImageParams = MessengerParams & MessageParamsImage diff --git a/packages/messages/lib/types/Channels/Messenger/MessengerParams.ts b/packages/messages/lib/types/Channels/Messenger/MessengerParams.ts new file mode 100644 index 00000000..861686f3 --- /dev/null +++ b/packages/messages/lib/types/Channels/Messenger/MessengerParams.ts @@ -0,0 +1,11 @@ +import { MessengerType } from './MessengerType'; + +/** + * Represents parameters specific to the Messenger platform. + * + * @group Messenger + * @category Parameters + */ +export type MessengerParams = { + messenger: MessengerType; +}; diff --git a/packages/messages/lib/types/Channels/Messenger/MessengerTextParams.ts b/packages/messages/lib/types/Channels/Messenger/MessengerTextParams.ts new file mode 100644 index 00000000..4d8cb391 --- /dev/null +++ b/packages/messages/lib/types/Channels/Messenger/MessengerTextParams.ts @@ -0,0 +1,10 @@ +import { MessageParamsText } from '../../MessageParamsText'; +import { MessengerParams } from './MessengerParams'; + +/** + * Represents parameters for sending a text message via the Messenger platform. + * + * @group Messenger + * @category Parameters + */ +export type MessengerTextParams = MessengerParams & MessageParamsText; diff --git a/packages/messages/lib/types/Channels/Messenger/MessengerType.ts b/packages/messages/lib/types/Channels/Messenger/MessengerType.ts new file mode 100644 index 00000000..adecc678 --- /dev/null +++ b/packages/messages/lib/types/Channels/Messenger/MessengerType.ts @@ -0,0 +1,19 @@ +import { MessengerCategory } from '../../../enums'; + +/** + * Represents the type of message to be sent via the Messenger platform. + * + * @group Messenger + * @category Parameters + */ +export type MessengerType = { + /** + * The category of the Messenger message. + */ + category: MessengerCategory; + + /** + * An optional tag describing the type and relevance of the 1:1 communication between your app and the end user. + */ + tag?: string; +}; diff --git a/packages/messages/lib/types/Channels/Messenger/MessengerVideoParams.ts b/packages/messages/lib/types/Channels/Messenger/MessengerVideoParams.ts new file mode 100644 index 00000000..3b609436 --- /dev/null +++ b/packages/messages/lib/types/Channels/Messenger/MessengerVideoParams.ts @@ -0,0 +1,10 @@ +import { MessageParamsVideo } from '../../MessageParamsVideo'; +import { MessengerParams } from './MessengerParams'; + +/** + * Represents parameters for sending a video message via the Messenger platform. + * + * @group Messenger + * @category Parameters + */ +export type MessengerVideoParams = MessengerParams & MessageParamsVideo; diff --git a/packages/messages/lib/types/Channels/Messenger/index.ts b/packages/messages/lib/types/Channels/Messenger/index.ts new file mode 100644 index 00000000..e9d16096 --- /dev/null +++ b/packages/messages/lib/types/Channels/Messenger/index.ts @@ -0,0 +1,43 @@ +import { MessengerAudioParams } from './MessengerAudioParams'; +import { MessengerFileParams } from './MessengerFileParams'; +import { MessengerImageParams } from './MessengerImageParams'; +import { MessengerParams } from './MessengerParams'; +import { MessengerTextParams } from './MessengerTextParams'; +import { MessengerType } from './MessengerType'; +import { MessengerVideoParams } from './MessengerVideoParams'; +import { Channels } from "../../../enums"; + +export * from './MessengerAudioParams'; +export * from './MessengerFileParams'; +export * from './MessengerImageParams'; +export * from './MessengerParams'; +export * from './MessengerTextParams'; +export * from './MessengerType'; +export * from './MessengerVideoParams'; + +/** + * Represents a union type that can be any of the Messenger-specific message + * parameters or MessengerType. + * + * @group Messenger + * @category Parameters + */ +export type AnyMessengerParams = + MessengerAudioParams | + MessengerFileParams | + MessengerImageParams | + MessengerParams | + MessengerTextParams | + MessengerType | + MessengerVideoParams; + +/** + * Represents a union type that includes the 'channel' property set to 'messenger' + * along with any of the Messenger-specific message parameters or MessengerType. + */ +export type AnyMessengerChannel = { + /** + * The channel through which the message will be sent, which is 'messenger' for Messenger. + */ + channel: Channels.MESSENGER +} & AnyMessengerParams diff --git a/packages/messages/lib/types/Channels/SMSParams.ts b/packages/messages/lib/types/Channels/SMSParams.ts new file mode 100644 index 00000000..319a5796 --- /dev/null +++ b/packages/messages/lib/types/Channels/SMSParams.ts @@ -0,0 +1,28 @@ +import { MessageParamsText } from "../MessageParamsText"; +import { Channels } from "../../enums"; + +/** + * Represents the parameters for sending an SMS message. + * + * This type is an alias for `MessageParamsText` and is used when creating an SMS message. + * + * @group SMS + * @category Parameters + * @remarks The purpose of this type is to ensure a consistent interface for SMS + * message parameters, making it easier to extend or modify the type in the + * future without impacting existing code that uses it. + * It is based on the `MessageParamsText` type. + */ +export type SMSParams = MessageParamsText; + +/** + * Represents an SMS channel message, combining the channel type with SMS-specific parameters. + * + * This type includes the `channel` field specifying the SMS channel and combines + * it with the SMS message parameters defined in `SMSParams`. + * + * @group SMS + */ +export type SMSChannel = { + channel: Channels.SMS +} & SMSParams; diff --git a/packages/messages/lib/types/Channels/Viber/ViberAction.ts b/packages/messages/lib/types/Channels/Viber/ViberAction.ts new file mode 100644 index 00000000..a15304a7 --- /dev/null +++ b/packages/messages/lib/types/Channels/Viber/ViberAction.ts @@ -0,0 +1,17 @@ +/** + * Represents an action associated with a Viber message. + * + * @group Viber + * @category Parameters + */ +export type ViberAction = { + /** + * The URL to be opened when the action is triggered. + */ + url: string; + + /** + * The text displayed for the action. + */ + text: string; +}; diff --git a/packages/messages/lib/types/Channels/Viber/ViberActionParams.ts b/packages/messages/lib/types/Channels/Viber/ViberActionParams.ts new file mode 100644 index 00000000..f8d81400 --- /dev/null +++ b/packages/messages/lib/types/Channels/Viber/ViberActionParams.ts @@ -0,0 +1,14 @@ +import { ViberService } from './ViberService'; +import { ViberAction } from './ViberAction'; +/** + * Represents parameters for a Viber action message. + * + * @group Viber + * @category Parameters + */ +export type ViberActionParams = { + /** + * The action associated with the Viber message. + */ + action: ViberAction; +} & ViberService; diff --git a/packages/messages/lib/types/Channels/Viber/ViberFileParams.ts b/packages/messages/lib/types/Channels/Viber/ViberFileParams.ts new file mode 100644 index 00000000..a531a952 --- /dev/null +++ b/packages/messages/lib/types/Channels/Viber/ViberFileParams.ts @@ -0,0 +1,15 @@ +import { MessageParamsFile } from '../../MessageParamsFile'; +import { ViberService } from './ViberService'; + +/** + * Represents parameters for sending a file via Viber. + * + * @group Viber + * @category Parameters + */ +export type ViberFileParams = { + /** + * The Viber service details for sending the file. + */ + viberService: ViberService; +} & MessageParamsFile; diff --git a/packages/messages/lib/types/Channels/Viber/ViberImageParams.ts b/packages/messages/lib/types/Channels/Viber/ViberImageParams.ts new file mode 100644 index 00000000..d36df5aa --- /dev/null +++ b/packages/messages/lib/types/Channels/Viber/ViberImageParams.ts @@ -0,0 +1,15 @@ +import { MessageParamsImage } from '../../MessageParamsImage'; +import { ViberActionParams } from './ViberActionParams'; + +/** + * Represents parameters for sending an image via Viber. + * + * @group Viber + * @category Parameters + */ +export type ViberImageParams = { + /** + * The Viber action parameters for sending the image. + */ + viberService: ViberActionParams; +} & MessageParamsImage; diff --git a/packages/messages/lib/types/Channels/Viber/ViberService.ts b/packages/messages/lib/types/Channels/Viber/ViberService.ts new file mode 100644 index 00000000..cb717ebd --- /dev/null +++ b/packages/messages/lib/types/Channels/Viber/ViberService.ts @@ -0,0 +1,27 @@ +import { ViberCategory } from '../../../enums'; + +/** + * Represents parameters for a Viber service message. + * + * @group Viber + * @category Parameters + */ +export type ViberService = { + /** + * The time-to-live (TTL) of the message to be delivered in seconds. + * If the message is not delivered within this time, it will be deleted. + */ + ttl: number; + + /** + * The Viber-specific type definition. + * To use "template," please contact your Vonage Account Manager to set up templates. + * To find out more, please visit the product page. + */ + type: string; + + /** + * The category of the Viber service message. + */ + category: ViberCategory; +}; diff --git a/packages/messages/lib/types/Channels/Viber/ViberTextParams.ts b/packages/messages/lib/types/Channels/Viber/ViberTextParams.ts new file mode 100644 index 00000000..d9195505 --- /dev/null +++ b/packages/messages/lib/types/Channels/Viber/ViberTextParams.ts @@ -0,0 +1,20 @@ +import { ViberActionParams } from './ViberActionParams'; +import { MessageParamsText } from '../../MessageParamsText'; + +/** + * Represents parameters for sending a text message via Viber with action buttons. + * + * @group Viber + * @category Parameters + */ +export type ViberTextParams = { + /** + * The Viber service and action parameters for the message. + */ + viberService: ViberActionParams; + + /** + * The text content of the message. + */ + text: string; +} & MessageParamsText diff --git a/packages/messages/lib/types/Channels/Viber/ViberVideoParams.ts b/packages/messages/lib/types/Channels/Viber/ViberVideoParams.ts new file mode 100644 index 00000000..44a9fb23 --- /dev/null +++ b/packages/messages/lib/types/Channels/Viber/ViberVideoParams.ts @@ -0,0 +1,34 @@ +import { MessageParamsVideo } from '../../MessageParamsVideo'; +import { ViberActionParams } from './ViberActionParams'; + +/** + * Represents parameters for sending a video message via Viber with action buttons. + * + * @group Viber + * @category Parameters + */ +export type ViberVideoParams = { + /** + * The Viber service, action parameters, and video message details. + */ + viberService: { + /** + * The duration of the video in seconds. + */ + duration: string; + /** + * The file size of the video in MB. + */ + fileSize: string; + } & ViberActionParams; + + /** + * The details of the video message to be sent. + */ + video: { + /** + * The URL of the video attachment. + */ + url: string; + }; +} & MessageParamsVideo diff --git a/packages/messages/lib/types/Channels/Viber/index.ts b/packages/messages/lib/types/Channels/Viber/index.ts new file mode 100644 index 00000000..eb13369c --- /dev/null +++ b/packages/messages/lib/types/Channels/Viber/index.ts @@ -0,0 +1,44 @@ +import { ViberAction } from './ViberAction'; +import { ViberActionParams } from './ViberActionParams'; +import { ViberFileParams } from './ViberFileParams'; +import { ViberImageParams } from './ViberImageParams'; +import { ViberService } from './ViberService'; +import { ViberTextParams } from './ViberTextParams'; +import { ViberVideoParams } from './ViberVideoParams'; +import { Channels } from "../../../enums"; + +export * from './ViberAction'; +export * from './ViberActionParams'; +export * from './ViberFileParams'; +export * from './ViberImageParams'; +export * from './ViberService'; +export * from './ViberTextParams'; +export * from './ViberVideoParams'; +/** + * Represents a union type that can be any of the Viber-specific message + * parameters or configurations. + * + * @group Viber + * @category Parameters + */ +export type AnyViberParams = + | ViberAction + | ViberActionParams + | ViberFileParams + | ViberImageParams + | ViberService + | ViberTextParams + | ViberVideoParams; + +/** + * Represents a union type that includes the 'channel' property set to 'viber' + * along with any of the Viber-specific message parameters or configurations. + * + * @group Viber + */ +export type AnyViberChannel = { + /** + * The channel through which the message will be sent, which is 'viber' for Viber. + */ + channel: Channels.VIBER; +} & AnyViberParams; diff --git a/packages/messages/lib/types/Channels/WhatsApp/WhatsAppAudioParams.ts b/packages/messages/lib/types/Channels/WhatsApp/WhatsAppAudioParams.ts new file mode 100644 index 00000000..1b9af0f8 --- /dev/null +++ b/packages/messages/lib/types/Channels/WhatsApp/WhatsAppAudioParams.ts @@ -0,0 +1,9 @@ +import { MessageParamsAudio } from '../../MessageParamsAudio'; + +/** + * Represents parameters for sending an audio message via WhatsApp. + * + * @group WhatsApp + * @category Parameters + */ +export type WhatsAppAudioParams = MessageParamsAudio diff --git a/packages/messages/lib/types/Channels/WhatsApp/WhatsAppCustomParams.ts b/packages/messages/lib/types/Channels/WhatsApp/WhatsAppCustomParams.ts new file mode 100644 index 00000000..fc5bde57 --- /dev/null +++ b/packages/messages/lib/types/Channels/WhatsApp/WhatsAppCustomParams.ts @@ -0,0 +1,15 @@ +import { MessageParams } from '../../MessageParams'; +import { WhatsAppCustomType } from './WhatsAppCustomType'; + +/** + * Represents parameters for sending a custom WhatsApp message with a file attachment. + * + * @group WhatsApp + * @category Parameters + */ +export type WhatsAppCustomParams = { + /** + * The custom WhatsApp message type. + */ + custom: WhatsAppCustomType; +} & MessageParams; diff --git a/packages/messages/lib/types/Channels/WhatsApp/WhatsAppCustomType.ts b/packages/messages/lib/types/Channels/WhatsApp/WhatsAppCustomType.ts new file mode 100644 index 00000000..98cb55c8 --- /dev/null +++ b/packages/messages/lib/types/Channels/WhatsApp/WhatsAppCustomType.ts @@ -0,0 +1,8 @@ +/** + * Represents a custom WhatsApp message type with arbitrary properties. + * + * @group WhatsApp + */ +export type WhatsAppCustomType = { + [key: string]: unknown +} diff --git a/packages/messages/lib/types/Channels/WhatsApp/WhatsAppFileParams.ts b/packages/messages/lib/types/Channels/WhatsApp/WhatsAppFileParams.ts new file mode 100644 index 00000000..02407240 --- /dev/null +++ b/packages/messages/lib/types/Channels/WhatsApp/WhatsAppFileParams.ts @@ -0,0 +1,9 @@ +import { MessageParamsFile } from '../../MessageParamsFile'; + +/** + * Represents a WhatsApp file message type. + * + * @group WhatsApp + * @category Parameters + */ +export type WhatsAppFileParams = MessageParamsFile; diff --git a/packages/messages/lib/types/Channels/WhatsApp/WhatsAppImageParams.ts b/packages/messages/lib/types/Channels/WhatsApp/WhatsAppImageParams.ts new file mode 100644 index 00000000..5fe84922 --- /dev/null +++ b/packages/messages/lib/types/Channels/WhatsApp/WhatsAppImageParams.ts @@ -0,0 +1,9 @@ +import { MessageParamsImage } from '../../MessageParamsImage'; + +/** + * Represents a WhatsApp image message type. + * + * @group WhatsApp + * @category Parameters + */ +export type WhatsAppImageParams = MessageParamsImage diff --git a/packages/messages/lib/types/Channels/WhatsApp/WhatsAppPolicyType.ts b/packages/messages/lib/types/Channels/WhatsApp/WhatsAppPolicyType.ts new file mode 100644 index 00000000..0c7714f2 --- /dev/null +++ b/packages/messages/lib/types/Channels/WhatsApp/WhatsAppPolicyType.ts @@ -0,0 +1,18 @@ +import { WhatsAppLanguageCode } from '../../../enums'; + +/** + * Represents a WhatsApp policy type for deterministic messaging. + * + * @group WhatsApp + */ +export type WhatsAppPolicyType = { + /** + * The policy type, which is set to 'deterministic'. + */ + policy: 'deterministic'; + + /** + * The locale for the WhatsApp message, following the WhatsApp language code. + */ + locale: WhatsAppLanguageCode; +}; diff --git a/packages/messages/lib/types/Channels/WhatsApp/WhatsAppStickerIdType.ts b/packages/messages/lib/types/Channels/WhatsApp/WhatsAppStickerIdType.ts new file mode 100644 index 00000000..7c9eea9f --- /dev/null +++ b/packages/messages/lib/types/Channels/WhatsApp/WhatsAppStickerIdType.ts @@ -0,0 +1,11 @@ +/** + * Represents a WhatsApp sticker ID type. + * + * @group WhatsApp + */ +export type WhatsAppStickerIdType = { + /** + * The ID of the WhatsApp sticker. + */ + id: string; +}; diff --git a/packages/messages/lib/types/Channels/WhatsApp/WhatsAppStickerParams.ts b/packages/messages/lib/types/Channels/WhatsApp/WhatsAppStickerParams.ts new file mode 100644 index 00000000..5f88fc9e --- /dev/null +++ b/packages/messages/lib/types/Channels/WhatsApp/WhatsAppStickerParams.ts @@ -0,0 +1,16 @@ +import { MessageParams } from '../../MessageParams'; +import { WhatsAppStickerIdType } from './WhatsAppStickerIdType'; +import { WhatsAppStickerUrlType } from './WhatsAppStickerUrlType'; + +/** + * Represents WhatsApp sticker parameters for sending stickers in a message. + * + * @group WhatsApp + * @category Parameters + */ +export type WhatsAppStickerParams = { + /** + * The sticker to be sent, which can be either a sticker ID or a sticker URL. + */ + sticker: WhatsAppStickerIdType | WhatsAppStickerUrlType; +} & MessageParams; diff --git a/packages/messages/lib/types/Channels/WhatsApp/WhatsAppStickerUrlType.ts b/packages/messages/lib/types/Channels/WhatsApp/WhatsAppStickerUrlType.ts new file mode 100644 index 00000000..4f955ccd --- /dev/null +++ b/packages/messages/lib/types/Channels/WhatsApp/WhatsAppStickerUrlType.ts @@ -0,0 +1,11 @@ +/** + * Represents a WhatsApp sticker by URL. + * + * @group WhatsApp + */ +export type WhatsAppStickerUrlType = { + /** + * The URL of the WhatsApp sticker. + */ + url: string; +}; diff --git a/packages/messages/lib/types/Channels/WhatsApp/WhatsAppTemplateParams.ts b/packages/messages/lib/types/Channels/WhatsApp/WhatsAppTemplateParams.ts new file mode 100644 index 00000000..7213a984 --- /dev/null +++ b/packages/messages/lib/types/Channels/WhatsApp/WhatsAppTemplateParams.ts @@ -0,0 +1,21 @@ +import { MessageParams } from '../../MessageParams'; +import { WhatsAppTemplateType } from './WhatsAppTemplateType'; +import { WhatsAppPolicyType } from './WhatsAppPolicyType'; + +/** + * Represents WhatsApp template message parameters. + * + * @group WhatsApp + * @category Parameters + */ +export type WhatsAppTemplateParams = { + /** + * WhatsApp policy type for the template message. + */ + whatsapp: WhatsAppPolicyType; + + /** + * The WhatsApp template to be sent. + */ + template: WhatsAppTemplateType; +} & MessageParams; diff --git a/packages/messages/lib/types/Channels/WhatsApp/WhatsAppTemplateType.ts b/packages/messages/lib/types/Channels/WhatsApp/WhatsAppTemplateType.ts new file mode 100644 index 00000000..bb194985 --- /dev/null +++ b/packages/messages/lib/types/Channels/WhatsApp/WhatsAppTemplateType.ts @@ -0,0 +1,16 @@ +/** + * Represents a WhatsApp template for sending structured template messages. + * + * @group WhatsApp + */ +export type WhatsAppTemplateType = { + /** + * The name of the WhatsApp template. + */ + name: string; + + /** + * An array of parameters for the WhatsApp template. + */ + parameters: string[]; +}; diff --git a/packages/messages/lib/types/Channels/WhatsApp/WhatsAppTextParams.ts b/packages/messages/lib/types/Channels/WhatsApp/WhatsAppTextParams.ts new file mode 100644 index 00000000..e550ed50 --- /dev/null +++ b/packages/messages/lib/types/Channels/WhatsApp/WhatsAppTextParams.ts @@ -0,0 +1,9 @@ +import { MessageParamsText } from '../../MessageParamsText'; + +/** + * Represents a text message type for WhatsApp. + * + * @group WhatsApp + * @category Parameters + */ +export type WhatsAppTextParams = MessageParamsText; diff --git a/packages/messages/lib/types/Channels/WhatsApp/WhatsAppVideoParams.ts b/packages/messages/lib/types/Channels/WhatsApp/WhatsAppVideoParams.ts new file mode 100644 index 00000000..96760489 --- /dev/null +++ b/packages/messages/lib/types/Channels/WhatsApp/WhatsAppVideoParams.ts @@ -0,0 +1,9 @@ +import { MessageParamsVideo } from '../../MessageParamsVideo'; + +/** + * Represents a video message type for WhatsApp. + * + * @group WhatsApp + * @category Parameters + */ +export type WhatsAppVideoParams = MessageParamsVideo; diff --git a/packages/messages/lib/types/Channels/WhatsApp/index.ts b/packages/messages/lib/types/Channels/WhatsApp/index.ts new file mode 100644 index 00000000..01c27cab --- /dev/null +++ b/packages/messages/lib/types/Channels/WhatsApp/index.ts @@ -0,0 +1,56 @@ +import { WhatsAppAudioParams } from './WhatsAppAudioParams'; +import { WhatsAppCustomParams } from './WhatsAppCustomParams'; +import { WhatsAppFileParams } from './WhatsAppFileParams'; +import { WhatsAppImageParams } from './WhatsAppImageParams'; +import { WhatsAppStickerIdType } from './WhatsAppStickerIdType'; +import { WhatsAppStickerParams } from './WhatsAppStickerParams'; +import { WhatsAppTemplateParams } from './WhatsAppTemplateParams'; +import { WhatsAppTextParams } from './WhatsAppTextParams'; +import { WhatsAppVideoParams } from './WhatsAppVideoParams'; +import { Channels } from "../../../enums"; + +export * from './WhatsAppAudioParams'; +export * from './WhatsAppCustomParams'; +export * from './WhatsAppCustomType'; +export * from './WhatsAppFileParams'; +export * from './WhatsAppImageParams'; +export * from './WhatsAppPolicyType'; +export * from './WhatsAppStickerIdType'; +export * from './WhatsAppStickerParams'; +export * from './WhatsAppStickerUrlType'; +export * from './WhatsAppTemplateParams'; +export * from './WhatsAppTemplateType'; +export * from './WhatsAppTextParams'; +export * from './WhatsAppVideoParams'; + +/** + * Represents a union type that can be any of the WhatsApp-specific message + * parameters or configurations. + * + * @group WhatsApp + * @category Parameters + */ +export type AnyWhatsAppParams = + | WhatsAppAudioParams + | WhatsAppCustomParams + | WhatsAppFileParams + | WhatsAppImageParams + | WhatsAppStickerIdType + | WhatsAppStickerParams + | WhatsAppTemplateParams + | WhatsAppTextParams + | WhatsAppVideoParams; + +/** + * Represents a union type that includes the 'channel' property set to + * 'whatsapp_service' along with any of the WhatsApp-specific message parameters or + * configurations. + * + * @group WhatsApp + */ +export type AnyWhatsAppChannel = { + /** + * The channel through which the message will be sent, which is 'whatsapp' for WhatsApp. + */ + channel: Channels.WHATSAPP; +} & AnyWhatsAppParams; diff --git a/packages/messages/lib/types/Channels/index.ts b/packages/messages/lib/types/Channels/index.ts new file mode 100644 index 00000000..c7b82636 --- /dev/null +++ b/packages/messages/lib/types/Channels/index.ts @@ -0,0 +1,21 @@ +import { AnyMessengerChannel } from "./Messenger"; +import { AnyMMSChannel } from "./MMS"; +import { AnyViberChannel } from "./Viber"; +import { AnyWhatsAppChannel } from "./WhatsApp"; +import { SMSChannel } from "./SMSParams"; + +export * from './Messenger'; +export * from './MMS'; +export * from './Viber'; +export * from './WhatsApp'; +export * from './SMSParams'; + +/** + * Represents a union type that can be any of the specific channel message + * parameters or configurations, including Messenger, MMS, Viber, WhatsApp, or SMS. + */ +export type AnyChannel = AnyMessengerChannel +| AnyMMSChannel +| AnyViberChannel +| AnyWhatsAppChannel +| SMSChannel diff --git a/packages/messages/lib/types/MessageAudioType.ts b/packages/messages/lib/types/MessageAudioType.ts index 78e50647..b2d62c88 100644 --- a/packages/messages/lib/types/MessageAudioType.ts +++ b/packages/messages/lib/types/MessageAudioType.ts @@ -1,3 +1,9 @@ +/** + * Represents an audio message type. + */ export type MessageAudioType = { - url: string -} + /** + * The URL of the audio attachment. + */ + url: string; +}; diff --git a/packages/messages/lib/types/MessageFileType.ts b/packages/messages/lib/types/MessageFileType.ts index 3fcc2048..3a57bbbd 100644 --- a/packages/messages/lib/types/MessageFileType.ts +++ b/packages/messages/lib/types/MessageFileType.ts @@ -1,4 +1,14 @@ +/** + * Represents a file message type. + */ export type MessageFileType = { - url: string - caption?: string -} + /** + * The URL of the file attachment. + */ + url: string; + + /** + * An optional caption to accompany the file. + */ + caption?: string; +}; diff --git a/packages/messages/lib/types/MessageImageType.ts b/packages/messages/lib/types/MessageImageType.ts index 0afc6fcb..39dfc5ae 100644 --- a/packages/messages/lib/types/MessageImageType.ts +++ b/packages/messages/lib/types/MessageImageType.ts @@ -1,3 +1,9 @@ +/** + * Represents an image message type. + */ export type MessageImageType = { - url: string -} + /** + * The URL of the image attachment. + */ + url: string; +}; diff --git a/packages/messages/lib/types/MessageParams.ts b/packages/messages/lib/types/MessageParams.ts index 7478db09..eec0ac60 100644 --- a/packages/messages/lib/types/MessageParams.ts +++ b/packages/messages/lib/types/MessageParams.ts @@ -1,5 +1,20 @@ +/** + * Represents the parameters for a message. + */ export type MessageParams = { - to: string - from: string - clientRef: string -} + /** + * The ID of the message recipient. + */ + to: string; + + /** + * The ID of the message sender. + */ + from: string; + + /** + * Client reference of up to 100 characters. + * The reference will be present in every message status. + */ + clientRef?: string; +}; diff --git a/packages/messages/lib/types/MessageParamsAudio.ts b/packages/messages/lib/types/MessageParamsAudio.ts index 383e782f..dc77dfdc 100644 --- a/packages/messages/lib/types/MessageParamsAudio.ts +++ b/packages/messages/lib/types/MessageParamsAudio.ts @@ -1,6 +1,12 @@ import { MessageParams } from './MessageParams'; import { MessageAudioType } from './MessageAudioType'; +/** + * Represents the parameters for a message with audio. + */ export type MessageParamsAudio = { - audio: MessageAudioType -} & MessageParams + /** + * The audio message content. + */ + audio: MessageAudioType; +} & MessageParams; diff --git a/packages/messages/lib/types/MessageParamsFile.ts b/packages/messages/lib/types/MessageParamsFile.ts index 0ce98290..71acb60c 100644 --- a/packages/messages/lib/types/MessageParamsFile.ts +++ b/packages/messages/lib/types/MessageParamsFile.ts @@ -1,6 +1,12 @@ import { MessageParams } from './MessageParams'; import { MessageFileType } from './MessageFileType'; +/** + * Represents the parameters for a message with a file attachment. + */ export type MessageParamsFile = { - file?: MessageFileType -} & MessageParams + /** + * The file attachment content. + */ + file: MessageFileType; +} & MessageParams; diff --git a/packages/messages/lib/types/MessageParamsImage.ts b/packages/messages/lib/types/MessageParamsImage.ts index f3e4d11c..abe502ff 100644 --- a/packages/messages/lib/types/MessageParamsImage.ts +++ b/packages/messages/lib/types/MessageParamsImage.ts @@ -1,6 +1,12 @@ import { MessageParams } from './MessageParams'; import { MessageImageType } from './MessageImageType'; +/** + * Represents the parameters for a message with an image attachment. + */ export type MessageParamsImage = { - image: MessageImageType -} & MessageParams + /** + * The image attachment content. + */ + image: MessageImageType; +} & MessageParams; diff --git a/packages/messages/lib/types/MessageParamsText.ts b/packages/messages/lib/types/MessageParamsText.ts index 825ea885..cb5d112f 100644 --- a/packages/messages/lib/types/MessageParamsText.ts +++ b/packages/messages/lib/types/MessageParamsText.ts @@ -1,5 +1,11 @@ import { MessageParams } from './MessageParams'; +/** + * Represents the parameters for a text message. + */ export type MessageParamsText = { - text: string -} & MessageParams + /** + * The text content of the message. + */ + text: string; +} & MessageParams; diff --git a/packages/messages/lib/types/MessageParamsVcard.ts b/packages/messages/lib/types/MessageParamsVcard.ts index 1ebc140b..d0d83e42 100644 --- a/packages/messages/lib/types/MessageParamsVcard.ts +++ b/packages/messages/lib/types/MessageParamsVcard.ts @@ -1,6 +1,12 @@ import { MessageParams } from './MessageParams'; import { MessageVcardType } from './MessageVcardType'; +/** + * Represents the parameters for a message containing a vCard. + */ export type MessageParamsVcard = { - vcard: MessageVcardType -} & MessageParams + /** + * The vCard information to be included in the message. + */ + vcard: MessageVcardType; +} & MessageParams; diff --git a/packages/messages/lib/types/MessageParamsVideo.ts b/packages/messages/lib/types/MessageParamsVideo.ts index eede7dc8..faf95b25 100644 --- a/packages/messages/lib/types/MessageParamsVideo.ts +++ b/packages/messages/lib/types/MessageParamsVideo.ts @@ -1,6 +1,12 @@ import { MessageParams } from './MessageParams'; import { MessageVideoType } from './MessageVideoType'; +/** + * Represents the parameters for a message containing a video. + */ export type MessageParamsVideo = { - video: MessageVideoType -} & MessageParams + /** + * The video information to be included in the message. + */ + video: MessageVideoType; +} & MessageParams; diff --git a/packages/messages/lib/types/MessageSuccess.ts b/packages/messages/lib/types/MessageSuccess.ts new file mode 100644 index 00000000..083532c9 --- /dev/null +++ b/packages/messages/lib/types/MessageSuccess.ts @@ -0,0 +1,3 @@ +export type MessageSuccess = { + messageUUID: string +} diff --git a/packages/messages/lib/types/MessageVcardType.ts b/packages/messages/lib/types/MessageVcardType.ts index 9b772927..63ba9633 100644 --- a/packages/messages/lib/types/MessageVcardType.ts +++ b/packages/messages/lib/types/MessageVcardType.ts @@ -1,3 +1,9 @@ +/** + * Represents a vCard message type. + */ export type MessageVcardType = { - url: string -} + /** + * The URL of the vCard attachment. + */ + url: string; +}; diff --git a/packages/messages/lib/types/MessageVideoType.ts b/packages/messages/lib/types/MessageVideoType.ts index 44d25328..2b489759 100644 --- a/packages/messages/lib/types/MessageVideoType.ts +++ b/packages/messages/lib/types/MessageVideoType.ts @@ -1,3 +1,9 @@ +/** + * Represents a video message type. + */ export type MessageVideoType = { - url: string -} + /** + * The URL of the video attachment. + */ + url: string; +}; diff --git a/packages/messages/lib/types/Messenger/MessengerAudioParams.ts b/packages/messages/lib/types/Messenger/MessengerAudioParams.ts deleted file mode 100644 index f2abe5cc..00000000 --- a/packages/messages/lib/types/Messenger/MessengerAudioParams.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { MessageParamsAudio } from '../MessageParamsAudio'; -import { MessengerParams } from './MessengerParams'; - -export type MessengerAudioParams = MessengerParams & MessageParamsAudio diff --git a/packages/messages/lib/types/Messenger/MessengerFileParams.ts b/packages/messages/lib/types/Messenger/MessengerFileParams.ts deleted file mode 100644 index 26ab59a1..00000000 --- a/packages/messages/lib/types/Messenger/MessengerFileParams.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { MessageParamsFile } from '../MessageParamsFile'; -import { MessengerParams } from './MessengerParams'; - -export type MessengerFileParams = MessengerParams & MessageParamsFile diff --git a/packages/messages/lib/types/Messenger/MessengerImageParams.ts b/packages/messages/lib/types/Messenger/MessengerImageParams.ts deleted file mode 100644 index 984e8b95..00000000 --- a/packages/messages/lib/types/Messenger/MessengerImageParams.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { MessageParamsImage } from '../MessageParamsImage'; -import { MessengerParams } from './MessengerParams'; - -export type MessengerImageParams = MessengerParams & MessageParamsImage diff --git a/packages/messages/lib/types/Messenger/MessengerParams.ts b/packages/messages/lib/types/Messenger/MessengerParams.ts deleted file mode 100644 index 80caf73b..00000000 --- a/packages/messages/lib/types/Messenger/MessengerParams.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { MessengerType } from './MessengerType'; - -export type MessengerParams = { - messenger: MessengerType -} diff --git a/packages/messages/lib/types/Messenger/MessengerTextParams.ts b/packages/messages/lib/types/Messenger/MessengerTextParams.ts deleted file mode 100644 index 8fadcf3a..00000000 --- a/packages/messages/lib/types/Messenger/MessengerTextParams.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { MessageParamsText } from '../MessageParamsText'; -import { MessengerParams } from './MessengerParams'; - -export type MessengerTextParams = MessengerParams & MessageParamsText diff --git a/packages/messages/lib/types/Messenger/MessengerType.ts b/packages/messages/lib/types/Messenger/MessengerType.ts deleted file mode 100644 index c4c4ea64..00000000 --- a/packages/messages/lib/types/Messenger/MessengerType.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { MessengerCategory } from '../../enums'; - -export type MessengerType = { - category: MessengerCategory - tag?: string -} diff --git a/packages/messages/lib/types/Messenger/MessengerVideoParams.ts b/packages/messages/lib/types/Messenger/MessengerVideoParams.ts deleted file mode 100644 index 8fffcfa5..00000000 --- a/packages/messages/lib/types/Messenger/MessengerVideoParams.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { MessageParamsVideo } from '../MessageParamsVideo'; -import { MessengerParams } from './MessengerParams'; - -export type MessengerVideoParams = MessengerParams & MessageParamsVideo diff --git a/packages/messages/lib/types/Messenger/index.ts b/packages/messages/lib/types/Messenger/index.ts deleted file mode 100644 index 4eb18ccf..00000000 --- a/packages/messages/lib/types/Messenger/index.ts +++ /dev/null @@ -1,7 +0,0 @@ -export * from './MessengerAudioParams'; -export * from './MessengerFileParams'; -export * from './MessengerImageParams'; -export * from './MessengerParams'; -export * from './MessengerTextParams'; -export * from './MessengerType'; -export * from './MessengerVideoParams'; diff --git a/packages/messages/lib/types/Requests/MMSAudioRequest.ts b/packages/messages/lib/types/Requests/MMSAudioRequest.ts index ff8c59ff..7c1c612f 100644 --- a/packages/messages/lib/types/Requests/MMSAudioRequest.ts +++ b/packages/messages/lib/types/Requests/MMSAudioRequest.ts @@ -1,11 +1,51 @@ +/** + * Represents a request for sending an audio message via the MMS (Multimedia Messaging Service) channel. + * + * @group MMS + * @category Requests + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type MMSAudioRequest = { - client_ref: string - message_type: 'audio' - audio: { - url: string - caption?: string - } - to: string - from: string - channel: 'mms' + /** + * A client-defined reference string for the message. + */ + client_ref: string; + + /** + * The type of the message, which is 'audio' for an audio message. + */ + message_type: 'audio'; + + /** + * The audio content of the message, including the URL of the audio and an optional caption. + */ + audio: { + /** + * The URL of the audio file to be sent in the message. + */ + url: string; + + /** + * An optional caption or description for the audio message. + */ + caption?: string; + }; + + /** + * The recipient's phone number or identifier. + */ + to: string; + + /** + * The sender's phone number or identifier. + */ + from: string; + + /** + * The channel through which the message will be sent, which is 'mms' for MMS. + */ + channel: 'mms'; } diff --git a/packages/messages/lib/types/Requests/MMSImageRequest.ts b/packages/messages/lib/types/Requests/MMSImageRequest.ts index 47c16d92..fb52ab8f 100644 --- a/packages/messages/lib/types/Requests/MMSImageRequest.ts +++ b/packages/messages/lib/types/Requests/MMSImageRequest.ts @@ -1,11 +1,51 @@ +/** + * Represents a request for sending an image message via the MMS (Multimedia Messaging Service) channel. + * + * @group MMS + * @category Requests + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type MMSImageRequest = { - client_ref: string - message_type: 'image' - image: { - url: string - caption?: string - } - to: string - from: string - channel: 'mms' + /** + * A client-defined reference string for the message. + */ + client_ref: string; + + /** + * The type of the message, which is 'image' for an image message. + */ + message_type: 'image'; + + /** + * The image content of the message, including the URL of the image and an optional caption. + */ + image: { + /** + * The URL of the image file to be sent in the message. + */ + url: string; + + /** + * An optional caption or description for the image message. + */ + caption?: string; + }; + + /** + * The recipient's phone number or identifier. + */ + to: string; + + /** + * The sender's phone number or identifier. + */ + from: string; + + /** + * The channel through which the message will be sent, which is 'mms' for MMS. + */ + channel: 'mms'; } diff --git a/packages/messages/lib/types/Requests/MMSVcardRequest.ts b/packages/messages/lib/types/Requests/MMSVcardRequest.ts index 98dd18b4..1adacac1 100644 --- a/packages/messages/lib/types/Requests/MMSVcardRequest.ts +++ b/packages/messages/lib/types/Requests/MMSVcardRequest.ts @@ -1,10 +1,46 @@ +/** + * Represents a request for sending a vCard message via the MMS (Multimedia Messaging Service) channel. + * + * @group MMS + * @category Requests + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type MMSVcardRequest = { - client_ref: string - message_type: 'vcard' - vcard: { - url: string - } - to: string - from: string - channel: 'mms' + /** + * A client-defined reference string for the message. + */ + client_ref: string; + + /** + * The type of the message, which is 'vcard' for a vCard message. + */ + message_type: 'vcard'; + + /** + * The vCard content of the message, including the URL of the vCard file. + */ + vcard: { + /** + * The URL of the vCard file to be sent in the message. + */ + url: string; + }; + + /** + * The recipient's phone number or identifier. + */ + to: string; + + /** + * The sender's phone number or identifier. + */ + from: string; + + /** + * The channel through which the message will be sent, which is 'mms' for MMS. + */ + channel: 'mms'; } diff --git a/packages/messages/lib/types/Requests/MMSVideoRequest.ts b/packages/messages/lib/types/Requests/MMSVideoRequest.ts index e879c0f8..e290bb57 100644 --- a/packages/messages/lib/types/Requests/MMSVideoRequest.ts +++ b/packages/messages/lib/types/Requests/MMSVideoRequest.ts @@ -1,11 +1,51 @@ +/** + * Represents a request for sending a video message via the MMS (Multimedia Messaging Service) channel. + * + * @group MMS + * @category Requests + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type MMSVideoRequest = { - client_ref: string - message_type: 'video' - video: { - url: string - caption?: string - } - to: string - from: string - channel: 'mms' + /** + * A client-defined reference string for the message. + */ + client_ref: string; + + /** + * The type of the message, which is 'video' for a video message. + */ + message_type: 'video'; + + /** + * The video content of the message, including the URL of the video file and an optional caption. + */ + video: { + /** + * The URL of the video file to be sent in the message. + */ + url: string; + + /** + * An optional caption for the video. + */ + caption?: string; + }; + + /** + * The recipient's phone number or identifier. + */ + to: string; + + /** + * The sender's phone number or identifier. + */ + from: string; + + /** + * The channel through which the message will be sent, which is 'mms' for MMS. + */ + channel: 'mms'; } diff --git a/packages/messages/lib/types/Requests/MessengerAudioRequest.ts b/packages/messages/lib/types/Requests/MessengerAudioRequest.ts index 573fed7a..d1c1e1c6 100644 --- a/packages/messages/lib/types/Requests/MessengerAudioRequest.ts +++ b/packages/messages/lib/types/Requests/MessengerAudioRequest.ts @@ -1,13 +1,31 @@ -import { MessengerType } from '../Messenger'; +import { MessengerType } from '../Channels'; +/** + * Represents a request to send an audio message via the Messenger channel. + * + * @group Messenger + * @category Requests + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure request structure before it's transformed into `snake_case` for the API call. + */ export type MessengerAudioRequest = { - client_ref: string - message_type: 'audio' - audio: { - url: string - } - to: string - from: string - channel: 'messenger' - messenger: MessengerType -} + /** A client reference string for tracking the message. */ + client_ref: string; + /** The message type, which is set to 'audio' for an audio message. */ + message_type: 'audio'; + /** The audio content of the message, including the URL of the audio file. */ + audio: { + /** The URL of the audio file. */ + url: string; + }; + /** The recipient of the message. */ + to: string; + /** The sender of the message. */ + from: string; + /** The channel for sending the message, which is set to 'messenger'. */ + channel: 'messenger'; + /** Additional details about the Messenger message type. */ + messenger: MessengerType; +}; diff --git a/packages/messages/lib/types/Requests/MessengerFileRequest.ts b/packages/messages/lib/types/Requests/MessengerFileRequest.ts index 08f4ba98..300c4816 100644 --- a/packages/messages/lib/types/Requests/MessengerFileRequest.ts +++ b/packages/messages/lib/types/Requests/MessengerFileRequest.ts @@ -1,13 +1,31 @@ -import { MessengerType } from '../Messenger'; +import { MessengerType } from '../Channels'; +/** + * Represents a request to send a file message via the Messenger channel. + * + * @group Messenger + * @category Requests + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure request structure before it's transformed into `snake_case` for the API call. + */ export type MessengerFileRequest = { - client_ref: string - message_type: 'file' - file: { - url: string - } - to: string - from: string - channel: 'messenger' - messenger: MessengerType -} + /** A client reference string for tracking the message. */ + client_ref: string; + /** The message type, which is set to 'file' for a file message. */ + message_type: 'file'; + /** The file content of the message, including the URL of the file. */ + file: { + /** The URL of the file. */ + url: string; + }; + /** The recipient of the message. */ + to: string; + /** The sender of the message. */ + from: string; + /** The channel for sending the message, which is set to 'messenger'. */ + channel: 'messenger'; + /** Additional details about the Messenger message type. */ + messenger: MessengerType; +}; diff --git a/packages/messages/lib/types/Requests/MessengerImageRequest.ts b/packages/messages/lib/types/Requests/MessengerImageRequest.ts index a74f8413..a9fc0b6c 100644 --- a/packages/messages/lib/types/Requests/MessengerImageRequest.ts +++ b/packages/messages/lib/types/Requests/MessengerImageRequest.ts @@ -1,13 +1,32 @@ -import { MessengerType } from '../Messenger'; +import { MessengerType } from '../Channels'; +/** + * Represents a request to send an image message via the Messenger channel. + * + * @group Messenger + * @category Requests + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure request structure before it's transformed into `snake_case` for the API call. + */ export type MessengerImageRequest = { - client_ref: string - message_type: 'image' - image: { - url: string - } - to: string - from: string - channel: 'messenger' - messenger: MessengerType + /** A client reference string for tracking the message. */ + client_ref: string; + /** The message type, which is set to 'image' for an image message. */ + message_type: 'image'; + /** The image content of the message, including the URL of the image. */ + image: { + /** The URL of the image. */ + url: string; + }; + /** The recipient of the message. */ + to: string; + /** The sender of the message. */ + from: string; + /** The channel for sending the message, which is set to 'messenger'. */ + channel: 'messenger'; + + /** Additional details about the Messenger message type. */ + messenger: MessengerType; } diff --git a/packages/messages/lib/types/Requests/MessengerTextRequest.ts b/packages/messages/lib/types/Requests/MessengerTextRequest.ts index 9ff96508..c3d0dda1 100644 --- a/packages/messages/lib/types/Requests/MessengerTextRequest.ts +++ b/packages/messages/lib/types/Requests/MessengerTextRequest.ts @@ -1,11 +1,47 @@ -import { MessengerType } from '../Messenger'; - +import { MessengerType } from '../Channels'; +/** + * Represents a request for sending a text message via the Messenger channel. + * + * @group Messenger + * @category Requests + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type MessengerTextRequest = { - client_ref: string - message_type: 'text' - text: string - to: string - from: string - channel: 'messenger' - messenger: MessengerType + /** + * A client-defined reference string for the message. + */ + client_ref: string; + + /** + * The type of the message, which is 'text' for a text message. + */ + message_type: 'text'; + + /** + * The text content of the message. + */ + text: string; + + /** + * The recipient's phone number or identifier. + */ + to: string; + + /** + * The sender's phone number or identifier. + */ + from: string; + + /** + * The channel through which the message will be sent, which is 'messenger' for Messenger. + */ + channel: 'messenger'; + + /** + * Additional information specific to the Messenger channel. + */ + messenger: MessengerType; } diff --git a/packages/messages/lib/types/Requests/MessengerVideoRequest.ts b/packages/messages/lib/types/Requests/MessengerVideoRequest.ts index 7e76cd1c..7795249f 100644 --- a/packages/messages/lib/types/Requests/MessengerVideoRequest.ts +++ b/packages/messages/lib/types/Requests/MessengerVideoRequest.ts @@ -1,13 +1,54 @@ -import { MessengerType } from '../Messenger'; +import { MessengerType } from '../Channels'; +/** + * Represents a request for sending a video message via the Messenger channel. + * + * @group Messenger + * @category Requests + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type MessengerVideoRequest = { - client_ref: string - message_type: 'video' - video: { - url: string - } - to: string - from: string - channel: 'messenger' - messenger: MessengerType + /** + * A client-defined reference string for the message. + */ + client_ref: string; + + /** + * The type of the message, which is 'video' for a video message. + */ + message_type: 'video'; + + /** + * The video content of the message. + */ + video: { + /** + * The URL of the video to be sent in the message. + */ + url: string; + }; + + /** + * The recipient's phone number or identifier. + */ + to: string; + + /** + * The sender's phone number or identifier. + */ + from: string; + + /** + * The channel through which the message will be sent, which is 'messenger' for Messenger. + */ + channel: 'messenger'; + + /** + * Additional information specific to the Messenger channel. + */ + messenger: MessengerType; } + diff --git a/packages/messages/lib/types/Requests/SMSMessageRequest.ts b/packages/messages/lib/types/Requests/SMSMessageRequest.ts index 26dcc7ef..ba0ce670 100644 --- a/packages/messages/lib/types/Requests/SMSMessageRequest.ts +++ b/packages/messages/lib/types/Requests/SMSMessageRequest.ts @@ -1,8 +1,41 @@ +/** + * Represents a request for sending a text message via the SMS (Short Message Service) channel. + * + * @group SMS + * @category Requests + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type SMSMessageRequest = { - client_ref: string - message_type: 'text' - text: string - to: string - from: string - channel: 'sms' + /** + * A client-defined reference string for the message. + */ + client_ref: string; + + /** + * The type of the message, which is 'text' for a text message. + */ + message_type: 'text'; + + /** + * The text content of the message. + */ + text: string; + + /** + * The recipient's phone number. + */ + to: string; + + /** + * The sender's phone number or identifier. + */ + from: string; + + /** + * The channel through which the message will be sent, which is 'sms' for SMS. + */ + channel: 'sms'; } diff --git a/packages/messages/lib/types/Requests/ViberFileRequest.ts b/packages/messages/lib/types/Requests/ViberFileRequest.ts index 3112afdf..0b5471d6 100644 --- a/packages/messages/lib/types/Requests/ViberFileRequest.ts +++ b/packages/messages/lib/types/Requests/ViberFileRequest.ts @@ -1,14 +1,58 @@ -import { ViberService } from '../Viber'; +import { ViberService } from '../Channels'; +/** + * Represents a request for sending a file message via the Viber Service channel. + * + * @group Viber + * @category Requests + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type ViberFileRequest = { - client_ref: string - message_type: 'file' - file: { - url: string - name: string - } - to: string - from: string - channel: 'viber_service' - viber_service: ViberService + /** + * A client-defined reference string for the message. + */ + client_ref: string; + + /** + * The type of the message, which is 'file' for a file message. + */ + message_type: 'file'; + + /** + * The file content to be sent, including the URL and name. + */ + file: { + /** + * The URL of the file to be sent. + */ + url: string; + + /** + * The name of the file. + */ + name: string; + }; + + /** + * The recipient's identifier. + */ + to: string; + + /** + * The sender's identifier. + */ + from: string; + + /** + * The channel through which the message will be sent, which is 'viber_service' for Viber Service. + */ + channel: 'viber_service'; + + /** + * The Viber service configuration. + */ + viber_service: ViberService; } diff --git a/packages/messages/lib/types/Requests/ViberImageRequest.ts b/packages/messages/lib/types/Requests/ViberImageRequest.ts index e6c9b65c..02d43ef9 100644 --- a/packages/messages/lib/types/Requests/ViberImageRequest.ts +++ b/packages/messages/lib/types/Requests/ViberImageRequest.ts @@ -1,14 +1,58 @@ -import { ViberService } from '../Viber'; +import { ViberService } from '../Channels'; +/** + * Represents a request for sending an image message via the Viber Service channel. + * + * @group Viber + * @category Requests + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type ViberImageRequest = { - client_ref: string - message_type: 'image' - image: { - url: string - caption?: string - } - to: string - from: string - channel: 'viber_service' - viber_service: ViberService + /** + * A client-defined reference string for the message. + */ + client_ref: string; + + /** + * The type of the message, which is 'image' for an image message. + */ + message_type: 'image'; + + /** + * The image content to be sent, including the URL and optional caption. + */ + image: { + /** + * The URL of the image to be sent. + */ + url: string; + + /** + * An optional caption for the image. + */ + caption?: string; + }; + + /** + * The recipient's identifier. + */ + to: string; + + /** + * The sender's identifier. + */ + from: string; + + /** + * The channel through which the message will be sent, which is 'viber_service' for Viber Service. + */ + channel: 'viber_service'; + + /** + * The Viber service configuration. + */ + viber_service: ViberService; } diff --git a/packages/messages/lib/types/Requests/ViberTextRequest.ts b/packages/messages/lib/types/Requests/ViberTextRequest.ts index 5463b4d5..e502f721 100644 --- a/packages/messages/lib/types/Requests/ViberTextRequest.ts +++ b/packages/messages/lib/types/Requests/ViberTextRequest.ts @@ -1,11 +1,48 @@ -import { ViberService } from '../Viber'; +import { ViberService } from '../Channels'; +/** + * Represents a request for sending a text message via the Viber Service channel. + * + * @group Viber + * @category Requests + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type ViberTextRequest = { - client_ref: string - message_type: 'text' - text: string - to: string - from: string - channel: 'viber_service' - viber_service: ViberService + /** + * A client-defined reference string for the message. + */ + client_ref: string; + + /** + * The type of the message, which is 'text' for a text message. + */ + message_type: 'text'; + + /** + * The text content of the message. + */ + text: string; + + /** + * The recipient's identifier. + */ + to: string; + + /** + * The sender's identifier. + */ + from: string; + + /** + * The channel through which the message will be sent, which is 'viber_service' for Viber Service. + */ + channel: 'viber_service'; + + /** + * The Viber service configuration. + */ + viber_service: ViberService; } diff --git a/packages/messages/lib/types/Requests/ViberVideoRequest.ts b/packages/messages/lib/types/Requests/ViberVideoRequest.ts index f4a40a88..3e5148f2 100644 --- a/packages/messages/lib/types/Requests/ViberVideoRequest.ts +++ b/packages/messages/lib/types/Requests/ViberVideoRequest.ts @@ -1,15 +1,63 @@ -import { ViberService } from '../Viber'; +import { ViberService } from '../Channels'; +/** + * Represents a request for sending a video message via the Viber Service channel. + * + * @group Viber + * @category Requests + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type ViberVideoRequest = { - client_ref: string - message_type: 'video' - video: { - url: string - caption?: string - thumb_url?: string - } - to: string - from: string - channel: 'viber_service' - viber_service: ViberService + /** + * A client-defined reference string for the message. + */ + client_ref: string; + + /** + * The type of the message, which is 'video' for a video message. + */ + message_type: 'video'; + + /** + * The video content of the message, including its URL and optional caption and thumbnail URL. + */ + video: { + /** + * The URL of the video. + */ + url: string; + + /** + * An optional caption for the video. + */ + caption?: string; + + /** + * An optional URL for the video's thumbnail. + */ + thumb_url?: string; + }; + + /** + * The recipient's identifier. + */ + to: string; + + /** + * The sender's identifier. + */ + from: string; + + /** + * The channel through which the message will be sent, which is 'viber_service' for Viber Service. + */ + channel: 'viber_service'; + + /** + * The Viber service configuration. + */ + viber_service: ViberService; } diff --git a/packages/messages/lib/types/Requests/WhatsAppAudioRequest.ts b/packages/messages/lib/types/Requests/WhatsAppAudioRequest.ts index b45490c2..f63210fa 100644 --- a/packages/messages/lib/types/Requests/WhatsAppAudioRequest.ts +++ b/packages/messages/lib/types/Requests/WhatsAppAudioRequest.ts @@ -1,10 +1,46 @@ +/** + * Represents a request for sending an audio message via the WhatsApp channel. + * + * @group WhatsApp + * @category Requests + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type WhatsAppAudioRequest = { - client_ref: string - message_type: 'audio' - audio: { - url: string - } - to: string - from: string - channel: 'whatsapp' + /** + * A client-defined reference string for the message. + */ + client_ref: string; + + /** + * The type of the message, which is 'audio' for an audio message. + */ + message_type: 'audio'; + + /** + * The audio content of the message, including its URL. + */ + audio: { + /** + * The URL of the audio. + */ + url: string; + }; + + /** + * The recipient's identifier. + */ + to: string; + + /** + * The sender's identifier. + */ + from: string; + + /** + * The channel through which the message will be sent, which is 'whatsapp' for WhatsApp. + */ + channel: 'whatsapp'; } diff --git a/packages/messages/lib/types/Requests/WhatsAppCustomRequest.ts b/packages/messages/lib/types/Requests/WhatsAppCustomRequest.ts index a3c240cc..edec0890 100644 --- a/packages/messages/lib/types/Requests/WhatsAppCustomRequest.ts +++ b/packages/messages/lib/types/Requests/WhatsAppCustomRequest.ts @@ -1,8 +1,41 @@ +/** + * Represents a request for sending a custom message via the WhatsApp channel. + * + * @group WhatsApp + * @category Requests + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type WhatsAppCustomRequest = { - client_ref: string - message_type: 'custom' - custom: Record - to: string - from: string - channel: 'whatsapp' + /** + * A client-defined reference string for the message. + */ + client_ref: string; + + /** + * The type of the message, which is 'custom' for a custom message. + */ + message_type: 'custom'; + + /** + * The custom content of the message as a record of unknown type. + */ + custom: Record; + + /** + * The recipient's identifier. + */ + to: string; + + /** + * The sender's identifier. + */ + from: string; + + /** + * The channel through which the message will be sent, which is 'whatsapp' for WhatsApp. + */ + channel: 'whatsapp'; } diff --git a/packages/messages/lib/types/Requests/WhatsAppFileRequest.ts b/packages/messages/lib/types/Requests/WhatsAppFileRequest.ts index 0f6d9fa2..8e456680 100644 --- a/packages/messages/lib/types/Requests/WhatsAppFileRequest.ts +++ b/packages/messages/lib/types/Requests/WhatsAppFileRequest.ts @@ -1,11 +1,51 @@ +/** + * Represents a request for sending a file message via the WhatsApp channel. + * + * @group WhatsApp + * @category Requests + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type WhatsAppFileRequest = { - client_ref: string - message_type: 'file' - file: { - url: string - caption?: string - } - to: string - from: string - channel: 'whatsapp' + /** + * A client-defined reference string for the message. + */ + client_ref: string; + + /** + * The type of the message, which is 'file' for a file message. + */ + message_type: 'file'; + + /** + * The file content of the message, including the URL of the file and an optional caption. + */ + file: { + /** + * The URL of the file to be sent. + */ + url: string; + + /** + * An optional caption for the file. + */ + caption?: string; + }; + + /** + * The recipient's identifier. + */ + to: string; + + /** + * The sender's identifier. + */ + from: string; + + /** + * The channel through which the message will be sent, which is 'whatsapp' for WhatsApp. + */ + channel: 'whatsapp'; } diff --git a/packages/messages/lib/types/Requests/WhatsAppImageRequest.ts b/packages/messages/lib/types/Requests/WhatsAppImageRequest.ts index c1e7885b..499a6e1b 100644 --- a/packages/messages/lib/types/Requests/WhatsAppImageRequest.ts +++ b/packages/messages/lib/types/Requests/WhatsAppImageRequest.ts @@ -1,11 +1,51 @@ +/** + * Represents a request for sending an image message via the WhatsApp channel. + * + * @group WhatsApp + * @category Requests + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type WhatsAppImageRequest = { - client_ref: string - message_type: 'image' - image: { - url: string - caption?: string - } - to: string - from: string - channel: 'whatsapp' + /** + * A client-defined reference string for the message. + */ + client_ref: string; + + /** + * The type of the message, which is 'image' for an image message. + */ + message_type: 'image'; + + /** + * The image content of the message, including the URL of the image and an optional caption. + */ + image: { + /** + * The URL of the image to be sent. + */ + url: string; + + /** + * An optional caption for the image. + */ + caption?: string; + }; + + /** + * The recipient's identifier. + */ + to: string; + + /** + * The sender's identifier. + */ + from: string; + + /** + * The channel through which the message will be sent, which is 'whatsapp' for WhatsApp. + */ + channel: 'whatsapp'; } diff --git a/packages/messages/lib/types/Requests/WhatsAppStickerIdRequest.ts b/packages/messages/lib/types/Requests/WhatsAppStickerIdRequest.ts index ef0f5c83..0045eb36 100644 --- a/packages/messages/lib/types/Requests/WhatsAppStickerIdRequest.ts +++ b/packages/messages/lib/types/Requests/WhatsAppStickerIdRequest.ts @@ -1,10 +1,46 @@ +/** + * Represents a request for sending a sticker message via the WhatsApp channel using a sticker ID. + * + * @group WhatsApp + * @category Requests + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type WhatsAppStickerIdRequest = { - client_ref: string - message_type: 'sticker' - sticker: { - id: string - } - to: string - from: string - channel: 'whatsapp' + /** + * A client-defined reference string for the message. + */ + client_ref: string; + + /** + * The type of the message, which is 'sticker' for a sticker message. + */ + message_type: 'sticker'; + + /** + * The sticker content of the message, including the sticker ID. + */ + sticker: { + /** + * The ID of the sticker to be sent. + */ + id: string; + }; + + /** + * The recipient's identifier. + */ + to: string; + + /** + * The sender's identifier. + */ + from: string; + + /** + * The channel through which the message will be sent, which is 'whatsapp' for WhatsApp. + */ + channel: 'whatsapp'; } diff --git a/packages/messages/lib/types/Requests/WhatsAppStickerUrlRequest.ts b/packages/messages/lib/types/Requests/WhatsAppStickerUrlRequest.ts index 03e112d0..5911bbb5 100644 --- a/packages/messages/lib/types/Requests/WhatsAppStickerUrlRequest.ts +++ b/packages/messages/lib/types/Requests/WhatsAppStickerUrlRequest.ts @@ -1,10 +1,46 @@ +/** + * Represents a request for sending a sticker message via the WhatsApp channel using a sticker URL. + * + * @group WhatsApp + * @category Requests + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type WhatsAppStickerUrlRequest = { - client_ref: string - message_type: 'sticker' - sticker: { - url: string - } - to: string - from: string - channel: 'whatsapp' + /** + * A client-defined reference string for the message. + */ + client_ref: string; + + /** + * The type of the message, which is 'sticker' for a sticker message. + */ + message_type: 'sticker'; + + /** + * The sticker content of the message, including the sticker URL. + */ + sticker: { + /** + * The URL of the sticker to be sent. + */ + url: string; + }; + + /** + * The recipient's identifier. + */ + to: string; + + /** + * The sender's identifier. + */ + from: string; + + /** + * The channel through which the message will be sent, which is 'whatsapp' for WhatsApp. + */ + channel: 'whatsapp'; } diff --git a/packages/messages/lib/types/Requests/WhatsAppTemplateRequest.ts b/packages/messages/lib/types/Requests/WhatsAppTemplateRequest.ts index 297a0b83..8791453b 100644 --- a/packages/messages/lib/types/Requests/WhatsAppTemplateRequest.ts +++ b/packages/messages/lib/types/Requests/WhatsAppTemplateRequest.ts @@ -1,11 +1,48 @@ -import { WhatsAppPolicyType, WhatsAppTemplateType } from '../WhatsApp/index'; +import { WhatsAppPolicyType, WhatsAppTemplateType } from '../Channels'; +/** + * Represents a request for sending a template message via the WhatsApp channel. + * + * @group WhatsApp + * @category Requests + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type WhatsAppTemplateRequest = { - client_ref: string - message_type: 'template' - template: WhatsAppTemplateType - to: string - from: string - channel: 'whatsapp' - whatsapp: WhatsAppPolicyType + /** + * A client-defined reference string for the message. + */ + client_ref: string; + + /** + * The type of the message, which is 'template' for a template message. + */ + message_type: 'template'; + + /** + * The template content of the message, including the template type. + */ + template: WhatsAppTemplateType; + + /** + * The recipient's identifier. + */ + to: string; + + /** + * The sender's identifier. + */ + from: string; + + /** + * The channel through which the message will be sent, which is 'whatsapp' for WhatsApp. + */ + channel: 'whatsapp'; + + /** + * The policy and locale settings for sending the WhatsApp template message. + */ + whatsapp: WhatsAppPolicyType; } diff --git a/packages/messages/lib/types/Requests/WhatsAppTextRequest.ts b/packages/messages/lib/types/Requests/WhatsAppTextRequest.ts index 11e4881a..6a47d748 100644 --- a/packages/messages/lib/types/Requests/WhatsAppTextRequest.ts +++ b/packages/messages/lib/types/Requests/WhatsAppTextRequest.ts @@ -1,8 +1,41 @@ +/** + * Represents a request for sending a text message via the WhatsApp channel. + * + * @group WhatsApp + * @category Requests + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type WhatsAppTextRequest = { - client_ref: string - message_type: 'text' - text: string - to: string - from: string - channel: 'whatsapp' + /** + * A client-defined reference string for the message. + */ + client_ref: string; + + /** + * The type of the message, which is 'text' for a text message. + */ + message_type: 'text'; + + /** + * The text content of the message. + */ + text: string; + + /** + * The recipient's identifier. + */ + to: string; + + /** + * The sender's identifier. + */ + from: string; + + /** + * The channel through which the message will be sent, which is 'whatsapp' for WhatsApp. + */ + channel: 'whatsapp'; } diff --git a/packages/messages/lib/types/Requests/WhatsAppVideoRequest.ts b/packages/messages/lib/types/Requests/WhatsAppVideoRequest.ts index 1d352ba4..33f31e03 100644 --- a/packages/messages/lib/types/Requests/WhatsAppVideoRequest.ts +++ b/packages/messages/lib/types/Requests/WhatsAppVideoRequest.ts @@ -1,11 +1,51 @@ +/** + * Represents a request for sending a video message via the WhatsApp channel. + * + * @group WhatsApp + * @category Requests + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type WhatsAppVideoRequest = { - client_ref: string - message_type: 'video' - video: { - url: string - caption?: string - } - to: string - from: string - channel: 'whatsapp' + /** + * A client-defined reference string for the message. + */ + client_ref: string; + + /** + * The type of the message, which is 'video' for a video message. + */ + message_type: 'video'; + + /** + * The video content of the message, including the URL and an optional caption. + */ + video: { + /** + * The URL of the video. + */ + url: string; + + /** + * An optional caption for the video. + */ + caption?: string; + }; + + /** + * The recipient's identifier. + */ + to: string; + + /** + * The sender's identifier. + */ + from: string; + + /** + * The channel through which the message will be sent, which is 'whatsapp' for WhatsApp. + */ + channel: 'whatsapp'; } diff --git a/packages/messages/lib/types/Responses/MessageErrorResponse.ts b/packages/messages/lib/types/Responses/MessageErrorResponse.ts index 201e5240..d80c2f22 100644 --- a/packages/messages/lib/types/Responses/MessageErrorResponse.ts +++ b/packages/messages/lib/types/Responses/MessageErrorResponse.ts @@ -1,10 +1,32 @@ -export type MessageErrorResponse = { - type: string - title: string - detail: string - instance: string - invalid_parameters?: { - name: string - reason: string - } -} +/** + * Represents an error response received when sending a message. + * + * This type includes information about the error type, title, details, and an instance identifier. + * + * If applicable, it may also contain information about invalid parameters that caused the error. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase` + * + * @group Responses + */ +type MessageErrorResponse = { + /** The type of the error. */ + type: string; + /** A title or brief description of the error. */ + title: string; + /** Additional details about the error. */ + detail: string; + /** An instance identifier for reference. */ + instance: string; + /** Optional: Invalid parameters that contributed to the error. */ + invalid_parameters?: { + /** The name of the invalid parameter. */ + name: string; + /** The reason or explanation for the parameter's invalidity. */ + reason: string; + }; +}; + +export default MessageErrorResponse; diff --git a/packages/messages/lib/types/Responses/MessageSuccessResponse.ts b/packages/messages/lib/types/Responses/MessageSuccessResponse.ts index 14f417b3..75c468cb 100644 --- a/packages/messages/lib/types/Responses/MessageSuccessResponse.ts +++ b/packages/messages/lib/types/Responses/MessageSuccessResponse.ts @@ -1,3 +1,16 @@ +/** + * Represents a successful response received when sending a message. + * + * This type includes a `message_uuid` field, which is a unique identifier for the sent message. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase` + * + * @group Responses + */ export type MessageSuccessResponse = { - message_uuid: string -} + /** A unique identifier for the sent message. */ + message_uuid: string; +}; + diff --git a/packages/messages/lib/types/SendMessageParams.ts b/packages/messages/lib/types/SendMessageParams.ts index 2a0944f3..0fbd1f14 100644 --- a/packages/messages/lib/types/SendMessageParams.ts +++ b/packages/messages/lib/types/SendMessageParams.ts @@ -1,48 +1,20 @@ import { - MessengerAudioInterface, - MessengerFileInterface, - MessengerImageInterface, - MessengerTextInterface, - MessengerVideoInterface, - MMSAudioInterface, - MMSImageInterface, - MMSVcardInterface, - MMSVideoInterface, - SMSTextInterface, - ViberFileInterface, - ViberImageInterface, - ViberTextInterface, - ViberVideoInterface, - WhatsAppAudioInterface, - WhatsAppCustomInterface, - WhatsAppFileInterface, - WhatsAppImageInterface, - WhatsAppStickerInterface, - WhatsAppTemplateInterface, - WhatsAppTextInterface, - WhatsAppVideoInterface, -} from '../interfaces'; + AnyMessengerParams, + AnyViberParams, + AnyWhatsAppParams, + AnyMMSParams, + SMSParams, +} from "./Channels"; +/** + * Represents parameters for sending various types of messages. + * This union type can be used to send messages across different platforms like + * Messenger, MMS, SMS, Viber, WhatsApp, etc. + * Use the corresponding Type for the specific message type you want to send. + */ export type SendMessageParams = - | MessengerAudioInterface - | MessengerFileInterface - | MessengerImageInterface - | MessengerTextInterface - | MessengerVideoInterface - | MMSAudioInterface - | MMSImageInterface - | MMSVcardInterface - | MMSVideoInterface - | SMSTextInterface - | ViberFileInterface - | ViberImageInterface - | ViberTextInterface - | ViberVideoInterface - | WhatsAppAudioInterface - | WhatsAppCustomInterface - | WhatsAppFileInterface - | WhatsAppImageInterface - | WhatsAppStickerInterface - | WhatsAppTemplateInterface - | WhatsAppTextInterface - | WhatsAppVideoInterface + AnyMessengerParams | + AnyViberParams | + AnyWhatsAppParams | + AnyMMSParams | + SMSParams diff --git a/packages/messages/lib/types/Viber/ViberAction.ts b/packages/messages/lib/types/Viber/ViberAction.ts deleted file mode 100644 index 4ffab16a..00000000 --- a/packages/messages/lib/types/Viber/ViberAction.ts +++ /dev/null @@ -1,4 +0,0 @@ -export type ViberAction = { - url: string - text: string -} diff --git a/packages/messages/lib/types/Viber/ViberActionParams.ts b/packages/messages/lib/types/Viber/ViberActionParams.ts deleted file mode 100644 index 8c7f1fd2..00000000 --- a/packages/messages/lib/types/Viber/ViberActionParams.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { ViberService } from './ViberService'; -import { ViberAction } from './ViberAction'; - -export type ViberActionParams = { - action: ViberAction -} & ViberService diff --git a/packages/messages/lib/types/Viber/ViberFileParams.ts b/packages/messages/lib/types/Viber/ViberFileParams.ts deleted file mode 100644 index 8a32dff6..00000000 --- a/packages/messages/lib/types/Viber/ViberFileParams.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { MessageParamsFile } from '../MessageParamsFile'; -import { ViberService } from './ViberService'; - -export type ViberFileParams = { - viberService: ViberService -} & MessageParamsFile diff --git a/packages/messages/lib/types/Viber/ViberImageParams.ts b/packages/messages/lib/types/Viber/ViberImageParams.ts deleted file mode 100644 index 35602569..00000000 --- a/packages/messages/lib/types/Viber/ViberImageParams.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { MessageParamsImage } from '../MessageParamsImage'; -import { ViberActionParams } from './ViberActionParams'; - -export type ViberImageParams = { - viberService: ViberActionParams -} & MessageParamsImage diff --git a/packages/messages/lib/types/Viber/ViberService.ts b/packages/messages/lib/types/Viber/ViberService.ts deleted file mode 100644 index 92c37db2..00000000 --- a/packages/messages/lib/types/Viber/ViberService.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { ViberCategory } from '../../enums'; - -export type ViberService = { - ttl: number - type: string - category: ViberCategory -} diff --git a/packages/messages/lib/types/Viber/ViberTextParams.ts b/packages/messages/lib/types/Viber/ViberTextParams.ts deleted file mode 100644 index 14d74ae6..00000000 --- a/packages/messages/lib/types/Viber/ViberTextParams.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { ViberActionParams } from './ViberActionParams'; -import { MessageParamsText } from '../MessageParamsText'; - -export type ViberTextParams = { - viberService: ViberActionParams -} & MessageParamsText diff --git a/packages/messages/lib/types/Viber/ViberVideoParams.ts b/packages/messages/lib/types/Viber/ViberVideoParams.ts deleted file mode 100644 index 45b8a185..00000000 --- a/packages/messages/lib/types/Viber/ViberVideoParams.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { MessageParamsVideo } from '../MessageParamsVideo'; -import { ViberVideoInterface } from '../../interfaces'; -import { ViberActionParams } from './ViberActionParams'; - -export type ViberVideoParams = { - viberService: Pick & ViberActionParams -} & MessageParamsVideo diff --git a/packages/messages/lib/types/Viber/index.ts b/packages/messages/lib/types/Viber/index.ts deleted file mode 100644 index 974ebf0e..00000000 --- a/packages/messages/lib/types/Viber/index.ts +++ /dev/null @@ -1,7 +0,0 @@ -export * from './ViberAction'; -export * from './ViberActionParams'; -export * from './ViberFileParams'; -export * from './ViberImageParams'; -export * from './ViberService'; -export * from './ViberTextParams'; -export * from './ViberVideoParams'; diff --git a/packages/messages/lib/types/WhatsApp/WhatsAppAudioParams.ts b/packages/messages/lib/types/WhatsApp/WhatsAppAudioParams.ts deleted file mode 100644 index 55ee4225..00000000 --- a/packages/messages/lib/types/WhatsApp/WhatsAppAudioParams.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { MessageParamsAudio } from '../MessageParamsAudio'; - -export type WhatsAppAudioParams = MessageParamsAudio diff --git a/packages/messages/lib/types/WhatsApp/WhatsAppCustomParams.ts b/packages/messages/lib/types/WhatsApp/WhatsAppCustomParams.ts deleted file mode 100644 index cb1668de..00000000 --- a/packages/messages/lib/types/WhatsApp/WhatsAppCustomParams.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { MessageParamsFile } from '../MessageParamsFile'; -import { WhatsAppCustomType } from './WhatsAppCustomType'; - -export type WhatsAppCustomParams = { - custom: WhatsAppCustomType -} & MessageParamsFile diff --git a/packages/messages/lib/types/WhatsApp/WhatsAppCustomType.ts b/packages/messages/lib/types/WhatsApp/WhatsAppCustomType.ts deleted file mode 100644 index 0bc915ed..00000000 --- a/packages/messages/lib/types/WhatsApp/WhatsAppCustomType.ts +++ /dev/null @@ -1,3 +0,0 @@ -export type WhatsAppCustomType = { - [key: string]: unknown -} diff --git a/packages/messages/lib/types/WhatsApp/WhatsAppFileParams.ts b/packages/messages/lib/types/WhatsApp/WhatsAppFileParams.ts deleted file mode 100644 index ca3365b2..00000000 --- a/packages/messages/lib/types/WhatsApp/WhatsAppFileParams.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { MessageParamsFile } from '../MessageParamsFile'; - -export type WhatsAppFileParams = MessageParamsFile diff --git a/packages/messages/lib/types/WhatsApp/WhatsAppImageParams.ts b/packages/messages/lib/types/WhatsApp/WhatsAppImageParams.ts deleted file mode 100644 index 770e25a9..00000000 --- a/packages/messages/lib/types/WhatsApp/WhatsAppImageParams.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { MessageParamsImage } from '../MessageParamsImage'; - -export type WhatsAppImageParams = MessageParamsImage diff --git a/packages/messages/lib/types/WhatsApp/WhatsAppPolicyType.ts b/packages/messages/lib/types/WhatsApp/WhatsAppPolicyType.ts deleted file mode 100644 index 22041788..00000000 --- a/packages/messages/lib/types/WhatsApp/WhatsAppPolicyType.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { WhatsAppLanguageCode } from '../../enums'; - -export type WhatsAppPolicyType = { - policy: 'deterministic' - locale: WhatsAppLanguageCode -} diff --git a/packages/messages/lib/types/WhatsApp/WhatsAppStickerIdType.ts b/packages/messages/lib/types/WhatsApp/WhatsAppStickerIdType.ts deleted file mode 100644 index 8524ff30..00000000 --- a/packages/messages/lib/types/WhatsApp/WhatsAppStickerIdType.ts +++ /dev/null @@ -1,3 +0,0 @@ -export type WhatsAppStickerIdType = { - id: string -} diff --git a/packages/messages/lib/types/WhatsApp/WhatsAppStickerParams.ts b/packages/messages/lib/types/WhatsApp/WhatsAppStickerParams.ts deleted file mode 100644 index bd3d5b06..00000000 --- a/packages/messages/lib/types/WhatsApp/WhatsAppStickerParams.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { MessageParams } from '../MessageParams'; -import { WhatsAppStickerIdType } from './WhatsAppStickerIdType'; -import { WhatsAppStickerUrlType } from './WhatsAppStickerUrlType'; - -export type WhatsAppStickerParams = { - sticker: WhatsAppStickerIdType | WhatsAppStickerUrlType -} & MessageParams diff --git a/packages/messages/lib/types/WhatsApp/WhatsAppStickerUrlType.ts b/packages/messages/lib/types/WhatsApp/WhatsAppStickerUrlType.ts deleted file mode 100644 index bd06921f..00000000 --- a/packages/messages/lib/types/WhatsApp/WhatsAppStickerUrlType.ts +++ /dev/null @@ -1,3 +0,0 @@ -export type WhatsAppStickerUrlType = { - url: string -} diff --git a/packages/messages/lib/types/WhatsApp/WhatsAppTemplateParams.ts b/packages/messages/lib/types/WhatsApp/WhatsAppTemplateParams.ts deleted file mode 100644 index ae319324..00000000 --- a/packages/messages/lib/types/WhatsApp/WhatsAppTemplateParams.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { MessageParams } from '../MessageParams'; -import { WhatsAppTemplateType } from './WhatsAppTemplateType'; -import { WhatsAppPolicyType } from './WhatsAppPolicyType'; - -export type WhatsAppTemplateParams = { - whatsapp: WhatsAppPolicyType - template: WhatsAppTemplateType -} & MessageParams diff --git a/packages/messages/lib/types/WhatsApp/WhatsAppTemplateType.ts b/packages/messages/lib/types/WhatsApp/WhatsAppTemplateType.ts deleted file mode 100644 index 4f5bdb32..00000000 --- a/packages/messages/lib/types/WhatsApp/WhatsAppTemplateType.ts +++ /dev/null @@ -1,4 +0,0 @@ -export type WhatsAppTemplateType = { - name: string - parameters: string[] -} diff --git a/packages/messages/lib/types/WhatsApp/WhatsAppTextParams.ts b/packages/messages/lib/types/WhatsApp/WhatsAppTextParams.ts deleted file mode 100644 index 5d31c2af..00000000 --- a/packages/messages/lib/types/WhatsApp/WhatsAppTextParams.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { MessageParamsText } from '../MessageParamsText'; - -export type WhatsAppTextParams = MessageParamsText diff --git a/packages/messages/lib/types/WhatsApp/WhatsAppVideoParams.ts b/packages/messages/lib/types/WhatsApp/WhatsAppVideoParams.ts deleted file mode 100644 index 0b5270e0..00000000 --- a/packages/messages/lib/types/WhatsApp/WhatsAppVideoParams.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { MessageParamsVideo } from '../MessageParamsVideo'; - -export type WhatsAppVideoParams = MessageParamsVideo diff --git a/packages/messages/lib/types/WhatsApp/index.ts b/packages/messages/lib/types/WhatsApp/index.ts deleted file mode 100644 index 62cf0f4e..00000000 --- a/packages/messages/lib/types/WhatsApp/index.ts +++ /dev/null @@ -1,13 +0,0 @@ -export * from './WhatsAppAudioParams'; -export * from './WhatsAppCustomParams'; -export * from './WhatsAppCustomType'; -export * from './WhatsAppFileParams'; -export * from './WhatsAppImageParams'; -export * from './WhatsAppPolicyType'; -export * from './WhatsAppStickerIdType'; -export * from './WhatsAppStickerParams'; -export * from './WhatsAppStickerUrlType'; -export * from './WhatsAppTemplateParams'; -export * from './WhatsAppTemplateType'; -export * from './WhatsAppTextParams'; -export * from './WhatsAppVideoParams'; diff --git a/packages/messages/lib/types/index.ts b/packages/messages/lib/types/index.ts index 7b639b05..b9d89bd9 100644 --- a/packages/messages/lib/types/index.ts +++ b/packages/messages/lib/types/index.ts @@ -1,3 +1,4 @@ +export * from './Channels'; export * from './MessageAudioType'; export * from './MessageFileType'; export * from './MessageImageType'; @@ -10,9 +11,7 @@ export * from './MessageParamsVcard'; export * from './MessageParamsVideo'; export * from './MessageVcardType'; export * from './MessageVideoType'; -export * from './Messenger/index'; -export * from './Responses/index'; export * from './Requests/index'; +export * from './Responses/index'; export * from './SendMessageParams'; -export * from './Viber/index'; -export * from './WhatsApp/index'; +export * from './MessageSuccess'; diff --git a/packages/messages/package.json b/packages/messages/package.json index 7383fc0c..aee0a840 100644 --- a/packages/messages/package.json +++ b/packages/messages/package.json @@ -1,4 +1,5 @@ { + "$schema": "https://json.schemastore.org/package.json", "name": "@vonage/messages", "version": "1.10.0", "description": "Multi-channel messaging that integrates WhatsApp, Facebook, Viber, SMS, and MMS", @@ -20,7 +21,16 @@ "url": "git+https://github.com/Vonage/vonage-node-sdk.git" }, "license": "Apache-2.0", - "author": "Chris Tankersley ", + "contributors": [ + { + "name": "Chris Tankersley", + "url": "https://github.com/dragonmantank" + }, + { + "name": "Chuck \"MANCHUCK\" Reeves", + "url": "https://github.com/manchuck" + } + ], "main": "dist/index.js", "types": "dist/index.d.ts", "directories": { @@ -33,7 +43,8 @@ "scripts": { "build": "npm run clean && npm run compile", "clean": "npx shx rm -rf dist tsconfig.tsbuildinfo", - "compile": "npx tsc --build --verbose" + "compile": "npx tsc --build --verbose", + "prepublishOnly": "npm run build" }, "dependencies": { "@vonage/auth": "^1.7.0", diff --git a/packages/messages/tsconfig.json b/packages/messages/tsconfig.json index e9b438f7..8e8615aa 100644 --- a/packages/messages/tsconfig.json +++ b/packages/messages/tsconfig.json @@ -1,24 +1,25 @@ { - "extends": "../../tsconfig.json", + "$schema": "https://json.schemastore.org/tsconfig", - "compilerOptions": { - "rootDir": "lib", - "outDir": "dist" - }, + "extends": "../../tsconfig.json", - "exclude": [ - "__tests__", - "jest.config.js", - "dist" - ], + "compilerOptions": { + "rootDir": "lib", + "outDir": "dist" + }, - "references": [ - { "path": "../auth" }, - { "path": "../server-client" }, - { "path": "../vetch" } - ], + "exclude": [ + "__tests__", + "dist" + ], - "ts-node": { - "esm": true - } + "references": [ + { "path": "../auth" }, + { "path": "../server-client" }, + { "path": "../vetch" } + ], + + "ts-node": { + "esm": true + } } diff --git a/packages/messages/typedoc.json b/packages/messages/typedoc.json new file mode 100644 index 00000000..5587b93d --- /dev/null +++ b/packages/messages/typedoc.json @@ -0,0 +1,18 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "extends": ["../../typedoc.base.json"], + "entryPoints": ["lib/index.ts"], + "name": "Vonage Messages", + "groupOrder": [ + "Client", + "MMS", + "Messenger", + "SMS", + "Viber", + "WhatsApp", + "Types", + "Responses", + "*" + ], + "defaultCategory": "" +} diff --git a/packages/number-insight-v2/lib/enums/insight.ts b/packages/number-insight-v2/lib/enums/insight.ts index 720cd5b9..59547d02 100644 --- a/packages/number-insight-v2/lib/enums/insight.ts +++ b/packages/number-insight-v2/lib/enums/insight.ts @@ -1,4 +1,14 @@ +/** + * Enum representing the types of insights available for phone number checks. + */ export enum Insight { + /** + * Use this insight to check the fraud score associated with a phone number. + */ FRAUD_SCORE = 'fraud_score', + + /** + * Use this insight to check if a SIM swap has occurred for a phone number in the last 7 days. + */ SIM_SWAP = 'sim_swap', } diff --git a/packages/number-insight-v2/lib/enums/label.ts b/packages/number-insight-v2/lib/enums/label.ts index 5f244e15..ec0299f1 100644 --- a/packages/number-insight-v2/lib/enums/label.ts +++ b/packages/number-insight-v2/lib/enums/label.ts @@ -1,5 +1,19 @@ +/** + * Enum representing the labels for risk scores. + */ export enum Label { + /** + * Represents a low risk score. + */ LOW = 'low', + + /** + * Represents a medium risk score. + */ MEDIUM = 'medium', + + /** + * Represents a high risk score. + */ HIGH = 'high', } diff --git a/packages/number-insight-v2/lib/enums/riskRecommendation.ts b/packages/number-insight-v2/lib/enums/riskRecommendation.ts index 94edf1a1..891fd3a9 100644 --- a/packages/number-insight-v2/lib/enums/riskRecommendation.ts +++ b/packages/number-insight-v2/lib/enums/riskRecommendation.ts @@ -1,5 +1,19 @@ +/** + * Enum representing the recommendations based on risk scores. + */ export enum RiskRecommendation { + /** + * Indicates that it is recommended to allow the action based on the risk score. + */ ALLOW = 'allow', + + /** + * Indicates that it is recommended to flag the action based on the risk score. + */ FLAG = 'flag', + + /** + * Indicates that it is recommended to block the action based on the risk score. + */ BLOCK = 'block', } diff --git a/packages/number-insight-v2/lib/enums/status.ts b/packages/number-insight-v2/lib/enums/status.ts index 21aaed1e..774809d4 100644 --- a/packages/number-insight-v2/lib/enums/status.ts +++ b/packages/number-insight-v2/lib/enums/status.ts @@ -1,4 +1,14 @@ +/** + * Enum representing the possible status values for an operation. + */ export enum Status { + /** + * Indicates that the operation has been completed successfully. + */ COMPLETED = 'completed', + + /** + * Indicates that the operation has failed. + */ FAILED = 'failed', } diff --git a/packages/number-insight-v2/lib/numberInsightV2.ts b/packages/number-insight-v2/lib/numberInsightV2.ts index d707b77e..93f96240 100644 --- a/packages/number-insight-v2/lib/numberInsightV2.ts +++ b/packages/number-insight-v2/lib/numberInsightV2.ts @@ -1,15 +1,71 @@ import { Client, AuthenticationType } from '@vonage/server-client'; -import { FraudCheckParameters, FraudScore, FraudScoreResponse } from './types'; +import { FraudCheck, FraudCheckParameters, FraudScoreResponse } from './types'; +/** + * Number Insight v2 is designed to give fraud scores for Application Integrations. + * This class represents the client for making fraud check requests. + */ export class NumberInsightV2 extends Client { protected authType = AuthenticationType.JWT; - async checkForFraud(params: FraudCheckParameters): Promise { + /** + * Make a fraud check request with the provided parameters. + * + * @param {FraudCheckParameters} params - The parameters for the fraud check request. + * @return {Promise} - A Promise that resolves with the fraud score response. + * @example + * Check for fraud on a phone number. + * ```ts + * import { Insight } from '@vonage/number-insight-v2'; + * const score = await client.numberInsightV2.checkForFraud({ + * type: 'phone', + * number: '447700900000', + * insights: [ + * Insight.FRAUD_SCORE, + * ], + * }); + * console.log(`Fraud score: ${score.riskScore}`); + * ``` + * + * @example + * Check for SIM swap on a phone number. + * ```ts + * import { Insight } from '@vonage/number-insight-v2'; + * const score = await client.numberInsightV2.checkForFraud({ + * type: 'phone', + * number: '447700900000', + * insights: [ + * Insight.SIM_SWAP, + * ], + * }); + * console.log(`SIM swap detected: ${score.simSwap ? 'Yes' : 'No'}`); + * ``` + * + * @example + * Check both fraud score and SIM swap on a phone number. + * ```ts + * import { Insight } from '@vonage/number-insight-v2'; + * const score = await client.numberInsightV2.checkForFraud({ + * type: 'phone', + * number: '447700900000', + * insights: [ + * Insight.SIM_SWAP, + * Insight.FRAUD_SCORE, + * ], + * }); + * console.log(`SIM swap detected: ${score.simSwap ? 'Yes' : 'No'}`); + * console.log(`Fraud score: ${score.riskScore}`); + * ``` + */ + async checkForFraud(params: FraudCheckParameters): Promise { const resp = await this.sendPostRequest( `${this.config.apiHost}/v2/ni`, params, ); - return Client.transformers.camelCaseObjectKeys(resp?.data, true); + return Client.transformers.camelCaseObjectKeys( + resp?.data, + true, + ) as FraudCheck; } } diff --git a/packages/number-insight-v2/lib/types/fraudCheck.ts b/packages/number-insight-v2/lib/types/fraudCheck.ts index f2bdd445..f0ea569f 100644 --- a/packages/number-insight-v2/lib/types/fraudCheck.ts +++ b/packages/number-insight-v2/lib/types/fraudCheck.ts @@ -2,10 +2,32 @@ import { PhoneInfo } from './phoneInfo'; import { FraudScore } from './fraudScore'; import { SimSwap } from './simSwap'; +/** + * Represents the result of a fraud check request. + */ export type FraudCheck = { + /** + * Unique UUID for this request for reference. + */ requestId: string; + + /** + * The type of lookup used in the request. Currently always 'phone'. + */ type: 'phone'; + + /** + * An object containing information about the phone number used in the fraud check operation(s). + */ phone: PhoneInfo; + + /** + * The result of the 'fraud_score' insight operation (optional). + */ fraudScore?: FraudScore; + + /** + * The result of the 'sim_swap' insight operation (optional). + */ simSwap?: SimSwap; }; diff --git a/packages/number-insight-v2/lib/types/fraudScore.ts b/packages/number-insight-v2/lib/types/fraudScore.ts index 7baffa6a..32e67144 100644 --- a/packages/number-insight-v2/lib/types/fraudScore.ts +++ b/packages/number-insight-v2/lib/types/fraudScore.ts @@ -1,8 +1,29 @@ import { RiskRecommendation, Label, Status } from '../enums'; +/** + * Represents the result of the fraud_score insight operation. + */ export type FraudScore = { + /** + * Score derived from evaluating fraud-related data associated with the phone number. + */ riskScore: string; + + /** + * Recommended action based on the riskScore. + * Must be one of the values from the 'RiskRecommendation' enum. + */ riskRecommendation: RiskRecommendation; + + /** + * Mapping of risk score to a verbose description. + * Must be one of the values from the 'Label' enum. + */ label: Label; + + /** + * The status of the fraud_score call. + * Must be one of the values from the 'Status' enum. + */ status: Status; }; diff --git a/packages/number-insight-v2/lib/types/parameters/fraudParameters.ts b/packages/number-insight-v2/lib/types/parameters/fraudParameters.ts index b0df2eba..632a485e 100644 --- a/packages/number-insight-v2/lib/types/parameters/fraudParameters.ts +++ b/packages/number-insight-v2/lib/types/parameters/fraudParameters.ts @@ -1,7 +1,22 @@ import { Insight } from '../../enums/'; +/** + * Represents the parameters for making a fraud check request. + */ export type FraudCheckParameters = { + /** + * The type of lookup used in the request. Currently always 'phone'. + */ type: 'phone'; + + /** + * A single phone number that you need insight about in the E.164 format. + * Don't use a leading + or 00 when entering a phone number, start with the country code, e.g., 447700900000. + */ phone: string; + + /** + * The insight(s) you need, at least one of: 'fraud_score' and 'sim_swap'. + */ insights: Insight[]; }; diff --git a/packages/number-insight-v2/lib/types/phoneInfo.ts b/packages/number-insight-v2/lib/types/phoneInfo.ts index 9b1da2b9..71eb63c8 100644 --- a/packages/number-insight-v2/lib/types/phoneInfo.ts +++ b/packages/number-insight-v2/lib/types/phoneInfo.ts @@ -1,5 +1,21 @@ +/** + * Represents information about a phone number. + */ export type PhoneInfo = { + /** + * The phone number. + */ phone: string; + + /** + * The name of the network carrier (optional). + * Included if insights included 'fraud_score'. + */ carrier?: string; + + /** + * Type of phone (optional). Examples include Mobile, Landline, VOIP, PrePaid, Personal, Toll-Free. + * Included if insights included 'fraud_score'. + */ type?: string; }; diff --git a/packages/number-insight-v2/lib/types/requests/fraudCheckRequest.ts b/packages/number-insight-v2/lib/types/requests/fraudCheckRequest.ts index 39c1fb3d..de674cf2 100644 --- a/packages/number-insight-v2/lib/types/requests/fraudCheckRequest.ts +++ b/packages/number-insight-v2/lib/types/requests/fraudCheckRequest.ts @@ -1,7 +1,26 @@ import { Insight } from '../../enums'; +/** + * Represents a fraud check request. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type FraudCheckRequest = { + /** + * The type of lookup used in the request. Currently always 'phone'. + */ type: 'phone'; + + /** + * A single phone number that you need insight about in the E.164 format. + * Don't use a leading + or 00 when entering a phone number, start with the country code, e.g., 447700900000. + */ phone: string; + + /** + * The insight(s) you need, at least one of: 'fraud_score' and 'sim_swap'. + */ insights: Insight[]; }; diff --git a/packages/number-insight-v2/lib/types/responses/fraudCheckResponse.ts b/packages/number-insight-v2/lib/types/responses/fraudCheckResponse.ts index 46f0810e..ce59ceaa 100644 --- a/packages/number-insight-v2/lib/types/responses/fraudCheckResponse.ts +++ b/packages/number-insight-v2/lib/types/responses/fraudCheckResponse.ts @@ -2,8 +2,26 @@ import { FraudCheck } from '../fraudCheck'; import { FraudScoreResponse } from './fraudScoreResponse'; import { SimSwap } from '../simSwap'; +/** + * Represents the response from a fraud check request. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type FraudCheckResponse = { + /** + * Unique UUID for this request for reference. + */ request_id: string; + + /** + * The response data for the 'fraud_score' insight operation. + */ fraud_score: FraudScoreResponse; + + /** + * The response data for the 'sim_swap' insight operation. + */ sim_swap: SimSwap; } & Omit; diff --git a/packages/number-insight-v2/lib/types/responses/fraudScoreResponse.ts b/packages/number-insight-v2/lib/types/responses/fraudScoreResponse.ts index 7756e5a1..a1fbfe87 100644 --- a/packages/number-insight-v2/lib/types/responses/fraudScoreResponse.ts +++ b/packages/number-insight-v2/lib/types/responses/fraudScoreResponse.ts @@ -1,7 +1,22 @@ import { RiskRecommendation } from '../../enums'; import { FraudScore } from '../fraudScore'; +/** + * Represents the response data for the 'fraud_score' insight operation. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type FraudScoreResponse = { + /** + * Score derived from evaluating fraud-related data associated with the phone number. + */ risk_score: string; + + /** + * Recommended action based on the risk_score. + * Must be one of the values from the 'RiskRecommendation' enum. + */ risk_recommendation: RiskRecommendation; } & Omit; diff --git a/packages/number-insight-v2/lib/types/simSwap.ts b/packages/number-insight-v2/lib/types/simSwap.ts index 163eeb3d..abfda7d9 100644 --- a/packages/number-insight-v2/lib/types/simSwap.ts +++ b/packages/number-insight-v2/lib/types/simSwap.ts @@ -1,7 +1,22 @@ import { Status } from '../enums/'; +/** + * Represents the result of the sim_swap insight operation. + */ export type SimSwap = { + /** + * The status of the sim_swap call. Must be one of the values from the 'Status' enum. + */ status: Status; + + /** + * true if the sim was swapped in the last 7 days, false otherwise. + * Returned only if the sim swap check succeeds. + */ swapped?: boolean; + + /** + * The reason for a sim swap error response. Returned only if the sim swap check fails. + */ reason?: string; }; diff --git a/packages/number-insight-v2/package.json b/packages/number-insight-v2/package.json index 6cedca2e..970eb748 100644 --- a/packages/number-insight-v2/package.json +++ b/packages/number-insight-v2/package.json @@ -1,4 +1,5 @@ { + "$schema": "https://json.schemastore.org/package.json", "name": "@vonage/number-insight-v2", "version": "1.1.0", "description": "Number Insight v2 is designed to give fraud scores for Application Integrations.", @@ -11,7 +12,16 @@ "url": "git+https://github.com/Vonage/vonage-node-sdk.git" }, "license": "Apache-2.0", - "author": "Chuck MANCHUCK Reeves ", + "contributors": [ + { + "name": "Chuck \"MANCHUCK\" Reeves", + "url": "https://github.com/manchuck" + }, + { + "name": "Chris Tankersley", + "url": "https://github.com/dragonmantank" + } + ], "main": "dist/index.js", "types": "dist/index.d.ts", "directories": { @@ -24,7 +34,8 @@ "scripts": { "build": "npm run clean && npm run compile", "clean": "npx shx rm -rf dist tsconfig.tsbuildinfo", - "compile": "npx tsc --build --verbose" + "compile": "npx tsc --build --verbose", + "prepublishOnly": "npm run build" }, "dependencies": { "@vonage/server-client": "^1.9.0" diff --git a/packages/number-insight-v2/tsconfig.json b/packages/number-insight-v2/tsconfig.json index b8ed59b9..cd40b0e3 100644 --- a/packages/number-insight-v2/tsconfig.json +++ b/packages/number-insight-v2/tsconfig.json @@ -1,19 +1,24 @@ { - "extends": "../../tsconfig.json", + "$schema": "https://json.schemastore.org/tsconfig", - "compilerOptions": { - "rootDir": "lib", - "outDir": "dist" - }, + "extends": "../../tsconfig.json", - "exclude": ["__tests__", "jest.config.js", "dist"], + "compilerOptions": { + "rootDir": "lib", + "outDir": "dist" + }, - "references": [ - { "path": "../server-client" }, - { "path": "../auth" } - ], + "exclude": [ + "__tests__", + "dist" + ], - "ts-node": { - "esm": true - } + "references": [ + { "path": "../server-client" }, + { "path": "../auth" } + ], + + "ts-node": { + "esm": true + } } diff --git a/packages/number-insight-v2/typedoc.json b/packages/number-insight-v2/typedoc.json new file mode 100644 index 00000000..05f37c02 --- /dev/null +++ b/packages/number-insight-v2/typedoc.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "extends": ["../../typedoc.base.json"], + "entryPoints": ["lib/index.ts"], + "name": "Vonage Number Insights V2" +} diff --git a/packages/number-insights/__tests__/number-insights.test.ts b/packages/number-insights/__tests__/number-insights.test.ts index 51284f13..8f322ace 100644 --- a/packages/number-insights/__tests__/number-insights.test.ts +++ b/packages/number-insights/__tests__/number-insights.test.ts @@ -1,273 +1,269 @@ -import { Auth } from '@vonage/auth' -import nock from 'nock' -import { NumberInsights } from '../lib/index' +import { Auth } from '@vonage/auth'; +import nock from 'nock'; +import { NumberInsights } from '../lib/index'; -const BASE_URL = 'https://api.nexmo.com' +const BASE_URL = 'https://api.nexmo.com'; describe('number-insights', () => { - let client + let client; - beforeEach(() => { - client = new NumberInsights( - new Auth({ apiKey: 'abcd', apiSecret: '1234' }) - ) - }) + beforeEach(() => { + client = new NumberInsights( + new Auth({ apiKey: 'abcd', apiSecret: '1234' }) + ); + }); - afterEach(() => { - client = null - }) + afterEach(() => { + client = null; + }); - test('do a basic lookup', async () => { - const expectedResponse = { - status: 0, - status_message: 'Success', - request_id: 'aaaaaaaa-bbbb-cccc-dddd-0123456789ab', - international_format_number: '447700900000', - national_format_number: '07700 900000', - country_code: 'GB', - country_code_iso3: 'GBR', - country_name: 'United Kingdom', - country_prefix: '44', - } + test('do a basic lookup', async () => { + const expectedResponse = { + status: 0, + status_message: 'Success', + request_id: 'aaaaaaaa-bbbb-cccc-dddd-0123456789ab', + international_format_number: '447700900000', + national_format_number: '07700 900000', + country_code: 'GB', + country_code_iso3: 'GBR', + country_name: 'United Kingdom', + country_prefix: '44', + }; - nock(BASE_URL) - .persist() - .get('/ni/basic/json') - .query({ - api_key: 'abcd', - api_secret: '1234', - number: expectedResponse.international_format_number, - }) - .reply(200, expectedResponse) + nock(BASE_URL) + .persist() + .get('/ni/basic/json') + .query({ + api_key: 'abcd', + api_secret: '1234', + number: expectedResponse.international_format_number, + }) + .reply(200, expectedResponse); - const lookup = await client.basicLookup('447700900000') - expect(lookup.status).toEqual(expectedResponse.status) - expect(lookup.status_message).toEqual(expectedResponse.status_message) - expect(lookup.request_id).toEqual(expectedResponse.request_id) - expect(lookup.international_format_number).toEqual( - expectedResponse.international_format_number - ) - expect(lookup.national_format_number).toEqual( - expectedResponse.national_format_number - ) - expect(lookup.country_code).toEqual(expectedResponse.country_code) - expect(lookup.country_code_iso3).toEqual( - expectedResponse.country_code_iso3 - ) - expect(lookup.country_name).toEqual(expectedResponse.country_name) - expect(lookup.country_prefix).toEqual(expectedResponse.country_prefix) - }) + const lookup = await client.basicLookup('447700900000'); + expect(lookup.status).toEqual(expectedResponse.status); + expect(lookup.status_message).toEqual(expectedResponse.status_message); + expect(lookup.request_id).toEqual(expectedResponse.request_id); + expect(lookup.international_format_number).toEqual( + expectedResponse.international_format_number + ); + expect(lookup.national_format_number).toEqual( + expectedResponse.national_format_number + ); + expect(lookup.country_code).toEqual(expectedResponse.country_code); + expect(lookup.country_code_iso3).toEqual( + expectedResponse.country_code_iso3 + ); + expect(lookup.country_name).toEqual(expectedResponse.country_name); + expect(lookup.country_prefix).toEqual(expectedResponse.country_prefix); + }); - test('do a standard lookup', async () => { - const expectedResponse = { - status: 0, - status_message: 'Success', - request_id: 'aaaaaaaa-bbbb-cccc-dddd-0123456789ab', - international_format_number: '447700900000', - national_format_number: '07700 900000', - country_code: 'GB', - country_code_iso3: 'GBR', - country_name: 'United Kingdom', - country_prefix: '44', - request_price: '0.04000000', - refund_price: '0.01500000', - remaining_balance: '1.23456789', - current_carrier: { - network_code: '12345', - name: 'Acme Inc', - country: 'GB', - network_type: 'mobile', - }, - original_carrier: { - network_code: '12345', - name: 'Acme Inc', - country: 'GB', - network_type: 'mobile', - }, - ported: 'not_ported', - caller_identity: { - caller_type: 'consumer', - caller_name: 'John Smith', - first_name: 'John', - last_name: 'Smith', - }, - caller_name: 'John Smith', - last_name: 'Smith', - first_name: 'John', - caller_type: 'consumer', - } + test('do a standard lookup', async () => { + const expectedResponse = { + status: 0, + status_message: 'Success', + request_id: 'aaaaaaaa-bbbb-cccc-dddd-0123456789ab', + international_format_number: '447700900000', + national_format_number: '07700 900000', + country_code: 'GB', + country_code_iso3: 'GBR', + country_name: 'United Kingdom', + country_prefix: '44', + request_price: '0.04000000', + refund_price: '0.01500000', + remaining_balance: '1.23456789', + current_carrier: { + network_code: '12345', + name: 'Acme Inc', + country: 'GB', + network_type: 'mobile', + }, + original_carrier: { + network_code: '12345', + name: 'Acme Inc', + country: 'GB', + network_type: 'mobile', + }, + ported: 'not_ported', + caller_identity: { + caller_type: 'consumer', + caller_name: 'John Smith', + first_name: 'John', + last_name: 'Smith', + }, + caller_name: 'John Smith', + last_name: 'Smith', + first_name: 'John', + caller_type: 'consumer', + }; - nock(BASE_URL) - .persist() - .get('/ni/standard/json') - .query({ - api_key: 'abcd', - api_secret: '1234', - number: expectedResponse.international_format_number, - }) - .reply(200, expectedResponse) + nock(BASE_URL) + .persist() + .get('/ni/standard/json') + .query({ + api_key: 'abcd', + api_secret: '1234', + number: expectedResponse.international_format_number, + }) + .reply(200, expectedResponse); - const lookup = await client.standardLookup('447700900000') - expect(lookup.status).toEqual(expectedResponse.status) - expect(lookup.status_message).toEqual(expectedResponse.status_message) - expect(lookup.request_id).toEqual(expectedResponse.request_id) - expect(lookup.international_format_number).toEqual( - expectedResponse.international_format_number - ) - expect(lookup.national_format_number).toEqual( - expectedResponse.national_format_number - ) - expect(lookup.country_code).toEqual(expectedResponse.country_code) - expect(lookup.country_code_iso3).toEqual( - expectedResponse.country_code_iso3 - ) - expect(lookup.country_name).toEqual(expectedResponse.country_name) - expect(lookup.country_prefix).toEqual(expectedResponse.country_prefix) - expect(lookup.request_price).toEqual(expectedResponse.request_price) - expect(lookup.refund_price).toEqual(expectedResponse.refund_price) - expect(lookup.remaining_balance).toEqual( - expectedResponse.remaining_balance - ) - expect(lookup.current_carrier).toEqual(expectedResponse.current_carrier) - expect(lookup.original_carrier).toEqual( - expectedResponse.original_carrier - ) - expect(lookup.ported).toEqual(expectedResponse.ported) - expect(lookup.caller_identity).toEqual(expectedResponse.caller_identity) - expect(lookup.caller_name).toEqual(expectedResponse.caller_name) - expect(lookup.last_name).toEqual(expectedResponse.last_name) - expect(lookup.first_name).toEqual(expectedResponse.first_name) - expect(lookup.caller_type).toEqual(expectedResponse.caller_type) - }) + const lookup = await client.standardLookup('447700900000'); + expect(lookup.status).toEqual(expectedResponse.status); + expect(lookup.status_message).toEqual(expectedResponse.status_message); + expect(lookup.request_id).toEqual(expectedResponse.request_id); + expect(lookup.international_format_number).toEqual( + expectedResponse.international_format_number + ); + expect(lookup.national_format_number).toEqual( + expectedResponse.national_format_number + ); + expect(lookup.country_code).toEqual(expectedResponse.country_code); + expect(lookup.country_code_iso3).toEqual( + expectedResponse.country_code_iso3 + ); + expect(lookup.country_name).toEqual(expectedResponse.country_name); + expect(lookup.country_prefix).toEqual(expectedResponse.country_prefix); + expect(lookup.request_price).toEqual(expectedResponse.request_price); + expect(lookup.refund_price).toEqual(expectedResponse.refund_price); + expect(lookup.remaining_balance).toEqual( + expectedResponse.remaining_balance + ); + expect(lookup.current_carrier).toEqual(expectedResponse.current_carrier); + expect(lookup.original_carrier).toEqual(expectedResponse.original_carrier); + expect(lookup.ported).toEqual(expectedResponse.ported); + expect(lookup.caller_identity).toEqual(expectedResponse.caller_identity); + expect(lookup.caller_name).toEqual(expectedResponse.caller_name); + expect(lookup.last_name).toEqual(expectedResponse.last_name); + expect(lookup.first_name).toEqual(expectedResponse.first_name); + expect(lookup.caller_type).toEqual(expectedResponse.caller_type); + }); - test('do an advanced lookup', async () => { - const expectedResponse = { - status: 0, - status_message: 'Success', - request_id: 'aaaaaaaa-bbbb-cccc-dddd-0123456789ab', - international_format_number: '447700900000', - national_format_number: '07700 900000', - country_code: 'GB', - country_code_iso3: 'GBR', - country_name: 'United Kingdom', - country_prefix: '44', - request_price: '0.04000000', - refund_price: '0.01500000', - remaining_balance: '1.23456789', - current_carrier: { - network_code: '12345', - name: 'Acme Inc', - country: 'GB', - network_type: 'mobile', - }, - original_carrier: { - network_code: '12345', - name: 'Acme Inc', - country: 'GB', - network_type: 'mobile', - }, - ported: 'not_ported', - roaming: { - status: 'roaming', - roaming_country_code: 'US', - roaming_network_code: '12345', - roaming_network_name: 'Acme Inc', - }, - caller_identity: { - caller_type: 'consumer', - caller_name: 'John Smith', - first_name: 'John', - last_name: 'Smith', - }, - lookup_outcome: 0, - lookup_outcome_message: 'Success', - valid_number: 'valid', - reachable: 'reachable', - real_time_data: { - active_status: 'true', - handset_status: 'On', - }, - } + test('do an advanced lookup', async () => { + const expectedResponse = { + status: 0, + status_message: 'Success', + request_id: 'aaaaaaaa-bbbb-cccc-dddd-0123456789ab', + international_format_number: '447700900000', + national_format_number: '07700 900000', + country_code: 'GB', + country_code_iso3: 'GBR', + country_name: 'United Kingdom', + country_prefix: '44', + request_price: '0.04000000', + refund_price: '0.01500000', + remaining_balance: '1.23456789', + current_carrier: { + network_code: '12345', + name: 'Acme Inc', + country: 'GB', + network_type: 'mobile', + }, + original_carrier: { + network_code: '12345', + name: 'Acme Inc', + country: 'GB', + network_type: 'mobile', + }, + ported: 'not_ported', + roaming: { + status: 'roaming', + roaming_country_code: 'US', + roaming_network_code: '12345', + roaming_network_name: 'Acme Inc', + }, + caller_identity: { + caller_type: 'consumer', + caller_name: 'John Smith', + first_name: 'John', + last_name: 'Smith', + }, + lookup_outcome: 0, + lookup_outcome_message: 'Success', + valid_number: 'valid', + reachable: 'reachable', + real_time_data: { + active_status: 'true', + handset_status: 'On', + }, + }; - nock(BASE_URL) - .persist() - .get('/ni/advanced/json') - .query({ - api_key: 'abcd', - api_secret: '1234', - number: expectedResponse.international_format_number, - }) - .reply(200, expectedResponse) + nock(BASE_URL) + .persist() + .get('/ni/advanced/json') + .query({ + api_key: 'abcd', + api_secret: '1234', + number: expectedResponse.international_format_number, + }) + .reply(200, expectedResponse); - const lookup = await client.advancedLookup('447700900000') - expect(lookup.status).toEqual(expectedResponse.status) - expect(lookup.status_message).toEqual(expectedResponse.status_message) - expect(lookup.request_id).toEqual(expectedResponse.request_id) - expect(lookup.international_format_number).toEqual( - expectedResponse.international_format_number - ) - expect(lookup.national_format_number).toEqual( - expectedResponse.national_format_number - ) - expect(lookup.country_code).toEqual(expectedResponse.country_code) - expect(lookup.country_code_iso3).toEqual( - expectedResponse.country_code_iso3 - ) - expect(lookup.country_name).toEqual(expectedResponse.country_name) - expect(lookup.country_prefix).toEqual(expectedResponse.country_prefix) - expect(lookup.request_price).toEqual(expectedResponse.request_price) - expect(lookup.refund_price).toEqual(expectedResponse.refund_price) - expect(lookup.remaining_balance).toEqual( - expectedResponse.remaining_balance - ) - expect(lookup.current_carrier).toEqual(expectedResponse.current_carrier) - expect(lookup.original_carrier).toEqual( - expectedResponse.original_carrier - ) - expect(lookup.ported).toEqual(expectedResponse.ported) - expect(lookup.caller_identity).toEqual(expectedResponse.caller_identity) - expect(lookup.roaming).toEqual(expectedResponse.roaming) - expect(lookup.lookup_outcome).toEqual(expectedResponse.lookup_outcome) - expect(lookup.lookup_outcome_message).toEqual( - expectedResponse.lookup_outcome_message - ) - expect(lookup.valid_number).toEqual(expectedResponse.valid_number) - expect(lookup.reachable).toEqual(expectedResponse.reachable) - expect(lookup.real_time_data).toEqual(expectedResponse.real_time_data) - }) + const lookup = await client.advancedLookup('447700900000'); + expect(lookup.status).toEqual(expectedResponse.status); + expect(lookup.status_message).toEqual(expectedResponse.status_message); + expect(lookup.request_id).toEqual(expectedResponse.request_id); + expect(lookup.international_format_number).toEqual( + expectedResponse.international_format_number + ); + expect(lookup.national_format_number).toEqual( + expectedResponse.national_format_number + ); + expect(lookup.country_code).toEqual(expectedResponse.country_code); + expect(lookup.country_code_iso3).toEqual( + expectedResponse.country_code_iso3 + ); + expect(lookup.country_name).toEqual(expectedResponse.country_name); + expect(lookup.country_prefix).toEqual(expectedResponse.country_prefix); + expect(lookup.request_price).toEqual(expectedResponse.request_price); + expect(lookup.refund_price).toEqual(expectedResponse.refund_price); + expect(lookup.remaining_balance).toEqual( + expectedResponse.remaining_balance + ); + expect(lookup.current_carrier).toEqual(expectedResponse.current_carrier); + expect(lookup.original_carrier).toEqual(expectedResponse.original_carrier); + expect(lookup.ported).toEqual(expectedResponse.ported); + expect(lookup.caller_identity).toEqual(expectedResponse.caller_identity); + expect(lookup.roaming).toEqual(expectedResponse.roaming); + expect(lookup.lookup_outcome).toEqual(expectedResponse.lookup_outcome); + expect(lookup.lookup_outcome_message).toEqual( + expectedResponse.lookup_outcome_message + ); + expect(lookup.valid_number).toEqual(expectedResponse.valid_number); + expect(lookup.reachable).toEqual(expectedResponse.reachable); + expect(lookup.real_time_data).toEqual(expectedResponse.real_time_data); + }); - test('do an async advanced lookup', async () => { - const expectedResponse = { - request_id: 'aaaaaaaa-bbbb-cccc-dddd-0123456789ab', - number: '447700900000', - remaining_balance: '1.23456789', - request_price: '0.01500000', - status: 0, - error_text: 'Success', - } + test('do an async advanced lookup', async () => { + const expectedResponse = { + request_id: 'aaaaaaaa-bbbb-cccc-dddd-0123456789ab', + number: '447700900000', + remaining_balance: '1.23456789', + request_price: '0.01500000', + status: 0, + error_text: 'Success', + }; - nock(BASE_URL) - .persist() - .get('/ni/advanced/async/json') - .query({ - api_key: 'abcd', - api_secret: '1234', - number: expectedResponse.number, - callback: 'https://test.com/lookup/handler', - }) - .reply(200, expectedResponse) + nock(BASE_URL) + .persist() + .get('/ni/advanced/async/json') + .query({ + api_key: 'abcd', + api_secret: '1234', + number: expectedResponse.number, + callback: 'https://test.com/lookup/handler', + }) + .reply(200, expectedResponse); - const lookup = await client.asyncAdvancedLookup( - '447700900000', - 'https://test.com/lookup/handler' - ) - expect(lookup.status).toEqual(expectedResponse.status) - expect(lookup.request_id).toEqual(expectedResponse.request_id) - expect(lookup.number).toEqual(expectedResponse.number) - expect(lookup.remaining_balance).toEqual( - expectedResponse.remaining_balance - ) - expect(lookup.request_price).toEqual(expectedResponse.request_price) - expect(lookup.error_text).toEqual(expectedResponse.error_text) - }) -}) + const lookup = await client.asyncAdvancedLookup( + '447700900000', + 'https://test.com/lookup/handler' + ); + expect(lookup.status).toEqual(expectedResponse.status); + expect(lookup.request_id).toEqual(expectedResponse.request_id); + expect(lookup.number).toEqual(expectedResponse.number); + expect(lookup.remaining_balance).toEqual( + expectedResponse.remaining_balance + ); + expect(lookup.request_price).toEqual(expectedResponse.request_price); + expect(lookup.error_text).toEqual(expectedResponse.error_text); + }); +}); diff --git a/packages/number-insights/lib/enums/CallerType.ts b/packages/number-insights/lib/enums/CallerType.ts index aa18e3c1..79b8d852 100644 --- a/packages/number-insights/lib/enums/CallerType.ts +++ b/packages/number-insights/lib/enums/CallerType.ts @@ -1,5 +1,19 @@ +/** + * Enum representing the type of caller for a phone number. + */ export enum CallerType { - UNKNOWN = 'unknown', - BUSINESS = 'business', - CONSUMER = 'consumer,', + /** + * The value will be "unknown" if the information about the caller type is not available. + */ + UNKNOWN = 'unknown', + + /** + * The value will be "business" if the owner of a phone number is a business. + */ + BUSINESS = 'business', + + /** + * The value will be "consumer" if the owner of a phone number is an individual. + */ + CONSUMER = 'consumer', } diff --git a/packages/number-insights/lib/enums/LookupOutcome.ts b/packages/number-insights/lib/enums/LookupOutcome.ts index 54651c8b..e95b0952 100644 --- a/packages/number-insights/lib/enums/LookupOutcome.ts +++ b/packages/number-insights/lib/enums/LookupOutcome.ts @@ -1,5 +1,19 @@ +/** + * Enum representing the outcomes of a lookup operation. + */ export enum LookupOutcome { - SUCCESS = 0, - PARTIAL_SUCCESS = 1, - FAILED = 2, + /** + * The lookup operation was successful. + */ + SUCCESS = 0, + + /** + * The lookup operation partially succeeded. + */ + PARTIAL_SUCCESS = 1, + + /** + * The lookup operation failed. + */ + FAILED = 2, } diff --git a/packages/number-insights/lib/enums/NetworkType.ts b/packages/number-insights/lib/enums/NetworkType.ts index 360a7186..969a3a2b 100644 --- a/packages/number-insights/lib/enums/NetworkType.ts +++ b/packages/number-insights/lib/enums/NetworkType.ts @@ -1,9 +1,39 @@ +/** + * Enum representing the type of network associated with a phone number. + */ export enum NetworkType { - MOBILE = 'mobile', - LANDLINE = 'landline', - LANDLINE_PREMIUM = 'landline_premium', - LANDLINE_TOLLFREE = 'landline_tollfree', - VIRTUAL = 'virtual', - UNKNOWN = 'unknown', - PAGER = 'pager', + /** + * The phone number is associated with a mobile network. + */ + MOBILE = 'mobile', + + /** + * The phone number is associated with a landline network. + */ + LANDLINE = 'landline', + + /** + * The phone number is associated with a premium landline network. + */ + LANDLINE_PREMIUM = 'landline_premium', + + /** + * The phone number is associated with a toll-free landline network. + */ + LANDLINE_TOLLFREE = 'landline_tollfree', + + /** + * The phone number is associated with a virtual network. + */ + VIRTUAL = 'virtual', + + /** + * The type of network associated with the phone number is unknown. + */ + UNKNOWN = 'unknown', + + /** + * The phone number is associated with a pager network. + */ + PAGER = 'pager', } diff --git a/packages/number-insights/lib/enums/Reachable.ts b/packages/number-insights/lib/enums/Reachable.ts index 70a0036e..7365d974 100644 --- a/packages/number-insights/lib/enums/Reachable.ts +++ b/packages/number-insights/lib/enums/Reachable.ts @@ -1,8 +1,34 @@ +/** + * Enum representing the reachability status of a phone number. + */ export enum Reachable { - UNKNOWN = 'unknown', - REACHABLE = 'reachable', - UNDELIVERABLE = 'undeliverable', - ABSENT = 'absent', - BAD_NUMBER = 'bad_number', - BLACKLISTED = 'blacklisted', + /** + * The reachability status is unknown. + */ + UNKNOWN = 'unknown', + + /** + * The phone number is reachable. + */ + REACHABLE = 'reachable', + + /** + * The phone number is undeliverable. + */ + UNDELIVERABLE = 'undeliverable', + + /** + * The phone number's owner is absent. + */ + ABSENT = 'absent', + + /** + * The phone number is invalid or a bad number. + */ + BAD_NUMBER = 'bad_number', + + /** + * The phone number is blacklisted. + */ + BLACKLISTED = 'blacklisted', } diff --git a/packages/number-insights/lib/enums/ValidNumber.ts b/packages/number-insights/lib/enums/ValidNumber.ts index 58ba06b5..67e08c6a 100644 --- a/packages/number-insights/lib/enums/ValidNumber.ts +++ b/packages/number-insights/lib/enums/ValidNumber.ts @@ -1,7 +1,29 @@ +/** + * Enum representing the validity status of a phone number. + */ export enum ValidNumber { - UNKNOWN = 'unknown', - VALID = 'valid', - NOT_VALID = 'not_valid', - INFERRED = 'inferred', - INFERRED_NOT_VALID = 'inferred_not_valid', + /** + * The validity status is unknown. + */ + UNKNOWN = 'unknown', + + /** + * The phone number is valid. + */ + VALID = 'valid', + + /** + * The phone number is not valid. + */ + NOT_VALID = 'not_valid', + + /** + * The validity of the phone number is inferred. + */ + INFERRED = 'inferred', + + /** + * The inferred validity of the phone number is not valid. + */ + INFERRED_NOT_VALID = 'inferred_not_valid', } diff --git a/packages/number-insights/lib/enums/index.ts b/packages/number-insights/lib/enums/index.ts new file mode 100644 index 00000000..1b096a74 --- /dev/null +++ b/packages/number-insights/lib/enums/index.ts @@ -0,0 +1,5 @@ +export * from './CallerType'; +export * from './LookupOutcome'; +export * from './NetworkType'; +export * from './Reachable'; +export * from './ValidNumber'; diff --git a/packages/number-insights/lib/index.ts b/packages/number-insights/lib/index.ts index dd5b3f6e..21870a43 100644 --- a/packages/number-insights/lib/index.ts +++ b/packages/number-insights/lib/index.ts @@ -1 +1,3 @@ -export { NumberInsights } from './number-insights' +export * from './number-insights'; +export * from './enums'; +export * from './types'; diff --git a/packages/number-insights/lib/interfaces/AdvancedLookupOptions.ts b/packages/number-insights/lib/interfaces/AdvancedLookupOptions.ts deleted file mode 100644 index 140b3da8..00000000 --- a/packages/number-insights/lib/interfaces/AdvancedLookupOptions.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { StandardLookupOptions } from './StandardLookupOptions' - -export interface AdvancedLookupOptions extends StandardLookupOptions { - real_time_data?: boolean -} diff --git a/packages/number-insights/lib/interfaces/AsyncAdvancedLookupOptions.ts b/packages/number-insights/lib/interfaces/AsyncAdvancedLookupOptions.ts deleted file mode 100644 index fbb59fa6..00000000 --- a/packages/number-insights/lib/interfaces/AsyncAdvancedLookupOptions.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { StandardLookupOptions } from './StandardLookupOptions' - -export interface AsyncAdvancedLookupOptions extends StandardLookupOptions { - callback: string -} diff --git a/packages/number-insights/lib/interfaces/BasicLookupOptions.ts b/packages/number-insights/lib/interfaces/BasicLookupOptions.ts deleted file mode 100644 index 435dcee8..00000000 --- a/packages/number-insights/lib/interfaces/BasicLookupOptions.ts +++ /dev/null @@ -1,3 +0,0 @@ -export interface BasicLookupOptions { - country?: string -} diff --git a/packages/number-insights/lib/interfaces/NumberInsightsResponse.ts b/packages/number-insights/lib/interfaces/NumberInsightsResponse.ts deleted file mode 100644 index 473791ef..00000000 --- a/packages/number-insights/lib/interfaces/NumberInsightsResponse.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { VetchResponse } from '@vonage/vetch' - -export interface NumberInsightsResponse extends VetchResponse {} diff --git a/packages/number-insights/lib/interfaces/Responses/AdvancedResponse.ts b/packages/number-insights/lib/interfaces/Responses/AdvancedResponse.ts deleted file mode 100644 index 3516b5ff..00000000 --- a/packages/number-insights/lib/interfaces/Responses/AdvancedResponse.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { LookupOutcome } from '../../enums/LookupOutcome' -import { Reachable } from '../../enums/Reachable' -import { ValidNumber } from '../../enums/ValidNumber' -import { StandardResponse } from './StandardResponse' - -export interface AdvancedResponse extends StandardResponse { - roaming: - | { - status: string - roaming_country_code: string - roaming_network_code: string - roaming_network_name: string - } - | string - lookup_outcome: LookupOutcome - lookup_outcome_message: string - valid_number: ValidNumber - reachable: Reachable - real_time_data: { - active_status: string - handset_status: string - } -} diff --git a/packages/number-insights/lib/interfaces/Responses/AsyncAdvancedResponse.ts b/packages/number-insights/lib/interfaces/Responses/AsyncAdvancedResponse.ts deleted file mode 100644 index 6160a6b5..00000000 --- a/packages/number-insights/lib/interfaces/Responses/AsyncAdvancedResponse.ts +++ /dev/null @@ -1,8 +0,0 @@ -export interface AsyncAdvancedResponse { - request_id: string - number: string - remaining_balance: string - request_price: string - status: number - error_text: string -} diff --git a/packages/number-insights/lib/interfaces/Responses/BasicResponse.ts b/packages/number-insights/lib/interfaces/Responses/BasicResponse.ts deleted file mode 100644 index 163a641e..00000000 --- a/packages/number-insights/lib/interfaces/Responses/BasicResponse.ts +++ /dev/null @@ -1,11 +0,0 @@ -export interface BasicResponse { - status: number - status_message: string - request_id: string - international_format_number: string - national_format_number: string - country_code: string - country_code_iso3: string - country_name: string - country_prefix: string -} diff --git a/packages/number-insights/lib/interfaces/Responses/StandardResponse.ts b/packages/number-insights/lib/interfaces/Responses/StandardResponse.ts deleted file mode 100644 index 7bebdea6..00000000 --- a/packages/number-insights/lib/interfaces/Responses/StandardResponse.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { CallerType } from '../../enums/CallerType' -import { NetworkType } from '../../enums/NetworkType' -import { BasicResponse } from './BasicResponse' - -export interface StandardResponse extends BasicResponse { - request_price: string - refund_price: string - remaining_balance: string - current_carrier: { - network_code: string - name: string - country: string - network_type: NetworkType - } - original_carrier: { - network_code: string - name: string - country: string - network_type: NetworkType - } - ported: string - caller_identity: { - caller_type: CallerType - caller_name: string - first_name: string - last_name: string - } - caller_name: string - last_name: string - first_name: string - caller_type: CallerType -} diff --git a/packages/number-insights/lib/interfaces/StandardLookupOptions.ts b/packages/number-insights/lib/interfaces/StandardLookupOptions.ts deleted file mode 100644 index 798d698e..00000000 --- a/packages/number-insights/lib/interfaces/StandardLookupOptions.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { BasicLookupOptions } from './BasicLookupOptions' - -export interface StandardLookupOptions extends BasicLookupOptions { - cname?: boolean -} diff --git a/packages/number-insights/lib/number-insights.ts b/packages/number-insights/lib/number-insights.ts index d09c00f2..e4747578 100644 --- a/packages/number-insights/lib/number-insights.ts +++ b/packages/number-insights/lib/number-insights.ts @@ -1,59 +1,180 @@ -import { Client } from '@vonage/server-client' -import { AdvancedLookupOptions } from './interfaces/AdvancedLookupOptions' -import { BasicLookupOptions } from './interfaces/BasicLookupOptions' -import { AdvancedResponse } from './interfaces/Responses/AdvancedResponse' -import { AsyncAdvancedResponse } from './interfaces/Responses/AsyncAdvancedResponse' -import { BasicResponse } from './interfaces/Responses/BasicResponse' -import { StandardResponse } from './interfaces/Responses/StandardResponse' -import { StandardLookupOptions } from './interfaces/StandardLookupOptions' +import { Client } from '@vonage/server-client'; +import { + AdvancedLookupOptions, + BasicLookupOptions, + AdvancedResponse, + AsyncAdvancedResponse, + BasicResponse, + StandardResponse, + StandardLookupOptions, +} from './types'; +/** + * Client for the Vonage Number Insights API. + * + * @example + * Create a standalone Number Insight client + * + * ```ts + * import { NumberInsights } from '@vonage/numberInsight'; + * + * const numberInsightClient = new NumberInsights({ + * apiKey: VONAGE_API_KEY, + * apiSecret: VONAGE_API_SECRET + * }); + * ``` + * + * @example + * Create an Number Insight client from the Vonage client + * + * ```ts + * import { Vonage } from '@vonage/server-client'; + * + * const vonage = new Vonage({ + * apiKey: VONAGE_API_KEY, + * apiSecret: VONAGE_API_SECRET + * }); + * + * const numberInsightClient = vonage.numberInsight; + * ``` + */ export class NumberInsights extends Client { - public async advancedLookup( - phoneNumber: string, - options?: AdvancedLookupOptions - ): Promise { - const params = { number: phoneNumber, ...options } - const resp = await this.sendGetRequest( - `${this.config.apiHost}/ni/advanced/json`, - params - ) - return resp.data - } + /** + * Perform an advanced number lookup operation. + * + * @param {string} phoneNumber - The phone number to perform the lookup for. + * @param {AdvancedLookupOptions} options - Additional options for the lookup. + * @return {Promise} A promise that resolves to the advanced lookup response. + * @example + * ```ts + * const lookup = await numberInsightsClient.advancedLookup('15555551212'); + * console.log(`Ths number is ${lookup.valid_number}`); + * ``` + */ + public async advancedLookup( + phoneNumber: string, + options?: AdvancedLookupOptions, + ): Promise { + const params = { number: phoneNumber, ...options }; + const resp = await this.sendGetRequest( + `${this.config.apiHost}/ni/advanced/json`, + params, + ); + return resp.data; + } - public async asyncAdvancedLookup( - phoneNumber: string, - callback: string, - options: StandardLookupOptions - ): Promise { - const params = { number: phoneNumber, callback, ...options } - const resp = await this.sendGetRequest( - `${this.config.apiHost}/ni/advanced/async/json`, - params - ) - return resp.data - } + /** + * Perform an asynchronous advanced number lookup operation. + * + * @param {string} phoneNumber - The phone number to perform the lookup for. + * @param {string} callback - The callback URL for receiving the async lookup response. + * @param {StandardLookupOptions} options - Additional options for the lookup. + * @return {Promise} A promise that resolves to the async advanced lookup response. + * + * @example + * ```ts + * const lookup = await numberInsightsClient.asyncAdvancedLookup( + * '15555551212', + * 'https://example.com/number-insights', + * ); + * console.log(`The request ID is ${lookup.request_id}`); + * ``` + * + * @example + * Lookup with the CNAME option: + * ```ts + * const lookup = await numberInsightsClient.asyncAdvancedLookup( + * '15555551212', + * 'https://example.com/number-insights', + * { cname: true }, + * ); + * console.log(`The request ID is ${lookup.request_id}`); + * ``` + */ + public async asyncAdvancedLookup( + phoneNumber: string, + callback: string, + options: StandardLookupOptions, + ): Promise { + const params = { number: phoneNumber, callback, ...options }; + const resp = await this.sendGetRequest( + `${this.config.apiHost}/ni/advanced/async/json`, + params, + ); + return resp.data; + } - public async basicLookup( - phoneNumber: string, - options?: BasicLookupOptions - ): Promise { - const params = { number: phoneNumber, ...options } - const resp = await this.sendGetRequest( - `${this.config.apiHost}/ni/basic/json`, - params - ) - return resp.data - } + /** + * Perform a basic number lookup operation. + * + * @param {string} phoneNumber - The phone number to perform the lookup for. + * @param {BasicLookupOptions} options - Additional options for the lookup. + * @return {Promise} A promise that resolves to the basic lookup response. + * + * @example + * ```ts + * const lookup = await numberInsightsClient.basicLookup( + * '15555551212', + * ); + * console.log(`The request ID is ${lookup.request_id}`); + * ``` + * + * @example + * Lookup with the country option: + * ```ts + * const lookup = await numberInsightsClient.basicLookup( + * '15555551212', + * { country: 'US' }, + * ); + * console.log(`The request ID is ${lookup.request_id}`); + * ``` + */ + public async basicLookup( + phoneNumber: string, + options?: BasicLookupOptions, + ): Promise { + const params = { number: phoneNumber, ...options }; + const resp = await this.sendGetRequest( + `${this.config.apiHost}/ni/basic/json`, + params, + ); + return resp.data; + } - public async standardLookup( - phoneNumber: string, - options?: StandardLookupOptions - ): Promise { - const params = { number: phoneNumber, ...options } - const resp = await this.sendGetRequest( - `${this.config.apiHost}/ni/standard/json`, - params - ) - return resp.data - } + /** + * Perform a standard number lookup operation. + * + * @param {string} phoneNumber - The phone number to perform the lookup for. + * @param {StandardLookupOptions} options - Additional options for the lookup. + * @return {Promise} A promise that resolves to the standard lookup response. + * + * @example + * ```ts + * const lookup = await numberInsightsClient.standardLookup( + * '15555551212', + * ); + * console.log(`The request ID is ${lookup.request_id}`); + * ``` + * + * @example + * Lookup with the cname option: + * ```ts + * const lookup = await numberInsightsClient.standardLookup( + * '15555551212', + * { cname: true }, + * ); + * console.log(`The request ID is ${lookup.request_id}`); + * ``` + */ + public async standardLookup( + phoneNumber: string, + options?: StandardLookupOptions, + ): Promise { + const params = { number: phoneNumber, ...options }; + const resp = await this.sendGetRequest( + `${this.config.apiHost}/ni/standard/json`, + params, + ); + return resp.data; + } } diff --git a/packages/number-insights/lib/types/AdvancedLookupOptions.ts b/packages/number-insights/lib/types/AdvancedLookupOptions.ts new file mode 100644 index 00000000..633afe52 --- /dev/null +++ b/packages/number-insights/lib/types/AdvancedLookupOptions.ts @@ -0,0 +1,12 @@ +import { StandardLookupOptions } from './StandardLookupOptions'; + +/** + * Interface representing advanced lookup options for a phone number lookup operation. + */ +export type AdvancedLookupOptions = StandardLookupOptions & { + /** + * Indicates whether real-time data should be included in the lookup. + * If `true`, real-time data is included; otherwise, it's not included. + */ + real_time_data?: boolean; +}; diff --git a/packages/number-insights/lib/types/AsyncAdvancedLookupOptions.ts b/packages/number-insights/lib/types/AsyncAdvancedLookupOptions.ts new file mode 100644 index 00000000..af2bd7fd --- /dev/null +++ b/packages/number-insights/lib/types/AsyncAdvancedLookupOptions.ts @@ -0,0 +1,11 @@ +import { StandardLookupOptions } from './StandardLookupOptions'; + +/** + * Interface representing asynchronous advanced lookup options for a phone number lookup operation. + */ +export type AsyncAdvancedLookupOptions = StandardLookupOptions & { + /** + * The callback URL to which the lookup response will be sent asynchronously. + */ + callback: string; +}; diff --git a/packages/number-insights/lib/types/BasicLookupOptions.ts b/packages/number-insights/lib/types/BasicLookupOptions.ts new file mode 100644 index 00000000..dd212323 --- /dev/null +++ b/packages/number-insights/lib/types/BasicLookupOptions.ts @@ -0,0 +1,9 @@ +/** + * Basic lookup options for a phone number lookup operation. + */ +export type BasicLookupOptions = { + /** + * The two-character country code for the phone number's country. + */ + country?: string; +}; diff --git a/packages/number-insights/lib/types/NumberInsightsClassParameters.ts b/packages/number-insights/lib/types/NumberInsightsClassParameters.ts deleted file mode 100644 index 5a2f1095..00000000 --- a/packages/number-insights/lib/types/NumberInsightsClassParameters.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { AuthInterface, AuthOpts } from '@vonage/auth' -import { VetchOptions } from '@vonage/vetch' - -export type NumberInsightsClassParameters = AuthOpts & - VetchOptions & { - auth?: AuthInterface - } diff --git a/packages/number-insights/lib/types/NumberInsightsResponse.ts b/packages/number-insights/lib/types/NumberInsightsResponse.ts new file mode 100644 index 00000000..bb08ffeb --- /dev/null +++ b/packages/number-insights/lib/types/NumberInsightsResponse.ts @@ -0,0 +1,7 @@ +import { VetchResponse } from '@vonage/vetch'; + +/** + * Interface representing a response from a number insights operation. + * This extends the `VetchResponse` interface. + */ +export type NumberInsightsResponse = VetchResponse; diff --git a/packages/number-insights/lib/types/Responses/AdvancedResponse.ts b/packages/number-insights/lib/types/Responses/AdvancedResponse.ts new file mode 100644 index 00000000..956f2341 --- /dev/null +++ b/packages/number-insights/lib/types/Responses/AdvancedResponse.ts @@ -0,0 +1,48 @@ +import { + LookupOutcome, + Reachable, + ValidNumber, +} from '../../enums'; + +import { StandardResponse } from './StandardResponse'; +import { RoamingDataResponse } from './RoamingDataResponse'; +import { RealTimeDataResponse } from './RealTimeDataResponse'; + +/** + * Type representing an advanced response from a phone number lookup operation. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ +export type AdvancedResponse = StandardResponse & { + /** + * Information about the roaming status of the phone number. + */ + roaming: RoamingDataResponse | string; + + /** + * The outcome of the lookup operation, represented by a `LookupOutcome` enum value. + */ + lookup_outcome: LookupOutcome; + + /** + * A message describing the outcome of the lookup operation. + */ + lookup_outcome_message: string; + + /** + * The validity status of the phone number, represented by a `ValidNumber` enum value. + */ + valid_number: ValidNumber; + + /** + * The reachability status of the phone number, represented by a `Reachable` enum value. + */ + reachable: Reachable; + + /** + * Real-time data related to the phone number. + */ + real_time_data: RealTimeDataResponse; +}; diff --git a/packages/number-insights/lib/types/Responses/AsyncAdvancedResponse.ts b/packages/number-insights/lib/types/Responses/AsyncAdvancedResponse.ts new file mode 100644 index 00000000..100f5013 --- /dev/null +++ b/packages/number-insights/lib/types/Responses/AsyncAdvancedResponse.ts @@ -0,0 +1,39 @@ +/** + * Type representing an asynchronous advanced response from a phone number lookup operation. + * This response may include additional details about the request and its status. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ +export type AsyncAdvancedResponse = { + /** + * The unique identifier for the request. + */ + request_id: string; + + /** + * The phone number associated with the response. + */ + number: string; + + /** + * Your account balance in EUR after this request. + */ + remaining_balance: string; + + /** + * The amount in EUR charged to your account for this request. + */ + request_price: string; + + /** + * The status code of the response. + */ + status: number; + + /** + * Any error text or message associated with the response. + */ + error_text: string; +}; diff --git a/packages/number-insights/lib/types/Responses/BasicResponse.ts b/packages/number-insights/lib/types/Responses/BasicResponse.ts new file mode 100644 index 00000000..3651d913 --- /dev/null +++ b/packages/number-insights/lib/types/Responses/BasicResponse.ts @@ -0,0 +1,53 @@ +/** + * Type representing a basic response from a phone number lookup operation. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ +export type BasicResponse = { + /** + * The status code of the response. + */ + status: number; + + /** + * The status message of the response. + */ + status_message: string; + + /** + * The unique identifier for the request. + */ + request_id: string; + + /** + * The phone number in international format. + */ + international_format_number: string; + + /** + * The phone number in the format used by the country. + */ + national_format_number: string; + + /** + * The two-character country code for the phone number. + */ + country_code: string; + + /** + * The three-character country code for the phone number. + */ + country_code_iso3: string; + + /** + * The full name of the country that the phone number is registered in. + */ + country_name: string; + + /** + * The numeric prefix for the country that the phone number is registered in. + */ + country_prefix: string; +}; diff --git a/packages/number-insights/lib/types/Responses/CallerIdentityResponse.ts b/packages/number-insights/lib/types/Responses/CallerIdentityResponse.ts new file mode 100644 index 00000000..321a8cea --- /dev/null +++ b/packages/number-insights/lib/types/Responses/CallerIdentityResponse.ts @@ -0,0 +1,22 @@ +import { CallerType } from '../../enums'; + +/** + * Type representing the identity of a caller. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ +export type CallerIdentityResponse = { + /** The type of the caller, either "business," "consumer," or "unknown." */ + caller_type: CallerType; + + /** The caller's name. */ + caller_name: string; + + /** The caller's first name. */ + first_name: string; + + /** The caller's last name. */ + last_name: string; +}; diff --git a/packages/number-insights/lib/types/Responses/CarrierInforResponse.ts b/packages/number-insights/lib/types/Responses/CarrierInforResponse.ts new file mode 100644 index 00000000..1b55d3f2 --- /dev/null +++ b/packages/number-insights/lib/types/Responses/CarrierInforResponse.ts @@ -0,0 +1,22 @@ +import { NetworkType } from '../../enums'; + +/** + * Type representing carrier information. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ +export type CarrierInfoResponse = { + /** The network code associated with the carrier. */ + network_code: string; + + /** The full name of the carrier. */ + name: string; + + /** The country in which the carrier operates. */ + country: string; + + /** The type of network associated with the carrier. */ + network_type: NetworkType; +}; diff --git a/packages/number-insights/lib/types/Responses/RealTimeDataResponse.ts b/packages/number-insights/lib/types/Responses/RealTimeDataResponse.ts new file mode 100644 index 00000000..2b7e4334 --- /dev/null +++ b/packages/number-insights/lib/types/Responses/RealTimeDataResponse.ts @@ -0,0 +1,11 @@ +/** + * Type representing real-time data related to a phone number. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ +export type RealTimeDataResponse = { + active_status: string; + handset_status: string; +}; diff --git a/packages/number-insights/lib/types/Responses/RoamingDataResponse.ts b/packages/number-insights/lib/types/Responses/RoamingDataResponse.ts new file mode 100644 index 00000000..a795bc92 --- /dev/null +++ b/packages/number-insights/lib/types/Responses/RoamingDataResponse.ts @@ -0,0 +1,13 @@ +/** + * Type representing information about the roaming status of a phone number. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ +export type RoamingDataResponse = { + status: string; + roaming_country_code: string; + roaming_network_code: string; + roaming_network_name: string; +}; diff --git a/packages/number-insights/lib/types/Responses/StandardResponse.ts b/packages/number-insights/lib/types/Responses/StandardResponse.ts new file mode 100644 index 00000000..22963440 --- /dev/null +++ b/packages/number-insights/lib/types/Responses/StandardResponse.ts @@ -0,0 +1,74 @@ +import { CallerType } from '../../enums'; +import { BasicResponse } from './BasicResponse'; +import { CarrierInfoResponse } from './CarrierInforResponse'; +import { CallerIdentityResponse } from './CallerIdentityResponse'; + +/** + * Type representing a standard response from a phone number lookup operation. + * This response includes various details such as pricing, carrier information, porting status, and caller identity. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ +export type StandardResponse = BasicResponse & { + /** The status code of the response. */ + status: number; + + /** The status message of the response. */ + status_message: string; + + /** The unique identifier for the request. */ + request_id: string; + + /** The phone number in international format. */ + international_format_number: string; + + /** The phone number in the format used by the country. */ + national_format_number: string; + + /** The two-character country code for the phone number. */ + country_code: string; + + /** The three-character country code for the phone number. */ + country_code_iso3: string; + + /** The full name of the country that the phone number is registered in. */ + country_name: string; + + /** The numeric prefix for the country that the phone number is registered in. */ + country_prefix: string; + + /** The price charged for the request in EUR. */ + request_price: string; + + /** The refund amount in EUR, reflecting lookup and CNAM pricing. */ + refund_price: string; + + /** Your account balance in EUR after this request. */ + remaining_balance: string; + + /** Information about the current carrier of the phone number. */ + current_carrier: CarrierInfoResponse; + + /** Information about the original carrier of the phone number. */ + original_carrier: CarrierInfoResponse; + + /** Porting status of the phone number. */ + ported: string; + + /** Information about the caller's identity. */ + caller_identity: CallerIdentityResponse; + + /** Full name of the person or business who owns the phone number. */ + caller_name: string; + + /** Last name of the person who owns the phone number. */ + last_name: string; + + /** First name of the person who owns the phone number. */ + first_name: string; + + /** The type of caller, either "business," "consumer," or "unknown." */ + caller_type: CallerType; +}; diff --git a/packages/number-insights/lib/types/Responses/index.ts b/packages/number-insights/lib/types/Responses/index.ts new file mode 100644 index 00000000..8559fb4b --- /dev/null +++ b/packages/number-insights/lib/types/Responses/index.ts @@ -0,0 +1,8 @@ +export * from './AdvancedResponse'; +export * from './AsyncAdvancedResponse'; +export * from './BasicResponse'; +export * from './CallerIdentityResponse'; +export * from './CarrierInforResponse'; +export * from './RealTimeDataResponse'; +export * from './RoamingDataResponse'; +export * from './StandardResponse'; diff --git a/packages/number-insights/lib/types/StandardLookupOptions.ts b/packages/number-insights/lib/types/StandardLookupOptions.ts new file mode 100644 index 00000000..2647b30c --- /dev/null +++ b/packages/number-insights/lib/types/StandardLookupOptions.ts @@ -0,0 +1,12 @@ +import { BasicLookupOptions } from './BasicLookupOptions'; + +/** + * Interface representing standard lookup options for a phone number lookup operation. + */ +export type StandardLookupOptions = BasicLookupOptions & { + /** + * Indicates whether caller name (CNAME) information should be included in the lookup. + * If `true`, CNAME information is included; otherwise, it's not included. + */ + cname?: boolean; +}; diff --git a/packages/number-insights/lib/types/index.ts b/packages/number-insights/lib/types/index.ts new file mode 100644 index 00000000..5c6f2f84 --- /dev/null +++ b/packages/number-insights/lib/types/index.ts @@ -0,0 +1,6 @@ +export * from './Responses'; +export * from './AdvancedLookupOptions'; +export * from './AsyncAdvancedLookupOptions'; +export * from './BasicLookupOptions'; +export * from './NumberInsightsResponse'; +export * from './StandardLookupOptions'; diff --git a/packages/number-insights/package.json b/packages/number-insights/package.json index 0ae759fb..39fc0731 100644 --- a/packages/number-insights/package.json +++ b/packages/number-insights/package.json @@ -1,4 +1,5 @@ { + "$schema": "https://json.schemastore.org/package.json", "name": "@vonage/number-insights", "version": "1.9.0", "description": "Vonage Number Insights API", @@ -11,7 +12,16 @@ "url": "git+https://github.com/Vonage/vonage-node-sdk.git" }, "license": "Apache-2.0", - "author": "Chris Tankersley ", + "contributors": [ + { + "name": "Chris Tankersley", + "url": "https://github.com/dragonmantank" + }, + { + "name": "Chuck \"MANCHUCK\" Reeves", + "url": "https://github.com/manchuck" + } + ], "main": "dist/index.js", "types": "dist/index.d.ts", "directories": { @@ -24,7 +34,8 @@ "scripts": { "build": "npm run clean && npm run compile", "clean": "npx shx rm -rf dist tsconfig.tsbuildinfo", - "compile": "npx tsc --build --verbose" + "compile": "npx tsc --build --verbose", + "prepublishOnly": "npm run build" }, "dependencies": { "@vonage/auth": "^1.7.0", @@ -36,6 +47,5 @@ }, "publishConfig": { "directory": "dist" - }, - "gitHead": "328f18e5c8a458cb4d06d7955ec2399a6ce6f5d8" + } } diff --git a/packages/number-insights/tsconfig.json b/packages/number-insights/tsconfig.json index e9b438f7..eadf2cc8 100644 --- a/packages/number-insights/tsconfig.json +++ b/packages/number-insights/tsconfig.json @@ -1,24 +1,25 @@ { - "extends": "../../tsconfig.json", + "$schema": "https://json.schemastore.org/tsconfig", - "compilerOptions": { - "rootDir": "lib", - "outDir": "dist" - }, + "extends": "../../tsconfig.json", - "exclude": [ - "__tests__", - "jest.config.js", - "dist" - ], + "compilerOptions": { + "rootDir": "lib", + "outDir": "dist" + }, - "references": [ - { "path": "../auth" }, - { "path": "../server-client" }, - { "path": "../vetch" } - ], + "exclude": [ + "__tests__", + "dist" + ], - "ts-node": { - "esm": true - } + "references": [ + { "path": "../auth" }, + { "path": "../server-client" }, + { "path": "../vetch" } + ], + + "ts-node": { + "esm": true + } } diff --git a/packages/number-insights/typedoc.json b/packages/number-insights/typedoc.json new file mode 100644 index 00000000..756762f7 --- /dev/null +++ b/packages/number-insights/typedoc.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "extends": ["../../typedoc.base.json"], + "entryPoints": ["lib/index.ts"], + "name": "Vonage JWT" +} diff --git a/packages/numbers/__tests__/__dataSets__/buyNumbers.ts b/packages/numbers/__tests__/__dataSets__/buyNumbers.ts index 9877c86a..94a9fb1b 100644 --- a/packages/numbers/__tests__/__dataSets__/buyNumbers.ts +++ b/packages/numbers/__tests__/__dataSets__/buyNumbers.ts @@ -11,9 +11,9 @@ export default [ `/number/buy?api_key=12345&api_secret=ABCDE`, 'POST', new URLSearchParams([ - ['target_api_key', '67890'], ['country', 'US'], ['msisdn', '12345'], + ['target_api_key', '67890'], ]).toString(), ], reply: [ @@ -46,9 +46,9 @@ export default [ `/number/buy?api_key=12345&api_secret=ABCDE`, 'POST', new URLSearchParams([ - ['target_api_key', '67890'], ['country', 'US'], ['msisdn', '12345'], + ['target_api_key', '67890'], ]).toString(), ], reply: [ diff --git a/packages/numbers/__tests__/__dataSets__/cancel.ts b/packages/numbers/__tests__/__dataSets__/cancel.ts index da628c33..437a6afc 100644 --- a/packages/numbers/__tests__/__dataSets__/cancel.ts +++ b/packages/numbers/__tests__/__dataSets__/cancel.ts @@ -13,9 +13,9 @@ export default [ `/number/cancel?api_key=12345&api_secret=ABCDE`, 'POST', new URLSearchParams([ - ['target_api_key', '67890'], ['country', 'US'], ['msisdn', '12345'], + ['target_api_key', '67890'], ]).toString(), ], reply: [200, validResponse], diff --git a/packages/numbers/__tests__/__dataSets__/update.ts b/packages/numbers/__tests__/__dataSets__/update.ts index 46b42eeb..a1382a4d 100644 --- a/packages/numbers/__tests__/__dataSets__/update.ts +++ b/packages/numbers/__tests__/__dataSets__/update.ts @@ -1,4 +1,4 @@ -import * as types from '../../lib/types'; +import { VoiceCallbackTypeEnum } from "../../lib"; const BASE_URL = 'https://rest.nexmo.com'; const CLIENT_METHOD = 'updateNumber'; @@ -33,7 +33,7 @@ export default [ country: 'US', msisdn: '12345', applicationId: '123abc', - voiceCallbackType: types.VoiceCallbackTypeEnum.App, + voiceCallbackType: VoiceCallbackTypeEnum.App, voiceCallbackValue: 'https://www.example.com/webhook', voiceStatusCallback: 'https://www.example.com/webhook/events', }, diff --git a/packages/numbers/lib/enums/Feature.ts b/packages/numbers/lib/enums/Feature.ts index aeebf107..52a5201f 100644 --- a/packages/numbers/lib/enums/Feature.ts +++ b/packages/numbers/lib/enums/Feature.ts @@ -1,5 +1,19 @@ +/** + * Enumeration of features for a virtual number. + */ export enum Feature { - 'MMS' = 'MMS', - 'SMS' = 'SMS', - 'VOICE' = 'VOICE', + /** + * Supports Multimedia Messaging Service (MMS). + */ + MMS = 'MMS', + + /** + * Supports Short Message Service (SMS). + */ + SMS = 'SMS', + + /** + * Supports Voice calling. + */ + VOICE = 'VOICE', } diff --git a/packages/numbers/lib/enums/LineType.ts b/packages/numbers/lib/enums/LineType.ts index b463e824..9cd4ef5c 100644 --- a/packages/numbers/lib/enums/LineType.ts +++ b/packages/numbers/lib/enums/LineType.ts @@ -1,5 +1,19 @@ +/** + * Enumeration of line types for virtual numbers. + */ export enum LineType { - 'LANDLINE' = 'landline', - 'MOBILE-LVN' = 'mobile-lvn', - 'LANDLINE-TOLL-FREE' = 'landline-toll-free', + /** + * Landline type. + */ + LANDLINE = 'landline', + + /** + * Mobile LVN (Local Virtual Number) type. + */ + MOBILE_LVN = 'mobile-lvn', + + /** + * Landline toll-free type. + */ + LANDLINE_TOLL_FREE = 'landline-toll-free', } diff --git a/packages/numbers/lib/enums/MessagesCallbackTypeEnum.ts b/packages/numbers/lib/enums/MessagesCallbackTypeEnum.ts new file mode 100644 index 00000000..86fb5c92 --- /dev/null +++ b/packages/numbers/lib/enums/MessagesCallbackTypeEnum.ts @@ -0,0 +1,9 @@ +/** + * Enumeration of messages callback types. + */ +export enum MessagesCallbackTypeEnum { + /** + * Callback type for an application. + */ + App = 'app', +} diff --git a/packages/numbers/lib/enums/SearchPattern.ts b/packages/numbers/lib/enums/SearchPattern.ts index d82b9f44..15c48388 100644 --- a/packages/numbers/lib/enums/SearchPattern.ts +++ b/packages/numbers/lib/enums/SearchPattern.ts @@ -1,5 +1,19 @@ +/** + * Enumeration of search patterns. + */ export enum SearchPattern { - 'START_WITH' = 0, - 'CONTAINS' = 1, - 'ENDS_WITH' = 2, + /** + * Indicates a search for values that start with the given pattern. + */ + START_WITH = 0, + + /** + * Indicates a search for values that contain the given pattern. + */ + CONTAINS = 1, + + /** + * Indicates a search for values that end with the given pattern. + */ + ENDS_WITH = 2, } diff --git a/packages/numbers/lib/enums/VoiceCallbackTypeEnum.ts b/packages/numbers/lib/enums/VoiceCallbackTypeEnum.ts new file mode 100644 index 00000000..44e6ed26 --- /dev/null +++ b/packages/numbers/lib/enums/VoiceCallbackTypeEnum.ts @@ -0,0 +1,19 @@ +/** + * Enumeration of voice callback types. + */ +export enum VoiceCallbackTypeEnum { + /** + * Callback type for SIP. + */ + Sip = 'sip', + + /** + * Callback type for telephone (tel). + */ + Tel = 'tel', + + /** + * Callback type for an application. + */ + App = 'app', +} diff --git a/packages/numbers/lib/enums/index.ts b/packages/numbers/lib/enums/index.ts new file mode 100644 index 00000000..40baf65f --- /dev/null +++ b/packages/numbers/lib/enums/index.ts @@ -0,0 +1,5 @@ +export * from './Feature'; +export * from './LineType'; +export * from './MessagesCallbackTypeEnum'; +export * from './SearchPattern'; +export * from './VoiceCallbackTypeEnum'; diff --git a/packages/numbers/lib/index.ts b/packages/numbers/lib/index.ts index a4a6afdd..7b9153e3 100644 --- a/packages/numbers/lib/index.ts +++ b/packages/numbers/lib/index.ts @@ -1,17 +1,3 @@ -export { Numbers } from './numbers' - -export { - NumbersClassParameters, - NumbersResponse, - NumbersAvailableList, - NumbersOwnedList, - NumbersEmptyResponse, - NumbersParams, - NumbersAvailableNumber, - Country, - NumbersUpdateParams, - VoiceCallbackTypeEnum, - MessagesCallbackTypeEnum, - NumbersOwnedNumber, - NumbersOwnedFilter, -} from './types' +export * from './enums'; +export * from './types'; +export * from './numbers'; diff --git a/packages/numbers/lib/numbers.ts b/packages/numbers/lib/numbers.ts index eccd49fe..8035efe7 100644 --- a/packages/numbers/lib/numbers.ts +++ b/packages/numbers/lib/numbers.ts @@ -1,30 +1,17 @@ import { AuthenticationType, Client } from '@vonage/server-client'; -import { Feature } from './enums/Feature'; +import { Feature, SearchPattern } from './enums'; +import omit from 'lodash.omit'; import { NumbersAvailableList, - NumbersOwnedFilter, NumbersOwnedList, - NumbersOwnedNumber, NumbersEmptyResponse, - NumbersUpdateParams, - NumbersSearchFilter, NumbersParams, + NumbersOwnedFilter, NumbersQuerySearchFilter, NumbersSearchSimple, -} from './types'; -import { SearchPattern } from './enums/SearchPattern'; -import omit from 'lodash.omit'; - -const remapObjects = (mapping, newObject: T, oldObject: O): T => { - for (const key in mapping) { - if (oldObject[mapping[key]]) { - newObject[key] = oldObject[mapping[key]]; - delete oldObject[mapping[key]]; - } - } - newObject = { ...newObject, ...oldObject }; - return newObject; -}; + NumbersSearchFilter, + NumbersUpdateParams, +} from "./types"; const buildSearch = ({ endsWith, @@ -46,7 +33,7 @@ const buildSearch = ({ }; } - // order of precdent contains, endsWith, startsWith + // order of precedent contains, endsWith, startsWith if (contains) { return { search_pattern: SearchPattern.CONTAINS, @@ -74,7 +61,7 @@ const buildSearch = ({ return {}; }; -const sortFeatures = (features: string[]): string => { +const sortFeatures = (features: Feature[]): string => { // API expects these as a CSV in a specific order if (features.length > 4) { throw new Error('Invalid number of features request'); @@ -104,64 +91,176 @@ const sortFeatures = (features: string[]): string => { return newOrder.join(','); }; +/** + * Client for buying, canceling, and searching for phone numbers. + * + * @example + * Create a standalone Numbers client + * + * ```ts + * import { Numbers } from '@vonage/numbers'; + * + * const numbersClient = new Numbers({ + * apiKey: VONAGE_API_KEY, + * apiSecret: VONAGE_API_SECRET + * }); + * ``` + * + * @example + * Create an Numbers client from the Vonage client + * + * ```ts + * import { Vonage } from '@vonage/server-client'; + * + * const vonage = new Vonage({ + * apiKey: VONAGE_API_KEY, + * apiSecret: VONAGE_API_SECRET + * }); + * + * const numbersClient = vonage.numbers; + * ``` + */ export class Numbers extends Client { protected authType = AuthenticationType.QUERY_KEY_SECRET; + /** + * Buy a phone number. + * + * @param {NumbersParams} params - The parameters for buying a number. + * @return {Promise} A promise that resolves to an empty response or an error response. + * + * @example + * Buy a phone number + * ```ts + * import { Country } from '@vonage/numbers'; + * const resp = await numbersClient.buyNumber({ + * country: Country.US, + * msisdn: '15555555555' + * }); + * + * if (resp.errorCode) { + * console.log(`Error: ${resp.errorCodeLabel}`); + * } else { + * console.log('Number bought successfully'); + * } + * ``` + */ public async buyNumber( - params?: NumbersParams, + params: NumbersParams, ): Promise { - const mapping = { target_api_key: 'targetApiKey' }; - const data = remapObjects(mapping, {}, params); const resp = await this.sendFormSubmitRequest( `${this.config.restHost}/number/buy`, - data, + Client.transformers.snakeCaseObjectKeys(params) as Record, ); return { - errorCode: resp.data['error-code'], + errorCode: `${resp.data['error-code']}`, errorCodeLabel: resp.data['error-code-label'], }; } + /** + * Cancel a phone number. + * + * @param {NumbersParams} params - The parameters for canceling a number. + * @return {Promise} A promise that resolves to an empty response or an error response. + * + * @example + * Cancel a phone number + * + * ```ts + * + * const resp = await numbersClient.cancelNumber({ + * msisdn: '15555555555' + * }); + * + * if (resp.errorCode) { + * console.log(`Error: ${resp.errorCodeLabel}`); + * } else { + * console.log('Number cancled successfully'); + * } + * ``` + */ public async cancelNumber( - params?: NumbersParams, + params: NumbersParams, ): Promise { - const mapping = { target_api_key: 'targetApiKey' }; - const data = remapObjects(mapping, {}, params); const resp = await this.sendFormSubmitRequest( `${this.config.restHost}/number/cancel`, - data, + Client.transformers.snakeCaseObjectKeys(params) as Record, ); return { - errorCode: resp.data['error-code'], + errorCode: `${resp.data['error-code']}`, errorCodeLabel: resp.data['error-code-label'], }; } - + /** + * Retrieves a list of available phone numbers based on the provided filter criteria. + * + * @param {NumbersSearchFilter} filter - The filter criteria for searching available numbers. + * @return {Promise} A promise that resolves to a list of available phone numbers or an error response. + * + * @example + * Search for available numbers that can send SMS and make voice calls + * ```ts + * import { Country, Feature } from '@vonage/numbers'; + * + * const resp = await numbersClient.getAvailableNumbers({ + * country: Country.US, + * features: [Feature.SMS, Feature.VOICE], + * }); + * + * console.log(`There are ${resp.count} numbers available`); + * + * for (const number of resp.numbers) { + * console.log(number.msisdn); + * console.log(number.cost); + * console.log(number.type); + * } + * ``` + */ public async getAvailableNumbers( filter: NumbersSearchFilter, ): Promise { - const mapping = { - search_pattern: 'searchPattern', - }; - const data: any = omit( - remapObjects(mapping, {}, { ...filter, ...buildSearch(filter) }), - ['startsWith', 'contains', 'endsWith', 'searchPattern'], + omit( + Client.transformers.snakeCaseObjectKeys({ + ...filter, + ...buildSearch(filter), + country: filter.country, + }), + ['starts_with', 'contains', 'ends_with', 'search_pattern'], ); - - if (data.features?.length > 0) { - data.features = sortFeatures(data.features); - } - const resp = await this.sendGetRequest( `${this.config.restHost}/number/search`, - data, + { + ...( filter.country ? { country: filter.country } : {}), + ...( filter.type ? { type: filter.type } : {}), + ...( filter.size ? { size: filter.size } : {}), + ...( filter.index ? { index: filter.index } : {}), + ...buildSearch(filter), + ...(filter.features ? { features: sortFeatures(filter.features) } : {}), + }, ); return resp.data; } + /** + * Retrieves a list of owned phone numbers based on the provided filter criteria. + * + * @param {NumbersOwnedFilter} [filter] - The filter criteria for searching owned numbers. + * @return {Promise} A promise that resolves to a list of owned phone numbers or an error response. + * @example + * Search for owned numbers + * ```ts + * const resp = await numbersClient.getOwnedNumbers(); + * console.log(`There are ${resp.count} numbers owned`); + * for (const number of resp.numbers) { + * console.log(number.msisdn); + * console.log(number.type); + * } + * ``` + */ public async getOwnedNumbers( filter?: NumbersOwnedFilter, ): Promise { @@ -175,20 +274,45 @@ export class Numbers extends Client { return resp.data; } + /** + * Updates the settings of a phone number. + * + * @param {NumbersUpdateParams} [params] - The parameters for updating a phone number. + * @return {Promise} A promise that resolves to an empty response or an error response. + * + * @example + * + * ```ts + * const resp = await numbersClient.updateNumber({ + * msisdn: '15555555555', + * voiceCallbackType: 'app', + * voiceCallbackValue: 'APPLICATION_ID', + * voiceStatusCallback: 'https://example.com/webhooks/voice', + * }); + * + * if (resp.errorCode) { + * console.log(`Error: ${resp.errorCodeLabel}`); + * } else { + * console.log('Number bought successfully'); + * } + * ``` + */ public async updateNumber( - params?: NumbersUpdateParams, + params: NumbersUpdateParams, ): Promise { - const mapping = { - app_id: 'applicationId', - }; - const data = remapObjects(mapping, {}, params); - const resp = await this.sendFormSubmitRequest( + const appId = params.applicationId || params.appId; + delete params.applicationId; + delete params.appId; + const resp = await this.sendFormSubmitRequest( `${this.config.restHost}/number/update`, - data, + { + ...(appId ? { app_id: appId } : {}), + ...params, + }, ); return { - errorCode: resp.data['error-code'], + errorCode: `${resp.data['error-code']}`, errorCodeLabel: resp.data['error-code-label'], }; } diff --git a/packages/numbers/lib/types.ts b/packages/numbers/lib/types.ts deleted file mode 100644 index b9cac9bc..00000000 --- a/packages/numbers/lib/types.ts +++ /dev/null @@ -1,145 +0,0 @@ -import { AuthOpts, AuthInterface } from '@vonage/auth'; -import { VetchResponse, VetchOptions } from '@vonage/vetch'; -import { Feature } from './enums/Feature'; -import { SearchPattern } from './enums/SearchPattern'; -import { LineType } from './enums/LineType'; - -export type NumbersClassParameters = AuthOpts & - VetchOptions & { - auth?: AuthInterface - } - -export type NumbersResponse = VetchResponse - -export interface NumbersAvailableList { - count?: number - numbers?: NumbersAvailableNumber[] -} - -export interface NumbersOwnedList { - count?: number - numbers?: NumbersOwnedNumber[] -} - -export interface NumbersEmptyResponse { - errorCode?: string - errorCodeLabel?: string -} - -export interface NumbersParams { - country: Country - msisdn: string - targetApiKey?: string -} - -export interface NumbersQueryParams { - country: Country - msisdn: string - target_api_key?: string -} - -export interface NumbersAvailableNumber { - country?: Country - msisdn?: string - type?: LineType - cost?: string - features?: Feature[] -} - -export type Country = string - -export interface NumbersUpdateParams { - country: Country - msisdn: string - applicationId?: string - moHttpUrl?: string - moSmppSysType?: string - voiceCallbackType?: VoiceCallbackTypeEnum - voiceCallbackValue?: string - voiceStatusCallback?: string - /** @deprecated */ - messagesCallbackType?: MessagesCallbackTypeEnum - /** @deprecated */ - messagesCallbackValue?: string -} - -export interface NumbersQueryUpdateParams { - country: Country - msisdn: string - app_id?: string - moHttpUrl?: string - moSmppSysType?: string - voiceCallbackType?: VoiceCallbackTypeEnum - voiceCallbackValue?: string - voiceStatusCallback?: string - /** @deprecated */ - messagesCallbackType?: MessagesCallbackTypeEnum - /** @deprecated */ - messagesCallbackValue?: string -} - -export enum VoiceCallbackTypeEnum { - Sip = 'sip', - Tel = 'tel', - App = 'app', -} - -export enum MessagesCallbackTypeEnum { - App = 'app', -} - -export interface NumbersOwnedNumber { - country?: Country - msisdn?: string - moHttpUrl?: string - type?: LineType - features?: Feature[] - voiceCallbackType?: string - voiceCallbackValue?: string - messagesCallbackType?: string - messagesCallbackValue?: string -} - -export interface NumbersSearchFilter { - country: Country - type?: LineType - pattern?: string - searchPattern?: SearchPattern - features?: Feature[] - size?: number - index?: number -} - -export interface NumbersSearchSimple { - startsWith?: string - endsWith?: string - contains?: string -} - -export interface NumbersQuerySearchFilter { - country: Country - pattern?: string - search_pattern?: number - size?: number - index?: number -} - -export interface NumbersOwnedFilter { - country?: Country - applicationId?: string - hasApplication?: boolean - pattern?: string - searchPattern?: SearchPattern - size?: number - index?: number -} - -export interface NumbersQueryOwnedFilter { - country?: Country - application_id?: string - has_application?: boolean - pattern?: string - search_pattern?: number - size?: number - index?: number -} diff --git a/packages/numbers/lib/types/Country.ts b/packages/numbers/lib/types/Country.ts new file mode 100644 index 00000000..13836ce2 --- /dev/null +++ b/packages/numbers/lib/types/Country.ts @@ -0,0 +1,254 @@ +/** + * ISO 3166-1 alpha-2 country codes. + */ +export type Country = + | 'AD' // Andorra + | 'AE' // United Arab Emirates + | 'AF' // Afghanistan + | 'AG' // Antigua and Barbuda + | 'AI' // Anguilla + | 'AL' // Albania + | 'AM' // Armenia + | 'AO' // Angola + | 'AQ' // Antarctica + | 'AR' // Argentina + | 'AS' // American Samoa + | 'AT' // Austria + | 'AU' // Australia + | 'AW' // Aruba + | 'AX' // Åland Islands + | 'AZ' // Azerbaijan + | 'BA' // Bosnia and Herzegovina + | 'BB' // Barbados + | 'BD' // Bangladesh + | 'BE' // Belgium + | 'BF' // Burkina Faso + | 'BG' // Bulgaria + | 'BH' // Bahrain + | 'BI' // Burundi + | 'BJ' // Benin + | 'BL' // Saint Barthélemy + | 'BM' // Bermuda + | 'BN' // Brunei Darussalam + | 'BO' // Bolivia (Plurinational State of) + | 'BQ' // Bonaire, Sint Eustatius and Saba + | 'BR' // Brazil + | 'BS' // Bahamas + | 'BT' // Bhutan + | 'BV' // Bouvet Island + | 'BW' // Botswana + | 'BY' // Belarus + | 'BZ' // Belize + | 'CA' // Canada + | 'CC' // Cocos (Keeling) Islands + | 'CD' // Congo, Democratic Republic of the + | 'CF' // Central African Republic + | 'CG' // Congo + | 'CH' // Switzerland + | 'CI' // Côte d'Ivoire + | 'CK' // Cook Islands + | 'CL' // Chile + | 'CM' // Cameroon + | 'CN' // China + | 'CO' // Colombia + | 'CR' // Costa Rica + | 'CU' // Cuba + | 'CV' // Cabo Verde + | 'CW' // Curaçao + | 'CX' // Christmas Island + | 'CY' // Cyprus + | 'CZ' // Czechia + | 'DE' // Germany + | 'DJ' // Djibouti + | 'DK' // Denmark + | 'DM' // Dominica + | 'DO' // Dominican Republic + | 'DZ' // Algeria + | 'EC' // Ecuador + | 'EE' // Estonia + | 'EG' // Egypt + | 'EH' // Western Sahara + | 'ER' // Eritrea + | 'ES' // Spain + | 'ET' // Ethiopia + | 'FI' // Finland + | 'FJ' // Fiji + | 'FK' // Falkland Islands (Malvinas) + | 'FM' // Micronesia (Federated States of) + | 'FO' // Faroe Islands + | 'FR' // France + | 'GA' // Gabon + | 'GB' // United Kingdom of Great Britain and Northern Ireland + | 'GD' // Grenada + | 'GE' // Georgia + | 'GF' // French Guiana + | 'GG' // Guernsey + | 'GH' // Ghana + | 'GI' // Gibraltar + | 'GL' // Greenland + | 'GM' // Gambia + | 'GN' // Guinea + | 'GP' // Guadeloupe + | 'GQ' // Equatorial Guinea + | 'GR' // Greece + | 'GS' // South Georgia and the South Sandwich Islands + | 'GT' // Guatemala + | 'GU' // Guam + | 'GW' // Guinea-Bissau + | 'GY' // Guyana + | 'HK' // Hong Kong + | 'HM' // Heard Island and McDonald Islands + | 'HN' // Honduras + | 'HR' // Croatia + | 'HT' // Haiti + | 'HU' // Hungary + | 'ID' // Indonesia + | 'IE' // Ireland + | 'IL' // Israel + | 'IM' // Isle of Man + | 'IN' // India + | 'IO' // British Indian Ocean Territory + | 'IQ' // Iraq + | 'IR' // Iran (Islamic Republic of) + | 'IS' // Iceland + | 'IT' // Italy + | 'JE' // Jersey + | 'JM' // Jamaica + | 'JO' // Jordan + | 'JP' // Japan + | 'KE' // Kenya + | 'KG' // Kyrgyzstan + | 'KH' // Cambodia + | 'KI' // Kiribati + | 'KM' // Comoros + | 'KN' // Saint Kitts and Nevis + | 'KP' // Korea (Democratic People's Republic of) + | 'KR' // Korea, Republic of + | 'KW' // Kuwait + | 'KY' // Cayman Islands + | 'KZ' // Kazakhstan + | 'LA' // Lao People's Democratic Republic + | 'LB' // Lebanon + | 'LC' // Saint Lucia + | 'LI' // Liechtenstein + | 'LK' // Sri Lanka + | 'LR' // Liberia + | 'LS' // Lesotho + | 'LT' // Lithuania + | 'LU' // Luxembourg + | 'LV' // Latvia + | 'LY' // Libya + | 'MA' // Morocco + | 'MC' // Monaco + | 'MD' // Moldova, Republic of + | 'ME' // Montenegro + | 'MF' // Saint Martin (French part) + | 'MG' // Madagascar + | 'MH' // Marshall Islands + | 'MK' // North Macedonia + | 'ML' // Mali + | 'MM' // Myanmar + | 'MN' // Mongolia + | 'MO' // Macao + | 'MP' // Northern Mariana Islands + | 'MQ' // Martinique + | 'MR' // Mauritania + | 'MS' // Montserrat + | 'MT' // Malta + | 'MU' // Mauritius + | 'MV' // Maldives + | 'MW' // Malawi + | 'MX' // Mexico + | 'MY' // Malaysia + | 'MZ' // Mozambique + | 'NA' // Namibia + | 'NC' // New Caledonia + | 'NE' // Niger + | 'NF' // Norfolk Island + | 'NG' // Nigeria + | 'NI' // Nicaragua + | 'NL' // Netherlands, Kingdom of the + | 'NO' // Norway + | 'NP' // Nepal + | 'NR' // Nauru + | 'NU' // Niue + | 'NZ' // New Zealand + | 'OM' // Oman + | 'PA' // Panama + | 'PE' // Peru + | 'PF' // French Polynesia + | 'PG' // Papua New Guinea + | 'PH' // Philippines + | 'PK' // Pakistan + | 'PL' // Poland + | 'PM' // Saint Pierre and Miquelon + | 'PN' // Pitcairn + | 'PR' // Puerto Rico + | 'PS' // Palestine, State of + | 'PT' // Portugal + | 'PW' // Palau + | 'PY' // Paraguay + | 'QA' // Qatar + | 'RE' // Réunion + | 'RO' // Romania + | 'RS' // Serbia + | 'RU' // Russian Federation + | 'RW' // Rwanda + | 'SA' // Saudi Arabia + | 'SB' // Solomon Islands + | 'SC' // Seychelles + | 'SD' // Sudan + | 'SE' // Sweden + | 'SG' // Singapore + | 'SH' // Saint Helena, Ascension and Tristan da Cunha + | 'SI' // Slovenia + | 'SJ' // Svalbard and Jan Mayen + | 'SK' // Slovakia + | 'SL' // Sierra Leone + | 'SM' // San Marino + | 'SN' // Senegal + | 'SO' // Somalia + | 'SR' // Suriname + | 'SS' // South Sudan + | 'ST' // Sao Tome and Principe + | 'SV' // El Salvador + | 'SX' // Sint Maarten (Dutch part) + | 'SY' // Syrian Arab Republic + | 'SZ' // Eswatini + | 'TC' // Turks and Caicos Islands + | 'TD' // Chad + | 'TF' // French Southern Territories + | 'TG' // Togo + | 'TH' // Thailand + | 'TJ' // Tajikistan + | 'TK' // Tokelau + | 'TL' // Timor-Leste + | 'TM' // Turkmenistan + | 'TN' // Tunisia + | 'TO' // Tonga + | 'TR' // Türkiye + | 'TT' // Trinidad and Tobago + | 'TV' // Tuvalu + | 'TW' // Taiwan, Province of China + | 'TZ' // Tanzania, United Republic of + | 'UA' // Ukraine + | 'UG' // Uganda | 'UM' // United States Minor Outlying Islands + | 'US' // United States of America + | 'UY' // Uruguay + | 'UZ' // Uzbekistan + | 'VA' // Holy See + | 'VC' // Saint Vincent and the Grenadines + | 'VE' // Venezuela (Bolivarian Republic of) + | 'VG' // Virgin Islands (British) + | 'VI' // Virgin Islands (U.S.) + | 'VN' // Viet Nam + | 'VU' // Vanuatu + | 'WF' // Wallis and Futuna + | 'WS' // Samoa + | 'YE' // Yemen + | 'YT' // Mayotte + | 'ZA' // South Africa + | 'ZM' // Zambia + | 'ZW' // Zimbabwe + | string; // Fallback + diff --git a/packages/numbers/lib/types/NumbersAvailableList.ts b/packages/numbers/lib/types/NumbersAvailableList.ts new file mode 100644 index 00000000..2e95118a --- /dev/null +++ b/packages/numbers/lib/types/NumbersAvailableList.ts @@ -0,0 +1,16 @@ +import { NumbersAvailableNumber } from "./NumbersAvailableNumber"; + +/** + * Represents a list of available numbers. + */ +export type NumbersAvailableList = { + /** + * The total count of available numbers. + */ + count?: number; + + /** + * An array of available numbers and their details. + */ + numbers?: NumbersAvailableNumber[]; +} diff --git a/packages/numbers/lib/types/NumbersAvailableNumber.ts b/packages/numbers/lib/types/NumbersAvailableNumber.ts new file mode 100644 index 00000000..9a1370e7 --- /dev/null +++ b/packages/numbers/lib/types/NumbersAvailableNumber.ts @@ -0,0 +1,37 @@ +import { LineType, Feature } from "../enums"; +import { Country } from "./Country"; + +/** + * Represents an available phone number with its details. + */ +export type NumbersAvailableNumber = { + /** + * The two-character country code in ISO 3166-1 alpha-2 format. + * Example: "US" for the United States. + */ + country?: Country; + + /** + * An available inbound virtual phone number. + * Example: "447700900000". + */ + msisdn?: string; + + /** + * The type of phone number. + * Example: "mobile-lvn" or "landline". + */ + type?: LineType; + + /** + * The cost associated with the phone number. + * Example: "$10.00". + */ + cost?: string; + + /** + * The capabilities/features of the phone number, such as SMS, VOICE, or MMS. + * Example: ["SMS", "VOICE"]. + */ + features?: Feature[]; +}; diff --git a/packages/numbers/lib/types/NumbersClassParameters.ts b/packages/numbers/lib/types/NumbersClassParameters.ts new file mode 100644 index 00000000..e5e89042 --- /dev/null +++ b/packages/numbers/lib/types/NumbersClassParameters.ts @@ -0,0 +1,15 @@ +import { AuthInterface, AuthParams } from "@vonage/auth"; +import { VetchOptions } from "@vonage/vetch"; + +/** + * Represents the parameters for configuring the NumbersClass. + * + * @deprecated This is no longer in use + */ +export type NumbersClassParameters = AuthParams & + VetchOptions & { + /** + * The authentication configuration. + */ + auth?: AuthInterface; +}; diff --git a/packages/numbers/lib/types/NumbersEmptyResponse.ts b/packages/numbers/lib/types/NumbersEmptyResponse.ts new file mode 100644 index 00000000..d8e227b9 --- /dev/null +++ b/packages/numbers/lib/types/NumbersEmptyResponse.ts @@ -0,0 +1,28 @@ +/** + * Represents a response with optional error code and label for empty number-related operations. + */ +export type NumbersEmptyResponse = { + /** + * The error code, if an error occurred during the operation. + * Example: "E001". + */ + errorCode?: string; + + /** + * A human-readable label or description of the error code. + * Example: "Invalid request." + */ + errorCodeLabel?: string; + + /** + * The error code, if an error occurred during the operation. + * Example: "E001". + */ + 'error-code'?: 200 | 401 | number; + + /** + * A human-readable label or description of the error code. + * Example: "Invalid request." + */ + 'error-code-label'?: string +}; diff --git a/packages/numbers/lib/types/NumbersOwnedFilter.ts b/packages/numbers/lib/types/NumbersOwnedFilter.ts new file mode 100644 index 00000000..df99612c --- /dev/null +++ b/packages/numbers/lib/types/NumbersOwnedFilter.ts @@ -0,0 +1,45 @@ +import { SearchPattern } from "../enums"; +import { Country } from "./Country"; + +/** + * Represents filters for searching owned numbers. + */ +export type NumbersOwnedFilter = { + /** + * The two-character country code in ISO 3166-1 alpha-2 format. + * Example: "US" for the United States. + */ + country?: Country; + + /** + * An Application ID. + * Example: "aaaaaaaa-bbbb-cccc-dddd-0123456789ab". + */ + applicationId?: string; + + /** + * Indicates whether numbers have an associated application. + */ + hasApplication?: boolean; + + /** + * A pattern to filter numbers. + */ + pattern?: string; + + /** + * The search pattern type. + * Example: SearchPattern.START_WITH. + */ + searchPattern?: SearchPattern; + + /** + * The maximum number of results to return. + */ + size?: number; + + /** + * The starting index for paginated results. + */ + index?: number; +}; diff --git a/packages/numbers/lib/types/NumbersOwnedList.ts b/packages/numbers/lib/types/NumbersOwnedList.ts new file mode 100644 index 00000000..50117c90 --- /dev/null +++ b/packages/numbers/lib/types/NumbersOwnedList.ts @@ -0,0 +1,16 @@ +import { NumbersOwnedNumber } from "./NumbersOwnedNumber"; + +/** + * Represents a list of owned numbers. + */ +export type NumbersOwnedList = { + /** + * The total count of owned numbers. + */ + count?: number; + + /** + * An array of owned numbers and their details. + */ + numbers?: NumbersOwnedNumber[]; +}; diff --git a/packages/numbers/lib/types/NumbersOwnedNumber.ts b/packages/numbers/lib/types/NumbersOwnedNumber.ts new file mode 100644 index 00000000..fc1c7096 --- /dev/null +++ b/packages/numbers/lib/types/NumbersOwnedNumber.ts @@ -0,0 +1,61 @@ +import { LineType, Feature } from "../enums"; +import { Country } from "./Country"; + +/** + * Represents an owned phone number with its details. + */ +export type NumbersOwnedNumber = { + /** + * The two-character country code in ISO 3166-1 alpha-2 format. + * Example: "US" for the United States. + */ + country?: Country; + + /** + * The owned phone number. + * Example: "447700900000". + */ + msisdn?: string; + + /** + * The URL of the webhook endpoint that handles inbound messages for the number. + * Example: "https://example.com/webhooks/inbound-sms". + */ + moHttpUrl?: string; + + /** + * The type of phone number. + * Example: "mobile-lvn" or "landline". + */ + type?: LineType; + + /** + * The capabilities/features of the phone number, such as SMS, VOICE, or MMS. + * Example: ["SMS", "VOICE"]. + */ + features?: Feature[]; + + /** + * The type of voice callback for the number. + * Example: "app" or "sip". + */ + voiceCallbackType?: string; + + /** + * The value associated with the voice callback. + * Example: "aaaaaaaa-bbbb-cccc-dddd-0123456789ab". + */ + voiceCallbackValue?: string; + + /** + * The type of messages callback for the number. + * Example: "app". + */ + messagesCallbackType?: string; + + /** + * The value associated with the messages callback. + * Example: "aaaaaaaa-bbbb-cccc-dddd-0123456789ab". + */ + messagesCallbackValue?: string; +}; diff --git a/packages/numbers/lib/types/NumbersParams.ts b/packages/numbers/lib/types/NumbersParams.ts new file mode 100644 index 00000000..3891a374 --- /dev/null +++ b/packages/numbers/lib/types/NumbersParams.ts @@ -0,0 +1,23 @@ +import { Country } from "./Country"; + +/** + * Represents parameters for configuring a phone number. + */ +export type NumbersParams = { + /** + * The two-character country code in ISO 3166-1 alpha-2 format. + * Example: "US" for the United States. + */ + country: Country; + + /** + * The phone number. + * Example: "447700900000". + */ + msisdn: string; + + /** + * An optional target API key. + */ + targetApiKey?: string; +}; diff --git a/packages/numbers/lib/types/NumbersQueryOwnedFilter.ts b/packages/numbers/lib/types/NumbersQueryOwnedFilter.ts new file mode 100644 index 00000000..6f211804 --- /dev/null +++ b/packages/numbers/lib/types/NumbersQueryOwnedFilter.ts @@ -0,0 +1,44 @@ +import { Country } from "./Country"; + +/** + * Represents filters for querying owned numbers. + */ +export type NumbersQueryOwnedFilter = { + /** + * The two-character country code in ISO 3166-1 alpha-2 format. + * Example: "US" for the United States. + */ + country?: Country; + + /** + * An Application ID. + * Example: "aaaaaaaa-bbbb-cccc-dddd-0123456789ab". + */ + application_id?: string; + + /** + * Indicates whether numbers have an associated application. + */ + has_application?: boolean; + + /** + * A pattern to filter numbers. + */ + pattern?: string; + + /** + * The search pattern type. + * Example: 0 for "START_WITH". + */ + search_pattern?: number; + + /** + * The maximum number of results to return. + */ + size?: number; + + /** + * The starting index for paginated results. + */ + index?: number; +}; diff --git a/packages/numbers/lib/types/NumbersQueryParams.ts b/packages/numbers/lib/types/NumbersQueryParams.ts new file mode 100644 index 00000000..28cd1020 --- /dev/null +++ b/packages/numbers/lib/types/NumbersQueryParams.ts @@ -0,0 +1,23 @@ +import { Country } from "./Country"; + +/** + * Represents parameters for querying phone numbers. + */ +export type NumbersQueryParams = { + /** + * The two-character country code in ISO 3166-1 alpha-2 format. + * Example: "US" for the United States. + */ + country: Country; + + /** + * The phone number. + * Example: "447700900000". + */ + msisdn: string; + + /** + * An optional target API key. + */ + target_api_key?: string; +}; diff --git a/packages/numbers/lib/types/NumbersQuerySearchFilter.ts b/packages/numbers/lib/types/NumbersQuerySearchFilter.ts new file mode 100644 index 00000000..fed5afec --- /dev/null +++ b/packages/numbers/lib/types/NumbersQuerySearchFilter.ts @@ -0,0 +1,33 @@ +import { Country } from "./Country"; + +/** + * Represents filters for searching phone numbers. + */ +export type NumbersQuerySearchFilter = { + /** + * The two-character country code in ISO 3166-1 alpha-2 format. + * Example: "US" for the United States. + */ + country?: Country; + + /** + * A pattern to filter numbers. + */ + pattern?: string; + + /** + * The search pattern type. + * Example: 0 for "START_WITH". + */ + search_pattern?: number; + + /** + * The maximum number of results to return. + */ + size?: number; + + /** + * The starting index for paginated results. + */ + index?: number; +}; diff --git a/packages/numbers/lib/types/NumbersQueryUpdateParams.ts b/packages/numbers/lib/types/NumbersQueryUpdateParams.ts new file mode 100644 index 00000000..705bc172 --- /dev/null +++ b/packages/numbers/lib/types/NumbersQueryUpdateParams.ts @@ -0,0 +1,62 @@ +import { VoiceCallbackTypeEnum, MessagesCallbackTypeEnum } from "../enums"; +import { Country } from "./Country"; + +/** + * Represents parameters for updating phone number settings. + */ +export type NumbersQueryUpdateParams = { + /** + * The two-character country code in ISO 3166-1 alpha-2 format. + * Example: "US" for the United States. + */ + country: Country; + + /** + * The phone number. + * Example: "447700900000". + */ + msisdn: string; + + /** + * An Application ID. + * Example: "aaaaaaaa-bbbb-cccc-dddd-0123456789ab". + */ + app_id?: string; + + /** + * The HTTP URL for handling MO (Mobile Originated) messages. + */ + moHttpUrl?: string; + + /** + * The SMPP system type for MO (Mobile Originated) messages. + */ + moSmppSysType?: string; + + /** + * The voice callback type. + */ + voiceCallbackType?: VoiceCallbackTypeEnum; + + /** + * The voice callback value. + */ + voiceCallbackValue?: string; + + /** + * The voice status callback URL. + */ + voiceStatusCallback?: string; + + /** + * The messages callback type. + * @deprecated + */ + messagesCallbackType?: MessagesCallbackTypeEnum; + + /** + * The messages callback value. + * @deprecated + */ + messagesCallbackValue?: string; +}; diff --git a/packages/numbers/lib/types/NumbersResponse.ts b/packages/numbers/lib/types/NumbersResponse.ts new file mode 100644 index 00000000..38fa000c --- /dev/null +++ b/packages/numbers/lib/types/NumbersResponse.ts @@ -0,0 +1,7 @@ +import { VetchResponse } from "@vonage/vetch"; + +/** + * Represents a response for phone numbers. + * @template T The type of the response data. + */ +export type NumbersResponse = VetchResponse; diff --git a/packages/numbers/lib/types/NumbersSearchFilter.ts b/packages/numbers/lib/types/NumbersSearchFilter.ts new file mode 100644 index 00000000..e50f9ff6 --- /dev/null +++ b/packages/numbers/lib/types/NumbersSearchFilter.ts @@ -0,0 +1,44 @@ +import { LineType, Feature, SearchPattern } from "../enums"; +import { Country } from "./Country"; + +/** + * Represents filters for searching phone numbers. + */ +export type NumbersSearchFilter = { + /** + * The two-character country code in ISO 3166-1 alpha-2 format. + * Example: "US" for the United States. + */ + country: Country; + + /** + * The type of the phone number. + */ + type?: LineType; + + /** + * A pattern to filter numbers. + */ + pattern?: string; + + /** + * The search pattern type. + * Example: 0 for "START_WITH". + */ + searchPattern?: SearchPattern; + + /** + * The capabilities or features of the number. + */ + features?: Feature[]; + + /** + * The maximum number of results to return. + */ + size?: number; + + /** + * The starting index for paginated results. + */ + index?: number; +}; diff --git a/packages/numbers/lib/types/NumbersSearchSimple.ts b/packages/numbers/lib/types/NumbersSearchSimple.ts new file mode 100644 index 00000000..d8c02387 --- /dev/null +++ b/packages/numbers/lib/types/NumbersSearchSimple.ts @@ -0,0 +1,19 @@ +/** + * Represents simple search options for phone numbers. + */ +export type NumbersSearchSimple = { + /** + * Filter numbers that start with a specific string. + */ + startsWith?: string; + + /** + * Filter numbers that end with a specific string. + */ + endsWith?: string; + + /** + * Filter numbers that contain a specific string. + */ + contains?: string; +}; diff --git a/packages/numbers/lib/types/NumbersUpdateParams.ts b/packages/numbers/lib/types/NumbersUpdateParams.ts new file mode 100644 index 00000000..f927b08f --- /dev/null +++ b/packages/numbers/lib/types/NumbersUpdateParams.ts @@ -0,0 +1,68 @@ +import { VoiceCallbackTypeEnum, MessagesCallbackTypeEnum } from "../enums"; +import { Country } from "./Country"; + +/** + * Represents parameters for updating phone numbers. + */ +export type NumbersUpdateParams = { + /** + * The two-character country code in ISO 3166-1 alpha-2 format. + * Example: "US" for the United States. + */ + country: Country; + + /** + * The phone number in E.164 format. + * Example: "+1234567890". + */ + msisdn: string; + + /** + * The application ID associated with the phone number. + * @deprecated Please use app_id + */ + applicationId?: string; + + /** + * The application ID associated with the phone number. + */ + appId?: string; + + /** + * The URL of the webhook endpoint that handles inbound messages. + */ + moHttpUrl?: string; + + /** + * The system type for SMPP MO messages. + */ + moSmppSysType?: string; + + /** + * The type of voice callback: "sip", "tel", or "app". + */ + voiceCallbackType?: VoiceCallbackTypeEnum; + + /** + * The value for voice callback. + */ + voiceCallbackValue?: string; + + /** + * The URL of the voice status callback. + */ + voiceStatusCallback?: string; + + /** + * The type of messages callback: "app". + * + * @deprecated Use voiceCallbackType instead. + */ + messagesCallbackType?: MessagesCallbackTypeEnum; + + /** + * The value for messages callback. + * @deprecated Use voiceCallbackValue instead. + */ + messagesCallbackValue?: string; +}; diff --git a/packages/numbers/lib/types/index.ts b/packages/numbers/lib/types/index.ts new file mode 100644 index 00000000..c6d02597 --- /dev/null +++ b/packages/numbers/lib/types/index.ts @@ -0,0 +1,17 @@ +export * from './Country'; +export * from './NumbersAvailableList'; +export * from './NumbersAvailableNumber'; +export * from './NumbersClassParameters'; +export * from './NumbersEmptyResponse'; +export * from './NumbersOwnedFilter'; +export * from './NumbersOwnedList'; +export * from './NumbersOwnedNumber'; +export * from './NumbersParams'; +export * from './NumbersQueryOwnedFilter'; +export * from './NumbersQueryParams'; +export * from './NumbersQuerySearchFilter'; +export * from './NumbersQueryUpdateParams'; +export * from './NumbersResponse'; +export * from './NumbersSearchFilter'; +export * from './NumbersSearchSimple'; +export * from './NumbersUpdateParams'; diff --git a/packages/numbers/package.json b/packages/numbers/package.json index b6ce0a14..b59ca9a5 100644 --- a/packages/numbers/package.json +++ b/packages/numbers/package.json @@ -1,4 +1,5 @@ { + "$schema": "https://json.schemastore.org/package.json", "name": "@vonage/numbers", "version": "1.9.0", "description": "Vonage Numbers SDK Package", @@ -11,7 +12,20 @@ "url": "git+https://github.com/Vonage/vonage-node-sdk.git" }, "license": "Apache-2.0", - "author": "Kelly J Andrews ", + "contributors": [ + { + "name": "Kelly J Andrews", + "url": "https://github.com/kellyjandrews" + }, + { + "name": "Chris Tankersley", + "url": "https://github.com/dragonmantank" + }, + { + "name": "Chuck \"MANCHUCK\" Reeves", + "url": "https://github.com/manchuck" + } + ], "main": "dist/index.js", "types": "dist/index.d.ts", "directories": { @@ -24,19 +38,20 @@ "scripts": { "build": "npm run clean && npm run compile", "clean": "npx shx rm -rf dist tsconfig.tsbuildinfo", - "compile": "npx tsc --build --verbose" + "compile": "npx tsc --build --verbose", + "prepublishOnly": "npm run build" }, "dependencies": { + "@types/lodash.omit": "4.5.8", "@vonage/auth": "^1.7.0", "@vonage/server-client": "^1.9.0", "@vonage/vetch": "^1.6.0", - "lodash.omit": "^4.5.0" + "lodash.omit": "4.5.0" }, "devDependencies": { "nock": "^13.3.4" }, "publishConfig": { "directory": "dist" - }, - "gitHead": "328f18e5c8a458cb4d06d7955ec2399a6ce6f5d8" + } } diff --git a/packages/numbers/typedoc.json b/packages/numbers/typedoc.json new file mode 100644 index 00000000..7f70fb7a --- /dev/null +++ b/packages/numbers/typedoc.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "extends": ["../../typedoc.base.json"], + "entryPoints": ["lib/index.ts"], + "name": "Vonage Numbers" +} diff --git a/packages/pricing/__tests__/pricing.test.ts b/packages/pricing/__tests__/pricing.test.ts index 5bcfdfff..ad104a6f 100644 --- a/packages/pricing/__tests__/pricing.test.ts +++ b/packages/pricing/__tests__/pricing.test.ts @@ -1,129 +1,129 @@ -import { Auth } from '@vonage/auth' -import nock from 'nock' -import { ServiceType } from '../lib/enums/ServiceType' -import { Pricing } from '../lib/index' +import { Auth } from '@vonage/auth'; +import nock from 'nock'; +import { ServiceType } from '../lib/enums/ServiceType'; +import { Pricing } from '../lib/index'; -const BASE_URL = 'https://rest.nexmo.com/'.replace(/\/+$/, '') +const BASE_URL = 'https://rest.nexmo.com/'.replace(/\/+$/, ''); describe('pricing', () => { - let client + let client; - beforeEach(() => { - client = new Pricing(new Auth({ apiKey: 'abcd', apiSecret: '1234' })) - }) + beforeEach(() => { + client = new Pricing(new Auth({ apiKey: 'abcd', apiSecret: '1234' })); + }); - afterEach(() => { - client = null - }) + afterEach(() => { + client = null; + }); - test('do a country lookup', async () => { - const expectedResponse = { - countryCode: 'CA', - countryName: 'Canada', - countryDisplayName: 'Canada', - currency: 'EUR', - defaultPrice: '0.00620000', - dialingPrefix: '1', - networks: [ - { - type: 'mobile', - price: '0.00590000', - currency: 'EUR', - mcc: '302', - mnc: '530', - networkCode: '302530', - networkName: 'Keewaytinook Okimakanak', - }, - ], - } + test('do a country lookup', async () => { + const expectedResponse = { + countryCode: 'CA', + countryName: 'Canada', + countryDisplayName: 'Canada', + currency: 'EUR', + defaultPrice: '0.00620000', + dialingPrefix: '1', + networks: [ + { + type: 'mobile', + price: '0.00590000', + currency: 'EUR', + mcc: '302', + mnc: '530', + networkCode: '302530', + networkName: 'Keewaytinook Okimakanak', + }, + ], + }; - nock(BASE_URL) - .persist() - .get('/account/get-pricing/outbound/sms') - .query({ api_key: 'abcd', api_secret: '1234', country: 'CA' }) - .reply(200, expectedResponse) + nock(BASE_URL) + .persist() + .get('/account/get-pricing/outbound/sms') + .query({ api_key: 'abcd', api_secret: '1234', country: 'CA' }) + .reply(200, expectedResponse); - const lookup = await client.listCountryPricing(ServiceType.SMS, 'CA') - expect(lookup.countryCode).toEqual(expectedResponse.countryCode) - expect(lookup.countryName).toEqual(expectedResponse.countryName) - expect(lookup.countryDisplayName).toEqual( - expectedResponse.countryDisplayName - ) - expect(lookup.currency).toEqual(expectedResponse.currency) - expect(lookup.defaultPrice).toEqual(expectedResponse.defaultPrice) - expect(lookup.dialingPrefix).toEqual(expectedResponse.dialingPrefix) - expect(lookup.networks).toEqual(expectedResponse.networks) - }) + const lookup = await client.listCountryPricing(ServiceType.SMS, 'CA'); + expect(lookup.countryCode).toEqual(expectedResponse.countryCode); + expect(lookup.countryName).toEqual(expectedResponse.countryName); + expect(lookup.countryDisplayName).toEqual( + expectedResponse.countryDisplayName, + ); + expect(lookup.currency).toEqual(expectedResponse.currency); + expect(lookup.defaultPrice).toEqual(expectedResponse.defaultPrice); + expect(lookup.dialingPrefix).toEqual(expectedResponse.dialingPrefix); + expect(lookup.networks).toEqual(expectedResponse.networks); + }); - test('do all country lookup', async () => { - const expectedResponse = { - count: '243', - countries: [ - { - countryName: 'Canada', - countryDisplayName: 'Canada', - currency: 'EUR', - defaultPrice: '0.00620000', - dialingPrefix: '1', - networks: [ - { - type: 'mobile', - price: '0.00590000', - currency: 'EUR', - mcc: '302', - mnc: '530', - networkCode: '302530', - networkName: 'Keewaytinook Okimakanak', - }, - ], - }, - ], - } + test('do all country lookup', async () => { + const expectedResponse = { + count: '243', + countries: [ + { + countryName: 'Canada', + countryDisplayName: 'Canada', + currency: 'EUR', + defaultPrice: '0.00620000', + dialingPrefix: '1', + networks: [ + { + type: 'mobile', + price: '0.00590000', + currency: 'EUR', + mcc: '302', + mnc: '530', + networkCode: '302530', + networkName: 'Keewaytinook Okimakanak', + }, + ], + }, + ], + }; - nock(BASE_URL) - .persist() - .get('/account/get-full-pricing/outbound/sms') - .query({ api_key: 'abcd', api_secret: '1234' }) - .reply(200, expectedResponse) + nock(BASE_URL) + .persist() + .get('/account/get-full-pricing/outbound/sms') + .query({ api_key: 'abcd', api_secret: '1234' }) + .reply(200, expectedResponse); - const lookup = await client.listAllCountriesPricing(ServiceType.SMS) - expect(lookup.count).toEqual(expectedResponse.count) - expect(lookup.countries).toEqual(expectedResponse.countries) - }) + const lookup = await client.listAllCountriesPricing(ServiceType.SMS); + expect(lookup.count).toEqual(expectedResponse.count); + expect(lookup.countries).toEqual(expectedResponse.countries); + }); - test('do prefix lookup', async () => { - const expectedResponse = { - count: '243', - countries: [ - { - countryName: 'Canada', - countryDisplayName: 'Canada', - currency: 'EUR', - defaultPrice: '0.00620000', - dialingPrefix: '1', - networks: [ - { - type: 'mobile', - price: '0.00590000', - currency: 'EUR', - mcc: '302', - mnc: '530', - networkCode: '302530', - networkName: 'Keewaytinook Okimakanak', - }, - ], - }, - ], - } + test('do prefix lookup', async () => { + const expectedResponse = { + count: '243', + countries: [ + { + countryName: 'Canada', + countryDisplayName: 'Canada', + currency: 'EUR', + defaultPrice: '0.00620000', + dialingPrefix: '1', + networks: [ + { + type: 'mobile', + price: '0.00590000', + currency: 'EUR', + mcc: '302', + mnc: '530', + networkCode: '302530', + networkName: 'Keewaytinook Okimakanak', + }, + ], + }, + ], + }; - nock(BASE_URL) - .persist() - .get('/account/get-prefix-pricing/outbound/sms') - .query({ api_key: 'abcd', api_secret: '1234', prefix: '1' }) - .reply(200, expectedResponse) + nock(BASE_URL) + .persist() + .get('/account/get-prefix-pricing/outbound/sms') + .query({ api_key: 'abcd', api_secret: '1234', prefix: '1' }) + .reply(200, expectedResponse); - const lookup = await client.listPrefixPricing(ServiceType.SMS, '1') - expect(lookup.count).toEqual(expectedResponse.count) - expect(lookup.countries).toEqual(expectedResponse.countries) - }) -}) + const lookup = await client.listPrefixPricing(ServiceType.SMS, '1'); + expect(lookup.count).toEqual(expectedResponse.count); + expect(lookup.countries).toEqual(expectedResponse.countries); + }); +}); diff --git a/packages/pricing/lib/enums/ServiceType.ts b/packages/pricing/lib/enums/ServiceType.ts index 1bc0d336..5aa61b48 100644 --- a/packages/pricing/lib/enums/ServiceType.ts +++ b/packages/pricing/lib/enums/ServiceType.ts @@ -1,5 +1,19 @@ +/** + * Enum representing different service types for pricing information. + */ export enum ServiceType { - SMS = 'sms', - SMS_TRANSIT = 'sms-transit', - VOICE = 'voice', + /** + * SMS service. + */ + SMS = 'sms', + + /** + * SMS Transit service. + */ + SMS_TRANSIT = 'sms-transit', + + /** + * Voice service. + */ + VOICE = 'voice', } diff --git a/packages/pricing/lib/enums/index.ts b/packages/pricing/lib/enums/index.ts new file mode 100644 index 00000000..434e6c1f --- /dev/null +++ b/packages/pricing/lib/enums/index.ts @@ -0,0 +1 @@ +export * from './ServiceType'; diff --git a/packages/pricing/lib/index.ts b/packages/pricing/lib/index.ts index bfab8da3..04f6e086 100644 --- a/packages/pricing/lib/index.ts +++ b/packages/pricing/lib/index.ts @@ -1 +1,3 @@ -export { Pricing } from './pricing' +export * from './pricing'; +export * from './types'; +export * from './enums'; diff --git a/packages/pricing/lib/interfaces/Network.ts b/packages/pricing/lib/interfaces/Network.ts deleted file mode 100644 index 7bf92a41..00000000 --- a/packages/pricing/lib/interfaces/Network.ts +++ /dev/null @@ -1,9 +0,0 @@ -export interface Network { - type: string - price: string - currency: string - mcc: string - mnc: string - networkCode: string - networkName: string -} diff --git a/packages/pricing/lib/interfaces/PricingResponse.ts b/packages/pricing/lib/interfaces/PricingResponse.ts deleted file mode 100644 index 541bd733..00000000 --- a/packages/pricing/lib/interfaces/PricingResponse.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { VetchResponse } from '@vonage/vetch' - -export interface PricingResponse extends VetchResponse {} diff --git a/packages/pricing/lib/interfaces/Response/OutboundAllCountriesPricingResponse.ts b/packages/pricing/lib/interfaces/Response/OutboundAllCountriesPricingResponse.ts deleted file mode 100644 index 3cbcc7fd..00000000 --- a/packages/pricing/lib/interfaces/Response/OutboundAllCountriesPricingResponse.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { OutboundCountryPricingResponse } from './OutboundCountryPricingResponse' - -export interface OutboundAllCountriesPricingResponse { - count: number - countries: OutboundCountryPricingResponse[] -} diff --git a/packages/pricing/lib/interfaces/Response/OutboundCountryPricingResponse.ts b/packages/pricing/lib/interfaces/Response/OutboundCountryPricingResponse.ts deleted file mode 100644 index baac3f90..00000000 --- a/packages/pricing/lib/interfaces/Response/OutboundCountryPricingResponse.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { Network } from '../Network' - -export interface OutboundCountryPricingResponse { - countryCode: string - countryName: string - countryDisplayName: string - currency: string - defaultPrice: string - dialingPrefix: string - networks: Network[] -} diff --git a/packages/pricing/lib/pricing.ts b/packages/pricing/lib/pricing.ts index ac4040af..b31efc91 100644 --- a/packages/pricing/lib/pricing.ts +++ b/packages/pricing/lib/pricing.ts @@ -1,41 +1,115 @@ -import { AuthenticationType, Client } from '@vonage/server-client' -import { ServiceType } from './enums/ServiceType' -import { OutboundAllCountriesPricingResponse } from './interfaces/Response/OutboundAllCountriesPricingResponse' -import { OutboundCountryPricingResponse } from './interfaces/Response/OutboundCountryPricingResponse' +import { AuthenticationType, Client } from '@vonage/server-client'; +import { ServiceType } from './enums'; +import { + OutboundAllCountriesPricingResponse, + OutboundCountryPricingResponse, +} from './types'; +/** + * The Pricing API allows you to retrieve pricing information for all countries + * and a specific service type, for a specific country and service type, or for + * a specific prefix and service type. + * + * @example + * Create a standalone Pricing client + * + * ```ts + * import { Pricing } from '@vonage/pricing'; + * + * const pricingClient = new Pricing({ + * apiKey: VONAGE_API_KEY, + * apiSecret: VONAGE_API_SECRET + * }); + * ``` + * + * @example + * Create an Pricing client from the Vonage client + * + * ```ts + * import { Vonage } from '@vonage/server-client'; + * + * const vonage = new Vonage({ + * apiKey: VONAGE_API_KEY, + * apiSecret: VONAGE_API_SECRET + * }); + * + * const pricingClient = vonage.pricing; + * ``` + */ export class Pricing extends Client { - protected authType = AuthenticationType.QUERY_KEY_SECRET + protected authType = AuthenticationType.QUERY_KEY_SECRET; - public async listCountryPricing( - type: ServiceType, - country: string - ): Promise { - const resp = await this.sendGetRequest( - `${this.config.restHost}/account/get-pricing/outbound/${type}`, - { country } - ) - return resp.data - } + /** + * Retrieves pricing information for a specific country and service type. + * + * @param {ServiceType} type - The service type. + * @param {string} country - The country for which pricing information is requested. + * @return {Promise} - Pricing information for the specified country. + * @example + * + * ```ts + * import { ServiceType } from '@vonage/pricing'; + * + * const pricing = await pricingClient.listCountryPricing(ServiceType.SMS, 'GB'); + * console.log(`The current price for Great Britian is ${pricing.defaultPrice}`); + * ``` + */ + async listCountryPricing( + type: ServiceType, + country: string, + ): Promise { + const resp = await this.sendGetRequest( + `${this.config.restHost}/account/get-pricing/outbound/${type}`, + { country }, + ); + return resp.data; + } - public async listAllCountriesPricing( - type: ServiceType - ): Promise { - const resp = - await this.sendGetRequest( - `${this.config.restHost}/account/get-full-pricing/outbound/${type}` - ) - return resp.data - } + /** + * Retrieves pricing information for all countries and a specific service type. + * @param {ServiceType} type - The service type. + * @return {Promise} - Pricing information for all countries. + * @example + * ```ts + * import { ServiceType } from '@vonage/pricing'; + * + * const pricing = await pricingClient.listAllCountriesPricing(ServiceType.SMS); + * for (const country in pricing.countries) { + * console.log(`The current price for ${country.countryName} is ${country.defaultPrice}`); + * } + * ``` + */ + async listAllCountriesPricing( + type: ServiceType, + ): Promise { + const resp = await this.sendGetRequest( + `${this.config.restHost}/account/get-full-pricing/outbound/${type}`, + ); + return resp.data; + } - public async listPrefixPricing( - type: ServiceType, - prefix: string - ): Promise { - const resp = - await this.sendGetRequest( - `${this.config.restHost}/account/get-prefix-pricing/outbound/${type}`, - { prefix } - ) - return resp.data - } + /** + * Retrieves pricing information for a specific prefix and service type. + * @param {ServiceType} type - The service type. + * @param {string} prefix - The prefix for which pricing information is requested. + * @return {Promise} - Pricing information for the specified prefix. + * + * @example + * ```ts + * import { ServiceType } from '@vonage/pricing'; + * + * const pricing = await pricingClient.listPrefixPricing(ServiceType.SMS, '44'); + * console.log(`The current price for Great Britian is ${pricing.defaultPrice}`); + * ``` + */ + async listPrefixPricing( + type: ServiceType, + prefix: string, + ): Promise { + const resp = await this.sendGetRequest( + `${this.config.restHost}/account/get-prefix-pricing/outbound/${type}`, + { prefix }, + ); + return resp.data; + } } diff --git a/packages/pricing/lib/types/Network.ts b/packages/pricing/lib/types/Network.ts new file mode 100644 index 00000000..60ec31a4 --- /dev/null +++ b/packages/pricing/lib/types/Network.ts @@ -0,0 +1,39 @@ +/** + * Type representing a network within a specific country's pricing information. + */ +export type Network = { + /** + * The type of network + */ + type: string; + + /** + * The cost to send a message or make a call on this network. + */ + price: string; + + /** + * The currency used for prices for this network + */ + currency: string; + + /** + * The Mobile Country Code (MCC) of the operator + */ + mcc: string; + + /** + * The Mobile Network Code (MNC) of the operator + */ + mnc: string; + + /** + * The Mobile Country Code and Mobile Network Code combined to give a unique reference for the operator + */ + networkCode: string; + + /** + * The company/organizational name of the operator + */ + networkName: string; +}; diff --git a/packages/pricing/lib/types/PricingClassParameters.ts b/packages/pricing/lib/types/PricingClassParameters.ts index ccadbe3a..7c2698f1 100644 --- a/packages/pricing/lib/types/PricingClassParameters.ts +++ b/packages/pricing/lib/types/PricingClassParameters.ts @@ -1,7 +1,14 @@ -import { AuthInterface, AuthOpts } from '@vonage/auth' -import { VetchOptions } from '@vonage/vetch' +import { AuthInterface, AuthParams } from '@vonage/auth'; +import { VetchOptions } from '@vonage/vetch'; -export type PricingClassParameters = AuthOpts & - VetchOptions & { - auth?: AuthInterface - } +/** + * Type representing parameters for a pricing class, including authentication and Vetch options. + */ +export type PricingClassParameters = AuthParams & + VetchOptions & { + /** + * An optional authentication interface. + * @return {AuthInterface|undefined} - The authentication interface if provided, otherwise undefined. + */ + auth?: AuthInterface; +}; diff --git a/packages/pricing/lib/types/PricingResponse.ts b/packages/pricing/lib/types/PricingResponse.ts new file mode 100644 index 00000000..09a80fc0 --- /dev/null +++ b/packages/pricing/lib/types/PricingResponse.ts @@ -0,0 +1,3 @@ +import { VetchResponse } from '@vonage/vetch'; + +export type PricingResponse = VetchResponse; diff --git a/packages/pricing/lib/types/Response/OutboundAllCountriesPricingResponse.ts b/packages/pricing/lib/types/Response/OutboundAllCountriesPricingResponse.ts new file mode 100644 index 00000000..16ae4ec8 --- /dev/null +++ b/packages/pricing/lib/types/Response/OutboundAllCountriesPricingResponse.ts @@ -0,0 +1,16 @@ +import { OutboundCountryPricingResponse } from './OutboundCountryPricingResponse'; + +/** + * Type representing the response for pricing information of all countries. + */ +export type OutboundAllCountriesPricingResponse = { + /** + * The number of countries in the response. + */ + count: number; + + /** + * An array of objects containing pricing information for individual countries. + */ + countries: OutboundCountryPricingResponse[]; +}; diff --git a/packages/pricing/lib/types/Response/OutboundCountryPricingResponse.ts b/packages/pricing/lib/types/Response/OutboundCountryPricingResponse.ts new file mode 100644 index 00000000..b77e950b --- /dev/null +++ b/packages/pricing/lib/types/Response/OutboundCountryPricingResponse.ts @@ -0,0 +1,40 @@ +import { Network } from '../Network'; +/** + * Type representing the response for pricing information of a specific country. + */ +export type OutboundCountryPricingResponse = { + /** + * Two-letter country code. + */ + countryCode: string; + + /** + * Readable country name. + */ + countryName: string; + + /** + * Readable country name. + */ + countryDisplayName: string; + + /** + * The currency that your account is being billed in. + */ + currency: string; + + /** + * The default price for services in this country. + */ + defaultPrice: string; + + /** + * The dialing prefix for this country. + */ + dialingPrefix: string; + + /** + * An array of network objects representing different networks in this country. + */ + networks: Network[]; +}; diff --git a/packages/pricing/lib/types/Response/index.ts b/packages/pricing/lib/types/Response/index.ts new file mode 100644 index 00000000..c9f9cce0 --- /dev/null +++ b/packages/pricing/lib/types/Response/index.ts @@ -0,0 +1,2 @@ +export * from './OutboundAllCountriesPricingResponse'; +export * from './OutboundCountryPricingResponse'; diff --git a/packages/pricing/lib/types/index.ts b/packages/pricing/lib/types/index.ts new file mode 100644 index 00000000..10b3d863 --- /dev/null +++ b/packages/pricing/lib/types/index.ts @@ -0,0 +1,4 @@ +export * from './Response'; +export * from './Network'; +export * from './PricingClassParameters'; +export * from './PricingResponse'; diff --git a/packages/pricing/package.json b/packages/pricing/package.json index dc2e9a48..014ab20b 100644 --- a/packages/pricing/package.json +++ b/packages/pricing/package.json @@ -1,4 +1,5 @@ { + "$schema": "https://json.schemastore.org/package.json", "name": "@vonage/pricing", "version": "1.9.0", "description": "Vonage API for pricing", @@ -11,7 +12,16 @@ "url": "git+https://github.com/Vonage/vonage-node-sdk.git" }, "license": "Apache-2.0", - "author": "Chris Tankersley ", + "contributors": [ + { + "name": "Chris Tankersley", + "url": "https://github.com/dragonmantank" + }, + { + "name": "Chuck \"MANCHUCK\" Reeves", + "url": "https://github.com/manchuck" + } + ], "main": "dist/index.js", "types": "dist/index.d.ts", "directories": { @@ -24,7 +34,8 @@ "scripts": { "build": "npm run clean && npm run compile", "clean": "npx shx rm -rf dist tsconfig.tsbuildinfo", - "compile": "npx tsc --build --verbose" + "compile": "npx tsc --build --verbose", + "prepublishOnly": "npm run build" }, "dependencies": { "@vonage/auth": "^1.7.0", @@ -36,6 +47,5 @@ }, "publishConfig": { "directory": "dist" - }, - "gitHead": "328f18e5c8a458cb4d06d7955ec2399a6ce6f5d8" + } } diff --git a/packages/pricing/tsconfig.json b/packages/pricing/tsconfig.json index e9b438f7..8e8615aa 100644 --- a/packages/pricing/tsconfig.json +++ b/packages/pricing/tsconfig.json @@ -1,24 +1,25 @@ { - "extends": "../../tsconfig.json", + "$schema": "https://json.schemastore.org/tsconfig", - "compilerOptions": { - "rootDir": "lib", - "outDir": "dist" - }, + "extends": "../../tsconfig.json", - "exclude": [ - "__tests__", - "jest.config.js", - "dist" - ], + "compilerOptions": { + "rootDir": "lib", + "outDir": "dist" + }, - "references": [ - { "path": "../auth" }, - { "path": "../server-client" }, - { "path": "../vetch" } - ], + "exclude": [ + "__tests__", + "dist" + ], - "ts-node": { - "esm": true - } + "references": [ + { "path": "../auth" }, + { "path": "../server-client" }, + { "path": "../vetch" } + ], + + "ts-node": { + "esm": true + } } diff --git a/packages/pricing/typedoc.json b/packages/pricing/typedoc.json new file mode 100644 index 00000000..9ea2894f --- /dev/null +++ b/packages/pricing/typedoc.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "extends": ["../../typedoc.base.json"], + "entryPoints": ["lib/index.ts"], + "name": "Vonage Pricing" +} diff --git a/packages/proactive-connect/lib/enums/eventTypes.ts b/packages/proactive-connect/lib/enums/eventTypes.ts index 0d320fb7..851b61b7 100644 --- a/packages/proactive-connect/lib/enums/eventTypes.ts +++ b/packages/proactive-connect/lib/enums/eventTypes.ts @@ -1,12 +1,54 @@ +/** + * Enumeration representing different event types. + */ export enum EventTypes { - ACTION_CALL_SUCCEEDED = 'action-call-succeeded', - ACTION_CALL_FAILED = 'action-call-failed', - ACTION_CALL_INFO = 'action-call-info', - RECIPIENT_RESPONSE = 'recipient-response', - RUN_ITEM_SKIPPED = 'run-item-skipped', - RUN_ITEM_FAILED = 'run-item-failed', - RUN_ITEM_SUBMITTED = 'run-item-submitted', - RUN_ITEMS_TOTAL = 'run-items-total', - RUN_ITEMS_READY = 'run-items-ready', - RUN_ITEMS_EXCLUDED = 'run-items-excluded', + /** + * Event type: Action call succeeded. + */ + ACTION_CALL_SUCCEEDED = 'action-call-succeeded', + + /** + * Event type: Action call failed. + */ + ACTION_CALL_FAILED = 'action-call-failed', + + /** + * Event type: Action call info. + */ + ACTION_CALL_INFO = 'action-call-info', + + /** + * Event type: Recipient response. + */ + RECIPIENT_RESPONSE = 'recipient-response', + + /** + * Event type: Run item skipped. + */ + RUN_ITEM_SKIPPED = 'run-item-skipped', + + /** + * Event type: Run item failed. + */ + RUN_ITEM_FAILED = 'run-item-failed', + + /** + * Event type: Run item submitted. + */ + RUN_ITEM_SUBMITTED = 'run-item-submitted', + + /** + * Event type: Run items total. + */ + RUN_ITEMS_TOTAL = 'run-items-total', + + /** + * Event type: Run items ready. + */ + RUN_ITEMS_READY = 'run-items-ready', + + /** + * Event type: Run items excluded. + */ + RUN_ITEMS_EXCLUDED = 'run-items-excluded', } diff --git a/packages/proactive-connect/lib/enums/listSyncStatus.ts b/packages/proactive-connect/lib/enums/listSyncStatus.ts index b9dda66a..833c9410 100644 --- a/packages/proactive-connect/lib/enums/listSyncStatus.ts +++ b/packages/proactive-connect/lib/enums/listSyncStatus.ts @@ -1,9 +1,39 @@ +/** + * Enumeration representing synchronization status between the list content (items) and its data source. + */ export enum SyncStatus { - CONFIGURED = 'configured', - CLEARING = 'clearing', - FETCHING = 'fetching', - PAUSED = 'paused', - CANCELLED = 'cancelled', - COMPLETED = 'completed', - FAILED = 'failed', + /** + * Configuration is complete. + */ + CONFIGURED = 'configured', + + /** + * Data is being cleared. + */ + CLEARING = 'clearing', + + /** + * Data is being fetched. + */ + FETCHING = 'fetching', + + /** + * Synchronization is paused. + */ + PAUSED = 'paused', + + /** + * Synchronization is cancelled. + */ + CANCELLED = 'cancelled', + + /** + * Synchronization is completed. + */ + COMPLETED = 'completed', + + /** + * Synchronization has failed. + */ + FAILED = 'failed', } diff --git a/packages/proactive-connect/lib/enums/sortOrder.ts b/packages/proactive-connect/lib/enums/sortOrder.ts index d7ba7363..36e0ddab 100644 --- a/packages/proactive-connect/lib/enums/sortOrder.ts +++ b/packages/proactive-connect/lib/enums/sortOrder.ts @@ -1,4 +1,14 @@ +/** + * Enumeration representing sorting order. + */ export enum SortOrder { - ASC = 'asc', - DESC = 'desc', + /** + * Ascending order. + */ + ASC = 'asc', + + /** + * Descending order. + */ + DESC = 'desc', } diff --git a/packages/proactive-connect/lib/proactiveConnect.ts b/packages/proactive-connect/lib/proactiveConnect.ts index 00f37423..ca85e891 100644 --- a/packages/proactive-connect/lib/proactiveConnect.ts +++ b/packages/proactive-connect/lib/proactiveConnect.ts @@ -1,15 +1,15 @@ import { AuthenticationType, Client } from '@vonage/server-client'; -import { HTTPMethods } from '@vonage/vetch'; +import { HTTPMethods, VetchOptions } from '@vonage/vetch'; import { FindListItemParams, FindListParams, + ImportFileResponse, List, ListItem, - ListPageResponse, ListItemPageResponse, ListItemResponse, + ListPageResponse, ListResponse, - ImportFileResponse, } from './types'; import pick from 'lodash.pick'; import { readFileSync, writeFileSync } from 'fs'; @@ -17,15 +17,20 @@ import FormData from 'form-data'; const apiListToList = (list: ListResponse): List => { delete list?._links; - return Client.transformers.camelCaseObjectKeys(list, true); + return Client.transformers.camelCaseObjectKeys(list, true) as List; }; const apiItemToItem = (item: ListItemResponse): ListItem => { delete item?._links; // do not deep transform as the data property has to remain the same - return Client.transformers.camelCaseObjectKeys(item); + return Client.transformers.camelCaseObjectKeys(item) as ListItem; }; +/** + * Represents an API client for interacting with the Vonage Proactive Connect + * API. This client provides methods for managing lists, list items, and + * performing import/export operations. + */ export class ProactiveConnect extends Client { public FORM_BOUNDARY = '-------------------------Vonage-Node_SDK'; @@ -39,6 +44,14 @@ export class ProactiveConnect extends Client { 'datasource', ]; + /** + * Retrieves all lists available in the Vonage Proactive Connect API. + * + * @param {FindListParams} params - Optional parameters for pagination and filtering. + * @return {AsyncGenerator} An async generator that yields lists as they are retrieved. + * + * @throws {Error} If there's an issue with the API request. + */ async *findAllLists( params: FindListParams = {}, ): AsyncGenerator { @@ -56,6 +69,14 @@ export class ProactiveConnect extends Client { } while (next); } + /** + * Creates a new list in the Vonage Proactive Connect API. + * + * @param {List} list - The list object representing the list to be created. + * @return {Promise} A promise that resolves to the newly created list. + * + * @throws {Error} If there's an issue with the API request or the list creation fails. + */ async createList(list: List): Promise { const resp = await this.sendPostRequest( `${this.config.proactiveHost}/v0.1/bulk/lists`, @@ -68,11 +89,19 @@ export class ProactiveConnect extends Client { return apiListToList(resp.data); } + /** + * Retrieves a list by its unique identifier from the Vonage Proactive Connect API. + * + * @param {string} listId - The unique identifier of the list to retrieve. + * @return {Promise} A promise that resolves to the retrieved list. + * + * @throws {Error} If there's an issue with the API request or the list retrieval fails. + */ async getListById(listId: string): Promise { const resp = await this.sendGetRequest( `${this.config.proactiveHost}/v0.1/bulk/lists/${listId}`, ); - return apiListToList(resp?.data); + return apiListToList(resp.data); } async updateList(listId: string, list: List): Promise { @@ -87,6 +116,14 @@ export class ProactiveConnect extends Client { return apiListToList(resp.data); } + /** + * Updates an existing list in the Vonage Proactive Connect API by its unique identifier. + * + * @param {string} listId - The unique identifier of the list to update. + * @return {Promise} A promise that resolves to the updated list. + * + * @throws {Error} If there's an issue with the API request or the list update fails. + */ async deleteList(listId: string): Promise { await this.sendDeleteRequest( `${this.config.proactiveHost}/v0.1/bulk/lists/${listId}`, @@ -94,6 +131,14 @@ export class ProactiveConnect extends Client { return true; } + /** + * Clears all data from an existing list in the Vonage Proactive Connect API by its unique identifier. + * + * @param {string} listId - The unique identifier of the list to clear. + * @return {Promise} A promise that resolves to `true` if the list is successfully cleared. + * + * @throws {Error} If there's an issue with the API request or the list clearing fails. + */ async clearList(listId: string): Promise { await this.sendPostRequest( `${this.config.proactiveHost}/v0.1/bulk/lists/${listId}/clear`, @@ -101,6 +146,15 @@ export class ProactiveConnect extends Client { return true; } + /** + * Retrieves all list items from a specific list in the Vonage Proactive Connect API. + * + * @param {string} listId - The unique identifier of the list to retrieve items from. + * @param {FindListItemParams} params - Optional parameters for pagination and filtering. + * @return {AsyncGenerator} An async generator that yields list items as they are retrieved. + * + * @throws {Error} If there's an issue with the API request. + */ async *findAllListItems( listId: string, params: FindListItemParams = {}, @@ -119,6 +173,15 @@ export class ProactiveConnect extends Client { } while (next); } + /** + * Creates a new list item in a specific list of the Vonage Proactive Connect API. + * + * @param {string} listId - The unique identifier of the list to add the item to. + * @param {ListItem} item - The list item object representing the item to be created. + * @return {Promise} A promise that resolves to the newly created list item. + * + * @throws {Error} If there's an issue with the API request or the list item creation fails. + */ async createListItem( listId: string, item: ListItem, @@ -133,6 +196,15 @@ export class ProactiveConnect extends Client { return apiItemToItem(resp.data); } + /** + * Retrieves a specific list item by its unique identifier from a list in the Vonage Proactive Connect API. + * + * @param {string} listId - The unique identifier of the list containing the item. + * @param {string} itemId - The unique identifier of the list item to retrieve. + * @return {Promise} A promise that resolves to the retrieved list item. + * + * @throws {Error} If there's an issue with the API request or the list item retrieval fails. + */ async getListItemById( listId: string, itemId: string, @@ -144,6 +216,16 @@ export class ProactiveConnect extends Client { return apiItemToItem(resp.data); } + /** + * Updates an existing list item in a specific list of the Vonage Proactive Connect API by its unique identifier. + * + * @param {string} listId - The unique identifier of the list containing the item. + * @param {string} itemId - The unique identifier of the list item to update. + * @param {ListItem} item - The list item object representing the updated item. + * @return {Promise} A promise that resolves to the updated list item. + * + * @throws {Error} If there's an issue with the API request or the list item update fails. + */ async updateListItem( listId: string, itemId: string, @@ -159,6 +241,15 @@ export class ProactiveConnect extends Client { return apiItemToItem(resp.data); } + /** + * Deletes a specific list item by its unique identifier from a list in the Vonage Proactive Connect API. + * + * @param {string} listId - The unique identifier of the list containing the item to delete. + * @param {string} itemId - The unique identifier of the list item to delete. + * @return {Promise} A promise that resolves to `true` if the list item is successfully deleted. + * + * @throws {Error} If there's an issue with the API request or the list item deletion fails. + */ async deleteListItem(listId: string, itemId: string): Promise { await this.sendDeleteRequest( `${this.config.proactiveHost}/v0.1/bulk/lists/${listId}/items/${itemId}`, @@ -166,6 +257,15 @@ export class ProactiveConnect extends Client { return true; } + /** + * Downloads a file containing all list items from a specific list in the Vonage Proactive Connect API. + * + * @param {string} listId - The unique identifier of the list to download items from. + * @param {string} file - The path to the file where the list items will be saved. + * @return {Promise} A promise that resolves to `true` if the list items are successfully downloaded and saved to the file. + * + * @throws {Error} If there's an issue with the API request or the file download fails. + */ async downloadListItems(listId: string, file: string): Promise { const resp = await this.sendGetRequest( `${this.config.proactiveHost}/v0.1/bulk/lists/${listId}/items/download`, @@ -175,6 +275,15 @@ export class ProactiveConnect extends Client { return true; } + /** + * Imports list items from a CSV file into a specific list in the Vonage Proactive Connect API. + * + * @param {string} listId - The unique identifier of the list to import items into. + * @param {string} file - The path to the CSV file containing the list items to import. + * @return {Promise} A promise that resolves to an import response containing details on the number of items inserted, updated, and deleted. + * + * @throws {Error} If there's an issue with the API request or the import process fails. + */ async importListItems( listId: string, file: string, @@ -185,9 +294,9 @@ export class ProactiveConnect extends Client { const resp = await this.sendRequest({ url: `${this.config.proactiveHost}/v0.1/bulk/lists/${listId}/items/download`, - body: itemsForm, + data: itemsForm.toString(), method: HTTPMethods.POST, - }); + } as VetchOptions); return resp.data; } diff --git a/packages/proactive-connect/lib/types/event.ts b/packages/proactive-connect/lib/types/event.ts index f7b54467..1ed0231e 100644 --- a/packages/proactive-connect/lib/types/event.ts +++ b/packages/proactive-connect/lib/types/event.ts @@ -1,12 +1,49 @@ -import { EventTypes } from '../enums/eventTypes'; +import { EventTypes } from '../enums'; +/** + * Represents an event that captures various activities or changes in the + * system, such as changes to user subscribe status, the creation of a new + * list based on a response, the invocation of a chat bot agent, or the + * triggering of certain analytics. + */ export type Event = { - occurredAt: string - type: EventTypes - id: string - jobId: string - srcCtx: string - data: unknown - runId: string - recipientId: string -} + /** + * The date and time when the event occurred. + */ + occurredAt: string; + + /** + * The type of the event, which should be one of the values from the 'EventTypes' enum. + */ + type: EventTypes; + + /** + * The unique identifier for the event. + */ + id: string; + + /** + * The unique identifier for the job related to the event. + */ + jobId: string; + + /** + * The name of the segment or matcher related to the event. + */ + srcCtx: string; + + /** + * The data associated with the event (unknown type). + */ + data: unknown; + + /** + * The unique identifier for the run related to the event. + */ + runId: string; + + /** + * The string identifier of a recipient, such as an email or phone number. + */ + recipientId: string; +}; diff --git a/packages/proactive-connect/lib/types/findListItemParams.ts b/packages/proactive-connect/lib/types/findListItemParams.ts index bf31739a..d009f3ce 100644 --- a/packages/proactive-connect/lib/types/findListItemParams.ts +++ b/packages/proactive-connect/lib/types/findListItemParams.ts @@ -1,7 +1,22 @@ -import { SortOrder } from '../enums'; +import { SortOrder } from "../enums"; +/** + * Represents parameters for finding list items. + */ export type FindListItemParams = { - page?: number - pageSize?: number - order?: SortOrder -} + /** + * The page number for pagination. + */ + page?: number; + + /** + * The number of items per page for pagination. + */ + pageSize?: number; + + /** + * The sorting order for the list items. + * Should be one of the values from the 'SortOrder' enum (ASC or DESC). + */ + order?: SortOrder; +}; diff --git a/packages/proactive-connect/lib/types/findListParams.ts b/packages/proactive-connect/lib/types/findListParams.ts index f49ced3c..93bb5125 100644 --- a/packages/proactive-connect/lib/types/findListParams.ts +++ b/packages/proactive-connect/lib/types/findListParams.ts @@ -1,7 +1,22 @@ import { SortOrder } from '../enums'; +/** + * Represents parameters for finding lists. + */ export type FindListParams = { - page?: number - pageSize?: number - order?: SortOrder -} + /** + * The page number for pagination. + */ + page?: number; + + /** + * The number of lists per page for pagination. + */ + pageSize?: number; + + /** + * The sorting order for the lists. + * Should be one of the values from the 'SortOrder' enum (ASC or DESC). + */ + order?: SortOrder; +}; diff --git a/packages/proactive-connect/lib/types/list.ts b/packages/proactive-connect/lib/types/list.ts index 0d33ba21..17cd52d8 100644 --- a/packages/proactive-connect/lib/types/list.ts +++ b/packages/proactive-connect/lib/types/list.ts @@ -3,15 +3,58 @@ import { ListManualDatasource } from './listManualDatasource'; import { ListSalesForceDataSource } from './listSalesForceDataSource'; import { ListSyncStatus } from './listSyncStatus'; +/** + * Represents a list with associated metadata and synchronization details. + */ export type List = { - id: string - createdAt: string - updatedAt: string - itemsCount: number - name: string - description?: string - tags?: Array - syncStatus: ListSyncStatus - attributes?: Array - datasource?: ListSalesForceDataSource | ListManualDatasource -} + /** + * The unique identifier for the list. + */ + id: string; + + /** + * The creation date and time of the list. + */ + createdAt: string; + + /** + * The last update date and time of the list. + */ + updatedAt: string; + + /** + * The number of items in the list. + */ + itemsCount: number; + + /** + * The name of the list. + */ + name: string; + + /** + * The description of the list (optional). + */ + description?: string; + + /** + * An array of tags associated with the list (optional). + */ + tags?: Array; + + /** + * The synchronization status of the list. + */ + syncStatus: ListSyncStatus; + + /** + * An array of attributes associated with the list (optional). + */ + attributes?: Array; + + /** + * The data source for the list, which can be either a Salesforce data source + * or a manual data source. + */ + datasource?: ListSalesForceDataSource | ListManualDatasource; +}; diff --git a/packages/proactive-connect/lib/types/listAttribute.ts b/packages/proactive-connect/lib/types/listAttribute.ts index ce252177..d1734bbb 100644 --- a/packages/proactive-connect/lib/types/listAttribute.ts +++ b/packages/proactive-connect/lib/types/listAttribute.ts @@ -1,5 +1,20 @@ +/** + * Represents an attribute associated with a list. + */ export type ListAttribute = { - name: string - alias?: string - key?: boolean -} + /** + * The name of the attribute. + */ + name: string; + + /** + * An optional alias for the attribute. + */ + alias?: string; + + /** + * Indicates whether the attribute is a key attribute (optional). + * Set to `true` if this attribute should be used as a key to correlate lists. + */ + key?: boolean; +}; diff --git a/packages/proactive-connect/lib/types/listItem.ts b/packages/proactive-connect/lib/types/listItem.ts index ce731792..e7a563e6 100644 --- a/packages/proactive-connect/lib/types/listItem.ts +++ b/packages/proactive-connect/lib/types/listItem.ts @@ -1,7 +1,30 @@ +/** + * Represents an item within a list, with associated metadata and data of a generic type. + * @template DataType - The type of data associated with the list item. + */ export type ListItem = { - id: string - listId: string - createdAt?: string - updatedAt?: string - data: DataType -} + /** + * The unique identifier for the list item. + */ + id: string; + + /** + * The unique identifier of the list to which this item belongs. + */ + listId: string; + + /** + * The creation date and time of the list item (optional). + */ + createdAt?: string; + + /** + * The last update date and time of the list item (optional). + */ + updatedAt?: string; + + /** + * The data associated with the list item. + */ + data: DataType; +}; diff --git a/packages/proactive-connect/lib/types/listManualDatasource.ts b/packages/proactive-connect/lib/types/listManualDatasource.ts index d7e83677..364f31d0 100644 --- a/packages/proactive-connect/lib/types/listManualDatasource.ts +++ b/packages/proactive-connect/lib/types/listManualDatasource.ts @@ -1,3 +1,9 @@ +/** + * Represents a manual data source for a list. + */ export type ListManualDatasource = { - type: 'manual' -} + /** + * The type of the data source, which is always 'manual'. + */ + type: 'manual'; +}; diff --git a/packages/proactive-connect/lib/types/listSalesForceDataSource.ts b/packages/proactive-connect/lib/types/listSalesForceDataSource.ts index e052f522..076e9803 100644 --- a/packages/proactive-connect/lib/types/listSalesForceDataSource.ts +++ b/packages/proactive-connect/lib/types/listSalesForceDataSource.ts @@ -1,5 +1,19 @@ +/** + * Represents a Salesforce data source for a list. + */ export type ListSalesForceDataSource = { - type: 'salesforce' - integrationId: string - soql: string -} + /** + * The type of the data source, which is always 'salesforce'. + */ + type: 'salesforce'; + + /** + * The integration ID defining Salesforce credentials to use for this data source. + */ + integrationId: string; + + /** + * The SOQL query defining which data to fetch from Salesforce. + */ + soql: string; +}; diff --git a/packages/proactive-connect/lib/types/listSyncStatus.ts b/packages/proactive-connect/lib/types/listSyncStatus.ts index 1e8b28a1..ed964c46 100644 --- a/packages/proactive-connect/lib/types/listSyncStatus.ts +++ b/packages/proactive-connect/lib/types/listSyncStatus.ts @@ -1,9 +1,31 @@ -import { SyncStatus } from '../enums/listSyncStatus'; +import { SyncStatus } from '../enums'; +/** + * Represents the synchronization status of a list. + */ export type ListSyncStatus = { - value: SyncStatus - metadataModified: boolean - dataModified: boolean - dirty: boolean - details?: string -} + /** + * The synchronization status value, which should be one of the values from the 'SyncStatus' enum. + */ + value: SyncStatus; + + /** + * Indicates whether the list metadata (definition) is modified since the latest sync. + */ + metadataModified: boolean; + + /** + * Indicates whether one or more list items were added, removed, and/or modified since the latest sync. + */ + dataModified: boolean; + + /** + * Indicates whether the list content or metadata were modified since the last sync. + */ + dirty: boolean; + + /** + * Additional details on the synchronization status (optional). + */ + details?: string; +}; diff --git a/packages/proactive-connect/lib/types/requests/writeListRequest.ts b/packages/proactive-connect/lib/types/requests/writeListRequest.ts index e2c07640..f9c9db1d 100644 --- a/packages/proactive-connect/lib/types/requests/writeListRequest.ts +++ b/packages/proactive-connect/lib/types/requests/writeListRequest.ts @@ -2,15 +2,34 @@ import { List } from '../list'; import { ListManualDatasource } from '../listManualDatasource'; import { ListSalesForceDataSource } from '../listSalesForceDataSource'; -type SaleForceDataSourceResponse = Omit< - ListSalesForceDataSource, - 'integrationId' -> & { - integration_id: string -} +/** + * Represents a response object for a Salesforce data source with modified integration ID. + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ +export type SaleForceDataSourceRequest = Omit< + ListSalesForceDataSource, + 'integrationId' + > & { + /** + * The integration ID defining Salesforce credentials to use for this data source. + */ + integration_id: string; +}; + +/** + * Represents a request object for creating or updating a list with associated metadata. + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type WriteListRequest = Pick< - List, - 'name' | 'description' | 'tags' | 'attributes' -> & { - datasource?: ListManualDatasource | SaleForceDataSourceResponse -} + List, + 'name' | 'description' | 'tags' | 'attributes' + > & { + /** + * The data source for the list, which can be either a manual data source or a Salesforce data source. + */ + datasource?: ListManualDatasource | SaleForceDataSourceRequest; +}; diff --git a/packages/proactive-connect/lib/types/responses/importFileResponse.ts b/packages/proactive-connect/lib/types/responses/importFileResponse.ts index 7be64aab..fd934cd1 100644 --- a/packages/proactive-connect/lib/types/responses/importFileResponse.ts +++ b/packages/proactive-connect/lib/types/responses/importFileResponse.ts @@ -1,5 +1,22 @@ +/** + * Represents the response when importing data from a file. + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type ImportFileResponse = { - inserted?: number - updated?: number - deleted?: number -} + /** + * The number of items successfully inserted during the import process. + */ + inserted?: number; + + /** + * The number of items updated during the import process. + */ + updated?: number; + + /** + * The number of items deleted during the import process. + */ + deleted?: number; +}; diff --git a/packages/proactive-connect/lib/types/responses/listItemPageResponse.ts b/packages/proactive-connect/lib/types/responses/listItemPageResponse.ts index 9da23254..7fb69c2d 100644 --- a/packages/proactive-connect/lib/types/responses/listItemPageResponse.ts +++ b/packages/proactive-connect/lib/types/responses/listItemPageResponse.ts @@ -1,14 +1,47 @@ import { APILinks } from '@vonage/server-client'; -import { SortOrder } from '../../enums/sortOrder'; +import { SortOrder } from '../../enums'; import { ListItemResponse } from './listItemResponse'; +/** + * Represents a paginated response containing a list of items with associated metadata. + * @template DataType - The type of data associated with the list items. + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type ListItemPageResponse = { - page: number - page_size: number - total_items: number - total_pages: number - order: SortOrder - _embedded: { - items: Array> - } -} & APILinks + /** + * The page number of the current page. + */ + page: number; + + /** + * The number of items per page. + */ + page_size: number; + + /** + * The total number of items across all pages. + */ + total_items: number; + + /** + * The total number of pages. + */ + total_pages: number; + + /** + * The sorting order applied to the list items. + */ + order: SortOrder; + + /** + * An embedded object containing an array of list items and their associated data. + */ + _embedded: { + /** + * An array of list item responses with associated data. + */ + items: Array>; + }; +} & APILinks; diff --git a/packages/proactive-connect/lib/types/responses/listItemResponse.ts b/packages/proactive-connect/lib/types/responses/listItemResponse.ts index 8b5c69a4..36e11929 100644 --- a/packages/proactive-connect/lib/types/responses/listItemResponse.ts +++ b/packages/proactive-connect/lib/types/responses/listItemResponse.ts @@ -1,13 +1,29 @@ import { APILinks } from '@vonage/server-client'; import { ListItem } from '../listItem'; -type Optional = Pick, K> & Omit - +/** + * Represents a response object for a list item with associated data. + * @template DataType - The type of data associated with the list item. + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type ListItemResponse = Omit< - ListItem, - 'createdAt' | 'updatedAt' | 'listId' -> & { - updated_at: string - created_at: string - list_id: string -} & Optional + ListItem, + 'createdAt' | 'updatedAt' | 'listId' + > & { + /** + * The creation date and time of the list item. + */ + created_at: string; + + /** + * The last update date and time of the list item. + */ + updated_at: string; + + /** + * The unique identifier of the list to which this item belongs. + */ + list_id: string; +} & APILinks diff --git a/packages/proactive-connect/lib/types/responses/listPageResponse.ts b/packages/proactive-connect/lib/types/responses/listPageResponse.ts index a844fbeb..c15d4f78 100644 --- a/packages/proactive-connect/lib/types/responses/listPageResponse.ts +++ b/packages/proactive-connect/lib/types/responses/listPageResponse.ts @@ -1,14 +1,46 @@ import { APILinks } from '@vonage/server-client'; -import { SortOrder } from '../../enums/sortOrder'; +import { SortOrder } from '../../enums'; import { ListResponse } from './listResponse'; +/** + * Represents a paginated response containing a list of lists with associated metadata. + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type ListPageResponse = { - page: number - page_size: number - total_items: number - total_pages: number - order: SortOrder - _embedded: { - lists: Array - } -} & APILinks + /** + * The page number of the current page. + */ + page: number; + + /** + * The number of lists per page. + */ + page_size: number; + + /** + * The total number of lists across all pages. + */ + total_items: number; + + /** + * The total number of pages. + */ + total_pages: number; + + /** + * The sorting order applied to the lists. + */ + order: SortOrder; + + /** + * An embedded object containing an array of list responses with associated metadata. + */ + _embedded: { + /** + * An array of list responses with associated metadata. + */ + lists: Array; + }; +} & APILinks; diff --git a/packages/proactive-connect/lib/types/responses/listResponse.ts b/packages/proactive-connect/lib/types/responses/listResponse.ts index 4283afa0..f3864575 100644 --- a/packages/proactive-connect/lib/types/responses/listResponse.ts +++ b/packages/proactive-connect/lib/types/responses/listResponse.ts @@ -4,30 +4,76 @@ import { ListSyncStatus } from '../listSyncStatus'; import { ListSalesForceDataSource } from '../listSalesForceDataSource'; import { ListManualDatasource } from '../listManualDatasource'; -type Optional = Pick, K> & Omit - -type SyncStatusResponse = Omit< - ListSyncStatus, - 'metadataModified' | 'dataModified' -> & { - metadata_modified: boolean - data_modified: boolean -} - -type SaleForceDataSourceResponse = Omit< - ListSalesForceDataSource, - 'integrationId' -> & { - integration_id: string -} +/** + * Represents a response object for synchronization status with modified metadata and data flags. + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ +export type SyncStatusResponse = Omit< + ListSyncStatus, + 'metadataModified' | 'dataModified' + > & { + /** + * Indicates whether the list metadata (definition) is modified since the latest sync. + */ + metadata_modified: boolean; + /** + * Indicates whether one or more list items were added, removed, and/or modified since the latest sync. + */ + data_modified: boolean; +}; + +/** + * Represents a response object for a Salesforce data source with modified integration ID. + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ +export type SaleForceDataSourceResponse = Omit< + ListSalesForceDataSource, + 'integrationId' + > & { + /** + * The integration ID defining Salesforce credentials to use for this data source. + */ + integration_id: string; +}; + +/** + * Represents a response object for a list with associated metadata and synchronization details. + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type ListResponse = Omit< - List, - 'createdAt' | 'updatedAt' | 'itemsCount' -> & { - datasource?: ListManualDatasource | SaleForceDataSourceResponse - created_at: string - updated_at: string - items_count: number - sync_status: SyncStatusResponse -} & Optional + List, + 'createdAt' | 'updatedAt' | 'itemsCount' + > & { + /** + * The data source for the list, which can be either a manual data source or a Salesforce data source. + */ + datasource?: ListManualDatasource | SaleForceDataSourceResponse; + + /** + * The creation date and time of the list. + */ + created_at: string; + + /** + * The last update date and time of the list. + */ + updated_at: string; + + /** + * The number of items in the list. + */ + items_count: number; + + /** + * The synchronization status of the list. + */ + sync_status: SyncStatusResponse; +} & APILinks; + diff --git a/packages/proactive-connect/package.json b/packages/proactive-connect/package.json index 5aea76c4..d72bfe5c 100644 --- a/packages/proactive-connect/package.json +++ b/packages/proactive-connect/package.json @@ -1,4 +1,5 @@ { + "$schema": "https://json.schemastore.org/package.json", "name": "@vonage/proactive-connect", "version": "1.6.0", "description": "Send large scale outreach campaigns using any channels available through the Vonage APIs", @@ -11,8 +12,13 @@ "url": "git+https://github.com/Vonage/vonage-node-sdk.git" }, "license": "Apache-2.0", - "author": "Chuck MANCHUCK Reeves ", - "main": "dist/index.ts", + "contributors": [ + { + "name": "Chuck \"MANCHUCK\" Reeves", + "url": "https://github.com/manchuck" + } + ], + "main": "dist/index.js", "types": "dist/index.d.ts", "directories": { "lib": "lib", @@ -24,7 +30,8 @@ "scripts": { "build": "npm run clean && npm run compile", "clean": "npx shx rm -rf dist tsconfig.tsbuildinfo", - "compile": "npx tsc --build --verbose" + "compile": "npx tsc --build --verbose", + "prepublishOnly": "npm run build" }, "dependencies": { "@vonage/server-client": "^1.9.0", diff --git a/packages/proactive-connect/tsconfig.json b/packages/proactive-connect/tsconfig.json index bb376b23..4365c435 100644 --- a/packages/proactive-connect/tsconfig.json +++ b/packages/proactive-connect/tsconfig.json @@ -1,20 +1,25 @@ { - "extends": "../../tsconfig.json", + "$schema": "https://json.schemastore.org/tsconfig", - "compilerOptions": { - "rootDir": "lib", - "outDir": "dist" - }, + "extends": "../../tsconfig.json", - "exclude": ["__tests__", "jest.config.js", "dist"], + "compilerOptions": { + "rootDir": "lib", + "outDir": "dist" + }, - "references": [ - { "path": "../server-client" }, - { "path": "../auth" }, - { "path": "../vetch" } - ], + "exclude": [ + "__tests__", + "dist" + ], - "ts-node": { - "esm": true - } + "references": [ + { "path": "../server-client" }, + { "path": "../auth" }, + { "path": "../vetch" } + ], + + "ts-node": { + "esm": true + } } diff --git a/packages/proactive-connect/typedoc.json b/packages/proactive-connect/typedoc.json new file mode 100644 index 00000000..540b59a3 --- /dev/null +++ b/packages/proactive-connect/typedoc.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "extends": ["../../typedoc.base.json"], + "entryPoints": ["lib/index.ts"], + "name": "Vonage Proactive connect" +} diff --git a/packages/redact/lib/enums/product.ts b/packages/redact/lib/enums/product.ts index c88fdf97..ba393ccc 100644 --- a/packages/redact/lib/enums/product.ts +++ b/packages/redact/lib/enums/product.ts @@ -1,7 +1,29 @@ +/** + * Enum representing different product types for redaction requests. + */ export enum ProductType { - SMS = 'SMS', - Voice = 'Voice', - NumberInsight = 'NumberInsight', - Verify = 'Verify', - VerifySDK = 'VerifySDK', + /** + * Represents the SMS product. + */ + SMS = 'SMS', + + /** + * Represents the Voice product. + */ + Voice = 'Voice', + + /** + * Represents the Number Insight product. + */ + NumberInsight = 'NumberInsight', + + /** + * Represents the Verify product. + */ + Verify = 'Verify', + + /** + * Represents the Verify SDK product. + */ + VerifySDK = 'VerifySDK', } diff --git a/packages/redact/lib/enums/type.ts b/packages/redact/lib/enums/type.ts index 92d699f4..e7862bc2 100644 --- a/packages/redact/lib/enums/type.ts +++ b/packages/redact/lib/enums/type.ts @@ -1,4 +1,14 @@ +/** + * Enum representing different message types for redaction requests. + */ export enum Type { - INBOUND = 'Inbound', - OUTBOUND = 'Outbound', + /** + * Represents an inbound message type. + */ + INBOUND = 'Inbound', + + /** + * Represents an outbound message type. + */ + OUTBOUND = 'Outbound', } diff --git a/packages/redact/lib/interfaces/request/transactionRequest.ts b/packages/redact/lib/interfaces/request/transactionRequest.ts index ce53eb26..c4c88f83 100644 --- a/packages/redact/lib/interfaces/request/transactionRequest.ts +++ b/packages/redact/lib/interfaces/request/transactionRequest.ts @@ -1,7 +1,22 @@ -import { Type, ProductType } from '../../enums/index'; +import { Type, ProductType } from '../../enums'; +/** + * Represents a request to redact a specific message. + */ export interface TransactionRequest { - id: string - product: ProductType - type: Type + /** + * The transaction ID to redact. + */ + id: string; + + /** + * Product name that the ID provided relates to. + * Must be one of: sms, voice, number-insight, verify, verify-sdk, messages. + */ + product: ProductType; + + /** + * Required if redacting SMS data. Must be one of: inbound, outbound. + */ + type: Type; } diff --git a/packages/redact/lib/interfaces/response/errorResponse.ts b/packages/redact/lib/interfaces/response/errorResponse.ts index 3848b70d..23b75066 100644 --- a/packages/redact/lib/interfaces/response/errorResponse.ts +++ b/packages/redact/lib/interfaces/response/errorResponse.ts @@ -1,6 +1,24 @@ +/** + * Represents an error response. + */ export interface ErrorResponse { - type: string - title: string - detail: string - instance: string + /** + * The type of error. + */ + type: string; + + /** + * A short title or summary of the error. + */ + title: string; + + /** + * A detailed description of the error. + */ + detail: string; + + /** + * An instance identifier associated with the error. + */ + instance: string; } diff --git a/packages/redact/lib/redact.ts b/packages/redact/lib/redact.ts index 1933c345..7c5ce1a0 100644 --- a/packages/redact/lib/redact.ts +++ b/packages/redact/lib/redact.ts @@ -1,9 +1,23 @@ import { Client, AuthenticationType } from '@vonage/server-client'; -import { TransactionParams } from './types/index'; +import { TransactionParams } from './types'; +/** + * Represents a client for the Redact API that extends the Vonage Client. + */ export class Redact extends Client { + /** + * The authentication type used for Redact API requests. + */ protected authType = AuthenticationType.BASIC; + /** + * Redacts a specific message using the provided parameters. + * + * @param {TransactionParams} params - Parameters for redacting a message. + * @return {Promise} A Promise that resolves when the redaction is successful. + * + * @throws {Error} If there is an error in processing the redaction request. + */ public async redactMessage(params: TransactionParams): Promise { await this.sendPostRequest( `${this.config.apiHost}/v1/redact/transaction`, diff --git a/packages/redact/lib/types/transactionParams.ts b/packages/redact/lib/types/transactionParams.ts index f55a95be..ac8cbafc 100644 --- a/packages/redact/lib/types/transactionParams.ts +++ b/packages/redact/lib/types/transactionParams.ts @@ -1,7 +1,22 @@ -import { Type, ProductType } from '../enums/index'; +import { Type, ProductType } from '../enums'; +/** + * Represents parameters for a transaction redaction request. + */ export type TransactionParams = { - id: string - product: ProductType - type: Type -} + /** + * The transaction ID to redact. + */ + id: string; + + /** + * Product name that the ID provided relates to. + * Must be one of: sms, voice, number-insight, verify, verify-sdk, messages. + */ + product: ProductType; + + /** + * Required if redacting SMS data. Must be one of: inbound, outbound. + */ + type: Type; +}; diff --git a/packages/redact/package.json b/packages/redact/package.json index b1edfac6..54544737 100644 --- a/packages/redact/package.json +++ b/packages/redact/package.json @@ -1,4 +1,5 @@ { + "$schema": "https://json.schemastore.org/package.json", "name": "@vonage/redact", "version": "1.8.0", "description": "Delete data from the Vonage platform.", @@ -11,7 +12,16 @@ "url": "git+https://github.com/Vonage/vonage-node-sdk.git" }, "license": "Apache-2.0", - "author": "Chuck MANCHUCK Reeves ", + "contributors": [ + { + "name": "Chuck \"MANCHUCK\" Reeves", + "url": "https://github.com/manchuck" + }, + { + "name": "Chris Tankersley", + "url": "https://github.com/dragonmantank" + } + ], "main": "dist/index.js", "types": "dist/index.d.ts", "directories": { @@ -24,7 +34,8 @@ "scripts": { "build": "npm run clean && npm run compile", "clean": "npx shx rm -rf dist tsconfig.tsbuildinfo", - "compile": "npx tsc --build --verbose" + "compile": "npx tsc --build --verbose", + "prepublishOnly": "npm run build" }, "dependencies": { "@vonage/server-client": "^1.9.0" diff --git a/packages/redact/tsconfig.json b/packages/redact/tsconfig.json index e9b438f7..8e8615aa 100644 --- a/packages/redact/tsconfig.json +++ b/packages/redact/tsconfig.json @@ -1,24 +1,25 @@ { - "extends": "../../tsconfig.json", + "$schema": "https://json.schemastore.org/tsconfig", - "compilerOptions": { - "rootDir": "lib", - "outDir": "dist" - }, + "extends": "../../tsconfig.json", - "exclude": [ - "__tests__", - "jest.config.js", - "dist" - ], + "compilerOptions": { + "rootDir": "lib", + "outDir": "dist" + }, - "references": [ - { "path": "../auth" }, - { "path": "../server-client" }, - { "path": "../vetch" } - ], + "exclude": [ + "__tests__", + "dist" + ], - "ts-node": { - "esm": true - } + "references": [ + { "path": "../auth" }, + { "path": "../server-client" }, + { "path": "../vetch" } + ], + + "ts-node": { + "esm": true + } } diff --git a/packages/redact/typedoc.json b/packages/redact/typedoc.json new file mode 100644 index 00000000..5fde9493 --- /dev/null +++ b/packages/redact/typedoc.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "extends": ["../../typedoc.base.json"], + "entryPoints": ["lib/index.ts"], + "name": "Vonage Redact" +} diff --git a/packages/server-client/__tests__/__dataSets__/post.ts b/packages/server-client/__tests__/__dataSets__/post.ts index 4a6376fc..6f0c35c1 100644 --- a/packages/server-client/__tests__/__dataSets__/post.ts +++ b/packages/server-client/__tests__/__dataSets__/post.ts @@ -49,6 +49,7 @@ export default [ fizz: 'buzz', }, ], + form: true, clientMethod: 'sendFormSubmitRequest', parameters: [ `${BASE_URL}/my/path`, diff --git a/packages/server-client/__tests__/client.test.ts b/packages/server-client/__tests__/client.test.ts index 7196efbe..671db4ae 100644 --- a/packages/server-client/__tests__/client.test.ts +++ b/packages/server-client/__tests__/client.test.ts @@ -8,13 +8,10 @@ describe.each(transfomTests)('$label', ({ tests }) => { 'Can $label [using $transformFn]', async ({ transformFn, original, parameters, expected }) => { expect(Client.transformers[transformFn]).toBeDefined(); - const results = Client.transformers[transformFn]( - original, - ...parameters, - ); + const results = Client.transformers[transformFn](original, ...parameters); expect(results).toEqual(expected); - }, + } ); }); @@ -27,7 +24,7 @@ describe.each(requestTests)('$label', ({ tests }) => { .filter(({ error }) => !error) .map((test) => { const request = test.request; - // Add on quey testing + // Add on query testing const url = new URL(`${BASE_URL}${request[0]}`); url.searchParams.append('api_key', API_KEY); url.searchParams.append('api_secret', API_SECRET); @@ -45,6 +42,16 @@ describe.each(requestTests)('$label', ({ tests }) => { authType: AuthenticationType.KEY_SECRET, }; + if (test.form && request[2]) { + const params = new URLSearchParams(request[2]); + params.sort(); + request[2] = params.toString(); + + const keyParams = new URLSearchParams(keyTest.request[2]); + keyParams.sort(); + keyTest.request[2] = keyParams.toString(); + } + const bodyMethods = ['PUT', 'POST', 'PATCH']; const method = request[1]; @@ -59,10 +66,7 @@ describe.each(requestTests)('$label', ({ tests }) => { }, { ...test, - request: [ - `${url.pathname}${url.search}`, - ...request.slice(1), - ], + request: [`${url.pathname}${url.search}`, ...request.slice(1)], authType: AuthenticationType.QUERY_KEY_SECRET, }, bodyMethods.includes(method) ? keyTest : null, @@ -89,7 +93,7 @@ describe.each(requestTests)('$label', ({ tests }) => { const results = await client[clientMethod](...parameters); expect(results).toEqual(expected); expect(nock.isDone()).toBeTruthy(); - }, + } ); if (failureTests.length < 1) { @@ -101,10 +105,10 @@ describe.each(requestTests)('$label', ({ tests }) => { async ({ request, response, clientMethod, parameters, error }) => { scope.intercept(...request).reply(...response); - await expect(() => - client[clientMethod](...parameters), - ).rejects.toThrow(error); + await expect(() => client[clientMethod](...parameters)).rejects.toThrow( + error + ); expect(nock.isDone()).toBeTruthy(); - }, + } ); }); diff --git a/packages/server-client/__tests__/file.test.ts b/packages/server-client/__tests__/file.test.ts index 206ee4ba..2ee3a50a 100644 --- a/packages/server-client/__tests__/file.test.ts +++ b/packages/server-client/__tests__/file.test.ts @@ -5,7 +5,7 @@ import { Auth } from '@vonage/auth'; import { mkdirSync, readFileSync, existsSync } from 'fs'; import { rm } from 'fs/promises'; -const FILE_PATH = `${process.cwd()}/path`; +const FILE_PATH = `${process.cwd()}/test-path`; const key = readFileSync(`${__dirname}/private.test.key`).toString(); @@ -80,4 +80,36 @@ describe('File tests', () => { expect(readFileSync(file).toString()).toEqual(content); expect(nock.isDone()).toBeTruthy(); }); + + test('Can download multiple files', async () => { + const file = `${FILE_PATH}/my-file.txt`; + const content = "Ford, I think I'm a couch"; + + const file2 = `${FILE_PATH}/my-file2.txt`; + const content2 = "I know how you feel."; + + scope + .get(`/v1/files/00000000-0000-0000-0000-000000000001`) + .delay(1000) + .reply(200, content) + .get(`/v1/files/00000000-0000-0000-0000-000000000002`) + .delay(800) + .reply(200, content2); + + expect(existsSync(file)).toBeFalsy(); + expect(existsSync(file2)).toBeFalsy(); + + await Promise.all([ + client.downloadFile('00000000-0000-0000-0000-000000000001', file), + client.downloadFile('00000000-0000-0000-0000-000000000002', file2), + ]); + + expect(existsSync(file)).toBeTruthy(); + expect(readFileSync(file).toString()).toEqual(content); + + expect(existsSync(file2)).toBeTruthy(); + expect(readFileSync(file2).toString()).toEqual(content2); + + expect(nock.isDone()).toBeTruthy(); + }); }); diff --git a/packages/server-client/lib/client.ts b/packages/server-client/lib/client.ts index 346f766b..253e3c3b 100644 --- a/packages/server-client/lib/client.ts +++ b/packages/server-client/lib/client.ts @@ -1,30 +1,49 @@ +import fetch, { Response } from 'node-fetch'; +import AbortError from 'node-fetch'; import { Auth, AuthInterface, AuthParams } from '@vonage/auth'; import { - request as vetchRequest, ResponseTypes, VetchResponse, VetchOptions, HTTPMethods, - Vetch, + ContentType, + VetchError, } from '@vonage/vetch'; -import { AuthenticationType } from './enums/AuthenticationType'; +import { AuthenticationType } from './enums'; import * as transfomers from './transformers'; import debug from 'debug'; -import { ConfigParams } from './types/index'; +import { ConfigParams } from './types'; const log = debug('vonage:server-client'); -export abstract class Client { +export class Client { + /** + * Static property containing utility transformers. + */ public static transformers = transfomers; - protected authType?: AuthenticationType; + /** + * The type of authentication used for the client's requests. + */ + protected authType?: AuthenticationType = AuthenticationType.QUERY_KEY_SECRET; + /** + * The authentication instance responsible for generating authentication headers and query parameters. + */ protected auth: AuthInterface; + /** + * Configuration settings for the client, including default hosts for various services and other request settings. + */ protected config: ConfigParams; + /** + * Creates a new instance of the Client. + * + * @param {AuthInterface | AuthParams} credentials - The authentication credentials or an authentication instance. + * @param {ConfigParams} [options] - Optional configuration settings for the client. + */ constructor(credentials: AuthInterface | AuthParams, options?: ConfigParams) { - // eslint-disable-next-line max-len this.auth = !Object.prototype.hasOwnProperty.call( credentials, 'getQueryParams', @@ -43,11 +62,24 @@ export abstract class Client { } as ConfigParams; } - public async addAuthenticationToRequest( + /** + * Adds the appropriate authentication headers or parameters to the request based on the authentication type. + * + * @param {VetchOptions} request - The request options to which authentication needs to be added. + * @return {Promise} - The request options with the added authentication. + */ + async addAuthenticationToRequest( request: VetchOptions, ): Promise { - let requestPath = 'data'; log(`adding ${this.authType || 'api key/secret'} to request`); + if ( + !Object.values(AuthenticationType).includes( + this.authType as AuthenticationType, + ) + ) { + throw new Error('No authentication type set'); + } + switch (this.authType) { case AuthenticationType.BASIC: request.headers = Object.assign({}, request.headers, { @@ -60,41 +92,41 @@ export abstract class Client { Authorization: await this.auth.createBearerHeader(), }); return request; + } - case AuthenticationType.QUERY_KEY_SECRET: - requestPath = 'params'; - // falls through - case AuthenticationType.KEY_SECRET: - default: + if (this.authType === AuthenticationType.QUERY_KEY_SECRET) { + log(`adding parameters to query string`); + request.params = { + ...(request.params ? request.params : {}), + ...(await this.auth.getQueryParams({})), + }; + return request; } - if (['GET', 'DELETE'].includes(request.method)) { - requestPath = 'params'; + if (typeof request.data === 'string') { + throw new Error('Cannot append auth parameters to body'); } const authParams = await this.auth.getQueryParams({}); - let params = { - ...request[requestPath], + request.data = request.data ?? {}; + + // JSON as default + log(`Adding parameters to body`); + request.data = { + ...request.data, ...authParams, }; - // This is most likely web-form - if ( - !request[requestPath] - && this.authType !== AuthenticationType.QUERY_KEY_SECRET - ) { - requestPath = 'body'; - params = new URLSearchParams({ - ...Object.fromEntries(request.body.entries()), - ...authParams, - }); - } - - request[requestPath] = params; return request; } - public async sendDeleteRequest(url: string): Promise> { + /** + * Sends a DELETE request to the specified URL. + * + * @param {string} url - The URL endpoint for the DELETE request. + * @return {Promise>} - The response from the DELETE request. + */ + async sendDeleteRequest(url: string): Promise> { const request = { url, method: HTTPMethods.DELETE, @@ -103,25 +135,37 @@ export abstract class Client { return await this.sendRequest(request); } - public async sendFormSubmitRequest( + /** + * Sends a POST request with form data to the specified URL. + * + * @param {string} url - The URL endpoint for the POST request. + * @param {Record} [payload] - Optional payload containing form data to send with the POST request. + * @return {Promise>} - The response from the POST request. + */ + async sendFormSubmitRequest( url: string, - payload?: { [key: string]: any }, + payload?: Record, ): Promise> { const request = { url, method: HTTPMethods.POST, - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - }, - ...(payload ? { body: new URLSearchParams(payload) } : {}), + type: ContentType.FORM_URLENCODED, + ...(payload ? { data: payload } : {}), } as VetchOptions; return await this.sendRequest(request); } - public async sendGetRequest( + /** + * Sends a GET request to the specified URL with optional query parameters. + * + * @param {string} url - The URL endpoint for the GET request. + * @param {Record} [queryParams] - Optional query parameters to append to the URL. These should be compatible with Node's URLSearchParams. + * @return {Promise>} - The response from the GET request. + */ + async sendGetRequest( url: string, - queryParams?: { [key: string]: any }, + queryParams?: { [key: string]: unknown }, ): Promise> { const request = { url, @@ -132,51 +176,226 @@ export abstract class Client { return await this.sendRequest(request); } - public async sendPatchRequest( + /** + * Sends a PATCH request to the specified URL with an optional payload. + * + * @param {string} url - The URL endpoint for the PATCH request. + * @param {Record} [payload] - Optional payload to be sent as the body of the PATCH request. + * @return {Promise>} - The response from the PATCH request. + */ + async sendPatchRequest( url: string, - payload?: { [key: string]: any }, + payload?: { [key: string]: unknown }, ): Promise> { return this.sendRequestWithData(HTTPMethods.PATCH, url, payload); } - public async sendPostRequest( + /** + * Sends a POST request to the specified URL with an optional payload. + * + * @param {string} url - The URL endpoint for the POST request. + * @param {Record} [payload] - Optional payload to be sent as the body of the POST request. + * @return {Promise>} - The response from the POST request. + */ + async sendPostRequest( url: string, - payload?: { [key: string]: any }, + payload?: { [key: string]: unknown }, ): Promise> { return this.sendRequestWithData(HTTPMethods.POST, url, payload); } - public sendPutRequest( + /** + * Sends a PUT request to the specified URL with an optional payload. + * + * @param {string} url - The URL endpoint for the PUT request. + * @param {Record} [payload] - Optional payload to be sent as the body of the PUT request. + * @return {Promise>} - The response from the PUT request. + */ + sendPutRequest( url: string, - payload?: { [key: string]: any }, + payload?: { [key: string]: unknown }, ): Promise> { return this.sendRequestWithData(HTTPMethods.PUT, url, payload); } - public async sendRequestWithData( - method: HTTPMethods, + /** + * Sends a request with JSON-encoded data to the specified URL using the provided HTTP method. + * + * @param {HTTPMethods.POST | HTTPMethods.PATCH | HTTPMethods.PUT} method - The HTTP method to be used for the request (only POST, PATCH, or PUT are acceptable). + * @param {string} url - The URL endpoint for the request. + * @param {Record} [payload] - Optional payload to be sent as the body of the request, JSON-encoded. + * @return {Promise>} - The response from the request. + */ + async sendRequestWithData( + method: HTTPMethods.POST | HTTPMethods.PATCH | HTTPMethods.PUT, url: string, - payload?: { [key: string]: any }, + payload?: { [key: string]: unknown }, ): Promise> { const request = { url, method: method, - headers: { - 'Content-Type': 'application/json', - }, + type: ContentType.JSON, ...(payload ? { data: payload } : {}), } as VetchOptions; return await this.sendRequest(request); } - public async sendRequest( + /** + * Sends a request adding necessary headers, handling authentication, and parsing the response. + * + * @param {VetchOptions} request - The options defining the request, including URL, method, headers, and data. + * @return {Promise>} - The parsed response from the request. + */ + async sendRequest(request: VetchOptions): Promise> { + const timeout = request.timeout || this.config.timeout; + const controller = new AbortController(); + const timeoutId: NodeJS.Timeout = setTimeout(() => { + controller.abort(); + }, timeout); + + try { + log('Preparing request', request); + request = await this.prepareRequest(request); + const fetcRequest = { + url: request.url, + method: request.method, + headers: request.headers as Record, + body: this.prepareBody(request), + ...(timeout ? { signal: controller.signal } : {}), + }; + log('Sending request', fetcRequest); + + return await this.parseResponse( + request, + await fetch(request.url, fetcRequest), + ); + } catch (error) { + if (error instanceof AbortError) { + log(`Request timed out after ${timeout}`); + } + throw error; + } finally { + clearTimeout(timeoutId); + } + } + + /** + * Prepares the request with necessary headers, authentication, and query parameters. + * + * @param {VetchOptions} request - The initial request options. + * @return {Promise} - The modified request options. + */ + protected async prepareRequest(request: VetchOptions): Promise { + request.headers = { + ...request.headers, + 'user-agent': [ + `@vonage/server-sdk/3.0.0`, + ` node/${process.version.replace('v', '')}`, + this.config.appendUserAgent ? ` ${this.config.appendUserAgent}` : '', + ].join(), + }; + + switch (request.type) { + case ContentType.FORM_URLENCODED: + request.headers['content-type'] = ContentType.FORM_URLENCODED; + break; + case ContentType.JSON: + request.headers['content-type'] = ContentType.JSON; + break; + } + + request = await this.addAuthenticationToRequest(request); + + const url = new URL(request.url as string); + const params = new URLSearchParams(request.params); + + // copy params into the URL + for (const [param, value] of params.entries()) { + url.searchParams.append(param, value); + } + + request.url = url.toString(); + return request; + } + + /** + * Prepares the body for the request based on the content type. + * + * @param {VetchOptions} request - The request options. + * @return {string | undefined} - The prepared request body as a string or undefined. + */ + protected prepareBody(request: VetchOptions): string | undefined { + request.headers = { + ...request?.headers, + }; + if (!request.data) { + return; + } + + if (request.type === ContentType.JSON) { + return JSON.stringify(request.data); + } + + if (request.type === ContentType.FORM_URLENCODED) { + const requestParams = new URLSearchParams(request.data); + requestParams.sort(); + return requestParams.toString(); + } + + return undefined; + } + + /** + * Parses the response based on its content type. + * + * @template T - The expected type of the parsed response data. + * + * @param {VetchOptions} request - The request options. + * @param {Response} response - The raw response from the request. + * @return {Promise>} - The parsed response. + */ + protected async parseResponse( request: VetchOptions, + response: Response, ): Promise> { - request.timeout = this.config.timeout; - request = await this.addAuthenticationToRequest(request); - const vetch = new Vetch(this.config); - const result = await vetch.request(request); - return result; + let decoded = null; + + if (!response.ok) { + log('Request failed', response); + throw new VetchError( + `Request failed with status code ${response.status}`, + request, + response, + ); + } + + switch (response.headers.get('content-type')) { + case ContentType.FORM_URLENCODED: + decoded = response.body + ? new URLSearchParams(await response.text()) + : ''; + break; + case ContentType.JSON: + decoded = await response.json(); + break; + default: + decoded = await response.text(); + } + + const responseHeaders = {}; + + for (const [header, value] of response.headers.entries()) { + Object.assign(response, header, value); + } + + return { + data: decoded as T, + config: request, + status: response.status, + statusText: response.statusText, + headers: responseHeaders, + request: request, + } as VetchResponse; } } diff --git a/packages/server-client/lib/enums/AuthenticationType.ts b/packages/server-client/lib/enums/AuthenticationType.ts index bfa90b7c..dd34104e 100644 --- a/packages/server-client/lib/enums/AuthenticationType.ts +++ b/packages/server-client/lib/enums/AuthenticationType.ts @@ -1,7 +1,31 @@ +/** + * Enum representing the different types of authentication methods + * supported by the Vonage APIs. + */ export enum AuthenticationType { - BASIC = 'basic', - JWT = 'jwt', - KEY_SECRET = 'key_secret', - QUERY_KEY_SECRET = 'query_key_secret', - SIGNATURE = 'signature', + /** + * @description Basic authentication using a base64-encoded string. + */ + BASIC = 'basic', + + /** + * @description JSON Web Token (JWT) authentication. + */ + JWT = 'jwt', + + /** + * @description Authentication using both API key and secret in the request body. + * @deprecated This method is deprecated. + */ + KEY_SECRET = 'key_secret', + + /** + * @description Authentication using API key and secret in the query parameters. + */ + QUERY_KEY_SECRET = 'query_key_secret', + + /** + * @description HMAC signature-based authentication. + */ + SIGNATURE = 'signature', } diff --git a/packages/server-client/lib/enums/GenericErrorCodes.ts b/packages/server-client/lib/enums/GenericErrorCodes.ts index 1cbf3ee0..ab9d8926 100644 --- a/packages/server-client/lib/enums/GenericErrorCodes.ts +++ b/packages/server-client/lib/enums/GenericErrorCodes.ts @@ -1,21 +1,136 @@ +/** + * Enum representing the different types of generic error codes + * that might be returned by the Vonage APIs. + */ export enum GenericErrors { - LOW_BALANCE = 'low-balance', - UNAUTHORIZED = 'unauthorized', - FORBIDDEN = 'forbidden', - NOT_FOUND = 'not-found', - UNPROVISIONED = 'unprovisioned', - ACCOUNT_SUSPENDED = 'account-suspended', - JWT_EXPIRED = 'jwt-expired', - JWT_REVOKED = 'jwt-revoked', - INVALID_API_KEY = 'invalid-api-key', - INVALID_SIGNATURE = 'invalid-signature', - INVALID_IP = 'invalid-ip', - MULTIPLE_AUTH_METHODS = 'multiple-auth-methods', - INVALID_ID = 'invalid-id', - INVALID_JSON = 'invalid-json', - WRONG_VERB = 'wrong-verb', - ACCEPT_HEADER = 'accept-header', - CONTENT_TYPE_HEADER = 'content-type-header', - UNAVAILABLE_LEGAL = 'unavailable-legal', - APPLICATION_SUSPENDED = 'application-suspended', + /** + * The account has insufficient funds. This request could not be performed + * due to your account balance being low. Top up your account in the Vonage + * Dashboard. + */ + LOW_BALANCE = 'low-balance', + + /** + * The provided credentials are incorrect or missing. You did not provide + * correct credentials. Check your authentication credentials; they can be + * found in the Vonage Dashboard. + */ + UNAUTHORIZED = 'unauthorized', + + /** + * The authenticated user does not have access to the requested resource. Your + * account does not have permission to perform this action. Check that you're + * using the correct credentials and that your account has this feature enabled. + */ + FORBIDDEN = 'forbidden', + + /** + * The requested resource could not be found. The requested resource does not + * exist, or you do not have access to it. Check both the URI that you're + * requesting and your authentication credentials. + */ + NOT_FOUND = 'not-found', + + /** + * The account is not provisioned for the requested service. The credentials + * provided do not have access to the requested product. Check that your API + * key is correct and has been whitelisted. + */ + UNPROVISIONED = 'unprovisioned', + + /** + * The account has been suspended. This account has been suspended. Contact + * support@api.vonage.com for more information. + */ + ACCOUNT_SUSPENDED = 'account-suspended', + + /** + * The provided JWT has expired. The JWT provided has expired. Generate a + * new JWT with an expiration date in the future. + */ + JWT_EXPIRED = 'jwt-expired', + + /** + * The provided JWT has been revoked. The JWT provided has been revoked. + * Generate a new JWT using your private key. + */ + JWT_REVOKED = 'jwt-revoked', + + /** + * The provided API key is invalid. The API key provided does not exist in + * our system, or you do not have access. Modify your request to provide a + * valid API key. + */ + INVALID_API_KEY = 'invalid-api-key', + + /** + * The provided signature is invalid. The signature provided did not + * validate. Check your signature secret and ensure you're following the + * correct signing process. + */ + INVALID_SIGNATURE = 'invalid-signature', + + /** + * The request originates from an unauthorized IP address. The source IP + * address of the request is not in our allow list. Make a request from an + * allowed IP address, or add your current IP to the list of authorized + * addresses. + */ + INVALID_IP = 'invalid-ip', + + /** + * Multiple authentication methods were provided in the request. + * Provide exactly one authentication method. + */ + MULTIPLE_AUTH_METHODS = 'multiple-auth-methods', + + /** + * The provided ID in the request is invalid. The ID provided does not exist + * in our system. Modify your request to provide a valid ID. + */ + INVALID_ID = 'invalid-id', + + /** + * The provided JSON in the request body is invalid. The request body did + * not contain valid JSON. Send a JSON request body, including a + * Content-Type header of application/json. + */ + INVALID_JSON = 'invalid-json', + + /** + * The HTTP verb used in the request is not allowed. This endpoint does not + * support the HTTP verb that you requested. Read the API documentation to + * see which verbs your desired endpoint supports. + */ + WRONG_VERB = 'wrong-verb', + + /** + * The provided Accept header in the request is invalid. Invalid Accept + * header provided. Most Vonage APIs only send back application/json. Check + * the API documentation for the specific API you're working with for a + * complete list of supported data types. + */ + ACCEPT_HEADER = 'accept-header', + + /** + * The provided Content-Type header in the request is invalid. Invalid + * Content-Type header provided. Most Vonage APIs only accept application/ + * json. Check the API documentation for the specific API you're working + * with for a complete list of supported data types. + */ + CONTENT_TYPE_HEADER = 'content-type-header', + + /** + * The requested service is unavailable due to legal reasons. Vonage APIs + * are unavailable in the following areas due to international sanctions: + * Sudan, Syria, Crimea, North Korea, Iran, and Cuba. + */ + UNAVAILABLE_LEGAL = 'unavailable-legal', + + /** + * The application associated with the request has been suspended. This + * application has been suspended. Re-enable the application or create a new + * application to use. + */ + APPLICATION_SUSPENDED = 'application-suspended', } diff --git a/packages/server-client/lib/fileClient.ts b/packages/server-client/lib/fileClient.ts index 551d2f59..3f2b6575 100644 --- a/packages/server-client/lib/fileClient.ts +++ b/packages/server-client/lib/fileClient.ts @@ -1,30 +1,69 @@ import { Client } from './client'; -import { AuthenticationType } from './enums/AuthenticationType'; -import { writeFileSync } from 'fs'; +import { AuthenticationType } from './enums'; import debug from 'debug'; +import { VetchError, HTTPMethods, VetchOptions } from '@vonage/vetch'; +import fetch from 'node-fetch'; +import { createWriteStream } from 'fs'; +import { pipeline } from 'stream/promises'; -const log = debug('vonage:server-client'); +const log = debug('vonage:file-client'); +/** + * A client for downloading files from Vonage. + * + * @extends Client + */ export class FileClient extends Client { protected authType = AuthenticationType.JWT; + protected saveFilePath: string = ''; + + /** + * Downloads a file from Vonage and saves it to a specified path. + * + * @param {string} file - The URL or ID of the file to be downloaded. + * @param {string} path - The path where the downloaded file should be saved. + * + * @throws {Error} Throws an error if the file could not be downloaded or saved. + * + * @return {Promise} Resolves when the file is successfully downloaded and saved. + */ async downloadFile(file: string, path: string): Promise { log(`Downloading file: ${file}`); let fileId = file; try { const fileURL = new URL(file); - fileId = fileURL.pathname.split('/').pop(); + fileId = fileURL.pathname.split('/').pop() || ''; } catch (_) { log(`Not a url`); } log(`File Id ${fileId}`); - const resp = await this.sendGetRequest( - `${this.config.apiHost}/v1/files/${fileId}`, + const request = await this.addAuthenticationToRequest({ + url: `${this.config.apiHost}/v1/files/${fileId}`, + method: HTTPMethods.GET, + } as VetchOptions); + log('File download request', request); + + const response = await fetch( + request.url, + { + method: request.method, + headers: request.headers as Record, + }, ); + log('File download response', response); + if (!response.ok) { + throw new VetchError( + `Unexpected response when downloading file: ${response.statusText}`, + request, + ); + } + log(`Saving to ${path}`); - writeFileSync(path, resp.data); + await pipeline(response.body, createWriteStream(path)); + log('File saved'); } } diff --git a/packages/server-client/lib/transformers.ts b/packages/server-client/lib/transformers.ts index 5b636ed3..ac11bf19 100644 --- a/packages/server-client/lib/transformers.ts +++ b/packages/server-client/lib/transformers.ts @@ -4,8 +4,20 @@ import kebabCase from 'lodash.kebabcase'; import partial from 'lodash.partial'; import isObject from 'lodash.isobject'; +export type TransformFunction = (key: string) => string; + +/** + * Transforms the keys of an object based on a provided transformation function. + * + * @param {TransformFunction} transformFn - The function to transform the object's keys. + * @param {Record} objectToTransform - The object whose keys are to be transformed. + * @param {boolean} [deep=false] - Whether to deeply transform nested object keys. + * @param {boolean} [preserve=false] - Whether to preserve the original object's keys. + * + * @return {Record} A new object with transformed keys. + */ export const transformObjectKeys = ( - transformFn: (key: string | number) => string, + transformFn: TransformFunction, objectToTransform: Record, deep = false, preserve = false, @@ -31,9 +43,9 @@ export const transformObjectKeys = ( isObject(t) ? transformObjectKeys( transformFn, - t as Record, - deep, - preserve, + t as Record, + deep, + preserve, ) : t, ); @@ -42,17 +54,41 @@ export const transformObjectKeys = ( transformedObject[newKey] = transformObjectKeys( transformFn, - value as Record, - deep, - preserve, + value as Record, + deep, + preserve, ); } return transformedObject; }; +/** + * Transforms the keys of an object to camelCase. + * + * @param {Record} objectToTransform - The object whose keys are to be transformed. + * @param {boolean} [deep=false] - Whether to deeply transform nested object keys. + * @param {boolean} [preserve=false] - Whether to preserve the original object's keys. + * @return {Record} A new object with camelCased keys. + */ export const camelCaseObjectKeys = partial(transformObjectKeys, camelCase); +/** + * Transforms the keys of an object to snake_case. + * + * @param {Record} objectToTransform - The object whose keys are to be transformed. + * @param {boolean} [deep=false] - Whether to deeply transform nested object keys. + * @param {boolean} [preserve=false] - Whether to preserve the original object's keys. + * @return {Record} A new object with snake_cased keys. + */ export const snakeCaseObjectKeys = partial(transformObjectKeys, snakeCase); +/** + * Transforms the keys of an object to kebab-case. + * + * @param {Record} objectToTransform - The object whose keys are to be transformed. + * @param {boolean} [deep=false] - Whether to deeply transform nested object keys. + * @param {boolean} [preserve=false] - Whether to preserve the original object's keys. + * @return {Record} A new object with kebab-cased keys. + */ export const kebabCaseObjectKeys = partial(transformObjectKeys, kebabCase); diff --git a/packages/server-client/lib/types/APILink.ts b/packages/server-client/lib/types/APILink.ts index 8827f0dd..34d9f3bc 100644 --- a/packages/server-client/lib/types/APILink.ts +++ b/packages/server-client/lib/types/APILink.ts @@ -1,4 +1,13 @@ +/** + * Represents a link object in the HAL format. + * + * @see {@link https://tools.ietf.org/html/rfc5988} for more details on Web Linking. + * + */ export type APILink = { - href: string - // TODO Add more from RFC 5988? + /** + * The URL of the link. + */ + href: string + // TODO Add more from RFC 5988? } diff --git a/packages/server-client/lib/types/APILinks.ts b/packages/server-client/lib/types/APILinks.ts index 5f8d0176..4581808e 100644 --- a/packages/server-client/lib/types/APILinks.ts +++ b/packages/server-client/lib/types/APILinks.ts @@ -1,11 +1,39 @@ import { APILink } from './APILink'; +/** + * Represents a set of links in the HAL format. + * + * @see {@link https://tools.ietf.org/html/draft-kelly-json-hal-08} for more details on HAL format. + * + */ export type APILinks = { - _links: { - self: APILink - next?: APILink - first?: APILink - last?: APILink - prev?: APILink - } -} + /** + * The set of links. + */ + _links?: { + /** + * The link for the current resource. + */ + self: APILink; + + /** + * The link for the next page of resources. + */ + next?: APILink; + + /** + * The link for the first page of resources. + */ + first?: APILink; + + /** + * The link for the last page of resources. + */ + last?: APILink; + + /** + * The link for the previous page of resources. + */ + prev?: APILink; + }; +}; diff --git a/packages/server-client/lib/types/ConfigParams.ts b/packages/server-client/lib/types/ConfigParams.ts index 2b87972b..07eff2a6 100644 --- a/packages/server-client/lib/types/ConfigParams.ts +++ b/packages/server-client/lib/types/ConfigParams.ts @@ -1,11 +1,50 @@ import { ResponseTypes } from '@vonage/vetch'; + +/** + * Type defining configuration parameters for API requests. + * + * @see {@link https://github.com/vonage/vetch} for more information on ResponseTypes. + */ export type ConfigParams = { + /** + * The host for REST API requests. + */ restHost?: string; + + /** + * The host for general API requests. + */ apiHost?: string; + + /** + * The host for video-related API requests. + */ videoHost?: string; + + /** + * The desired response type for API requests. + * @deprecated The client will now use the `content-type` header to decode the + * response properly + */ responseType?: ResponseTypes; + + /** + * The maximum time, in milliseconds, to wait for API responses. + */ timeout?: number; + + /** + * The host for proactive API requests. + */ proactiveHost?: string; + + /** + * The host for meetings-related API requests. + */ meetingsHost?: string; + + /** + * A string to append to the User-Agent header in API requests. + */ appendUserAgent?: string; }; diff --git a/packages/server-client/package.json b/packages/server-client/package.json index a08eb3be..0de4aa50 100644 --- a/packages/server-client/package.json +++ b/packages/server-client/package.json @@ -1,7 +1,8 @@ { + "$schema": "https://json.schemastore.org/package.json", "name": "@vonage/server-client", "version": "1.9.0", - "description": "Core services related to talking to the Vonage APIs", + "description": "The Vonage Server Client provides core functionalities for interacting with Vonage APIs, ensuring a standardized response regardless of the underlying HTTP adapter.", "homepage": "https://developer.vonage.com", "bugs": { "url": "https://github.com/Vonage/vonage-node-sdk/issues" @@ -11,7 +12,16 @@ "url": "git+https://github.com/Vonage/vonage-node-sdk.git" }, "license": "Apache-2.0", - "author": "Chris Tankersley ", + "contributors": [ + { + "name": "Chris Tankersley", + "url": "https://github.com/dragonmantank" + }, + { + "name": "Chuck \"MANCHUCK\" Reeves", + "url": "https://github.com/manchuck" + } + ], "main": "dist/index.js", "types": "dist/index.d.ts", "directories": { @@ -34,9 +44,16 @@ "lodash.isobject": "3.0.2", "lodash.kebabcase": "^4.1.1", "lodash.partial": "^4.2.1", - "lodash.snakecase": "^4.1.1" + "lodash.snakecase": "^4.1.1", + "node-fetch": "^2" }, "devDependencies": { + "@types/lodash.camelcase": "4.3.7", + "@types/lodash.isobject": "3.0.7", + "@types/lodash.kebabcase": "4.1.7", + "@types/lodash.partial": "4.2.7", + "@types/lodash.snakecase": "4.1.7", + "@types/node-fetch": "2.6.6", "nock": "^13.3.4" }, "publishConfig": { diff --git a/packages/server-client/tsconfig.json b/packages/server-client/tsconfig.json index 5e4237b6..bb6870a4 100644 --- a/packages/server-client/tsconfig.json +++ b/packages/server-client/tsconfig.json @@ -1,23 +1,25 @@ { - "extends": "../../tsconfig.json", + "$schema": "https://json.schemastore.org/tsconfig", - "compilerOptions": { - "rootDir": "lib", - "outDir": "dist" - }, + "extends": "../../tsconfig.json", - "exclude": [ - "__tests__", - "jest.config.js", - "dist" - ], + "compilerOptions": { + "rootDir": "lib", + "outDir": "dist" + }, - "references": [ - { "path": "../auth" }, - { "path": "../vetch" } - ], + "exclude": [ + "__tests__", + "jest.config.js", + "dist" + ], - "ts-node": { - "esm": true - } + "references": [ + { "path": "../auth" }, + { "path": "../vetch" } + ], + + "ts-node": { + "esm": true + } } diff --git a/packages/server-client/typedoc.json b/packages/server-client/typedoc.json new file mode 100644 index 00000000..efa04374 --- /dev/null +++ b/packages/server-client/typedoc.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "extends": ["../../typedoc.base.json"], + "entryPoints": ["lib/index.ts"], + "name": "Vonage Server Client" +} diff --git a/packages/server-sdk/__tests__/server-sdk.test.ts b/packages/server-sdk/__tests__/server-sdk.test.ts index 82fb88a4..aa3b7809 100644 --- a/packages/server-sdk/__tests__/server-sdk.test.ts +++ b/packages/server-sdk/__tests__/server-sdk.test.ts @@ -2,8 +2,8 @@ import { Auth } from '@vonage/auth'; import { Vonage } from '../lib/index'; describe('sdk', () => { - test("client gets created", async () => { - const client = new Vonage(new Auth({apiKey: 'abcd', apiSecret: '1234'})); + test('client gets created', async () => { + const client = new Vonage(new Auth({ apiKey: 'abcd', apiSecret: '1234' })); expect(client).toBeInstanceOf(Vonage); }); }); diff --git a/packages/server-sdk/lib/index.ts b/packages/server-sdk/lib/index.ts index 2a6bbe59..9ec0431a 100644 --- a/packages/server-sdk/lib/index.ts +++ b/packages/server-sdk/lib/index.ts @@ -1 +1 @@ -export { Vonage } from './vonage' +export { Vonage } from './vonage'; diff --git a/packages/server-sdk/lib/vonage.ts b/packages/server-sdk/lib/vonage.ts index 2e95e6e7..3f635749 100644 --- a/packages/server-sdk/lib/vonage.ts +++ b/packages/server-sdk/lib/vonage.ts @@ -14,32 +14,98 @@ import { Verify2 } from '@vonage/verify2'; import { Voice } from '@vonage/voice'; import { Video } from '@vonage/video'; +/** + * Represents the Vonage SDK for interacting with Vonage APIs. + */ export class Vonage { + /** + * The credentials used for authentication. + */ protected credentials: AuthInterface; + + /** + * Optional configuration parameters. + */ protected options: ConfigParams; + /** + * Provides access to the Accounts API. + */ public accounts: Accounts; + + /** + * Provides access to the Applications API. + */ public applications: Applications; + + /** + * Provides access to the Messages API. + */ public messages: Messages; + + /** + * Provides access to the Number Insights API. + */ public numberInsights: NumberInsights; + + /** + * Provides access to the Numbers API. + */ public numbers: Numbers; + + /** + * Provides access to the Pricing API. + */ public pricing: Pricing; + + /** + * Provides access to the Redact API. + */ public redact: Redact; + + /** + * Provides access to the Secrets API. + */ public secrets: Secrets; + + /** + * Provides access to the SMS API. + */ public sms: SMS; + + /** + * Provides access to the Users API. + */ public users: Users; + + /** + * Provides access to the Verify V2 API. + */ public verify2: Verify2; + + /** + * Provides access to the Verify API. + */ public verify: Verify; + + /** + * Provides access to the Voice API. + */ public voice: Voice; public video: Video; + /** + * The credentials used for authentication. + * @param {AuthInterface} credentials - The authentication credentials. + * @param {ConfigParams} [options] - Optional configuration parameters. + */ constructor(credentials: AuthInterface, options?: ConfigParams) { if (typeof credentials.getQueryParams === 'undefined') { credentials = new Auth(credentials); } this.credentials = credentials; - this.options = options; + this.options = options || {}; this.accounts = new Accounts(this.credentials, this.options); this.applications = new Applications(this.credentials, this.options); diff --git a/packages/server-sdk/package.json b/packages/server-sdk/package.json index e29cc056..460e513d 100644 --- a/packages/server-sdk/package.json +++ b/packages/server-sdk/package.json @@ -1,4 +1,5 @@ { + "$schema": "https://json.schemastore.org/package.json", "name": "@vonage/server-sdk", "version": "3.11.0", "description": "Node.js Client for the Vonage API Platform", @@ -11,7 +12,16 @@ "url": "git+https://github.com/Vonage/vonage-node-sdk.git" }, "license": "Apache-2.0", - "author": "Chris Tankersley ", + "contributors": [ + { + "name": "Chris Tankersley", + "url": "https://github.com/dragonmantank" + }, + { + "name": "Chuck \"MANCHUCK\" Reeves", + "url": "https://github.com/manchuck" + } + ], "main": "dist/index.js", "types": "dist/index.d.ts", "directories": { @@ -24,7 +34,8 @@ "scripts": { "build": "npm run clean && npm run compile", "clean": "npx shx rm -rf dist tsconfig.tsbuildinfo", - "compile": "npx tsc --build --verbose" + "compile": "npx tsc --build --verbose", + "prepublishOnly": "npm run build" }, "dependencies": { "@vonage/accounts": "^1.9.0", @@ -45,6 +56,5 @@ }, "publishConfig": { "directory": "dist" - }, - "gitHead": "328f18e5c8a458cb4d06d7955ec2399a6ce6f5d8" + } } diff --git a/packages/server-sdk/tsconfig.json b/packages/server-sdk/tsconfig.json index 2fa978f8..3ea86bde 100644 --- a/packages/server-sdk/tsconfig.json +++ b/packages/server-sdk/tsconfig.json @@ -1,36 +1,37 @@ { - "extends": "../../tsconfig.json", + "$schema": "https://json.schemastore.org/tsconfig", - "compilerOptions": { - "rootDir": "lib", - "outDir": "dist" - }, + "extends": "../../tsconfig.json", - "exclude": [ - "__tests__", - "jest.config.js", - "dist" - ], + "compilerOptions": { + "rootDir": "lib", + "outDir": "dist" + }, - "references": [ - { "path": "../accounts" }, - { "path": "../applications" }, - { "path": "../auth" }, - { "path": "../messages" }, - { "path": "../number-insights" }, - { "path": "../numbers" }, - { "path": "../pricing" }, - { "path": "../server-client" }, - { "path": "../sms" }, - { "path": "../users" }, - { "path": "../redact" }, - { "path": "../verify" }, - { "path": "../verify2" }, - { "path": "../vetch" }, - { "path": "../voice" } - ], + "exclude": [ + "__tests__", + "dist" + ], - "ts-node": { - "esm": true - } + "references": [ + { "path": "../accounts" }, + { "path": "../applications" }, + { "path": "../auth" }, + { "path": "../messages" }, + { "path": "../number-insights" }, + { "path": "../numbers" }, + { "path": "../pricing" }, + { "path": "../server-client" }, + { "path": "../sms" }, + { "path": "../users" }, + { "path": "../redact" }, + { "path": "../verify" }, + { "path": "../verify2" }, + { "path": "../vetch" }, + { "path": "../voice" } + ], + + "ts-node": { + "esm": true + } } diff --git a/packages/server-sdk/typedoc.json b/packages/server-sdk/typedoc.json new file mode 100644 index 00000000..0de76fd7 --- /dev/null +++ b/packages/server-sdk/typedoc.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "extends": ["../../typedoc.base.json"], + "entryPoints": ["lib/index.ts"], + "name": "Vonage Server SDK" +} diff --git a/packages/sms/lib/classes/Error/MessageSendAllFailure.ts b/packages/sms/lib/classes/Error/MessageSendAllFailure.ts index 0fec45ef..b6926a72 100644 --- a/packages/sms/lib/classes/Error/MessageSendAllFailure.ts +++ b/packages/sms/lib/classes/Error/MessageSendAllFailure.ts @@ -1,7 +1,17 @@ -import { SMSMessages } from '../../interfaces'; +import { SMSMessages } from '../../types'; import { SMSFailure } from './SMSFailure'; +/** + * Class representing a failure when sending all SMS messages. + * + * Extends the SMSFailure class and is used to indicate that all SMS messages failed to send. + */ export class MessageSendAllFailure extends SMSFailure { + /** + * Creates an instance of MessageSendAllFailure. + * + * @param {SMSMessages} response - The response containing details about the failed SMS messages. + */ constructor(response: SMSMessages) { super('All SMS messages failed to send', response); } diff --git a/packages/sms/lib/classes/Error/MessageSendPartialFailure.ts b/packages/sms/lib/classes/Error/MessageSendPartialFailure.ts index 0277dee4..03ffea7c 100644 --- a/packages/sms/lib/classes/Error/MessageSendPartialFailure.ts +++ b/packages/sms/lib/classes/Error/MessageSendPartialFailure.ts @@ -1,7 +1,17 @@ -import { SMSMessages } from '../../interfaces'; +import { SMSMessages } from '../../types'; import { SMSFailure } from './SMSFailure'; +/** + * Class representing a partial failure when sending SMS messages. + * + * Extends the SMSFailure class and is used to indicate that some SMS messages failed to send. + */ export class MessageSendPartialFailure extends SMSFailure { + /** + * Creates an instance of MessageSendPartialFailure. + * + * @param {SMSMessages} response - The response containing details about the partially failed SMS messages. + */ constructor(response: SMSMessages) { super('Some SMS messages failed to send', response); } diff --git a/packages/sms/lib/classes/Error/SMSFailure.ts b/packages/sms/lib/classes/Error/SMSFailure.ts index 6dd0de70..a5a964de 100644 --- a/packages/sms/lib/classes/Error/SMSFailure.ts +++ b/packages/sms/lib/classes/Error/SMSFailure.ts @@ -1,28 +1,62 @@ import { SMSStatus } from '../../enums'; -import { SMSMessages, ErrorMessage, Message } from '../../interfaces/index'; +import { SMSMessages, ErrorMessage, Message } from '../../types'; +/** + * Class representing a failure response when sending SMS messages. + * + * Extends the built-in Error class and provides methods for accessing and handling failed SMS messages. + */ export class SMSFailure extends Error { + /** + * The response containing details about the SMS messages. + */ protected response: SMSMessages; + /** + * Creates an instance of SMSFailure. + * + * @param {string} message - The error message. + * @param {SMSMessages} response - The response containing details about the SMS messages. + */ constructor(message: string, response: SMSMessages) { super(message); this.response = response; } + /** + * Retrieves an array of all messages in the response. + * + * @return {Array} An array of all messages in the response. + */ public getMessages(): Array { return (this.response.messages as Array) || []; } + /** + * Retrieves an array of failed messages in the response. + * + * @return {Array} An array of failed messages in the response. + */ public getFailedMessages(): Array { return this.getMessages().filter( ({ status }: ErrorMessage) => status !== SMSStatus.SUCCESS, ); } + /** + * Retrieves the original response containing details about the SMS messages. + * + * @return {SMSMessages} The original response containing details about the SMS messages. + */ public getResponse(): SMSMessages { return this.response; } + /** + * Retrieves an array of successfully sent messages in the response. + * + * @return {Array} An array of successfully sent messages in the response. + */ public getSuccessfulMessages(): Array { return this.getMessages().filter( ({ status }: Message) => status === SMSStatus.SUCCESS, diff --git a/packages/sms/lib/enums/CollectionFormats.ts b/packages/sms/lib/enums/CollectionFormats.ts index d3599cf3..8c82b2e2 100644 --- a/packages/sms/lib/enums/CollectionFormats.ts +++ b/packages/sms/lib/enums/CollectionFormats.ts @@ -1,6 +1,26 @@ +/** + * Collection Formats for API Parameter Serialization. + * + * Defines various collection formats used for serializing API parameters. + */ export const COLLECTION_FORMATS = { + /** + * Comma-separated values collection format. + */ csv: ',', + + /** + * Space-separated values collection format. + */ ssv: ' ', + + /** + * Tab-separated values collection format. + */ tsv: '\t', + + /** + * Pipe-separated values collection format. + */ pipes: '|', }; diff --git a/packages/sms/lib/enums/MessageClassEnum.ts b/packages/sms/lib/enums/MessageClassEnum.ts index b1426ec5..f09a2ccb 100644 --- a/packages/sms/lib/enums/MessageClassEnum.ts +++ b/packages/sms/lib/enums/MessageClassEnum.ts @@ -1,6 +1,26 @@ +/** + * Enumeration representing the possible message classes. + * + * Defines different message classes that can be associated with SMS messages. + */ export enum MessageClassEnum { - NUMBER_0 = 0, - NUMBER_1 = 1, - NUMBER_2 = 2, - NUMBER_3 = 3, + /** + * Class 0: Flash SMS. + */ + NUMBER_0 = 0, + + /** + * Class 1: Immediate display (user should be able to read the message instantly). + */ + NUMBER_1 = 1, + + /** + * Class 2: Mobile equipment-to-mobile equipment (ME-to-ME) communication. + */ + NUMBER_2 = 2, + + /** + * Class 3: SIM card-based storage. + */ + NUMBER_3 = 3, } diff --git a/packages/sms/lib/enums/SMSErrors.ts b/packages/sms/lib/enums/SMSErrors.ts index 078165d9..a9fca15c 100644 --- a/packages/sms/lib/enums/SMSErrors.ts +++ b/packages/sms/lib/enums/SMSErrors.ts @@ -1,22 +1,111 @@ -export enum SMSStatus { - SUCCESS = '0', - THROTTLED = '1', - MISSING_REQUIRED_PARAM = '2', - INVALID_PARAM = '3', - INVALID_CREDENTIALS = '4', - INTERNAL_ERROR = '5', - INVALID_MESSAGE = '6', - BARRED_NUMBER = '7', - PARTNER_ACCOUNT_BARRED = '7', - PARTNER_QUOTA_violation = '9', - TOO_MANY_EXISTING_BINDS = '10', - ACCOUNT_NOT_ENABLED = '11', - MESSAGE_TOO_LONG = '12', - INVALID_SIGNATURE = '14', - INVALID_SENDER_ADDRESS = '15', - INVALID_NETWORK_CODE = '22', - INVALID_CALLBACK_URL = '23', - NON_WHITELISTED_DESTINATION = '29', - SIGNATURE_AND_API_SECRET_DISALLOWED = '32', - NUMBER_DEACTIVATED = '33', +/** + * Enumeration representing possible SMS status codes. + * + * Defines different status codes that can be associated with SMS messages. + * + * @remarks This matches SMSStatus. Since Enums can't be joined, this is here + * to help check valid statuses + */ +export enum SMSErrors { + /** + * Success: The message was sent successfully. + */ + SUCCESS = '0', + + /** + * Throttled: Sending SMS faster than the account limit. + */ + THROTTLED = '1', + + /** + * Missing Required Parameter: One or more required parameters are missing. + */ + MISSING_REQUIRED_PARAM = '2', + + /** + * Invalid Parameter: The value of one or more parameters is invalid. + */ + INVALID_PARAM = '3', + + /** + * Invalid Credentials: API key and/or secret are incorrect, invalid, or disabled. + */ + INVALID_CREDENTIALS = '4', + + /** + * Internal Error: An error occurred while processing the message. + */ + INTERNAL_ERROR = '5', + + /** + * Invalid Message: The platform was unable to process the message. + */ + INVALID_MESSAGE = '6', + + /** + * Barred Number: The number you're trying to send messages to is blocklisted. + */ + BARRED_NUMBER = '7', + + /** + * Partner Account Barred: Your Vonage account has been suspended. + */ + PARTNER_ACCOUNT_BARRED = '8', + + /** + * Partner Quota Violation: Insufficient credit to send the message. + */ + PARTNER_QUOTA_VIOLATION = '9', + + /** + * Too Many Existing Binds: Number of simultaneous connections exceeds account allocation. + */ + TOO_MANY_EXISTING_BINDS = '10', + + /** + * Account Not Enabled For HTTP: Account is not provisioned for the SMS API. + */ + ACCOUNT_NOT_ENABLED = '11', + + /** + * Message Too Long: Message length exceeds the maximum allowed. + */ + MESSAGE_TOO_LONG = '12', + + /** + * Invalid Signature: The supplied signature could not be verified. + */ + INVALID_SIGNATURE = '14', + + /** + * Invalid Sender Address: Using a non-authorized sender ID in the 'from' field. + */ + INVALID_SENDER_ADDRESS = '15', + + /** + * Invalid Network Code: Network code is unrecognized or doesn't match the destination. + */ + INVALID_NETWORK_CODE = '22', + + /** + * Invalid Callback URL: Callback URL is too long or contains illegal characters. + */ + INVALID_CALLBACK_URL = '23', + + /** + * Non-Whitelisted Destination: Vonage account is in demo mode and requires whitelisted numbers. + * This error is returned if you attempt to send a message to a number that isn't in your + * pre-approved destination list. + */ + NON_WHITELISTED_DESTINATION = '29', + + /** + * Signature And API Secret Disallowed: A signed request may not present an API secret. + */ + SIGNATURE_AND_API_SECRET_DISALLOWED = '32', + + /** + * Number Deactivated: The number you're trying to send messages to is deactivated. + */ + NUMBER_DEACTIVATED = '33', } diff --git a/packages/sms/lib/enums/SMSStatus.ts b/packages/sms/lib/enums/SMSStatus.ts index 3dbc42a9..affff8c3 100644 --- a/packages/sms/lib/enums/SMSStatus.ts +++ b/packages/sms/lib/enums/SMSStatus.ts @@ -1,22 +1,111 @@ +/** + * Enumeration representing possible SMS status codes. + * + * Defines different status codes that can be associated with SMS messages. + * + * @remarks This matches SMSErrors. Since Enums can't be joined, this is here + * to help check valid statuses + */ export enum SMSStatus { + /** + * Success: The message was sent successfully. + */ SUCCESS = '0', + + /** + * Throttled: Sending SMS faster than the account limit. + */ THROTTLED = '1', + + /** + * Missing Required Parameter: One or more required parameters are missing. + */ MISSING_REQUIRED_PARAM = '2', + + /** + * Invalid Parameter: The value of one or more parameters is invalid. + */ INVALID_PARAM = '3', + + /** + * Invalid Credentials: API key and/or secret are incorrect, invalid, or disabled. + */ INVALID_CREDENTIALS = '4', + + /** + * Internal Error: An error occurred while processing the message. + */ INTERNAL_ERROR = '5', + + /** + * Invalid Message: The platform was unable to process the message. + */ INVALID_MESSAGE = '6', + + /** + * Barred Number: The number you're trying to send messages to is blocklisted. + */ BARRED_NUMBER = '7', + + /** + * Partner Account Barred: Your Vonage account has been suspended. + */ PARTNER_ACCOUNT_BARRED = '8', - PARTNER_QUOTA_violation = '9', + + /** + * Partner Quota Violation: Insufficient credit to send the message. + */ + PARTNER_QUOTA_VIOLATION = '9', + + /** + * Too Many Existing Binds: Number of simultaneous connections exceeds account allocation. + */ TOO_MANY_EXISTING_BINDS = '10', + + /** + * Account Not Enabled For HTTP: Account is not provisioned for the SMS API. + */ ACCOUNT_NOT_ENABLED = '11', + + /** + * Message Too Long: Message length exceeds the maximum allowed. + */ MESSAGE_TOO_LONG = '12', + + /** + * Invalid Signature: The supplied signature could not be verified. + */ INVALID_SIGNATURE = '14', + + /** + * Invalid Sender Address: Using a non-authorized sender ID in the 'from' field. + */ INVALID_SENDER_ADDRESS = '15', + + /** + * Invalid Network Code: Network code is unrecognized or doesn't match the destination. + */ INVALID_NETWORK_CODE = '22', + + /** + * Invalid Callback URL: Callback URL is too long or contains illegal characters. + */ INVALID_CALLBACK_URL = '23', + + /** + * Non-Whitelisted Destination: Vonage account is in demo mode and requires whitelisted numbers. + * This error is returned if you attempt to send a message to a number that isn't in your + * pre-approved destination list. + */ NON_WHITELISTED_DESTINATION = '29', + + /** + * Signature And API Secret Disallowed: A signed request may not present an API secret. + */ SIGNATURE_AND_API_SECRET_DISALLOWED = '32', + + /** + * Number Deactivated: The number you're trying to send messages to is deactivated. + */ NUMBER_DEACTIVATED = '33', } diff --git a/packages/sms/lib/enums/TypeEnum.ts b/packages/sms/lib/enums/TypeEnum.ts index 3f963223..cdf961dc 100644 --- a/packages/sms/lib/enums/TypeEnum.ts +++ b/packages/sms/lib/enums/TypeEnum.ts @@ -1,5 +1,21 @@ +/** + * Enumeration representing possible message types for SMS. + * + * Defines different message types that can be associated with SMS messages. + */ export enum TypeEnum { - TEXT = 'text', - BINARY = 'binary', - UNICODE = 'unicode', + /** + * Text: The message body contains standard text. + */ + TEXT = 'text', + + /** + * Binary: The message body is in binary format. + */ + BINARY = 'binary', + + /** + * Unicode: The message body is URL-encoded Unicode, valid for various character sets. + */ + UNICODE = 'unicode', } diff --git a/packages/sms/lib/index.ts b/packages/sms/lib/index.ts index 60c2d556..3ce601d6 100644 --- a/packages/sms/lib/index.ts +++ b/packages/sms/lib/index.ts @@ -1,5 +1,4 @@ -export * from './classes/index'; -export * from './enums/index'; -export * from './interfaces/index'; +export * from './classes'; +export * from './enums'; export * from './sms'; -export * from './types/index'; +export * from './types'; diff --git a/packages/sms/lib/interfaces/ErrorMessage.ts b/packages/sms/lib/interfaces/ErrorMessage.ts deleted file mode 100644 index a2c4ee2e..00000000 --- a/packages/sms/lib/interfaces/ErrorMessage.ts +++ /dev/null @@ -1,4 +0,0 @@ -export interface ErrorMessage { - status?: string - errorText?: string -} diff --git a/packages/sms/lib/interfaces/InboundMessage.ts b/packages/sms/lib/interfaces/InboundMessage.ts deleted file mode 100644 index e393c6c7..00000000 --- a/packages/sms/lib/interfaces/InboundMessage.ts +++ /dev/null @@ -1,18 +0,0 @@ -export interface InboundMessage { - 'api-key': string - msisdn: string - to: string - messageId: string - text: string - type: string - keyword: string - 'message-timestamp': string - timestamp: string - nonce: string - concat: string - 'concat-ref': string - 'concat-total': string - 'concat-part': string - data: string - udh: string -} diff --git a/packages/sms/lib/interfaces/Message.ts b/packages/sms/lib/interfaces/Message.ts deleted file mode 100644 index d6ac58b0..00000000 --- a/packages/sms/lib/interfaces/Message.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { SMSMessageResponse } from './Response/index'; - -export interface Message extends SMSMessageResponse { - messageId?: string - remainingBalance?: string - messagePrice?: string - clientRef?: string - accountRef?: string -} diff --git a/packages/sms/lib/interfaces/Request/SMSRequestBody.ts b/packages/sms/lib/interfaces/Request/SMSRequestBody.ts deleted file mode 100644 index 33b5c67d..00000000 --- a/packages/sms/lib/interfaces/Request/SMSRequestBody.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { MessageClassEnum, TypeEnum } from '../../enums/index'; - -export interface SMSRequestBody { - to: string - from: string - text?: string - body?: string - 'type?': TypeEnum - 'ttl?': number - 'client_ref?': string - 'callback?': string - 'message_class?': number - 'udh?': string - 'protocol-id'?: number - 'status-report-req'?: boolean - 'message-class'?: MessageClassEnum - 'client-ref'?: string - 'entity-id'?: string - 'content-id'?: string -} diff --git a/packages/sms/lib/interfaces/Response/DeliveryReceipt.ts b/packages/sms/lib/interfaces/Response/DeliveryReceipt.ts deleted file mode 100644 index 8e51894b..00000000 --- a/packages/sms/lib/interfaces/Response/DeliveryReceipt.ts +++ /dev/null @@ -1,16 +0,0 @@ -export interface DeliveryReceipt { - msisdn?: string - to?: string - networkCode?: string - messageId?: string - price?: string - status?: string - scts?: string - errCode?: string - apiKey?: string - clientRef?: string - messageTimestamp?: string - timestamp?: string - nonce?: string - sig?: string -} diff --git a/packages/sms/lib/interfaces/Response/SMSEmptyResponse.ts b/packages/sms/lib/interfaces/Response/SMSEmptyResponse.ts deleted file mode 100644 index 765ef6d8..00000000 --- a/packages/sms/lib/interfaces/Response/SMSEmptyResponse.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** - * @deprecated there is no subsistution for this - */ -export interface SMSEmptyResponse { - errorCode?: string - errorCodeLabel?: string -} diff --git a/packages/sms/lib/interfaces/Response/SMSErrorMessageResponse.ts b/packages/sms/lib/interfaces/Response/SMSErrorMessageResponse.ts deleted file mode 100644 index 9044a620..00000000 --- a/packages/sms/lib/interfaces/Response/SMSErrorMessageResponse.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { SMSStatus } from '../../enums/SMSErrors'; - -export interface SMSErrorMessageResponse { - status: SMSStatus - 'error-text': string -} diff --git a/packages/sms/lib/interfaces/Response/SMSGeneralResponse.ts b/packages/sms/lib/interfaces/Response/SMSGeneralResponse.ts deleted file mode 100644 index a0f45bb6..00000000 --- a/packages/sms/lib/interfaces/Response/SMSGeneralResponse.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { SMSResponse } from './SMSResponse'; - -/** - * @deprecated please use SMSResponse - */ -export type SMSGeneralResponse = SMSResponse diff --git a/packages/sms/lib/interfaces/Response/SMSMessageResponse.ts b/packages/sms/lib/interfaces/Response/SMSMessageResponse.ts deleted file mode 100644 index f7ced1f7..00000000 --- a/packages/sms/lib/interfaces/Response/SMSMessageResponse.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { SMSStatus } from '../../enums/SMSErrors'; - -export interface SMSMessageResponse { - to: string - 'message-id': string - status: SMSStatus - 'remaining-balance': string - 'message-price': string - network: string - 'client-ref'?: string - 'account-ref'?: string -} diff --git a/packages/sms/lib/interfaces/Response/SMSResponse.ts b/packages/sms/lib/interfaces/Response/SMSResponse.ts deleted file mode 100644 index 4908cbee..00000000 --- a/packages/sms/lib/interfaces/Response/SMSResponse.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { SMSErrorMessageResponse } from './SMSErrorMessageResponse'; -import { SMSMessageResponse } from './SMSMessageResponse'; - -export interface SMSResponse { - 'message-count': number - messages: SMSMessageResponse[] | SMSErrorMessageResponse[] -} diff --git a/packages/sms/lib/interfaces/Response/SendSMSResponse.ts b/packages/sms/lib/interfaces/Response/SendSMSResponse.ts deleted file mode 100644 index b4ccfd2d..00000000 --- a/packages/sms/lib/interfaces/Response/SendSMSResponse.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { SMSResponse } from './SMSResponse'; - -/** - * @deprecated please use SMSResponse - */ -export type SendSMSResponse = SMSResponse diff --git a/packages/sms/lib/interfaces/SMSMessages.ts b/packages/sms/lib/interfaces/SMSMessages.ts deleted file mode 100644 index 52e97b8b..00000000 --- a/packages/sms/lib/interfaces/SMSMessages.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { ErrorMessage } from './ErrorMessage'; -import { Message } from './Message'; -import { SMSResponse } from './Response/index'; - -export interface SMSMessages extends SMSResponse { - messageCount: number - messages: Array -} diff --git a/packages/sms/lib/interfaces/index.ts b/packages/sms/lib/interfaces/index.ts deleted file mode 100644 index b51011f4..00000000 --- a/packages/sms/lib/interfaces/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -export * from './ErrorMessage'; -export * from './InboundMessage'; -export * from './Message'; -export * from './Response/index'; -export * from './Response/index'; -export * from './SMSMessages'; diff --git a/packages/sms/lib/sms.ts b/packages/sms/lib/sms.ts index b6c80e49..1aaef5c3 100644 --- a/packages/sms/lib/sms.ts +++ b/packages/sms/lib/sms.ts @@ -1,26 +1,81 @@ -import { Client } from '@vonage/server-client'; -import { - MessageSendAllFailure, - MessageSendPartialFailure, -} from './classes/index'; -import { SMSMessages, SMSResponse, Message } from './interfaces/index'; -import { SMSParams } from './types/index'; -import { SMSStatus } from './enums/index'; +import { Client, AuthenticationType } from '@vonage/server-client'; +import { MessageSendAllFailure, MessageSendPartialFailure } from './classes'; +import { SMSMessages, SMSResponse, Message, SMSParams } from './types'; +import { SMSStatus } from './enums'; import crypto from 'crypto'; import { AlgorithmTypes } from '@vonage/auth'; +/** + * Client for sending legacy SMS messages using the Vonage API. + * + * @example + * Create a standalone SMS client + * + * ```ts + * import { AlgorithmTypes } from '@vonage/auth'; + * import { SMS } from '@vonage/sms'; + * + * const smsClient = new SMS({ + * apiKey: VONAGE_API_KEY, + * apiSecret: VONAGE_API_SECRET + * secret: { + * secret: VONAGE_SIGNATURE_SECRET + * algorithm: AlgorithmTypes.sha512hmac + * }, + * }); + * ``` + * + * @example + * Create an SMS client from the Vonage client + * + * ```ts + * import { AlgorithmTypes } from '@vonage/auth'; + * import { Vonage } from '@vonage/server-client'; + * + * const vonage = new Vonage({ + * apiKey: VONAGE_API_KEY, + * apiSecret: VONAGE_API_SECRET + * secret: { + * secret: VONAGE_SIGNATURE_SECRET + * algorithm: AlgorithmTypes.sha512hmac + * }, + * }); + * + * const smsClient = vonage.sms; + * ``` + */ export class SMS extends Client { + protected authType?: AuthenticationType = AuthenticationType.KEY_SECRET; + + /** + * Sends an SMS message using the legacy Vonage SMS API. + * + * @param {SMSParams} [params] - The parameters for the SMS message. + * @return {Promise} A Promise that resolves to the response containing details about the sent SMS messages. + * @throws {MessageSendAllFailure} If all SMS messages fail to send. + * @throws {MessageSendPartialFailure} If some SMS messages fail to send. + * @example + * + * ```ts + * const response = await smsClient.send({ + * to: TO_NUMBER, + * from: FROM_NUMBER, + * text: 'Hello from Vonage SMS API', + * }); + * console.log(`Number of messages sent: ${response.messageCount}`);); + * ``` + */ public async send(params?: SMSParams): Promise { const resp = await this.sendPostRequest( `${this.config.restHost}/sms/json`, - Client.transformers.kebabCaseObjectKeys(params), + Client.transformers.kebabCaseObjectKeys(params || {}), ); const messageData: SMSMessages = Client.transformers.camelCaseObjectKeys( resp.data, true, true, - ); + ) as SMSMessages; const totalMessages = messageData.messageCount || 0; const messages = (messageData.messages as Array) || []; @@ -41,9 +96,39 @@ export class SMS extends Client { throw new MessageSendPartialFailure(messageData); } + /** + * Verifies the signature of a request using the specified algorithm and signature secret. + * + * @remarks + * This will not parse the request parameters from the request object, so you will need to do that yourself. + * + * @param {string} signature - The signature to be verified. + * @param {Record} params - The request parameters used to generate the signature. + * @param {string} signatureSecret - The secret key used for generating the signature. + * @param {AlgorithmTypes} algorithm - The algorithm used for generating the signature. + * @return {boolean} `true` if the signature is valid, `false` otherwise. + * @throws {Error} If the provided signature algorithm is not supported. + * + * @example + * ```ts + * const params = Object.assign(request.query, request.body); + * const { sig } = params; + * + * sms.verifySignature( + * sig, + * {}, // request parameters + * VONAGE_API_SIGNATURE_SECRET, + * AlgorithmTypes.md5hash, + * ) === params.sig) { + * console.log("Valid signature"); + * } else { + * console.log("Invalid signature"); + * } + * ``` + */ public verifySignature( signature: string, - params: string | { [key: string]: string }, + params: Record, signatureSecret: string, algorithm: AlgorithmTypes, ): boolean { @@ -58,12 +143,12 @@ export class SMS extends Client { Object.keys(params) .sort() - .forEach((key) => { + .forEach((key: string) => { // replace & and = with _ signedQuery += '&' + key + '=' + params[key].replace(/[&=]/g, '_'); }); - const hashMap = {}; + const hashMap = {} as Record; hashMap[AlgorithmTypes.md5hmac] = 'md5'; hashMap[AlgorithmTypes.sha1hmac] = 'sha1'; hashMap[AlgorithmTypes.sha256hmac] = 'sha256'; diff --git a/packages/sms/lib/types.ts b/packages/sms/lib/types.ts deleted file mode 100644 index 134057a7..00000000 --- a/packages/sms/lib/types.ts +++ /dev/null @@ -1,34 +0,0 @@ -export * from './classes/index'; -export * from './enums/index'; -export * from './interfaces/index'; -export * from './types/index'; - -import { ErrorMessage } from './interfaces/ErrorMessage'; -import { Message } from './interfaces/Message'; -import debug from 'debug'; - -const log = debug('vonage:sms'); - -log('Importing from the types.ts is depreacted and will be removed'); - -/** - * @deprecated no replacement for this - */ -export interface ErrorXml { - messages?: ErrorMessage[] -} - -/** - * @deprecated no replacement for this - */ -export interface ModelError { - messageCount?: string - messages?: ErrorMessage[] -} - -/** - * @deprecated no replacement for this - */ -export interface SMSXml { - messages?: Message[] -} diff --git a/packages/sms/lib/types/ErrorMessage.ts b/packages/sms/lib/types/ErrorMessage.ts new file mode 100644 index 00000000..db15535e --- /dev/null +++ b/packages/sms/lib/types/ErrorMessage.ts @@ -0,0 +1,16 @@ +/** + * Interface representing an error message. + * + * Describes the structure of an error message containing status and error text. + */ +export type ErrorMessage = { + /** + * The status code indicating the error (optional). + */ + status?: string; + + /** + * The error text providing details about the error (optional). + */ + errorText?: string; +} diff --git a/packages/sms/lib/types/InboundMessage.ts b/packages/sms/lib/types/InboundMessage.ts new file mode 100644 index 00000000..fe829b2b --- /dev/null +++ b/packages/sms/lib/types/InboundMessage.ts @@ -0,0 +1,88 @@ +import { TypeEnum } from '../enums'; + +/** + * Interface representing an inbound SMS message. + * + * Describes the structure of an inbound SMS message, including its properties and details. + */ +export type InboundMessage = { + /** + * The Vonage API Key of the receiving account. + */ + 'api-key': string; + + /** + * The phone number that this inbound message was sent from in E.164 format. + */ + msisdn: string; + + /** + * The phone number the message was sent to (virtual number) in E.164 format. + */ + to: string; + + /** + * The unique ID of the inbound message. + */ + messageId: string; + + /** + * The message body for this inbound message. + */ + text: string; + + /** + * The format of the message body. + */ + type: TypeEnum | string; + + /** + * The first word in the message body, converted to uppercase. + */ + keyword: string; + + /** + * The time when Vonage started to push this Inbound SMS to your webhook endpoint. + */ + 'message-timestamp': string; + + /** + * A Unix timestamp representation of 'message-timestamp'. + */ + timestamp: string; + + /** + * A random string that forms part of the signed set of parameters for validation. + */ + nonce: string; + + /** + * Indicates whether this is a concatenated message. + */ + concat: string; + + /** + * The transaction reference for concatenated messages. + */ + 'concat-ref': string; + + /** + * The total number of parts in this concatenated message. + */ + 'concat-total': string; + + /** + * The number of this part in the concatenated message. + */ + 'concat-part': string; + + /** + * The content of this message, if the type is binary. + */ + data: string; + + /** + * The hex encoded User Data Header, if the type is binary. + */ + udh: string; +} diff --git a/packages/sms/lib/types/Message.ts b/packages/sms/lib/types/Message.ts new file mode 100644 index 00000000..f8ac4505 --- /dev/null +++ b/packages/sms/lib/types/Message.ts @@ -0,0 +1,33 @@ +import { SMSMessageResponse } from './Responses'; + +/** + * Type representing an SMS message. + * + * Extends the structure of an SMS message response and includes additional optional properties. + */ +export type Message = SMSMessageResponse & { + /** + * The unique ID of the SMS message (optional). + */ + messageId?: string; + + /** + * Your estimated remaining balance after sending the SMS (optional). + */ + remainingBalance?: string; + + /** + * The estimated cost of the SMS message (optional). + */ + messagePrice?: string; + + /** + * Your client reference for the message (optional). + */ + clientRef?: string; + + /** + * An optional string used to identify separate accounts using the SMS endpoint for billing purposes (optional). + */ + accountRef?: string; +} diff --git a/packages/sms/lib/types/Requests/SMSRequestBody.ts b/packages/sms/lib/types/Requests/SMSRequestBody.ts new file mode 100644 index 00000000..260f25d6 --- /dev/null +++ b/packages/sms/lib/types/Requests/SMSRequestBody.ts @@ -0,0 +1,89 @@ +import { MessageClassEnum, TypeEnum } from '../../enums'; + +/** + * Interface representing the request body for sending an SMS. + * + * Describes the structure of the request body used when sending an SMS message. + */ +export type SMSRequestBody = { + /** + * The recipient's phone number in E.164 format. + */ + to: string; + + /** + * The Alphanumeric senderID (if supported for the destination) or virtual number (specified in E.164 format) that + * the SMS is being sent from. + */ + from: string; + + /** + * The body of the message being sent (optional). + */ + text?: string; + + /** + * Hex-encoded binary data (optional). + */ + body?: string; + + /** + * The format of the message body (optional). + */ + 'type?': TypeEnum; + + /** + * The duration in milliseconds for delivery attempts (optional). + */ + 'ttl?': number; + + /** + * Your own reference for the message (optional). + */ + 'client_ref?': string; + + /** + * The webhook endpoint for the delivery receipt (optional). + */ + 'callback?': string; + + /** + * The Data Coding Scheme value of the message (optional). + */ + 'message_class?': number; + + /** + * Custom Hex-encoded User Data Header (optional). + */ + 'udh?': string; + + /** + * The value of the protocol identifier to use (optional). + */ + 'protocol-id'?: number; + + /** + * Boolean indicating if a Delivery Receipt is requested (optional). + */ + 'status-report-req'?: boolean; + + /** + * The Data Coding Scheme value of the message (optional). + */ + 'message-class'?: MessageClassEnum; + + /** + * Your own reference for the message (optional). + */ + 'client-ref'?: string; + + /** + * A string parameter for regulatory requirements (optional). + */ + 'entity-id'?: string; + + /** + * A string parameter for regulatory requirements (optional). + */ + 'content-id'?: string; +}; diff --git a/packages/sms/lib/interfaces/Request/index.ts b/packages/sms/lib/types/Requests/index.ts similarity index 100% rename from packages/sms/lib/interfaces/Request/index.ts rename to packages/sms/lib/types/Requests/index.ts diff --git a/packages/sms/lib/types/Responses/DeliveryReceipt.ts b/packages/sms/lib/types/Responses/DeliveryReceipt.ts new file mode 100644 index 00000000..d6504e23 --- /dev/null +++ b/packages/sms/lib/types/Responses/DeliveryReceipt.ts @@ -0,0 +1,76 @@ +/** + * Interface representing a delivery receipt for an SMS message. + * + * Describes the structure of a delivery receipt containing information about the message's delivery status. + */ +export type DeliveryReceipt = { + /** + * The recipient's phone number in E.164 format (optional). + */ + msisdn?: string; + + /** + * The SenderID set in the 'from' field of the request (optional). + */ + to?: string; + + /** + * The Mobile Country Code Mobile Network Code (MCCMNC) of the carrier (optional). + */ + networkCode?: string; + + /** + * The Vonage ID for this message (optional). + */ + messageId?: string; + + /** + * The cost of the message (optional). + */ + price?: string; + + /** + * A code explaining the message's delivery status (optional). + */ + status?: string; + + /** + * When the Delivery Receipt was received from the carrier in YYMMDDHHMM format (optional). + */ + scts?: string; + + /** + * The status of the request (optional). + */ + errCode?: string; + + /** + * The API key that sent the SMS (optional). + */ + apiKey?: string; + + /** + * Your client reference for the message (optional). + */ + clientRef?: string; + + /** + * The time when Vonage started to push this Delivery Receipt to your webhook endpoint (optional). + */ + messageTimestamp?: string; + + /** + * A Unix timestamp representation of 'messageTimestamp' (optional). + */ + timestamp?: string; + + /** + * A random string forming part of the signed set of parameters for validation (optional). + */ + nonce?: string; + + /** + * The hash of the request parameters, a timestamp, and the signature secret (optional). + */ + sig?: string; +} diff --git a/packages/sms/lib/types/Responses/SMSEmptyResponse.ts b/packages/sms/lib/types/Responses/SMSEmptyResponse.ts new file mode 100644 index 00000000..ab0d8dc7 --- /dev/null +++ b/packages/sms/lib/types/Responses/SMSEmptyResponse.ts @@ -0,0 +1,16 @@ +/** + * Deprecated interface for an empty SMS response. + * + * @deprecated There is no substitution for this interface. + */ +export type SMSEmptyResponse = { + /** + * The error code, if applicable (optional). + */ + errorCode?: string; + + /** + * A label for the error code, if provided (optional). + */ + errorCodeLabel?: string; +} diff --git a/packages/sms/lib/types/Responses/SMSErrorMessageResponse.ts b/packages/sms/lib/types/Responses/SMSErrorMessageResponse.ts new file mode 100644 index 00000000..81f52269 --- /dev/null +++ b/packages/sms/lib/types/Responses/SMSErrorMessageResponse.ts @@ -0,0 +1,18 @@ +import { SMSStatus } from '../../enums'; + +/** + * Interface representing an SMS error message response. + * + * Describes the structure of a response containing an SMS status and error text. + */ +export type SMSErrorMessageResponse = { + /** + * The SMS status code indicating the error. + */ + status: SMSStatus; + + /** + * The error text providing details about the error. + */ + 'error-text': string; +} diff --git a/packages/sms/lib/types/Responses/SMSGeneralResponse.ts b/packages/sms/lib/types/Responses/SMSGeneralResponse.ts new file mode 100644 index 00000000..05e9ce8e --- /dev/null +++ b/packages/sms/lib/types/Responses/SMSGeneralResponse.ts @@ -0,0 +1,10 @@ +import { SMSResponse } from './SMSResponse'; + +/** + * Deprecated type alias for `SMSResponse`. + * + * Please use `SMSResponse` instead. + * + * @deprecated Use `SMSResponse` instead. + */ +export type SMSGeneralResponse = SMSResponse; diff --git a/packages/sms/lib/types/Responses/SMSMessageResponse.ts b/packages/sms/lib/types/Responses/SMSMessageResponse.ts new file mode 100644 index 00000000..7f549ef6 --- /dev/null +++ b/packages/sms/lib/types/Responses/SMSMessageResponse.ts @@ -0,0 +1,47 @@ +import { SMSStatus } from '../../enums'; +/** + * Interface representing an SMS message response. + * + * Describes the structure of a response containing information about an SMS message's status and details. + */ +export type SMSMessageResponse = { + /** + * The recipient's phone number in E.164 format. + */ + to: string; + + /** + * The unique ID of the SMS message. + */ + 'message-id': string; + + /** + * The status of the SMS message. + */ + status: SMSStatus; + + /** + * Your estimated remaining balance after sending the SMS. + */ + 'remaining-balance': string; + + /** + * The estimated cost of the SMS message. + */ + 'message-price': string; + + /** + * The estimated ID of the network of the recipient. + */ + network: string; + + /** + * Your client reference for the message (optional). + */ + 'client-ref'?: string; + + /** + * An optional string used to identify separate accounts using the SMS endpoint for billing purposes (optional). + */ + 'account-ref'?: string; +} diff --git a/packages/sms/lib/types/Responses/SMSResponse.ts b/packages/sms/lib/types/Responses/SMSResponse.ts new file mode 100644 index 00000000..0168ed57 --- /dev/null +++ b/packages/sms/lib/types/Responses/SMSResponse.ts @@ -0,0 +1,19 @@ +import { SMSErrorMessageResponse } from './SMSErrorMessageResponse'; +import { SMSMessageResponse } from './SMSMessageResponse'; + +/** + * Interface representing an SMS response. + * + * Describes the structure of a response containing information about SMS messages or error messages. + */ +export type SMSResponse = { + /** + * The count of messages included in the response. + */ + 'message-count': number; + + /** + * An array of SMS message responses or SMS error message responses. + */ + messages: (SMSMessageResponse[] | SMSErrorMessageResponse[]); +} diff --git a/packages/sms/lib/types/Responses/SendSMSResponse.ts b/packages/sms/lib/types/Responses/SendSMSResponse.ts new file mode 100644 index 00000000..63d49b05 --- /dev/null +++ b/packages/sms/lib/types/Responses/SendSMSResponse.ts @@ -0,0 +1,10 @@ +import { SMSResponse } from './SMSResponse'; + +/** + * Deprecated type alias for `SMSResponse`. + * + * Please use `SMSResponse` instead. + * + * @deprecated Use `SMSResponse` instead. + */ +export type SendSMSResponse = SMSResponse; diff --git a/packages/sms/lib/interfaces/Response/index.ts b/packages/sms/lib/types/Responses/index.ts similarity index 100% rename from packages/sms/lib/interfaces/Response/index.ts rename to packages/sms/lib/types/Responses/index.ts diff --git a/packages/sms/lib/types/SMSMessages.ts b/packages/sms/lib/types/SMSMessages.ts new file mode 100644 index 00000000..8d9de3a2 --- /dev/null +++ b/packages/sms/lib/types/SMSMessages.ts @@ -0,0 +1,23 @@ +import { ErrorMessage } from './ErrorMessage'; +import { Message } from './Message'; +import { SMSResponse } from './Responses'; + +/** + * Interface representing an SMS response containing multiple messages, including errors. + * + * Extends the structure of an SMS response and includes additional properties for message count + * and an array of messages, which can include both valid messages and error messages. + * + * @extends {SMSResponse} + */ +export type SMSMessages = SMSResponse &{ + /** + * The count of messages included in the response. + */ + messageCount: number; + + /** + * An array of messages, which can include both valid messages and error messages. + */ + messages: Array; +} diff --git a/packages/sms/lib/types/SMSParams.ts b/packages/sms/lib/types/SMSParams.ts index 1aa3a094..c98b9801 100644 --- a/packages/sms/lib/types/SMSParams.ts +++ b/packages/sms/lib/types/SMSParams.ts @@ -1,23 +1,99 @@ -import { MessageClassEnum } from '../enums/MessageClassEnum'; -import { TypeEnum } from '../enums/TypeEnum'; - -export interface SMSParams { - from: string - to: string - text?: string - ttl?: number - statusReportReq?: boolean - callback?: string - messageClass?: MessageClassEnum - type?: TypeEnum - body?: string - udh?: string - protocolId?: number - title?: string - url?: string - validity?: string - clientRef?: string - accountRef?: string - entityId?: string - contentId?: string +import { MessageClassEnum, TypeEnum } from '../enums'; + +/** + * Type representing parameters for sending an SMS. + * + * Describes the structure of parameters that can be used when sending an SMS, including sender, recipient, + * message content, and additional options. + */ +export type SMSParams = { + /** + * The sender's phone number or name. + */ + from: string; + + /** + * The recipient's phone number in E.164 format. + */ + to: string; + + /** + * The text content of the SMS message (optional). + */ + text?: string; + + /** + * The time-to-live (TTL) duration in milliseconds for delivery attempts (optional). + */ + ttl?: number; + + /** + * Indicates if a delivery receipt is requested (optional). + */ + statusReportReq?: boolean; + + /** + * The webhook callback URL for receiving delivery receipts (optional). + */ + callback?: string; + + /** + * The message class (optional). + */ + messageClass?: MessageClassEnum; + + /** + * The format of the message body (optional). + */ + type?: TypeEnum; + + /** + * The binary body of the message (optional). + */ + body?: string; + + /** + * The User Data Header (UDH) for binary messages (optional). + */ + udh?: string; + + /** + * The protocol identifier for binary messages (optional). + */ + protocolId?: number; + + /** + * The title of the message (optional). + */ + title?: string; + + /** + * The URL for WAP Push messages (optional). + */ + url?: string; + + /** + * The validity period of the message (optional). + */ + validity?: string; + + /** + * Your client reference for the message (optional). + */ + clientRef?: string; + + /** + * An optional string used to identify separate accounts using the SMS endpoint for billing purposes (optional). + */ + accountRef?: string; + + /** + * An optional entity ID for regulatory requirements (optional). + */ + entityId?: string; + + /** + * An optional content ID for regulatory requirements (optional). + */ + contentId?: string; } diff --git a/packages/sms/lib/types/index.ts b/packages/sms/lib/types/index.ts index a56b229f..10dd1c9e 100644 --- a/packages/sms/lib/types/index.ts +++ b/packages/sms/lib/types/index.ts @@ -1 +1,7 @@ export * from './SMSParams'; +export * from './ErrorMessage'; +export * from './InboundMessage'; +export * from './Message'; +export * from './Responses'; +export * from './Requests'; +export * from './SMSMessages'; diff --git a/packages/sms/package.json b/packages/sms/package.json index 3bc812ac..2d75d4ae 100644 --- a/packages/sms/package.json +++ b/packages/sms/package.json @@ -1,4 +1,5 @@ { + "$schema": "https://json.schemastore.org/package.json", "name": "@vonage/sms", "version": "1.10.0", "description": "Vonage SMS API SDK package", @@ -11,7 +12,20 @@ "url": "git+https://github.com/Vonage/vonage-node-sdk.git" }, "license": "Apache-2.0", - "author": "Kelly J Andrews ", + "contributors": [ + { + "name": "Kelly J Andrews", + "url": "https://github.com/kellyjandrews" + }, + { + "name": "Chris Tankersley", + "url": "https://github.com/dragonmantank" + }, + { + "name": "Chuck \"MANCHUCK\" Reeves", + "url": "https://github.com/manchuck" + } + ], "main": "dist/index.js", "types": "dist/index.d.ts", "directories": { @@ -24,11 +38,11 @@ "scripts": { "build": "npm run clean && npm run compile", "clean": "npx shx rm -rf dist tsconfig.tsbuildinfo", - "compile": "npx tsc --build --verbose" + "compile": "npx tsc --build --verbose", + "prepublishOnly": "npm run build" }, "dependencies": { - "@vonage/server-client": "^1.9.0", - "debug": "^4.3.4" + "@vonage/server-client": "^1.9.0" }, "devDependencies": { "@vonage/auth": "^1.7.0", @@ -36,6 +50,5 @@ }, "publishConfig": { "directory": "dist" - }, - "gitHead": "328f18e5c8a458cb4d06d7955ec2399a6ce6f5d8" + } } diff --git a/packages/sms/tsconfig.json b/packages/sms/tsconfig.json index 6791c6b6..4365c435 100644 --- a/packages/sms/tsconfig.json +++ b/packages/sms/tsconfig.json @@ -1,24 +1,25 @@ { - "extends": "../../tsconfig.json", + "$schema": "https://json.schemastore.org/tsconfig", - "compilerOptions": { - "rootDir": "lib", - "outDir": "dist" - }, + "extends": "../../tsconfig.json", - "exclude": [ - "__tests__", - "jest.config.js", - "dist" - ], + "compilerOptions": { + "rootDir": "lib", + "outDir": "dist" + }, - "references": [ - { "path": "../server-client" }, - { "path": "../auth" }, - { "path": "../vetch" } - ], + "exclude": [ + "__tests__", + "dist" + ], - "ts-node": { - "esm": true - } + "references": [ + { "path": "../server-client" }, + { "path": "../auth" }, + { "path": "../vetch" } + ], + + "ts-node": { + "esm": true + } } diff --git a/packages/sms/typedoc.json b/packages/sms/typedoc.json new file mode 100644 index 00000000..cf46ce53 --- /dev/null +++ b/packages/sms/typedoc.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "extends": ["../../typedoc.base.json"], + "entryPoints": ["lib/index.ts"], + "name": "Vonage SMS" +} diff --git a/packages/subaccounts/lib/subaccount.ts b/packages/subaccounts/lib/subaccount.ts index bed3264f..831e2a59 100644 --- a/packages/subaccounts/lib/subaccount.ts +++ b/packages/subaccounts/lib/subaccount.ts @@ -20,11 +20,20 @@ import { } from './types'; const apiToSubAccount = (subAccount: SubAccountResponse): SubAccount => - Client.transformers.camelCaseObjectKeys(subAccount, true); + Client.transformers.camelCaseObjectKeys(subAccount, true) as SubAccount; +/** + * Represents a client for interacting with Vonage Subaccounts API. This class provides methods + * for managing subaccounts, credit transfers, balance transfers, and number transfers. + */ export class SubAccounts extends Client { protected authType = AuthenticationType.BASIC; + /** + * Retrieves a page of subaccounts associated with the primary account. + * + * @return {Promise} A promise that resolves to a page of subaccount information. + */ async getSubAccountPage(): Promise { const resp = await this.sendGetRequest( `${this.config.apiHost}/accounts/${this.auth.apiKey}/subaccounts`, @@ -33,18 +42,34 @@ export class SubAccounts extends Client { return resp.data; } + /** + * Retrieves a list of subaccounts associated with the primary account. + * + * @return {Promise>} A promise that resolves to an array of subaccount information. + */ async listSubAccounts(): Promise> { const resp = await this.getSubAccountPage(); return resp._embedded.subaccounts.map(apiToSubAccount); } + /** + * Retrieves information about the primary account associated with the subaccounts. + * + * @return {Promise} A promise that resolves to information about the primary account. + */ async getPrimaryAccount(): Promise { const resp = await this.getSubAccountPage(); return Client.transformers.camelCaseObjectKeys( resp._embedded.primary_account, - ); + ) as Account; } + /** + * Creates a new subaccount under the primary account. + * + * @param {SubAccountCreateParameters} subAccount - The parameters for creating the subaccount. + * @return {Promise} A promise that resolves to the created subaccount information. + */ async createSubAccount( subAccount: SubAccountCreateParameters, ): Promise { @@ -56,6 +81,12 @@ export class SubAccounts extends Client { return apiToSubAccount(resp.data); } + /** + * Retrieves information about a specific subaccount by its ID. + * + * @param {string} subAccountId - The ID of the subaccount to retrieve. + * @return {Promise} A promise that resolves to the subaccount information. + */ async getSubAccount(subAccountId: string): Promise { const resp = await this.sendGetRequest( `${this.config.apiHost}/accounts/${this.auth.apiKey}/subaccounts/${subAccountId}`, @@ -64,6 +95,13 @@ export class SubAccounts extends Client { return apiToSubAccount(resp.data); } + /** + * Modifies one or more properties of a specific subaccount. + * + * @param {string} subAccountId - The ID of the subaccount to modify. + * @param {SubAccountModifyParameters} params - The parameters for modifying the subaccount. + * @return {Promise} A promise that resolves to the modified subaccount information. + */ async updateSubAccount( subAccountId: string, params: SubAccountModifyParameters, @@ -76,6 +114,12 @@ export class SubAccounts extends Client { return apiToSubAccount(resp.data); } + /** + * Retrieves a list of credit transfers that have taken place for a primary account within a specified time period. + * + * @param {CreditTransferListParameters} params - The parameters for filtering the list of credit transfers. + * @return {Promise>} A promise that resolves to an array of credit transfer information. + */ async listCreditTransfers( params: CreditTransferListParameters, ): Promise> { @@ -85,10 +129,16 @@ export class SubAccounts extends Client { ); return resp.data._embedded.credit_transfers.map((transfer) => - Client.transformers.camelCaseObjectKeys(transfer), + Client.transformers.camelCaseObjectKeys(transfer) as CreditTransfer, ); } + /** + * Transfers credit limit between a primary account and one of its subaccounts. + * + * @param {CreditTransferParameters} params - The parameters for transferring credit. + * @return {Promise} A promise that resolves to information about the credit transfer. + */ async transferCredit( params: CreditTransferParameters, ): Promise { @@ -97,9 +147,15 @@ export class SubAccounts extends Client { Client.transformers.snakeCaseObjectKeys(params), ); - return Client.transformers.camelCaseObjectKeys(resp.data); + return Client.transformers.camelCaseObjectKeys(resp.data) as CreditTransfer; } + /** + * Retrieves a list of balance transfers that have taken place for a primary account within a specified time period. + * + * @param {BalanceTransferListParameters} params - The parameters for filtering balance transfers. + * @return {Promise>} A promise that resolves to an array of balance transfer information. + */ async listBalanceTransfers( params: BalanceTransferListParameters, ): Promise> { @@ -109,10 +165,16 @@ export class SubAccounts extends Client { ); return resp.data._embedded.balance_transfers.map((transfer) => - Client.transformers.camelCaseObjectKeys(transfer), + Client.transformers.camelCaseObjectKeys(transfer) as BalanceTransfer, ); } + /** + * Transfers balance between a primary account and one of its subaccounts. + * + * @param {BalanceTransferParameters} params - The parameters for the balance transfer. + * @return {Promise} A promise that resolves to the details of the balance transfer. + */ async transferBalance( params: BalanceTransferParameters, ): Promise { @@ -121,9 +183,17 @@ export class SubAccounts extends Client { Client.transformers.snakeCaseObjectKeys(params), ); - return Client.transformers.camelCaseObjectKeys(resp.data); + return Client.transformers.camelCaseObjectKeys( + resp.data, + ) as BalanceTransfer; } + /** + * Transfers a phone number from one account to another. + * + * @param {NumberTransfer} params - The parameters for the number transfer. + * @return {Promise} A promise that resolves to the details of the number transfer. + */ async transferNumber(params: NumberTransfer): Promise { const resp = await this.sendPostRequest( `${this.config.apiHost}/accounts/${this.auth.apiKey}/transfer-number`, diff --git a/packages/subaccounts/lib/types/account.ts b/packages/subaccounts/lib/types/account.ts index 634e0d74..39fb02a9 100644 --- a/packages/subaccounts/lib/types/account.ts +++ b/packages/subaccounts/lib/types/account.ts @@ -1,8 +1,35 @@ +/** + * Type definition representing an account, which includes properties such as + * `apiKey`, `name`, `createdAt`, `suspended`, `balance`, and `creditLimit`. + */ export type Account = { + /** + * The API key associated with the account. + */ apiKey: string; + + /** + * The name of the account. + */ name: string; + + /** + * The creation date and time of the account. + */ createdAt: string; + + /** + * The suspension status of the account. + */ suspended: boolean; + + /** + * The balance of the account. + */ balance: number; + + /** + * The credit limit of the account. + */ creditLimit: number; }; diff --git a/packages/subaccounts/lib/types/balanceTransfer.ts b/packages/subaccounts/lib/types/balanceTransfer.ts index 3b70cb24..00bb2fc5 100644 --- a/packages/subaccounts/lib/types/balanceTransfer.ts +++ b/packages/subaccounts/lib/types/balanceTransfer.ts @@ -1,8 +1,35 @@ +/** + * Type definition representing a balance transfer, which includes properties + * such as `balanceTransferId`, `amount`, `from`, `to`, `reference`, and `createdAt`. + */ export type BalanceTransfer = { + /** + * The unique identifier for the balance transfer. + */ balanceTransferId: string; + + /** + * The amount of the balance transfer. + */ amount: number; + + /** + * The source account from which the balance is transferred. + */ from: string; + + /** + * The destination account to which the balance is transferred. + */ to: string; + + /** + * A reference for the balance transfer. + */ reference: string; + + /** + * The date and time when the balance transfer was executed. + */ createdAt: string; }; diff --git a/packages/subaccounts/lib/types/creditTransfer.ts b/packages/subaccounts/lib/types/creditTransfer.ts index f04131f2..c3655b5a 100644 --- a/packages/subaccounts/lib/types/creditTransfer.ts +++ b/packages/subaccounts/lib/types/creditTransfer.ts @@ -1,8 +1,35 @@ +/** + * Type definition representing a credit transfer, which includes properties such as `creditTransferId`, `amount`, + * `from`, `to`, `reference`, and `createdAt`. + */ export type CreditTransfer = { + /** + * The unique identifier for the credit transfer. + */ creditTransferId: string; + + /** + * The amount of the credit transfer. + */ amount: number; + + /** + * The source account from which the credit is transferred. + */ from: string; + + /** + * The destination account to which the credit is transferred. + */ to: string; + + /** + * A reference for the credit transfer. + */ reference: string; + + /** + * The date and time when the credit transfer was executed. + */ createdAt: string; }; diff --git a/packages/subaccounts/lib/types/numberTransfer.ts b/packages/subaccounts/lib/types/numberTransfer.ts index 44fd41b2..ef93034e 100644 --- a/packages/subaccounts/lib/types/numberTransfer.ts +++ b/packages/subaccounts/lib/types/numberTransfer.ts @@ -1,6 +1,25 @@ +/** + * Type definition representing a number transfer, which includes properties such as `number`, `country`, `from`, and + * `to`. + */ export type NumberTransfer = { + /** + * The number being transferred. + */ number: string; + + /** + * The two-character country code in ISO 3166-1 alpha-2 format. + */ country: string; + + /** + * The source account from which the number is transferred. + */ from: string; + + /** + * The destination account to which the number is transferred. + */ to: string; }; diff --git a/packages/subaccounts/lib/types/parameters/balanceTransferListParameters.ts b/packages/subaccounts/lib/types/parameters/balanceTransferListParameters.ts index e9606479..d19070c4 100644 --- a/packages/subaccounts/lib/types/parameters/balanceTransferListParameters.ts +++ b/packages/subaccounts/lib/types/parameters/balanceTransferListParameters.ts @@ -1,5 +1,19 @@ +/** + * Type definition for parameters used to retrieve a list of balance transfers for a primary account. + */ export type BalanceTransferListParameters = { + /** + * The start date of the retrieval period. + */ startDate: string; + + /** + * The end date of the retrieval period. If absent, all transfers until now are returned. + */ endDate?: string; + + /** + * Subaccount to filter by. You may send this multiple times to filter on multiple subaccounts. + */ subaccount?: string; }; diff --git a/packages/subaccounts/lib/types/parameters/balanceTransferParameters.ts b/packages/subaccounts/lib/types/parameters/balanceTransferParameters.ts index b6abec3e..57f63a7e 100644 --- a/packages/subaccounts/lib/types/parameters/balanceTransferParameters.ts +++ b/packages/subaccounts/lib/types/parameters/balanceTransferParameters.ts @@ -1,6 +1,24 @@ +/** + * Type definition for parameters used to transfer balance between accounts. + */ export type BalanceTransferParameters = { + /** + * The account ID from which the balance is transferred. + */ from: string; + + /** + * The account ID to which the balance is transferred. + */ to: string; + + /** + * The amount of balance to transfer. + */ amount: string; + + /** + * (Optional) A reference for the balance transfer. + */ reference?: string; }; diff --git a/packages/subaccounts/lib/types/parameters/creditTransferListParameters.ts b/packages/subaccounts/lib/types/parameters/creditTransferListParameters.ts index ba2a2606..19f46169 100644 --- a/packages/subaccounts/lib/types/parameters/creditTransferListParameters.ts +++ b/packages/subaccounts/lib/types/parameters/creditTransferListParameters.ts @@ -1,5 +1,19 @@ +/** + * Type definition for parameters used to retrieve a list of credit transfers for a primary account. + */ export type CreditTransferListParameters = { + /** + * The start date of the retrieval period. + */ startDate: string; + + /** + * (Optional) The end date of the retrieval period. If absent, all transfers until now are returned. + */ endDate?: string; + + /** + * (Optional) Subaccount to filter by. You may send this multiple times to filter on multiple subaccounts. + */ sub?: string; }; diff --git a/packages/subaccounts/lib/types/parameters/creditTransferParameters.ts b/packages/subaccounts/lib/types/parameters/creditTransferParameters.ts index 44f36833..ce914e15 100644 --- a/packages/subaccounts/lib/types/parameters/creditTransferParameters.ts +++ b/packages/subaccounts/lib/types/parameters/creditTransferParameters.ts @@ -1,6 +1,24 @@ +/** + * Type definition for parameters used to perform a credit transfer between accounts. + */ export type CreditTransferParameters = { + /** + * The account ID from which the credit is transferred. + */ from: string; + + /** + * The account ID to which the credit is transferred. + */ to: string; + + /** + * The amount of credit to transfer. + */ amount: string; + + /** + * (Optional) A reference for the credit transfer. + */ reference?: string; }; diff --git a/packages/subaccounts/lib/types/parameters/subAccountCreateParameters.ts b/packages/subaccounts/lib/types/parameters/subAccountCreateParameters.ts index 5e63520e..f119a6cb 100644 --- a/packages/subaccounts/lib/types/parameters/subAccountCreateParameters.ts +++ b/packages/subaccounts/lib/types/parameters/subAccountCreateParameters.ts @@ -1,5 +1,19 @@ +/** + * Type definition for parameters used to create a subaccount for a primary account. + */ export type SubAccountCreateParameters = { + /** + * Name of the subaccount. + */ name: string; + + /** + * API secret of the subaccount. + */ secret: string; + + /** + * Flag indicating whether to use the primary account balance (true) or not (false). + */ usePrimaryAccountBalance: boolean; }; diff --git a/packages/subaccounts/lib/types/parameters/subAccountModifyParameters.ts b/packages/subaccounts/lib/types/parameters/subAccountModifyParameters.ts index 17cacf8c..f5e091ad 100644 --- a/packages/subaccounts/lib/types/parameters/subAccountModifyParameters.ts +++ b/packages/subaccounts/lib/types/parameters/subAccountModifyParameters.ts @@ -1,4 +1,14 @@ +/** + * Type definition for parameters used to modify a subaccount's properties. + */ export type SubAccountModifyParameters = { + /** + * (Optional) Indicates whether the subaccount should be suspended (true) or not (false). + */ suspended?: boolean; + + /** + * (Optional) New name for the subaccount. + */ name?: string; }; diff --git a/packages/subaccounts/lib/types/parameters/transferListParameters.ts b/packages/subaccounts/lib/types/parameters/transferListParameters.ts index b6ac64de..e6f97019 100644 --- a/packages/subaccounts/lib/types/parameters/transferListParameters.ts +++ b/packages/subaccounts/lib/types/parameters/transferListParameters.ts @@ -1,5 +1,19 @@ +/** + * Type definition for parameters used to retrieve a list of transfers for a primary account. + */ export type TransferListParameters = { + /** + * The start date of the retrieval period. + */ startDate: string; + + /** + * (Optional) The end date of the retrieval period. If absent, all transfers until now are returned. + */ endDate?: string; + + /** + * (Optional) Subaccount to filter by. You may send this multiple times to filter on multiple subaccounts. + */ subAccount?: string; }; diff --git a/packages/subaccounts/lib/types/requests/subAccountCreateRequest.ts b/packages/subaccounts/lib/types/requests/subAccountCreateRequest.ts index d0a0b03a..ecb99dd3 100644 --- a/packages/subaccounts/lib/types/requests/subAccountCreateRequest.ts +++ b/packages/subaccounts/lib/types/requests/subAccountCreateRequest.ts @@ -1,5 +1,13 @@ -import { SubAccountCreateParameters } from '../parameters/subAccountCreateParameters'; +import { SubAccountCreateParameters } from '../parameters'; +/** + * Type definition for the request used to create a subaccount for a primary account. + * It combines the `use_primary_account_balance` property with the properties from `SubAccountCreateParameters` + * while omitting the `usePrimaryAccountBalance` property. + */ export type SubAccountCreateRequest = { + /** + * Flag indicating whether to use the primary account balance (true) or not (false). + */ use_primary_account_balance: boolean; } & Omit; diff --git a/packages/subaccounts/lib/types/responses/accountResponse.ts b/packages/subaccounts/lib/types/responses/accountResponse.ts index 426bd64c..99df0fbd 100644 --- a/packages/subaccounts/lib/types/responses/accountResponse.ts +++ b/packages/subaccounts/lib/types/responses/accountResponse.ts @@ -1,9 +1,34 @@ import { SubAccount } from '../subAccount'; +/** + * Type definition for the response representing an account, which includes + * properties such as `api_key`, `created_at`, `balance`, and `credit_limit`. + * This type combines properties from the account response with the properties + * of a subaccount (excluding specific subaccount-related properties). + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type AccountResponse = { + /** + * The API key associated with the account. + */ api_key: string; + + /** + * The creation date and time of the account. + */ created_at: string; + + /** + * The balance of the account. + */ balance: number; + + /** + * The credit limit of the account. + */ credit_limit: number; } & Omit< SubAccount, @@ -12,4 +37,4 @@ export type AccountResponse = { | 'usePrimaryAccountBalance' | 'createdAt' | 'creditLimit' ->; + >; diff --git a/packages/subaccounts/lib/types/responses/balanceTransferPageResponse.ts b/packages/subaccounts/lib/types/responses/balanceTransferPageResponse.ts index 32bb5539..3b62ca70 100644 --- a/packages/subaccounts/lib/types/responses/balanceTransferPageResponse.ts +++ b/packages/subaccounts/lib/types/responses/balanceTransferPageResponse.ts @@ -1,7 +1,18 @@ import { APILinks } from '@vonage/server-client'; import { BalanceTransferResponse } from './balanceTransferResponse'; +/** + * Type definition for the response representing a page of balance transfers, + * which includes an array of `balance_transfers` and APILinks. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type BalanceTransferPageResponse = { + /** + * An object containing an array of `balance_transfers`. + */ _embedded: { balance_transfers: Array; }; diff --git a/packages/subaccounts/lib/types/responses/balanceTransferResponse.ts b/packages/subaccounts/lib/types/responses/balanceTransferResponse.ts index 779f1935..a2fec9f1 100644 --- a/packages/subaccounts/lib/types/responses/balanceTransferResponse.ts +++ b/packages/subaccounts/lib/types/responses/balanceTransferResponse.ts @@ -1,6 +1,22 @@ import { BalanceTransfer } from '../balanceTransfer'; +/** + * Type definition for the response representing a balance transfer, which includes properties such as + * `balance_transfer_id` and `created_at`. This type combines properties from the balance transfer response with the + * properties of a `BalanceTransfer` (excluding specific properties). + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the pure response before the client will + * transform the keys into `camelCase`. + */ export type BalanceTransferResponse = { + /** + * The unique identifier for the balance transfer. + */ balance_transfer_id: string; + + /** + * The date and time when the balance transfer was executed. + */ created_at: string; } & Omit; diff --git a/packages/subaccounts/lib/types/responses/creditTransferResponse.ts b/packages/subaccounts/lib/types/responses/creditTransferResponse.ts index 0c67a09c..c6e8d1cf 100644 --- a/packages/subaccounts/lib/types/responses/creditTransferResponse.ts +++ b/packages/subaccounts/lib/types/responses/creditTransferResponse.ts @@ -1,6 +1,23 @@ import { CreditTransfer } from '../creditTransfer'; +/** + * Type definition for the response representing a credit transfer, which + * includes properties such as `credit_transfer_id` and `created_at`. This type + * combines properties from the credit transfer response with the properties of + * a `CreditTransfer` (excluding specific properties). + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type CreditTransferResponse = { + /** + * The unique identifier for the credit transfer. + */ credit_transfer_id: string; + + /** + * The date and time when the credit transfer was executed. + */ created_at: string; } & Omit; diff --git a/packages/subaccounts/lib/types/responses/creditTransferResponsePage.ts b/packages/subaccounts/lib/types/responses/creditTransferResponsePage.ts index e1da3291..0a82503a 100644 --- a/packages/subaccounts/lib/types/responses/creditTransferResponsePage.ts +++ b/packages/subaccounts/lib/types/responses/creditTransferResponsePage.ts @@ -1,6 +1,17 @@ import { CreditTransferResponse } from './creditTransferResponse'; +/** + * Type definition for the response representing a page of credit transfers, + * which includes an array of `credit_transfers`. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type CreditTransferResponsePage = { + /** + * An object containing an array of `credit_transfers`. + */ _embedded: { credit_transfers: Array; }; diff --git a/packages/subaccounts/lib/types/responses/subAccountResponse.ts b/packages/subaccounts/lib/types/responses/subAccountResponse.ts index a1f85ff4..d4ce8ea0 100644 --- a/packages/subaccounts/lib/types/responses/subAccountResponse.ts +++ b/packages/subaccounts/lib/types/responses/subAccountResponse.ts @@ -1,6 +1,23 @@ import { AccountResponse } from './accountResponse'; +/** + * Type definition for the response representing a subaccount, which includes + * properties such as `primary_account_api_key` and + * `use_primary_account_balance`. This type combines properties from the + * subaccount response with the properties of an `AccountResponse`. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type SubAccountResponse = { + /** + * The API key associated with the primary account. + */ primary_account_api_key: string; + + /** + * Flag indicating whether to use the primary account balance (true) or not (false). + */ use_primary_account_balance: boolean; } & AccountResponse; diff --git a/packages/subaccounts/lib/types/responses/subAccountResponsePage.ts b/packages/subaccounts/lib/types/responses/subAccountResponsePage.ts index 3f99ff9c..0cbc38e1 100644 --- a/packages/subaccounts/lib/types/responses/subAccountResponsePage.ts +++ b/packages/subaccounts/lib/types/responses/subAccountResponsePage.ts @@ -2,9 +2,29 @@ import { SubAccountResponse } from './subAccountResponse'; import { AccountResponse } from './accountResponse'; import { APILinks } from '@vonage/server-client'; +/** + * Type definition for the response representing a page of subaccounts, which + * includes properties such as `total_balance`, `total_credit_limit`, + * `_embedded` with `primary_account`, `subaccounts`, and APILinks. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type SubAccountResponsePage = { + /** + * The total balance of the subaccounts. + */ total_balance: number; + + /** + * The total credit limit of the subaccounts. + */ total_credit_limit: number; + + /** + * An object containing the primary account information and an array of `subaccounts`. + */ _embedded: { primary_account: AccountResponse; subaccounts: Array; diff --git a/packages/subaccounts/lib/types/subAccount.ts b/packages/subaccounts/lib/types/subAccount.ts index bbb671a8..035c823b 100644 --- a/packages/subaccounts/lib/types/subAccount.ts +++ b/packages/subaccounts/lib/types/subAccount.ts @@ -1,6 +1,18 @@ import { Account } from './account'; +/** + * Type definition representing a subaccount, which includes properties such + * as `primaryAccountApiKey` and `usePrimaryAccountBalance`, in addition to + * properties from the `Account` type. + */ export type SubAccount = { + /** + * The API key associated with the primary account. + */ primaryAccountApiKey: string; + + /** + * Flag indicating whether to use the primary account balance (true) or not (false). + */ usePrimaryAccountBalance: boolean; } & Account; diff --git a/packages/subaccounts/package.json b/packages/subaccounts/package.json index 862e14ae..107728fd 100644 --- a/packages/subaccounts/package.json +++ b/packages/subaccounts/package.json @@ -1,4 +1,5 @@ { + "$schema": "https://json.schemastore.org/package.json", "name": "@vonage/subaccounts", "version": "1.5.0", "description": "The Subaccounts API enables you to create subaccounts under your primary account. Subaccounts facilitate differential product configuration, reporting, and billing. The Subaccounts API is released initially with restricted availability.", @@ -14,7 +15,16 @@ "url": "git+https://github.com/Vonage/vonage-node-sdk.git" }, "license": "Apache-2.0", - "author": "Chuck MANCHUCK Reeves ", + "contributors": [ + { + "name": "Chuck \"MANCHUCK\" Reeves", + "url": "https://github.com/manchuck" + }, + { + "name": "Chris Tankersley", + "url": "https://github.com/dragonmantank" + } + ], "main": "dist/index.js", "types": "dist/index.d.ts", "directories": { @@ -27,7 +37,8 @@ "scripts": { "build": "npm run clean && npm run compile", "clean": "npx shx rm -rf dist tsconfig.tsbuildinfo", - "compile": "npx tsc --build --verbose" + "compile": "npx tsc --build --verbose", + "prepublishOnly": "npm run build" }, "dependencies": { "@vonage/server-client": "^1.9.0" diff --git a/packages/subaccounts/tsconfig.json b/packages/subaccounts/tsconfig.json index b8ed59b9..cd40b0e3 100644 --- a/packages/subaccounts/tsconfig.json +++ b/packages/subaccounts/tsconfig.json @@ -1,19 +1,24 @@ { - "extends": "../../tsconfig.json", + "$schema": "https://json.schemastore.org/tsconfig", - "compilerOptions": { - "rootDir": "lib", - "outDir": "dist" - }, + "extends": "../../tsconfig.json", - "exclude": ["__tests__", "jest.config.js", "dist"], + "compilerOptions": { + "rootDir": "lib", + "outDir": "dist" + }, - "references": [ - { "path": "../server-client" }, - { "path": "../auth" } - ], + "exclude": [ + "__tests__", + "dist" + ], - "ts-node": { - "esm": true - } + "references": [ + { "path": "../server-client" }, + { "path": "../auth" } + ], + + "ts-node": { + "esm": true + } } diff --git a/packages/subaccounts/typedoc.json b/packages/subaccounts/typedoc.json new file mode 100644 index 00000000..d3fdb2b4 --- /dev/null +++ b/packages/subaccounts/typedoc.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "extends": ["../../typedoc.base.json"], + "entryPoints": ["lib/index.ts"], + "name": "Vonage Subaccounts" +} diff --git a/packages/users/lib/enums/userSort.ts b/packages/users/lib/enums/userSort.ts index c8f98818..0e50398d 100644 --- a/packages/users/lib/enums/userSort.ts +++ b/packages/users/lib/enums/userSort.ts @@ -1,4 +1,14 @@ +/** + * Enum representing the sorting order. + */ export enum SortOrder { + /** + * Ascending order. + */ ASC = 'ASC', + + /** + * Descending order. + */ DESC = 'DESC', } diff --git a/packages/users/lib/types/messengerChannel.ts b/packages/users/lib/types/messengerChannel.ts index c48acc02..56ee7694 100644 --- a/packages/users/lib/types/messengerChannel.ts +++ b/packages/users/lib/types/messengerChannel.ts @@ -1,3 +1,9 @@ +/** + * Represents a Messenger channel with an ID. + */ export type MessengerChannel = { + /** + * The unique ID associated with the Messenger channel. + */ id: string; }; diff --git a/packages/users/lib/types/mmsChannel.ts b/packages/users/lib/types/mmsChannel.ts index 2f1ecbbc..111d60ab 100644 --- a/packages/users/lib/types/mmsChannel.ts +++ b/packages/users/lib/types/mmsChannel.ts @@ -1,3 +1,9 @@ +/** + * Represents an MMS (Multimedia Messaging Service) channel with a phone number. + */ export type MmsChannel = { + /** + * The phone number associated with the MMS channel. + */ number: string; }; diff --git a/packages/users/lib/types/parameters/userListParameters.ts b/packages/users/lib/types/parameters/userListParameters.ts index 47cdc200..ea428743 100644 --- a/packages/users/lib/types/parameters/userListParameters.ts +++ b/packages/users/lib/types/parameters/userListParameters.ts @@ -1,8 +1,29 @@ -import { SortOrder } from '../../enums/userSort'; +import { SortOrder } from '../../enums'; +/** + * Parameters for listing users. + */ export type UserListParameters = { + /** + * The number of records to return in the response. Minimum: 1, Maximum: 100, Default: 10. + * Example: 10 + */ pageSize?: number; + + /** + * The sorting order for the records. Must be one of: 'ASC' (Ascending) or 'DESC' (Descending). + */ order?: SortOrder; + + /** + * The cursor to start returning results from. You are not expected to provide this manually, + * but to follow the URL provided in _links.next.href or _links.prev.href in the response which contains a cursor + * value. + */ cursor?: string; + + /** + * Unique name for a user. Example: 'my_user_name'. + */ name?: string; }; diff --git a/packages/users/lib/types/pstnChannel.ts b/packages/users/lib/types/pstnChannel.ts index d9b05837..d817a593 100644 --- a/packages/users/lib/types/pstnChannel.ts +++ b/packages/users/lib/types/pstnChannel.ts @@ -1,3 +1,9 @@ +/** + * Represents a PSTN (Public Switched Telephone Network) channel with a phone number. + */ export type PstnChannel = { + /** + * The phone number associated with the PSTN channel. + */ number: number; }; diff --git a/packages/users/lib/types/requests/userRequest.ts b/packages/users/lib/types/requests/userRequest.ts index 8a421154..5c001ecc 100644 --- a/packages/users/lib/types/requests/userRequest.ts +++ b/packages/users/lib/types/requests/userRequest.ts @@ -1,12 +1,56 @@ import { UserType } from '../index'; import { WebSocketChannelRequest } from './websocketChannelRequest'; +/** + * Represents a request to create or update a user's properties. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ +export type UserPropertiesRequest = { + /** + * Custom key-value pairs associated with the user. + * + * @remarks Data here will not have their properties transformed + */ + custom_data: Record; +}; + +/** + * Represents a request to create or update a user's channels. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ +export type UserChannelsRequest = { + /** + * An array of WebSocket channel requests. + */ + websocket: Array; +} & Omit, 'websocket'>;; + +/** + * Represents a request to create or update a user. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type UserRequest = { + /** + * The URL of the user's image. + */ image_url: string; - properties: { - custom_data: Record; - }; - channels: { - websocket: Array; - } & Omit, 'websocket'>; + + /** + * User properties including custom data. + */ + properties: UserPropertiesRequest; + + /** + * Channels for communication, specifically WebSocket channels. + */ + channels: UserChannelsRequest } & Omit; diff --git a/packages/users/lib/types/requests/websocketChannelRequest.ts b/packages/users/lib/types/requests/websocketChannelRequest.ts index fea89d05..790ca643 100644 --- a/packages/users/lib/types/requests/websocketChannelRequest.ts +++ b/packages/users/lib/types/requests/websocketChannelRequest.ts @@ -1,5 +1,15 @@ import { WebsocketChannel } from '../websocketChannel'; +/** + * Represents a request to create or update a WebSocket channel. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type WebSocketChannelRequest = { + /** + * The content type associated with the WebSocket channel. + */ 'content-type': string; } & Omit; diff --git a/packages/users/lib/types/responses/userPageResponse.ts b/packages/users/lib/types/responses/userPageResponse.ts index d03f8093..ed94b6e9 100644 --- a/packages/users/lib/types/responses/userPageResponse.ts +++ b/packages/users/lib/types/responses/userPageResponse.ts @@ -1,8 +1,22 @@ import { APILinks } from '@vonage/server-client'; import { UserResponse } from './userResponse'; +/** + * Represents a page response containing a list of users. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type UserPageResponse = { + /** + * The number of records returned in this response. + */ page_size: number; + + /** + * An object containing an array of user responses. + */ _embedded: { users: Array; }; diff --git a/packages/users/lib/types/responses/userResponse.ts b/packages/users/lib/types/responses/userResponse.ts index 8e228ca1..1ec1e5d8 100644 --- a/packages/users/lib/types/responses/userResponse.ts +++ b/packages/users/lib/types/responses/userResponse.ts @@ -1,4 +1,11 @@ import { APILinks } from '@vonage/server-client'; -import { UserRequest } from '../requests/userRequest'; +import { UserRequest } from '../requests'; +/** + * Represents a response containing user information. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type UserResponse = UserRequest & APILinks; diff --git a/packages/users/lib/types/responses/websocketChannelResponse.ts b/packages/users/lib/types/responses/websocketChannelResponse.ts index 0ea36f5a..5e3339cb 100644 --- a/packages/users/lib/types/responses/websocketChannelResponse.ts +++ b/packages/users/lib/types/responses/websocketChannelResponse.ts @@ -1,5 +1,14 @@ import { WebsocketChannel } from '../websocketChannel'; - +/** + * Represents a response containing WebSocket channel information. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type WebSocketChannelResponse = { + /** + * The content type associated with the WebSocket channel. + */ 'content-type': string; } & Omit; diff --git a/packages/users/lib/types/sipChannel.ts b/packages/users/lib/types/sipChannel.ts index 4856afad..b2c9b399 100644 --- a/packages/users/lib/types/sipChannel.ts +++ b/packages/users/lib/types/sipChannel.ts @@ -1,5 +1,19 @@ +/** + * Represents a SIP (Session Initiation Protocol) channel with the URI, username, and password. + */ export type SipChannel = { + /** + * The SIP URI associated with the channel. + */ uri: string; + + /** + * The username for authentication with the SIP channel. + */ username: string; + + /** + * The password for authentication with the SIP channel. + */ password: string; }; diff --git a/packages/users/lib/types/smsChannel.ts b/packages/users/lib/types/smsChannel.ts index a93cc725..32da58c6 100644 --- a/packages/users/lib/types/smsChannel.ts +++ b/packages/users/lib/types/smsChannel.ts @@ -1,3 +1,9 @@ +/** + * Represents an SMS (Short Message Service) channel with a phone number. + */ export type SmsChannel = { + /** + * The phone number associated with the SMS channel. + */ number: string; }; diff --git a/packages/users/lib/types/userType.ts b/packages/users/lib/types/userType.ts index 6791f8e1..b4ea0762 100644 --- a/packages/users/lib/types/userType.ts +++ b/packages/users/lib/types/userType.ts @@ -8,23 +8,88 @@ import { MessengerChannel } from './messengerChannel'; import { PstnChannel } from './pstnChannel'; import { SipChannel } from './sipChannel'; +/** + * Represents a user with various properties and communication channels. + */ export type UserType = { + /** + * The unique ID associated with the user. + */ id?: string; + + /** + * The name of the user. + */ name?: string; + + /** + * The display name of the user. + */ displayName?: string; + + /** + * The URL of the user's image. + */ imageUrl?: string; + + /** + * Custom data associated with the user. + */ properties?: { + /** + * Custom key-value pairs for user data. + */ customData: Record; }; + + /** + * Communication channels associated with the user. + */ channels?: { + /** + * PSTN (Public Switched Telephone Network) channels. + */ pstn?: Array; + + /** + * SIP (Session Initiation Protocol) channels. + */ sip?: Array; + + /** + * VBC (Voice Business Communication) channels. + */ vbc?: Array; + + /** + * WebSocket channels. + */ websocket?: Array; + + /** + * SMS (Short Message Service) channels. + */ sms?: Array; + + /** + * MMS (Multimedia Messaging Service) channels. + */ mms?: Array; + + /** + * WhatsApp channels. + */ whatsapp?: Array; + + /** + * Viber channels. + */ viber?: Array; + + /** + * Messenger channels. + */ messenger?: Array; }; }; + diff --git a/packages/users/lib/types/vbcChannel.ts b/packages/users/lib/types/vbcChannel.ts index bbe9b854..de2de8cd 100644 --- a/packages/users/lib/types/vbcChannel.ts +++ b/packages/users/lib/types/vbcChannel.ts @@ -1,3 +1,9 @@ +/** + * Represents a VBC (Voice Business Communication) channel with an extension. + */ export type VbcChannel = { + /** + * The extension associated with the VBC channel. + */ extension: string; }; diff --git a/packages/users/lib/types/viberChannel.ts b/packages/users/lib/types/viberChannel.ts index 1880d5e0..66e96c48 100644 --- a/packages/users/lib/types/viberChannel.ts +++ b/packages/users/lib/types/viberChannel.ts @@ -1,3 +1,9 @@ +/** + * Represents a Viber channel with a phone number. + */ export type ViberChannel = { + /** + * The phone number associated with the Viber channel. + */ number: string; }; diff --git a/packages/users/lib/types/websocketChannel.ts b/packages/users/lib/types/websocketChannel.ts index 80b9946a..5b801884 100644 --- a/packages/users/lib/types/websocketChannel.ts +++ b/packages/users/lib/types/websocketChannel.ts @@ -1,5 +1,19 @@ +/** + * Represents a WebSocket channel configuration. + */ export type WebsocketChannel = { + /** + * The WebSocket URI for the channel. + */ uri: string; + + /** + * Optional content type for WebSocket channel data. + */ contentType?: string; + + /** + * Optional headers for WebSocket channel configuration. + */ headers?: Record; }; diff --git a/packages/users/lib/types/whatsappChannel.ts b/packages/users/lib/types/whatsappChannel.ts index f4d35cfa..751f4140 100644 --- a/packages/users/lib/types/whatsappChannel.ts +++ b/packages/users/lib/types/whatsappChannel.ts @@ -1,3 +1,9 @@ +/** + * Represents a WhatsApp channel with a phone number. + */ export type WhatsappChannel = { + /** + * The phone number associated with the WhatsApp channel. + */ number: string; }; diff --git a/packages/users/lib/user.ts b/packages/users/lib/user.ts index aefd229b..61d6fb0c 100644 --- a/packages/users/lib/user.ts +++ b/packages/users/lib/user.ts @@ -7,18 +7,21 @@ import { WebSocketChannelRequest, WebSocketChannelResponse, WebsocketChannel, -} from './types/index'; +} from './types'; const apiUserToUser = (apiUser: UserResponse): UserType => { - const user = Client.transformers.camelCaseObjectKeys(apiUser, true); + delete apiUser._links; - delete user.links; - delete user.properties?.customData; - if (apiUser.properties) { - user.properties.customData = apiUser.properties?.custom_data; + const user = Client.transformers.camelCaseObjectKeys( + apiUser, + true, + ) as UserType; + + if (user.properties) { + user.properties.customData = apiUser.properties.custom_data; } - if (apiUser?.channels?.websocket) { + if (user.channels?.websocket) { user.channels.websocket = apiUser.channels.websocket.map( (apiSocket: WebSocketChannelResponse): WebsocketChannel => { const socket = { @@ -38,19 +41,23 @@ const apiUserToUser = (apiUser: UserResponse): UserType => { ); } - return user; + return user as UserType; }; const userToAPI = (user: UserType): UserResponse => { - const apiUser = Client.transformers.snakeCaseObjectKeys(user, true); + const apiUser = Client.transformers.snakeCaseObjectKeys( + user, + true, + ) as UserResponse; + // preserve user properties - if (apiUser.properties?.custom_data) { + if (user.properties?.customData) { apiUser.properties.custom_data = user.properties.customData; } // Websockets will change when transformed - if (apiUser.channels?.websocket) { - apiUser.channels.websocket = user.channels.websocket.map( + if (user.channels?.websocket) { + apiUser.channels.websocket = user.channels.websocket?.map( (socket: WebsocketChannel): WebSocketChannelRequest => { const apiSocket = { uri: socket.uri, @@ -73,12 +80,25 @@ const userToAPI = (user: UserType): UserResponse => { delete apiUser.id; - return apiUser; + return apiUser as UserResponse; }; +/** + * The `Users` class provides methods for managing user data through API requests. + * + * Vonage API responses and requests use `snake_case` for property names, but + * this class performs the necessary key transformations to work with + * `camelCase` property names in your application. + */ export class Users extends Client { protected authType = AuthenticationType.JWT; + /** + * Retrieves a list of users, optionally paginated, based on the provided parameters. + * + * @param {UserListParameters} params - Optional parameters to filter and paginate the list of users. + * @return {AsyncGenerator} An async generator that yields user objects. + */ async *listAllUsers( params: UserListParameters = {}, ): AsyncGenerator { @@ -94,10 +114,23 @@ export class Users extends Client { ? new URL(resp._links.next.href) : null; - cursor = next ? next.searchParams.get('cursor') : null; + cursor = next ? `${next.searchParams.get('cursor')}` : undefined; } while (cursor); } + /** + * Retrieves a page of users based on the provided parameters, such as pagination and filtering. + * + * @param {UserListParameters} [params={}] - Optional parameters to filter and paginate the list of users. + * @param {number} [params.pageSize] - The number of users to include per page. + * @param {SortOrder} [params.order] - The sorting order for the list (ASC or DESC). + * @param {string} [params.cursor] - A cursor for paginating through the user list. + * @param {string} [params.name] - A name to filter users by. + * + * @return {Promise} A Promise that resolves to a UserPageResponse object containing the user page data. + * + * @throws {Error} If there is an issue with the request or response. + */ async getUserPage( params: UserListParameters = {}, ): Promise { @@ -109,6 +142,13 @@ export class Users extends Client { return resp.data; } + /** + * Creates a new user with the provided user data. + * + * @param {UserType} user - The user data to create a new user. + * @return {Promise} A Promise that resolves to the newly created user. + * @throws {Error} If there is an issue with the request or response. + */ async createUser(user: UserType): Promise { const resp = await this.sendPostRequest( `${this.config.apiHost}/v1/users`, @@ -118,6 +158,13 @@ export class Users extends Client { return apiUserToUser(resp.data); } + /** + * Retrieves user information for the specified user ID. + * + * @param {string} userId - The unique identifier of the user to retrieve. + * @return {Promise} A Promise that resolves to the user information for the specified user ID. + * @throws {Error} If there is an issue with the request or response, or if the user with the specified ID is not found. + */ async getUser(userId: string): Promise { const resp = await this.sendGetRequest( `${this.config.apiHost}/v1/users/${userId}`, @@ -126,6 +173,13 @@ export class Users extends Client { return apiUserToUser(resp.data); } + /** + * Updates the user information for the specified user. + * + * @param {UserType} user - The user object containing the updated information. + * @return {Promise} A Promise that resolves to the updated user information. + * @throws {Error} If there is an issue with the request or response, or if the user with the specified ID is not found. + */ async updateUser(user: UserType): Promise { const resp = await this.sendPutRequest( `${this.config.apiHost}/v1/users/${user.id}`, @@ -135,6 +189,13 @@ export class Users extends Client { return apiUserToUser(resp.data); } + /** + * Deletes the user with the specified user ID. + * + * @param {string} userId - The unique ID of the user to be deleted. + * @return {Promise} A Promise that resolves once the user is successfully deleted. + * @throws {Error} If there is an issue with the request or response, or if the user with the specified ID is not found. + */ async deleteUser(userId: string): Promise { await this.sendDeleteRequest( `${this.config.apiHost}/v1/users/${userId}`, diff --git a/packages/users/package.json b/packages/users/package.json index 494889d5..cb3132c7 100644 --- a/packages/users/package.json +++ b/packages/users/package.json @@ -1,4 +1,5 @@ { + "$schema": "https://json.schemastore.org/package.json", "name": "@vonage/users", "version": "1.3.0", "description": "The concept of a user exists in Vonage APIs, you can associate one with a user in your own application if you choose. A user can have multiple memberships to conversations and can communicate with other users through various different mediums.", @@ -11,7 +12,16 @@ "url": "git+https://github.com/Vonage/vonage-node-sdk.git" }, "license": "Apache-2.0", - "author": "Chuck MANCHUCK Reeves ", + "contributors": [ + { + "name": "Chuck \"MANCHUCK\" Reeves", + "url": "https://github.com/manchuck" + }, + { + "name": "Chris Tankersley", + "url": "https://github.com/dragonmantank" + } + ], "main": "dist/index.js", "types": "dist/index.d.ts", "directories": { @@ -24,7 +34,8 @@ "scripts": { "build": "npm run clean && npm run compile", "clean": "npx shx rm -rf dist tsconfig.tsbuildinfo", - "compile": "npx tsc --build --verbose" + "compile": "npx tsc --build --verbose", + "prepublishOnly": "npm run build" }, "dependencies": { "@vonage/server-client": "^1.9.0" diff --git a/packages/users/tsconfig.json b/packages/users/tsconfig.json index e9b438f7..8e8615aa 100644 --- a/packages/users/tsconfig.json +++ b/packages/users/tsconfig.json @@ -1,24 +1,25 @@ { - "extends": "../../tsconfig.json", + "$schema": "https://json.schemastore.org/tsconfig", - "compilerOptions": { - "rootDir": "lib", - "outDir": "dist" - }, + "extends": "../../tsconfig.json", - "exclude": [ - "__tests__", - "jest.config.js", - "dist" - ], + "compilerOptions": { + "rootDir": "lib", + "outDir": "dist" + }, - "references": [ - { "path": "../auth" }, - { "path": "../server-client" }, - { "path": "../vetch" } - ], + "exclude": [ + "__tests__", + "dist" + ], - "ts-node": { - "esm": true - } + "references": [ + { "path": "../auth" }, + { "path": "../server-client" }, + { "path": "../vetch" } + ], + + "ts-node": { + "esm": true + } } diff --git a/packages/users/typedoc.json b/packages/users/typedoc.json new file mode 100644 index 00000000..fcd8b567 --- /dev/null +++ b/packages/users/typedoc.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "extends": ["../../typedoc.base.json"], + "entryPoints": ["lib/index.ts"], + "name": "Vonage Users" +} diff --git a/packages/verify/__tests__/__dataSets__/cancel.ts b/packages/verify/__tests__/__dataSets__/cancel.ts index 1b847458..88dea83d 100644 --- a/packages/verify/__tests__/__dataSets__/cancel.ts +++ b/packages/verify/__tests__/__dataSets__/cancel.ts @@ -1,9 +1,10 @@ -import { Command, CheckStatus } from '../../lib/enums/index'; +import { Command, CheckStatus } from '../../lib/enums'; import { VerifyCancelResponse, VerifyControlErrorResponse, -} from '../../lib/interfaces/Response/index'; -import { VerifyControl, VerifyControlError } from '../../lib/interfaces/index'; + VerifyControl, + VerifyControlError, +} from '../../lib/types'; export default [ { diff --git a/packages/verify/__tests__/__dataSets__/check.ts b/packages/verify/__tests__/__dataSets__/check.ts index 30b05ef2..f5fc9725 100644 --- a/packages/verify/__tests__/__dataSets__/check.ts +++ b/packages/verify/__tests__/__dataSets__/check.ts @@ -1,4 +1,4 @@ -import { VerifyCheckResponse, VerifyCheck } from '../../lib/interfaces/index'; +import { VerifyCheckResponse, VerifyCheck } from '../../lib/types'; export default [ { diff --git a/packages/verify/__tests__/__dataSets__/search.ts b/packages/verify/__tests__/__dataSets__/search.ts index 7b62a4fc..e5595c6c 100644 --- a/packages/verify/__tests__/__dataSets__/search.ts +++ b/packages/verify/__tests__/__dataSets__/search.ts @@ -3,12 +3,12 @@ import { VerifySearch, VerifySearchErrorResponse, VerifySearchError, -} from '../../lib/interfaces/index'; +} from '../../lib/types'; import { SearchStatus, SearchCheckStatus, SearchEventTypes, -} from '../../lib/enums/index'; +} from '../../lib/enums'; const params = new URLSearchParams({ api_key: '12345', diff --git a/packages/verify/__tests__/__dataSets__/start.ts b/packages/verify/__tests__/__dataSets__/start.ts index 4ca0ad50..fd4f7ee8 100644 --- a/packages/verify/__tests__/__dataSets__/start.ts +++ b/packages/verify/__tests__/__dataSets__/start.ts @@ -8,8 +8,9 @@ import { VerifyRequest, VerifyRequestErrorResponse, VerifyError, -} from '../../lib/interfaces/index'; -import { PSD2Parameters, VerificationParameters } from '../../lib/types/index'; + PSD2Parameters, + VerificationParameters, +} from '../../lib/types/index'; import { PSD2, Verification } from '../../lib/classes/index'; export default [ diff --git a/packages/verify/lib/classes/PSD2.ts b/packages/verify/lib/classes/PSD2.ts index 5a92fa34..bb09e382 100644 --- a/packages/verify/lib/classes/PSD2.ts +++ b/packages/verify/lib/classes/PSD2.ts @@ -1,19 +1,59 @@ -import { PSD2Parameters } from '../types/index'; -import { VerifyWorkflows, VerifyLanguages } from '../enums/index'; +import { PSD2Parameters } from '../types'; +import { VerifyWorkflows, VerifyLanguages } from '../enums'; +/** + * Represents parameters for a PSD2 (Payment Services Directive 2) verification + * request. + */ export class PSD2 implements PSD2Parameters { + /** + * The phone number to be verified. + */ number: string; + + /** + * The payee's name or identifier for the payment confirmation. + */ payee: string; + + /** + * The decimal amount of the payment to be confirmed, in Euros. + */ amount: number; + + /** + * The country code associated with the phone number (optional). + */ country?: string; + + /** + * The desired length of the verification code (optional). + */ codeLength?: number; - lg?: VerifyLanguages; + /** - * @deprecated - */ + * @deprecated This property is deprecated. Use `lg` instead. + */ language?: string; + + /** + * The language for sending verification messages (optional). + */ + lg?: VerifyLanguages; + + /** + * The duration in seconds for which the verification code will be valid. + */ pinExpiry?: number; + + /** + * The duration in seconds to wait before sending the next verification event. + */ nextEventWait?: number; + + /** + * The workflow ID for customizing the verification process (optional). + */ workflowId?: VerifyWorkflows; constructor( @@ -29,16 +69,12 @@ export class PSD2 implements PSD2Parameters { workflowId?: VerifyWorkflows, ) { this.number = phoneNumber; + this.amount = amount; + this.payee = payee; if (country) { this.country = country; } - if (payee) { - this.payee = payee; - } - if (amount) { - this.amount = amount; - } if (codeLength) { this.codeLength = codeLength; } diff --git a/packages/verify/lib/classes/Verification.ts b/packages/verify/lib/classes/Verification.ts index 93ef4b51..c64c49d1 100644 --- a/packages/verify/lib/classes/Verification.ts +++ b/packages/verify/lib/classes/Verification.ts @@ -1,19 +1,59 @@ -import { VerificationParameters } from '../types/index'; -import { VerifyWorkflows, VerifyLanguages } from '../enums/index'; +import { VerificationParameters } from '../types'; +import { VerifyWorkflows, VerifyLanguages } from '../enums'; +/** + * Represents parameters for a verification request. + */ export class Verification implements VerificationParameters { + /** + * The phone number to be verified. + */ number: string; + + /** + * The brand or application name associated with the verification request. + */ brand: string; + + /** + * The country code associated with the phone number (optional). + */ country?: string; + + /** + * The sender ID or phone number that will be used to send verification + * messages (optional). + */ senderId?: string; + + /** + * The desired length of the verification code (optional). + */ codeLength?: number; + /** - * @deprecated - */ + * @deprecated This property is deprecated. Use `lg` instead. + */ language?: string; + + /** + * The language for sending verification messages (optional). + */ lg?: VerifyLanguages; + + /** + * The duration in seconds for which the verification code will be valid. + */ pinExpiry?: number; + + /** + * The duration in seconds to wait before sending the next verification event. + */ nextEventWait?: number; + + /** + * The workflow ID for customizing the verification process (optional). + */ workflowId?: VerifyWorkflows; constructor( diff --git a/packages/verify/lib/enums/CheckStatus.ts b/packages/verify/lib/enums/CheckStatus.ts index 891b88ac..cc30716d 100644 --- a/packages/verify/lib/enums/CheckStatus.ts +++ b/packages/verify/lib/enums/CheckStatus.ts @@ -1,18 +1,84 @@ +/** + * Enum representing the status of a verification check. + */ export enum CheckStatus { - SUCCESS = '0', - THROTTLED = '1', - MISSING_REQUIRED_PARAM = '2', - INVALID_PARAM = '3', - INVALID_CREDENTIALS = '4', - INTERNAL_ERROR = '5', - FAILED_TO_PROCESS = '6', - BARRED_API_KEY = '8', - PARTNER_QUOTA_EXCEEDED = '9', - CONCURRENT_VERIFICATIONS = '10', - UNSUPPORTED_NETWORK = '15', - CODE_MISMATCH = '16', - INVALID_CODE = '17', - DELIEVERY_FAILED = '19', - PIN_NOT_SUPPORTED = '20', - NON_PREMITTED_DESTINATION = '29', + /** + * The verification check was successful. + */ + SUCCESS = '0', + + /** + * The verification request was throttled. + */ + THROTTLED = '1', + + /** + * A required parameter was missing in the verification request. + */ + MISSING_REQUIRED_PARAM = '2', + + /** + * An invalid parameter was provided in the verification request. + */ + INVALID_PARAM = '3', + + /** + * Invalid credentials were used in the verification request. + */ + INVALID_CREDENTIALS = '4', + + /** + * An internal error occurred during the verification process. + */ + INTERNAL_ERROR = '5', + + /** + * Failed to process the verification request. + */ + FAILED_TO_PROCESS = '6', + + /** + * The API key used in the verification request is barred. + */ + BARRED_API_KEY = '8', + + /** + * Partner quota for verifications exceeded. + */ + PARTNER_QUOTA_EXCEEDED = '9', + + /** + * Concurrent verifications not allowed. + */ + CONCURRENT_VERIFICATIONS = '10', + + /** + * The network is not supported for verification. + */ + UNSUPPORTED_NETWORK = '15', + + /** + * Code mismatch in the verification request. + */ + CODE_MISMATCH = '16', + + /** + * Invalid verification code provided. + */ + INVALID_CODE = '17', + + /** + * Delivery of the verification failed. + */ + DELIVERY_FAILED = '19', + + /** + * PIN not supported for verification. + */ + PIN_NOT_SUPPORTED = '20', + + /** + * Destination not permitted for verification. + */ + NON_PERMITTED_DESTINATION = '29', } diff --git a/packages/verify/lib/enums/Command.ts b/packages/verify/lib/enums/Command.ts index cb0b4d96..fa6ead2b 100644 --- a/packages/verify/lib/enums/Command.ts +++ b/packages/verify/lib/enums/Command.ts @@ -1,4 +1,14 @@ +/** + * Enum representing commands for controlling Verify requests. + */ export enum Command { - CANCEL = 'cancel', - TRIGGER_NEXT_EVENT = 'trigger_next_event', + /** + * Command to request cancellation of the verification process. + */ + CANCEL = 'cancel', + + /** + * Command to trigger the next verification event (if any). + */ + TRIGGER_NEXT_EVENT = 'trigger_next_event', } diff --git a/packages/verify/lib/enums/SearchCheckStatus.ts b/packages/verify/lib/enums/SearchCheckStatus.ts index d940c5c4..a4cf9c4d 100644 --- a/packages/verify/lib/enums/SearchCheckStatus.ts +++ b/packages/verify/lib/enums/SearchCheckStatus.ts @@ -1,4 +1,14 @@ +/** + * Enum representing the status of a verification check during Verify search. + */ export enum SearchCheckStatus { - INVALID = 'INVALID', - VALID = 'VALID', + /** + * The verification check is invalid. + */ + INVALID = 'INVALID', + + /** + * The verification check is valid. + */ + VALID = 'VALID', } diff --git a/packages/verify/lib/enums/SearchEventTypes.ts b/packages/verify/lib/enums/SearchEventTypes.ts index 50b1081c..d7150c14 100644 --- a/packages/verify/lib/enums/SearchEventTypes.ts +++ b/packages/verify/lib/enums/SearchEventTypes.ts @@ -1,4 +1,14 @@ +/** + * Enum representing the types of events that can occur during Verify search. + */ export enum SearchEventTypes { - TTS = 'TTS', - SMS = 'SMS', + /** + * Text-to-Speech event. + */ + TTS = 'TTS', + + /** + * Short Message Service (SMS) event. + */ + SMS = 'SMS', } diff --git a/packages/verify/lib/enums/SearchStatus.ts b/packages/verify/lib/enums/SearchStatus.ts index 3f734b4b..9b064030 100644 --- a/packages/verify/lib/enums/SearchStatus.ts +++ b/packages/verify/lib/enums/SearchStatus.ts @@ -1,7 +1,29 @@ +/** + * Enum representing the status of a Verify search request. + */ export enum SearchStatus { - IN_PROGRESS = 'IN PROGRESS', - SUCCESS = 'SUCCESS', - FAILED = 'FAILED', - EXPIRED = 'EXPIRED', - CANCELLED = 'CANCELLED', + /** + * The search is still in progress. + */ + IN_PROGRESS = 'IN PROGRESS', + + /** + * Your user entered a correct verification code. + */ + SUCCESS = 'SUCCESS', + + /** + * Your user entered an incorrect code more than three times. + */ + FAILED = 'FAILED', + + /** + * Your user did not enter a code before the pin_expiry time elapsed. + */ + EXPIRED = 'EXPIRED', + + /** + * The verification process was canceled by a Verify control request. + */ + CANCELLED = 'CANCELLED', } diff --git a/packages/verify/lib/enums/VerifyLanguages.ts b/packages/verify/lib/enums/VerifyLanguages.ts index 371e2e38..5f8ffb87 100644 --- a/packages/verify/lib/enums/VerifyLanguages.ts +++ b/packages/verify/lib/enums/VerifyLanguages.ts @@ -1,41 +1,199 @@ +/** + * Enum representing supported languages for Verify requests. + */ export enum VerifyLanguages { - ARABIC = 'ar-xa', - CZECH = 'cs-cz', - WELSH = 'cy-cy', - WELSH_UK = 'cy-gb', - DANISH = 'da-dk', - GERMAN = 'de-de', - GREEK = 'el-gr', - ENGLISH_AUSTRALIA = 'en-au', - ENGLISH_UK = 'en-gb', - ENGLISH_INDIA = 'en-in', - ENGLISH_US = 'en-us', - SPANISH_SPAIN = 'es-es', - SPANISH_MEXICO = 'es-mx', - SPANISH_US = 'es-us', - FINNISH = 'fi-fi', - FILIPINO = 'fil-ph', - FRENCH_CANADA = 'fr-ca', - FRENCH_FRANCE = 'fr-fr', - HINDI = 'hi-in', - HUNGARIAN = 'hu-hu', - INDONESIAN = 'id-id', - ICELANDIC = 'is-is', - ITALIAN = 'it-it', - JAPANESE = 'ja-jp', - KOREAN = 'ko-kr', - NORWEGIAN = 'nb-no', - DUTCH = 'nl-nl', - POLISH = 'pl-pl', - PORTUGUESE_BRAZIL = 'pt-br', - PORTUGUESE_PORTUGAL = 'pt-pt', - ROMANIAN = 'ro-ro', - RUSSIAN = 'ru-ru', - SWEDISH = 'sv-se', - THAI = 'th-th', - TURKISH = 'tr-tr', - VIETNAMESE = 'vi-vn', - YUE_CHINESE_CANTONESE = 'yue-cn', - CHINESE_MAINLAND = 'zh-cn', - CHINESE_TAIWAN = 'zh-tw', + /** + * Arabic language (ar-xa). + */ + ARABIC = 'ar-xa', + + /** + * Czech language (cs-cz). + */ + CZECH = 'cs-cz', + + /** + * Welsh language (cy-cy). + */ + WELSH = 'cy-cy', + + /** + * Welsh language, United Kingdom (cy-gb). + */ + WELSH_UK = 'cy-gb', + + /** + * Danish language (da-dk). + */ + DANISH = 'da-dk', + + /** + * German language (de-de). + */ + GERMAN = 'de-de', + + /** + * Greek language (el-gr). + */ + GREEK = 'el-gr', + + /** + * English language, Australia (en-au). + */ + ENGLISH_AUSTRALIA = 'en-au', + + /** + * English language, United Kingdom (en-gb). + */ + ENGLISH_UK = 'en-gb', + + /** + * English language, India (en-in). + */ + ENGLISH_INDIA = 'en-in', + + /** + * English language, United States (en-us). + */ + ENGLISH_US = 'en-us', + + /** + * Spanish language, Spain (es-es). + */ + SPANISH_SPAIN = 'es-es', + + /** + * Spanish language, Mexico (es-mx). + */ + SPANISH_MEXICO = 'es-mx', + + /** + * Spanish language, United States (es-us). + */ + SPANISH_US = 'es-us', + + /** + * Finnish language (fi-fi). + */ + FINNISH = 'fi-fi', + + /** + * Filipino language (fil-ph). + */ + FILIPINO = 'fil-ph', + + /** + * French language, Canada (fr-ca). + */ + FRENCH_CANADA = 'fr-ca', + + /** + * French language, France (fr-fr). + */ + FRENCH_FRANCE = 'fr-fr', + + /** + * Hindi language (hi-in). + */ + HINDI = 'hi-in', + + /** + * Hungarian language (hu-hu). + */ + HUNGARIAN = 'hu-hu', + + /** + * Indonesian language (id-id). + */ + INDONESIAN = 'id-id', + + /** + * Icelandic language (is-is). + */ + ICELANDIC = 'is-is', + + /** + * Italian language (it-it). + */ + ITALIAN = 'it-it', + + /** + * Japanese language (ja-jp). + */ + JAPANESE = 'ja-jp', + + /** + * Korean language (ko-kr). + */ + KOREAN = 'ko-kr', + + /** + * Norwegian language (nb-no). + */ + NORWEGIAN = 'nb-no', + + /** + * Dutch language (nl-nl). + */ + DUTCH = 'nl-nl', + + /** + * Polish language (pl-pl). + */ + POLISH = 'pl-pl', + + /** + * Portuguese language, Brazil (pt-br). + */ + PORTUGUESE_BRAZIL = 'pt-br', + + /** + * Portuguese language, Portugal (pt-pt). + */ + PORTUGUESE_PORTUGAL = 'pt-pt', + + /** + * Romanian language (ro-ro). + */ + ROMANIAN = 'ro-ro', + + /** + * Russian language (ru-ru). + */ + RUSSIAN = 'ru-ru', + + /** + * Swedish language (sv-se). + */ + SWEDISH = 'sv-se', + + /** + * Thai language (th-th). + */ + THAI = 'th-th', + + /** + * Turkish language (tr-tr). + */ + TURKISH = 'tr-tr', + + /** + * Vietnamese language (vi-vn). + */ + VIETNAMESE = 'vi-vn', + + /** + * Yue Chinese Cantonese language (yue-cn). + */ + YUE_CHINESE_CANTONESE = 'yue-cn', + + /** + * Chinese language, Mainland (zh-cn). + */ + CHINESE_MAINLAND = 'zh-cn', + + /** + * Chinese language, Taiwan (zh-tw). + */ + CHINESE_TAIWAN = 'zh-tw', } diff --git a/packages/verify/lib/enums/VerifyStatus.ts b/packages/verify/lib/enums/VerifyStatus.ts index 713ca8c1..91f8ce59 100644 --- a/packages/verify/lib/enums/VerifyStatus.ts +++ b/packages/verify/lib/enums/VerifyStatus.ts @@ -1,18 +1,87 @@ +/** + * Enum representing the status codes for Verify operations. + */ export enum VerifyStatus { - SUCCESS = '0', - THROTTLED = '1', - MISSING_REQUIRED_PARAM = '2', - INVALID_PARAM = '3', - INVALID_CREDENTIALS = '4', - INTERNAL_ERROR = '5', - FAILED_TO_PROCESS = '6', - BARRED_API_KEY = '8', - PARTNER_QUOTA_EXCEEDED = '9', - CONCURRENT_VERIFICATIONS = '10', - UNSUPPORTED_NETWORK = '15', - CODE_MISMATCH = '16', - INVALID_CODE = '17', - DELIEVERY_FAILED = '19', - PIN_NOT_SUPPORTED = '20', - NON_PREMITTED_DESTINATION = '29', + /** + * Success: Your user entered a correct verification code. + */ + SUCCESS = '0', + + /** + * Throttled: You have exceeded the rate limit for Verify requests. + */ + THROTTLED = '1', + + /** + * Missing Required Parameter: A required parameter is missing in the request. + */ + MISSING_REQUIRED_PARAM = '2', + + /** + * Invalid Parameter: An invalid parameter was provided in the request. + */ + INVALID_PARAM = '3', + + /** + * Invalid Credentials: The provided API credentials are invalid. + */ + INVALID_CREDENTIALS = '4', + + /** + * Internal Error: An internal error occurred during processing. + */ + INTERNAL_ERROR = '5', + + /** + * Failed to Process: The request failed to process. + */ + FAILED_TO_PROCESS = '6', + + /** + * Barred API Key: The API key used in the request is barred. + */ + BARRED_API_KEY = '8', + + /** + * Partner Quota Exceeded: The partner's quota for Verify requests has + * been exceeded. + */ + PARTNER_QUOTA_EXCEEDED = '9', + + /** + * Concurrent Verifications: Multiple verifications are being processed + * concurrently. + */ + CONCURRENT_VERIFICATIONS = '10', + + /** + * Unsupported Network: The network is not supported for verification. + */ + UNSUPPORTED_NETWORK = '15', + + /** + * Code Mismatch: The verification code entered by the user does not match. + */ + CODE_MISMATCH = '16', + + /** + * Invalid Code: The verification code provided is invalid. + */ + INVALID_CODE = '17', + + /** + * Delivery Failed: The delivery of the verification code failed. + */ + DELIVERY_FAILED = '19', + + /** + * PIN Not Supported: PIN verification is not supported. + */ + PIN_NOT_SUPPORTED = '20', + + /** + * Non-Permitted Destination: The destination is not permitted for + * verification. + */ + NON_PERMITTED_DESTINATION = '29', } diff --git a/packages/verify/lib/enums/Workflows.ts b/packages/verify/lib/enums/Workflows.ts index d2608c8c..79c88b12 100644 --- a/packages/verify/lib/enums/Workflows.ts +++ b/packages/verify/lib/enums/Workflows.ts @@ -1,9 +1,39 @@ +/** + * Enum representing predefined Verify workflows. + */ export enum VerifyWorkflows { - SMS_TTS_TTS = '1', - SMS_SMS_TTS = '2', - TTS_TTS = '3', - SMS_SMS = '4', - SMS_TTS = '5', - SMS = '6', - TTS = '7', + /** + * Workflow: SMS - TTS - TTS + */ + SMS_TTS_TTS = '1', + + /** + * Workflow: SMS - SMS - TTS + */ + SMS_SMS_TTS = '2', + + /** + * Workflow: TTS - TTS + */ + TTS_TTS = '3', + + /** + * Workflow: SMS - SMS + */ + SMS_SMS = '4', + + /** + * Workflow: SMS - TTS + */ + SMS_TTS = '5', + + /** + * Workflow: SMS + */ + SMS = '6', + + /** + * Workflow: TTS + */ + TTS = '7', } diff --git a/packages/verify/lib/index.ts b/packages/verify/lib/index.ts index 311b7ae0..85f7999d 100644 --- a/packages/verify/lib/index.ts +++ b/packages/verify/lib/index.ts @@ -1,5 +1,4 @@ export { Verify } from './verify'; export * from './classes/index'; export * from './enums/index'; -export * from './interfaces/index'; export * from './types/index'; diff --git a/packages/verify/lib/interfaces/Response/SearchCheckInformationResponse.ts b/packages/verify/lib/interfaces/Response/SearchCheckInformationResponse.ts deleted file mode 100644 index 262ddf40..00000000 --- a/packages/verify/lib/interfaces/Response/SearchCheckInformationResponse.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { SearchCheckStatus } from '../../enums/index'; - -export interface SearchCheckInformationResponse { - date_received: string - code: string - status: SearchCheckStatus - ip_address: string -} diff --git a/packages/verify/lib/interfaces/Response/SearchEventInformationResponse.ts b/packages/verify/lib/interfaces/Response/SearchEventInformationResponse.ts deleted file mode 100644 index ee42ab15..00000000 --- a/packages/verify/lib/interfaces/Response/SearchEventInformationResponse.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { SearchEventTypes } from '../../enums/index'; - -export interface SearchEventInformationResponse { - type: SearchEventTypes - id: string -} diff --git a/packages/verify/lib/interfaces/Response/UnblockRequestResponse.ts b/packages/verify/lib/interfaces/Response/UnblockRequestResponse.ts deleted file mode 100644 index d55a1016..00000000 --- a/packages/verify/lib/interfaces/Response/UnblockRequestResponse.ts +++ /dev/null @@ -1,4 +0,0 @@ -export interface UblockRequestResponse { - network: string - unblocked_until: string -} diff --git a/packages/verify/lib/interfaces/Response/VerifyCancelResponse.ts b/packages/verify/lib/interfaces/Response/VerifyCancelResponse.ts deleted file mode 100644 index 3de69387..00000000 --- a/packages/verify/lib/interfaces/Response/VerifyCancelResponse.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { VerifyControlResponse } from './VerifyControlResponse'; -import { Command } from '../../enums/index'; - -/** - * @deprecated Please use VerifyControlResponse instead - */ -export interface VerifyCancelResponse extends VerifyControlResponse { - command: Command.CANCEL -} diff --git a/packages/verify/lib/interfaces/Response/VerifyCheckErrorResponse.ts b/packages/verify/lib/interfaces/Response/VerifyCheckErrorResponse.ts deleted file mode 100644 index e18f69b5..00000000 --- a/packages/verify/lib/interfaces/Response/VerifyCheckErrorResponse.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { CheckStatus } from '../../enums/index'; - -export interface VerifyCheckErrorResponse { - request_id: string - status: CheckStatus - error_text: string -} diff --git a/packages/verify/lib/interfaces/Response/VerifyCheckResponse.ts b/packages/verify/lib/interfaces/Response/VerifyCheckResponse.ts deleted file mode 100644 index 4f9530da..00000000 --- a/packages/verify/lib/interfaces/Response/VerifyCheckResponse.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { CheckStatus } from '../../enums/index'; - -export interface VerifyCheckResponse { - request_id: string - status: CheckStatus - event_id?: string - price?: string - currency?: string - estimated_price_messages_sent?: string - error_text?: string -} diff --git a/packages/verify/lib/interfaces/Response/VerifyControlError.ts b/packages/verify/lib/interfaces/Response/VerifyControlError.ts deleted file mode 100644 index 316bb28f..00000000 --- a/packages/verify/lib/interfaces/Response/VerifyControlError.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { CheckStatus } from '../../enums/index'; - -export interface VerifyControlErrorResponse { - status: CheckStatus - error_text: string -} diff --git a/packages/verify/lib/interfaces/Response/VerifyControlResponse.ts b/packages/verify/lib/interfaces/Response/VerifyControlResponse.ts deleted file mode 100644 index 6c4e210e..00000000 --- a/packages/verify/lib/interfaces/Response/VerifyControlResponse.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { Command } from '../../enums/index'; - -export interface VerifyControlResponse { - status: string - command: Command -} diff --git a/packages/verify/lib/interfaces/Response/VerifyRequestError.ts b/packages/verify/lib/interfaces/Response/VerifyRequestError.ts deleted file mode 100644 index 104a1df1..00000000 --- a/packages/verify/lib/interfaces/Response/VerifyRequestError.ts +++ /dev/null @@ -1,6 +0,0 @@ -export interface VerifyRequestErrorResponse { - request_id?: string - status: string - error_text: string - network?: string -} diff --git a/packages/verify/lib/interfaces/Response/VerifyRequestResponse.ts b/packages/verify/lib/interfaces/Response/VerifyRequestResponse.ts deleted file mode 100644 index 574b86a0..00000000 --- a/packages/verify/lib/interfaces/Response/VerifyRequestResponse.ts +++ /dev/null @@ -1,4 +0,0 @@ -export interface VerifyRequestResponse { - request_id: string - status: string -} diff --git a/packages/verify/lib/interfaces/Response/VerifyResponse.ts b/packages/verify/lib/interfaces/Response/VerifyResponse.ts deleted file mode 100644 index 35932fb0..00000000 --- a/packages/verify/lib/interfaces/Response/VerifyResponse.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { CheckStatus } from '../../enums/index'; -export interface VerifyResponse { - request_id: string - status: CheckStatus -} diff --git a/packages/verify/lib/interfaces/Response/VerifySearchErrorResponse.ts b/packages/verify/lib/interfaces/Response/VerifySearchErrorResponse.ts deleted file mode 100644 index 4fb80976..00000000 --- a/packages/verify/lib/interfaces/Response/VerifySearchErrorResponse.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { SearchStatus } from '../../enums/index'; - -export interface VerifySearchErrorResponse { - request_id: string - status: SearchStatus - error_text: string -} diff --git a/packages/verify/lib/interfaces/Response/VerifySearchResponse.ts b/packages/verify/lib/interfaces/Response/VerifySearchResponse.ts deleted file mode 100644 index b610829d..00000000 --- a/packages/verify/lib/interfaces/Response/VerifySearchResponse.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { SearchCheckInformationResponse } from './SearchCheckInformationResponse'; -import { SearchEventInformationResponse } from './SearchEventInformationResponse'; -import { SearchStatus } from './../../enums/index'; - -export interface VerifySearchResponse { - request_id: string - account_id: string - status: SearchStatus - number: string - price: string - currency: string - sender_id: string - date_submitted: string - date_finalized: string - first_event_date: string - last_event_date: string - checks: SearchCheckInformationResponse[] - events: SearchEventInformationResponse[] - estimated_price_messages_sent: string -} diff --git a/packages/verify/lib/interfaces/VerifyCheck.ts b/packages/verify/lib/interfaces/VerifyCheck.ts deleted file mode 100644 index b37e4544..00000000 --- a/packages/verify/lib/interfaces/VerifyCheck.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { VerifyRequestResponse } from './Response/index'; - -export interface VerifyCheck extends VerifyRequestResponse { - requestId: string - eventId?: string - errorText?: string - estimatedPriceMessagesSent?: string -} diff --git a/packages/verify/lib/interfaces/VerifyCheckError.ts b/packages/verify/lib/interfaces/VerifyCheckError.ts deleted file mode 100644 index 2ffdd7c3..00000000 --- a/packages/verify/lib/interfaces/VerifyCheckError.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { VerifyCheckErrorResponse } from './Response/index'; - -export interface VerifyCheckError extends VerifyCheckErrorResponse { - requestId: string - errorId: string -} diff --git a/packages/verify/lib/interfaces/VerifyControl.ts b/packages/verify/lib/interfaces/VerifyControl.ts deleted file mode 100644 index 5f9af63e..00000000 --- a/packages/verify/lib/interfaces/VerifyControl.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { VerifyControlResponse } from './Response/index'; - -export type VerifyControl = VerifyControlResponse diff --git a/packages/verify/lib/interfaces/VerifyControlError.ts b/packages/verify/lib/interfaces/VerifyControlError.ts deleted file mode 100644 index c5ef295a..00000000 --- a/packages/verify/lib/interfaces/VerifyControlError.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { CheckStatus } from '../enums/index'; - -export type VerifyControlError = { - status: CheckStatus - errorText: string -} diff --git a/packages/verify/lib/interfaces/VerifyError.ts b/packages/verify/lib/interfaces/VerifyError.ts deleted file mode 100644 index 1ae7b0a8..00000000 --- a/packages/verify/lib/interfaces/VerifyError.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { VerifyRequest } from './VerifyRequest'; - -export interface VerifyError extends VerifyRequest { - error_text: string - errorText: string - network?: string -} diff --git a/packages/verify/lib/interfaces/VerifyRequest.ts b/packages/verify/lib/interfaces/VerifyRequest.ts deleted file mode 100644 index f290ba1e..00000000 --- a/packages/verify/lib/interfaces/VerifyRequest.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { VerifyRequestResponse } from './Response/VerifyRequestResponse'; - -export interface VerifyRequest extends VerifyRequestResponse { - requestId: string -} diff --git a/packages/verify/lib/interfaces/VerifySearch.ts b/packages/verify/lib/interfaces/VerifySearch.ts deleted file mode 100644 index 1735deac..00000000 --- a/packages/verify/lib/interfaces/VerifySearch.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { VerifySearchResponse } from './Response/index'; -import { VerifySearchCheck } from './VerifySearchCheck'; - -export interface VerifySearch extends Omit { - requestId: string - accountId: string - senderId: string - dateSubmitted: string - dateFinalized: string - firstEventDate?: string - lastEventDate?: string - checks: VerifySearchCheck[] - estimatedPriceMessagesSent: string -} diff --git a/packages/verify/lib/interfaces/VerifySearchCheck.ts b/packages/verify/lib/interfaces/VerifySearchCheck.ts deleted file mode 100644 index 331b6b8f..00000000 --- a/packages/verify/lib/interfaces/VerifySearchCheck.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { VerifyCheckResponse } from './Response/index'; - -export interface VerifySearchCheck extends VerifyCheckResponse { - dateReceived: string - ipAddress: string -} diff --git a/packages/verify/lib/interfaces/VerifySearchError.ts b/packages/verify/lib/interfaces/VerifySearchError.ts deleted file mode 100644 index 24efef63..00000000 --- a/packages/verify/lib/interfaces/VerifySearchError.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { VerifySearchErrorResponse } from './Response/index'; - -export interface VerifySearchError extends VerifySearchErrorResponse { - requestId: string - errorText: string -} diff --git a/packages/verify/lib/interfaces/index.ts b/packages/verify/lib/interfaces/index.ts deleted file mode 100644 index e5439115..00000000 --- a/packages/verify/lib/interfaces/index.ts +++ /dev/null @@ -1,11 +0,0 @@ -export * from './Response/index'; -export * from './PSD2Request'; -export * from './VerificationRequest'; -export * from './VerifyCheck'; -export * from './VerifyCheckError'; -export * from './VerifySearch'; -export * from './VerifyControl'; -export * from './VerifyControlError'; -export * from './VerifySearchError'; -export * from './VerifyRequest'; -export * from './VerifyError'; diff --git a/packages/verify/lib/types/PSD2Parameters.ts b/packages/verify/lib/types/PSD2Parameters.ts index aa4430bc..e7396fcd 100644 --- a/packages/verify/lib/types/PSD2Parameters.ts +++ b/packages/verify/lib/types/PSD2Parameters.ts @@ -1,9 +1,20 @@ import { VerificationParameters } from './VerificationParams'; +/** + * Represents parameters for a PSD2 (Payment Services Directive 2) + * verification request. + */ export type PSD2Parameters = Omit< - VerificationParameters, - 'brand' | 'senderId' | 'pinCode' -> & { - payee: string - amount: number + VerificationParameters, + 'brand' | 'senderId' | 'pinCode' + > & { + /** + * The payee's name or identifier for the payment confirmation. + */ + payee: string; + + /** + * The decimal amount of the payment to be confirmed, in Euros. + */ + amount: number; } diff --git a/packages/verify/lib/interfaces/PSD2Request.ts b/packages/verify/lib/types/PSD2Request.ts similarity index 65% rename from packages/verify/lib/interfaces/PSD2Request.ts rename to packages/verify/lib/types/PSD2Request.ts index c2b1edc1..d51d682f 100644 --- a/packages/verify/lib/interfaces/PSD2Request.ts +++ b/packages/verify/lib/types/PSD2Request.ts @@ -1,4 +1,4 @@ -import { PSD2Parameters } from '../types/index'; +import { PSD2Parameters } from './index'; /** * @deprecated please use PSD2Parameters diff --git a/packages/verify/lib/interfaces/Response/CheckInformation.ts b/packages/verify/lib/types/Response/CheckInformation.ts similarity index 77% rename from packages/verify/lib/interfaces/Response/CheckInformation.ts rename to packages/verify/lib/types/Response/CheckInformation.ts index 391657c5..59558351 100644 --- a/packages/verify/lib/interfaces/Response/CheckInformation.ts +++ b/packages/verify/lib/types/Response/CheckInformation.ts @@ -1,6 +1,8 @@ import { SearchEventInformationResponse } from './SearchEventInformationResponse'; /** + * Represents the information of a check event response. + * * @deprecated Please use SearchEventInformation instead */ export type CheckInformation = SearchEventInformationResponse diff --git a/packages/verify/lib/interfaces/Response/EventInformation.ts b/packages/verify/lib/types/Response/EventInformation.ts similarity index 78% rename from packages/verify/lib/interfaces/Response/EventInformation.ts rename to packages/verify/lib/types/Response/EventInformation.ts index 8594554a..7e7b4d92 100644 --- a/packages/verify/lib/interfaces/Response/EventInformation.ts +++ b/packages/verify/lib/types/Response/EventInformation.ts @@ -1,6 +1,7 @@ import { SearchEventInformationResponse } from './SearchEventInformationResponse'; /** + * Represents the event information for a response. * @deprecated please use SearchEventInformation instead - **/ + */ export type EventInformation = SearchEventInformationResponse diff --git a/packages/verify/lib/interfaces/Response/PSD2RequestResponse.ts b/packages/verify/lib/types/Response/PSD2RequestResponse.ts similarity index 64% rename from packages/verify/lib/interfaces/Response/PSD2RequestResponse.ts rename to packages/verify/lib/types/Response/PSD2RequestResponse.ts index d7d52f76..21196ba9 100644 --- a/packages/verify/lib/interfaces/Response/PSD2RequestResponse.ts +++ b/packages/verify/lib/types/Response/PSD2RequestResponse.ts @@ -1,3 +1,6 @@ import { VerifyRequestResponse } from './VerifyRequestResponse'; +/** + * Represents the response for a PSD2 verification request. + */ export type VerifyPDS2Response = VerifyRequestResponse diff --git a/packages/verify/lib/types/Response/SearchCheckInformationResponse.ts b/packages/verify/lib/types/Response/SearchCheckInformationResponse.ts new file mode 100644 index 00000000..91310830 --- /dev/null +++ b/packages/verify/lib/types/Response/SearchCheckInformationResponse.ts @@ -0,0 +1,26 @@ +import { SearchCheckStatus } from '../../enums'; + +/** + * Represents the response data for searching check information. + */ +export type SearchCheckInformationResponse = { + /** + * The date when the check information was received. + */ + date_received: string; + + /** + * The code associated with the check information. + */ + code: string; + + /** + * The status of the search check. + */ + status: SearchCheckStatus; + + /** + * The IP address associated with the check information. + */ + ip_address: string; +} diff --git a/packages/verify/lib/types/Response/SearchEventInformationResponse.ts b/packages/verify/lib/types/Response/SearchEventInformationResponse.ts new file mode 100644 index 00000000..16ea706f --- /dev/null +++ b/packages/verify/lib/types/Response/SearchEventInformationResponse.ts @@ -0,0 +1,15 @@ +import { SearchEventTypes } from '../../enums'; + +/** + * Represents the response for searching event information. + */ +export type SearchEventInformationResponse = { + /** + * The type of the event. + */ + type: SearchEventTypes; + /** + * The ID of the event. + */ + id: string; +} diff --git a/packages/verify/lib/types/Response/UnblockRequestResponse.ts b/packages/verify/lib/types/Response/UnblockRequestResponse.ts new file mode 100644 index 00000000..eaf2becc --- /dev/null +++ b/packages/verify/lib/types/Response/UnblockRequestResponse.ts @@ -0,0 +1,17 @@ +/** + * Represents the response of an unblock request. + */ +/** + * Represents the response of an unblock request. + */ +export type UblockRequestResponse = { + /** + * The network associated with the unblock request. + */ + network: string; + + /** + * The date and time until which the unblock is valid. + */ + unblocked_until: string; +} diff --git a/packages/verify/lib/types/Response/VerifyCancelResponse.ts b/packages/verify/lib/types/Response/VerifyCancelResponse.ts new file mode 100644 index 00000000..fcbd39b1 --- /dev/null +++ b/packages/verify/lib/types/Response/VerifyCancelResponse.ts @@ -0,0 +1,14 @@ +import { VerifyControlResponse } from './VerifyControlResponse'; +import { Command } from '../../enums'; + +/** + * Represents the response for cancelling a verification request. + * + * @deprecated Please use VerifyControlResponse instead + */ +export type VerifyCancelResponse = VerifyControlResponse & { + /** + * The command type for the response, which is "CANCEL". + */ + command: Command.CANCEL; +} diff --git a/packages/verify/lib/interfaces/Response/VerifyCheckError.ts b/packages/verify/lib/types/Response/VerifyCheckError.ts similarity index 100% rename from packages/verify/lib/interfaces/Response/VerifyCheckError.ts rename to packages/verify/lib/types/Response/VerifyCheckError.ts diff --git a/packages/verify/lib/types/Response/VerifyCheckErrorResponse.ts b/packages/verify/lib/types/Response/VerifyCheckErrorResponse.ts new file mode 100644 index 00000000..0b579e0e --- /dev/null +++ b/packages/verify/lib/types/Response/VerifyCheckErrorResponse.ts @@ -0,0 +1,21 @@ +import { CheckStatus } from '../../enums'; + +/** + * Represents the response object for a failed verification check. + */ +export type VerifyCheckErrorResponse = { + /** + * The unique identifier for the verification request. + */ + request_id: string + + /** + * The status of the verification check. + */ + status: CheckStatus + + /** + * The error message associated with the failed verification check. + */ + error_text: string +} diff --git a/packages/verify/lib/types/Response/VerifyCheckResponse.ts b/packages/verify/lib/types/Response/VerifyCheckResponse.ts new file mode 100644 index 00000000..c0037d22 --- /dev/null +++ b/packages/verify/lib/types/Response/VerifyCheckResponse.ts @@ -0,0 +1,31 @@ +import { CheckStatus } from '../../enums'; + +/** + * Represents the response object for the Verify Check API. + */ +export type VerifyCheckResponse = { + /** + * The unique identifier for the verification request. + */ + request_id: string; + + /** + * The status of the verification check. + */ + status: CheckStatus; + + /** + * The unique identifier for the verification event. + */ + event_id?: string; + + /** + * The price of the verification check. + */ + price?: string; + + /** + * The currency of the price. + */ + currency?: string; +} diff --git a/packages/verify/lib/types/Response/VerifyControlError.ts b/packages/verify/lib/types/Response/VerifyControlError.ts new file mode 100644 index 00000000..50a802e9 --- /dev/null +++ b/packages/verify/lib/types/Response/VerifyControlError.ts @@ -0,0 +1,16 @@ +import { CheckStatus } from '../../enums'; + +/** + * Represents an error response for a Verify control operation. + */ +export type VerifyControlErrorResponse = { + /** + * The status code indicating the outcome of the operation. + */ + status: CheckStatus; + + /** + * The error text providing more information about the error. + */ + error_text: string; +} diff --git a/packages/verify/lib/types/Response/VerifyControlResponse.ts b/packages/verify/lib/types/Response/VerifyControlResponse.ts new file mode 100644 index 00000000..26bb57aa --- /dev/null +++ b/packages/verify/lib/types/Response/VerifyControlResponse.ts @@ -0,0 +1,16 @@ +import { Command } from '../../enums'; + +/** + * Represents the response for a Verify control operation. + */ +export type VerifyControlResponse = { + /** + * The status code indicating the outcome of the operation. + */ + status: string; + + /** + * The command associated with the Verify control operation. + */ + command: Command; +} diff --git a/packages/verify/lib/types/Response/VerifyRequestError.ts b/packages/verify/lib/types/Response/VerifyRequestError.ts new file mode 100644 index 00000000..ec43f236 --- /dev/null +++ b/packages/verify/lib/types/Response/VerifyRequestError.ts @@ -0,0 +1,24 @@ +/** + * Represents an error response for a Verify request operation. + */ +export type VerifyRequestErrorResponse = { + /** + * (Optional) The unique identifier for the Verify request. + */ + request_id?: string; + + /** + * The status code indicating the outcome of the operation. + */ + status: string; + + /** + * The error text providing more information about the error. + */ + error_text: string; + + /** + * (Optional) The network associated with the error. + */ + network?: string; +} diff --git a/packages/verify/lib/types/Response/VerifyRequestResponse.ts b/packages/verify/lib/types/Response/VerifyRequestResponse.ts new file mode 100644 index 00000000..f93b9bea --- /dev/null +++ b/packages/verify/lib/types/Response/VerifyRequestResponse.ts @@ -0,0 +1,14 @@ +/** + * Represents the response for a Verify request operation. + */ +export type VerifyRequestResponse = { + /** + * The unique identifier for the Verify request. + */ + request_id: string; + + /** + * The status code indicating the outcome of the operation. + */ + status: string; +} diff --git a/packages/verify/lib/types/Response/VerifyResponse.ts b/packages/verify/lib/types/Response/VerifyResponse.ts new file mode 100644 index 00000000..f22881fe --- /dev/null +++ b/packages/verify/lib/types/Response/VerifyResponse.ts @@ -0,0 +1,16 @@ +import { CheckStatus } from '../../enums'; + +/** + * Represents the response for a Verify operation. + */ +export type VerifyResponse = { + /** + * The unique identifier for the Verify request. + */ + request_id: string; + + /** + * The status code indicating the outcome of the operation. + */ + status: CheckStatus; +} diff --git a/packages/verify/lib/types/Response/VerifySearchErrorResponse.ts b/packages/verify/lib/types/Response/VerifySearchErrorResponse.ts new file mode 100644 index 00000000..77c68988 --- /dev/null +++ b/packages/verify/lib/types/Response/VerifySearchErrorResponse.ts @@ -0,0 +1,21 @@ +import { SearchStatus } from '../../enums'; + +/** + * Represents an error response for a Verify search operation. + */ +export type VerifySearchErrorResponse = { + /** + * The unique identifier for the Verify request. + */ + request_id: string; + + /** + * The status code indicating the outcome of the search operation. + */ + status: SearchStatus; + + /** + * The error text providing more information about the error. + */ + error_text: string; +} diff --git a/packages/verify/lib/types/Response/VerifySearchResponse.ts b/packages/verify/lib/types/Response/VerifySearchResponse.ts new file mode 100644 index 00000000..44c35289 --- /dev/null +++ b/packages/verify/lib/types/Response/VerifySearchResponse.ts @@ -0,0 +1,79 @@ +import { SearchCheckInformationResponse } from './SearchCheckInformationResponse'; +import { SearchEventInformationResponse } from './SearchEventInformationResponse'; +import { SearchStatus } from '../../enums'; + +/** + * Represents the response for a Verify search operation. + */ +export type VerifySearchResponse = { + /** + * The unique identifier for the Verify request. + */ + request_id: string; + + /** + * The account ID associated with the request. + */ + account_id: string; + + /** + * The status code indicating the outcome of the search operation. + */ + status: SearchStatus; + + /** + * The phone number this verification request was used for. + */ + number: string; + + /** + * The cost incurred for this verification request. + */ + price: string; + + /** + * The currency code. + */ + currency: string; + + /** + * The sender ID provided in the Verify request. + */ + sender_id: string; + + /** + * The date and time the verification request was submitted. + */ + date_submitted: string; + + /** + * The date and time the verification request was completed. + */ + date_finalized: string; + + /** + * The time the first verification attempt was made. + */ + first_event_date: string; + + /** + * The time the last verification attempt was made. + */ + last_event_date: string; + + /** + * The list of checks made for this verification and their outcomes. + */ + checks: SearchCheckInformationResponse[]; + + /** + * The events that have taken place to verify this number, and their + * unique identifiers. + */ + events: SearchEventInformationResponse[]; + + /** + * The estimated cost of messages sent for the verification process. + */ + estimated_price_messages_sent: string; +} diff --git a/packages/verify/lib/interfaces/Response/index.ts b/packages/verify/lib/types/Response/index.ts similarity index 100% rename from packages/verify/lib/interfaces/Response/index.ts rename to packages/verify/lib/types/Response/index.ts diff --git a/packages/verify/lib/types/VerificationParams.ts b/packages/verify/lib/types/VerificationParams.ts index b80a0ef9..93f19243 100644 --- a/packages/verify/lib/types/VerificationParams.ts +++ b/packages/verify/lib/types/VerificationParams.ts @@ -1,14 +1,71 @@ -import { VerifyWorkflows, VerifyLanguages } from '../enums/index'; +import { VerifyWorkflows, VerifyLanguages } from '../enums'; +/** + * Represents parameters for a verification request. + */ export interface VerificationParameters { - number: string - brand: string - country?: string - senderId?: string - codeLength?: number - lg?: VerifyLanguages - pinExpiry?: number - nextEventWait?: number - workflowId?: VerifyWorkflows - pinCode?: string + /** + * The mobile or landline phone number to verify. Unless you are setting + * country explicitly, this number must be in E.164 format. + */ + number: string; + + /** + * An 18-character alphanumeric string you can use to personalize the + * verification request SMS body, to help users identify your company or + * application name. For example: "Your Acme Inc PIN is ..." + */ + brand: string; + + /** + * (Optional) The two-character country code if the number is not provided in + * international format or if you are not sure if the number is correctly + * formatted. Verify will then format the number for you. + */ + country?: string; + + /** + * (Optional) An 11-character alphanumeric string that represents the identity + * of the sender of the verification request. Depending on the destination of + * the phone number you are sending the verification SMS to, restrictions + * might apply. + */ + senderId?: string; + + /** + * (Optional) The length of the verification code. + */ + codeLength?: number; + + /** + * (Optional) The language used for the Verify request. + */ + lg?: VerifyLanguages; + + /** + * (Optional) How long the generated verification code is valid for, + * in seconds. + */ + pinExpiry?: number; + + /** + * (Optional) The wait time in seconds between attempts to deliver the + * verification code. + */ + nextEventWait?: number; + + /** + * (Optional) Selects the predefined sequence of SMS and TTS (Text To Speech) + * actions to use in order to convey the PIN to your user. + */ + workflowId?: VerifyWorkflows; + + /** + * (Optional) A custom PIN to send to the user. If a PIN is not provided, + * Verify will generate a random PIN for you. This feature is not enabled by + * default - please discuss with your Account Manager if you would like it + * enabled. If this feature is not enabled on your account, error status 20 + * will be returned. + */ + pinCode?: string; } diff --git a/packages/verify/lib/interfaces/VerificationRequest.ts b/packages/verify/lib/types/VerificationRequest.ts similarity index 55% rename from packages/verify/lib/interfaces/VerificationRequest.ts rename to packages/verify/lib/types/VerificationRequest.ts index 64a6f2a3..7e8751ec 100644 --- a/packages/verify/lib/interfaces/VerificationRequest.ts +++ b/packages/verify/lib/types/VerificationRequest.ts @@ -1,6 +1,8 @@ -import { VerificationParameters } from '../types/index'; +import { VerificationParameters } from './index'; /** + * Represents a verification request. + * * @deprecated please use VerificationParameters */ export type VerificationRequest = VerificationParameters diff --git a/packages/verify/lib/types/VerifyCheck.ts b/packages/verify/lib/types/VerifyCheck.ts new file mode 100644 index 00000000..c01802b4 --- /dev/null +++ b/packages/verify/lib/types/VerifyCheck.ts @@ -0,0 +1,26 @@ +import { VerifyRequestResponse } from './Response'; + +/** + * Represents a Verify Check response. + */ +export type VerifyCheck = VerifyRequestResponse & { + /** + * The unique identifier for the Verify request. + */ + requestId: string + + /** + * The unique identifier for the Verify event. + */ + eventId?: string + + /** + * The error message, if any, associated with the Verify Check. + */ + errorText?: string + + /** + * The estimated price for the messages sent during the Verify Check. + */ + estimatedPriceMessagesSent?: string +} diff --git a/packages/verify/lib/types/VerifyCheckError.ts b/packages/verify/lib/types/VerifyCheckError.ts new file mode 100644 index 00000000..b7f83627 --- /dev/null +++ b/packages/verify/lib/types/VerifyCheckError.ts @@ -0,0 +1,16 @@ +import { VerifyCheckErrorResponse } from './Response'; + +/** + * Represents an error that occurred during the verification check process. + */ +export type VerifyCheckError = VerifyCheckErrorResponse & { + /** + * The unique identifier of the request. + */ + requestId: string + + /** + * The unique identifier of the error. + */ + errorId: string +} diff --git a/packages/verify/lib/types/VerifyClassParameters.ts b/packages/verify/lib/types/VerifyClassParameters.ts index 84a34b96..259ad3d9 100644 --- a/packages/verify/lib/types/VerifyClassParameters.ts +++ b/packages/verify/lib/types/VerifyClassParameters.ts @@ -1,7 +1,15 @@ -import { AuthInterface, AuthOpts } from '@vonage/auth' -import { VetchOptions } from '@vonage/vetch' +import { AuthInterface, AuthParams } from '@vonage/auth'; +import { VetchOptions } from '@vonage/vetch'; -export type VerifyClassParameters = AuthOpts & - VetchOptions & { - auth?: AuthInterface - } +/** + * Represents parameters for configuring the VerifyClass. + * + * @deprecated The class will set the correct type + */ +export type VerifyClassParameters = AuthParams & + VetchOptions & { + /** + * (Optional) An authentication interface to use for authentication. + */ + auth?: AuthInterface; +}; diff --git a/packages/verify/lib/types/VerifyControl.ts b/packages/verify/lib/types/VerifyControl.ts new file mode 100644 index 00000000..c47b8895 --- /dev/null +++ b/packages/verify/lib/types/VerifyControl.ts @@ -0,0 +1,6 @@ +import { VerifyControlResponse } from './Response'; + +/** + * Represents the VerifyControl type. + */ +export type VerifyControl = VerifyControlResponse diff --git a/packages/verify/lib/types/VerifyControlError.ts b/packages/verify/lib/types/VerifyControlError.ts new file mode 100644 index 00000000..d2175afe --- /dev/null +++ b/packages/verify/lib/types/VerifyControlError.ts @@ -0,0 +1,16 @@ +import { CheckStatus } from '../enums'; + +/** + * Represents an error that occurred during the verification control process. + */ +export type VerifyControlError = { + /** + * The status of the verification control. + */ + status: CheckStatus; + + /** + * The error message associated with the verification control error. + */ + errorText: string; +} diff --git a/packages/verify/lib/types/VerifyError.ts b/packages/verify/lib/types/VerifyError.ts new file mode 100644 index 00000000..779e0217 --- /dev/null +++ b/packages/verify/lib/types/VerifyError.ts @@ -0,0 +1,22 @@ +import { VerifyRequest } from './VerifyRequest'; + +/** + * Represents an error response for a Verify operation with additional + * error-related properties. + */ +export type VerifyError = VerifyRequest & { + /** + * The error text providing more information about the error. + */ + error_text: string; + + /** + * The error text providing more information about the error + */ + errorText: string; + + /** + * (Optional) The network associated with the error. + */ + network?: string; +} diff --git a/packages/verify/lib/types/VerifyRequest.ts b/packages/verify/lib/types/VerifyRequest.ts new file mode 100644 index 00000000..4cacd41b --- /dev/null +++ b/packages/verify/lib/types/VerifyRequest.ts @@ -0,0 +1,11 @@ +import { VerifyRequestResponse } from './Response'; + +/** + * Represents a Verify request with an additional requestId property. + */ +export type VerifyRequest = VerifyRequestResponse & { + /** + * The unique identifier for the Verify request. + */ + requestId: string; +} diff --git a/packages/verify/lib/types/VerifySearch.ts b/packages/verify/lib/types/VerifySearch.ts new file mode 100644 index 00000000..73c5a5f8 --- /dev/null +++ b/packages/verify/lib/types/VerifySearch.ts @@ -0,0 +1,57 @@ +import { VerifySearchResponse } from './Response'; +import { VerifySearchCheck } from './VerifySearchCheck'; + +/** + * Represents the response for a Verify search operation. + */ +export type VerifySearch = Omit & { + /** + * The unique identifier for the Verify request. + */ + requestId: string; + + /** + * The Vonage account ID associated with the request. + */ + accountId: string; + + /** + * The sender ID provided in the Verify request. + */ + senderId: string; + + /** + * The date and time the verification request was submitted in the + * format 'YYYY-MM-DD HH:MM:SS'. + */ + dateSubmitted: string; + + /** + * The date and time the verification request was completed in the + * format 'YYYY-MM-DD HH:MM:SS'. + */ + dateFinalized: string; + + /** + * (Optional) The time the first verification attempt was made in the + * format 'YYYY-MM-DD HH:MM:SS'. + */ + firstEventDate?: string; + + /** + * (Optional) The time the last verification attempt was made in the + * format 'YYYY-MM-DD HH:MM:SS'. + */ + lastEventDate?: string; + + /** + * The list of verification checks made for this verification and + * their outcomes. + */ + checks: VerifySearchCheck[]; + + /** + * The estimated cost of messages sent during the verification process. + */ + estimatedPriceMessagesSent: string; +} diff --git a/packages/verify/lib/types/VerifySearchCheck.ts b/packages/verify/lib/types/VerifySearchCheck.ts new file mode 100644 index 00000000..1e7ab70b --- /dev/null +++ b/packages/verify/lib/types/VerifySearchCheck.ts @@ -0,0 +1,17 @@ +import { VerifyCheckResponse } from './Response'; + +/** + * Represents a verification check result as part of a Verify search operation. + */ +export type VerifySearchCheck = VerifyCheckResponse & { + /** + * The date and time this check was received in the format + * 'YYYY-MM-DD HH:MM:SS'. + */ + dateReceived: string; + + /** + * The IP address associated with this verification check. + */ + ipAddress: string; +} diff --git a/packages/verify/lib/types/VerifySearchError.ts b/packages/verify/lib/types/VerifySearchError.ts new file mode 100644 index 00000000..ef143cd6 --- /dev/null +++ b/packages/verify/lib/types/VerifySearchError.ts @@ -0,0 +1,16 @@ +import { VerifySearchErrorResponse } from './Response'; + +/** + * Represents an error response for a Verify search operation. + */ +export type VerifySearchError = VerifySearchErrorResponse & { + /** + * The unique identifier for the Verify request that resulted in an error. + */ + requestId: string; + + /** + * A descriptive error message providing more information about the error. + */ + errorText: string; +} diff --git a/packages/verify/lib/types/index.ts b/packages/verify/lib/types/index.ts index 9b00a97f..4e2ef421 100644 --- a/packages/verify/lib/types/index.ts +++ b/packages/verify/lib/types/index.ts @@ -1,3 +1,15 @@ export * from './PSD2Parameters'; +export * from './PSD2Request'; +export * from './Response'; export * from './VerificationParams'; +export * from './VerificationRequest'; +export * from './VerifyCheck'; +export * from './VerifyCheckError'; export * from './VerifyClassParameters'; +export * from './VerifyControl'; +export * from './VerifyControlError'; +export * from './VerifyError'; +export * from './VerifyRequest'; +export * from './VerifySearch'; +export * from './VerifySearchCheck'; +export * from './VerifySearchError'; diff --git a/packages/verify/lib/verify.ts b/packages/verify/lib/verify.ts index 245e5f9a..7c78f85e 100644 --- a/packages/verify/lib/verify.ts +++ b/packages/verify/lib/verify.ts @@ -1,5 +1,5 @@ -import { Client } from '@vonage/server-client'; -import { Command } from './enums/index'; +import { Client, AuthenticationType } from '@vonage/server-client'; +import { Command } from './enums'; import { VerifyControl, VerifyControlError, @@ -15,39 +15,182 @@ import { VerifyRequestErrorResponse, VerifyError, VerifyRequest, -} from './interfaces/index'; -import { VerificationParameters, PSD2Parameters } from './types/index'; + VerificationParameters, + PSD2Parameters, +} from './types'; import omit from 'lodash.omit'; +/** + * The Verify class provides methods for managing and performing verification processes using the Vonage Verify API. + * + * It allows you to initiate new verification requests, check verification codes, search for verification request + * details, and perform control actions like canceling or triggering the next event for a verification process. + * + * @example + * Create a standalone Verify client + * + * ```ts + * import { Verify } from '@vonage/verify'; + * + * const verifyClient = new Verify({ + * apiKey: VONAGE_API_KEY, + * apiSecret: VONAGE_API_SECRET + * }); + * ``` + * + * @example + * Create an Verify client from the Vonage client + * + * ```ts + * import { Vonage } from '@vonage/server-client'; + * + * const vonage = new Vonage({ + * apiKey: VONAGE_API_KEY, + * apiSecret: VONAGE_API_SECRET + * }); + * + * const verifyClient = vonage.verify; + * ``` + */ export class Verify extends Client { + + protected authType?: AuthenticationType = AuthenticationType.KEY_SECRET; + + /** + * Sends a control command for a specific verification request. + * + * @param {Command} command - The control command to send, either "cancel" or "trigger_next_event". + * @param {string} requestId - The request ID of the verification to control. + * @return {Promise} A Promise that resolves to a `VerifyControl` object containing the control response on success or a `VerifyControlError` object on error. + * @throws {VerifyControlError} If an error occurs while sending the control command. + * + * @example + * Cancel a verification request + * ```ts + * import { Command, CheckStatus } from '@vonage/verify'; + * + * const result = await verifyClient.sendControl(Command.CANCEL, 'REQUEST_ID') + * if (result.status === CheckStatus.SUCCESS) { + * console.log('Verification request canceled.'); + * console.log(result.status); + * } else { + * console.log('Error canceling verification request.'); + * console.log(result.errorText); + * } + * ``` + * + * @example + * Trigger the next event for a verification request + * ```ts + * import { Command, CheckStatus } from '@vonage/verify'; + * + * const result = await verifyClient.sendControl(Command.TRIGGER_NEXT_EVENT, 'REQUEST_ID') + * if (result.status === CheckStatus.SUCCESS) { + * console.log('Next event triggered'); + * console.log(result.status); + * } else { + * console.log('Error triggering next event'); + * console.log(result.errorText); + * } + * ``` + */ public async sendControl( command: Command, requestId: string, ): Promise { const data = { request_id: requestId, - cmd: Command.CANCEL, + cmd: command, }; // eslint-disable-next-line max-len const resp = await this.sendPostRequest< VerifyControlResponse | VerifyControlErrorResponse >(`${this.config.apiHost}/verify/control/json`, data); - return Client.transformers.camelCaseObjectKeys(resp.data, true, true); + return Client.transformers.camelCaseObjectKeys( + resp.data, + true, + true, + ) as VerifyControl | VerifyControlError; } + /** + * Cancels a specific verification request. + * + * @param {string} requestId - The request ID of the verification to cancel. + * @return {Promise} A Promise that resolves to a `VerifyControl` object containing the control response on success or a `VerifyControlError` object on error. + * @throws {VerifyControlError} If an error occurs while canceling the verification request. + * + * @example + * ```ts + * import { CheckStatus } from '@vonage/verify'; + * + * const result = await verifyClient.cancel('REQUEST_ID') + * + * if (result.status === CheckStatus.SUCCESS) { + * console.log('Verification request canceled.'); + * console.log(result.status); + * } else { + * console.log('Error canceling verification request.'); + * console.log(result.errorText); + * } + * ``` + * + */ public async cancel( requestId: string, ): Promise { return this.sendControl(Command.CANCEL, requestId); } + /** + * Triggers the next verification event for a specific verification request. + * + * @param {string} requestId - The request ID of the verification to trigger the next event for. + * @return {Promise} A Promise that resolves to a `VerifyControl` object containing the control response on success or a `VerifyControlError` object on error. + * @throws {VerifyControlError} If an error occurs while triggering the next verification event. + * + * @example + * ```ts + * import { CheckStatus } from '@vonage/verify'; + * + * const result = await verifyClient.trigger('REQUEST_ID') + * + * if (result.status === CheckStatus.SUCCESS) { + * console.log('Verification request canceled.'); + * console.log(result.status); + * } else { + * console.log('Error canceling verification request.'); + * console.log(result.errorText); + * } + * ``` + */ public async trigger( requestId: string, ): Promise { return this.sendControl(Command.TRIGGER_NEXT_EVENT, requestId); } + /** + * Checks the verification code for a specific verification request. + * + * @param {string} requestId - The request ID of the verification to check. + * @param {string} code - The verification code to check against. + * @return {Promise} A Promise that resolves to a `VerifyCheck` object containing the verification result on success or a `VerifyCheckError` object on error. + * @throws {VerifyCheckError} If an error occurs during the verification check. + * + * @example + * ```ts + * import { CheckStatus } from '@vonage/verify'; + * + * const result = await verifyClient.check('REQUEST_ID', 'CODE') + * if (result.status === CheckStatus.SUCCESS) { + * console.log('Verification code is valid.'); + * } else { + * console.log('Verification code is invalid.'); + * } + * ``` + */ public async check( requestId: string, code: string, @@ -60,20 +203,81 @@ export class Verify extends Client { code: code, }); - return Client.transformers.camelCaseObjectKeys(resp.data, true, true); + return Client.transformers.camelCaseObjectKeys( + resp.data, + true, + true, + ) as VerifyCheck | VerifyCheckError; } + /** + * Searches for the status of a verification request by its request ID. + * + * @param {string} requestId - The request ID of the verification to search for. + * @return {Promise} A `VerifySearch` object containing the verification details on success or a `VerifySearchError` object on error. + * + * @example + * ```ts + * const result = await verifyClient.search('REQUEST_ID') + * if (result.errorText) { + * console.log(`Request found with error ${result.errorText}`); + * } else { + * console.log(`Request found and submitted on ${result.dateSubmitted}`); + * } + * ``` + */ public async search( requestId: string, ): Promise { + this.authType = AuthenticationType.QUERY_KEY_SECRET; const resp = await this.sendGetRequest( `${this.config.apiHost}/verify/search/json`, { request_id: requestId }, ); - return Client.transformers.camelCaseObjectKeys(resp.data, true, true); + this.authType = AuthenticationType.KEY_SECRET; + return Client.transformers.camelCaseObjectKeys( + resp.data, + true, + true, + ) as VerifySearch | VerifySearchError; } + /** + * Starts a verification request. + * + * @param {VerificationParameters | PSD2Parameters} request - The verification parameters for the request. + * @return {Promise} A `VerifyError` object on error or a `VerifyRequest` object on success. + * + * @example + * ```ts + * const result = await verifyClient.start({ + * number: TO_NUMBER, + * brand: BRAND_NAME + * }); + * + * if (result.requestId) { + * console.log(`Request started with id ${result.requestId}`); + * } else { + * console.log(`Request failed with error: ${result.errorText}`); + * } + * ``` + * + * @example + * Start a request with PSD2 parameters + * ```ts + * const result = await verifyClient.start({ + * number: TO_NUMBER, + * payee: PAYEE, + * amount: AMOUNT, + * }) + * if (result.requestId) { + * console.log(`Request started with id ${result.requestId}`); + * } else { + * console.log(`Request failed with error: ${result.errorText}`); + * } + * ``` + */ public async start( request: VerificationParameters | PSD2Parameters, ): Promise { @@ -87,6 +291,10 @@ export class Verify extends Client { Client.transformers.snakeCaseObjectKeys(omit(request, ['language'])), ); - return Client.transformers.camelCaseObjectKeys(resp.data, true, true); + return Client.transformers.camelCaseObjectKeys( + resp.data, + true, + true, + ) as VerifyError | VerifyRequest; } } diff --git a/packages/verify/package.json b/packages/verify/package.json index a5272981..c1a136f8 100644 --- a/packages/verify/package.json +++ b/packages/verify/package.json @@ -1,7 +1,8 @@ { + "$schema": "https://json.schemastore.org/package.json", "name": "@vonage/verify", "version": "1.9.0", - "description": "Verify package for Vonage", + "description": "Verify API provides a choice of routes for sending a code to a user. You can use this to confirm a user's contact information, as a second factor when authenticating users, or for step-up authentication.", "keywords": [ "vonage", "verify", @@ -19,7 +20,16 @@ "url": "git+https://github.com/Vonage/vonage-node-sdk.git" }, "license": "Apache-2.0", - "author": "Chris Tankersley ", + "contributors": [ + { + "name": "Chris Tankersley", + "url": "https://github.com/dragonmantank" + }, + { + "name": "Chuck \"MANCHUCK\" Reeves", + "url": "https://github.com/manchuck" + } + ], "main": "dist/index.js", "types": "dist/index.d.ts", "directories": { @@ -32,9 +42,11 @@ "scripts": { "build": "npm run clean && npm run compile", "clean": "npx shx rm -rf dist tsconfig.tsbuildinfo", - "compile": "npx tsc --build --verbose" + "compile": "npx tsc --build --verbose", + "prepublishOnly": "npm run build" }, "dependencies": { + "@types/lodash.omit": "4.5.9", "@vonage/auth": "^1.7.0", "@vonage/server-client": "^1.9.0", "@vonage/vetch": "^1.6.0", @@ -45,6 +57,5 @@ }, "publishConfig": { "access": "public" - }, - "gitHead": "328f18e5c8a458cb4d06d7955ec2399a6ce6f5d8" + } } diff --git a/packages/verify/tsconfig.json b/packages/verify/tsconfig.json index bb376b23..4365c435 100644 --- a/packages/verify/tsconfig.json +++ b/packages/verify/tsconfig.json @@ -1,20 +1,25 @@ { - "extends": "../../tsconfig.json", + "$schema": "https://json.schemastore.org/tsconfig", - "compilerOptions": { - "rootDir": "lib", - "outDir": "dist" - }, + "extends": "../../tsconfig.json", - "exclude": ["__tests__", "jest.config.js", "dist"], + "compilerOptions": { + "rootDir": "lib", + "outDir": "dist" + }, - "references": [ - { "path": "../server-client" }, - { "path": "../auth" }, - { "path": "../vetch" } - ], + "exclude": [ + "__tests__", + "dist" + ], - "ts-node": { - "esm": true - } + "references": [ + { "path": "../server-client" }, + { "path": "../auth" }, + { "path": "../vetch" } + ], + + "ts-node": { + "esm": true + } } diff --git a/packages/verify/typedoc.json b/packages/verify/typedoc.json new file mode 100644 index 00000000..366a8a89 --- /dev/null +++ b/packages/verify/typedoc.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "extends": ["../../typedoc.base.json"], + "entryPoints": ["lib/index.ts"], + "name": "Vonage Verify" +} diff --git a/packages/verify2/lib/enums/channels.ts b/packages/verify2/lib/enums/channels.ts index 66efc8e1..74d9c3db 100644 --- a/packages/verify2/lib/enums/channels.ts +++ b/packages/verify2/lib/enums/channels.ts @@ -1,13 +1,44 @@ +/** + * Enum representing different communication channels for verification. + */ export enum Channels { + /** + * SMS channel for verification. + */ SMS = 'sms', + + /** + * WhatsApp channel for verification. + */ WHATSAPP = 'whatsapp', + + /** + * Interactive WhatsApp channel for verification. + */ WHATSAPP_INTERACTIVE = 'whatsapp_interactive', + + /** + * Voice channel for verification. + */ VOICE = 'voice', + + /** + * Email channel for verification. + */ EMAIL = 'email', } +/** + * Enum representing the Silent Authentication channel. + */ export enum SilentAuthChannel { + /** + * Silent Authentication channel for verification. + */ SILENT_AUTH = 'silent_auth', } +/** + * Type alias for the Silent Authentication channel. + */ export type SilenAuthChannel = SilentAuthChannel; diff --git a/packages/verify2/lib/enums/eventStatus.ts b/packages/verify2/lib/enums/eventStatus.ts index 053745d4..de452ea8 100644 --- a/packages/verify2/lib/enums/eventStatus.ts +++ b/packages/verify2/lib/enums/eventStatus.ts @@ -1,6 +1,24 @@ +/** + * Enum representing the status of an event in the verification process. + */ export enum EventStatus { - COMPLETED = 'completed', - FAILED = 'failed', - USER_REJECTED = 'user_rejected', - REJECTED = 'rejected', + /** + * The event has been completed successfully. + */ + COMPLETED = 'completed', + + /** + * The event has failed. + */ + FAILED = 'failed', + + /** + * The user has rejected the event. + */ + USER_REJECTED = 'user_rejected', + + /** + * The event has been rejected. + */ + REJECTED = 'rejected', } diff --git a/packages/verify2/lib/enums/requestStatus.ts b/packages/verify2/lib/enums/requestStatus.ts index 6c0ad7ad..2e132d6b 100644 --- a/packages/verify2/lib/enums/requestStatus.ts +++ b/packages/verify2/lib/enums/requestStatus.ts @@ -1,5 +1,19 @@ +/** + * Enum representing the status of a verification request. + */ export enum RequestStatus { - COMPLETED = 'completed', - FAILED = 'failed', - EXPIRED = 'expired', + /** + * The verification request has been completed successfully. + */ + COMPLETED = 'completed', + + /** + * The verification request has failed. + */ + FAILED = 'failed', + + /** + * The verification request has expired. + */ + EXPIRED = 'expired', } diff --git a/packages/verify2/lib/enums/requestWorkflowsStatus.ts b/packages/verify2/lib/enums/requestWorkflowsStatus.ts index 372c47c2..c70012fb 100644 --- a/packages/verify2/lib/enums/requestWorkflowsStatus.ts +++ b/packages/verify2/lib/enums/requestWorkflowsStatus.ts @@ -1,7 +1,29 @@ +/** + * Enum representing the status of a verification request workflow step. + */ export enum RequestWorkflowStatus { - UNUSED = 'unused', - COMPLETED = 'completed', - FAILED = 'failed', - EXPIRED = 'expired', - USER_REJECTED = 'user_rejected', + /** + * The workflow step is unused. + */ + UNUSED = 'unused', + + /** + * The workflow step has been completed successfully. + */ + COMPLETED = 'completed', + + /** + * The workflow step has failed. + */ + FAILED = 'failed', + + /** + * The workflow step has expired. + */ + EXPIRED = 'expired', + + /** + * The user has rejected the workflow step. + */ + USER_REJECTED = 'user_rejected', } diff --git a/packages/verify2/lib/enums/silentAuthStatus.ts b/packages/verify2/lib/enums/silentAuthStatus.ts index cd618d44..0959d8a6 100644 --- a/packages/verify2/lib/enums/silentAuthStatus.ts +++ b/packages/verify2/lib/enums/silentAuthStatus.ts @@ -1,7 +1,29 @@ +/** + * Enum representing the status of Silent Authentication. + */ export enum SilenAuthStatus { - COMPLETED = 'completed', - FAILED = 'failed', - USER_REJECTED = 'user_rejected', - EXPIRED = 'expired', - ACTION_PENDING = 'action_pending', + /** + * Silent Authentication has been completed successfully. + */ + COMPLETED = 'completed', + + /** + * Silent Authentication has failed. + */ + FAILED = 'failed', + + /** + * The user has rejected Silent Authentication. + */ + USER_REJECTED = 'user_rejected', + + /** + * Silent Authentication has expired. + */ + EXPIRED = 'expired', + + /** + * An action is pending for Silent Authentication. + */ + ACTION_PENDING = 'action_pending', } diff --git a/packages/verify2/lib/enums/verifyErrors.ts b/packages/verify2/lib/enums/verifyErrors.ts index fb1ba4fb..15641f45 100644 --- a/packages/verify2/lib/enums/verifyErrors.ts +++ b/packages/verify2/lib/enums/verifyErrors.ts @@ -1,6 +1,16 @@ import { GenericErrors } from '@vonage/server-client'; +/** + * Type representing possible errors related to verification requests. + */ export type VerifyErrors = { - EXPIRED: 'expired' - CONFLICT: 'conflict' -} & GenericErrors + /** + * Indicates that the verification request has expired. + */ + EXPIRED: 'expired', + + /** + * Indicates a conflict error in the verification request. + */ + CONFLICT: 'conflict', +} & GenericErrors; diff --git a/packages/verify2/lib/enums/verifyLocale.ts b/packages/verify2/lib/enums/verifyLocale.ts index 13ff903a..608d2f07 100644 --- a/packages/verify2/lib/enums/verifyLocale.ts +++ b/packages/verify2/lib/enums/verifyLocale.ts @@ -1,15 +1,69 @@ +/** + * Enum representing different locales for verification. + */ export enum VerifyLocale { - EN_US = 'en-us', - EN_GB = 'en-gb', - ES_ES = 'es-es', - ES_MX = 'es-mx', - ES_US = 'es-us', - IT_IT = 'it-it', - FR_FR = 'fr-fr', - DE_DE = 'de-de', - RU_RU = 'ru-ru', - HI_IN = 'hi-in', - PT_BR = 'pt-br', - PT_PT = 'pt-pt', - ID_ID = 'id-id', + /** + * English (United States) locale. + */ + EN_US = 'en-us', + + /** + * English (United Kingdom) locale. + */ + EN_GB = 'en-gb', + + /** + * Spanish (Spain) locale. + */ + ES_ES = 'es-es', + + /** + * Spanish (Mexico) locale. + */ + ES_MX = 'es-mx', + + /** + * Spanish (United States) locale. + */ + ES_US = 'es-us', + + /** + * Italian (Italy) locale. + */ + IT_IT = 'it-it', + + /** + * French (France) locale. + */ + FR_FR = 'fr-fr', + + /** + * German (Germany) locale. + */ + DE_DE = 'de-de', + + /** + * Russian (Russia) locale. + */ + RU_RU = 'ru-ru', + + /** + * Hindi (India) locale. + */ + HI_IN = 'hi-in', + + /** + * Portuguese (Brazil) locale. + */ + PT_BR = 'pt-br', + + /** + * Portuguese (Portugal) locale. + */ + PT_PT = 'pt-pt', + + /** + * Indonesian (Indonesia) locale. + */ + ID_ID = 'id-id', } diff --git a/packages/verify2/lib/types/checkCodeRequest.ts b/packages/verify2/lib/types/checkCodeRequest.ts index 685507d9..99b268ad 100644 --- a/packages/verify2/lib/types/checkCodeRequest.ts +++ b/packages/verify2/lib/types/checkCodeRequest.ts @@ -1,3 +1,9 @@ +/** + * Represents a request to check a code against a verification request. + */ export type CheckCodeRequest = { - code: string -} + /** + * The code to be checked against the verification request. + */ + code: string; +}; diff --git a/packages/verify2/lib/types/checkRequestResponse.ts b/packages/verify2/lib/types/checkRequestResponse.ts index 1dd4588a..7efe5308 100644 --- a/packages/verify2/lib/types/checkRequestResponse.ts +++ b/packages/verify2/lib/types/checkRequestResponse.ts @@ -1,4 +1,14 @@ +/** + * Represents the response for checking a code against a verification request. + */ export type CheckRequestResponse = { - request_id: string - status: string -} + /** + * The ID of the verification request. + */ + request_id: string; + + /** + * The status of the verification request. + */ + status: string; +}; diff --git a/packages/verify2/lib/types/emailWorkflow.ts b/packages/verify2/lib/types/emailWorkflow.ts index 121113a6..a10023c1 100644 --- a/packages/verify2/lib/types/emailWorkflow.ts +++ b/packages/verify2/lib/types/emailWorkflow.ts @@ -1,7 +1,21 @@ import { Channels } from '../enums'; +/** + * Represents a workflow for sending a verification code via email. + */ export type EmailWorkflow = { - channel: Channels.EMAIL - to: string - from?: string -} + /** + * The communication channel for sending the verification code. + */ + channel: Channels.EMAIL; + + /** + * The recipient's email address where the verification code will be sent. + */ + to: string; + + /** + * (Optional) The sender's email address for the verification email. + */ + from?: string; +}; diff --git a/packages/verify2/lib/types/eventCallback.ts b/packages/verify2/lib/types/eventCallback.ts index fa38a2f6..f6f3899b 100644 --- a/packages/verify2/lib/types/eventCallback.ts +++ b/packages/verify2/lib/types/eventCallback.ts @@ -1,11 +1,42 @@ import { Channels, EventStatus } from '../enums'; +/** + * Represents an event callback received for a verification request. + */ export type EventCallback = { - request_id: string - triggerd_at: string - type: string - channel: Channels - status: EventStatus - finalized_at: string - client_ref?: string -} + /** + * The ID of the verification request associated with the event. + */ + request_id: string; + + /** + * The date and time when the event was triggered in ISO 8601 format. + */ + triggerd_at: string; // Typo: Should be 'triggered_at' + + /** + * The type of response for the event. + */ + type: string; + + /** + * The communication channel for the verification request. + */ + channel: Channels; + + /** + * The status of the event. + */ + status: EventStatus; + + /** + * The date and time when the verification request was completed + * in ISO 8601 format. + */ + finalized_at: string; + + /** + * (Optional) The client reference given in the original Verify request. + */ + client_ref?: string; +}; diff --git a/packages/verify2/lib/types/request.ts b/packages/verify2/lib/types/request.ts index 2b771386..ac539aa4 100644 --- a/packages/verify2/lib/types/request.ts +++ b/packages/verify2/lib/types/request.ts @@ -1,3 +1,9 @@ +/** + * Represents a request object with a unique request ID. + */ export type Request = { - requestId: string -} + /** + * The unique identifier for the request. + */ + requestId: string; +}; diff --git a/packages/verify2/lib/types/requestStatusCallback.ts b/packages/verify2/lib/types/requestStatusCallback.ts index 0fab3c50..94be68b5 100644 --- a/packages/verify2/lib/types/requestStatusCallback.ts +++ b/packages/verify2/lib/types/requestStatusCallback.ts @@ -1,11 +1,40 @@ import { RequestStatus } from '../enums'; import { RequestStatusCallbackWorkflow } from './requestStatusCallbackWorkflow'; +/** + * Represents a callback received for the status update of a + * verification request. + */ export type RequestStatusCallback = { - request_id: string - submitted_at: string - status: RequestStatus - type: string - channel_timeout: number - workflow: Array -} + /** + * The ID of the verification request associated with the callback. + */ + request_id: string; + + /** + * The date and time when the verification request was submitted + * in ISO 8601 format. + */ + submitted_at: string; + + /** + * The status of the verification request. + */ + status: RequestStatus; + + /** + * The type of response for the callback. + */ + type: string; + + /** + * The number of seconds before the current step in the verification + * request times out. + */ + channel_timeout: number; + + /** + * An array of workflow details for the verification request. + */ + workflow: Array; +}; diff --git a/packages/verify2/lib/types/requestStatusCallbackWorkflow.ts b/packages/verify2/lib/types/requestStatusCallbackWorkflow.ts index 7e72aaec..7195e660 100644 --- a/packages/verify2/lib/types/requestStatusCallbackWorkflow.ts +++ b/packages/verify2/lib/types/requestStatusCallbackWorkflow.ts @@ -1,7 +1,21 @@ import { Channels, RequestWorkflowStatus } from '../enums'; +/** + * Represents a workflow step within a verification request's status callback. + */ export type RequestStatusCallbackWorkflow = { - channel: Channels - initiated_at: string - status: RequestWorkflowStatus -} + /** + * The communication channel associated with this workflow step. + */ + channel: Channels; + + /** + * The date and time when this workflow step was initiated in ISO 8601 format. + */ + initiated_at: string; + + /** + * The status of this workflow step within the verification request. + */ + status: RequestWorkflowStatus; +}; diff --git a/packages/verify2/lib/types/silentAuthCallback.ts b/packages/verify2/lib/types/silentAuthCallback.ts index 54f16fa3..9e6291bf 100644 --- a/packages/verify2/lib/types/silentAuthCallback.ts +++ b/packages/verify2/lib/types/silentAuthCallback.ts @@ -1,13 +1,47 @@ import { SilentAuthChannel, SilenAuthStatus } from '../enums'; +/** + * Represents a callback received for Silent Authentication. + */ export type SilentAuthCallback = { + /** + * The ID of the Silent Authentication request associated with the callback. + */ request_id: string; - triggerd_at: string; + + /** + * The date and time when the Silent Authentication event was triggered + * in ISO 8601 format. + */ + triggerd_at: string; // Typo: Should be 'triggered_at' + + /** + * The type of response for the Silent Authentication event. + */ type: string; + + /** + * The communication channel for Silent Authentication (always 'silent_auth'). + */ channel: SilentAuthChannel.SILENT_AUTH; + + /** + * The status of the Silent Authentication event. + */ status: SilenAuthStatus; + + /** + * Information about the action in the Silent Authentication event. + */ action: { + /** + * The type of action, which is 'check' for Silent Authentication. + */ type: 'check'; + + /** + * The URL for Silent Authentication Verify workflow completion. + */ check_url: string; }; }; diff --git a/packages/verify2/lib/types/silentAuthWorkflow.ts b/packages/verify2/lib/types/silentAuthWorkflow.ts index 58e99c40..bc3fe2da 100644 --- a/packages/verify2/lib/types/silentAuthWorkflow.ts +++ b/packages/verify2/lib/types/silentAuthWorkflow.ts @@ -1,6 +1,16 @@ import { SilentAuthChannel } from '../enums'; +/** + * Represents a workflow for Silent Authentication. + */ export type SilentAuthWorkflow = { + /** + * The communication channel for Silent Authentication. + */ channel: SilentAuthChannel; + + /** + * The target identifier for Silent Authentication. + */ to: string; }; diff --git a/packages/verify2/lib/types/smsWorkflow.ts b/packages/verify2/lib/types/smsWorkflow.ts index 73225dc1..daf36f1f 100644 --- a/packages/verify2/lib/types/smsWorkflow.ts +++ b/packages/verify2/lib/types/smsWorkflow.ts @@ -1,7 +1,22 @@ import { Channels } from '../enums'; +/** + * Represents a workflow for sending a verification code via SMS. + */ export type SMSWorkflow = { - channel: Channels.SMS - to: string - appHash?: string -} + /** + * The communication channel for sending the verification code. + */ + channel: Channels.SMS; + + /** + * The recipient's phone number where the verification code will be sent, + * in the E.164 format. + */ + to: string; + + /** + * (Optional) An application-specific hash value for the SMS workflow. + */ + appHash?: string; +}; diff --git a/packages/verify2/lib/types/verifcationRequest.ts b/packages/verify2/lib/types/verifcationRequest.ts index 95c1956d..29f8913c 100644 --- a/packages/verify2/lib/types/verifcationRequest.ts +++ b/packages/verify2/lib/types/verifcationRequest.ts @@ -6,20 +6,59 @@ import { VoiceWorkflow } from './voiceWorkflow'; import { WhatsAppInteractiveWorkflow } from './whatsAppInteractiveWorkflow'; import { WhatsAppWorkflow } from './whatsAppWorkflow'; +/** + * Represents a verification request for sending verification codes via + * different communication channels. + */ export type VerificationRequest = { - brand: string - workflow: Array< - | EmailWorkflow - | (Omit & { app_hash: string }) - | SilentAuthWorkflow - | VoiceWorkflow - | WhatsAppInteractiveWorkflow - | WhatsAppWorkflow - > - code?: string - locale?: VerifyLocale - channel_timeout?: number - client_ref?: string - code_length?: 4 | 5 | 6 | 7 | 8 | 9 | 10 - fraud_check?: boolean -} + /** + * The brand associated with the verification request. + */ + brand: string; + + /** + * An array of workflow configurations for sending verification codes via + * different channels. Each element in the array corresponds to a specific + * channel workflow. + */ + workflow: Array< + | EmailWorkflow + | (Omit & { app_hash: string }) + | SilentAuthWorkflow + | VoiceWorkflow + | WhatsAppInteractiveWorkflow + | WhatsAppWorkflow + >; + + /** + * (Optional) The verification code to be sent. + */ + code?: string; + + /** + * (Optional) The locale for the verification request. + */ + locale?: VerifyLocale; + + /** + * (Optional) The timeout duration for the verification channel in seconds. + */ + channel_timeout?: number; + + /** + * (Optional) The client reference associated with the verification request. + */ + client_ref?: string; + + /** + * (Optional) The length of the verification code, if not provided, + * defaults to 4 digits. + */ + code_length?: 4 | 5 | 6 | 7 | 8 | 9 | 10; + + /** + * (Optional) Indicates whether fraud checking is enabled for the + * verification request. + */ + fraud_check?: boolean; +}; diff --git a/packages/verify2/lib/types/verifcationRequestParams.ts b/packages/verify2/lib/types/verifcationRequestParams.ts index dbd6de57..5de2a006 100644 --- a/packages/verify2/lib/types/verifcationRequestParams.ts +++ b/packages/verify2/lib/types/verifcationRequestParams.ts @@ -6,20 +6,59 @@ import { VoiceWorkflow } from './voiceWorkflow'; import { WhatsAppInteractiveWorkflow } from './whatsAppInteractiveWorkflow'; import { WhatsAppWorkflow } from './whatsAppWorkflow'; +/** + * Represents parameters for creating a verification request for sending + * verification codes via different communication channels. + */ export type VerificationRequestParams = { - brand: string - workflow: Array< - | EmailWorkflow - | SMSWorkflow - | SilentAuthWorkflow - | VoiceWorkflow - | WhatsAppInteractiveWorkflow - | WhatsAppWorkflow - > - code?: string - locale?: VerifyLocale - channelTimeout?: number - clientRef?: string - codeLength?: 4 | 5 | 6 | 7 | 8 | 9 | 10 - fraudCheck?: boolean -} + /** + * The brand associated with the verification request. + */ + brand: string; + + /** + * An array of workflow configurations for sending verification codes via + * different channels. Each element in the array corresponds to a specific + * channel workflow. + */ + workflow: Array< + | EmailWorkflow + | SMSWorkflow + | SilentAuthWorkflow + | VoiceWorkflow + | WhatsAppInteractiveWorkflow + | WhatsAppWorkflow + >; + + /** + * (Optional) The verification code to be sent. + */ + code?: string; + + /** + * (Optional) The locale for the verification request. + */ + locale?: VerifyLocale; + + /** + * (Optional) The timeout duration for the verification channel in seconds. + */ + channelTimeout?: number; + + /** + * (Optional) The client reference associated with the verification request. + */ + clientRef?: string; + + /** + * (Optional) The length of the verification code, if not provided, + * defaults to 4 digits. + */ + codeLength?: 4 | 5 | 6 | 7 | 8 | 9 | 10; + + /** + * (Optional) Indicates whether fraud checking is enabled for the + * verification request. + */ + fraudCheck?: boolean; +}; diff --git a/packages/verify2/lib/types/verificationResponse.ts b/packages/verify2/lib/types/verificationResponse.ts index a3b045ab..d89f78e1 100644 --- a/packages/verify2/lib/types/verificationResponse.ts +++ b/packages/verify2/lib/types/verificationResponse.ts @@ -1,3 +1,9 @@ +/** + * Represents a response for a verification request. + */ export type VerificationResponse = { - request_id: string -} + /** + * The unique identifier for the verification request. + */ + request_id: string; +}; diff --git a/packages/verify2/lib/types/voiceWorkflow.ts b/packages/verify2/lib/types/voiceWorkflow.ts index ab827384..31024af6 100644 --- a/packages/verify2/lib/types/voiceWorkflow.ts +++ b/packages/verify2/lib/types/voiceWorkflow.ts @@ -1,6 +1,17 @@ import { Channels } from '../enums'; +/** + * Represents a workflow for sending a verification code via voice call. + */ export type VoiceWorkflow = { - channel: Channels.VOICE - to: string -} + /** + * The communication channel for sending the verification code. + */ + channel: Channels.VOICE; + + /** + * The recipient's phone number where the verification code will be sent, + * in the E.164 format. + */ + to: string; +}; diff --git a/packages/verify2/lib/types/whatsAppInteractiveWorkflow.ts b/packages/verify2/lib/types/whatsAppInteractiveWorkflow.ts index 366ff0f6..40fc707a 100644 --- a/packages/verify2/lib/types/whatsAppInteractiveWorkflow.ts +++ b/packages/verify2/lib/types/whatsAppInteractiveWorkflow.ts @@ -1,6 +1,18 @@ import { Channels } from '../enums'; +/** + * Represents a workflow for sending a verification code via interactive + * WhatsApp. + */ export type WhatsAppInteractiveWorkflow = { - channel: Channels.WHATSAPP_INTERACTIVE - to: string -} + /** + * The communication channel for sending the verification code. + */ + channel: Channels.WHATSAPP_INTERACTIVE; + + /** + * The recipient's phone number where the verification code will be sent, + * typically in the E.164 format. + */ + to: string; +}; diff --git a/packages/verify2/lib/types/whatsAppWorkflow.ts b/packages/verify2/lib/types/whatsAppWorkflow.ts index e94d02ee..0d2f7bfe 100644 --- a/packages/verify2/lib/types/whatsAppWorkflow.ts +++ b/packages/verify2/lib/types/whatsAppWorkflow.ts @@ -1,7 +1,23 @@ import { Channels } from '../enums'; +/** + * Represents a workflow for sending a verification code via WhatsApp. + */ export type WhatsAppWorkflow = { - channel: Channels.WHATSAPP - to: string - from?: string -} + /** + * The communication channel for sending the verification code. + */ + channel: Channels.WHATSAPP; + + /** + * The recipient's phone number where the verification code will be sent, + * typically in the E.164 format. + */ + to: string; + + /** + * (Optional) The sender's phone number or identifier for the WhatsApp + * message. + */ + from?: string; +}; diff --git a/packages/verify2/lib/verify2.ts b/packages/verify2/lib/verify2.ts index 8665dc74..a3828640 100644 --- a/packages/verify2/lib/verify2.ts +++ b/packages/verify2/lib/verify2.ts @@ -6,9 +6,22 @@ import { CheckRequestResponse, } from './types'; +/** + * A class for interacting with the Vonage Verify API (Version 2). + */ export class Verify2 extends Client { + /** + * The authentication type used for this client (JWT). + */ protected authType = AuthenticationType.JWT; + /** + * Creates a new verification request. + * + * @param {VerificationRequestParams} params - The parameters for the + * verification request. + * @return {Request} A `Request` object containing the request ID. + */ public async newRequest( params: VerificationRequestParams, ): Promise { @@ -22,6 +35,12 @@ export class Verify2 extends Client { }; } + /** + * Checks a verification code against a verification request. + * @param {string} requestId - The ID of the verification request. + * @param {string} code - The verification code to check. + * @return {string} The status of the verification code check. + */ public async checkCode(requestId: string, code: string): Promise { const resp = await this.sendPostRequest( `${this.config.apiHost}/v2/verify/${requestId}`, @@ -33,6 +52,11 @@ export class Verify2 extends Client { return resp.data.status; } + /** + * Cancels a verification request. + * @param {string} requestId - The ID of the verification request to cancel. + * @return {boolean} `true` if the cancellation was successful. + */ public async cancel(requestId: string): Promise { try { await this.sendDeleteRequest( diff --git a/packages/verify2/package.json b/packages/verify2/package.json index 5e6d3fc2..d202927a 100644 --- a/packages/verify2/package.json +++ b/packages/verify2/package.json @@ -1,4 +1,5 @@ { + "$schema": "https://json.schemastore.org/package.json", "name": "@vonage/verify2", "version": "1.8.0", "description": "Verify API provides a choice of routes for sending a code to a user. You can use this to confirm a user's contact information, as a second factor when authenticating users, or for step-up authentication.", @@ -11,7 +12,16 @@ "url": "git+https://github.com/Vonage/vonage-node-sdk.git" }, "license": "Apache-2.0", - "author": "Chuck MANCHUCK Reeves ", + "contributors": [ + { + "name": "Chuck \"MANCHUCK\" Reeves", + "url": "https://github.com/manchuck" + }, + { + "name": "Chris Tankersley", + "url": "https://github.com/dragonmantank" + } + ], "main": "dist/index.js", "types": "dist/index.d.ts", "directories": { @@ -24,7 +34,8 @@ "scripts": { "build": "npm run clean && npm run compile", "clean": "npx shx rm -rf dist tsconfig.tsbuildinfo", - "compile": "npx tsc --build --verbose" + "compile": "npx tsc --build --verbose", + "prepublishOnly": "npm run build" }, "dependencies": { "@vonage/server-client": "^1.9.0" diff --git a/packages/verify2/tsconfig.json b/packages/verify2/tsconfig.json index bb376b23..4365c435 100644 --- a/packages/verify2/tsconfig.json +++ b/packages/verify2/tsconfig.json @@ -1,20 +1,25 @@ { - "extends": "../../tsconfig.json", + "$schema": "https://json.schemastore.org/tsconfig", - "compilerOptions": { - "rootDir": "lib", - "outDir": "dist" - }, + "extends": "../../tsconfig.json", - "exclude": ["__tests__", "jest.config.js", "dist"], + "compilerOptions": { + "rootDir": "lib", + "outDir": "dist" + }, - "references": [ - { "path": "../server-client" }, - { "path": "../auth" }, - { "path": "../vetch" } - ], + "exclude": [ + "__tests__", + "dist" + ], - "ts-node": { - "esm": true - } + "references": [ + { "path": "../server-client" }, + { "path": "../auth" }, + { "path": "../vetch" } + ], + + "ts-node": { + "esm": true + } } diff --git a/packages/verify2/typedoc.json b/packages/verify2/typedoc.json new file mode 100644 index 00000000..59c737a5 --- /dev/null +++ b/packages/verify2/typedoc.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "extends": ["../../typedoc.base.json"], + "entryPoints": ["lib/index.ts"], + "name": "Vonage Verify v2" +} diff --git a/packages/vetch/__tests__/index.test.ts b/packages/vetch/__tests__/index.test.ts deleted file mode 100644 index 62bc97af..00000000 --- a/packages/vetch/__tests__/index.test.ts +++ /dev/null @@ -1,5 +0,0 @@ -import * as main from '../lib'; - -test('main exports', () => { - expect(main.Vetch).toBeDefined(); -}); diff --git a/packages/vetch/__tests__/vetch.test.ts b/packages/vetch/__tests__/vetch.test.ts deleted file mode 100644 index cce67c3d..00000000 --- a/packages/vetch/__tests__/vetch.test.ts +++ /dev/null @@ -1,207 +0,0 @@ -import { Vetch, request } from '../lib'; -import { stringify } from 'querystring'; -import nock from 'nock'; -import { HTTPMethods } from '../lib/enums/HTTPMethods'; - -nock.disableNetConnect(); - -afterEach(() => { - nock.cleanAll(); -}); - -const url = 'https://just-testing.com'; - -describe('option validation', () => { - test('should throw error if no url provided', async () => { - expect.assertions(1); - await expect(request({})).rejects.toEqual(new Error('URL is required.')); - }); -}); - -describe('error handling', () => { - test('should throw on non-2xx responses by default', async () => { - expect.assertions(1); - nock(url).get('/').reply(500); - await expect(request({ url })).rejects.toEqual( - expect.objectContaining({ code: '500' }), - ); - }); -}); - -describe('option configuration', () => { - test('should use options passed in constructor', async () => { - expect.assertions(1); - nock(url).head('/').reply(200); - const inst = new Vetch({ method: HTTPMethods.HEAD }); - const res = await inst.request({ url }); - expect(res.config.method).toEqual('HEAD'); - }); - - test('should allow nested options passed in constructor', async () => { - expect.assertions(2); - nock(url).get('/').reply(200); - const inst = new Vetch({ headers: { spiderman: 'Norman Osbourne' } }); - const res = await inst.request({ - url, - headers: { ironMan: 'Mandarin' }, - }); - expect(res.config.headers?.spiderman).toEqual('Norman Osbourne'); - expect(res.config.headers?.ironMan).toEqual('Mandarin'); - }); - - test('should allow setting a base url', async () => { - expect.assertions(1); - nock(url).get('/v1/thor').reply(200, {}); - const inst = new Vetch({ baseURL: `${url}/v1` }); - const res = await inst.request({ url: '/thor' }); - expect(res.data).toEqual({}); - }); - - test('should allow URL params', async () => { - expect.assertions(2); - const qs = '?black=panther&captain=america'; - const opts = { url: `${url}/${qs}` }; - nock(url).get(`/${qs}`).reply(200, {}); - const res = await request(opts); - expect(res.status).toEqual(200); - expect(res.config.url).toEqual(`${url}/${qs}`); - }); - - test('should encode params from object', async () => { - const opts = { - url, - params: { - black: 'panther', - captain: 'america', - }, - }; - const qs = '?black=panther&captain=america'; - nock(url).get(`/${qs}`).reply(200, {}); - const res = await request(opts); - expect(res.status).toEqual(200); - expect(res.config.url).toEqual(`${url}${qs}`); - }); - - test('should merge URL with params from options', async () => { - const opts = { - url: `${url}?black=panther`, - params: { - captain: 'america', - }, - }; - const qs = '?black=panther&captain=america'; - nock(url).get(`/${qs}`).reply(200, {}); - const res = await request(opts); - expect(res.status).toEqual(200); - expect(res.config.url).toEqual(`${url}${qs}`); - }); - - test('should return json by default', async () => { - const body = { avengers: 'assemble' }; - nock(url).get('/').reply(200, body); - const res = await request({ url }); - expect(res.data).toEqual(body); - }); - - test('should default to application/json', async () => { - nock(url).matchHeader('accept', 'application/json').get('/').reply(200, {}); - const res = await request({ url }); - expect(res.data).toEqual({}); - }); - - test('should include the request data in the response config', async () => { - const body = { avengers: 'assemble' }; - nock(url).post('/', body).reply(200); - const res = await request({ url, method: HTTPMethods.POST, data: body }); - expect(res.config.data).toEqual(body); - }); - - test('should allow for our custom user agent', async () => { - const options = { - reqheaders: { - 'user-agent': (val: string) => { - return /^@vonage\/server-sdk\/[\d].[\d].[\d].* node\/.*$/.test(val); - }, - }, - }; - - nock(url, options).get('/').reply(200); - const inst = new Vetch(); - await inst.request({ url }); - expect(nock.isDone()).toBeTruthy(); - }); - - test('should append to user agent', async () => { - const options = { - reqheaders: { - 'user-agent': (val: string) => { - return /^@vonage\/server-sdk\/[\d].[\d].[\d].* node\/.* foo$/.test( - val, - ); - }, - }, - }; - - nock(url, options).get('/').reply(200); - const inst = new Vetch(); - await inst.request({ url, appendUserAgent: 'foo' }); - expect(nock.isDone()).toBeTruthy(); - }); - - test('should timeout', async () => { - nock(url).get('/').delayConnection(5).reply(200); - const inst = new Vetch({ timeout: 1 }); - await expect(inst.request({ url })).rejects.toThrow( - 'The user aborted a request', - ); - }); -}); - -describe('data handling', () => { - test('should accept a string in the request data', async () => { - const body = { avengers: 'assemble' }; - const encoded = stringify(body); - nock(url) - .matchHeader('content-type', 'application/x-www-form-urlencoded') - .post('/', encoded) - .reply(200, {}); - const res = await request({ - url, - method: HTTPMethods.POST, - data: encoded, - headers: { 'content-type': 'application/x-www-form-urlencoded' }, - }); - expect(res.data).toEqual({}); - }); - - test('should default to application/json content-type with object request', async () => { - const body = { avengers: 'assemble' }; - nock(url) - .matchHeader('Content-Type', 'application/json') - .post('/', JSON.stringify(body)) - .reply(200, {}); - const res = await request({ - url, - method: HTTPMethods.POST, - data: body, - }); - - expect(res.data).toEqual({}); - }); -}); - -describe('defaults and instances', () => { - test('should allow creating a new instance', () => { - const vetch = new Vetch(); - expect(typeof vetch.request).toEqual('function'); - }); - - it('should allow passing empty options', async () => { - const body = { avengers: 'assemble' }; - nock(url).get('/').reply(200, body); - const vetch = new Vetch({ url }); - const res = await vetch.request(); - - expect(res.data).toEqual(body); - }); -}); diff --git a/packages/vetch/lib/enums/HTTPMethods.ts b/packages/vetch/lib/enums/HTTPMethods.ts index 9439eebd..da266a58 100644 --- a/packages/vetch/lib/enums/HTTPMethods.ts +++ b/packages/vetch/lib/enums/HTTPMethods.ts @@ -1,11 +1,19 @@ +/** + * Enum representing the HTTP methods that can be used for Vonage API requests. + */ export enum HTTPMethods { - GET = 'GET', - HEAD = 'HEAD', - POST = 'POST', - DELETE = 'DELETE', - PUT = 'PUT', - CONNECT = 'CONNECT', - OPTIONS = 'OPTIONS', - TRACE = 'TRACE', - PATCH = 'PATCH', + /** Represents an HTTP GET request. */ + GET = 'GET', + + /** Represents an HTTP POST request. */ + POST = 'POST', + + /** Represents an HTTP DELETE request. */ + DELETE = 'DELETE', + + /** Represents an HTTP PUT request. */ + PUT = 'PUT', + + /** Represents an HTTP PATCH request. */ + PATCH = 'PATCH', } diff --git a/packages/vetch/lib/enums/contentType.ts b/packages/vetch/lib/enums/contentType.ts new file mode 100644 index 00000000..5b71c1f2 --- /dev/null +++ b/packages/vetch/lib/enums/contentType.ts @@ -0,0 +1,21 @@ +/** + * Enum representing possible MIME types for the 'content-type' HTTP header that + * Vonage API's could accept. + * + * Note: Most of the APIs will only accept `application/json`. Please refer + * to the specific API documentation to determine if another content type is + * accepted + */ +export enum ContentType { + /** Represents the MIME type for JSON data. */ + JSON = 'application/json', + + /** Represents the MIME type for URL-encoded form data. */ + FORM_URLENCODED = 'application/x-www-form-urlencoded', + + /** Represents the MIME type for XML data. */ + XML = 'application/xml', + + /** Represents the MIME type for CSV data. */ + CSV = 'text/csv', +} diff --git a/packages/vetch/lib/enums/index.ts b/packages/vetch/lib/enums/index.ts new file mode 100644 index 00000000..f509c08d --- /dev/null +++ b/packages/vetch/lib/enums/index.ts @@ -0,0 +1,3 @@ +export * from './HTTPMethods'; +export * from './contentType'; +export * from './responseTypes'; diff --git a/packages/vetch/lib/enums/responseTypes.ts b/packages/vetch/lib/enums/responseTypes.ts index 2fa140c2..02e1c922 100644 --- a/packages/vetch/lib/enums/responseTypes.ts +++ b/packages/vetch/lib/enums/responseTypes.ts @@ -1,5 +1,22 @@ +/** + * @deprecated + * Enum representing the expected response types for API requests. This was + * originaly used to set what the expected response type will be. It is better + * to use the content-type header from the response to decode properly. + */ export enum ResponseTypes { + /** + * Represents a JSON-formatted response. + */ json = 'json', + + /** + * Represents a stream response, typically for handling large data or files. + */ stream = 'stream', + + /** + * Represents a plain text response. + */ text = 'text', } diff --git a/packages/vetch/lib/errors/vetchError.ts b/packages/vetch/lib/errors/vetchError.ts new file mode 100644 index 00000000..811a9d23 --- /dev/null +++ b/packages/vetch/lib/errors/vetchError.ts @@ -0,0 +1,32 @@ +import { VetchOptions } from '../types'; +import { Response } from 'node-fetch'; + +/** + * Class representing an error from a Vetch API request. Extends the built-in + * Error class and adds additional properties related to the API request and + * response. + * + * @template T - The type of the data payload in the VetchResponse, expected to be an object that has been decoded from JSON or WebForm. + * + * @property {string} [code] - An optional error code. + * @property {VetchOptions} config - Configuration options for the API request. + * @property {VetchResponse} response - The API response that resulted in the error. + */ +export class VetchError extends Error { + code?: string; + config: VetchOptions; + response?: Response; + + /** + * Creates an instance of VetchError. + * + * @param {string} message - The error message. + * @param {VetchOptions} options - Configuration options for the API request. + * @param {VetchResponse} response - Configuration options for the API request. + */ + constructor(message: string, options: VetchOptions, response?: Response) { + super(message); + this.config = options; + this.response = response; + } +} diff --git a/packages/vetch/lib/index.ts b/packages/vetch/lib/index.ts index 697cc381..0d30b0c3 100644 --- a/packages/vetch/lib/index.ts +++ b/packages/vetch/lib/index.ts @@ -1,16 +1,3 @@ -import { Vetch } from './vetch'; -import { VetchOptions } from './interfaces/vetchOptions'; - -export { Vetch, VetchOptions }; - -export const instance = new Vetch(); - -export async function request(opts: VetchOptions) { - return instance.request(opts); -} -export { VetchError } from './types/vetchError'; -export { Headers } from './interfaces/headers'; -export { VetchPromise } from './types/vetchPromise'; -export { VetchResponse } from './interfaces/vetchResponse'; -export { ResponseTypes } from './enums/responseTypes'; -export * from './enums/HTTPMethods'; +export * from './types'; +export * from './enums'; +export * from './errors/vetchError'; diff --git a/packages/vetch/lib/interfaces/headers.ts b/packages/vetch/lib/interfaces/headers.ts deleted file mode 100644 index b90f8111..00000000 --- a/packages/vetch/lib/interfaces/headers.ts +++ /dev/null @@ -1,3 +0,0 @@ -export interface Headers { - [index: string]: any -} diff --git a/packages/vetch/lib/interfaces/vetchHttpRequest.ts b/packages/vetch/lib/interfaces/vetchHttpRequest.ts deleted file mode 100644 index 54e14902..00000000 --- a/packages/vetch/lib/interfaces/vetchHttpRequest.ts +++ /dev/null @@ -1,3 +0,0 @@ -export interface VetchHttpRequest { - responseUrl: string -} diff --git a/packages/vetch/lib/interfaces/vetchOptions.ts b/packages/vetch/lib/interfaces/vetchOptions.ts deleted file mode 100644 index d320ea31..00000000 --- a/packages/vetch/lib/interfaces/vetchOptions.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { HTTPMethods } from '../enums/HTTPMethods'; -import { Headers } from './headers'; -import { ResponseTypes } from '../enums/responseTypes'; -import http from 'http'; -import https from 'https'; -import URL from 'url'; -import { VetchPromise } from '../types/vetchPromise'; - -export interface VetchOptions { - adapter?: ( - options: VetchOptions, - defaultAdapter: (options: VetchOptions) => VetchPromise - ) => VetchPromise; - url?: string; - baseUrl?: string; - baseURL?: string; - method?: HTTPMethods; - headers?: Headers; - data?: any; - body?: any; - params?: any; - responseType?: ResponseTypes; - checkStatus?: (status: number) => boolean; - size?: number; - timeout?: number; - appendUserAgent?: string; - agent?: - | boolean - | http.Agent - | https.Agent - | ((parsedUrl: URL) => boolean | https.Agent | http.Agent); -} diff --git a/packages/vetch/lib/interfaces/vetchResponse.ts b/packages/vetch/lib/interfaces/vetchResponse.ts deleted file mode 100644 index 0b1af586..00000000 --- a/packages/vetch/lib/interfaces/vetchResponse.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { Headers } from './headers'; -import { VetchHttpRequest } from './vetchHttpRequest'; -import { VetchOptions } from './vetchOptions'; - -export interface VetchResponse { - config: VetchOptions - data: T - error?: true - status: number - statusText: string - headers: Headers - request: VetchHttpRequest -} diff --git a/packages/vetch/lib/types/headers.ts b/packages/vetch/lib/types/headers.ts new file mode 100644 index 00000000..e927ab3d --- /dev/null +++ b/packages/vetch/lib/types/headers.ts @@ -0,0 +1,9 @@ +/** + * Interface representing HTTP headers as a string-keyed object. Each property + * represents a header name, and the associated value can be a string or an + * array of strings. Includes optional 'authorization' and 'content-type' + * properties with restricted possible values for 'content-type'. + */ +export type Headers = { + [index: string]: string; +}; diff --git a/packages/vetch/lib/types/index.ts b/packages/vetch/lib/types/index.ts new file mode 100644 index 00000000..285cee8d --- /dev/null +++ b/packages/vetch/lib/types/index.ts @@ -0,0 +1,4 @@ +export * from './headers'; +export * from './vetchOptions'; +export * from './vetchPromise'; +export * from './vetchResponse'; diff --git a/packages/vetch/lib/types/vetchError.ts b/packages/vetch/lib/types/vetchError.ts deleted file mode 100644 index 629c2ec4..00000000 --- a/packages/vetch/lib/types/vetchError.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { VetchResponse } from '../interfaces/vetchResponse'; -import { VetchOptions } from '../interfaces/vetchOptions'; - -export class VetchError extends Error { - code?: string; - config: VetchOptions; - response: VetchResponse; - - constructor(message: string, options: VetchOptions) { - super(message); - this.config = options; - } -} diff --git a/packages/vetch/lib/types/vetchOptions.ts b/packages/vetch/lib/types/vetchOptions.ts new file mode 100644 index 00000000..3fae6e9a --- /dev/null +++ b/packages/vetch/lib/types/vetchOptions.ts @@ -0,0 +1,61 @@ +import { ContentType, HTTPMethods, ResponseTypes } from '../enums'; +import { Headers } from './headers'; + +/** + * Options to configure the Vetch request. + */ +export type VetchOptions = { + /** + * The content type for the request, e.g., JSON, WebForm, etc. + */ + type: ContentType; + + /** + * The HTTP method to use for the request, e.g., GET, POST, etc. + */ + method: HTTPMethods; + + /** + * The URL endpoint for the request. + */ + url: string; + + /** + * Request body data. Use 'data' instead of 'body' for newer implementations. + */ + data?: Record | string; + + /** @deprecated Use 'data' instead of 'body' */ + body?: Record | string; + + /** + * Query parameters for the request. + */ + params?: Record; + + /** + * Expected response type. + * @deprecated `ResponseTypes` is deprecated and will be removed in future versions. + */ + responseType?: ResponseTypes; + + /** + * A function to check the response status. + */ + checkStatus?: (status: number) => boolean; + + /** + * Additional user agent string to append. + */ + appendUserAgent?: string; + + /** + * The headers to be sent with the request. + */ + headers?: Headers; + + /** + * Time in milliseconds to wait for the request to complete. + */ + timeout?: number; +}; diff --git a/packages/vetch/lib/types/vetchPromise.ts b/packages/vetch/lib/types/vetchPromise.ts index f71a2f32..34942934 100644 --- a/packages/vetch/lib/types/vetchPromise.ts +++ b/packages/vetch/lib/types/vetchPromise.ts @@ -1,3 +1,12 @@ -import { VetchResponse } from '../interfaces/vetchResponse'; +import { VetchResponse } from './vetchResponse'; +/** + * Type representing a promise that resolves with a standardized Vetch API + * response. Vetch ("Vonage Fetch") ensures a consistent API response + * structure, irrespective of the HTTP adapter utilized by the developer. + * + * @deprecated + * + * @template T - The type of the data payload in the VetchResponse, expected to be an object that has been decoded from JSON or WebForm. + */ export type VetchPromise = Promise> diff --git a/packages/vetch/lib/types/vetchResponse.ts b/packages/vetch/lib/types/vetchResponse.ts new file mode 100644 index 00000000..9e9f0201 --- /dev/null +++ b/packages/vetch/lib/types/vetchResponse.ts @@ -0,0 +1,39 @@ +import { VetchOptions } from './vetchOptions'; +import { Headers } from '../types'; + +/** + * Represents the response returned by a Vetch request. + * + * @template T - The type of the response data. + */ +export type VetchResponse = { + /** + * The configuration options used for the request. + */ + config: VetchOptions; + + /** + * The parsed response data. + */ + data: T; + + /** + * The response headers. + */ + headers: Headers; + + /** + * The HTTP status code of the response. + */ + status: number; + + /** + * The HTTP status text of the response. + */ + statusText: string; + + /** + * The configuration options for the request (same as 'config'). + */ + request: VetchOptions; +}; diff --git a/packages/vetch/lib/vetch.ts b/packages/vetch/lib/vetch.ts deleted file mode 100644 index fc486e06..00000000 --- a/packages/vetch/lib/vetch.ts +++ /dev/null @@ -1,177 +0,0 @@ -import fetch, { Response as fetchResponse, options } from 'node-fetch'; -import { stringify } from 'querystring'; -import merge from 'lodash.merge'; -import http from 'http'; -import https from 'https'; -import { VetchError } from './types/vetchError'; -import { Headers } from './interfaces/headers'; -import { VetchResponse } from './interfaces/vetchResponse'; -import { ResponseTypes } from './enums/responseTypes'; -import { VetchOptions } from './interfaces/vetchOptions'; -import debug from 'debug'; - -const log = debug('vonage:vetch'); - -export class Vetch { - defaults: VetchOptions; - - constructor(defaults?: VetchOptions) { - this.defaults = defaults || { responseType: ResponseTypes.json }; - if (!this.defaults.responseType) { - this.defaults.responseType = ResponseTypes.json; - } - } - - private async _defaultAdapter( - opts: VetchOptions, - ): Promise> { - const { timeout } = opts; - let timeoutId = null; - const fetchConfig: options = opts; - if (timeout) { - const controller = new AbortController(); - timeoutId = setTimeout(() => controller.abort(), timeout); - fetchConfig.signal = controller.signal; - } - - try { - const res = await fetch(opts.url, fetchConfig); - const data = await this.getResponseData(opts, res); - return this.createResponse(opts, res, data); - } finally { - clearTimeout(timeoutId); - } - } - - async request(opts: VetchOptions = {}): Promise> { - opts = this.validateOpts(opts); - - log('api request', opts); - - const formattedResponse = await this._defaultAdapter(opts); - - log('api response', formattedResponse); - if (!opts.checkStatus(formattedResponse.status)) { - const err = new VetchError( - `Request failed with status code ${formattedResponse.status}`, - opts, - ); - err.code = String(formattedResponse.status); - err.response = formattedResponse; - throw err; - } - - return formattedResponse; - } - - private async getResponseData( - opts: VetchOptions, - res: fetchResponse, - ): Promise { - switch (opts.responseType) { - case 'stream': - return res.buffer(); - case 'json': { - let data = await res.text(); - try { - data = JSON.parse(data); - } catch { - // continue - } - return data; - } - default: - return res.text(); - } - } - - private validateOpts(options: VetchOptions): VetchOptions { - const opts = merge({}, this.defaults, options); - - opts.headers = opts.headers || {}; - opts.checkStatus = this.checkStatus; - - if (!opts.url) { - throw new Error('URL is required.'); - } - - const baseUrl = opts.baseUrl || opts.baseURL; - if (baseUrl) { - opts.url = baseUrl + opts.url; - } - - if (opts.params) { - let queryParams = stringify(opts.params); - if (queryParams.startsWith('?')) { - queryParams = queryParams.slice(1); - } - - const prefix = opts.url.includes('?') ? '&' : '?'; - opts.url = `${opts.url}${prefix}${queryParams}`; - } - - if (opts.data) { - if (typeof opts.data === 'object') { - opts.body = JSON.stringify(opts.data); - opts.headers['Content-Type'] = 'application/json'; - } else { - opts.body = opts.data; - } - } - - if (!opts.headers.Accept && opts.responseType === 'json') { - opts.headers.Accept = 'application/json'; - } - - // Set our user agent - opts.headers['user-agent'] = [ - `@vonage/server-sdk/3.0.0`, - ` node/${process.version.replace('v', '')}`, - opts.appendUserAgent ? ` ${opts.appendUserAgent}` : '', - ].join(''); - - // Allow a custom timeout to be used - const httpAgent = new http.Agent({ - timeout: opts.timeout, - }); - const httpsAgent = new https.Agent({ - timeout: opts.timeout, - }); - opts.agent = (parsedUrl: URL): https.Agent | http.Agent => { - if (parsedUrl.protocol === 'http:') { - return httpAgent; - } else { - return httpsAgent; - } - }; - - return opts; - } - - private checkStatus(status: number) { - return status >= 200 && status < 300; - } - - private createResponse( - opts: VetchOptions, - res: fetchResponse, - data?: T, - ): VetchResponse { - const headers = {} as Headers; - - res.headers.forEach((value, key) => { - headers[key] = value; - }); - - return { - config: opts, - data: data as T, - headers, - status: res.status, - statusText: res.statusText, - request: { - responseUrl: res.url, - }, - }; - } -} diff --git a/packages/vetch/package.json b/packages/vetch/package.json index fe49b19f..9ccbdb74 100644 --- a/packages/vetch/package.json +++ b/packages/vetch/package.json @@ -1,7 +1,8 @@ { + "$schema": "https://json.schemastore.org/package.json", "name": "@vonage/vetch", "version": "1.6.0", - "description": "Vonage package for server side fetch.", + "description": "Vonage's type and enum definitions module for server-side HTTP interactions.", "homepage": "https://github.com/vonage/vonage-node-sdk/tree/master/packages/vetch#readme", "bugs": { "url": "https://github.com/Vonage/vonage-node-sdk/issues" @@ -11,7 +12,20 @@ "url": "git+https://github.com/Vonage/vonage-node-sdk.git" }, "license": "Apache-2.0", - "author": "Kelly J Andrews ", + "contributors": [ + { + "name": "Kelly J Andrews", + "url": "https://github.com/kellyjandrews" + }, + { + "name": "Chris Tankersley", + "url": "https://github.com/dragonmantank" + }, + { + "name": "Chuck \"MANCHUCK\" Reeves", + "url": "https://github.com/manchuck" + } + ], "main": "dist/index.js", "types": "dist/index.d.ts", "files": [ @@ -20,15 +34,11 @@ "scripts": { "build": "npm run clean && npm run compile", "clean": "npx shx rm -rf dist tsconfig.tsbuildinfo", - "compile": "npx tsc --build --verbose" + "compile": "npx tsc --build --verbose", + "prepublishOnly": "npm run build" }, "dependencies": { - "debug": "^4.3.4", - "lodash.merge": "^4.6.2", - "node-fetch": "^2.2" - }, - "devDependencies": { - "nock": "^13.3.4" + "node-fetch": "^2.7" }, "publishConfig": { "directory": "dist" diff --git a/packages/vetch/tsconfig.json b/packages/vetch/tsconfig.json index d6934c67..d79f1087 100644 --- a/packages/vetch/tsconfig.json +++ b/packages/vetch/tsconfig.json @@ -1,18 +1,20 @@ { - "extends": "../../tsconfig.json", + "$schema": "https://json.schemastore.org/tsconfig", - "compilerOptions": { - "rootDir": "lib", - "outDir": "dist" - }, + "extends": "../../tsconfig.json", - "exclude": [ - "__tests__", - "jest.config.js", - "dist" - ], + "compilerOptions": { + "rootDir": "lib", + "outDir": "dist" + }, - "ts-node": { - "esm": true - } + "exclude": [ + "__tests__", + "jest.config.js", + "dist" + ], + + "ts-node": { + "esm": true + } } diff --git a/packages/vetch/typedoc.json b/packages/vetch/typedoc.json new file mode 100644 index 00000000..db67527c --- /dev/null +++ b/packages/vetch/typedoc.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "extends": ["../../typedoc.base.json"], + "entryPoints": ["lib/index.ts"], + "name": "Vonage Vetch" +} diff --git a/packages/video/__tests__/__dataSets__/video.ts b/packages/video/__tests__/__dataSets__/video.ts index f8dce119..0d728f09 100644 --- a/packages/video/__tests__/__dataSets__/video.ts +++ b/packages/video/__tests__/__dataSets__/video.ts @@ -1,7 +1,7 @@ import { ExperienceComposerResolution } from '../../lib/enums/ExperienceComposerResolution'; -import { ExperienceComposerOptions } from '../../lib/interfaces/ExperienceComposerOptions'; -import { CaptionOptions } from '../../lib/interfaces/CaptionOptions'; -import { SIPCallOptions } from '../../lib/interfaces/SIPCallOptions'; +import { ExperienceComposerOptions } from '../../lib/types/ExperienceComposerOptions'; +import { CaptionOptions } from '../../lib/types/CaptionOptions'; +import { SIPCallOptions } from '../../lib/types/SIPCallOptions'; const renderInformation = { id: '1248e7070b81464c9789f46ad10e7764', diff --git a/packages/video/__tests__/video.test.ts b/packages/video/__tests__/video.test.ts index c8e83627..5c4fd3e2 100644 --- a/packages/video/__tests__/video.test.ts +++ b/packages/video/__tests__/video.test.ts @@ -1,12 +1,12 @@ import nock from 'nock'; import fs from 'fs'; import { Video } from '../lib/video'; -import { decode } from 'jsonwebtoken' +import { decode } from 'jsonwebtoken'; import { LayoutType } from '../lib/enums/LayoutType'; -import { MediaMode } from '../lib/interfaces/MediaMode'; -import { ArchiveMode } from '../lib/interfaces/ArchiveMode'; +import { MediaMode } from '../lib/enums/MediaMode'; +import { ArchiveMode } from '../lib/types/ArchiveMode'; import { Auth } from '@vonage/auth'; -import testDataSets from './__dataSets__/index' +import testDataSets from './__dataSets__/index'; const BASE_URL = 'https://video.api.vonage.com/'.replace(/\/+$/, ''); @@ -18,16 +18,16 @@ describe.each(testDataSets)('$label', ({ tests }) => { client = new Video(new Auth({ applicationId: 'abcd-1234', privateKey: fs.readFileSync(`${__dirname}/private.test.key`).toString() })); scope = nock(BASE_URL, { reqheaders: { - authorization: value => value.startsWith('Bearer ') && value.length > 10 - } - }).persist() + authorization: value => value.startsWith('Bearer ') && value.length > 10, + }, + }).persist(); }); afterEach(() => { client = null; scope = null; nock.cleanAll(); - }) + }); test.each(tests)( 'Can $label using: $clientMethod', @@ -36,34 +36,34 @@ describe.each(testDataSets)('$label', ({ tests }) => { const results = await client[clientMethod](...parameters); expect(results).toEqual(expected); expect(nock.isDone()).toBeTruthy(); - } - ) -}) + }, + ); +}); // Legacy unit tests describe('video', () => { let client; beforeEach(() => { - client = new Video(new Auth({ applicationId: 'abcd-1234', privateKey: fs.readFileSync(`${__dirname}/private.test.key`).toString() })); + client = new Video(new Auth({ applicationId: 'abcd-1234', privateKey: fs.readFileSync(`${__dirname}/private.test.key`).toString() })); }); afterEach(() => { - client = null; + client = null; }); test("can create a server session", async () => { - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() - .post('/session/create', /archiveMode=manual&p2p.preference=disabled&location=/) - .reply(200, [ + .post('/session/create', /archiveMode=manual&location=null&p2p.preference=disabled/) + .reply(200, { "session_id": "the session ID", "project_id": "your OpenTok API key", "create_dt": "The creation date", - "media_server_url": "The URL of the OpenTok media router used by the session -- ignore this" - } - ]); + "media_server_url": "The URL of the OpenTok media router used by the session -- ignore this", + }, + ); const session = await client.createSession(); expect(session.sessionId).toEqual('the session ID'); @@ -73,19 +73,19 @@ describe('video', () => { }); test("can creating a server session properly sets correct p2p preference for relayed", async () => { - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() - .post('/session/create', /archiveMode=manual&p2p.preference=enabled&location=/) - .reply(200, [ + .post('/session/create', /archiveMode=manual&location=null&p2p.preference=enabled/) + .reply(200, { "session_id": "the session ID", "project_id": "your OpenTok API key", "create_dt": "The creation date", - "media_server_url": "The URL of the OpenTok media router used by the session -- ignore this" - } - ]); + "media_server_url": "The URL of the OpenTok media router used by the session -- ignore this", + }, + ); - const session = await client.createSession({mediaMode: MediaMode.RELAYED}); + const session = await client.createSession({ mediaMode: MediaMode.RELAYED }); expect(session.sessionId).toEqual('the session ID'); expect(session.archiveMode).toEqual(ArchiveMode.MANUAL); expect(session.mediaMode).toEqual(MediaMode.RELAYED); @@ -93,19 +93,19 @@ describe('video', () => { }); test("can creating a server session properly sets correct p2p preference for routed", async () => { - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() - .post('/session/create', /archiveMode=manual&p2p.preference=disabled&location=/) - .reply(200, [ + .post('/session/create', /archiveMode=manual&location=null&p2p.preference=disabled/) + .reply(200, { "session_id": "the session ID", "project_id": "your OpenTok API key", "create_dt": "The creation date", - "media_server_url": "The URL of the OpenTok media router used by the session -- ignore this" - } - ]); + "media_server_url": "The URL of the OpenTok media router used by the session -- ignore this", + }, + ); - const session = await client.createSession({mediaMode: MediaMode.ROUTED}); + const session = await client.createSession({ mediaMode: MediaMode.ROUTED }); expect(session.sessionId).toEqual('the session ID'); expect(session.archiveMode).toEqual(ArchiveMode.MANUAL); expect(session.mediaMode).toEqual(MediaMode.ROUTED); @@ -113,19 +113,19 @@ describe('video', () => { }); test("can creating a server session properly sets correct archive mode for manual", async () => { - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() - .post('/session/create', /archiveMode=manual&p2p.preference=disabled&location=/) - .reply(200, [ + .post('/session/create', /archiveMode=manual&location=null&p2p.preference=disabled/) + .reply(200, { "session_id": "the session ID", "project_id": "your OpenTok API key", "create_dt": "The creation date", - "media_server_url": "The URL of the OpenTok media router used by the session -- ignore this" - } - ]); + "media_server_url": "The URL of the OpenTok media router used by the session -- ignore this", + }, + ); - const session = await client.createSession({ArchiveMode: ArchiveMode.MANUAL}); + const session = await client.createSession({ ArchiveMode: ArchiveMode.MANUAL }); expect(session.sessionId).toEqual('the session ID'); expect(session.archiveMode).toEqual(ArchiveMode.MANUAL); expect(session.mediaMode).toEqual(MediaMode.ROUTED); @@ -133,19 +133,19 @@ describe('video', () => { }); test("can creating a server session properly sets correct archive mode for always", async () => { - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() - .post('/session/create', /archiveMode=always&p2p.preference=disabled&location=/) - .reply(200, [ + .post('/session/create', /archiveMode=always&location=null&p2p.preference=disabled/) + .reply(200, { "session_id": "the session ID", "project_id": "your OpenTok API key", "create_dt": "The creation date", - "media_server_url": "The URL of the OpenTok media router used by the session -- ignore this" - } - ]); + "media_server_url": "The URL of the OpenTok media router used by the session -- ignore this", + }, + ); - const session = await client.createSession({archiveMode: ArchiveMode.ALWAYS}); + const session = await client.createSession({ archiveMode: ArchiveMode.ALWAYS }); expect(session.sessionId).toEqual('the session ID'); expect(session.archiveMode).toEqual(ArchiveMode.ALWAYS); expect(session.mediaMode).toEqual(MediaMode.ROUTED); @@ -153,19 +153,19 @@ describe('video', () => { }); test("can creating a server session properly sets location", async () => { - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() - .post('/session/create', /archiveMode=manual&p2p.preference=disabled&location=10.0.1.2/) - .reply(200, [ + .post('/session/create', /archiveMode=manual&location=10.0.1.2&p2p.preference=disabled/) + .reply(200, { "session_id": "the session ID", "project_id": "your OpenTok API key", "create_dt": "The creation date", - "media_server_url": "The URL of the OpenTok media router used by the session -- ignore this" - } - ]); + "media_server_url": "The URL of the OpenTok media router used by the session -- ignore this", + }, + ); - const session = await client.createSession({location: '10.0.1.2'}); + const session = await client.createSession({ location: '10.0.1.2' }); expect(session.sessionId).toEqual('the session ID'); expect(session.archiveMode).toEqual(ArchiveMode.MANUAL); expect(session.mediaMode).toEqual(MediaMode.ROUTED); @@ -174,35 +174,35 @@ describe('video', () => { test("can generate a client JWT token", async () => { const token = await client.generateClientToken('abcd'); - const decoded: any = decode(token, {json: true, complete: true}); + const decoded: any = decode(token, { json: true, complete: true }); expect(decoded.payload.application_id).toEqual('abcd-1234'); expect(decoded.payload.scope).toEqual('session.connect'); expect(decoded.payload.session_id).toEqual('abcd'); expect(decoded.payload.sub).toEqual('video'); - expect(decoded.payload.acl.paths).toEqual({'/session/**': {}}); + expect(decoded.payload.acl.paths).toEqual({ '/session/**': {} }); }); test("can generate a client JWT token with renamed values", async () => { - const now = Math.round(new Date().getTime() / 1000); + const now = Math.round(new Date().getTime() / 1000) + 500; const token = await client.generateClientToken('abcd', { data: 'test', - expireTime: now + 500, - initialLayoutClassList: ['foo', 'bar'] + expireTime: now, + initialLayoutClassList: ['foo', 'bar'], }); - const decoded: any = decode(token, {json: true, complete: true}); + const decoded: any = decode(token, { json: true, complete: true }); expect(decoded.payload.application_id).toEqual('abcd-1234'); expect(decoded.payload.scope).toEqual('session.connect'); expect(decoded.payload.session_id).toEqual('abcd'); expect(decoded.payload.connection_data).toEqual('test'); - expect(decoded.payload.exp).toEqual(now + 500); + expect(decoded.payload.exp).toEqual(now); expect(decoded.payload.initial_layout_class_list).toEqual('foo bar'); }); test("can generate a client JWT token with custom options", async () => { - const token = await client.generateClientToken('abcd', {role: 'publisher'}); - const decoded: any = decode(token, {json: true, complete: true}); + const token = await client.generateClientToken('abcd', { role: 'publisher' }); + const decoded: any = decode(token, { json: true, complete: true }); expect(decoded.payload.application_id).toEqual('abcd-1234'); expect(decoded.payload.scope).toEqual('session.connect'); @@ -211,21 +211,21 @@ describe('video', () => { }); test("can send a signal to everyone", async () => { - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() - .post('/v2/project/abcd-1234/session/1234/signal', {type: "foo", data: "bar"}) + .post('/v2/project/abcd-1234/session/1234/signal', { type: "foo", data: "bar" }) .reply(200); - await client.sendSignal({type: "foo", data: "bar"}, "1234"); + await client.sendSignal({ type: "foo", data: "bar" }, "1234"); }); test("can send a signal to one connection", async () => { - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() - .post('/v2/project/abcd-1234/session/1234/connection/qwer/signal', {type: "foo", data: "bar"}) + .post('/v2/project/abcd-1234/session/1234/connection/qwer/signal', { type: "foo", data: "bar" }) .reply(200); - await client.sendSignal({type: "foo", data: "bar"}, "1234", "qwer"); + await client.sendSignal({ type: "foo", data: "bar" }, "1234", "qwer"); }); test("can start an archive with no options", async () => { @@ -244,12 +244,12 @@ describe('video', () => { "size" : 0, "status" : "started", "streamMode" : "auto", - "url" : null + "url" : null, }; - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() - .post('/v2/project/abcd-1234/archive', {sessionId: '1234'}) + .post('/v2/project/abcd-1234/archive', { sessionId: '1234' }) .reply(200, expectedResponse); const resp = await client.startArchive("1234"); @@ -273,15 +273,15 @@ describe('video', () => { "size" : 0, "status" : "started", "streamMode" : "auto", - "url" : null + "url" : null, }; - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() - .post('/v2/project/abcd-1234/archive', {sessionId: '1234', name: 'test', hasVideo: false}) + .post('/v2/project/abcd-1234/archive', { sessionId: '1234', name: 'test', hasVideo: false }) .reply(200, expectedResponse); - const resp = await client.startArchive("1234", {name: 'test', hasVideo: false}); + const resp = await client.startArchive("1234", { name: 'test', hasVideo: false }); expect(resp.name).toEqual(expectedResponse.name); expect(resp.sessionId).toEqual(expectedResponse.sessionId); }); @@ -300,10 +300,10 @@ describe('video', () => { "sessionId" : "flR1ZSBPY3QgMjkgMTI6MTM6MjMgUERUIDIwMTN", "size" : 0, "status" : "stopped", - "url" : null + "url" : null, }; - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() .post('/v2/project/abcd-1234/archive/b40ef09b-3811-4726-b508-e41a0f96c68f/stop') .reply(200, expectedResponse); @@ -331,7 +331,7 @@ describe('video', () => { "status" : "available", "streamMode" : "manual", "streams" : [], - "url" : "https://tokbox.com.archive2.s3.amazonaws.com/123456/09141e29-8770-439b-b180-337d7e637545/archive.mp4" + "url" : "https://tokbox.com.archive2.s3.amazonaws.com/123456/09141e29-8770-439b-b180-337d7e637545/archive.mp4", }, { "createdAt" : 1384221380000, "duration" : 328, @@ -347,10 +347,10 @@ describe('video', () => { "status" : "available", "streamMode" : "auto", "streams" : [], - "url" : "https://tokbox.com.archive2.s3.amazonaws.com/123456/b40ef09b-3811-4726-b508-e41a0f96c68f/archive.mp4" - } ]}; + "url" : "https://tokbox.com.archive2.s3.amazonaws.com/123456/b40ef09b-3811-4726-b508-e41a0f96c68f/archive.mp4", + } ] }; - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() .get('/v2/project/abcd-1234/archive') .reply(200, expectedResponse); @@ -379,15 +379,15 @@ describe('video', () => { "status" : "available", "streamMode" : "manual", "streams" : [], - "url" : "https://tokbox.com.archive2.s3.amazonaws.com/123456/09141e29-8770-439b-b180-337d7e637545/archive.mp4" - }, ]}; + "url" : "https://tokbox.com.archive2.s3.amazonaws.com/123456/09141e29-8770-439b-b180-337d7e637545/archive.mp4", + } ] }; - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() .get('/v2/project/abcd-1234/archive?sessionId=2_MX40NzIwMzJ-flR1ZSBPY3QgMjkgMTI6MTM6MjMgUERUIDIwMTN-MC45NDQ2MzE2NH4') .reply(200, expectedResponse); - const resp = await client.searchArchives({sessionId: '2_MX40NzIwMzJ-flR1ZSBPY3QgMjkgMTI6MTM6MjMgUERUIDIwMTN-MC45NDQ2MzE2NH4'}); + const resp = await client.searchArchives({ sessionId: '2_MX40NzIwMzJ-flR1ZSBPY3QgMjkgMTI6MTM6MjMgUERUIDIwMTN-MC45NDQ2MzE2NH4' }); expect(resp.count).toEqual(expectedResponse.count); expect(resp.items[0].sessionId).toEqual(expectedResponse.items[0].sessionId); }); @@ -409,10 +409,10 @@ describe('video', () => { "status" : "available", "streamMode" : "auto", "streams" : [], - "url" : "https://tokbox.com.archive2.s3.amazonaws.com/123456/09141e29-8770-439b-b180-337d7e637545/archive.mp4" + "url" : "https://tokbox.com.archive2.s3.amazonaws.com/123456/09141e29-8770-439b-b180-337d7e637545/archive.mp4", }; - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() .get('/v2/project/abcd-1234/archive/b40ef09b-3811-4726-b508-e41a0f96c68f') .reply(200, expectedResponse); @@ -424,7 +424,7 @@ describe('video', () => { }); test("can delete an archive", async () => { - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() .delete('/v2/project/abcd-1234/archive/b40ef09b-3811-4726-b508-e41a0f96c68f') .reply(204); @@ -433,34 +433,34 @@ describe('video', () => { }); test("can update an archive layout", async () => { - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() - .put('/v2/project/abcd-1234/archive/b40ef09b-3811-4726-b508-e41a0f96c68f/layout', {type: LayoutType.BEST_FIT}) + .put('/v2/project/abcd-1234/archive/b40ef09b-3811-4726-b508-e41a0f96c68f/layout', { type: LayoutType.BEST_FIT }) .reply(204); - await client.updateArchiveLayout('b40ef09b-3811-4726-b508-e41a0f96c68f', {type: LayoutType.BEST_FIT}); + await client.updateArchiveLayout('b40ef09b-3811-4726-b508-e41a0f96c68f', { type: LayoutType.BEST_FIT }); }); test("can add a stream to an archive", async () => { - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() - .patch('/v2/project/abcd-1234/archive/b40ef09b-3811-4726-b508-e41a0f96c68f/stream', {addStream: 'test-1234', hasAudio: false, hasVideo: true}) + .patch('/v2/project/abcd-1234/archive/b40ef09b-3811-4726-b508-e41a0f96c68f/stream', { addStream: 'test-1234', hasAudio: false, hasVideo: true }) .reply(204); await client.addArchiveStream('b40ef09b-3811-4726-b508-e41a0f96c68f', 'test-1234', false); }); test("can remove a stream from an archive", async () => { - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() - .patch('/v2/project/abcd-1234/archive/b40ef09b-3811-4726-b508-e41a0f96c68f/stream', {removeStream: 'test-1234'}) + .patch('/v2/project/abcd-1234/archive/b40ef09b-3811-4726-b508-e41a0f96c68f/stream', { removeStream: 'test-1234' }) .reply(204); await client.removeArchiveStream('b40ef09b-3811-4726-b508-e41a0f96c68f', 'test-1234'); }); test("can force disconnect a client", async () => { - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() .delete('/v2/project/abcd-1234/session/sess-1234/connection/conn-1234') .reply(204); @@ -473,9 +473,9 @@ describe('video', () => { "id": "8b732909-0a06-46a2-8ea8-074e64d43422", "videoType": "camera", "name": "", - "layoutClassList": ["full"] + "layoutClassList": ["full"], }; - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() .get('/v2/project/abcd-1234/session/sess-1234/stream/8b732909-0a06-46a2-8ea8-074e64d43422') .reply(200, expectedResponse); @@ -492,11 +492,11 @@ describe('video', () => { "id": "8b732909-0a06-46a2-8ea8-074e64d43422", "videoType": "camera", "name": "", - "layoutClassList": ["full"] - } - ] + "layoutClassList": ["full"], + }, + ], }; - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() .get('/v2/project/abcd-1234/session/sess-1234/stream') .reply(200, expectedResponse); @@ -513,11 +513,11 @@ describe('video', () => { "status": "ACTIVE", "name": "Joe Montana", "environment": "standard", - "createdAt": 1414642898000 // A UNIX timestamp (in milliseconds) + "createdAt": 1414642898000, // A UNIX timestamp (in milliseconds) }; - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() - .post('/v2/project/abcd-1234/session/sess-1234/mute', { active: true, excludedStreamIds: ['stream-pub-1234']}) + .post('/v2/project/abcd-1234/session/sess-1234/mute', { active: true, excludedStreamIds: ['stream-pub-1234'] }) .reply(200, expectedResponse); const resp = await client.forceMuteAll('sess-1234', ['stream-pub-1234']); @@ -531,11 +531,11 @@ describe('video', () => { "status": "ACTIVE", "name": "Joe Montana", "environment": "standard", - "createdAt": 1414642898000 // A UNIX timestamp (in milliseconds) + "createdAt": 1414642898000, // A UNIX timestamp (in milliseconds) }; - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() - .post('/v2/project/abcd-1234/session/sess-1234/mute', { active: false, excludedStreamIds: []}) + .post('/v2/project/abcd-1234/session/sess-1234/mute', { active: false, excludedStreamIds: [] }) .reply(200, expectedResponse); const resp = await client.disableForceMute('sess-1234'); @@ -549,9 +549,9 @@ describe('video', () => { "status": "ACTIVE", "name": "Joe Montana", "environment": "standard", - "createdAt": 1414642898000 // A UNIX timestamp (in milliseconds) + "createdAt": 1414642898000, // A UNIX timestamp (in milliseconds) }; - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() .post('/v2/project/abcd-1234/session/sess-1234/stream/stream-user-1234/mute') .reply(200, expectedResponse); @@ -561,21 +561,21 @@ describe('video', () => { }); test("can set class list for streams", async () => { - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() - .put('/v2/project/abcd-1234/session/sess-1234/stream', {items: [{id: 'stream-1234', layoutClassList: ["full"]}]}) + .put('/v2/project/abcd-1234/session/sess-1234/stream', { items: [{ id: 'stream-1234', layoutClassList: ["full"] }] }) .reply(200); - await client.setStreamClassLists('sess-1234', [{id: 'stream-1234', layoutClassList: ["full"]}]); + await client.setStreamClassLists('sess-1234', [{ id: 'stream-1234', layoutClassList: ["full"] }]); }); test("can initiate a SIP call", async () => { const options = { token: client.generateClientToken(), sip: { - uri: 'sip:user@sip.partner.com;transport=tls' - } - } + uri: 'sip:user@sip.partner.com;transport=tls', + }, + }; const expectedResponse = { id: "b0a5a8c7-dc38-459f-a48d-a7f2008da853", @@ -585,7 +585,7 @@ describe('video', () => { const expectedBody = Object.assign({}, { sessionId: "2_MX40NTMyODc3Mn5-fg" }, options); - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() .post('/v2/project/abcd-1234/dial', expectedBody) .reply(200, expectedResponse); @@ -598,42 +598,42 @@ describe('video', () => { }); test("can play DTMF digits to everyone", async () => { - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() - .post('/v2/project/abcd-1234/session/2_MX40NTMyODc3Mn5-fg/play-dtmf', { digits: '1234#'}) + .post('/v2/project/abcd-1234/session/2_MX40NTMyODc3Mn5-fg/play-dtmf', { digits: '1234#' }) .reply(200); await client.playDTMF("2_MX40NTMyODc3Mn5-fg", "1234#"); }); test("can play DTMF digits into one connection", async () => { - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() - .post('/v2/project/abcd-1234/session/2_MX40NTMyODc3Mn5-fg/connection/396edda0-fc30-41fd-8e63/play-dtmf', {digits: "1234#"}) + .post('/v2/project/abcd-1234/session/2_MX40NTMyODc3Mn5-fg/connection/396edda0-fc30-41fd-8e63/play-dtmf', { digits: "1234#" }) .reply(200); - await client.playDTMF("2_MX40NTMyODc3Mn5-fg", "1234#", "396edda0-fc30-41fd-8e63"); + await client.playDTMF("2_MX40NTMyODc3Mn5-fg", "1234#", "396edda0-fc30-41fd-8e63"); }); test("can connect to a websocket", async () => { const token = client.generateClientToken(); - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() - .post('/v2/project/abcd-1234/connect', {sessionId: "2_MX40NTMyODc3Mn5-fg", token, websocket: {uri: 'wss://mydomain.com/websocket/'}}) - .reply(200, {id: 'CALLID', connectionId: 'CONNECTIONID'}); + .post('/v2/project/abcd-1234/connect', { sessionId: "2_MX40NTMyODc3Mn5-fg", token, websocket: { uri: 'wss://mydomain.com/websocket/' } }) + .reply(200, { id: 'CALLID', connectionId: 'CONNECTIONID' }); - const resp = await client.connectToWebsocket("2_MX40NTMyODc3Mn5-fg", token, {uri: 'wss://mydomain.com/websocket/'}); - expect(resp.id).toEqual('CALLID') - expect(resp.connectionId).toEqual('CONNECTIONID') + const resp = await client.connectToWebsocket("2_MX40NTMyODc3Mn5-fg", token, { uri: 'wss://mydomain.com/websocket/' }); + expect(resp.id).toEqual('CALLID'); + expect(resp.connectionId).toEqual('CONNECTIONID'); }); test("can disconnect a websocket", async () => { - nock(BASE_URL, {reqheaders: {'Authorization': value => value.startsWith('Bearer ') && value.length > 10 }}) + nock(BASE_URL, { reqheaders: { 'Authorization': value => value.startsWith('Bearer ') && value.length > 10 } }) .persist() .post('/v2/project/abcd-1234/connect/CALLID/stop') .reply(200); - await client.disconnectWebsocket('CALLID'); + await client.disconnectWebsocket('CALLID'); }); }); diff --git a/packages/video/lib/enums/ArchiveOutputMode.ts b/packages/video/lib/enums/ArchiveOutputMode.ts index b72aa090..827e4e9e 100644 --- a/packages/video/lib/enums/ArchiveOutputMode.ts +++ b/packages/video/lib/enums/ArchiveOutputMode.ts @@ -1,4 +1,14 @@ +/** + * Enum representing different output modes for video archives. + */ export enum ArchiveOutputMode { + /** + * Represents the composed output mode where all streams are mixed into one. + */ COMPOSED = 'composed', + + /** + * Represents the individual output mode where each stream is recorded separately. + */ INDIVIDUAL = 'individual', } diff --git a/packages/video/lib/enums/AudioRate.ts b/packages/video/lib/enums/AudioRate.ts index bc65adfa..bd989ccc 100644 --- a/packages/video/lib/enums/AudioRate.ts +++ b/packages/video/lib/enums/AudioRate.ts @@ -1,4 +1,14 @@ +/** + * Enum representing different audio sample rates. + */ export enum AudioRate { + /** + * Represents an audio sample rate of 16 kHz. + */ "16KHZ" = 16000, + + /** + * Represents an audio sample rate of 8 kHz. + */ "8KHZ" = 8000 -} \ No newline at end of file +} diff --git a/packages/video/lib/enums/CaptionStatus.ts b/packages/video/lib/enums/CaptionStatus.ts index 37d4c287..9abac180 100644 --- a/packages/video/lib/enums/CaptionStatus.ts +++ b/packages/video/lib/enums/CaptionStatus.ts @@ -1,6 +1,24 @@ +/** + * Enum representing different captioning status. + */ export enum CaptionStatus { - STARTED = "started", - STOPPED = "stopped", - PAUSED = "paused", - FAILED = "failed" -} \ No newline at end of file + /** + * Indicates that captioning has started. + */ + STARTED = "started", + + /** + * Indicates that captioning has stopped. + */ + STOPPED = "stopped", + + /** + * Indicates that captioning has been paused. + */ + PAUSED = "paused", + + /** + * Indicates that captioning has failed. + */ + FAILED = "failed" +} diff --git a/packages/video/lib/enums/ExperienceComposerResolution.ts b/packages/video/lib/enums/ExperienceComposerResolution.ts index b1fa27f9..167e88ea 100644 --- a/packages/video/lib/enums/ExperienceComposerResolution.ts +++ b/packages/video/lib/enums/ExperienceComposerResolution.ts @@ -1,8 +1,26 @@ import { Resolution } from "./Resolution"; +/** + * Enum representing different resolutions for an experience composer. + */ export enum ExperienceComposerResolution { - SD_LANDSCAPE = Resolution.SD_LANDSCAPE, - SD_PORTRAIT = Resolution.SD_PORTRAIT, - HD_LANDSCAPE = Resolution.HD_LANDSCAPE, - HD_PORTRAIT = Resolution.HD_PORTRAIT, -} \ No newline at end of file + /** + * Standard definition landscape resolution. + */ + SD_LANDSCAPE = Resolution.SD_LANDSCAPE, + + /** + * Standard definition portrait resolution. + */ + SD_PORTRAIT = Resolution.SD_PORTRAIT, + + /** + * High definition landscape resolution. + */ + HD_LANDSCAPE = Resolution.HD_LANDSCAPE, + + /** + * High definition portrait resolution. + */ + HD_PORTRAIT = Resolution.HD_PORTRAIT, +} diff --git a/packages/video/lib/enums/LayoutType.ts b/packages/video/lib/enums/LayoutType.ts index c8207d74..d2ff6696 100644 --- a/packages/video/lib/enums/LayoutType.ts +++ b/packages/video/lib/enums/LayoutType.ts @@ -1,7 +1,29 @@ +/** + * Enum representing different layout types for live streaming broadcasts. + */ export enum LayoutType { + /** + * Automatically determine the best fit layout. + */ BEST_FIT = 'bestFit', + + /** + * Use a custom layout for the broadcast. + */ CUSTOM = 'custom', + + /** + * Horizontal presentation layout. + */ HORIZONTAL_PRESENTATION = 'horizontalPresentation', + + /** + * Picture-in-picture (PIP) layout. + */ PIP = 'pip', + + /** + * Vertical presentation layout. + */ VERTICAL_PRESENTATION = 'verticalPresentation', } diff --git a/packages/video/lib/enums/MediaMode.ts b/packages/video/lib/enums/MediaMode.ts new file mode 100644 index 00000000..2c6ce43f --- /dev/null +++ b/packages/video/lib/enums/MediaMode.ts @@ -0,0 +1,14 @@ +/** + * Enum representing media modes for a session. + */ +export enum MediaMode { + /** + * Routed mode where media is disabled. + */ + ROUTED = 'disabled', + + /** + * Relayed mode where media is enabled. + */ + RELAYED = 'enabled', +} diff --git a/packages/video/lib/enums/Resolution.ts b/packages/video/lib/enums/Resolution.ts index 0c8dc110..13f02de6 100644 --- a/packages/video/lib/enums/Resolution.ts +++ b/packages/video/lib/enums/Resolution.ts @@ -1,8 +1,34 @@ +/** + * Enum representing different video resolutions for live streaming broadcasts. + */ export enum Resolution { + /** + * Full HD landscape resolution (1920x1080 pixels). + */ FHD_LANDSCAPE = '1920x1080', + + /** + * Full HD portrait resolution (1080x1920 pixels). + */ FHD_PORTRAIT = '1080x1920', + + /** + * HD landscape resolution (1280x720 pixels). + */ HD_LANDSCAPE = '1280x720', + + /** + * HD portrait resolution (720x1280 pixels). + */ HD_PORTRAIT = '720x1280', + + /** + * Standard definition landscape resolution (640x480 pixels). + */ SD_LANDSCAPE = '640x480', + + /** + * Standard definition portrait resolution (480x640 pixels). + */ SD_PORTRAIT = '480x640', } diff --git a/packages/video/lib/enums/StreamMode.ts b/packages/video/lib/enums/StreamMode.ts index 17886877..513b0016 100644 --- a/packages/video/lib/enums/StreamMode.ts +++ b/packages/video/lib/enums/StreamMode.ts @@ -1,4 +1,14 @@ +/** + * Enum representing different stream modes for live streaming broadcasts. + */ export enum StreamMode { + /** + * Streams are selected automatically based on session rules. + */ AUTO = 'auto', + + /** + * Streams are manually selected for inclusion in the broadcast. + */ MANUAL = 'manual', } diff --git a/packages/video/lib/enums/index.ts b/packages/video/lib/enums/index.ts index c42ec4ca..12428565 100644 --- a/packages/video/lib/enums/index.ts +++ b/packages/video/lib/enums/index.ts @@ -5,3 +5,4 @@ export * from './ExperienceComposerResolution'; export * from './LayoutType'; export * from './Resolution'; export * from './StreamMode'; +export * from './MediaMode'; diff --git a/packages/video/lib/index.ts b/packages/video/lib/index.ts index 0de80f0e..09d465c9 100644 --- a/packages/video/lib/index.ts +++ b/packages/video/lib/index.ts @@ -1,4 +1,4 @@ export * from './enums'; -export * from './interfaces'; +export * from './types'; export * from './parameters'; export * from './video'; diff --git a/packages/video/lib/interfaces/ArchiveLayout.ts b/packages/video/lib/interfaces/ArchiveLayout.ts deleted file mode 100644 index defd26cf..00000000 --- a/packages/video/lib/interfaces/ArchiveLayout.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { LayoutType } from '../enums/LayoutType'; - -export interface ArchiveLayout { - type: LayoutType; - stylesheet?: string; - screenshareType?: string; -} diff --git a/packages/video/lib/interfaces/ArchiveMode.ts b/packages/video/lib/interfaces/ArchiveMode.ts deleted file mode 100644 index 86901f89..00000000 --- a/packages/video/lib/interfaces/ArchiveMode.ts +++ /dev/null @@ -1,4 +0,0 @@ -export enum ArchiveMode { - MANUAL = 'manual', - ALWAYS = 'always', -} diff --git a/packages/video/lib/interfaces/ArchiveOptions.ts b/packages/video/lib/interfaces/ArchiveOptions.ts deleted file mode 100644 index fa167f7f..00000000 --- a/packages/video/lib/interfaces/ArchiveOptions.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { ArchiveOutputMode } from '../enums/ArchiveOutputMode'; -import { Resolution } from '../enums/Resolution'; -import { StreamMode } from '../enums/StreamMode'; -import { ArchiveLayout } from './ArchiveLayout'; - -export interface ArchiveOptions { - hasAudio?: boolean; - hasVideo?: boolean; - layout?: ArchiveLayout; - name?: string; - outputMode?: ArchiveOutputMode; - resolution?: Resolution; - streamMode?: StreamMode; -} diff --git a/packages/video/lib/interfaces/ArchiveSearchFilter.ts b/packages/video/lib/interfaces/ArchiveSearchFilter.ts deleted file mode 100644 index ea48f8ce..00000000 --- a/packages/video/lib/interfaces/ArchiveSearchFilter.ts +++ /dev/null @@ -1,5 +0,0 @@ -export interface ArchiveSearchFilter { - offset?: number; - count?: number; - sessionId?: string; -} diff --git a/packages/video/lib/interfaces/BroadcastConfig.ts b/packages/video/lib/interfaces/BroadcastConfig.ts deleted file mode 100644 index 44f1bac9..00000000 --- a/packages/video/lib/interfaces/BroadcastConfig.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { LayoutType } from '../enums/LayoutType'; -import { Resolution } from '../enums/Resolution'; -import { StreamMode } from '../enums/StreamMode'; -import { RTMPStream } from './RTMPStream'; - -export interface BroadcastConfig { - multiBroadcastTag?: string; - maxDuration?: number; - maxBitrate?: number; - layout?: LayoutType; - hasAudio?: boolean; - hasVideo?: boolean; - outputs: { - hls?: { - lowLatency?: boolean; - dvr?: boolean; - }; - rtmp: RTMPStream[]; - }; - streamMode?: StreamMode; - resolution?: Resolution; -} diff --git a/packages/video/lib/interfaces/BroadcastSearchFilter.ts b/packages/video/lib/interfaces/BroadcastSearchFilter.ts deleted file mode 100644 index c671deb4..00000000 --- a/packages/video/lib/interfaces/BroadcastSearchFilter.ts +++ /dev/null @@ -1,5 +0,0 @@ -export interface BroadcastSearchFilter { - offset?: number; - count?: number; - sessionId?: string; -} diff --git a/packages/video/lib/interfaces/BroadcastUpdateConfig.ts b/packages/video/lib/interfaces/BroadcastUpdateConfig.ts deleted file mode 100644 index 4171cb1e..00000000 --- a/packages/video/lib/interfaces/BroadcastUpdateConfig.ts +++ /dev/null @@ -1,7 +0,0 @@ -export interface BroadcastUpdateConfig { - broadcastId: string; - hasAudio?: boolean; - hasVideo?: boolean; - addStream?: string; - removeStream?: string; -} diff --git a/packages/video/lib/interfaces/CaptionOptions.ts b/packages/video/lib/interfaces/CaptionOptions.ts deleted file mode 100644 index e24146b1..00000000 --- a/packages/video/lib/interfaces/CaptionOptions.ts +++ /dev/null @@ -1,6 +0,0 @@ -export interface CaptionOptions { - languageCode?: "en-us" - maxDuration?: number - partialCaptions?: "true" | "false" - statusCallbackUrl?: string -} \ No newline at end of file diff --git a/packages/video/lib/interfaces/ClientTokenClaims.ts b/packages/video/lib/interfaces/ClientTokenClaims.ts deleted file mode 100644 index 147a01bf..00000000 --- a/packages/video/lib/interfaces/ClientTokenClaims.ts +++ /dev/null @@ -1,15 +0,0 @@ -export interface ClientTokenClaims { - scope: string, - session_id: string, - role: string, - initial_layout_class_list: string - data?: string - exp?: number - connection_data?: string - sub: string, - acl: { - paths: { - [key: string]: object - } - } -} \ No newline at end of file diff --git a/packages/video/lib/interfaces/ClientTokenOptions.ts b/packages/video/lib/interfaces/ClientTokenOptions.ts deleted file mode 100644 index cfb050ec..00000000 --- a/packages/video/lib/interfaces/ClientTokenOptions.ts +++ /dev/null @@ -1,6 +0,0 @@ -export interface ClientTokenOptions { - role?: string; - data?: string; - expireTime?: number; - initialLayoutClassList?: string[]; -} diff --git a/packages/video/lib/interfaces/ExperienceComposerListFilter.ts b/packages/video/lib/interfaces/ExperienceComposerListFilter.ts deleted file mode 100644 index 95825226..00000000 --- a/packages/video/lib/interfaces/ExperienceComposerListFilter.ts +++ /dev/null @@ -1,4 +0,0 @@ -export interface ExperienceComposerListFilter { - offset?: number; - count?: number; -} diff --git a/packages/video/lib/interfaces/ExperienceComposerOptions.ts b/packages/video/lib/interfaces/ExperienceComposerOptions.ts deleted file mode 100644 index e8f50278..00000000 --- a/packages/video/lib/interfaces/ExperienceComposerOptions.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { ExperienceComposerResolution } from "../enums/ExperienceComposerResolution"; - -export interface ExperienceComposerOptions { - url: string - properties?: { - name?: string - } - maxDuration?: number - resolution?: ExperienceComposerResolution - statusCallbackUrl?: string -} \ No newline at end of file diff --git a/packages/video/lib/interfaces/MediaMode.ts b/packages/video/lib/interfaces/MediaMode.ts deleted file mode 100644 index 3dea0abf..00000000 --- a/packages/video/lib/interfaces/MediaMode.ts +++ /dev/null @@ -1,4 +0,0 @@ -export enum MediaMode { - ROUTED = 'disabled', - RELAYED = 'enabled', -} diff --git a/packages/video/lib/interfaces/RTMPStream.ts b/packages/video/lib/interfaces/RTMPStream.ts deleted file mode 100644 index 08a9cda2..00000000 --- a/packages/video/lib/interfaces/RTMPStream.ts +++ /dev/null @@ -1,5 +0,0 @@ -export interface RTMPStream { - id?: string; - serverUrl: string; - streamName: string; -} diff --git a/packages/video/lib/interfaces/Request/InitiateSIPCallRequest.ts b/packages/video/lib/interfaces/Request/InitiateSIPCallRequest.ts deleted file mode 100644 index 7909b929..00000000 --- a/packages/video/lib/interfaces/Request/InitiateSIPCallRequest.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { SIPCallOptions } from '../SIPCallOptions'; - -export interface InitiateSIPCallRequest extends SIPCallOptions { - sessionId: string -} diff --git a/packages/video/lib/interfaces/Response/BroadcastDetailsResponse.ts b/packages/video/lib/interfaces/Response/BroadcastDetailsResponse.ts deleted file mode 100644 index 62a353f6..00000000 --- a/packages/video/lib/interfaces/Response/BroadcastDetailsResponse.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { Resolution } from '../../enums/Resolution'; -import { StreamMode } from '../../enums/StreamMode'; -import { RTMPStream } from '../RTMPStream'; - -export interface BroadcastDetailsResponse { - id: string; - sessionId: string; - multiBroadcasTag?: string; - applicationId: string; - createdAt: number; - updatedAt: number; - maxDuration?: number; - maxBitrate?: number; - broadcastUrls: { - hls?: string; - rtmp: RTMPStream[]; - }; - settings?: { - hls?: { - lowLatency?: boolean; - }; - }; - resolution?: Resolution; - hasVideo: boolean; - hasAudio: boolean; - streamMode: StreamMode; -} diff --git a/packages/video/lib/interfaces/Response/CaptionStatusResponse.ts b/packages/video/lib/interfaces/Response/CaptionStatusResponse.ts deleted file mode 100644 index 6ad78e11..00000000 --- a/packages/video/lib/interfaces/Response/CaptionStatusResponse.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { CaptionStatus } from "../../enums/CaptionStatus"; - -export interface CaptionStatusResponse { - captionId: string - applicationId: string - sessionId: string - status: CaptionStatus - createdAt: number - updatedAt: number - duration: number - languageCode: "en-us" - provider: "aws-transcribe" - reason?: string -} \ No newline at end of file diff --git a/packages/video/lib/interfaces/Response/CreateSessionResponse.ts b/packages/video/lib/interfaces/Response/CreateSessionResponse.ts deleted file mode 100644 index 5aadbe24..00000000 --- a/packages/video/lib/interfaces/Response/CreateSessionResponse.ts +++ /dev/null @@ -1,6 +0,0 @@ -export interface CreateSessionResponse { - session_id: string; - project_id: string; - create_dt: string; - media_server_url: string; -} diff --git a/packages/video/lib/interfaces/Response/EnableCaptionResponse.ts b/packages/video/lib/interfaces/Response/EnableCaptionResponse.ts deleted file mode 100644 index 0d5f0961..00000000 --- a/packages/video/lib/interfaces/Response/EnableCaptionResponse.ts +++ /dev/null @@ -1,3 +0,0 @@ -export interface EnableCaptionResponse { - captionsId: string -} \ No newline at end of file diff --git a/packages/video/lib/interfaces/Response/ExperienceComposerResponse.ts b/packages/video/lib/interfaces/Response/ExperienceComposerResponse.ts deleted file mode 100644 index 96389474..00000000 --- a/packages/video/lib/interfaces/Response/ExperienceComposerResponse.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { ExperienceComposerResolution } from "../../enums/ExperienceComposerResolution"; - -export interface ExperienceComposerResponse { - id: string - sessionId: string - applicationId: string - createdAt: number - updatedAt: number - url: string - resolution: ExperienceComposerResolution - status: "starting" | "started" | "stopped" | "failed" - streamId: string - reason?: string -} \ No newline at end of file diff --git a/packages/video/lib/interfaces/Response/MultiArchiveResponse.ts b/packages/video/lib/interfaces/Response/MultiArchiveResponse.ts deleted file mode 100644 index 01c86331..00000000 --- a/packages/video/lib/interfaces/Response/MultiArchiveResponse.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { SingleArchiveResponse } from './SingleArchiveResponse'; - -export interface MultiArchiveResponse { - count: number; - items: SingleArchiveResponse[]; -} diff --git a/packages/video/lib/interfaces/Response/MultiBroadcastResponse.ts b/packages/video/lib/interfaces/Response/MultiBroadcastResponse.ts deleted file mode 100644 index 12f87dc3..00000000 --- a/packages/video/lib/interfaces/Response/MultiBroadcastResponse.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { BroadcastDetailsResponse } from './BroadcastDetailsResponse'; - -export interface MultiBroadcastResponse { - count: number; - items: BroadcastDetailsResponse[]; -} diff --git a/packages/video/lib/interfaces/Response/MultiExperienceComposerResponse.ts b/packages/video/lib/interfaces/Response/MultiExperienceComposerResponse.ts deleted file mode 100644 index b054a1e8..00000000 --- a/packages/video/lib/interfaces/Response/MultiExperienceComposerResponse.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { ExperienceComposerResponse } from "./ExperienceComposerResponse"; - -export interface MultiExperienceComposerResponse { - count: number - items: ExperienceComposerResponse[] -} \ No newline at end of file diff --git a/packages/video/lib/interfaces/Response/MultiStreamLayoutResponse.ts b/packages/video/lib/interfaces/Response/MultiStreamLayoutResponse.ts deleted file mode 100644 index 5ef095c7..00000000 --- a/packages/video/lib/interfaces/Response/MultiStreamLayoutResponse.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { SingleStreamLayoutResponse } from './SingleStreamLayoutResponse'; - -export interface MultiStreamLayoutResponse { - count: number; - items: SingleStreamLayoutResponse[]; -} diff --git a/packages/video/lib/interfaces/Response/ProjectDetailsResponse.ts b/packages/video/lib/interfaces/Response/ProjectDetailsResponse.ts deleted file mode 100644 index 22bec231..00000000 --- a/packages/video/lib/interfaces/Response/ProjectDetailsResponse.ts +++ /dev/null @@ -1,8 +0,0 @@ -export interface ProjectDetailsResponse { - id: string; - secret: string; - status: string; - name: string; - environment: string; - createdAt: number; -} diff --git a/packages/video/lib/interfaces/Response/SIPCallResponse.ts b/packages/video/lib/interfaces/Response/SIPCallResponse.ts deleted file mode 100644 index 8e8cfb34..00000000 --- a/packages/video/lib/interfaces/Response/SIPCallResponse.ts +++ /dev/null @@ -1,5 +0,0 @@ -export interface SIPCallResponse { - id: string; - connectionId: string; - streamId: string; -} diff --git a/packages/video/lib/interfaces/Response/SingleArchiveResponse.ts b/packages/video/lib/interfaces/Response/SingleArchiveResponse.ts deleted file mode 100644 index 60e4cc38..00000000 --- a/packages/video/lib/interfaces/Response/SingleArchiveResponse.ts +++ /dev/null @@ -1,18 +0,0 @@ -export interface SingleArchiveResponse { - createdAt: number; - duration: number; - hasAudio: boolean; - hasVideo: boolean; - id: string; - name: string; - outputMode: string; - projectId: string; - reason: string; - resolution: string; - sessionId: string; - size: number; - status: string; - streamMode: string; - url?: string; - streams?: string[]; -} diff --git a/packages/video/lib/interfaces/Response/SingleStreamLayoutResponse.ts b/packages/video/lib/interfaces/Response/SingleStreamLayoutResponse.ts deleted file mode 100644 index 36460743..00000000 --- a/packages/video/lib/interfaces/Response/SingleStreamLayoutResponse.ts +++ /dev/null @@ -1,6 +0,0 @@ -export interface SingleStreamLayoutResponse { - id: string; - videoType: string; - name: string; - layoutClassList: string[]; -} diff --git a/packages/video/lib/interfaces/Response/WebSocketConnectResponse.ts b/packages/video/lib/interfaces/Response/WebSocketConnectResponse.ts deleted file mode 100644 index c4ce5601..00000000 --- a/packages/video/lib/interfaces/Response/WebSocketConnectResponse.ts +++ /dev/null @@ -1,4 +0,0 @@ -export interface WebSocketConnectResponse { - id: string - connectionId: string -} diff --git a/packages/video/lib/interfaces/SIPCallOptions.ts b/packages/video/lib/interfaces/SIPCallOptions.ts deleted file mode 100644 index 80ee092b..00000000 --- a/packages/video/lib/interfaces/SIPCallOptions.ts +++ /dev/null @@ -1,17 +0,0 @@ -export interface SIPCallOptions { - token: string; - sip: { - uri: string; - from?: string; - headers?: { - [key: string]: string; - }, - auth?: { - username: string; - password: string; - } - secure?: boolean; - video?: boolean; - observeForceMute?: boolean; - } -} diff --git a/packages/video/lib/interfaces/Session.ts b/packages/video/lib/interfaces/Session.ts deleted file mode 100644 index 66fc215e..00000000 --- a/packages/video/lib/interfaces/Session.ts +++ /dev/null @@ -1,6 +0,0 @@ -export interface Session { - sessionId: string; - location: string; - mediaMode: string; - archiveMode: string; -} diff --git a/packages/video/lib/interfaces/StreamClassList.ts b/packages/video/lib/interfaces/StreamClassList.ts deleted file mode 100644 index f37c3e68..00000000 --- a/packages/video/lib/interfaces/StreamClassList.ts +++ /dev/null @@ -1,4 +0,0 @@ -export interface StreamClassList { - id: string; - layoutClassList: string[]; -} diff --git a/packages/video/lib/interfaces/VideoResponse.ts b/packages/video/lib/interfaces/VideoResponse.ts deleted file mode 100644 index 62f85a7d..00000000 --- a/packages/video/lib/interfaces/VideoResponse.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { VetchResponse } from '@vonage/vetch'; - -export type VideoResponse = VetchResponse diff --git a/packages/video/lib/interfaces/WebSocketConfig.ts b/packages/video/lib/interfaces/WebSocketConfig.ts deleted file mode 100644 index 6169134c..00000000 --- a/packages/video/lib/interfaces/WebSocketConfig.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { AudioRate } from '../enums/AudioRate'; - -export interface WebSocketConfig { - uri: string - streams?: string[] - headers?: { - [key: string]: string - } - audioRate?: AudioRate -} diff --git a/packages/video/lib/parameters/VideoClassParameters.ts b/packages/video/lib/parameters/VideoClassParameters.ts index be903ea6..93037e37 100644 --- a/packages/video/lib/parameters/VideoClassParameters.ts +++ b/packages/video/lib/parameters/VideoClassParameters.ts @@ -1,10 +1,24 @@ -import { AuthOpts } from '@vonage/auth'; +import { AuthParams } from '@vonage/auth'; import { AuthInterface } from '@vonage/auth'; import { VetchOptions } from '@vonage/vetch'; -export type VideoClassParameters = AuthOpts & +/** + * Parameters required to initialize the Video class. + */ +export type VideoClassParameters = AuthParams & VetchOptions & { - applicationId: string; - privateKey: string; - auth?: AuthInterface; - }; + /** + * The unique identifier for the application. + */ + applicationId: string; + + /** + * The private key used for authentication. + */ + privateKey: string; + + /** + * Optional authentication interface to use for custom authentication. + */ + auth?: AuthInterface; +}; diff --git a/packages/video/lib/types/ArchiveLayout.ts b/packages/video/lib/types/ArchiveLayout.ts new file mode 100644 index 00000000..094c864d --- /dev/null +++ b/packages/video/lib/types/ArchiveLayout.ts @@ -0,0 +1,23 @@ +import { LayoutType } from "../enums"; + +/** + * Represents the layout configuration for an archive. + */ +export type ArchiveLayout = { + /** + * The type of layout to be used for the archive. + */ + type: LayoutType; + + /** + * Optional: The stylesheet used for custom layout (only applicable if type is 'custom'). + */ + stylesheet?: string; + + /** + * Optional: The screenshare layout type to use when there is a screen-sharing + * stream in the archive (only applicable if type is 'bestFit' and + * screenshareType is set). + */ + screenshareType?: string; +} diff --git a/packages/video/lib/types/ArchiveMode.ts b/packages/video/lib/types/ArchiveMode.ts new file mode 100644 index 00000000..5d2ded90 --- /dev/null +++ b/packages/video/lib/types/ArchiveMode.ts @@ -0,0 +1,14 @@ +/** + * Enum representing different archive modes. + */ +export enum ArchiveMode { + /** + * Archive mode set to 'manual', where archives are started and stopped manually. + */ + MANUAL = 'manual', + + /** + * Archive mode set to 'always', where archives are continuously recorded. + */ + ALWAYS = 'always', +} diff --git a/packages/video/lib/types/ArchiveOptions.ts b/packages/video/lib/types/ArchiveOptions.ts new file mode 100644 index 00000000..f7f387dc --- /dev/null +++ b/packages/video/lib/types/ArchiveOptions.ts @@ -0,0 +1,42 @@ +import { ArchiveOutputMode, Resolution, StreamMode } from '../enums'; +import { ArchiveLayout } from './ArchiveLayout'; + +/** + * Interface representing options for creating an archive. + */ +export type ArchiveOptions = { + /** + * Flag indicating whether audio should be included in the archive. + */ + hasAudio?: boolean; + + /** + * Flag indicating whether video should be included in the archive. + */ + hasVideo?: boolean; + + /** + * Layout configuration for the archive. + */ + layout?: ArchiveLayout; + + /** + * Name of the archive. + */ + name?: string; + + /** + * Output mode for the archive. + */ + outputMode?: ArchiveOutputMode; + + /** + * Resolution for the archive. + */ + resolution?: Resolution; + + /** + * Stream mode for the archive. + */ + streamMode?: StreamMode; +} diff --git a/packages/video/lib/types/ArchiveSearchFilter.ts b/packages/video/lib/types/ArchiveSearchFilter.ts new file mode 100644 index 00000000..4d3e4248 --- /dev/null +++ b/packages/video/lib/types/ArchiveSearchFilter.ts @@ -0,0 +1,19 @@ +/** + * Interface representing filters for searching archives. + */ +export type ArchiveSearchFilter = { + /** + * The start offset in the list of existing archives. + */ + offset?: number; + + /** + * The number of archives to retrieve starting at the offset. Default is 50, with a maximum of 1000. + */ + count?: number; + + /** + * Retrieve archives for a specific session ID. + */ + sessionId?: string; +} diff --git a/packages/video/lib/types/BroadcastConfig.ts b/packages/video/lib/types/BroadcastConfig.ts new file mode 100644 index 00000000..592315b9 --- /dev/null +++ b/packages/video/lib/types/BroadcastConfig.ts @@ -0,0 +1,83 @@ +import { LayoutType, Resolution, StreamMode } from '../enums'; +import { RTMPStream } from './RTMPStream'; + +/** + * Interface representing configuration options for HLS streaming. + */ +export type HLSConfig = { + /** + * Whether to enable low-latency mode for the HLS stream. + */ + lowLatency?: boolean; + + /** + * Whether to enable DVR functionality (rewinding, pausing, and resuming) in players that support it. + */ + dvr?: boolean; +} + +/** + * Interface representing configuration options for different types of broadcast streams (HLS and RTMP). + */ +export type BroadcastOutputs = { + /** + * Configuration options for HLS streaming. + */ + hls?: HLSConfig; + + /** + * Configuration options for RTMP streaming. + */ + rtmp: RTMPStream[]; +} + +/** + * Interface representing configuration options for a live streaming broadcast. + */ +export type BroadcastConfig = { + /** + * The unique tag for simultaneous broadcasts (if one was set). + */ + multiBroadcastTag?: string; + + /** + * The maximum duration for the broadcast, in seconds. The broadcast will + * automatically stop when the maximum duration is reached. + */ + maxDuration?: number; + + /** + * The maximum bitrate for the stream. + */ + maxBitrate?: number; + + /** + * The layout type for the broadcast. + */ + layout?: LayoutType; + + /** + * Whether the broadcast has audio. + */ + hasAudio?: boolean; + + /** + * Whether the broadcast has video. + */ + hasVideo?: boolean; + + /** + * Configuration options for different types of broadcast streams (HLS and RTMP). + */ + outputs: BroadcastOutputs; + + /** + * The stream mode for the broadcast. + */ + streamMode?: StreamMode; + + /** + * The resolution of the broadcast. + */ + resolution?: Resolution; +} diff --git a/packages/video/lib/types/BroadcastSearchFilter.ts b/packages/video/lib/types/BroadcastSearchFilter.ts new file mode 100644 index 00000000..88717378 --- /dev/null +++ b/packages/video/lib/types/BroadcastSearchFilter.ts @@ -0,0 +1,19 @@ +/** + * Interface representing a filter for searching broadcasts. + */ +export type BroadcastSearchFilter = { + /** + * The offset for paginating the results. + */ + offset?: number; + + /** + * The maximum number of items to return. + */ + count?: number; + + /** + * The session ID to filter broadcasts by. + */ + sessionId?: string; +} diff --git a/packages/video/lib/types/BroadcastUpdateConfig.ts b/packages/video/lib/types/BroadcastUpdateConfig.ts new file mode 100644 index 00000000..3fe95d5d --- /dev/null +++ b/packages/video/lib/types/BroadcastUpdateConfig.ts @@ -0,0 +1,29 @@ +/** + * Interface representing the configuration for updating a broadcast. + */ +export type BroadcastUpdateConfig = { + /** + * The ID of the broadcast to update. + */ + broadcastId: string; + + /** + * Whether to include audio in the broadcast. + */ + hasAudio?: boolean; + + /** + * Whether to include video in the broadcast. + */ + hasVideo?: boolean; + + /** + * The ID of a stream to add to the broadcast. + */ + addStream?: string; + + /** + * The ID of a stream to remove from the broadcast. + */ + removeStream?: string; +} diff --git a/packages/video/lib/types/CaptionOptions.ts b/packages/video/lib/types/CaptionOptions.ts new file mode 100644 index 00000000..199ab93e --- /dev/null +++ b/packages/video/lib/types/CaptionOptions.ts @@ -0,0 +1,24 @@ +/** + * Interface representing options for captions. + */ +export type CaptionOptions = { + /** + * The language code for captions (e.g., "en-us"). + */ + languageCode?: "en-us"; + + /** + * The maximum duration for captions. + */ + maxDuration?: number; + + /** + * Whether to generate partial captions. + */ + partialCaptions?: "true" | "false"; + + /** + * The URL for the status callback of captions. + */ + statusCallbackUrl?: string; +} diff --git a/packages/video/lib/types/ClientTokenClaims.ts b/packages/video/lib/types/ClientTokenClaims.ts new file mode 100644 index 00000000..b135e245 --- /dev/null +++ b/packages/video/lib/types/ClientTokenClaims.ts @@ -0,0 +1,56 @@ +/** + * Interface representing claims for a client token. + */ +export type ClientTokenClaims = { + /** + * The scope of the token. + */ + scope: string; + + /** + * The session ID associated with the token. + */ + session_id: string; + + /** + * The role of the token. + */ + role: string; + + /** + * The initial layout class list. + */ + initial_layout_class_list: string; + + /** + * Additional data for the token (optional). + */ + data?: string; + + /** + * The expiration time of the token (optional). + */ + exp?: number; + + /** + * Connection data associated with the token (optional). + */ + connection_data?: string; + + /** + * The subject of the token. + */ + sub: string; + + /** + * Access control list (ACL) for paths. + */ + acl: { + /** + * Paths and associated objects in the ACL. + */ + paths: { + [key: string]: object; + }; + }; +} diff --git a/packages/video/lib/types/ClientTokenOptions.ts b/packages/video/lib/types/ClientTokenOptions.ts new file mode 100644 index 00000000..37701358 --- /dev/null +++ b/packages/video/lib/types/ClientTokenOptions.ts @@ -0,0 +1,24 @@ +/** + * Interface representing options for generating a client token. + */ +export type ClientTokenOptions = { + /** + * The role associated with the client token (optional). + */ + role?: string; + + /** + * Additional data for the client token (optional). + */ + data?: string; + + /** + * The expiration time of the client token in seconds (optional). + */ + expireTime?: number; + + /** + * An array of initial layout class list for the client token (optional). + */ + initialLayoutClassList?: string[]; +} diff --git a/packages/video/lib/types/ExperienceComposerListFilter.ts b/packages/video/lib/types/ExperienceComposerListFilter.ts new file mode 100644 index 00000000..4efa3023 --- /dev/null +++ b/packages/video/lib/types/ExperienceComposerListFilter.ts @@ -0,0 +1,14 @@ +/** + * Interface representing filters for listing Experience Composer items. + */ +export type ExperienceComposerListFilter = { + /** + * The offset for paginating through the list (optional). + */ + offset?: number; + + /** + * The maximum number of items to retrieve (optional). + */ + count?: number; +} diff --git a/packages/video/lib/types/ExperienceComposerOptions.ts b/packages/video/lib/types/ExperienceComposerOptions.ts new file mode 100644 index 00000000..dcfaa713 --- /dev/null +++ b/packages/video/lib/types/ExperienceComposerOptions.ts @@ -0,0 +1,36 @@ +import { ExperienceComposerResolution } from "../enums"; + +/** + * Interface representing options for creating an Experience Composer. + */ +export type ExperienceComposerOptions = { + /** + * The URL of the Experience Composer. + */ + url: string; + + /** + * Optional properties for the Experience Composer. + */ + properties?: { + /** + * The name of the Experience Composer. + */ + name?: string; + }; + + /** + * The maximum duration for the Experience Composer (optional). + */ + maxDuration?: number; + + /** + * The resolution of the Experience Composer (optional). + */ + resolution?: ExperienceComposerResolution; + + /** + * The callback URL for status updates (optional). + */ + statusCallbackUrl?: string; +} diff --git a/packages/video/lib/types/RTMPStream.ts b/packages/video/lib/types/RTMPStream.ts new file mode 100644 index 00000000..ddef6451 --- /dev/null +++ b/packages/video/lib/types/RTMPStream.ts @@ -0,0 +1,19 @@ +/** + * Interface representing an RTMP stream configuration. + */ +export type RTMPStream = { + /** + * Optional unique identifier for the RTMP stream. + */ + id?: string; + + /** + * The RTMP server URL to which the stream will be sent. + */ + serverUrl: string; + + /** + * The name of the stream on the RTMP server. + */ + streamName: string; +} diff --git a/packages/video/lib/types/Request/InitiateSIPCallRequest.ts b/packages/video/lib/types/Request/InitiateSIPCallRequest.ts new file mode 100644 index 00000000..4edfe48b --- /dev/null +++ b/packages/video/lib/types/Request/InitiateSIPCallRequest.ts @@ -0,0 +1,11 @@ +import { SIPCallOptions } from '../SIPCallOptions'; + +/** + * Represents the request to initiate a SIP call with additional session information. + */ +export type InitiateSIPCallRequest = SIPCallOptions & { + /** + * The session ID of the Vonage Video session to associate with the SIP call. + */ + sessionId: string; +}; diff --git a/packages/video/lib/types/Response/BroadcastDetailsResponse.ts b/packages/video/lib/types/Response/BroadcastDetailsResponse.ts new file mode 100644 index 00000000..ee9dac81 --- /dev/null +++ b/packages/video/lib/types/Response/BroadcastDetailsResponse.ts @@ -0,0 +1,102 @@ +import { StreamMode, Resolution } from '../../enums'; +import { RTMPStream } from '../RTMPStream'; + +/** + * Represents HLS settings for a live streaming broadcast. + */ +export type HlsSettings = { + /** + * Whether to enable low-latency mode for the HLS stream. + */ + lowLatency?: boolean; +}; + +/** + * Represents the response containing details about a live streaming broadcast. + */ +export type BroadcastDetailsResponse = { + /** + * The unique ID for the broadcast. + */ + id: string; + + /** + * The Vonage Video session ID associated with the broadcast. + */ + sessionId: string; + + /** + * The unique tag for simultaneous broadcasts (if one was set). + */ + multiBroadcasTag?: string; + + /** + * The Vonage Application UUID. + */ + applicationId: string; + + /** + * The time the broadcast started, expressed in milliseconds since the Unix epoch (January 1, 1970, 00:00:00 UTC). + */ + createdAt: number; + + /** + * The timestamp when the broadcast was last updated, expressed in milliseconds since the Unix epoch. + */ + updatedAt: number; + + /** + * The maximum duration for the broadcast (if one was set), in seconds. + */ + maxDuration?: number; + + /** + * The maximum bitrate for the stream. + */ + maxBitrate?: number; + + /** + * An object containing details about the HLS and RTMP broadcasts. + */ + broadcastUrls: { + /** + * The URL for the HLS broadcast. + */ + hls?: string; + + /** + * An array of RTMP streams. + */ + rtmp: RTMPStream[]; + }; + + /** + * An object containing settings for HLS. + */ + settings?: { + /** + * HLS settings. + */ + hls?: HlsSettings; + }; + + /** + * The resolution of the broadcast, if set. + */ + resolution?: Resolution; + + /** + * Indicates whether the broadcast has video. + */ + hasVideo: boolean; + + /** + * Indicates whether the broadcast has audio. + */ + hasAudio: boolean; + + /** + * The stream mode for the broadcast. + */ + streamMode: StreamMode; +}; diff --git a/packages/video/lib/types/Response/CaptionStatusResponse.ts b/packages/video/lib/types/Response/CaptionStatusResponse.ts new file mode 100644 index 00000000..2082f9c0 --- /dev/null +++ b/packages/video/lib/types/Response/CaptionStatusResponse.ts @@ -0,0 +1,57 @@ +import { CaptionStatus } from "../../enums"; + +/** + * Represents a response containing the status of captions for a live streaming broadcast. + */ +export type CaptionStatusResponse = { + /** + * The unique ID for the caption. + */ + captionId: string; + + /** + * The Vonage Application UUID. + */ + applicationId: string; + + /** + * The Vonage Video session ID associated with the broadcast. + */ + sessionId: string; + + /** + * The status of the captions. + */ + status: CaptionStatus; + + /** + * The time when the caption was created, expressed in milliseconds since the + * Unix epoch (January 1, 1970, 00:00:00 UTC). + */ + createdAt: number; + + /** + * The timestamp when the caption was last updated, expressed in milliseconds since the Unix epoch. + */ + updatedAt: number; + + /** + * The duration of the caption, in seconds. + */ + duration: number; + + /** + * The language code of the captions (e.g., "en-us" for English, US). + */ + languageCode: "en-us"; + + /** + * The caption provider (e.g., "aws-transcribe"). + */ + provider: "aws-transcribe"; + + /** + * An optional reason for the caption status. + */ + reason?: string; +}; diff --git a/packages/video/lib/types/Response/CreateSessionResponse.ts b/packages/video/lib/types/Response/CreateSessionResponse.ts new file mode 100644 index 00000000..3ce3ad1f --- /dev/null +++ b/packages/video/lib/types/Response/CreateSessionResponse.ts @@ -0,0 +1,24 @@ +/** + * Represents a response containing the details of a created session. + */ +export type CreateSessionResponse = { + /** + * The unique session ID. + */ + session_id: string; + + /** + * The project ID associated with the session. + */ + project_id: string; + + /** + * The creation date and time of the session in string format. + */ + create_dt: string; + + /** + * The URL of the media server associated with the session. + */ + media_server_url: string; +}; diff --git a/packages/video/lib/types/Response/EnableCaptionResponse.ts b/packages/video/lib/types/Response/EnableCaptionResponse.ts new file mode 100644 index 00000000..c65e115b --- /dev/null +++ b/packages/video/lib/types/Response/EnableCaptionResponse.ts @@ -0,0 +1,9 @@ +/** + * Represents a response indicating the ID of the enabled caption. + */ +export type EnableCaptionResponse = { + /** + * The unique ID of the enabled caption. + */ + captionsId: string; +} diff --git a/packages/video/lib/types/Response/ExperienceComposerResponse.ts b/packages/video/lib/types/Response/ExperienceComposerResponse.ts new file mode 100644 index 00000000..b4fb3eb5 --- /dev/null +++ b/packages/video/lib/types/Response/ExperienceComposerResponse.ts @@ -0,0 +1,56 @@ +import { ExperienceComposerResolution } from "../../enums"; + +/** + * Represents a response from the Experience Composer. + */ +export type ExperienceComposerResponse = { + /** + * The unique ID of the response. + */ + id: string; + + /** + * The session ID associated with the response. + */ + sessionId: string; + + /** + * The application ID associated with the response. + */ + applicationId: string; + + /** + * The timestamp when the response was created (milliseconds since the Unix epoch). + */ + createdAt: number; + + /** + * The timestamp when the response was last updated (milliseconds since the Unix epoch). + */ + updatedAt: number; + + /** + * The URL associated with the response. + */ + url: string; + + /** + * The resolution used by the Experience Composer. + */ + resolution: ExperienceComposerResolution; + + /** + * The status of the response, which can be one of: "starting", "started", "stopped", "failed". + */ + status: "starting" | "started" | "stopped" | "failed"; + + /** + * The stream ID associated with the response. + */ + streamId: string; + + /** + * An optional reason for the status, if available. + */ + reason?: string; +} diff --git a/packages/video/lib/types/Response/MultiArchiveResponse.ts b/packages/video/lib/types/Response/MultiArchiveResponse.ts new file mode 100644 index 00000000..be411866 --- /dev/null +++ b/packages/video/lib/types/Response/MultiArchiveResponse.ts @@ -0,0 +1,16 @@ +import { SingleArchiveResponse } from './SingleArchiveResponse'; + +/** + * Represents a response containing multiple archive items. + */ +export type MultiArchiveResponse = { + /** + * The count of archive items in the response. + */ + count: number; + + /** + * An array of SingleArchiveResponse objects representing individual archive items. + */ + items: SingleArchiveResponse[]; +} diff --git a/packages/video/lib/types/Response/MultiBroadcastResponse.ts b/packages/video/lib/types/Response/MultiBroadcastResponse.ts new file mode 100644 index 00000000..a02b7e3c --- /dev/null +++ b/packages/video/lib/types/Response/MultiBroadcastResponse.ts @@ -0,0 +1,16 @@ +import { BroadcastDetailsResponse } from './BroadcastDetailsResponse'; + +/** + * Represents a response containing multiple broadcast details items. + */ +export type MultiBroadcastResponse = { + /** + * The count of broadcast details items in the response. + */ + count: number; + + /** + * An array of BroadcastDetailsResponse objects representing individual broadcast details items. + */ + items: BroadcastDetailsResponse[]; +} diff --git a/packages/video/lib/types/Response/MultiExperienceComposerResponse.ts b/packages/video/lib/types/Response/MultiExperienceComposerResponse.ts new file mode 100644 index 00000000..2ec4f0a5 --- /dev/null +++ b/packages/video/lib/types/Response/MultiExperienceComposerResponse.ts @@ -0,0 +1,16 @@ +import { ExperienceComposerResponse } from './ExperienceComposerResponse'; + +/** + * Represents a response containing multiple ExperienceComposerResponse items. + */ +export type MultiExperienceComposerResponse = { + /** + * The count of ExperienceComposerResponse items in the response. + */ + count: number; + + /** + * An array of ExperienceComposerResponse objects representing individual items. + */ + items: ExperienceComposerResponse[]; +} diff --git a/packages/video/lib/types/Response/MultiStreamLayoutResponse.ts b/packages/video/lib/types/Response/MultiStreamLayoutResponse.ts new file mode 100644 index 00000000..995db4e9 --- /dev/null +++ b/packages/video/lib/types/Response/MultiStreamLayoutResponse.ts @@ -0,0 +1,16 @@ +import { SingleStreamLayoutResponse } from './SingleStreamLayoutResponse'; + +/** + * Represents a response containing multiple SingleStreamLayoutResponse items. + */ +export type MultiStreamLayoutResponse = { + /** + * The count of SingleStreamLayoutResponse items in the response. + */ + count: number; + + /** + * An array of SingleStreamLayoutResponse objects representing individual items. + */ + items: SingleStreamLayoutResponse[]; +} diff --git a/packages/video/lib/types/Response/ProjectDetailsResponse.ts b/packages/video/lib/types/Response/ProjectDetailsResponse.ts new file mode 100644 index 00000000..333b934c --- /dev/null +++ b/packages/video/lib/types/Response/ProjectDetailsResponse.ts @@ -0,0 +1,34 @@ +/** + * Represents the details of a project. + */ +export type ProjectDetailsResponse = { + /** + * The unique identifier of the project. + */ + id: string; + + /** + * The secret associated with the project. + */ + secret: string; + + /** + * The status of the project. + */ + status: string; + + /** + * The name of the project. + */ + name: string; + + /** + * The environment of the project. + */ + environment: string; + + /** + * The timestamp when the project was created, expressed in milliseconds since the Unix epoch. + */ + createdAt: number; +} diff --git a/packages/video/lib/types/Response/SIPCallResponse.ts b/packages/video/lib/types/Response/SIPCallResponse.ts new file mode 100644 index 00000000..cf5499f2 --- /dev/null +++ b/packages/video/lib/types/Response/SIPCallResponse.ts @@ -0,0 +1,19 @@ +/** + * Represents the response for a SIP call initiation. + */ +export type SIPCallResponse = { + /** + * The unique identifier of the SIP call. + */ + id: string; + + /** + * The connection identifier associated with the SIP call. + */ + connectionId: string; + + /** + * The stream identifier associated with the SIP call. + */ + streamId: string; +} diff --git a/packages/video/lib/types/Response/SingleArchiveResponse.ts b/packages/video/lib/types/Response/SingleArchiveResponse.ts new file mode 100644 index 00000000..108516b3 --- /dev/null +++ b/packages/video/lib/types/Response/SingleArchiveResponse.ts @@ -0,0 +1,84 @@ +/** + * Represents the details of a single archive. + */ +export type SingleArchiveResponse = { + /** + * The timestamp when the archive was created, expressed in milliseconds since the Unix epoch. + */ + createdAt: number; + + /** + * The duration of the archive in seconds. + */ + duration: number; + + /** + * Indicates whether the archive has audio. + */ + hasAudio: boolean; + + /** + * Indicates whether the archive has video. + */ + hasVideo: boolean; + + /** + * The unique identifier of the archive. + */ + id: string; + + /** + * The name of the archive. + */ + name: string; + + /** + * The output mode of the archive. + */ + outputMode: string; + + /** + * The unique identifier of the project to which the archive belongs. + */ + projectId: string; + + /** + * The reason for the archive status. + */ + reason: string; + + /** + * The resolution of the archive. + */ + resolution: string; + + /** + * The unique identifier of the session associated with the archive. + */ + sessionId: string; + + /** + * The size of the archive in bytes. + */ + size: number; + + /** + * The status of the archive. + */ + status: string; + + /** + * The stream mode of the archive. + */ + streamMode: string; + + /** + * The URL of the archive. + */ + url?: string; + + /** + * An array of stream identifiers associated with the archive. + */ + streams?: string[]; +} diff --git a/packages/video/lib/types/Response/SingleStreamLayoutResponse.ts b/packages/video/lib/types/Response/SingleStreamLayoutResponse.ts new file mode 100644 index 00000000..da7fd112 --- /dev/null +++ b/packages/video/lib/types/Response/SingleStreamLayoutResponse.ts @@ -0,0 +1,24 @@ +/** + * Represents the details of a single stream layout. + */ +export type SingleStreamLayoutResponse = { + /** + * The unique identifier of the stream layout. + */ + id: string; + + /** + * The type of video associated with the stream layout. + */ + videoType: string; + + /** + * The name of the stream layout. + */ + name: string; + + /** + * An array of CSS class names associated with the layout. + */ + layoutClassList: string[]; +} diff --git a/packages/video/lib/types/Response/WebSocketConnectResponse.ts b/packages/video/lib/types/Response/WebSocketConnectResponse.ts new file mode 100644 index 00000000..95a15799 --- /dev/null +++ b/packages/video/lib/types/Response/WebSocketConnectResponse.ts @@ -0,0 +1,14 @@ +/** + * Represents the response for a WebSocket connection. + */ +export type WebSocketConnectResponse = { + /** + * The unique identifier of the WebSocket connection. + */ + id: string; + + /** + * The connection identifier associated with the WebSocket connection. + */ + connectionId: string; +} diff --git a/packages/video/lib/interfaces/Response/index.ts b/packages/video/lib/types/Response/index.ts similarity index 100% rename from packages/video/lib/interfaces/Response/index.ts rename to packages/video/lib/types/Response/index.ts diff --git a/packages/video/lib/types/SIPCallOptions.ts b/packages/video/lib/types/SIPCallOptions.ts new file mode 100644 index 00000000..49fe2653 --- /dev/null +++ b/packages/video/lib/types/SIPCallOptions.ts @@ -0,0 +1,66 @@ +/** + * Configuration options for a SIP call. + */ +export type SIPCallSIPConfig = { + /** + * The SIP URI to initiate the call. + */ + uri: string; + + /** + * The optional "from" field for the SIP call. + */ + from?: string; + + /** + * Custom headers to be included in the SIP call. + */ + headers?: { + [key: string]: string; + }; + + /** + * Authentication credentials for the SIP call. + */ + auth?: { + /** + * The username for SIP authentication. + */ + username: string; + + /** + * The password for SIP authentication. + */ + password: string; + }; + + /** + * Indicates whether the SIP call should be secure. + */ + secure?: boolean; + + /** + * Indicates whether video is enabled for the SIP call. + */ + video?: boolean; + + /** + * Indicates whether to observe and force mute for the SIP call. + */ + observeForceMute?: boolean; +} + +/** + * Interface representing options for initiating a SIP call. + */ +export type SIPCallOptions = { + /** + * The authentication token for the SIP call. + */ + token: string; + + /** + * Configuration options for the SIP call. + */ + sip: SIPCallSIPConfig; +} diff --git a/packages/video/lib/types/Session.ts b/packages/video/lib/types/Session.ts new file mode 100644 index 00000000..3c551af0 --- /dev/null +++ b/packages/video/lib/types/Session.ts @@ -0,0 +1,24 @@ +/** + * Interface representing a session configuration. + */ +export type Session = { + /** + * The unique identifier for the session. + */ + sessionId: string; + + /** + * The location of the session. + */ + location: string; + + /** + * The media mode for the session (e.g., "ROUTED" or "RELAYED"). + */ + mediaMode: string; + + /** + * The archive mode for the session (e.g., "MANUAL" or "ALWAYS"). + */ + archiveMode: string; +} diff --git a/packages/video/lib/types/Singal.ts b/packages/video/lib/types/Singal.ts new file mode 100644 index 00000000..09fc1c1d --- /dev/null +++ b/packages/video/lib/types/Singal.ts @@ -0,0 +1,14 @@ +/** + * Represents a signal containing type and data properties. + */ +export type Signal = { + /** + * The type of the signal, which can be a custom string identifying the signal type. + */ + type: string; + + /** + * The data associated with the signal, which can be any string data related to the signal. + */ + data: string; +} diff --git a/packages/video/lib/types/StreamClassList.ts b/packages/video/lib/types/StreamClassList.ts new file mode 100644 index 00000000..6d414db2 --- /dev/null +++ b/packages/video/lib/types/StreamClassList.ts @@ -0,0 +1,14 @@ +/** + * Represents a stream with associated layout class list. + */ +export type StreamClassList = { + /** + * The ID of the stream. + */ + id: string; + + /** + * An array of layout class names associated with the stream. + */ + layoutClassList: string[]; +} diff --git a/packages/video/lib/types/VideoResponse.ts b/packages/video/lib/types/VideoResponse.ts new file mode 100644 index 00000000..b3ffdb57 --- /dev/null +++ b/packages/video/lib/types/VideoResponse.ts @@ -0,0 +1,6 @@ +import { VetchResponse } from '@vonage/vetch'; + +/** + * Represents a video response that wraps a Vetch response. + */ +export type VideoResponse = VetchResponse; diff --git a/packages/video/lib/types/WebSocketConfig.ts b/packages/video/lib/types/WebSocketConfig.ts new file mode 100644 index 00000000..d3b78224 --- /dev/null +++ b/packages/video/lib/types/WebSocketConfig.ts @@ -0,0 +1,28 @@ +import { AudioRate } from '../enums'; + +/** + * Configuration options for establishing a WebSocket connection. + */ +export type WebSocketConfig = { + /** + * The URI to connect to the WebSocket server. + */ + uri: string; + + /** + * An array of stream IDs to associate with the WebSocket connection. + */ + streams?: string[]; + + /** + * Optional headers to include in the WebSocket request. + */ + headers?: { + [key: string]: string; + }; + + /** + * The audio rate to be used for the WebSocket connection. + */ + audioRate?: AudioRate; +} diff --git a/packages/video/lib/interfaces/index.ts b/packages/video/lib/types/index.ts similarity index 89% rename from packages/video/lib/interfaces/index.ts rename to packages/video/lib/types/index.ts index 9c2e0889..2a4563c4 100644 --- a/packages/video/lib/interfaces/index.ts +++ b/packages/video/lib/types/index.ts @@ -10,10 +10,11 @@ export * from './ClientTokenClaims'; export * from './ClientTokenOptions'; export * from './ExperienceComposerListFilter'; export * from './ExperienceComposerOptions'; -export * from './MediaMode'; export * from './Response'; +export * from './Request/InitiateSIPCallRequest'; export * from './RTMPStream'; export * from './Session'; +export * from './Singal'; export * from './SIPCallOptions'; export * from './StreamClassList'; export * from './VideoResponse'; diff --git a/packages/video/lib/video.ts b/packages/video/lib/video.ts index 5ea65dae..26bc4d5e 100644 --- a/packages/video/lib/video.ts +++ b/packages/video/lib/video.ts @@ -1,41 +1,104 @@ import { tokenGenerate } from '@vonage/jwt'; -import { VideoResponse } from './interfaces/VideoResponse'; -import { MultiStreamLayoutResponse } from './interfaces/Response/MultiStreamLayoutResponse'; -import { SingleStreamLayoutResponse } from './interfaces/Response/SingleStreamLayoutResponse'; -import { ProjectDetailsResponse } from './interfaces/Response/ProjectDetailsResponse'; -import { ArchiveOptions } from './interfaces/ArchiveOptions'; -import { SingleArchiveResponse } from './interfaces/Response/SingleArchiveResponse'; -import { MultiArchiveResponse } from './interfaces/Response/MultiArchiveResponse'; -import { ArchiveSearchFilter } from './interfaces/ArchiveSearchFilter'; -import { ArchiveLayout } from './interfaces/ArchiveLayout'; -import { MediaMode } from './interfaces/MediaMode'; -import { ArchiveMode } from './interfaces/ArchiveMode'; -import { Session } from './interfaces/Session'; -import { StreamClassList } from './interfaces/StreamClassList'; -import { ClientTokenOptions } from './interfaces/ClientTokenOptions'; import { AuthenticationType, Client } from '@vonage/server-client'; -import { BroadcastConfig } from './interfaces/BroadcastConfig'; -import { BroadcastDetailsResponse } from './interfaces/Response/BroadcastDetailsResponse'; -import { BroadcastSearchFilter } from './interfaces/BroadcastSearchFilter'; -import { MultiBroadcastResponse } from './interfaces/Response/MultiBroadcastResponse'; -import { BroadcastUpdateConfig } from './interfaces/BroadcastUpdateConfig'; -import { SIPCallOptions } from './interfaces/SIPCallOptions'; -import { SIPCallResponse } from './interfaces/Response/SIPCallResponse'; -import { WebSocketConfig } from './interfaces/WebSocketConfig'; -import { WebSocketConnectResponse } from './interfaces/Response/WebSocketConnectResponse'; -import { MultiExperienceComposerResponse } from './interfaces/Response/MultiExperienceComposerResponse'; -import { ExperienceComposerResponse } from './interfaces/Response/ExperienceComposerResponse'; -import { ExperienceComposerOptions } from './interfaces/ExperienceComposerOptions'; -import { ExperienceComposerListFilter } from './interfaces/ExperienceComposerListFilter'; -import { ClientTokenClaims } from './interfaces/ClientTokenClaims'; -import { CaptionOptions } from './interfaces/CaptionOptions'; -import { EnableCaptionResponse } from './interfaces/Response/EnableCaptionResponse'; -import { CaptionStatusResponse } from './interfaces/Response/CaptionStatusResponse'; -import { InitiateSIPCallRequest } from './interfaces/Request/InitiateSIPCallRequest'; +import { MediaMode } from './enums'; +import { + ArchiveLayout, + ArchiveMode, + ArchiveOptions, + ArchiveSearchFilter, + BroadcastConfig, + BroadcastDetailsResponse, + BroadcastSearchFilter, + BroadcastUpdateConfig, + CaptionOptions, + CaptionStatusResponse, + ClientTokenClaims, + ClientTokenOptions, + CreateSessionResponse, + EnableCaptionResponse, + ExperienceComposerListFilter, + ExperienceComposerOptions, + ExperienceComposerResponse, + InitiateSIPCallRequest, + MultiArchiveResponse, + MultiBroadcastResponse, + MultiExperienceComposerResponse, + MultiStreamLayoutResponse, + ProjectDetailsResponse, + SIPCallOptions, + SIPCallResponse, + Session, + Signal, + SingleArchiveResponse, + SingleStreamLayoutResponse, + StreamClassList, + VideoResponse, + WebSocketConfig, + WebSocketConnectResponse, +} from './types'; +/** + * Video Client for managing and interacting with video-related operations in your application. + * This client allows you to control sessions, streams, archives, broadcasts, and various video-related features. + * + * Usage: + * - Create and manage video sessions with customizable settings. + * - Control video streams, including muting, adding, and removing streams. + * - Initiate SIP calls and establish WebSockets for real-time communication. + * - Enable and disable captions for improved accessibility. + * - Start, stop, and manage video archives and broadcasts. + * - Render experiences and access detailed information about streams and archives. + * - Generate client tokens for secure session connections. + * - Perform various video-related operations with ease. + * + * @remarks + * The Video Client is designed to simplify video management tasks within your application. + * It provides a comprehensive set of methods and options to configure and control video interactions seamlessly. + * + * @example + * Create a standalone Video client + * + * ```ts + * import { Video } from '@vonage/video'; + * + * const videoClient = new Video({ + * apiKey: VONAGE_API_KEY, + * apiSecret: VONAGE_API_SECRET + * }); + * ``` + * + * @example + * Create an Video client from the Vonage client + * + * ```ts + * import { Vonage } from '@vonage/server-client'; + * + * const vonage = new Vonage({ + * apiKey: VONAGE_API_KEY, + * apiSecret: VONAGE_API_SECRET + * }); + * + * const videoClient = vonage.video; + * ``` + */ export class Video extends Client { protected authType = AuthenticationType.JWT; + /** + * Adds a stream to an existing archive, allowing you to include additional streams in the archive recording. + * + * @param {string} archiveId - The ID of the archive to which you want to add a stream. + * @param {string} streamId - The ID of the stream you want to add to the archive. + * @param {boolean} [audio=true] - Whether to include audio from the added stream (default: true). + * @param {boolean} [video=true] - Whether to include video from the added stream (default: true). + * @return {Promise} A promise that resolves when the stream has been successfully added to the archive. + * @throws {Error} If an error occurs while adding the stream to the archive. + * + * @example + * ```ts + * await videoClient.addArchiveStream(ARCHIVE_ID, STREAM_ID); + * ``` + */ public async addArchiveStream( archiveId: string, streamId: string, @@ -54,6 +117,19 @@ export class Video extends Client { ); } + /** + * Adds a stream to an existing broadcast, allowing you to include additional streams in the live broadcast. + * + * @param {string} broadcastId - The ID of the broadcast to which you want to add a stream. + * @param {string} streamId - The ID of the stream you want to add to the broadcast. + * @return {Promise} A promise that resolves when the stream has been successfully added to the broadcast. + * @throws {Error} If an error occurs while adding the stream to the broadcast. + * + * @example + * ```ts + * await videoClient.addStreamToBroadcast(BROADCAST_ID, STREAM_ID); + * ``` + */ public async addStreamToBroadcast( broadcastId: string, streamId: string, @@ -61,6 +137,28 @@ export class Video extends Client { await this.updateBroadcast({ broadcastId, addStream: streamId }); } + /** + * Connects to a WebSocket for a specified session using the provided client token and WebSocket configuration. + * + * @param {string} sessionId - The ID of the session to which you want to connect via WebSocket. + * @param {string} clientToken - The client token generated for authentication. + * @param {WebSocketConfig} config - The WebSocket configuration specifying the URI and optional parameters. + * @return {Promise} A promise that resolves with WebSocket connection details upon successful connection. + * @throws {Error} If an error occurs during the WebSocket connection process. + * + * @example + * ```ts + * const result = await videoClient.connectToWebsocket( + * SESSION_ID, + * CLIENT_TOKEN, + * { + * uri: 'wss://example.com', + * }, + * ) + * + * console.log(result.id); + * ``` + */ public async connectToWebsocket( sessionId: string, clientToken: string, @@ -79,49 +177,148 @@ export class Video extends Client { return resp.data; } + /** + * Creates a new session with the specified options. + * + * @param {Object} [sessionOptions] - Optional session configuration options. + * @param {ArchiveMode} [sessionOptions.archiveMode=ArchiveMode.MANUAL] - The archive mode for the session. + * @param {MediaMode} [sessionOptions.mediaMode=MediaMode.ROUTED] - The media mode for the session. + * @param {string} [sessionOptions.location] - The location for the session. + * @return {Promise} A promise that resolves with details of the newly created session. + * @throws {Error} If an error occurs during the session creation process. + * + * @example + * Create a session with default options + * ```ts + * const session = await videoClient.createSession({}); + * console.log(session.sessionId); + * ``` + * + * @example + * Create a session with archive mode set to manual + * ```ts + * import { ArchiveMode } from '@vonage/video'; + * + * const session = await videoClient.createSession({ + * archiveMode: ArchiveMode.MANUAL, + * }); + * console.log(session.sessionId); + * ``` + * + * @example + * Create a session with location set to a specific region + * ```ts + * const session = await videoClient.createSession({ + * location: 'eu', + * }); + * console.log(session.sessionId); + * ``` + * + * @example + * Create a session with media mode set to routed + * ```ts + * import { MediaMode } from '@vonage/video'; + * + * const session = await videoClient.createSession({ + * mediaMode: MediaMode.ROUTED, + * }); + * console.log(session.sessionId); + * ``` + */ public async createSession(sessionOptions?: { - archiveMode?: ArchiveMode - location?: string - mediaMode?: MediaMode - }): Promise { + archiveMode?: ArchiveMode; + location?: string; + mediaMode?: MediaMode; + }): Promise { const data = { archiveMode: sessionOptions?.archiveMode ?? ArchiveMode.MANUAL, 'p2p.preference': sessionOptions?.mediaMode ?? MediaMode.ROUTED, location: sessionOptions?.location ?? null, - }; + } as Record; - const resp = await this.sendFormSubmitRequest( + const resp = await this.sendFormSubmitRequest( `${this.config.videoHost}/session/create`, data, ); return { - sessionId: resp.data[0].session_id, + sessionId: resp.data.session_id, archiveMode: data.archiveMode, mediaMode: data['p2p.preference'], location: data.location, }; } + /** + * Deletes an archive with the specified archive ID. + * + * @param {string} archiveId - The ID of the archive to delete. + * @return {Promise} A promise that resolves when the archive is successfully deleted. + * @throws {Error} If an error occurs while deleting the archive or if the archive with the given ID does not exist. + * + * @example + * ```ts + * await videoClient.deleteArchive(ARCHIVE_ID); + * ``` + */ public async deleteArchive(archiveId: string): Promise { await this.sendDeleteRequest( `${this.config.videoHost}/v2/project/${this.auth.applicationId}/archive/${archiveId}`, ); } + /** + * Disables captions for a specific caption ID. + * + * @param {string} captionId - The ID of the caption to disable. + * @return {Promise} A promise that resolves when the captions are successfully disabled. + * @throws {Error} If an error occurs while disabling captions or if the caption with the given ID does not exist. + * + * @example + * ```ts + * await videoClient.disableCaptions(CAPTION_ID); + * ``` + */ public async disableCaptions(captionId: string): Promise { await this.sendPostRequest( `${this.config.videoHost}/v2/project/${this.auth.applicationId}/captions/${captionId}/stop`, ); } + /** + * Disables force mute for a session, allowing audio for all streams. + * + * @param {string} sessionId - The ID of the session for which to disable force mute. + * @param {string[]} excludedStreamIds - An optional array of stream IDs to exclude from the force mute operation. + * @return {Promise} A promise that resolves when the force mute is successfully disabled for the session. + * @throws {Error} If an error occurs while disabling force mute or if the session with the given ID does not exist. + * + * @example + * ```ts + * const forceMute = await videoClient.disableForceMute(SESSION_ID); + * console.log(forceMute.status); + * ``` + */ public async disableForceMute( sessionId: string, excludedStreamIds: string[] = [], - ) { + ): Promise { return this.muteAllStreams(sessionId, false, excludedStreamIds); } + /** + * Disconnects a client from a session. + * + * @param {string} sessionId - The ID of the session from which to disconnect the client. + * @param {string} connectionId - The ID of the client's connection to disconnect. + * @return {Promise} A promise that resolves when the client is successfully disconnected from the session. + * @throws {Error} If an error occurs while disconnecting the client or if the session or connection with the given IDs do not exist. + * + * @example + * ```ts + * await videoClient.disconnectClient(SESSION_ID, CONNECTION_ID); + * ``` + */ public async disconnectClient( sessionId: string, connectionId: string, @@ -131,12 +328,39 @@ export class Video extends Client { ); } + /** + * Disconnects a WebSocket connection associated with a call or session. + * + * @param {string} callId - The ID of the call or session to which the WebSocket connection is associated. + * @return {Promise} A promise that resolves when the WebSocket connection is successfully disconnected. + * @throws {Error} If an error occurs while disconnecting the WebSocket connection or if the call or session with the given ID does not exist. + * + * @example + * ```ts + * await videoClient.disconnectWebsocket(CALL_ID); + * ``` + */ public async disconnectWebsocket(callId: string): Promise { await this.sendPostRequest( `${this.config.videoHost}/v2/project/${this.auth.applicationId}/connect/${callId}/stop`, ); } + /** + * Enables captions for a session using the specified client token and caption options. + * + * @param {string} sessionId - The ID of the session to enable captions for. + * @param {string} clientToken - The client token associated with the session, used for authentication. + * @param {CaptionOptions} [captionOptions] - Optional caption options to configure caption behavior. + * @return {Promise} A promise that resolves with an `EnableCaptionResponse` containing information about the enabled captions. + * @throws {Error} If an error occurs while enabling captions or if the session with the given ID does not exist. + * + * @example + * ```ts + * const result = await videoClient.enableCaptions(SESSION_ID, CLIENT_TOKEN); + * console.log(result.captionId); + * ``` + */ public async enableCaptions( sessionId: string, clientToken: string, @@ -154,23 +378,51 @@ export class Video extends Client { return resp.data; } + /** + * Forces muting of all streams in a session, except those specified in the `excludedStreamIds` array. + * + * @param {string} sessionId - The ID of the session in which to force mute streams. + * @param {string[]} [excludedStreamIds] - An optional array of stream IDs to exclude from muting. + * @return {Promise} A promise that resolves with a `ProjectDetailsResponse` containing updated session details after muting. + * @throws {Error} If an error occurs while muting the streams or if the session with the given ID does not exist. + * + * @example + * ```ts + * const forceMute = await videoClient.forceMuteAll(SESSION_ID); + * console.log(forceMute.status); + * ``` + */ public async forceMuteAll( sessionId: string, excludedStreamIds: string[] = [], - ) { + ): Promise { return this.muteAllStreams(sessionId, true, excludedStreamIds); } + /** + * Generates a client token for connecting to a session with the specified options. + * + * @param {string} sessionId - The ID of the session to generate the client token for. + * @param {ClientTokenOptions} [tokenOptions] - Optional token options including role, data, and expiration time. + * @return {string} A client token that can be used for authentication when connecting to a session. + * + * @example + * ```ts + * const token = videoClient.generateClientToken(SESSION_ID); + * console.log(`The token is ${token}`); + * ``` + */ public generateClientToken( sessionId: string, tokenOptions?: ClientTokenOptions, - ) { + ): string { const now = Math.round(new Date().getTime() / 1000); const claims: ClientTokenClaims = { scope: 'session.connect', session_id: sessionId, role: 'publisher', initial_layout_class_list: '', + exp: tokenOptions?.expireTime || now + 86400, sub: 'video', acl: { paths: { @@ -187,19 +439,28 @@ export class Video extends Client { } if (tokenOptions?.initialLayoutClassList) { claims.initial_layout_class_list - = tokenOptions.initialLayoutClassList.join(' '); - } - if (tokenOptions?.expireTime && tokenOptions.expireTime > now) { - claims.exp = tokenOptions.expireTime; + = tokenOptions.initialLayoutClassList.join(' '); } return tokenGenerate( - this.auth.applicationId, - this.auth.privateKey, + this.auth.applicationId as string, + this.auth.privateKey as string | Buffer, claims, ); } + /** + * Retrieves information about a specific archive by its ID. + * + * @param {string} archiveId - The ID of the archive to retrieve. + * @return {Promise} A promise that resolves to the details of the requested archive. + * + * @example + * ```ts + * const archive = await videoClient.getArchive(ARCHIVE_ID); + * console.log(archive.createdAt); + * ``` + */ public async getArchive(archiveId: string): Promise { const resp = await this.sendGetRequest( `${this.config.videoHost}/v2/project/${this.auth.applicationId}/archive/${archiveId}`, @@ -207,6 +468,17 @@ export class Video extends Client { return resp.data; } + /** + * Retrieves information about a specific broadcast by its ID. + * + * @param {string} broadcastId - The ID of the broadcast to retrieve. + * @return {Promise} A promise that resolves to the details of the requested broadcast. + * + * ```ts + * const broadcast = await videoClient.getBroadcast(BROADCAST_ID); + * console.log(broadcast.createdAt); + * ``` + */ public async getBroadcast( broadcastId: string, ): Promise { @@ -216,6 +488,18 @@ export class Video extends Client { return resp.data; } + /** + * Retrieves the status of a caption by its ID. + * + * @param {string} captionId - The ID of the caption to retrieve the status for. + * @return {Promise} A promise that resolves to the status of the requested caption. + * + * @example + * ```ts + * const captionStatus = await videoClient.getCaptionStatus(CAPTION_ID); + * console.log(captionStatus.status); + * ``` + */ public async getCaptionStatus( captionId: string, ): Promise { @@ -225,6 +509,18 @@ export class Video extends Client { return resp.data; } + /** + * Retrieves the details of an Experience Composer render by its ID. + * + * @param {string} renderId - The ID of the Experience Composer render to retrieve. + * @return {Promise} A promise that resolves to the details of the requested Experience Composer render. + * + * @example + * ```ts + * const render = await videoClient.getExperienceComposerRender(RENDER_ID); + * console.log(render.createdAt); + * ``` + */ public async getExperienceComposerRender( renderId: string, ): Promise { @@ -234,6 +530,26 @@ export class Video extends Client { return resp.data; } + /** + * Retrieves information about one or more streams in a session. + * + * @param {string} sessionId - The ID of the session to retrieve stream information from. + * @param {string | undefined} [streamId] - Optional. The ID of a specific stream to retrieve information for. + * @return {Promise} A promise that resolves to stream information. If a specific `streamId` is provided, it resolves to a single stream's information (SingleStreamLayoutResponse), otherwise, it resolves to multiple streams' information (MultiStreamLayoutResponse). + * + * @example + * ```ts + * const streamInfo = await videoClient.getStreamInfo(SESSION_ID); + * + * if (streamInfo.items) { + * streamInfo.items.forEach((item) => { + * console.log(item.id); + * }); + * } else { + * console.log(streamInfo.id); + * } + * ``` + */ public async getStreamInfo( sessionId: string, streamId?: string, @@ -244,8 +560,8 @@ export class Video extends Client { } let resp: VideoResponse< - MultiStreamLayoutResponse | SingleStreamLayoutResponse - >; + MultiStreamLayoutResponse | SingleStreamLayoutResponse + >; if (streamId) { resp = await this.sendGetRequest(url); } else { @@ -266,6 +582,32 @@ export class Video extends Client { return obj; } + /** + * Initiates a SIP call within a session. + * + * @param {string} sessionId - The ID of the session in which to initiate the SIP call. + * @param {SIPCallOptions} options - The options for initiating the SIP call. + * @return {Promise} A promise that resolves to the SIP call response, including the call ID and other details. + * + * @example + * Start a SIP call with default options + * ```ts + * const sipCall = await videoClient.intiateSIPCall(SESSION_ID); + * console.log(sipCall.id); + * ``` + * + * @example + * Start a SIP call with custom options + * ```ts + * const sipCall = await videoClient.intiateSIPCall( + * SESSION_ID, + * { + * uri: 'sip://example.com', + * } + * ); + * console.log(sipCall.id); + * ``` + */ public async intiateSIPCall( sessionId: string, options: SIPCallOptions, @@ -285,6 +627,20 @@ export class Video extends Client { return resp.data; } + /** + * Lists Experience Composer renders based on the specified filter criteria. + * + * @param {ExperienceComposerListFilter} filter - An optional filter to apply when listing Experience Composer renders. + * @return {Promise} A promise that resolves to a list of Experience Composer renders matching the filter criteria. + * + * @example + * ```ts + * const renders = await videoClient.listExperienceComposerRenders(); + * for (const render of renders.items) { + * console.log(render.id); + * } + * ``` + */ public async listExperienceComposerRenders( filter: ExperienceComposerListFilter, ): Promise { @@ -295,6 +651,20 @@ export class Video extends Client { return resp.data; } + /** + * Mutes or unmutes all streams in a session, optionally excluding specific stream IDs from muting. + * + * @param {string} sessionId - The ID of the session in which to mute or unmute streams. + * @param {boolean} active - `true` to mute all streams, `false` to unmute all streams. + * @param {string[]} excludedStreamIds - An optional array of stream IDs to exclude from muting/unmuting. + * @return {Promise} A promise that resolves to the updated session details. + * + * @example + * ```ts + * const forceMute = await videoClient.muteAll(SESSION_ID); + * console.log(forceMute.status); + * ``` + */ protected async muteAllStreams( sessionId: string, active: boolean, @@ -310,6 +680,19 @@ export class Video extends Client { return resp.data; } + /** + * Mutes or unmutes a specific stream in a session. + * + * @param {string} sessionId - The ID of the session containing the stream. + * @param {string} streamId - The ID of the stream to mute or unmute. + * @return {Promise} A promise that resolves to the updated session details. + * + * @example + * ```ts + * const forceMute = await videoClient.muteStream(SESSION_ID, STREAM_ID); + * console.log(forceMute.status); + * ``` + */ public async muteStream( sessionId: string, streamId: string, @@ -320,6 +703,19 @@ export class Video extends Client { return resp.data; } + /** + * Sends DTMF (Dual-Tone Multi-Frequency) tones to a specific session or connection. + * + * @param {string} sessionId - The ID of the session to send DTMF tones to. + * @param {string} digits - The DTMF tones to play. + * @param {string} [connectionId] - Optional. The ID of the connection within the session to send DTMF tones to. + * @return {Promise} A promise that resolves when the DTMF tones have been played. + * + * @example + * ```ts + * await videoClient.playDTMF(SESSION_ID, '1234'); + * ``` + */ public async playDTMF( sessionId: string, digits: string, @@ -333,6 +729,18 @@ export class Video extends Client { await this.sendPostRequest(url, { digits }); } + /** + * Removes a stream from an archive. + * + * @param {string} archiveId - The ID of the archive from which to remove the stream. + * @param {string} streamId - The ID of the stream to remove from the archive. + * @return {Promise} A promise that resolves when the stream has been successfully removed from the archive. + * + * @example + * ```ts + * await videoClient.removeArchiveStream(ARCHIVE_ID, STREAM_ID); + * ``` + */ public async removeArchiveStream( archiveId: string, streamId: string, @@ -343,6 +751,18 @@ export class Video extends Client { ); } + /** + * Removes a stream from a broadcast. + * + * @param {string} broadcastId - The ID of the broadcast from which to remove the stream. + * @param {string} streamId - The ID of the stream to remove from the broadcast. + * @return {Promise} A promise that resolves when the stream has been successfully removed from the broadcast. + * + * @example + * ```ts + * await videoClient.removeStreamFromBroadcast(BROADCAST_ID, STREAM_ID); + * ``` + */ public async removeStreamFromBroadcast( broadcastId: string, streamId: string, @@ -350,6 +770,31 @@ export class Video extends Client { await this.updateBroadcast({ broadcastId, removeStream: streamId }); } + /** + * Searches for archives based on the specified filter criteria. + * + * @param {ArchiveSearchFilter} [filter] - Optional filter criteria to narrow down the search. + * @return {Promise} A promise that resolves with the search results, including multiple archive items. + * + * @example + * ```ts + * const archives = await videoClient.searchArchives(); + * for (const archive of archives.items) { + * console.log(archive.id); + * } + * ``` + * @example + * Search for archives for a session + * ```ts + * const archives = await videoClient.searchArchives({ + * sessionId: SESSION_ID, + * }); + * + * for (const archive of archives.items) { + * console.log(archive.id); + * } + * ``` + */ public async searchArchives( filter?: ArchiveSearchFilter, ): Promise { @@ -360,6 +805,31 @@ export class Video extends Client { return resp.data; } + /** + * Searches for broadcasts based on the specified filter criteria. + * + * @param {BroadcastSearchFilter} [filter] - Optional filter criteria to narrow down the search. + * @return {Promise} A promise that resolves with the search results, including multiple broadcast items. + * + * @example + * ```ts + * const broadcasts = await videoClient.searchBroadcasts(); + * for (const broadcast of broadcasts.items) { + * console.log(broadcast.id); + * } + * ``` + * + * @example + * Get braodcasts for a session + * ```ts + * const broadcasts = await videoClient.searchBroadcasts({ + * sessionId: SESSION_ID, + * }) + * for (const broadcast of broadcasts.items) { + * console.log(broadcast.id); + * } + * ``` + */ public async searchBroadcasts( filter?: BroadcastSearchFilter, ): Promise { @@ -370,8 +840,26 @@ export class Video extends Client { return resp.data; } + /** + * Sends a signal to a session or a specific connection within a session. + * + * @param {Signal} signal - The signal to send, including a type and data. + * @param {string} sessionId - The ID of the session to which the signal will be sent. + * @param {string} [connectionId] - Optional. The ID of the connection within the session to which the signal will be sent. If not provided, the signal will be sent to the entire session. + * @return {Promise} A promise that resolves when the signal is successfully sent. + * + * @example + * await videoClient.sendSignal( + * { + * type: 'text', + * data: 'Hello world!', + * }, + * SESSION_ID, + * ); + * ``` + */ public async sendSignal( - signal: { type: string; data: string }, + signal: Signal, sessionId: string, connectionId?: string, ): Promise { @@ -383,6 +871,27 @@ export class Video extends Client { await this.sendPostRequest(url, signal); } + /** + * Sets the stream class lists for one or more streams within a session. + * + * @param {string} sessionId - The ID of the session for which stream class lists will be set. + * @param {StreamClassList[]} settings - An array of objects specifying the stream ID and corresponding class lists to be set. + * @return {Promise} A promise that resolves when the stream class lists are successfully set. + * + * @example + * + * ```ts + * await videoClient.setStreamClassLists( + * SESSION_ID, + * [ + * { + * id: STREAM_ID, + * layoutClassList: ['full'], + * } + * ] + * ) + * ``` + */ public async setStreamClassLists( sessionId: string, settings: StreamClassList[], @@ -393,6 +902,19 @@ export class Video extends Client { ); } + /** + * Starts an archive for a given session with optional configuration. + * + * @param {string} sessionId - The ID of the session to archive. + * @param {ArchiveOptions} [options] - Optional configuration for the archive, such as audio/video settings, layout, and more. + * @return {Promise} A promise that resolves with information about the started archive. + * + * @example + * ```ts + * const archive = await videoClient.startArchive(SESSION_ID); + * console.log(archive.id); + * ``` + */ public async startArchive( sessionId: string, options?: ArchiveOptions, @@ -406,6 +928,30 @@ export class Video extends Client { return resp.data; } + /** + * Starts a broadcast for a given session with the specified configuration. + * + * @param {string} sessionId - The ID of the session to start broadcasting. + * @param {BroadcastConfig} config - Configuration for the broadcast, including stream settings, layout, and more. + * @return {Promise} A promise that resolves with information about the started broadcast. + * + * @example + * ```ts + * const broadcast = await videoClient.startBroadcast( + * SESSION_ID, + * { + * outputs: { + * hls: { + * lowLatency: true, + * } + * rtmp: [{ + * serverUrl: 'rtmp://example.com', + * }], + * } + * } + * ); + * ``` + */ public async startBroadcast( sessionId: string, config: BroadcastConfig, @@ -418,6 +964,25 @@ export class Video extends Client { return resp.data; } + /** + * Starts rendering an experience composer with the provided configuration. + * + * @param {string} sessionId - The ID of the session associated with the experience composer. + * @param {string} token - The client token for authentication. + * @param {ExperienceComposerOptions} config - Configuration options for the experience composer rendering. + * @return {Promise} A promise that resolves with information about the started experience composer rendering. + * + * @example + * ```ts + * + * const render = await videoClient.startExperienceComposerRender( + * SESSION_ID, + * token, + * ) + * + * console.log(render.id); + * ``` + */ public async startExperienceComposerRender( sessionId: string, token: string, @@ -431,15 +996,38 @@ export class Video extends Client { return resp.data; } - public async stopArchive( - archiveId: string, - ): Promise { + /** + * Stops an archive with the given archive ID. + * + * @param {string} archiveId - The ID of the archive to stop. + * @return {Promise} A promise that resolves with information about the stopped archive. + * + * @example + * ```ts + * const archive = await videoClient.stopArchive(ARCHIVE_ID); + * + * console.log(archive.status); + * ``` + */ + public async stopArchive(archiveId: string): Promise { const resp = await this.sendPostRequest( `${this.config.videoHost}/v2/project/${this.auth.applicationId}/archive/${archiveId}/stop`, ); return resp.data; } + /** + * Stops a broadcast with the given broadcast ID. + * + * @param {string} broadcastId - The ID of the broadcast to stop. + * @return {Promise} A promise that resolves with information about the stopped broadcast. + * + * @example + * ```ts + * const broadcast = await videoClient.stopBroadcast(BROADCAST_ID); + * console.log(broadcast.status); + * ``` + */ public async stopBroadcast( broadcastId: string, ): Promise { @@ -449,20 +1037,60 @@ export class Video extends Client { return resp.data; } + /** + * Stops an Experience Composer render with the given render ID. + * + * @param {string} renderId - The ID of the Experience Composer render to stop. + * @return {Promise} A promise that resolves when the render is successfully stopped. + * + * @example + * ```ts + * await videoClient.stopExperienceComposerRender(RENDER_ID); + * ``` + */ public async stopExperienceComposerRender(renderId: string): Promise { await this.sendDeleteRequest( `${this.config.videoHost}/v2/project/${this.auth.applicationId}/render/${renderId}`, ); } - public async updateArchiveLayout(archiveId: string, layout: ArchiveLayout) { - const resp = await this.sendPutRequest( + /** + * Updates the layout of an archive with the given archive ID. + * + * @param {string} archiveId - The ID of the archive to update the layout for. + * @param {ArchiveLayout} layout - The new layout configuration to set for the archive. + * @return {Promise} A promise that resolves when the layout is successfully updated. + * + * @example + * ```ts + * await videoClient.updateArchiveLayout( + * ``` + */ + public async updateArchiveLayout( + archiveId: string, + layout: ArchiveLayout, + ): Promise { + await this.sendPutRequest( `${this.config.videoHost}/v2/project/${this.auth.applicationId}/archive/${archiveId}/layout`, layout, ); - return resp.data; } + /** + * Updates the configuration of a broadcast with the given broadcast ID. + * + * @param {BroadcastUpdateConfig} config - The configuration options to update the broadcast. + * @return {Promise} A promise that resolves when the broadcast is successfully updated. + * + * @example + * ```ts + * + * await videoClient.updateBroadcast({ + * broadcastId: BROADCAST_ID, + * hasAudio: true, + * }) + * ``` + */ public async updateBroadcast(config: BroadcastUpdateConfig): Promise { await this.sendPatchRequest( `${this.config.videoHost}/v2/project/${this.auth.applicationId}/broadcast/${config.broadcastId}/streams`, diff --git a/packages/video/package.json b/packages/video/package.json index c42a6c0a..15c33e35 100644 --- a/packages/video/package.json +++ b/packages/video/package.json @@ -1,4 +1,5 @@ { + "$schema": "https://json.schemastore.org/package.json", "name": "@vonage/video", "version": "1.13.0", "description": "Package to interact with the Vonage Video API (Not OpenTok Compatible)", @@ -15,7 +16,16 @@ "url": "git+https://github.com/Vonage/vonage-node-sdk.git" }, "license": "Apache-2.0", - "author": "Chris Tankersley ", + "contributors": [ + { + "name": "Chris Tankersley", + "url": "https://github.com/dragonmantank" + }, + { + "name": "Chuck \"MANCHUCK\" Reeves", + "url": "https://github.com/manchuck" + } + ], "main": "dist/index.js", "types": "dist/index.d.ts", "directories": { @@ -28,7 +38,8 @@ "scripts": { "build": "npm run clean && npm run compile", "clean": "npx shx rm -rf dist tsconfig.tsbuildinfo", - "compile": "npx tsc --build --verbose" + "compile": "npx tsc --build --verbose", + "prepublishOnly": "npm run build" }, "dependencies": { "@vonage/auth": "^1.7.0", @@ -42,6 +53,5 @@ }, "publishConfig": { "directory": "dist" - }, - "gitHead": "328f18e5c8a458cb4d06d7955ec2399a6ce6f5d8" + } } diff --git a/packages/video/tsconfig.json b/packages/video/tsconfig.json index 8a781439..eede6e8e 100644 --- a/packages/video/tsconfig.json +++ b/packages/video/tsconfig.json @@ -1,25 +1,27 @@ { - "extends": "../../tsconfig.json", + "$schema": "https://json.schemastore.org/tsconfig", - "compilerOptions": { - "rootDir": "lib", - "outDir": "dist" - }, + "extends": "../../tsconfig.json", - "exclude": [ - "__tests__", - "jest.config.js", - "dist" - ], + "compilerOptions": { + "rootDir": "lib", + "outDir": "dist" + }, - "references": [ - { "path": "../auth" }, - { "path": "../jwt" }, - { "path": "../server-client" }, - { "path": "../vetch" } - ], + "exclude": [ + "__tests__", + "jest.config.js", + "dist" + ], - "ts-node": { - "esm": true - } + "references": [ + { "path": "../auth" }, + { "path": "../jwt" }, + { "path": "../server-client" }, + { "path": "../vetch" } + ], + + "ts-node": { + "esm": true + } } diff --git a/packages/video/typedoc.json b/packages/video/typedoc.json new file mode 100644 index 00000000..0dfd9e71 --- /dev/null +++ b/packages/video/typedoc.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "extends": ["../../typedoc.base.json"], + "entryPoints": ["lib/index.ts"], + "name": "Vonage Video" +} diff --git a/packages/voice/lib/classes/Endpoint/PhoneEndpoint.ts b/packages/voice/lib/classes/Endpoint/PhoneEndpoint.ts index 6933e2c9..3458efea 100644 --- a/packages/voice/lib/classes/Endpoint/PhoneEndpoint.ts +++ b/packages/voice/lib/classes/Endpoint/PhoneEndpoint.ts @@ -1,20 +1,38 @@ -import { PSTNEndpoint } from '../../types/Endpoint/PSTNEndpoint'; +import { PSTNEndpoint } from '../../types'; import debug from 'debug'; debug('@vonage/voice')( - 'This class is deprecated. Please update to use the appropriate type', + 'This class is deprecated. Please update to use the PSTNEndpoint instead', ); /** - * @deprecated This class is deprecated. Please update to use the - * appropriate type + * Represents a PSTN (Public Switched Telephone Network) endpoint for making phone calls. + * @deprecated This class is deprecated. Please update to use the PSTNEndpoint type instead */ export class PhoneEndpoint implements PSTNEndpoint { + /** + * The type of the endpoint, which is always 'phone'. + */ type: 'phone'; + + /** + * The phone number associated with this PSTN endpoint. + */ number: string; + + /** + * Optional DTMF (Dual-Tone Multi-Frequency) answer to send when the call is answered. + */ dtmfAnswer?: string; + /** + * Create a new PhoneEndpoint instance. + * + * @param {string} phoneNumber - The phone number for the PSTN endpoint. + * @param {string} dtmfAnswer - Optional DTMF answer to send when the call is answered. + */ constructor(phoneNumber: string, dtmfAnswer?: string) { + this.type = 'phone'; this.number = phoneNumber; if (dtmfAnswer) { diff --git a/packages/voice/lib/classes/Endpoint/SIPEndpoint.ts b/packages/voice/lib/classes/Endpoint/SIPEndpoint.ts index 0493ad31..301ff780 100644 --- a/packages/voice/lib/classes/Endpoint/SIPEndpoint.ts +++ b/packages/voice/lib/classes/Endpoint/SIPEndpoint.ts @@ -2,19 +2,42 @@ import { SIPEndpoint as SIPEndpointType } from '../../types/Endpoint/SIPEndpoint import debug from 'debug'; debug('@vonage/voice')( - 'This class is deprecated. Please update to use the appropriate type', + // eslint-disable-next-line max-len + 'This class is deprecated. Please update to use the SIPEndpointType type instead', ); /** - * @deprecated This class is deprecated. Please update to use the - * appropriate type + * Represents a SIP (Session Initiation Protocol) endpoint for making voice calls. + * @deprecated This class is deprecated. Please update to use the SIPEndpointType type instead. */ export class SIPEndpoint implements SIPEndpointType { + /** + * The type of the endpoint, which is always 'sip'. + */ type: 'sip'; + + /** + * The SIP URI associated with this endpoint. + * + * @param {string} uri - The SIP URI for the SIP endpoint. + */ uri: string; + + /** + * Optional custom headers to include in SIP requests. + * + * @param {Array>} headers - Optional custom headers as an array of key-value pairs. + */ headers?: Array>; + /** + * Create a new SIPEndpoint instance. + * + * @param {string} uri - The SIP URI for the SIP endpoint. + * @param {Array>} headers - Optional custom headers as an array of key-value pairs. + */ constructor(uri: string, headers?: Array>) { + this.type = 'sip'; this.uri = uri; if (headers) { diff --git a/packages/voice/lib/classes/Endpoint/VBCEndpoint.ts b/packages/voice/lib/classes/Endpoint/VBCEndpoint.ts index c7866f23..4a5f5c6e 100644 --- a/packages/voice/lib/classes/Endpoint/VBCEndpoint.ts +++ b/packages/voice/lib/classes/Endpoint/VBCEndpoint.ts @@ -2,18 +2,34 @@ import { VBCEndpoint as VBCEndpointType } from '../../types/Endpoint/VBCEndpoint import debug from 'debug'; debug('@vonage/voice')( - 'This class is deprecated. Please update to use the appropriate type', + // eslint-disable-next-line max-len + 'This class is deprecated. Please update to use the VBCEndpointType type instead', ); /** - * @deprecated This class is deprecated. Please update to use the - * appropriate type + * Represents a VBC (Vonage Business Cloud) endpoint for making voice calls. + * @deprecated This class is deprecated. Please update to use the VBCEndpointType type instead. */ export class VBCEndpoint implements VBCEndpointType { + /** + * The type of the endpoint, which is always 'vbc'. + */ type: 'vbc'; + + /** + * The VBC extension associated with this endpoint. + * + * @param {string} extension - The VBC extension for the VBC endpoint. + */ extension: string; + /** + * Create a new VBCEndpoint instance. + * + * @param {string} extension - The VBC extension for the VBC endpoint. + */ constructor(extension: string) { + this.type = 'vbc'; this.extension = extension; } } diff --git a/packages/voice/lib/classes/Endpoint/WebsocketEndpoint.ts b/packages/voice/lib/classes/Endpoint/WebsocketEndpoint.ts index 3c3deb04..1df91b31 100644 --- a/packages/voice/lib/classes/Endpoint/WebsocketEndpoint.ts +++ b/packages/voice/lib/classes/Endpoint/WebsocketEndpoint.ts @@ -1,26 +1,57 @@ -import { WebsocketBitrate } from '../../enums/Endpoint/WebsocketBitrate'; +import { WebsocketBitrate } from '../../enums'; import { WebsocketEndpoint as WebsocketEndpointType } from '../../types/Endpoint/WebsocketEndpoint'; import debug from 'debug'; debug('@vonage/voice')( - 'This class is deprecated. Please update to use the appropriate type', + // eslint-disable-next-line max-len + 'This class is deprecated. Please update to use the WebsocketEndpointType type instead', ); /** - * @deprecated This class is deprecated. Please update to use the - * appropriate type + * Represents a WebSocket endpoint for making voice calls. + * + * @deprecated This class is deprecated. Please update to use the WebsocketEndpointType type instead. */ export class WebsocketEndpoint implements WebsocketEndpointType { + /** + * The type of the endpoint, which is always 'websocket'. + */ type: 'websocket'; + + /** + * The WebSocket URI associated with this endpoint. + * + * @param {string} uri - The WebSocket URI for the WebSocket endpoint. + */ uri: string; + + /** + * The content type or bitrate for WebSocket streaming. + * + * @param {WebsocketBitrate} contentType - The content type or bitrate for WebSocket streaming. + */ contentType: WebsocketBitrate; + + /** + * Optional custom headers to include in WebSocket requests. + * + * @param {Record} headers - Optional custom headers as key-value pairs. + */ headers?: Record; + /** + * Create a new WebsocketEndpoint instance. + * + * @param {string} uri - The WebSocket URI for the WebSocket endpoint. + * @param {WebsocketBitrate} contentType - The content type or bitrate for WebSocket streaming. + * @param {Record} headers - Optional custom headers as key-value pairs. + */ constructor( uri: string, contentType: WebsocketBitrate, headers?: Record, ) { + this.type = 'websocket'; this.uri = uri; this.contentType = contentType; @@ -28,5 +59,4 @@ export class WebsocketEndpoint implements WebsocketEndpointType { this.headers = headers; } } - url: string; } diff --git a/packages/voice/lib/classes/NCCO/Connect.ts b/packages/voice/lib/classes/NCCO/Connect.ts index a2bc1752..2a261338 100644 --- a/packages/voice/lib/classes/NCCO/Connect.ts +++ b/packages/voice/lib/classes/NCCO/Connect.ts @@ -1,23 +1,106 @@ import { NCCOActions } from '../../enums'; -import { ConnectEventType } from '../../enums/NCCO/ConnectEventType'; -import { MachineDetection } from '../../enums/NCCO/MachineDetection'; -import { ConnectAction } from '../../types/NCCO/ConnectAction'; +import { ConnectEventType } from '../../enums'; +import { MachineDetection } from '../../enums'; +import { ConnectAction } from '../../types'; import { Serializable } from '../../ncco'; -import { CallEndpoint } from '../../types/Endpoint/CallEndpoint'; +import { CallEndpoint } from '../../types'; +/** + * Represents a Connect action in the Nexmo Call Control Object (NCCO) for making voice calls. + */ export class Connect implements ConnectAction, Serializable { + /** + * The action type, which is always 'connect'. + */ action: NCCOActions.CONNECT = NCCOActions.CONNECT; + + /** + * An array of CallEndpoint objects representing the endpoints to connect to in the call. + * + * @param {CallEndpoint} endpoint - An array of CallEndpoint objects + * representing the endpoints to connect to in the call. + */ endpoint: CallEndpoint[]; + + /** + * The caller's phone number to display as the caller ID. + * + * @param {string} from - The caller's phone number to display as the caller ID. + */ from?: string; + + /** + * Set to true to use a random phone number as the caller ID from the list of + * numbers assigned to the current application. + * + * @param {boolean} randomFromNumber - Set to true to use a random phone number as the caller ID. + */ randomFromNumber?: boolean; + + /** + * The event type for call progress events sent to the specified event URL. + * + * @param {ConnectEventType} eventType - The event type for call progress events. + */ eventType?: ConnectEventType; + + /** + * The time in seconds that Vonage waits for the call to be answered before timing out. + * + * @param {number} timeout - The timeout value in seconds. + */ timeout?: number; + + /** + * The maximum number of concurrent calls that can be handled by your application. + * + * @param {number} limit - The maximum number of concurrent calls. + */ limit?: number; + + /** + * Configure the behavior when Vonage detects that the call is answered by voicemail. + * + * @param {MachineDetection} machineDetection - The behavior when voicemail is detected. + */ machineDetection?: MachineDetection; + + /** + * An array of event URLs where call progress events are sent to. Multiple URLs can be specified. + * + * @param {string} eventUrl - An array of event URLs. + */ eventUrl?: string[]; + + /** + * The HTTP method used to send event information to the event URL(s). + * + * @param {string} eventMethod - The HTTP method used for event callbacks. + */ eventMethod?: string; + + /** + * The URL of a ringback tone to play to the caller while waiting for the call to be answered. + * + * @param {string} ringbackTone - The URL of the ringback tone audio file. + */ ringbackTone?: string; + /** + * Create a new Connect instance. + * + * @param {CallEndpoint} endpoint - An array of CallEndpoint objects representing the endpoints to connect to in the call. + * @param {string} from - The caller's phone number to display as the caller ID. + * @param {boolean} randomFromNumber - Set to true to use a random phone number as the caller ID. + * @param {ConnectEventType} eventType - The event type for call progress events. + * @param {number} timeout - The timeout value in seconds. + * @param {number} limit - The maximum number of concurrent calls. + * @param {MachineDetection} machineDetection - The behavior when voicemail is detected. + * @param {string} eventUrl - An array of event URLs. + * @param {string} eventMethod - The HTTP method used for event callbacks. + * @param {string} ringbackTone - The URL of the ringback tone audio file. + */ + constructor( endpoint: CallEndpoint, from?: string, @@ -61,6 +144,11 @@ export class Connect implements ConnectAction, Serializable { } } + /** + * Serialize the Connect action to a Nexmo Call Control Object (NCCO) format. + * + * @return {ConnectAction} - The serialized Connect action. + */ serializeToNCCO() { const data: ConnectAction = { action: NCCOActions.CONNECT, diff --git a/packages/voice/lib/classes/NCCO/Conversation.ts b/packages/voice/lib/classes/NCCO/Conversation.ts index b0110389..b57b9572 100644 --- a/packages/voice/lib/classes/NCCO/Conversation.ts +++ b/packages/voice/lib/classes/NCCO/Conversation.ts @@ -2,17 +2,83 @@ import { NCCOActions } from '../../enums'; import { ConversationAction } from '../../interfaces/NCCO/ConversationAction'; import { Serializable } from '../../ncco'; +/** + * Represents a Conversation action in the Nexmo Call Control Object (NCCO) for managing audio conferences. + */ export class Conversation implements ConversationAction, Serializable { + /** + * The action type, which is always 'conversation'. + */ action: NCCOActions.CONVERSATION = NCCOActions.CONVERSATION; + + /** + * The name of the conversation. + * + * @param {string} name - The name of the conversation. + */ name: string; + + /** + * An array of URLs for music to be played while participants are on hold. + * + * @param {string[]} musicOnHoldUrl - An array of music on hold URLs. + */ musicOnHoldUrl?: string[]; + + /** + * Set to true to start the conversation when a participant enters. + * + * @param {boolean} startOnEnter - Set to true to start the conversation on participant enter. + */ startOnEnter?: boolean; + + /** + * Set to true to end the conversation when the last participant exits. + * + * @param {boolean} endOnExit - Set to true to end the conversation on last participant exit. + */ endOnExit?: boolean; + + /** + * Set to true to record the conversation. + * + * @param {boolean} record - Set to true to record the conversation. + */ record?: boolean; + + /** + * An array of participant IDs (e.g., phone numbers) who can speak in the conversation. + * + * @param {string[]} canSpeak - An array of participant IDs who can speak in the conversation. + */ canSpeak?: string[]; + + /** + * An array of participant IDs (e.g., phone numbers) who can hear in the conversation. + * + * @param {string[]} canHear - An array of participant IDs who can hear in the conversation. + */ canHear?: string[]; + + /** + * Set to true to mute all participants in the conversation. + * + * @param {boolean} mute - Set to true to mute all participants in the conversation. + */ mute?: boolean; + /** + * Create a new Conversation instance. + * + * @param {string} name - The name of the conversation. + * @param {string} musicOnHoldUrl - An array of music on hold URLs. + * @param {boolean} startOnEnter - Set to true to start the conversation on participant enter. + * @param {boolean} endOnExit - Set to true to end the conversation on last participant exit. + * @param {boolean} record - Set to true to record the conversation. + * @param {string[]} canSpeak - An array of participant IDs who can speak in the conversation. + * @param {string[]} canHear - An array of participant IDs who can hear in the conversation. + * @param {boolean} mute - Set to true to mute all participants in the conversation. + */ constructor( name: string, musicOnHoldUrl?: string, @@ -48,7 +114,12 @@ export class Conversation implements ConversationAction, Serializable { } } - serializeToNCCO() { + /** + * Serialize the Conversation action to a Nexmo Call Control Object (NCCO) format. + * + * @return {ConversationAction} - The serialized Conversation action. + */ + serializeToNCCO(): ConversationAction { const data: ConversationAction = { action: NCCOActions.CONVERSATION, name: this.name, diff --git a/packages/voice/lib/classes/NCCO/Input.ts b/packages/voice/lib/classes/NCCO/Input.ts index 207000dd..bb454a5f 100644 --- a/packages/voice/lib/classes/NCCO/Input.ts +++ b/packages/voice/lib/classes/NCCO/Input.ts @@ -1,17 +1,51 @@ import { NCCOActions } from '../../enums'; -import { DTMFSettings } from '../../types/NCCO/DTMFSettings'; -import { InputAction } from '../../types/NCCO/InputAction'; -import { SpeechSettings } from '../../types/NCCO/SpeechSettings'; +import { DTMFSettings } from '../../types'; +import { InputAction } from '../../types'; +import { SpeechSettings } from '../../types'; import { Serializable } from '../../ncco'; +/** + * Represents an Input action in the Nexmo Call Control Object (NCCO) for gathering user input. + */ export class Input implements InputAction, Serializable { + /** + * The action type, which is always 'input'. + */ action: NCCOActions.INPUT = NCCOActions.INPUT; + + /** + * An array of input types ('dtmf' and/or 'speech'). + */ type: string[] = []; + + /** + * DTMF input settings. + */ dtmf?: DTMFSettings; + + /** + * Speech input settings. + */ speech?: SpeechSettings; + + /** + * An array of URLs to send events to asynchronously. + */ eventUrl?: string[] = []; + + /** + * The HTTP method used to send events (e.g., 'POST' or 'GET'). + */ eventMethod?: string; + /** + * Create a new Input instance. + * + * @param {DTMFSettings} dtmf - DTMF input settings. + * @param {SpeechSettings} speech - Speech input settings. + * @param {string} eventUrl - URL to send events to asynchronously. + * @param {string} eventMethod - The HTTP method used to send events. + */ constructor( dtmf?: DTMFSettings, speech?: SpeechSettings, @@ -29,8 +63,9 @@ export class Input implements InputAction, Serializable { } if (eventUrl) { - this.eventUrl.push(eventUrl); + this.eventUrl = [ eventUrl ]; } + if (eventMethod) { this.eventMethod = eventMethod; } @@ -42,7 +77,12 @@ export class Input implements InputAction, Serializable { } } - serializeToNCCO() { + /** + * Serialize the Input action to a Nexmo Call Control Object (NCCO) format. + * + * @return {InputAction} - The serialized Input action. + */ + serializeToNCCO(): InputAction { const data: InputAction = { action: NCCOActions.INPUT, type: this.type, diff --git a/packages/voice/lib/classes/NCCO/NCCOBuilder.ts b/packages/voice/lib/classes/NCCO/NCCOBuilder.ts index 1145efe6..e4d7c817 100644 --- a/packages/voice/lib/classes/NCCO/NCCOBuilder.ts +++ b/packages/voice/lib/classes/NCCO/NCCOBuilder.ts @@ -1,17 +1,34 @@ -import { isNCCOSerializable } from '../../interfaces/NCCO/Serializable'; -import { Action } from '../../ncco'; +import { Serializable } from '../../ncco'; +import { NCCOAction } from '../../types'; +/** + * A builder class for creating Nexmo Call Control Objects (NCCOs). + */ export class NCCOBuilder { - protected actions = []; + protected actions: Array = []; - public addAction(action: Action) { - this.actions.push(action); + /** + * Add an action to the NCCO builder. + * + * @param {Action} action - The action to add to the NCCO. + * @return {NCCOBuilder} - The NCCO builder instance (for method chaining). + */ + public addAction(action: NCCOAction): NCCOBuilder { + this.actions.push( + ('serializeToNCCO' in action + ? (action as Serializable).serializeToNCCO() + : action + ) as NCCOAction, + ); return this; } - public build() { - return this.actions.map((action) => - isNCCOSerializable(action) ? action.serializeToNCCO() : action, - ); + /** + * Build the NCCO by serializing the added actions. + * + * @return {Array} - The built NCCO, which is an array of actions. + */ + public build(): Array { + return this.actions; } } diff --git a/packages/voice/lib/classes/NCCO/Notify.ts b/packages/voice/lib/classes/NCCO/Notify.ts index 22a092c5..38d5a05c 100644 --- a/packages/voice/lib/classes/NCCO/Notify.ts +++ b/packages/voice/lib/classes/NCCO/Notify.ts @@ -1,7 +1,10 @@ -import { NotifyAction } from '../../types/NCCO/NotifyAction'; +import { NotifyAction } from '../../types'; import { Serializable } from '../../ncco'; import { NCCOActions } from '../../enums'; +/** + * Represents a Notify action in an NCCO. + */ export class Notify implements NotifyAction, Serializable { action: NCCOActions.NOTIFY = NCCOActions.NOTIFY; payload: { @@ -10,6 +13,13 @@ export class Notify implements NotifyAction, Serializable { eventUrl: string[]; eventMethod?: string; + /** + * Creates a new Notify action. + * + * @param {Object} payload - The payload data to send with the notification. + * @param {string} eventUrl - The URL where the notification events will be sent. + * @param {string} [eventMethod] - The HTTP method for sending notification events (e.g., "POST"). + */ constructor( payload: { [key: string]: string }, eventUrl: string, @@ -23,7 +33,12 @@ export class Notify implements NotifyAction, Serializable { } } - serializeToNCCO() { + /** + * Serialize the Notify action to an NCCO-compatible format. + * + * @return {NotifyAction} - The serialized Notify action. + */ + serializeToNCCO(): NotifyAction { const data: NotifyAction = { action: NCCOActions.NOTIFY, payload: this.payload, diff --git a/packages/voice/lib/classes/NCCO/Record.ts b/packages/voice/lib/classes/NCCO/Record.ts index b5f93e70..1351ad8b 100644 --- a/packages/voice/lib/classes/NCCO/Record.ts +++ b/packages/voice/lib/classes/NCCO/Record.ts @@ -1,19 +1,74 @@ import { NCCOActions } from '../../enums'; -import { RecordingFormat } from '../../enums/NCCO/RecordingFormat'; -import { RecordAction } from '../../types/NCCO/RecordAction'; +import { RecordingFormat } from '../../enums'; +import { RecordAction } from '../../types'; +/** + * Represents a Record action in an NCCO. + */ export class Record implements RecordAction { + /** + * The action type for the Record action. + */ action: NCCOActions.RECORD = NCCOActions.RECORD; + + /** + * The recording format (e.g., "mp3", "wav"). + */ format?: RecordingFormat; + + /** + * The split type for recording (always "conversation"). + */ protected wrappedSplit?: string; + + /** + * The number of audio channels (1 to 32). + */ protected wrappedChannels?: number; + + /** + * The duration of silence (in seconds) to end the recording (3 to 10 seconds). + */ protected wrappedEndOnSilence?: number; + + /** + * The DTMF key that ends the recording (e.g., "0", "*", "#"). + */ protected wrappedEndOnKey?: string; + + /** + * The maximum recording duration in seconds (3 to 7200 seconds). + */ protected wrappedTimeOut?: number; + + /** + * Whether to play a beep before recording starts. + */ beepStart?: boolean; + + /** + * The URL where recording events will be sent. + */ eventUrl?: string[]; + + /** + * The HTTP method for sending recording events (e.g., "POST"). + */ eventMethod?: string; + /** + * Creates a new Record action. + * + * @param {RecordingFormat} format - The recording format (e.g., "mp3", "wav"). + * @param {string} split - The split type for recording (should be "conversation"). + * @param {number} channels - The number of audio channels (1 to 32). + * @param {number} endOnSilence - The duration of silence (in seconds) to end the recording (3 to 10 seconds). + * @param {string} endOnKey - The DTMF key that ends the recording (e.g., "0", "*", "#"). + * @param {number} timeout - The maximum recording duration in seconds (3 to 7200 seconds). + * @param {boolean} beepStart - Whether to play a beep before recording starts. + * @param {string} eventUrl - The URL where recording events will be sent. + * @param {string} eventMethod - The HTTP method for sending recording events (e.g., "POST"). + */ constructor( format?: RecordingFormat, split?: string, @@ -54,10 +109,21 @@ export class Record implements RecordAction { } } - public get channels(): number { + /** + * Getter for the number of audio channels. + * + * @return {number | undefined} - The current number of audio channels. + */ + public get channels(): number | undefined { return this.wrappedChannels; } + /** + * Setter for the number of audio channels. + * + * @param {number} channels - The number of audio channels (1 to 32). + * @throws {Error} - If the channel value is invalid or split is not set to "conversation." + */ public set channels(channels: number) { if (channels < 1 || channels > 32) { throw new Error('Channels must be between 1 and 32, inclusive'); @@ -72,10 +138,21 @@ export class Record implements RecordAction { this.wrappedChannels = channels; } - public get endOnKey(): string { + /** + * Getter for the character that signals the end of recording. + * + * @return {string | undefined} - The character that signals the end of recording. + */ + public get endOnKey(): string | undefined { return this.wrappedEndOnKey; } + /** + * Setter for the DTMF key that ends the recording. + * + * @param {string} character - The DTMF key that ends the recording (e.g., "0", "*", "#"). + * @throws {Error} - If the character is not a valid DTMF key. + */ public set endOnKey(character: string) { const re = /^[0-9*#]$/; if (!re.test(character)) { @@ -85,10 +162,21 @@ export class Record implements RecordAction { this.wrappedEndOnKey = character; } - public get endOnSilence(): number { + /** + * Getter for the duration of silence (in seconds) that signals the end of recording. + * + * @return {number | undefined} - The duration of silence (in seconds) that signals the end of recording. + */ + public get endOnSilence(): number | undefined { return this.wrappedEndOnSilence; } + /** + * Setter for the duration of silence to end the recording. + * + * @param {number} numSeconds - The duration of silence in seconds (3 to 10 seconds). + * @throws {Error} - If the duration value is out of the valid range. + */ public set endOnSilence(numSeconds: number) { if (numSeconds < 3 || numSeconds > 10) { throw new Error( @@ -99,10 +187,21 @@ export class Record implements RecordAction { this.wrappedEndOnSilence = numSeconds; } + /** + * Getter for the recording split type. + * + * @return {string} - The recording split type, which is always 'conversation'. + */ public get split(): 'conversation' { return 'conversation'; } + /** + * Setter for the recording split type. + * + * @param {string} splitType - The recording split type. Must be set to 'conversation'. + * @throws {Error} - Throws an error if the splitType is not 'conversation'. + */ public set split(splitType: string) { if (splitType !== 'conversation') { throw new Error("Recording can only be split to 'conversation'"); @@ -111,10 +210,21 @@ export class Record implements RecordAction { this.wrappedSplit = splitType; } - public get timeout(): number { + /** + * Getter for the recording timeout duration in seconds. + * + * @return {number | undefined } - The recording timeout duration in seconds. + */ + public get timeout(): number | undefined { return this.wrappedTimeOut; } + /** + * Setter for the recording timeout. + * + * @param {number} seconds - The maximum recording duration in seconds (3 to 7200 seconds). + * @throws {Error} - If the timeout value is out of the valid range. + */ public set timeout(seconds: number) { if (seconds < 3 || seconds > 7200) { throw new Error( @@ -125,6 +235,11 @@ export class Record implements RecordAction { this.wrappedTimeOut = seconds; } + /** + * Serializes the Record action to NCCO format. + * + * @return {RecordAction} - The serialized Record action. + */ serializeToNCCO(): RecordAction { const data: RecordAction = { action: NCCOActions.RECORD, diff --git a/packages/voice/lib/classes/NCCO/Stream.ts b/packages/voice/lib/classes/NCCO/Stream.ts index e3805ff6..eabe515f 100644 --- a/packages/voice/lib/classes/NCCO/Stream.ts +++ b/packages/voice/lib/classes/NCCO/Stream.ts @@ -2,13 +2,45 @@ import { NCCOActions } from '../../enums'; import { StreamAction } from '../../interfaces/NCCO/StreamAction'; import { Serializable } from '../../ncco'; +/** + * Represents a Stream action in a Nexmo Call Control Object (NCCO). + * + * This action allows streaming audio into the call. + */ export class Stream implements StreamAction, Serializable { + /** + * The action type for this NCCO action. + */ action: NCCOActions.STREAM = NCCOActions.STREAM; + + /** + * An array of stream URLs to play audio from. + */ streamUrl: string[]; + + /** + * The audio level at which to play the stream (optional). + */ level?: number; + + /** + * Indicates whether the stream should allow barge-in (optional). + */ bargeIn?: boolean; + + /** + * The number of times to loop the audio (optional). + */ loop?: number; + /** + * Creates a new Stream action. + * + * @param {string} streamUrl - The URL of the audio stream. + * @param {number} [level] - The audio level at which to play the stream (optional). + * @param {boolean} [bargeIn] - Indicates whether the stream should allow barge-in (optional). + * @param {number} [loop] - The number of times to loop the audio (optional). + */ constructor( streamUrl: string, level?: number, @@ -28,6 +60,11 @@ export class Stream implements StreamAction, Serializable { } } + /** + * Serializes the Stream action to a Nexmo Call Control Object (NCCO). + * + * @return {StreamAction} - The serialized Stream action. + */ serializeToNCCO() { const data: StreamAction = { action: NCCOActions.STREAM, diff --git a/packages/voice/lib/classes/NCCO/Talk.ts b/packages/voice/lib/classes/NCCO/Talk.ts index 0f42430d..b0b1ee81 100644 --- a/packages/voice/lib/classes/NCCO/Talk.ts +++ b/packages/voice/lib/classes/NCCO/Talk.ts @@ -1,17 +1,64 @@ import { NCCOActions, TTSLanguages } from '../../enums'; -import { TalkAction } from '../../types/NCCO/TalkAction'; +import { TalkAction } from '../../types'; import { Serializable } from '../../ncco'; +/** + * Represents a Talk action in a Nexmo Call Control Object (NCCO). + * + * This action allows the text-to-speech (TTS) synthesis of spoken words in the call. + */ export class Talk implements TalkAction, Serializable { + /** + * The action type for this NCCO action. + */ action: NCCOActions.TALK = NCCOActions.TALK; + + /** + * The text to be spoken during the call. + */ text: string; + + /** + * Indicates whether the talk action allows barge-in (optional). + */ bargeIn?: boolean; + + /** + * The number of times to loop the speech (optional). + */ loop?: number; + + /** + * The audio level at which to play the speech (optional). + */ level?: string; + + /** + * The language for the text-to-speech synthesis (optional). + */ language?: TTSLanguages; + + /** + * The speech style (optional). + */ style?: string; + + /** + * Indicates whether to use premium text-to-speech (optional). + */ premium?: boolean; + /** + * Creates a new Talk action. + * + * @param {string} text - The text to be spoken during the call. + * @param {boolean} [bargeIn] - Indicates whether the talk action allows barge-in (optional). + * @param {number} [loop] - The number of times to loop the speech (optional). + * @param {string} [level] - The audio level at which to play the speech (optional). + * @param {TTSLanguages} [language] - The language for the text-to-speech synthesis (optional). + * @param {string} [style] - The speech style (optional). + * @param {boolean} [premium] - Indicates whether to use premium text-to-speech (optional). + */ constructor( text: string, bargeIn?: boolean, @@ -43,6 +90,11 @@ export class Talk implements TalkAction, Serializable { } } + /** + * Serializes the Talk action to a Nexmo Call Control Object (NCCO). + * + * @return {TalkAction} - The serialized Talk action. + */ serializeToNCCO() { const data: TalkAction = { action: NCCOActions.TALK, diff --git a/packages/voice/lib/classes/OutboundCall.ts b/packages/voice/lib/classes/OutboundCall.ts index 164b0f02..03cddbe7 100644 --- a/packages/voice/lib/classes/OutboundCall.ts +++ b/packages/voice/lib/classes/OutboundCall.ts @@ -1,33 +1,67 @@ import { PhoneEndpointObject } from '../interfaces/Endpoint/PhoneEndpointObject'; -import { CallEndpoint } from '../types/Endpoint/CallEndpoint'; +import { CallEndpoint } from '../types'; import debug from 'debug'; import { HttpMethod, MachineDetectionBehavior } from '../enums'; debug('@vonage/voice')( - 'This class is deprecated. Please update to use the appropriate type', + 'This class is deprecated. Please update to use the CommonOutboundCall type', ); /** - * @deprecated This class is deprecated. Please update to use the - * appropriate type + * Represents an outbound call. + * + * @deprecated This class is deprecated. Please update to use the CommonOutboundCall type */ export abstract class OutboundCall { - to: CallEndpoint[]; - from: PhoneEndpointObject; + /** + * The list of call endpoints to which the outbound call will be made. + */ + to: Array; + + /** + * The phone endpoint object representing the caller's information. + */ + from?: PhoneEndpointObject; + + /** + * Indicates whether to use a random from number (optional). + */ randomFromNumber?: boolean; + + /** + * The list of event URLs (optional). + */ eventUrl?: string[]; + + /** + * The HTTP method to use for event notifications (optional). + */ eventMethod?: HttpMethod; + + /** + * The machine detection behavior (optional). + */ machineDetection?: MachineDetectionBehavior; + + /** + * The length timer for the call (optional). + */ lengthTimer?: number; + + /** + * The ringing timer for the call (optional). + */ ringingTimer?: number; + /** + * Creates a new outbound call. + * + * @param {CallEndpoint} to - The call endpoint to which the outbound call will be made. + * @param {PhoneEndpointObject} [from] - The phone endpoint object representing the caller's information. + */ constructor(to: CallEndpoint, from?: PhoneEndpointObject) { this.to = [to]; - if (from) { - this.from = from; - } else { - this.randomFromNumber = true; - } + this.from = from; } } diff --git a/packages/voice/lib/classes/OutboundCallWithAnswerURL.ts b/packages/voice/lib/classes/OutboundCallWithAnswerURL.ts index d0e2a467..2c9e1a97 100644 --- a/packages/voice/lib/classes/OutboundCallWithAnswerURL.ts +++ b/packages/voice/lib/classes/OutboundCallWithAnswerURL.ts @@ -1,26 +1,40 @@ import { PhoneEndpointObject } from '../interfaces/Endpoint/PhoneEndpointObject'; -import { OutboundCallWithAnswerURL as IOutboundCallWithAnswerURL } from '../interfaces/OutboundCallWithAnswerURL'; -import { CallEndpoint } from '../types/Endpoint/CallEndpoint'; +import { CallEndpoint } from '../types'; import { OutboundCall } from './OutboundCall'; import debug from 'debug'; debug('@vonage/voice')( - 'This class is deprecated. Please update to use the appropriate type', + 'This class is deprecated. Please update to use the CallWithAnswerURL type', ); /** - * @deprecated This class is deprecated. Please update to use the - * appropriate type + * Represents an outbound call with an answer URL. + * + * @deprecated This class is deprecated. Please update to use the CallWithAnswerURL type */ export class OutboundCallWithAnswerURL extends OutboundCall - implements IOutboundCallWithAnswerURL { + /** + * The list of answer URLs. + */ /* tslint:disable-next-line */ answer_url: string[]; + /** + * The list of answer URLs. + * + * @deprecated Use `answer_url` instead. + */ answerUrl: string[]; + /** + * Creates a new outbound call with an answer URL. + * + * @param {string} answerUrl - The answer URL for the call. + * @param {CallEndpoint} to - The call endpoint to which the outbound call will be made. + * @param {PhoneEndpointObject} [from] - The phone endpoint object representing the caller's information. + */ constructor(answerUrl: string, to: CallEndpoint, from?: PhoneEndpointObject) { super(to, from); this.answer_url = [answerUrl]; diff --git a/packages/voice/lib/classes/OutboundCallWithNCCO.ts b/packages/voice/lib/classes/OutboundCallWithNCCO.ts index dc1ba3d8..33be0198 100644 --- a/packages/voice/lib/classes/OutboundCallWithNCCO.ts +++ b/packages/voice/lib/classes/OutboundCallWithNCCO.ts @@ -1,25 +1,37 @@ import { PhoneEndpointObject } from '../interfaces/Endpoint/PhoneEndpointObject'; -import { OutboundCallWithNCCO as IOutboundCallWithNCCO } from '../interfaces/OutboundCallWithNCCO'; -import { Action } from '../ncco'; -import { CallEndpoint } from '../types/Endpoint/CallEndpoint'; +import { CallEndpoint, NCCOAction } from '../types'; import { OutboundCall } from './OutboundCall'; import debug from 'debug'; debug('@vonage/voice')( - 'This class is deprecated. Please update to use the appropriate type', + 'This class is deprecated. Please update to use the CallWithNCCO type', ); /** - * @deprecated This class is deprecated. Please update to use the - * appropriate type + * Represents an outbound call with NCCO (Nexmo Call Control Object). + * + * @deprecated This class is deprecated. Please update to use the CallWithNCCO type */ export class OutboundCallWithNCCO extends OutboundCall - implements IOutboundCallWithNCCO { - public ncco: Action[]; + /** + * The list of NCCO actions. + */ + ncco: Array; - constructor(ncco: Action[], to: CallEndpoint, from?: PhoneEndpointObject) { + /** + * Creates a new outbound call with NCCO. + * + * @param {Array} ncco - The NCCO actions for the call. + * @param {CallEndpoint} to - The call endpoint to which the outbound call will be made. + * @param {PhoneEndpointObject} [from] - The phone endpoint object representing the caller's information. + */ + constructor( + ncco: Array, + to: CallEndpoint, + from?: PhoneEndpointObject, + ) { super(to, from); this.ncco = ncco; } diff --git a/packages/voice/lib/enums/AdvancedMachineDetectionMode.ts b/packages/voice/lib/enums/AdvancedMachineDetectionMode.ts index 12f380bc..de5b7bb3 100644 --- a/packages/voice/lib/enums/AdvancedMachineDetectionMode.ts +++ b/packages/voice/lib/enums/AdvancedMachineDetectionMode.ts @@ -1,4 +1,14 @@ +/** + * Enum representing different modes for advanced machine detection in the Connect NCCO action. + */ export enum AdvancedMachineDetectionMode { + /** + * Detect mode, used for advanced machine detection without beep detection. + */ DETECT = 'detect', + + /** + * Detect beep mode, used for advanced machine detection with beep detection. + */ DETECTBEEP = 'detect_beep', } diff --git a/packages/voice/lib/enums/CallDirection.ts b/packages/voice/lib/enums/CallDirection.ts index 2bd688ff..0fb33e0d 100644 --- a/packages/voice/lib/enums/CallDirection.ts +++ b/packages/voice/lib/enums/CallDirection.ts @@ -1,4 +1,14 @@ +/** + * Enum representing the direction of a call, whether it is outbound or inbound. + */ export enum CallDirection { + /** + * Outbound call direction. + */ OUTBOUND = 'outbound', + + /** + * Inbound call direction. + */ INBOUND = 'inbound', } diff --git a/packages/voice/lib/enums/CallStatus.ts b/packages/voice/lib/enums/CallStatus.ts index 339e1ddd..d99e685b 100644 --- a/packages/voice/lib/enums/CallStatus.ts +++ b/packages/voice/lib/enums/CallStatus.ts @@ -1,13 +1,59 @@ +/** + * Enum representing the status of a call, including its various stages and outcomes. + */ export enum CallStatus { + /** + * The call has started. + */ STARTED = 'started', + + /** + * The call is ringing. + */ RINGING = 'ringing', + + /** + * The call has been answered. + */ ANSWERED = 'answered', + + /** + * The call has been detected as a machine. + */ MACHINE = 'machine', + + /** + * The call has been completed. + */ COMPLETED = 'completed', + + /** + * The call is busy. + */ BUSY = 'busy', + + /** + * The call has been cancelled. + */ CANCELLED = 'cancelled', + + /** + * The call has failed. + */ FAILED = 'failed', + + /** + * The call has been rejected. + */ REJECTED = 'rejected', + + /** + * The call has timed out. + */ TIMEOUT = 'timeout', + + /** + * The call went unanswered. + */ UNANSWERED = 'unanswered', } diff --git a/packages/voice/lib/enums/Endpoint/WebsocketBitrate.ts b/packages/voice/lib/enums/Endpoint/WebsocketBitrate.ts index ad6fe0f8..0e1eef73 100644 --- a/packages/voice/lib/enums/Endpoint/WebsocketBitrate.ts +++ b/packages/voice/lib/enums/Endpoint/WebsocketBitrate.ts @@ -1,4 +1,14 @@ +/** + * Enum representing different bitrate options for audio in a WebSocket configuration. + */ export enum WebsocketBitrate { - RATE_8000 = 'audio/l16;rate=8000', - RATE_16000 = 'audio/l16;rate=16000', + /** + * Audio bitrate at 8000 samples per second. + */ + RATE_8000 = 'audio/l16;rate=8000', + + /** + * Audio bitrate at 16000 samples per second. + */ + RATE_16000 = 'audio/l16;rate=16000', } diff --git a/packages/voice/lib/enums/HttpMethod.ts b/packages/voice/lib/enums/HttpMethod.ts index 5a3bbf6d..4d0fea64 100644 --- a/packages/voice/lib/enums/HttpMethod.ts +++ b/packages/voice/lib/enums/HttpMethod.ts @@ -1,4 +1,14 @@ +/** + * Enum representing HTTP methods used for making web requests. + */ export enum HttpMethod { + /** + * The HTTP GET method, used for retrieving data from a server. + */ GET = 'GET', + + /** + * The HTTP POST method, used for sending data to a server to create or update resources. + */ POST = 'POST', } diff --git a/packages/voice/lib/enums/MachineDetctionBehavior.ts b/packages/voice/lib/enums/MachineDetctionBehavior.ts index 61deacd2..65377f6a 100644 --- a/packages/voice/lib/enums/MachineDetctionBehavior.ts +++ b/packages/voice/lib/enums/MachineDetctionBehavior.ts @@ -1,4 +1,14 @@ +/** + * Enum representing the behavior of machine detection in a call. + */ export enum MachineDetectionBehavior { + /** + * Continue the call even if a machine is detected. + */ CONTINUE = 'continue', + + /** + * Hang up the call if a machine is detected. + */ HANGUP = 'hangup', } diff --git a/packages/voice/lib/enums/NCCO/ConnectEventType.ts b/packages/voice/lib/enums/NCCO/ConnectEventType.ts index 73462e99..a45fdd98 100644 --- a/packages/voice/lib/enums/NCCO/ConnectEventType.ts +++ b/packages/voice/lib/enums/NCCO/ConnectEventType.ts @@ -1,3 +1,9 @@ +/** + * Enum representing different event types for the Connect NCCO action. + */ export enum ConnectEventType { - SYNCHRONOUS = 'synchronous', + /** + * Synchronous event type. + */ + SYNCHRONOUS = 'synchronous', } diff --git a/packages/voice/lib/enums/NCCO/MachineDetection.ts b/packages/voice/lib/enums/NCCO/MachineDetection.ts index 26240267..bfcb3dab 100644 --- a/packages/voice/lib/enums/NCCO/MachineDetection.ts +++ b/packages/voice/lib/enums/NCCO/MachineDetection.ts @@ -1,4 +1,14 @@ +/** + * Enum representing machine detection behavior for the Connect NCCO action. + */ export enum MachineDetection { + /** + * Continue with the call if machine detection is triggered. + */ CONTINUE = 'continue', + + /** + * Hang up the call if machine detection is triggered. + */ HANGUP = 'hangup', } diff --git a/packages/voice/lib/enums/NCCO/RecordingFormat.ts b/packages/voice/lib/enums/NCCO/RecordingFormat.ts index 01e4e4e3..447cf437 100644 --- a/packages/voice/lib/enums/NCCO/RecordingFormat.ts +++ b/packages/voice/lib/enums/NCCO/RecordingFormat.ts @@ -1,5 +1,19 @@ +/** + * Enum representing different recording formats for the Record NCCO action. + */ export enum RecordingFormat { - MP3 = 'mp3', - WAV = 'wav', - OGG = 'ogg', + /** + * MP3 audio format. + */ + MP3 = 'mp3', + + /** + * WAV audio format. + */ + WAV = 'wav', + + /** + * OGG audio format. + */ + OGG = 'ogg', } diff --git a/packages/voice/lib/enums/NCCOActions.ts b/packages/voice/lib/enums/NCCOActions.ts index e56d9d13..9daf539c 100644 --- a/packages/voice/lib/enums/NCCOActions.ts +++ b/packages/voice/lib/enums/NCCOActions.ts @@ -1,9 +1,39 @@ +/** + * Enum representing the available actions in a Nexmo Call Control Object (NCCO). + */ export enum NCCOActions { + /** + * Connect the call to an endpoint or multiple endpoints. + */ CONNECT = 'connect', + + /** + * Start a conversation that can include multiple participants. + */ CONVERSATION = 'conversation', + + /** + * Collect input from the caller, including DTMF tones or speech. + */ INPUT = 'input', + + /** + * Send a notification or message to a specified endpoint. + */ NOTIFY = 'notify', + + /** + * Record the audio of a call. + */ RECORD = 'record', + + /** + * Stream audio to a call. + */ STREAM = 'stream', + + /** + * Play a text-to-speech message to the caller. + */ TALK = 'talk', } diff --git a/packages/voice/lib/enums/TTSLanguages.ts b/packages/voice/lib/enums/TTSLanguages.ts index 1ad3ef4d..19a15a4d 100644 --- a/packages/voice/lib/enums/TTSLanguages.ts +++ b/packages/voice/lib/enums/TTSLanguages.ts @@ -1,48 +1,234 @@ +/** + * Enum representing the supported Text-to-Speech (TTS) languages for Nexmo's voice calls. + */ export enum TTSLanguages { + /** + * Arabic (ar) - Supported Text-to-Speech (TTS) language. + */ AR = 'ar', + + /** + * Catalan (ca-ES) - Supported Text-to-Speech (TTS) language. + */ CA_ES = 'ca-ES', + + /** + * Mandarin Chinese (cmn-CN) - Supported Text-to-Speech (TTS) language. + */ CMN_CN = 'cmn-CN', + + /** + * Mandarin Chinese (cmn-TW) - Supported Text-to-Speech (TTS) language. + */ CMN_TW = 'cmn-TW', + + /** + * Czech (cs-CZ) - Supported Text-to-Speech (TTS) language. + */ CS_CZ = 'cs-CZ', + + /** + * Welsh (cy-GB) - Supported Text-to-Speech (TTS) language. + */ CY_GB = 'cy-GB', + + /** + * Danish (da-DK) - Supported Text-to-Speech (TTS) language. + */ DA_DK = 'da-DK', + + /** + * German (de-DE) - Supported Text-to-Speech (TTS) language. + */ DE_DE = 'de-DE', + + /** + * Greek (el-GR) - Supported Text-to-Speech (TTS) language. + */ EL_GR = 'el-GR', + + /** + * Australian English (en-AU) - Supported Text-to-Speech (TTS) language. + */ EN_AU = 'en-AU', + + /** + * British English (en-GB) - Supported Text-to-Speech (TTS) language. + */ EN_GB = 'en-GB', + + /** + * British English (en-GB-WLS) - Supported Text-to-Speech (TTS) language. + */ EN_GB_WLS = 'en-GB-WLS', + + /** + * Indian English (en-IN) - Supported Text-to-Speech (TTS) language. + */ EN_IN = 'en-IN', + + /** + * US English (en-US) - Supported Text-to-Speech (TTS) language. + */ EN_US = 'en-US', + + /** + * South African English (en-ZA) - Supported Text-to-Speech (TTS) language. + */ EN_ZA = 'en-ZA', + + /** + * Spanish (es-ES) - Supported Text-to-Speech (TTS) language. + */ ES_ES = 'es-ES', + + /** + * Mexican Spanish (es-MX) - Supported Text-to-Speech (TTS) language. + */ ES_MX = 'es-MX', + + /** + * US Spanish (es-US) - Supported Text-to-Speech (TTS) language. + */ ES_US = 'es-US', + + /** + * Basque (eu-ES) - Supported Text-to-Speech (TTS) language. + */ EU_ES = 'eu-ES', + + /** + * Finnish (fi-FI) - Supported Text-to-Speech (TTS) language. + */ FI_FI = 'fi-FI', + + /** + * Filipino (fil-PH) - Supported Text-to-Speech (TTS) language. + */ FIL_PH = 'fil-PH', + + /** + * Canadian French (fr-CA) - Supported Text-to-Speech (TTS) language. + */ FR_CA = 'fr-CA', + + /** + * French (fr-FR) - Supported Text-to-Speech (TTS) language. + */ FR_FR = 'fr-FR', + + /** + * Hebrew (he-IL) - Supported Text-to-Speech (TTS) language. + */ HE_IL = 'he-IL', + + /** + * Hindi (hi-IN) - Supported Text-to-Speech (TTS) language. + */ HI_IN = 'hi-IN', + + /** + * Hungarian (hu-HU) - Supported Text-to-Speech (TTS) language. + */ HU_HU = 'hu-HU', + + /** + * Indonesian (id-ID) - Supported Text-to-Speech (TTS) language. + */ ID_ID = 'id-ID', + + /** + * Icelandic (is-IS) - Supported Text-to-Speech (TTS) language. + */ IS_IS = 'is-IS', + + /** + * Italian (it-IT) - Supported Text-to-Speech (TTS) language. + */ IT_IT = 'it-IT', + + /** + * Japanese (ja-JP) - Supported Text-to-Speech (TTS) language. + */ JA_JP = 'ja-JP', + + /** + * Korean (ko-KR) - Supported Text-to-Speech (TTS) language. + */ KO_KR = 'ko-KR', + + /** + * Norwegian Bokmål (nb-NO) - Supported Text-to-Speech (TTS) language. + */ NB_NO = 'nb-NO', + + /** + * Dutch (nl-NL) - Supported Text-to-Speech (TTS) language. + */ NL_NL = 'nl-NL', + + /** + * Norwegian (no-NO) - Supported Text-to-Speech (TTS) language. + */ NO_NO = 'no-NO', + + /** + * Polish (pl-PL) - Supported Text-to-Speech (TTS) language. + */ PL_PL = 'pl-PL', + + /** + * Brazilian Portuguese (pt-BR) - Supported Text-to-Speech (TTS) language. + */ PT_BR = 'pt-BR', + + /** + * Portuguese (pt-PT) - Supported Text-to-Speech (TTS) language. + */ PT_PT = 'pt-PT', + + /** + * Romanian (ro-RO) - Supported Text-to-Speech (TTS) language. + */ RO_RO = 'ro-RO', + + /** + * Russian (ru-RU) - Supported Text-to-Speech (TTS) language. + */ RU_RU = 'ru-RU', + + /** + * Slovak (sk-SK) - Supported Text-to-Speech (TTS) language. + */ SK_SK = 'sk-SK', + + /** + * Swedish (sv-SE) - Supported Text-to-Speech (TTS) language. + */ SV_SE = 'sv-SE', + + /** + * Thai (th-TH) - Supported Text-to-Speech (TTS) language. + */ TH_TH = 'th-TH', + + /** + * Turkish (tr-TR) - Supported Text-to-Speech (TTS) language. + */ TR_TR = 'tr-TR', + + /** + * Ukrainian (uk-UA) - Supported Text-to-Speech (TTS) language. + */ UK_UA = 'uk-UA', + + /** + * Vietnamese (vi-VN) - Supported Text-to-Speech (TTS) language. + */ VI_VN = 'vi-VN', + + /** + * Cantonese Chinese (yue-CN) - Supported Text-to-Speech (TTS) language. + */ YUE_CN = 'yue-CN', } diff --git a/packages/voice/lib/enums/TTSVoices.ts b/packages/voice/lib/enums/TTSVoices.ts index 520771c8..79c49d6a 100644 --- a/packages/voice/lib/enums/TTSVoices.ts +++ b/packages/voice/lib/enums/TTSVoices.ts @@ -1,98 +1,485 @@ +/** + * Enum representing supported Text-to-Speech (TTS) voices. + */ export enum TTSVoices { + /** + * Aditi - Supported Text-to-Speech (TTS) voice. + */ ADITI = 'Aditi', + + /** + * Agnieszka - Supported Text-to-Speech (TTS) voice. + */ AGNIESZKA = 'Agnieszka', + + /** + * Alva - Supported Text-to-Speech (TTS) voice. + */ ALVA = 'Alva', + + /** + * Amy - Supported Text-to-Speech (TTS) voice. + */ AMY = 'Amy', + + /** + * Astrid - Supported Text-to-Speech (TTS) voice. + */ ASTRID = 'Astrid', + + /** + * Bianca - Supported Text-to-Speech (TTS) voice. + */ BIANCA = 'Bianca', + + /** + * Brian - Supported Text-to-Speech (TTS) voice. + */ BRIAN = 'Brian', + + /** + * Carla - Supported Text-to-Speech (TTS) voice. + */ CARLA = 'Carla', + + /** + * Carmen - Supported Text-to-Speech (TTS) voice. + */ CARMEN = 'Carmen', + + /** + * Carmit - Supported Text-to-Speech (TTS) voice. + */ CARMIT = 'Carmit', + + /** + * Catarina - Supported Text-to-Speech (TTS) voice. + */ CATARINA = 'Catarina', + + /** + * Celine - Supported Text-to-Speech (TTS) voice. + */ CELINE = 'Celine', + + /** + * Cem - Supported Text-to-Speech (TTS) voice. + */ CEM = 'Cem', + + /** + * Chantal - Supported Text-to-Speech (TTS) voice. + */ CHANTAL = 'Chantal', + + /** + * Chipmunk - Supported Text-to-Speech (TTS) voice. + */ CHIPMUNK = 'Chipmunk', + + /** + * Conchita - Supported Text-to-Speech (TTS) voice. + */ CONCHITA = 'Conchita', + + /** + * Cristiano - Supported Text-to-Speech (TTS) voice. + */ CRISTIANO = 'Cristiano', + + /** + * Damayanti - Supported Text-to-Speech (TTS) voice. + */ DAMAYANTI = 'Damayanti', + + /** + * Dora - Supported Text-to-Speech (TTS) voice. + */ DORA = 'Dora', + + /** + * Emma - Supported Text-to-Speech (TTS) voice. + */ EMMA = 'Emma', + + /** + * Empar - Supported Text-to-Speech (TTS) voice. + */ EMPAR = 'Empar', + + /** + * Enrique - Supported Text-to-Speech (TTS) voice. + */ ENRIQUE = 'Enrique', + + /** + * Eric - Supported Text-to-Speech (TTS) voice. + */ ERIC = 'Eric', + + /** + * Ewa - Supported Text-to-Speech (TTS) voice. + */ EWA = 'Ewa', + + /** + * Felipe - Supported Text-to-Speech (TTS) voice. + */ FELIPE = 'Felipe', + + /** + * Filiz - Supported Text-to-Speech (TTS) voice. + */ FILIZ = 'Filiz', + + /** + * Geraint - Supported Text-to-Speech (TTS) voice. + */ GERAINT = 'Geraint', + + /** + * Giorgio - Supported Text-to-Speech (TTS) voice. + */ GIORGIO = 'Giorgio', + + /** + * Gwyneth - Supported Text-to-Speech (TTS) voice. + */ GWYNETH = 'Gwyneth', + + /** + * Hans - Supported Text-to-Speech (TTS) voice. + */ HANS = 'Hans', + + /** + * Henrik - Supported Text-to-Speech (TTS) voice. + */ HENRIK = 'Henrik', + + /** + * Ines - Supported Text-to-Speech (TTS) voice. + */ INES = 'Ines', + + /** + * Ioana - Supported Text-to-Speech (TTS) voice. + */ IOANA = 'Ioana', + + /** + * Iveta - Supported Text-to-Speech (TTS) voice. + */ IVETA = 'Iveta', + + /** + * Ivy - Supported Text-to-Speech (TTS) voice. + */ IVY = 'Ivy', + + /** + * Jacek - Supported Text-to-Speech (TTS) voice. + */ JACEK = 'Jacek', + + /** + * Jan - Supported Text-to-Speech (TTS) voice. + */ JAN = 'Jan', + + /** + * Jennifer - Supported Text-to-Speech (TTS) voice. + */ JENNIFER = 'Jennifer', + + /** + * Joana - Supported Text-to-Speech (TTS) voice. + */ JOANA = 'Joana', + + /** + * Joanna - Supported Text-to-Speech (TTS) voice. + */ JOANNA = 'Joanna', + + /** + * Joey - Supported Text-to-Speech (TTS) voice. + */ JOEY = 'Joey', + + /** + * Jordi - Supported Text-to-Speech (TTS) voice. + */ JORDI = 'Jordi', + + /** + * Justin - Supported Text-to-Speech (TTS) voice. + */ JUSTIN = 'Justin', + + /** + * Kanya - Supported Text-to-Speech (TTS) voice. + */ KANYA = 'Kanya', + + /** + * Karl - Supported Text-to-Speech (TTS) voice. + */ KARL = 'Karl', + + /** + * Kendra - Supported Text-to-Speech (TTS) voice. + */ KENDRA = 'Kendra', + + /** + * Kimberly - Supported Text-to-Speech (TTS) voice. + */ KIMBERLY = 'Kimberly', + + /** + * Laila - Supported Text-to-Speech (TTS) voice. + */ LAILA = 'Laila', + + /** + * Laura - Supported Text-to-Speech (TTS) voice. + */ LAURA = 'Laura', + + /** + * Lea - Supported Text-to-Speech (TTS) voice. + */ LEA = 'Lea', + + /** + * Lekha - Supported Text-to-Speech (TTS) voice. + */ LEKHA = 'Lekha', + + /** + * Liv - Supported Text-to-Speech (TTS) voice. + */ LIV = 'Liv', + + /** + * Lotte - Supported Text-to-Speech (TTS) voice. + */ LOTTE = 'Lotte', + + /** + * Lucia - Supported Text-to-Speech (TTS) voice. + */ LUCIA = 'Lucia', + + /** + * Luciana - Supported Text-to-Speech (TTS) voice. + */ LUCIANA = 'Luciana', + + /** + * Mads - Supported Text-to-Speech (TTS) voice. + */ MADS = 'Mads', + + /** + * Maged - Supported Text-to-Speech (TTS) voice. + */ MAGED = 'Maged', + + /** + * Maja - Supported Text-to-Speech (TTS) voice. + */ MAJA = 'Maja', + + /** + * Mariska - Supported Text-to-Speech (TTS) voice. + */ MARISKA = 'Mariska', + + /** + * Marlene - Supported Text-to-Speech (TTS) voice. + */ MARLENE = 'Marlene', + + /** + * Mathieu - Supported Text-to-Speech (TTS) voice. + */ MATHIEU = 'Mathieu', + + /** + * Matthew - Supported Text-to-Speech (TTS) voice. + */ MATTHEW = 'Matthew', + + /** + * Maxim - Supported Text-to-Speech (TTS) voice. + */ MAXIM = 'Maxim', + + /** + * Mei-Jia - Supported Text-to-Speech (TTS) voice. + */ MEI_JIA = 'Mei-Jia', + + /** + * Melina - Supported Text-to-Speech (TTS) voice. + */ MELINA = 'Melina', + + /** + * Mia - Supported Text-to-Speech (TTS) voice. + */ MIA = 'Mia', + + /** + * Miguel - Supported Text-to-Speech (TTS) voice. + */ MIGUEL = 'Miguel', + + /** + * Miren - Supported Text-to-Speech (TTS) voice. + */ MIREN = 'Miren', + + /** + * Mizuki - Supported Text-to-Speech (TTS) voice. + */ MIZUKI = 'Mizuki', + + /** + * Montserrat - Supported Text-to-Speech (TTS) voice. + */ MONTSERRAT = 'Montserrat', + + /** + * Naja - Supported Text-to-Speech (TTS) voice. + */ NAJA = 'Naja', + + /** + * Nicole - Supported Text-to-Speech (TTS) voice. + */ NICOLE = 'Nicole', + + /** + * Nikos - Supported Text-to-Speech (TTS) voice. + */ NIKOS = 'Nikos', + + /** + * Nora - Supported Text-to-Speech (TTS) voice. + */ NORA = 'Nora', + + /** + * Oskar - Supported Text-to-Speech (TTS) voice. + */ OSKAR = 'Oskar', + + /** + * Penelope - Supported Text-to-Speech (TTS) voice. + */ PENELOPE = 'Penelope', + + /** + * Raveena - Supported Text-to-Speech (TTS) voice. + */ RAVEENA = 'Raveena', + + /** + * Ricardo - Supported Text-to-Speech (TTS) voice. + */ RICARDO = 'Ricardo', + + /** + * Ruben - Supported Text-to-Speech (TTS) voice. + */ RUBEN = 'Ruben', + + /** + * Russell - Supported Text-to-Speech (TTS) voice. + */ RUSSELL = 'Russell', + + /** + * Salli - Supported Text-to-Speech (TTS) voice. + */ SALLI = 'Salli', + + /** + * Satu - Supported Text-to-Speech (TTS) voice. + */ SATU = 'Satu', + + /** + * Seoyeon - Supported Text-to-Speech (TTS) voice. + */ SEOYEON = 'Seoyeon', + + /** + * Sin-Ji - Supported Text-to-Speech (TTS) voice. + */ SIN_JI = 'Sin-Ji', + + /** + * Sora - Supported Text-to-Speech (TTS) voice. + */ SORA = 'Sora', + + /** + * Takumi - Supported Text-to-Speech (TTS) voice. + */ TAKUMI = 'Takumi', + + /** + * Tarik - Supported Text-to-Speech (TTS) voice. + */ TARIK = 'Tarik', + + /** + * Tatyana - Supported Text-to-Speech (TTS) voice. + */ TATYANA = 'Tatyana', + + /** + * Tessa - Supported Text-to-Speech (TTS) voice. + */ TESSA = 'Tessa', + + /** + * Tian-Tian - Supported Text-to-Speech (TTS) voice. + */ TIAN_TIAN = 'Tian-Tian', + + /** + * Vicki - Supported Text-to-Speech (TTS) voice. + */ VICKI = 'Vicki', + + /** + * Vitoria - Supported Text-to-Speech (TTS) voice. + */ VITORIA = 'Vitoria', + + /** + * Yelda - Supported Text-to-Speech (TTS) voice. + */ YELDA = 'Yelda', + + /** + * Zeina - Supported Text-to-Speech (TTS) voice. + */ ZEINA = 'Zeina', + + /** + * Zhiyu - Supported Text-to-Speech (TTS) voice. + */ ZHIYU = 'Zhiyu', + + /** + * Zuzana - Supported Text-to-Speech (TTS) voice. + */ ZUZANA = 'Zuzana', + } diff --git a/packages/voice/lib/interfaces/Endpoint/CallEndpointObject.ts b/packages/voice/lib/interfaces/Endpoint/CallEndpointObject.ts index 878964e5..15a6c3a1 100644 --- a/packages/voice/lib/interfaces/Endpoint/CallEndpointObject.ts +++ b/packages/voice/lib/interfaces/Endpoint/CallEndpointObject.ts @@ -1,12 +1,11 @@ -import { CallEndpoint } from '../../types/index'; +import { CallEndpoint } from '../../types'; import debug from 'debug'; debug('@vonage/voice')( - 'This interface is deprecated. Please update to use the appropriate type', + 'This interface is deprecated. Please update to use the CallEndpoint type', ); /** - * @deprecated This interface is deprecated. Please update to use the - * appropriate type + * @deprecated This interface is deprecated. Please update to use the CallEndpoint type */ export type CallEndpointObject = CallEndpoint; diff --git a/packages/voice/lib/interfaces/Endpoint/Headers.ts b/packages/voice/lib/interfaces/Endpoint/Headers.ts index d484f9d6..bfd05df0 100644 --- a/packages/voice/lib/interfaces/Endpoint/Headers.ts +++ b/packages/voice/lib/interfaces/Endpoint/Headers.ts @@ -1,11 +1,4 @@ -import debug from 'debug'; - -debug('@vonage/voice')( - 'This interface is deprecated. Please update to use the appropriate type', -); - /** - * @deprecated This interface is deprecated. Please update to use the - * appropriate type + * Headers for the endpoints */ export type Headers = Record; diff --git a/packages/voice/lib/interfaces/Endpoint/PhoneEndpointObject.ts b/packages/voice/lib/interfaces/Endpoint/PhoneEndpointObject.ts index b5036c77..b0b302f1 100644 --- a/packages/voice/lib/interfaces/Endpoint/PhoneEndpointObject.ts +++ b/packages/voice/lib/interfaces/Endpoint/PhoneEndpointObject.ts @@ -1,12 +1,11 @@ -import { PhoneEndpoint } from '../../types/index'; +import { PhoneEndpoint } from '../../types'; import debug from 'debug'; debug('@vonage/voice')( - 'This interface is deprecated. Please update to use the appropriate type', + 'This interface is deprecated. Please update to use the PhoneEndpoint type', ); /** - * @deprecated This interface is deprecated. Please update to use the - * appropriate type + * @deprecated This interface is deprecated. Please update to use the PhoneEndpoint type */ export type PhoneEndpointObject = PhoneEndpoint; diff --git a/packages/voice/lib/interfaces/Endpoint/SIPEndpointObject.ts b/packages/voice/lib/interfaces/Endpoint/SIPEndpointObject.ts index 5b6fe5a8..6c743a69 100644 --- a/packages/voice/lib/interfaces/Endpoint/SIPEndpointObject.ts +++ b/packages/voice/lib/interfaces/Endpoint/SIPEndpointObject.ts @@ -1,12 +1,11 @@ -import { SIPEndpoint } from '../../types/index'; +import { SIPEndpoint } from '../../types'; import debug from 'debug'; debug('@vonage/voice')( - 'This interface is deprecated. Please update to use the appropriate type', + 'This interface is deprecated. Please update to use the SIPEndpoint type', ); /** - * @deprecated This interface is deprecated. Please update to use the - * appropriate type + * @deprecated This interface is deprecated. Please update to use the SIPEndpoint type */ export type SIPEndpointObject = SIPEndpoint; diff --git a/packages/voice/lib/interfaces/Endpoint/VBCEndpointObject.ts b/packages/voice/lib/interfaces/Endpoint/VBCEndpointObject.ts index f7d2f4ab..3c99a353 100644 --- a/packages/voice/lib/interfaces/Endpoint/VBCEndpointObject.ts +++ b/packages/voice/lib/interfaces/Endpoint/VBCEndpointObject.ts @@ -1,12 +1,11 @@ -import { VBCEndpoint } from '../../types/index'; +import { VBCEndpoint } from '../../types'; import debug from 'debug'; debug('@vonage/voice')( - 'This interface is deprecated. Please update to use the appropriate type', + 'This interface is deprecated. Please update to use the VBCEndpoint type', ); /** - * @deprecated This interface is deprecated. Please update to use the - * appropriate type + * @deprecated This interface is deprecated. Please update to use the VBCEndpoint type */ export type VBCEndpointObject = VBCEndpoint; diff --git a/packages/voice/lib/interfaces/Endpoint/WebsocketEndpointObject.ts b/packages/voice/lib/interfaces/Endpoint/WebsocketEndpointObject.ts index c1058562..ae1ba73d 100644 --- a/packages/voice/lib/interfaces/Endpoint/WebsocketEndpointObject.ts +++ b/packages/voice/lib/interfaces/Endpoint/WebsocketEndpointObject.ts @@ -1,12 +1,12 @@ -import { WebsocketEndpoint } from '../../types/index'; +import { WebsocketEndpoint } from '../../types'; import debug from 'debug'; debug('@vonage/voice')( - 'This interface is deprecated. Please update to use the appropriate type', + // eslint-disable-next-line max-len + 'This interface is deprecated. Please update to use the WebsocketEndpoint type', ); /** - * @deprecated This interface is deprecated. Please update to use the - * appropriate type + * @deprecated This interface is deprecated. Please update to use the WebsocketEndpoint type */ export type WebsocketEndpointObject = WebsocketEndpoint; diff --git a/packages/voice/lib/interfaces/NCCO/ConnectAction.ts b/packages/voice/lib/interfaces/NCCO/ConnectAction.ts index e5f04942..d98b66b8 100644 --- a/packages/voice/lib/interfaces/NCCO/ConnectAction.ts +++ b/packages/voice/lib/interfaces/NCCO/ConnectAction.ts @@ -2,11 +2,11 @@ import { ConnectAction as ConnectActionType } from '../../types/index'; import debug from 'debug'; debug('@vonage/voice')( - 'This interface is deprecated. Please update to use the appropriate type', + // eslint-disable-next-line max-len + 'This interface is deprecated. Please update to use the ConnectActionType type', ); /** - * @deprecated This interface is deprecated. Please update to use the - * appropriate type + * @deprecated This interface is deprecated. Please update to use the ConnectActionType type */ export type ConnectAction = ConnectActionType; diff --git a/packages/voice/lib/interfaces/NCCO/ConversationAction.ts b/packages/voice/lib/interfaces/NCCO/ConversationAction.ts index 3b416ba4..db6b7000 100644 --- a/packages/voice/lib/interfaces/NCCO/ConversationAction.ts +++ b/packages/voice/lib/interfaces/NCCO/ConversationAction.ts @@ -2,11 +2,11 @@ import { ConversationAction as ConnectionActionType } from '../../types/index'; import debug from 'debug'; debug('@vonage/voice')( - 'This interface is deprecated. Please update to use the appropriate type', + // eslint-disable-next-line max-len + 'This interface is deprecated. Please update to use the ConnectionActionType type', ); /** - * @deprecated This interface is deprecated. Please update to use the - * appropriate type + * @deprecated This interface is deprecated. Please update to use the ConnectionActionType type */ export type ConversationAction = ConnectionActionType; diff --git a/packages/voice/lib/interfaces/NCCO/DTMFSettings.ts b/packages/voice/lib/interfaces/NCCO/DTMFSettings.ts index 15c28613..4285490f 100644 --- a/packages/voice/lib/interfaces/NCCO/DTMFSettings.ts +++ b/packages/voice/lib/interfaces/NCCO/DTMFSettings.ts @@ -2,11 +2,11 @@ import { DTMFSettings as DTMFSettingsType } from '../../types/index'; import debug from 'debug'; debug('@vonage/voice')( - 'This interface is deprecated. Please update to use the appropriate type', + // eslint-disable-next-line max-len + 'This interface is deprecated. Please update to use the DTMFSettingsType type', ); /** - * @deprecated This interface is deprecated. Please update to use the - * appropriate type + * @deprecated This interface is deprecated. Please update to use the DTMFSettingsType type */ export type DTMFSettings = DTMFSettingsType; diff --git a/packages/voice/lib/interfaces/NCCO/InputAction.ts b/packages/voice/lib/interfaces/NCCO/InputAction.ts index c2c78a9a..9eed1e70 100644 --- a/packages/voice/lib/interfaces/NCCO/InputAction.ts +++ b/packages/voice/lib/interfaces/NCCO/InputAction.ts @@ -2,11 +2,10 @@ import { InputAction as InputActionType } from '../../types/index'; import debug from 'debug'; debug('@vonage/voice')( - 'This interface is deprecated. Please update to use the appropriate type', + 'This interface is deprecated. Please update to use the InputActionType type', ); /** - * @deprecated This interface is deprecated. Please update to use the - * appropriate type + * @deprecated This interface is deprecated. Please update to use the InputActionType type */ export type InputAction = InputActionType; diff --git a/packages/voice/lib/interfaces/NCCO/NotifyAction.ts b/packages/voice/lib/interfaces/NCCO/NotifyAction.ts index a27add8d..8b0f8dfd 100644 --- a/packages/voice/lib/interfaces/NCCO/NotifyAction.ts +++ b/packages/voice/lib/interfaces/NCCO/NotifyAction.ts @@ -2,11 +2,11 @@ import { NotifyAction as NotifyActionType } from '../../types/index'; import debug from 'debug'; debug('@vonage/voice')( - 'This interface is deprecated. Please update to use the appropriate type', + // eslint-disable-next-line max-len + 'This interface is deprecated. Please update to use the NotifyActionType type', ); /** - * @deprecated This interface is deprecated. Please update to use the - * appropriate type + * @deprecated This interface is deprecated. Please update to use the NotifyActionType type */ export type NotifyAction = NotifyActionType; diff --git a/packages/voice/lib/interfaces/NCCO/RecordAction.ts b/packages/voice/lib/interfaces/NCCO/RecordAction.ts index 438d3c7b..08e86df0 100644 --- a/packages/voice/lib/interfaces/NCCO/RecordAction.ts +++ b/packages/voice/lib/interfaces/NCCO/RecordAction.ts @@ -2,11 +2,11 @@ import { RecordAction as RecordActionType } from '../../types/index'; import debug from 'debug'; debug('@vonage/voice')( - 'This interface is deprecated. Please update to use the appropriate type', + // eslint-disable-next-line max-len + 'This interface is deprecated. Please update to use the RecordActionType type', ); /** - * @deprecated This interface is deprecated. Please update to use the - * appropriate type + * @deprecated This interface is deprecated. Please update to use the RecordActionType type */ export type RecordAction = RecordActionType; diff --git a/packages/voice/lib/interfaces/NCCO/Serializable.ts b/packages/voice/lib/interfaces/NCCO/Serializable.ts index 0d5df71a..5ea0add9 100644 --- a/packages/voice/lib/interfaces/NCCO/Serializable.ts +++ b/packages/voice/lib/interfaces/NCCO/Serializable.ts @@ -1,13 +1,23 @@ -import debug from 'debug'; - -debug('@vonage/voice')( - 'This interface is deprecated. Please update to use the appropriate type', -); - -export function isNCCOSerializable(nccoObject): boolean { +/** + * Checks if an object is serializable to Nexmo Call Control Objects (NCCO). + * + * @deprecated not needed anymore + * + * @param {Serializable} nccoObject - The object to check for serializability. + * @return {boolean} `true` if the object is serializable, otherwise `false`. + */ +export function isNCCOSerializable(nccoObject: object): boolean { return 'serializeToNCCO' in nccoObject; } +/** + * Interface for objects that can be serialized to Nexmo Call Control Objects (NCCO). + */ export interface Serializable { - serializeToNCCO(); + /** + * Serialize the object to Nexmo Call Control Objects (NCCO) format. + * + * @returns The NCCO representation of the object. + */ + serializeToNCCO(): Record; } diff --git a/packages/voice/lib/interfaces/NCCO/SpeechSettings.ts b/packages/voice/lib/interfaces/NCCO/SpeechSettings.ts index 8690c0dd..92500621 100644 --- a/packages/voice/lib/interfaces/NCCO/SpeechSettings.ts +++ b/packages/voice/lib/interfaces/NCCO/SpeechSettings.ts @@ -2,11 +2,11 @@ import { SpeechSettings as SpeechSettingsType } from '../../types/index'; import debug from 'debug'; debug('@vonage/voice')( - 'This interface is deprecated. Please update to use the appropriate type', + // eslint-disable-next-line max-len + 'This interface is deprecated. Please update to use the SpeechSettingsType type', ); /** - * @deprecated This interface is deprecated. Please update to use the - * appropriate type + * @deprecated This interface is deprecated. Please update to use the SpeechSettingsType type */ export type SpeechSettings = SpeechSettingsType; diff --git a/packages/voice/lib/interfaces/NCCO/StreamAction.ts b/packages/voice/lib/interfaces/NCCO/StreamAction.ts index 151ca496..69d22a7f 100644 --- a/packages/voice/lib/interfaces/NCCO/StreamAction.ts +++ b/packages/voice/lib/interfaces/NCCO/StreamAction.ts @@ -2,11 +2,11 @@ import { StreamAction as StreamActionType } from '../../types/index'; import debug from 'debug'; debug('@vonage/voice')( - 'This interface is deprecated. Please update to use the appropriate type', + // eslint-disable-next-line max-len + 'This interface is deprecated. Please update to use the StreamActionType type', ); /** - * @deprecated This interface is deprecated. Please update to use the - * appropriate type + * @deprecated This interface is deprecated. Please update to use the StreamActionType type */ export type StreamAction = StreamActionType; diff --git a/packages/voice/lib/interfaces/NCCO/TalkAction.ts b/packages/voice/lib/interfaces/NCCO/TalkAction.ts index 2e9006aa..1576bd53 100644 --- a/packages/voice/lib/interfaces/NCCO/TalkAction.ts +++ b/packages/voice/lib/interfaces/NCCO/TalkAction.ts @@ -2,11 +2,10 @@ import { TalkAction as TalkActionType } from '../../types/index'; import debug from 'debug'; debug('@vonage/voice')( - 'This interface is deprecated. Please update to use the appropriate type', + 'This interface is deprecated. Please update to use the TalkActionType type', ); /** - * @deprecated This interface is deprecated. Please update to use the - * appropriate type + * @deprecated This interface is deprecated. Please update to use the TalkActionType type */ export type TalkAction = TalkActionType; diff --git a/packages/voice/lib/interfaces/NCCO/Transfer.ts b/packages/voice/lib/interfaces/NCCO/Transfer.ts index 36a241af..26a283b7 100644 --- a/packages/voice/lib/interfaces/NCCO/Transfer.ts +++ b/packages/voice/lib/interfaces/NCCO/Transfer.ts @@ -1,22 +1,51 @@ import { Action } from '../../ncco'; -import debug from 'debug'; - -debug('@vonage/voice')( - 'This interface is deprecated. Please update to use the appropriate type', -); +/** + * Represents a Nexmo Call Control Object (NCCO) transfer action. + */ export interface NCCOTransfer { + /** + * The action type, which is 'transfer'. + */ action: string; + + /** + * The destination of the transfer, including the type and NCCO actions. + */ destination: { + /** + * The type of destination, which is 'ncco'. + */ type: string; + + /** + * The NCCO actions to be executed at the destination. + */ ncco: Action[]; }; } +/** + * Represents a Nexmo Call Control Object (NCCO) URL transfer action. + */ export interface URLTransfer { + /** + * The action type, which is 'transfer'. + */ action: string; + + /** + * The destination of the transfer, including the type and URL. + */ destination: { + /** + * The type of destination, which is 'url'. + */ type: string; + + /** + * The URL to which the call will be transferred. + */ url: string[]; }; } diff --git a/packages/voice/lib/interfaces/OutboundCall.ts b/packages/voice/lib/interfaces/OutboundCall.ts index 1de7fb44..c3179f51 100644 --- a/packages/voice/lib/interfaces/OutboundCall.ts +++ b/packages/voice/lib/interfaces/OutboundCall.ts @@ -1,22 +1,54 @@ -import { CallEndpoint } from '../types/Endpoint/CallEndpoint'; +import { CallEndpoint } from '../types'; import { PhoneEndpointObject } from './Endpoint/PhoneEndpointObject'; import debug from 'debug'; debug('@vonage/voice')( - 'This interface is deprecated. Please update to use the appropriate type', + 'This interface is deprecated. Please update to use the OutboundCall type', ); /** - * @deprecated This interface is deprecated. Please update to use the - * appropriate type + * Represents an outbound call configuration. + * @deprecated This interface is deprecated. Please update to use the OutboundCall type. */ export interface OutboundCall { + /** + * The call's destination(s). + */ to: CallEndpoint[]; + + /** + * The caller's phone number or endpoint. + */ from?: PhoneEndpointObject; + + /** + * Indicates whether to use a random caller's phone number. + */ randomFromNumber?: boolean; + + /** + * URLs to receive call events. + */ eventUrl?: string[]; + + /** + * The HTTP method used to send events to the event URLs. + */ eventMethod?: string; + + /** + * Whether machine detection should be enabled for the call. + * @deprecated Machine detection behavior should be set separately using `machineDetection` property. + */ machineDetection?: boolean; + + /** + * The length of time to wait for a call answer, in seconds. + */ lengthTimer?: number; + + /** + * The length of time to ring before assuming a no-answer, in seconds. + */ ringingTimer?: number; } diff --git a/packages/voice/lib/interfaces/OutboundCallWithAnswerURL.ts b/packages/voice/lib/interfaces/OutboundCallWithAnswerURL.ts index fa4f3c01..6150dae7 100644 --- a/packages/voice/lib/interfaces/OutboundCallWithAnswerURL.ts +++ b/packages/voice/lib/interfaces/OutboundCallWithAnswerURL.ts @@ -1,12 +1,12 @@ import debug from 'debug'; -import { CallWithAnswerURL } from '../types/index'; +import { CallWithAnswerURL } from '../types'; debug('@vonage/voice')( - 'This interface is deprecated. Please update to use the appropriate type', + // eslint-disable-next-line max-len + 'This interface is deprecated. Please update to use the CallWithAnswerURL type', ); /** - * @deprecated This interface is deprecated. Please update to use the - * appropriate type + * @deprecated This interface is deprecated. Please update to use the CallWithAnswerURL type */ export type OutboundCallWithAnswerURL = CallWithAnswerURL; diff --git a/packages/voice/lib/interfaces/OutboundCallWithNCCO.ts b/packages/voice/lib/interfaces/OutboundCallWithNCCO.ts index adb47999..c5b4a44e 100644 --- a/packages/voice/lib/interfaces/OutboundCallWithNCCO.ts +++ b/packages/voice/lib/interfaces/OutboundCallWithNCCO.ts @@ -1,12 +1,11 @@ -import { CallWithNCCO } from '../types/index'; +import { CallWithNCCO } from '../types'; import debug from 'debug'; debug('@vonage/voice')( - 'This interface is deprecated. Please update to use the appropriate type', + 'This interface is deprecated. Please update to use the CallWithNCCO type', ); /** - * @deprecated This interface is deprecated. Please update to use the - * appropriate type + * @deprecated This interface is deprecated. Please update to use the CallWithNCCO type */ export type OutboundCallWithNCCO = CallWithNCCO; diff --git a/packages/voice/lib/types.ts b/packages/voice/lib/types.ts deleted file mode 100644 index 6013df4a..00000000 --- a/packages/voice/lib/types.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { VetchResponse } from '@vonage/vetch'; -import { VoiceClassParameters as VoiceClassParametersType } from './types/Parameters/VoiceClassParameters'; -import { CallDetailResponse as CallDetailResponseType } from './types/Responses'; -import { - CallPageResponse, - CreateCallResponse, - UpdateCallResponse, -} from './types/Responses'; -import { GetCallDetailsParameters } from './types/Parameters/GetCallsDetailsParameters'; -import debug from 'debug'; - -debug('@vonage/voice')( - 'This file is deprecated please update to use the core package', -); - -export type VoiceResponse = VetchResponse; - -export type VoiceClassParameters = VoiceClassParametersType; - -export type CallDetailResponse = CallDetailResponseType; - -export type CallListResponse = CallPageResponse; - -/** - * @deprecated Pelease use GetCallDetailsParameters instead - */ -export type CallListFilter = { - date_start?: string; - date_end?: string; - page_size?: string; - record_index?: string; - conversation_uuid?: string; -} & GetCallDetailsParameters; - -export type CallCreateResponse = CreateCallResponse; - -export type CallModifyResponse = UpdateCallResponse; diff --git a/packages/voice/lib/types/AdvancedMachineDetection.ts b/packages/voice/lib/types/AdvancedMachineDetection.ts index 125e5228..b5bb977d 100644 --- a/packages/voice/lib/types/AdvancedMachineDetection.ts +++ b/packages/voice/lib/types/AdvancedMachineDetection.ts @@ -1,10 +1,26 @@ import { MachineDetectionBehavior, AdvancedMachineDetectionMode, -} from '../enums/index'; +} from '../enums'; +/** + * Represents advanced settings for machine detection during a call, including + * behavior, mode, and optional beep timeout. + */ export type AdvancedMachineDetection = { + /** + * The behavior to follow when machine detection occurs. + */ behavior: MachineDetectionBehavior; + + /** + * The mode of advanced machine detection. + */ mode: AdvancedMachineDetectionMode; + + /** + * (Optional) The timeout duration (in seconds) for detecting a beep during + * machine detection. + */ beepTimeout?: number; }; diff --git a/packages/voice/lib/types/BasicCallDetail.ts b/packages/voice/lib/types/BasicCallDetail.ts index 70ecc22d..ad37c132 100644 --- a/packages/voice/lib/types/BasicCallDetail.ts +++ b/packages/voice/lib/types/BasicCallDetail.ts @@ -1,8 +1,26 @@ import { CallStatus } from '../enums'; +/** + * Represents basic details of a call, including its UUID, conversation UUID, duration, and status. + */ export type BasicCallDetail = { + /** + * The UUID of the call. + */ uuid: string; + + /** + * The UUID of the conversation associated with the call. + */ conversationUUID: string; + + /** + * The duration of the call in a string format. + */ duration: string; + + /** + * The status of the call, indicating its current state. + */ status: CallStatus; }; diff --git a/packages/voice/lib/types/CallDetail.ts b/packages/voice/lib/types/CallDetail.ts index 62925001..84e27f3a 100644 --- a/packages/voice/lib/types/CallDetail.ts +++ b/packages/voice/lib/types/CallDetail.ts @@ -1,13 +1,39 @@ import { BasicCallDetail } from './BasicCallDetail'; import { CommonCallFields } from './CommonCallFields'; -import { CallDirection } from '../enums/index'; - -export type CallDetail = CommonCallFields & - BasicCallDetail & { - direction: CallDirection; - rate: string; - price: string; - startTime: string; - endTime: string; - network: string; - }; +import { CallDirection } from '../enums'; + +/** + * Represents detailed information about a call, including common call fields, call direction, rate, price, start time, + * end time, and network information. + */ +export type CallDetail = CommonCallFields & BasicCallDetail & { + /** + * The direction of the call, indicating whether it is inbound or outbound. + */ + direction: CallDirection; + + /** + * The rate associated with the call in a string format. + */ + rate: string; + + /** + * The price of the call in a string format. + */ + price: string; + + /** + * The start time of the call in a string format. + */ + startTime: string; + + /** + * The end time of the call in a string format. + */ + endTime: string; + + /** + * The network information related to the call. + */ + network: string; +}; diff --git a/packages/voice/lib/types/CallResult.ts b/packages/voice/lib/types/CallResult.ts index 63cbc0b0..e2e0ccd4 100644 --- a/packages/voice/lib/types/CallResult.ts +++ b/packages/voice/lib/types/CallResult.ts @@ -1,8 +1,26 @@ import { CallStatus } from '../enums'; +/** + * Represents the result of a call, including the UUID, status, direction (inbound or outbound), and conversation UUID. + */ export type CallResult = { + /** + * The universally unique identifier (UUID) associated with the call. + */ uuid: string; + + /** + * The status of the call, indicating its current state or outcome. + */ status: CallStatus; + + /** + * The direction of the call, specifying whether it is inbound or outbound. + */ direction: 'inbound' | 'outbound'; + + /** + * The UUID associated with the conversation related to the call. + */ conversationUUID: string; }; diff --git a/packages/voice/lib/types/CallUpdateResult.ts b/packages/voice/lib/types/CallUpdateResult.ts index 7905a38b..dcea7277 100644 --- a/packages/voice/lib/types/CallUpdateResult.ts +++ b/packages/voice/lib/types/CallUpdateResult.ts @@ -1,4 +1,14 @@ +/** + * Represents the result of updating a call, including the UUID and a message describing the update. + */ export type CallUpdateResult = { + /** + * The universally unique identifier (UUID) associated with the call. + */ uuid: string; + + /** + * A message describing the update or the result of the call update operation. + */ message: string; }; diff --git a/packages/voice/lib/types/CallWithAnswerURL.ts b/packages/voice/lib/types/CallWithAnswerURL.ts index 17768f27..614ae52c 100644 --- a/packages/voice/lib/types/CallWithAnswerURL.ts +++ b/packages/voice/lib/types/CallWithAnswerURL.ts @@ -1,7 +1,17 @@ import { CommonOutboundCall } from './CommonOutboundCall'; -import { HttpMethod } from '../enums/index'; +import { HttpMethod } from '../enums'; +/** + * Represents an outbound call with an answer URL, including common call properties and the answer URL information. + */ export type CallWithAnswerURL = CommonOutboundCall & { + /** + * The URL(s) to which call events should be sent when the call is answered. + */ answerUrl: string[]; + + /** + * The HTTP method used to send events to the answer URL(s), typically "GET" or "POST." + */ answerMethod?: HttpMethod; }; diff --git a/packages/voice/lib/types/CallWithNCCO.ts b/packages/voice/lib/types/CallWithNCCO.ts index ef80392d..1153a4c5 100644 --- a/packages/voice/lib/types/CallWithNCCO.ts +++ b/packages/voice/lib/types/CallWithNCCO.ts @@ -1,6 +1,12 @@ import { NCCOAction } from './NCCO'; import { CommonOutboundCall } from './CommonOutboundCall'; +/** + * Represents an outbound call with associated Nexmo Call Control Objects (NCCO) actions. + */ export type CallWithNCCO = CommonOutboundCall & { + /** + * An array of NCCO actions to be executed during the call. + */ ncco: Array; }; diff --git a/packages/voice/lib/types/CommonCallFields.ts b/packages/voice/lib/types/CommonCallFields.ts index 24d6d622..d67922b9 100644 --- a/packages/voice/lib/types/CommonCallFields.ts +++ b/packages/voice/lib/types/CommonCallFields.ts @@ -1,6 +1,16 @@ import { CallEndpoint, PSTNEndpoint } from './Endpoint'; +/** + * Represents common fields for defining an outbound call, including the caller (from) and recipient (to) endpoints. + */ export type CommonCallFields = { + /** + * The caller's endpoint information, excluding DTMF answer details. + */ from: Omit; + + /** + * The recipient's endpoint information for the call. + */ to: CallEndpoint; }; diff --git a/packages/voice/lib/types/CommonOutboundCall.ts b/packages/voice/lib/types/CommonOutboundCall.ts index 1386bc6b..2c9640dd 100644 --- a/packages/voice/lib/types/CommonOutboundCall.ts +++ b/packages/voice/lib/types/CommonOutboundCall.ts @@ -1,14 +1,45 @@ -import { HttpMethod, MachineDetectionBehavior } from '../enums/index'; -import { CallEndpoint } from './Endpoint/index'; +import { HttpMethod, MachineDetectionBehavior } from '../enums'; +import { CallEndpoint } from './Endpoint'; import { AdvancedMachineDetection } from './AdvancedMachineDetection'; import { CommonCallFields } from './CommonCallFields'; +/** + * Represents common fields for defining an outbound call, including the caller (from) and recipient (to) endpoints, + * along with additional call parameters. + */ export type CommonOutboundCall = Omit & { + /** + * An array of recipient endpoints for the call. + */ to: Array; + + /** + * Specifies the behavior for machine detection during the call. + */ machineDetection?: MachineDetectionBehavior; + + /** + * Advanced machine detection settings for the call. + */ advancedMachineDetection?: AdvancedMachineDetection; + + /** + * The length of time to wait for call answer, in seconds. + */ lengthTimer?: number; + + /** + * The length of time to wait for the call to ring before considering it unanswered, in seconds. + */ ringingTimer?: number; + + /** + * An array of URLs to notify with call events. + */ eventUrl?: string[]; + + /** + * The HTTP method to use when sending events to the specified event URLs. + */ eventMethod?: HttpMethod; }; diff --git a/packages/voice/lib/types/Endpoint/CallEndpoint.ts b/packages/voice/lib/types/Endpoint/CallEndpoint.ts index c071efea..bf55a7ae 100644 --- a/packages/voice/lib/types/Endpoint/CallEndpoint.ts +++ b/packages/voice/lib/types/Endpoint/CallEndpoint.ts @@ -3,6 +3,10 @@ import { SIPEndpoint } from './SIPEndpoint'; import { VBCEndpoint } from './VBCEndpoint'; import { WebsocketEndpoint } from './WebsocketEndpoint'; +/** + * Represents a call endpoint, which can be of different types such as Phone, SIP, VBC, or Websocket. + * This type can be used to specify the destination for an outbound call. + */ export type CallEndpoint = | WebsocketEndpoint | PhoneEndpoint diff --git a/packages/voice/lib/types/Endpoint/PSTNEndpoint.ts b/packages/voice/lib/types/Endpoint/PSTNEndpoint.ts index 89314e03..d9f80a97 100644 --- a/packages/voice/lib/types/Endpoint/PSTNEndpoint.ts +++ b/packages/voice/lib/types/Endpoint/PSTNEndpoint.ts @@ -1,5 +1,20 @@ +/** + * Represents a PSTN (Public Switched Telephone Network) endpoint, which can be used as a call destination. + */ export type PSTNEndpoint = { + /** + * Specifies the type of endpoint, which is 'phone' for phone numbers. + */ type: 'phone'; + + /** + * The phone number associated with the endpoint. + */ number: string; + + /** + * An optional DTMF (Dual-Tone Multi-Frequency) answer string. When provided, + * it enables automated call answering by sending DTMF tones. + */ dtmfAnswer?: string; }; diff --git a/packages/voice/lib/types/Endpoint/PhoneEndpoint.ts b/packages/voice/lib/types/Endpoint/PhoneEndpoint.ts index 5a33e0f8..a63ce381 100644 --- a/packages/voice/lib/types/Endpoint/PhoneEndpoint.ts +++ b/packages/voice/lib/types/Endpoint/PhoneEndpoint.ts @@ -1,4 +1,14 @@ +/** + * Represents a phone endpoint, which can be used as a call destination. + */ export type PhoneEndpoint = { + /** + * Specifies the type of endpoint, which is 'phone' for phone numbers. + */ type: 'phone'; + + /** + * The phone number associated with the endpoint. + */ number: string; }; diff --git a/packages/voice/lib/types/Endpoint/SIPEndpoint.ts b/packages/voice/lib/types/Endpoint/SIPEndpoint.ts index f9fa7078..2020da70 100644 --- a/packages/voice/lib/types/Endpoint/SIPEndpoint.ts +++ b/packages/voice/lib/types/Endpoint/SIPEndpoint.ts @@ -1,5 +1,19 @@ +/** + * Represents a SIP (Session Initiation Protocol) endpoint, which can be used as a call destination. + */ export type SIPEndpoint = { + /** + * Specifies the type of endpoint, which is 'sip' for SIP URIs. + */ type: 'sip'; + + /** + * The SIP URI associated with the endpoint. + */ uri: string; + + /** + * An optional array of headers as key-value pairs. These headers can be included in the SIP request. + */ headers?: Array>; }; diff --git a/packages/voice/lib/types/Endpoint/VBCEndpoint.ts b/packages/voice/lib/types/Endpoint/VBCEndpoint.ts index 3d849ded..8ec2b104 100644 --- a/packages/voice/lib/types/Endpoint/VBCEndpoint.ts +++ b/packages/voice/lib/types/Endpoint/VBCEndpoint.ts @@ -1,4 +1,14 @@ +/** + * Represents a Vonage Business Cloud (VBC) endpoint, which can be used as a call destination. + */ export type VBCEndpoint = { + /** + * Specifies the type of endpoint, which is 'vbc' for Vonage Business Cloud. + */ type: 'vbc'; + + /** + * An optional extension associated with the VBC endpoint. If provided, the call will be directed to this extension. + */ extension?: string; }; diff --git a/packages/voice/lib/types/Endpoint/WebsocketEndpoint.ts b/packages/voice/lib/types/Endpoint/WebsocketEndpoint.ts index 777ee3c9..d64f23c6 100644 --- a/packages/voice/lib/types/Endpoint/WebsocketEndpoint.ts +++ b/packages/voice/lib/types/Endpoint/WebsocketEndpoint.ts @@ -1,6 +1,24 @@ +/** + * Represents a WebSocket endpoint, which can be used as a call destination. + */ export type WebsocketEndpoint = { + /** + * Specifies the type of endpoint, which is 'websocket' for WebSocket. + */ type: 'websocket'; + + /** + * The URI (Uniform Resource Identifier) of the WebSocket endpoint. + */ uri: string; + + /** + * An optional content type to specify the format of the data sent to the WebSocket endpoint. + */ contentType?: string; + + /** + * Optional headers to include when connecting to the WebSocket endpoint. + */ headers?: Record; }; diff --git a/packages/voice/lib/types/NCCO/Action.ts b/packages/voice/lib/types/NCCO/Action.ts index 58b6bf00..054cd9ba 100644 --- a/packages/voice/lib/types/NCCO/Action.ts +++ b/packages/voice/lib/types/NCCO/Action.ts @@ -1,3 +1,7 @@ import { NCCOAction } from './NCCOActions'; +/** + * Represents a Nexmo Call Control Object (NCCO) action that defines the behavior of a call. + * This type is an alias for the `NCCOAction` type. + */ export type Action = NCCOAction; diff --git a/packages/voice/lib/types/NCCO/ConnectAction.ts b/packages/voice/lib/types/NCCO/ConnectAction.ts index 9a73b7bd..0bbb7acf 100644 --- a/packages/voice/lib/types/NCCO/ConnectAction.ts +++ b/packages/voice/lib/types/NCCO/ConnectAction.ts @@ -1,16 +1,60 @@ -import { CallEndpoint } from '../Endpoint/CallEndpoint'; +import { CallEndpoint } from '../Endpoint'; import { NCCOActions, MachineDetection, ConnectEventType } from '../../enums'; +/** + * Represents a Nexmo Call Control Object (NCCO) action for connecting a call to one or more endpoints. + * The `ConnectAction` defines the behavior of the call when connecting. + */ export type ConnectAction = { + /** The type of action, which is "connect" for connecting a call. */ action: NCCOActions.CONNECT; + + /** An array of URLs to webhook endpoints that will receive events related to this action. */ eventUrl?: string[]; + + /** + * The event type to be sent to the event URL(s). Possible values include: + * - "synchronous" (default): Events are sent synchronously. + */ eventType?: ConnectEventType; + + /** The caller's identity that will be displayed to the callee. */ from?: string; + + /** An array of `CallEndpoint` objects representing the endpoints to connect the call to. */ endpoint: Array; + + /** + * When `true`, a random caller ID number will be generated and used as the `from` number. + * This can help with privacy and security by masking the original caller's number. + */ randomFromNumber?: boolean; + + /** + * The maximum time (in seconds) that the platform should wait for an answer from the endpoint. + * If no answer is received within this time, the call may be treated as unanswered. + */ timeout?: number; + + /** + * The maximum number of times this action should be executed. If set, the + * action will only be executed up to the specified limit. + */ limit?: number; + + /** + * The behavior of machine detection when connecting the call. Possible values include: + * - "continue" (default): Continue connecting the call even if a machine is detected. + * - "hangup": Hang up the call if a machine is detected. + */ machineDetection?: MachineDetection; + + /** The HTTP method to use when making requests to the `eventUrl`. Default is "POST". */ eventMethod?: string; + + /** + * The URL to a ringback tone to play to the caller while waiting for the call to connect. + * It's usually a URL to an audio file that serves as a ringtone. + */ ringbackTone?: string; }; diff --git a/packages/voice/lib/types/NCCO/ConversationAction.ts b/packages/voice/lib/types/NCCO/ConversationAction.ts index 0bdb1ed0..873483f2 100644 --- a/packages/voice/lib/types/NCCO/ConversationAction.ts +++ b/packages/voice/lib/types/NCCO/ConversationAction.ts @@ -1,12 +1,55 @@ import { NCCOActions } from '../../enums'; + +/** + * Represents a Nexmo Call Control Object (NCCO) action for starting a conversation within a call. + * The `ConversationAction` defines the behavior of the conversation. + */ export type ConversationAction = { + /** The type of action, which is "conversation" for starting a conversation. */ action: NCCOActions.CONVERSATION; + + /** The name or identifier of the conversation. */ name: string; + + /** + * An array of URLs to music or audio files to be played to participants when they are on hold. + * It provides background music or audio while participants are waiting in the conversation. + */ musicOnHoldUrl?: string[]; + + /** + * When `true`, the conversation starts when a participant enters the conversation. + * If set to `false`, the conversation must be explicitly started. + */ startOnEnter?: boolean; + + /** + * When `true`, the conversation ends when a participant exits the conversation. + * If set to `false`, the conversation must be explicitly ended. + */ endOnExit?: boolean; + + /** + * When `true`, the conversation will be recorded, and the audio will be saved. + * Participants' voices will be recorded during the conversation. + */ record?: boolean; + + /** + * An array of participant identifiers (e.g., participant's phone numbers or usernames) + * who can speak in the conversation. Restricts who can actively participate in the conversation as speakers. + */ canSpeak?: string[]; + + /** + * An array of participant identifiers (e.g., participant's phone numbers or usernames) who can hear the conversation. + * Restricts who can listen to the conversation as listeners. + */ canHear?: string[]; + + /** + * When `true`, all participants in the conversation are muted by default. + * Participants must unmute themselves to speak in the conversation. + */ mute?: boolean; }; diff --git a/packages/voice/lib/types/NCCO/DTMFSettings.ts b/packages/voice/lib/types/NCCO/DTMFSettings.ts index 0c4b781d..f2f373a3 100644 --- a/packages/voice/lib/types/NCCO/DTMFSettings.ts +++ b/packages/voice/lib/types/NCCO/DTMFSettings.ts @@ -1,5 +1,23 @@ +/** + * Represents settings for Dual-Tone Multi-Frequency (DTMF) recognition in a Nexmo Call Control Object (NCCO) action. + * DTMF settings define how the system handles DTMF tones during a call. + */ export type DTMFSettings = { + /** + * The duration (in seconds) to wait for the user to input DTMF digits. + * If no digits are entered within this timeout, the DTMF recognition ends. + */ timeOut?: number; + + /** + * The maximum number of DTMF digits to collect. + * Once the maximum digits are collected, the DTMF recognition ends. + */ maxDigits?: number; + + /** + * When set to `true`, the DTMF recognition ends and submits the collected digits when a '#' key is pressed. + * If set to `false`, the DTMF recognition ends when the maximum digits are collected or the timeout occurs. + */ submitOnHash?: boolean; }; diff --git a/packages/voice/lib/types/NCCO/InputAction.ts b/packages/voice/lib/types/NCCO/InputAction.ts index 8d5dfe36..ee703be9 100644 --- a/packages/voice/lib/types/NCCO/InputAction.ts +++ b/packages/voice/lib/types/NCCO/InputAction.ts @@ -2,11 +2,44 @@ import { NCCOActions } from '../../enums'; import { DTMFSettings } from './DTMFSettings'; import { SpeechSettings } from './SpeechSettings'; +/** + * Represents an Input action in a Nexmo Call Control Object (NCCO). + * An Input action allows you to collect user input, including Dual-Tone Multi-Frequency (DTMF) and speech recognition. + */ export type InputAction = { + /** + * The action type, which is set to NCCOActions.INPUT for Input actions. + */ action: NCCOActions.INPUT; + + /** + * An array that specifies the input types that are enabled. + * Possible values are 'dtmf' for DTMF input and 'speech' for speech recognition. + * At least one input type must be enabled. + */ type: string[]; + + /** + * Optional settings for Dual-Tone Multi-Frequency (DTMF) input recognition. + * Use this property to configure how DTMF input is handled. + */ dtmf?: DTMFSettings; + + /** + * Optional settings for speech recognition input. + * Use this property to configure speech recognition options. + */ speech?: SpeechSettings; + + /** + * An array of URLs where events related to this Input action will be sent. + * Events may include user input and recognition results. + */ eventUrl?: string[]; + + /** + * The HTTP method used to send events to the specified event URLs. + * Valid values are 'GET' and 'POST'. + */ eventMethod?: string; }; diff --git a/packages/voice/lib/types/NCCO/NCCOActions.ts b/packages/voice/lib/types/NCCO/NCCOActions.ts index 479f5bdc..687aa7de 100644 --- a/packages/voice/lib/types/NCCO/NCCOActions.ts +++ b/packages/voice/lib/types/NCCO/NCCOActions.ts @@ -6,6 +6,19 @@ import { StreamAction } from './StreamAction'; import { InputAction } from './InputAction'; import { NotifyAction } from './NotifyAction'; +/** + * Represents a Nexmo Call Control Object (NCCO) action, which can be one of the following types: + * - ConnectAction + * - ConversationAction + * - InputAction + * - NotifyAction + * - RecordAction + * - StreamAction + * - TalkAction + * + * An NCCO action defines a specific action or behavior in a call flow, and these actions can be combined + * to create complex call scenarios when constructing NCCOs. + */ export type NCCOAction = | ConnectAction | ConversationAction diff --git a/packages/voice/lib/types/NCCO/NotifyAction.ts b/packages/voice/lib/types/NCCO/NotifyAction.ts index a05e8f88..8e12fe29 100644 --- a/packages/voice/lib/types/NCCO/NotifyAction.ts +++ b/packages/voice/lib/types/NCCO/NotifyAction.ts @@ -1,8 +1,29 @@ import { NCCOActions } from '../../enums'; +/** + * Represents a Notify action in a Nexmo Call Control Object (NCCO). A Notify action is used to send a notification + * to the specified event URLs with the provided payload. + */ export type NotifyAction = { + /** + * The action type, which should be set to 'notify'. + */ action: NCCOActions.NOTIFY; + + /** + * The payload to be sent as part of the notification. It is a key-value pair object where the keys and values + * are both strings. + */ payload: Record; + + /** + * An array of event URLs to which the notification will be sent. + */ eventUrl: string[]; + + /** + * (Optional) The HTTP method used for sending the notification to the event URLs. If not specified, the default + * HTTP method is used. + */ eventMethod?: string; }; diff --git a/packages/voice/lib/types/NCCO/RecordAction.ts b/packages/voice/lib/types/NCCO/RecordAction.ts index 382ff156..f2954087 100644 --- a/packages/voice/lib/types/NCCO/RecordAction.ts +++ b/packages/voice/lib/types/NCCO/RecordAction.ts @@ -1,14 +1,62 @@ import { NCCOActions, RecordingFormat } from '../../enums'; +/** + * Represents a Record action in a Nexmo Call Control Object (NCCO). A Record + * action is used to record audio during a call. You can specify various options + * such as the recording format, channel configuration, timeout, and more. + */ export type RecordAction = { + /** + * The action type, which should be set to 'record'. + */ action: NCCOActions.RECORD; + + /** + * (Optional) An array of event URLs to which recording events will be sent. These events include the start and stop + * of recording. + */ eventUrl?: string[]; + + /** + * (Optional) If set to `true`, a beep sound will be played at the beginning of the recording. Default is `false`. + */ beepStart?: boolean; + + /** + * (Optional) The HTTP method used for sending recording events to the specified event URLs. If not specified, the + * default HTTP method is used. + */ eventMethod?: string; + + /** + * (Optional) The format in which the recording should be stored. Supported formats include 'mp3', 'wav', and 'ogg'. + * If not specified, the default format may be used. + */ format?: RecordingFormat; + + /** + * (Optional) Specifies how the recording should be split. The only supported value is 'conversation'. + */ split?: 'conversation'; + + /** + * (Optional) The number of channels for the recording. Must be between 1 and 32, inclusive. + */ channels?: number; + + /** + * (Optional) The maximum duration of silence (in seconds) before the recording is stopped automatically. Must be + * between 3 and 10 seconds, inclusive. + */ endOnSilence?: number; + + /** + * (Optional) The key that, when pressed, will stop the recording. Valid characters are '0-9', '*', and '#'. + */ endOnKey?: string; + + /** + * (Optional) The maximum duration of the recording in seconds. Must be between 3 and 7200 seconds, inclusive. + */ timeOut?: number; }; diff --git a/packages/voice/lib/types/NCCO/SpeechSettings.ts b/packages/voice/lib/types/NCCO/SpeechSettings.ts index 72f09ffe..38db3cde 100644 --- a/packages/voice/lib/types/NCCO/SpeechSettings.ts +++ b/packages/voice/lib/types/NCCO/SpeechSettings.ts @@ -1,9 +1,42 @@ +/** + * Represents settings for speech recognition within a Nexmo Call Control Object (NCCO). + */ export interface SpeechSettings { + /** + * (Optional) A unique identifier (UUID) for the speech recognition session. If not provided, Nexmo generates one. + */ uuid?: string; + + /** + * (Optional) If set to `true`, speech recognition will end when there is a period of silence. Default is `false`. + */ endOnSilence?: boolean; + + /** + * (Optional) The language in which speech recognition should be performed. This should be + * a language code or identifier. + */ language?: string; + + /** + * (Optional) An array of context strings that provide additional information for speech + * recognition. Contexts can help improve recognition accuracy. + */ context?: string[]; + + /** + * (Optional) The maximum time (in seconds) to wait for the start of speech recognition after the audio begins. + */ startTimeout?: number; + + /** + * (Optional) The maximum duration (in seconds) for speech recognition in a single session. If + * recognition exceeds this duration, it will be terminated. + */ maxDuration?: number; + + /** + * (Optional) If set to `true`, the audio of the recognized speech will be saved. Default is `false`. + */ saveAudio?: boolean; } diff --git a/packages/voice/lib/types/NCCO/StreamAction.ts b/packages/voice/lib/types/NCCO/StreamAction.ts index 316ff755..0dc16699 100644 --- a/packages/voice/lib/types/NCCO/StreamAction.ts +++ b/packages/voice/lib/types/NCCO/StreamAction.ts @@ -1,9 +1,34 @@ import { NCCOActions } from '../../enums'; +/** + * Represents a Stream action within a Nexmo Call Control Object (NCCO). This action + * allows streaming audio content to a call. + */ export type StreamAction = { + /** + * The action type, which is always set to 'stream'. + */ action: NCCOActions.STREAM; + + /** + * An array of URLs pointing to the audio streams to be played during the call. + */ streamUrl: Array; + + /** + * (Optional) The audio level at which the stream should be played. Valid values + * range from -1 (quietest) to 1 (loudest). + */ level?: number; + + /** + * (Optional) If set to `true`, allows barge-in, which means the caller can interrupt + * the stream by speaking. Default is `false`. + */ bargeIn?: boolean; + + /** + * (Optional) The number of times the audio stream should be looped. If not specified, the stream will not loop. + */ loop?: number; }; diff --git a/packages/voice/lib/types/NCCO/TalkAction.ts b/packages/voice/lib/types/NCCO/TalkAction.ts index fd9dcb71..a0f9cfda 100644 --- a/packages/voice/lib/types/NCCO/TalkAction.ts +++ b/packages/voice/lib/types/NCCO/TalkAction.ts @@ -1,12 +1,49 @@ import { NCCOActions, TTSLanguages } from '../../enums'; +/** + * Represents a Talk action within a Nexmo Call Control Object (NCCO). This action + * allows text-to-speech (TTS) to be spoken during a call. + */ export type TalkAction = { + /** + * The action type, which is always set to 'talk'. + */ action: NCCOActions.TALK; + + /** + * The text that should be spoken using text-to-speech (TTS) during the call. + */ text: string; + + /** + * (Optional) If set to `true`, allows barge-in, which means the caller can interrupt the TTS + * speech by speaking. Default is `false`. + */ bargeIn?: boolean; + + /** + * (Optional) The number of times the TTS speech should be looped. If not specified, the TTS speech will not loop. + */ loop?: number; + + /** + * (Optional) The voice level at which the TTS speech should be spoken. This can be a string + * representation of the level. + */ level?: string; + + /** + * (Optional) The language in which the TTS speech should be spoken. Use one of the supported TTS language codes. + */ language?: TTSLanguages; + + /** + * (Optional) The style or type of voice to use for TTS speech. This can be a string representing the voice style. + */ style?: string; + + /** + * (Optional) If set to `true`, indicates that premium TTS should be used for the speech. Default is `false`. + */ premium?: boolean; }; diff --git a/packages/voice/lib/types/OutboundCall.ts b/packages/voice/lib/types/OutboundCall.ts index fb228edc..e72c99b1 100644 --- a/packages/voice/lib/types/OutboundCall.ts +++ b/packages/voice/lib/types/OutboundCall.ts @@ -1,4 +1,9 @@ import { CallWithAnswerURL } from './CallWithAnswerURL'; import { CallWithNCCO } from './CallWithNCCO'; +/** + * Represents an outbound call, which can either include an answer URL (for simple call scenarios) + * or an NCCO (Nexmo Call Control Object) for more complex call scenarios. Depending on the use case, + * it can be either a `CallWithAnswerURL` or a `CallWithNCCO`. + */ export type OutboundCall = CallWithNCCO | CallWithAnswerURL; diff --git a/packages/voice/lib/types/Parameters/CallListFilter.ts b/packages/voice/lib/types/Parameters/CallListFilter.ts new file mode 100644 index 00000000..7b19513b --- /dev/null +++ b/packages/voice/lib/types/Parameters/CallListFilter.ts @@ -0,0 +1,12 @@ +import { GetCallDetailsParameters } from "./GetCallsDetailsParameters"; + +/** + * @deprecated Pelease use GetCallDetailsParameters instead + */ +export type CallListFilter = { + date_start?: string; + date_end?: string; + page_size?: string; + record_index?: string; + conversation_uuid?: string; +} & GetCallDetailsParameters; diff --git a/packages/voice/lib/types/Parameters/EarmuffCallParameters.ts b/packages/voice/lib/types/Parameters/EarmuffCallParameters.ts index 1c6dbff4..3e12470a 100644 --- a/packages/voice/lib/types/Parameters/EarmuffCallParameters.ts +++ b/packages/voice/lib/types/Parameters/EarmuffCallParameters.ts @@ -1,3 +1,9 @@ +/** + * Represents parameters for an "earmuff" action in a call. + */ export type EarmuffCallParameters = { + /** + * The action to earmuff the call. + */ action: 'earmuff'; }; diff --git a/packages/voice/lib/types/Parameters/GetCallsDetailsParameters.ts b/packages/voice/lib/types/Parameters/GetCallsDetailsParameters.ts index d209837e..357abf3f 100644 --- a/packages/voice/lib/types/Parameters/GetCallsDetailsParameters.ts +++ b/packages/voice/lib/types/Parameters/GetCallsDetailsParameters.ts @@ -1,11 +1,41 @@ -import { CallStatus } from '../../enums/CallStatus'; +import { CallStatus } from '../../enums'; +/** + * Represents parameters for retrieving call details. + */ export type GetCallDetailsParameters = { + /** + * Optional: The status of the calls to retrieve. + */ status?: CallStatus; + + /** + * Optional: The start date for filtering calls. + */ dateStart?: string; + + /** + * Optional: The end date for filtering calls. + */ dateEnd?: string; + + /** + * Optional: The page size for pagination. + */ pageSize?: number; + + /** + * Optional: The record index for pagination. + */ recordIndex?: number; + + /** + * Optional: The order in which calls are retrieved (ascending or descending). + */ order?: 'asc' | 'desc'; + + /** + * Optional: The conversation UUID for filtering calls. + */ conversationUuid?: string; }; diff --git a/packages/voice/lib/types/Parameters/HangupCallParameters.ts b/packages/voice/lib/types/Parameters/HangupCallParameters.ts index 2292c24c..0965330b 100644 --- a/packages/voice/lib/types/Parameters/HangupCallParameters.ts +++ b/packages/voice/lib/types/Parameters/HangupCallParameters.ts @@ -1,3 +1,9 @@ +/** + * Represents parameters for hanging up a call. + */ export type HangupCallParameters = { + /** + * The action indicating that the call should be hung up. + */ action: 'hangup'; }; diff --git a/packages/voice/lib/types/Parameters/MuteCallParameters.ts b/packages/voice/lib/types/Parameters/MuteCallParameters.ts index 5af0432d..d768b143 100644 --- a/packages/voice/lib/types/Parameters/MuteCallParameters.ts +++ b/packages/voice/lib/types/Parameters/MuteCallParameters.ts @@ -1,3 +1,9 @@ +/** + * Represents parameters for muting a call. + */ export type MuteCallParameters = { + /** + * The action indicating that the call should be muted. + */ action: 'mute'; }; diff --git a/packages/voice/lib/types/Parameters/PlayDTMFParameters.ts b/packages/voice/lib/types/Parameters/PlayDTMFParameters.ts index 56feedb2..57638319 100644 --- a/packages/voice/lib/types/Parameters/PlayDTMFParameters.ts +++ b/packages/voice/lib/types/Parameters/PlayDTMFParameters.ts @@ -1,3 +1,9 @@ +/** + * Represents parameters for playing DTMF (Dual-Tone Multi-Frequency) digits in a call. + */ export type PlayDTMFParameters = { + /** + * The DTMF digits to be played in the call. + */ digits: string; }; diff --git a/packages/voice/lib/types/Parameters/PlayTTSParameters.ts b/packages/voice/lib/types/Parameters/PlayTTSParameters.ts index 2a27685f..729a6de5 100644 --- a/packages/voice/lib/types/Parameters/PlayTTSParameters.ts +++ b/packages/voice/lib/types/Parameters/PlayTTSParameters.ts @@ -1,11 +1,41 @@ -import { TTSLanguages, TTSVoices } from '../../enums/index'; +import { TTSLanguages, TTSVoices } from '../../enums'; +/** + * Represents parameters for playing Text-to-Speech (TTS) in a call. + */ export type PlayTTSParameters = { + /** + * The text to be converted to speech and played in the call. + */ text: string; + + /** + * The language in which the text should be spoken. Optional. + */ language?: TTSLanguages; + + /** + * The style or voice variant for the TTS. Optional. + */ style?: number; + + /** + * Indicates if premium TTS features should be used. Optional. + */ premium?: boolean; + + /** + * The name of the specific TTS voice to use. Optional. + */ voiceName?: TTSVoices; + + /** + * The number of times to loop the TTS playback. Optional. + */ loop?: number; + + /** + * The audio level for the TTS playback. Optional. + */ level?: string; }; diff --git a/packages/voice/lib/types/Parameters/StreamAudioParameters.ts b/packages/voice/lib/types/Parameters/StreamAudioParameters.ts index d9591bc2..ecac8317 100644 --- a/packages/voice/lib/types/Parameters/StreamAudioParameters.ts +++ b/packages/voice/lib/types/Parameters/StreamAudioParameters.ts @@ -1,5 +1,19 @@ +/** + * Represents parameters for streaming audio in a call. + */ export type StreamAudioParameters = { + /** + * An array of URLs specifying the audio streams to be played in the call. + */ streamUrl: Array; + + /** + * The number of times to loop the audio stream playback. Optional. + */ loop?: number; + + /** + * The audio level or volume for the streamed audio. Optional. + */ level?: number; }; diff --git a/packages/voice/lib/types/Parameters/TransferCallParameters.ts b/packages/voice/lib/types/Parameters/TransferCallParameters.ts index 0ed3e078..9e77b1c1 100644 --- a/packages/voice/lib/types/Parameters/TransferCallParameters.ts +++ b/packages/voice/lib/types/Parameters/TransferCallParameters.ts @@ -1,17 +1,36 @@ import { XOR } from 'ts-xor'; -import { NCCOAction } from '../NCCO/index'; +import { NCCOAction } from '../NCCO'; +/** + * Destination using URL. + */ type TransferWithURL = { ncco: Array; }; +/** + * Destination using NCCO. + */ type TransferWithNCCO = { url: Array; }; +/** + * Represents parameters for transferring a call to another destination. + */ export type TransferCallParameters = { + /** + * The action type indicating a call transfer. + */ action: 'transfer'; + + /** + * The destination of the transfer, which can be specified using NCCO or a URL. + */ destination: { + /** + * The type of destination, either 'ncco' for NCCO-based transfer or 'url' for URL-based transfer. + */ type: 'ncco'; } & XOR; }; diff --git a/packages/voice/lib/types/Parameters/UnearmuffCallParameters.ts b/packages/voice/lib/types/Parameters/UnearmuffCallParameters.ts index 8455fed1..bfe5d3a4 100644 --- a/packages/voice/lib/types/Parameters/UnearmuffCallParameters.ts +++ b/packages/voice/lib/types/Parameters/UnearmuffCallParameters.ts @@ -1,3 +1,9 @@ +/** + * Represents parameters for unearmuffing a call, allowing the call audio to be heard again. + */ export type UnearmuffCallParameters = { + /** + * The action type indicating unearmuffing of a call. + */ action: 'unearmuff'; }; diff --git a/packages/voice/lib/types/Parameters/UnmuteCallParameters.ts b/packages/voice/lib/types/Parameters/UnmuteCallParameters.ts index 03de2822..fe882f33 100644 --- a/packages/voice/lib/types/Parameters/UnmuteCallParameters.ts +++ b/packages/voice/lib/types/Parameters/UnmuteCallParameters.ts @@ -1,3 +1,9 @@ +/** + * Represents parameters for unmuting a call, allowing audio to be transmitted and received again. + */ export type UnmuteCallParameters = { + /** + * The action type indicating unmuting of a call. + */ action: 'unmute'; }; diff --git a/packages/voice/lib/types/Parameters/index.ts b/packages/voice/lib/types/Parameters/index.ts index d7ab248e..fb29d33c 100644 --- a/packages/voice/lib/types/Parameters/index.ts +++ b/packages/voice/lib/types/Parameters/index.ts @@ -1,4 +1,5 @@ export * from './CreateCallParameters'; +export * from './CallListFilter'; export * from './GetCallsDetailsParameters'; export * from './EarmuffCallParameters'; export * from './HangupCallParameters'; diff --git a/packages/voice/lib/types/Requests/CreateCallRequest.ts b/packages/voice/lib/types/Requests/CreateCallRequest.ts index c4edba3c..bfa4f842 100644 --- a/packages/voice/lib/types/Requests/CreateCallRequest.ts +++ b/packages/voice/lib/types/Requests/CreateCallRequest.ts @@ -2,14 +2,47 @@ import { OutboundCall } from '../OutboundCall'; import { AdvancedMachineDetection } from '../AdvancedMachineDetection'; import { MachineDetection } from '../../enums'; +/** + * Represents the request payload for creating a call, including various call settings. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type CreateCallRequest = { + /** + * Specifies whether to use a random caller number for the call. + */ random_from_number?: boolean; + + /** + * An array of URLs for event callbacks during the call's lifecycle. + */ event_url?: Array; + + /** + * The type of machine detection to use for the call. + */ machine_detection?: MachineDetection; + + /** + * Advanced machine detection settings, including beep timeout. + */ advanced_machine_detection: { + /** + * The beep timeout setting for advanced machine detection. + */ beep_timeout?: number; } & Omit; + + /** + * The length timer setting for the call. + */ length_timer?: number; + + /** + * The ringing timer setting for the call. + */ ringing_timer?: number; } & Omit< OutboundCall, diff --git a/packages/voice/lib/types/Requests/GetCallsDetailsRequest.ts b/packages/voice/lib/types/Requests/GetCallsDetailsRequest.ts index 7184bad2..3c9b35ef 100644 --- a/packages/voice/lib/types/Requests/GetCallsDetailsRequest.ts +++ b/packages/voice/lib/types/Requests/GetCallsDetailsRequest.ts @@ -1,12 +1,38 @@ -import { GetCallDetailsParameters } from '../Parameters/GetCallsDetailsParameters'; +import { GetCallDetailsParameters } from '../Parameters'; +/** + * Represents the request payload for retrieving call details with various filtering options. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type GetCallDetailsRequest = { + /** + * The start date for filtering call records. + */ date_start?: string; + + /** + * The end date for filtering call records. + */ date_end?: string; + + /** + * The maximum number of records to return per page. + */ page_size?: number; + + /** + * The record index for pagination. + */ record_index?: number; + + /** + * The UUID of the conversation to filter call records by. + */ conversation_uuid?: string; } & Omit< GetCallDetailsParameters, 'dateEnd' | 'dateStart' | 'pageSize' | 'recordIndex' | 'conversationUuid' ->; + >; diff --git a/packages/voice/lib/types/Requests/ModifyCallRequest.ts b/packages/voice/lib/types/Requests/ModifyCallRequest.ts index 0ec57736..a43ea562 100644 --- a/packages/voice/lib/types/Requests/ModifyCallRequest.ts +++ b/packages/voice/lib/types/Requests/ModifyCallRequest.ts @@ -7,7 +7,15 @@ import { UnmuteCallParameters, } from '../Parameters'; -export type ModufyCallRequestParameters = +/** + * Represents the parameters for modifying a call, including actions like + * earmuff, hangup, mute, transfer, unearmuff, and unmute. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ +export type ModifyCallRequestParameters = | EarmuffCallParameters | HangupCallParameters | MuteCallParameters diff --git a/packages/voice/lib/types/Requests/PlayDTMFRequest.ts b/packages/voice/lib/types/Requests/PlayDTMFRequest.ts index cb6f4cf1..76c50899 100644 --- a/packages/voice/lib/types/Requests/PlayDTMFRequest.ts +++ b/packages/voice/lib/types/Requests/PlayDTMFRequest.ts @@ -1,3 +1,10 @@ import { PlayDTMFParameters } from '../Parameters/PlayDTMFParameters'; +/** + * Represents the parameters for playing DTMF (Dual-Tone Multi-Frequency) tones during a call. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type PlayDTMFRequest = PlayDTMFParameters; diff --git a/packages/voice/lib/types/Requests/PlayTTSRequest.ts b/packages/voice/lib/types/Requests/PlayTTSRequest.ts index 3bb6df59..b2a02b40 100644 --- a/packages/voice/lib/types/Requests/PlayTTSRequest.ts +++ b/packages/voice/lib/types/Requests/PlayTTSRequest.ts @@ -1,6 +1,16 @@ -import { TTSVoices } from '../../enums/index'; -import { PlayTTSParameters } from '../Parameters/PlayTTSParameters'; +import { TTSVoices } from '../../enums'; +import { PlayTTSParameters } from '../Parameters'; +/** + * Represents the parameters for playing text-to-speech (TTS) during a call. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type PlayTTSRequest = { + /** + * The name of the TTS voice to use for speech synthesis. + */ voice_name?: TTSVoices; } & Omit; diff --git a/packages/voice/lib/types/Requests/StreamAudioRequest.ts b/packages/voice/lib/types/Requests/StreamAudioRequest.ts index 9a687f7f..4ea715f5 100644 --- a/packages/voice/lib/types/Requests/StreamAudioRequest.ts +++ b/packages/voice/lib/types/Requests/StreamAudioRequest.ts @@ -1,5 +1,15 @@ import { StreamAudioParameters } from '../Parameters/StreamAudioParameters'; +/** + * Represents the parameters for streaming audio during a call. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type StreamAudioRequest = { + /** + * An array of stream URLs for the audio source. + */ stream_url: Array; } & Omit; diff --git a/packages/voice/lib/types/Responses/CallDetailResponse.ts b/packages/voice/lib/types/Responses/CallDetailResponse.ts index 85774d18..b06d5429 100644 --- a/packages/voice/lib/types/Responses/CallDetailResponse.ts +++ b/packages/voice/lib/types/Responses/CallDetailResponse.ts @@ -2,13 +2,35 @@ import { APILinks } from '@vonage/server-client'; import { CallDetail } from '../CallDetail'; import { CallEndpointResponse } from './CallEndpointResponse'; +/** + * Represents the response for retrieving call details. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type CallDetailResponse = { + /** + * The UUID of the conversation associated with the call. + */ conversation_uuid: string; + + /** + * The start time of the call. + */ start_time: string; + + /** + * The end time of the call. + */ end_time: string; + + /** + * Information about the recipient (callee) of the call. + */ to: CallEndpointResponse; } & Omit< CallDetail, 'conversationUUID' | 'startTime' | 'endTime' | 'to' | 'from' -> & + > & APILinks; diff --git a/packages/voice/lib/types/Responses/CallEndpointResponse.ts b/packages/voice/lib/types/Responses/CallEndpointResponse.ts index f73bfa23..62e719fd 100644 --- a/packages/voice/lib/types/Responses/CallEndpointResponse.ts +++ b/packages/voice/lib/types/Responses/CallEndpointResponse.ts @@ -5,6 +5,17 @@ import { VBCEndpoint, } from '../Endpoint'; +/** + * Represents the response for a call endpoint, which can be one of the following: + * - Phone endpoint + * - Websocket endpoint + * - SIP endpoint + * - VBC (Vonage Business Cloud) endpoint + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type CallEndpointResponse = | PhoneEndpoint | WebsocketEndpoint diff --git a/packages/voice/lib/types/Responses/CallPageResponse.ts b/packages/voice/lib/types/Responses/CallPageResponse.ts index 7a151852..b5c7ef13 100644 --- a/packages/voice/lib/types/Responses/CallPageResponse.ts +++ b/packages/voice/lib/types/Responses/CallPageResponse.ts @@ -1,11 +1,37 @@ import { APILinks } from '@vonage/server-client'; import { CallDetailResponse } from '../../types'; +/** + * Represents the response for a page of call details, including information + * about the page itself and an array of call details. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type CallPageResponse = { + /** + * The total count of call details in the response. + */ count: number; + + /** + * The number of call details per page. + */ page_size: number; + + /** + * The index of the first call detail in the current page. + */ record_index: number; + + /** + * An embedded object containing an array of call details. + */ _embedded: { + /** + * An array of call details. + */ calls: Array; }; } & APILinks; diff --git a/packages/voice/lib/types/Responses/CreateCallResponse.ts b/packages/voice/lib/types/Responses/CreateCallResponse.ts index 0db9c50c..a67d1987 100644 --- a/packages/voice/lib/types/Responses/CreateCallResponse.ts +++ b/packages/voice/lib/types/Responses/CreateCallResponse.ts @@ -1,6 +1,28 @@ +/** + * Represents the response for creating a call, including the call's UUID, status, direction, and conversation UUID. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type CreateCallResponse = { + /** + * The UUID of the created call. + */ uuid: string; + + /** + * The status of the created call. + */ status: string; + + /** + * The direction of the call (e.g., "outbound" or "inbound"). + */ direction: string; + + /** + * The UUID of the conversation associated with the call. + */ conversation_uuid: string; }; diff --git a/packages/voice/lib/types/Responses/CreateOutboundCallResponse.ts b/packages/voice/lib/types/Responses/CreateOutboundCallResponse.ts index 9f2a2665..6b3704fb 100644 --- a/packages/voice/lib/types/Responses/CreateOutboundCallResponse.ts +++ b/packages/voice/lib/types/Responses/CreateOutboundCallResponse.ts @@ -1,5 +1,15 @@ import { BasicCallDetail } from '../BasicCallDetail'; +/** + * Represents the response for creating an outbound call, including the conversation UUID and basic call details. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type CreateOutboundCallResponse = { + /** + * The UUID of the conversation associated with the outbound call. + */ conversation_uuid: string; } & Omit; diff --git a/packages/voice/lib/types/Responses/UpdateCallResponse.ts b/packages/voice/lib/types/Responses/UpdateCallResponse.ts index af33e1fb..b0778ae7 100644 --- a/packages/voice/lib/types/Responses/UpdateCallResponse.ts +++ b/packages/voice/lib/types/Responses/UpdateCallResponse.ts @@ -1,4 +1,18 @@ +/** + * Represents the response for updating a call, including a message and the UUID of the call. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + */ export type UpdateCallResponse = { + /** + * A message associated with the call update response. + */ message: string; + + /** + * The UUID of the call that was updated. + */ uuid: string; }; diff --git a/packages/voice/lib/voice.ts b/packages/voice/lib/voice.ts index 7a974cdc..aa5d8fa1 100644 --- a/packages/voice/lib/voice.ts +++ b/packages/voice/lib/voice.ts @@ -1,4 +1,5 @@ import { AuthenticationType, Client, FileClient } from '@vonage/server-client'; +import { NCCOActions } from './enums'; import { GetCallDetailsParameters, CallPageResponse, @@ -11,9 +12,8 @@ import { Action, TalkAction, OutboundCall, -} from './types/index'; +} from './types'; -import { CallListFilter } from './types'; import { ResponseTypes } from '@vonage/vetch'; const apiCallsToCalls = (call: CallDetailResponse): CallDetail => { @@ -27,7 +27,7 @@ const apiCallsToCalls = (call: CallDetailResponse): CallDetail => { return { ...transformedCall, conversationUUID: call.conversation_uuid, - }; + } as CallDetail; }; type NCCODestination = { @@ -36,9 +36,55 @@ type NCCODestination = { ncco?: Array; }; +/** + * A Clint to make calls to the Vonage Voice API. + * + * @remarks + * Vonage API's will return information using `snake_case`. This represents the + * pure response before the client will transform the keys into `camelCase`. + * + * @example + * Create a standalone Voice client + * + * ```ts + * import { Voice } from '@vonage/voice'; + * + * const voiceClient = new Voice({ + * apiKey: VONAGE_API_KEY, + * apiSecret: VONAGE_API_SECRET + * }); + * ``` + * + * @example + * Create an Voice client from the Vonage client + * + * ```ts + * import { Vonage } from '@vonage/server-client'; + * + * const vonage = new Vonage({ + * apiKey: VONAGE_API_KEY, + * apiSecret: VONAGE_API_SECRET + * }); + * + * const voiceClient = vonage.voice; + * ``` + */ export class Voice extends Client { protected authType = AuthenticationType.JWT; + /** + * Retrieves details of all calls using pagination. + * + * @param {GetCallDetailsParameters} params - Optional parameters for filtering and pagination. + * @return {AsyncGenerator} An async generator that yields call details or void when there are no more results. + * + * @example + * ```ts + * for await (const call of voiceClient.getAllCalls()) { + * console.log(call.startTime); + * } + * ``` + */ async *getAllCalls( params: GetCallDetailsParameters = {}, ): AsyncGenerator { @@ -50,11 +96,54 @@ export class Voice extends Client { yield* resp?._embedded?.calls.map(apiCallsToCalls); next = resp?._links?.next ? new URL(resp._links.next.href) : null; if (next) { - params.recordIndex = parseInt(next.searchParams.get('record_index')); + params.recordIndex = parseInt( + next.searchParams.get('record_index') as string, + ); } } while (next); } + /** + * Retrieves a page of call details based on the specified parameters. + * + * @param {GetCallDetailsParameters} params - Optional parameters for filtering and pagination. + * @return {Promise} A promise that resolves to a page of call details. + * + * @example + * ```ts + * const page = await voiceClient.getCallsPage(); + * for (const call of page._embedded.calls) { + * console.log(call.startTime); + * } + * ``` + * + * @example + * Get the next page of call details + * ```ts + * const page = await voiceClient.getCallsPage({ + * pageSize: 4, + * recordIndex: 10, + * }); + * for (const call of page._embedded.calls) { + * console.log(call.startTime); + * } + * ``` + * + * @example + * Get all started calls + * ```ts + * import { CallStatus } from '@vonage/voice'; + * + * const page = await voiceClient.getCallsPage({ + * pageSize: 4, + * recordIndex: 10, + * status: CallStatus.STARTED, + * }); + * for (const call of page._embedded.calls) { + * console.log(call.startTime); + * } + * ``` + */ async getCallsPage( params: GetCallDetailsParameters, ): Promise { @@ -67,10 +156,42 @@ export class Voice extends Client { }; } - async search(filter?: CallListFilter): Promise { + /** + * Searches for call details based on the provided filter. + * + * @param {GetCallDetailsParameters} [filter] - Optional filter criteria to narrow down the search. + * @return {Promise} A promise that resolves to a page of call details matching the filter. + * + * @example + * ```ts + * const page = await voiceClient.search({ + * pageSize: 4, + * }); + * + * for (const call of page._embedded.calls) { + * console.log(call.startTime); + * console.log(call.status); + * console.log(call.direction); + * console.log(call.duration); + * }; + * ``` + */ + async search(filter: GetCallDetailsParameters): Promise { return this.getCallsPage(filter); } + /** + * Retrieves detailed information about a specific call using its UUID. + * + * @param {string} uuid - The UUID of the call to retrieve details for. + * @return {Promise} A promise that resolves to detailed information about the call. + * + * @example + * ```ts + * const call = await voiceClient.getCall('CALL_UUID'); + * console.log(call.startTime); + * ``` + */ async getCall(uuid: string): Promise { const resp = await this.sendGetRequest( `${this.config.apiHost}/v1/calls/${uuid}`, @@ -78,6 +199,43 @@ export class Voice extends Client { return apiCallsToCalls(resp.data); } + /** + * Initiates an outbound call with the specified configuration. + * + * @param {OutboundCall} call - The configuration for the outbound call. + * @return {Promise} A promise that resolves to the result of the outbound call initiation. + * + * @example + * Create a call with answer NCCO + * ```ts + * const call = await voiceClient.createOutboundCall({ + * to: [{ + * type: 'phone', + * number: TO_NUMBER + * }], + * asnwer_url: ['https://example.com/answer'], + * }); + * + * console.log(call.uuid); + * + * ``` + * @example + * Create a call with answer URL + * ```ts + * const call = await voiceClient.createOutboundCall({ + * to: [{ + * type: 'phone', + * number: TO_NUMBER + * }], + * ncco: [{ + * action: 'talk', + * text: 'This is a text to speech call from Vonage' + * }] + * }); + * + * console.log(call.uuid); + * ``` + */ async createOutboundCall(call: OutboundCall): Promise { const resp = await this.sendPostRequest( `${this.config.apiHost}/v1/calls`, @@ -90,35 +248,113 @@ export class Voice extends Client { ); delete result.conversationUuid; result.conversationUUID = resp.data.conversation_uuid; - return result; + return result as CallResult; } + /** + * Plays DTMF (Dual-Tone Multi-Frequency) tones on an active call. + * + * @param {string} uuid - The UUID of the call on which to play DTMF tones. + * @param {string} digits - The DTMF tones to play. + * @return {Promise} A promise that resolves to the result of playing DTMF tones on the call. + * + * @example + * ```ts + * const result = await voiceClient.playDTMF('CALL_UUID', '1234'); + * console.log(result.status); + * ``` + */ async playDTMF(uuid: string, digits: string): Promise { const resp = await this.sendPutRequest( `${this.config.apiHost}/v1/calls/${uuid}/dtmf`, { digits: digits }, ); - return Client.transformers.snakeCaseObjectKeys(resp.data, true, true); + return Client.transformers.snakeCaseObjectKeys( + resp.data, + true, + true, + ) as CallUpdateResult; } + /** + * Plays text-to-speech (TTS) audio on an active call. + * + * @param {string} uuid - The UUID of the call on which to play TTS audio. + * @param {TalkAction} action - The TTS action configuration. + * @return {Promise} A promise that resolves to the result of playing TTS audio on the call. + * + * @example + * ```ts + * const result = await voiceClient.playTTS( + * CALL_UUID, + * { + * text: 'This is a text to speech call from Vonage', + * }, + * ); + * + * console.log(result.status); + * ``` + */ async playTTS(uuid: string, action: TalkAction): Promise { - delete action.action; - delete action.bargeIn; - const resp = await this.sendPutRequest( `${this.config.apiHost}/v1/calls/${uuid}/talk`, - Client.transformers.snakeCaseObjectKeys(action), + { + text: action.text, + loop: action.loop, + level: action.level, + language: action.language, + style: action.style, + premium: action.premium, + }, ); - return Client.transformers.snakeCaseObjectKeys(resp.data, true, true); + + return Client.transformers.snakeCaseObjectKeys( + resp.data, + true, + true, + ) as CallUpdateResult; } + /** + * Stops any ongoing text-to-speech (TTS) audio playback on an active call. + * + * @param {string} uuid - The UUID of the call on which to stop TTS audio playback. + * @return {Promise} A promise that resolves to the result of stopping TTS audio playback on the call. + * + * @example + * + * ```ts + * const result = await voiceClient.stopTTS(CALL_UUID); + * console.log(result.status); + * ``` + */ async stopTTS(uuid: string): Promise { const resp = await this.sendDeleteRequest( `${this.config.apiHost}/v1/calls/${uuid}/talk`, ); - return Client.transformers.snakeCaseObjectKeys(resp.data, true, true); + return Client.transformers.snakeCaseObjectKeys( + resp.data, + true, + true, + ) as CallUpdateResult; } + /** + * Stream audio to an active call, allowing you to play audio files or live audio streams. + * + * @param {string} uuid - The UUID of the call to which to stream audio. + * @param {string} url - The URL of the audio stream to play. + * @param {number} [loop=1] - The number of times to loop the audio stream (default is 1). + * @param {number} [volumeLevel=0.0] - The volume level of the audio stream (0.0 to 1.0, default is 0.0). + * @return {Promise} A promise that resolves to the result of streaming audio to the call. + * + * + * @example + * ```ts + * const result = await voiceClient.streamAudio(CALL_UUID, 'https://example.com/audio.mp3'); + * console.log(result.message); + * ``` + */ async streamAudio( uuid: string, url: string, @@ -133,16 +369,54 @@ export class Voice extends Client { level: String(volumeLevel), }, ); - return Client.transformers.snakeCaseObjectKeys(resp.data, true, true); + return Client.transformers.snakeCaseObjectKeys( + resp.data, + true, + true, + ) as UpdateCallResponse; } + /** + * Stop streaming audio to an active call. + * + * @param {string} uuid - The UUID of the call from which to stop streaming audio. + * @return {Promise} A promise that resolves to the result of stopping audio streaming to the call. + * + * @example + * ```ts + * const result = await voiceClient.stopStreamAudio(CALL_UUID); + * console.log(result.message); + * ``` + */ async stopStreamAudio(uuid: string): Promise { const resp = await this.sendDeleteRequest( `${this.config.apiHost}/v1/calls/${uuid}/stream`, ); - return Client.transformers.snakeCaseObjectKeys(resp.data, true, true); + return Client.transformers.snakeCaseObjectKeys( + resp.data, + true, + true, + ) as CallUpdateResult; } + /** + * Transfer an active call to a new destination using a Nexmo Call Control Object (NCCO). + * + * @param {string} uuid - The UUID of the call to transfer. + * @param {Action[]} ncco - The NCCO actions defining the transfer destination. + * @return {Promise} A promise that resolves when the call has been successfully transferred. + * + * @example + * ```ts + * await voiceClient.transferCallWithNCCO( + * CALL_UUID, + * [{ + * action: 'talk', + * text: 'You will now be transferred to a new destination'' + * }], + * ) + * ``` + */ async transferCallWithNCCO(uuid: string, ncco: Action[]): Promise { return this.callAction(uuid, 'transfer', { type: 'ncco', @@ -150,6 +424,21 @@ export class Voice extends Client { }); } + /** + * Transfer an active call to a new destination using a URL. + * + * @param {string} uuid - The UUID of the call to transfer. + * @param {string} url - The URL of the transfer destination. + * @return {Promise} A promise that resolves when the call has been successfully transferred. + * + * @example + * ```ts + * await voiceClient.transferCallWithURL( + * CALL_UUID, + * 'https://example.com/transfer', + * ); + * ``` + */ async transferCallWithURL(uuid: string, url: string): Promise { return this.callAction(uuid, 'transfer', { type: 'ncco', @@ -157,26 +446,92 @@ export class Voice extends Client { }); } + /** + * Hang up an active call. + * + * @param {string} uuid - The UUID of the call to hang up. + * @return {Promise} A promise that resolves when the call has been successfully hung up. + * @example + * ```ts + * await voiceClient.hangupCall(CALL_UUID); + * ``` + */ async hangupCall(uuid: string): Promise { return this.callAction(uuid, 'hangup'); } + /** + * Mute an active call. + * + * @param {string} uuid - The UUID of the call to mute. + * @return {Promise} A promise that resolves when the call has been successfully muted. + * + * @example + * ```ts + * await voiceClient.muteCall(CALL_UUID); + * ``` + */ async muteCall(uuid: string): Promise { return this.callAction(uuid, 'mute'); } + /** + * Unmute a muted call, allowing audio to be transmitted again. + * + * @param {string} uuid - The UUID of the call to unmute. + * @return {Promise} A promise that resolves when the call has been successfully unmuted. + * + * @example + * ```ts + * await voiceClient.unmuteCall(CALL_UUID); + * ``` + */ async unmuteCall(uuid: string): Promise { return this.callAction(uuid, 'unmute'); } + /** + * Places a call on earmuff, muting the audio for all participants except the user. + * + * @param {string} uuid - The UUID of the call to earmuff. + * @return {Promise} A promise that resolves when the call has been successfully earmuffed. + * + * @example + * ```ts + * await voiceClient.earmuffCall(CALL_UUID); + * ``` + */ async earmuffCall(uuid: string): Promise { return this.callAction(uuid, 'earmuff'); } + /** + * Remove an earmuff from a call, allowing all participants to hear each other again. + * + * @param {string} uuid - The UUID of the call to unearmuff. + * @return {Promise} A promise that resolves when the call has been successfully unearmuffed. + * + * @example + * ```ts + * await voiceClient.unearmuffCall(CALL_UUID); + * ``` + */ async unearmuffCall(uuid: string): Promise { return this.callAction(uuid, 'unearmuff'); } + /** + * Download the recording of a call to the specified file path. + * + * @param {string} file - The name of the recording file to download. + * @param {string} path - The local file path where the recording will be saved. + * @return {Promise} A promise that resolves when the recording has been successfully downloaded. + * + * @example + * ```ts + * await voiceClient.downloadRecording(RECORDING_UUID, './recording.mp3'); + * ``` + */ async downloadRecording(file: string, path: string): Promise { const config = this.config; config.responseType = ResponseTypes.stream; @@ -185,6 +540,18 @@ export class Voice extends Client { return await client.downloadFile(file, path); } + /** + * Download the transcription of a call to the specified file path. + * + * @param {string} file - The name of the transcription file to download. + * @param {string} path - The local file path where the transcription will be saved. + * @return {Promise} A promise that resolves when the transcription has been successfully downloaded. + * + * @example + * ```ts + * await voiceClient.downloadTranscription(TRANSCRIPTION_UUID, './transcription.txt'); + * ``` + */ async downloadTranscription(file: string, path: string): Promise { const config = this.config; config.responseType = ResponseTypes.text; @@ -193,6 +560,19 @@ export class Voice extends Client { return await client.downloadFile(file, path); } + /** + * Send a call action to a specific call identified by its UUID. + * + * @param {string} uuid - The UUID of the call to which the action should be applied. + * @param {string} action - The action to perform on the call (e.g., 'hangup', 'mute', 'unmute'). + * @param {NCCODestination} [destination] - The destination details for transfer actions. + * @return {Promise} A promise that resolves when the call action has been successfully executed. + * + * @example + * ```ts + * await voiceClient.callAction(CALL_UUID, 'mute'); + * ``` + */ protected async callAction( uuid: string, action: string, diff --git a/packages/voice/package.json b/packages/voice/package.json index 4cfb823e..271eb883 100644 --- a/packages/voice/package.json +++ b/packages/voice/package.json @@ -1,7 +1,8 @@ { + "$schema": "https://json.schemastore.org/package.json", "name": "@vonage/voice", "version": "1.9.0", - "description": "Vonage Voice API", + "description": "The Voice API lets you create outbound calls, control in-progress calls and get information about historical calls.", "keywords": [ "vonage", "voice" @@ -15,7 +16,16 @@ "url": "git+https://github.com/Vonage/vonage-node-sdk.git" }, "license": "Apache-2.0", - "author": "Chris Tankersley ", + "contributors": [ + { + "name": "Chris Tankersley", + "url": "https://github.com/dragonmantank" + }, + { + "name": "Chuck \"MANCHUCK\" Reeves", + "url": "https://github.com/manchuck" + } + ], "main": "dist/index.js", "types": "dist/index.d.ts", "directories": { @@ -28,7 +38,8 @@ "scripts": { "build": "npm run clean && npm run compile", "clean": "npx shx rm -rf dist tsconfig.tsbuildinfo", - "compile": "npx tsc --build --verbose" + "compile": "npx tsc --build --verbose", + "prepublishOnly": "npm run build" }, "dependencies": { "@types/debug": "^4.1.9", @@ -45,6 +56,5 @@ }, "publishConfig": { "directory": "dist" - }, - "gitHead": "328f18e5c8a458cb4d06d7955ec2399a6ce6f5d8" + } } diff --git a/packages/voice/tsconfig.json b/packages/voice/tsconfig.json index e9b438f7..c342fe6e 100644 --- a/packages/voice/tsconfig.json +++ b/packages/voice/tsconfig.json @@ -1,24 +1,26 @@ { - "extends": "../../tsconfig.json", + "$schema": "https://json.schemastore.org/tsconfig", - "compilerOptions": { - "rootDir": "lib", - "outDir": "dist" - }, + "extends": "../../tsconfig.json", - "exclude": [ - "__tests__", - "jest.config.js", - "dist" - ], + "compilerOptions": { + "rootDir": "lib", + "outDir": "dist" + }, - "references": [ - { "path": "../auth" }, - { "path": "../server-client" }, - { "path": "../vetch" } - ], + "exclude": [ + "__tests__", + "jest.config.js", + "dist" + ], - "ts-node": { - "esm": true - } + "references": [ + { "path": "../auth" }, + { "path": "../server-client" }, + { "path": "../vetch" } + ], + + "ts-node": { + "esm": true + } } diff --git a/packages/voice/typedoc.json b/packages/voice/typedoc.json new file mode 100644 index 00000000..8b1e8f69 --- /dev/null +++ b/packages/voice/typedoc.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "extends": ["../../typedoc.base.json"], + "entryPoints": ["lib/index.ts"], + "name": "Vonage Voice" +} diff --git a/scripts/generateExample.mjs b/scripts/generateExample.mjs new file mode 100644 index 00000000..022f55f4 --- /dev/null +++ b/scripts/generateExample.mjs @@ -0,0 +1,132 @@ +import { readFileSync, createWriteStream } from "fs"; +import RecursiveIterator from 'recursive-iterator'; +import { ReflectionKind } from "typedoc"; + +const data = readFileSync("./docs/docs.json", "utf8"); + +const docs = JSON.parse(data); +const log = createWriteStream('./docs/EXAMPLES.md', { flags: 'w' }); + +const iterator = new RecursiveIterator(docs); + +let value; +let section = ''; +let currentClass = ''; +const lines = [ + '# Examples', + '', +]; + +// Group by module +const sections = {}; + +const exampleFilter = (tag) => tag.tag === '@example'; + +const remarksFilter = (tag) => tag.tag === '@remarks'; + +const getExamples = (node) => node + .signatures[0] + .comment + ?.blockTags + ?.filter(exampleFilter); + +const formatBlocks = (examples) => examples.map( + ({ content }) => [ + ...content.map(({ text }) => text), + '', + ], +).flat(); + +do { + value = iterator.next(); + if (value.done) { + break; + } + + const { parent, key } = value.value || {}; + + // We set the section name to the module + if (parent.kind === ReflectionKind.Module) { + section = parent.name; + sections[section] = sections[section] || { + name: section, + classes: {}, + }; + continue; + } + + if (parent.kind === ReflectionKind.Class + && !Object.hasOwn(sections[section].classes, parent.name)) { + currentClass = parent.name; + sections[section].classes[currentClass] = { + name: currentClass, + classExamples: [ + `### ${currentClass} Class`, + '', + // eslint-disable-next-line max-len + ...[ (parent?.comment?.summary || []).map(({ text }) => text), '' ].flat(), + ...formatBlocks( + parent.comment?.blockTags?.filter(remarksFilter) || [], + ).flat(), + ...formatBlocks( + parent.comment?.blockTags?.filter(exampleFilter) || [], + ).flat(), + ], + examples: [], + }; + continue; + } + + // We don't want to include anything that isn't a function or method + if (![ + ReflectionKind.ConstructorSignature, + ReflectionKind.Constructor, + ReflectionKind.Function, + ReflectionKind.Method, + ].includes(parent.kind)) { + continue; + } + + // We want to skip inherited methods + if (key !== 'variant' + || !Object.hasOwn(parent, 'signatures') + || Object.hasOwn(parent, 'inheritedFrom')) { + continue; + } + + // Add examples if they exist + const examples = getExamples(parent) || []; + if (examples.length < 1) { + continue; + } + + const name = parent.name !== 'constructor' ? parent.name : currentClass; + + sections[section].classes[currentClass].examples = [ + ...sections[section].classes[currentClass].examples, + `#### ${name}`, + '', + parent.signatures[0].comment.summary[0].text, + '', + ...formatBlocks(examples), + ]; +} while (true); + +Object.values(sections).forEach(({ name, classes }) => { + Object.values(classes).forEach( ({ examples, classExamples }) => { + if (examples.length < 1) { + return; + } + lines.push(`## ${name} Package`); + lines.push(''); + lines.push(classExamples.flat()); + lines.push(''); + lines.push(examples.flat()); + }); +}); + +for (const line of lines.flat()) { + log.write(`${line}\n`); +} + +log.end(); diff --git a/tsconfig.json b/tsconfig.json index 790a8f06..65095530 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,37 +1,14 @@ { - "compilerOptions": { - "sourceMap": true, - "removeComments": false, - "lib": [ - "ES2022" - ], + "$schema": "https://json.schemastore.org/tsconfig", - "strict": false, - "target": "ES2022", - "module": "CommonJS", - "moduleResolution": "node", - "esModuleInterop": true, - "skipLibCheck": true, - "allowJs": true, - "pretty": true, - "preserveSymlinks": true, - "resolveJsonModule": true, + "extends": "@tsconfig/node16/tsconfig.json", - "types": [ - "jest", - "node" - ], + "compilerOptions": { + "skipLibCheck": true, + "composite": true + }, - "noImplicitAny": false, - "noUnusedLocals": false, - - "declaration": true, - "composite": true, - "noEmit": false, - "baseUrl": "." - }, - - "ts-node": { - "esm": true - } + "ts-node": { + "esm": true + } } diff --git a/typedoc.base.json b/typedoc.base.json new file mode 100644 index 00000000..b336a5d2 --- /dev/null +++ b/typedoc.base.json @@ -0,0 +1,20 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "includeVersion": false, + "excludeExternals": true, + "cleanOutputDir": true, + "categorizeByGroup": true, + "navigation": { + "includeCategories": true, + "includeGroups": false + }, + "visibilityFilters": { + "protected": false, + "private": false, + "inherited": true, + "external": false, + "@alpha": false, + "@beta": false + }, + "groupOrder": ["Client"] +} diff --git a/typedoc.json b/typedoc.json new file mode 100644 index 00000000..45f54bd8 --- /dev/null +++ b/typedoc.json @@ -0,0 +1,15 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "includeVersion": false, + "entryPointStrategy": "packages", + "entryPoints": [ + "packages/*" + ], + "json": "docs/docs.json", + "out": "docs", + "logLevel": "Verbose", + "excludeInternal": true, + "plugin": [ + "typedoc-plugin-markdown" + ] +}