From c607f9360920e20dfbfb34084959b7c02886c6d7 Mon Sep 17 00:00:00 2001 From: Serhii Mamontov Date: Thu, 31 Oct 2024 00:45:52 +0200 Subject: [PATCH] fix(types): fix `Actions` type definition Fix definition of type which represent message actions received from history and list of users which added action of specific type and value to the message. Closes #407 refactor(types): remove indexed signature for publish Remove redundant indexed signature from publish message parameters type definition. Closes #413 refactor(types): add serializable objects to `Payload` type Extend `Payload` type definition with objects which can be serialized by `JSON.stringify` using `toJSON()` methods. Closes #412 refactor(types): aggregate generated types definitions Aggregate multiple types definitions into single type definition type with proper type names and namespaces. Closes #405 #409 #410 refactor(types): add missing Subscribe Event Engine types Add Subscribe Event Engine and Event Listener types to the bundled types definition file. Closes #377 --- .scripts/types-aggregate.config.json | 68 - .scripts/types-aggregate.ts | 862 +- dist/web/pubnub.js | 1499 ++- dist/web/pubnub.min.js | 4 +- dist/web/pubnub.worker.js | 8 + lib/core/components/configuration.js | 2 +- lib/core/components/push_payload.js | 2 +- lib/core/endpoints/subscribe.js | 4 - lib/core/interfaces/configuration.js | 7 +- lib/core/pubnub-common.js | 3 +- .../NodeCryptoModule/nodeCryptoModule.js | 22 +- lib/errors/pubnub-error.js | 2 - lib/node/index.js | 4 +- lib/transport/web-react-native-transport.js | 5 +- lib/types/cbor/common.d.ts | 6 - lib/types/core/components/abort_signal.d.ts | 9 - lib/types/core/components/base64_codec.d.ts | 6 - lib/types/core/components/configuration.d.ts | 6 - .../components/cryptography/hmac-sha256.d.ts | 3 - .../core/components/cryptography/index.d.ts | 6 - .../core/components/deduping_manager.d.ts | 6 - lib/types/core/components/eventEmitter.d.ts | 6 - .../core/components/listener_manager.d.ts | 76 - lib/types/core/components/push_payload.d.ts | 543 -- .../core/components/reconnection_manager.d.ts | 8 - lib/types/core/components/request.d.ts | 6 - .../components/stringify_buffer_keys.d.ts | 6 - lib/types/core/components/subject.d.ts | 6 - .../core/components/subscription-manager.d.ts | 6 - lib/types/core/components/token_manager.d.ts | 6 - lib/types/core/components/uuid.d.ts | 6 - lib/types/core/constants/categories.d.ts | 75 - lib/types/core/constants/operations.d.ts | 204 - .../core/endpoints/access_manager/audit.d.ts | 6 - .../core/endpoints/access_manager/grant.d.ts | 6 - .../endpoints/access_manager/grant_token.d.ts | 6 - .../access_manager/revoke_token.d.ts | 6 - .../endpoints/actions/add_message_action.d.ts | 6 - .../actions/get_message_actions.d.ts | 6 - .../actions/remove_message_action.d.ts | 6 - .../channel_groups/add_channels.d.ts | 6 - .../channel_groups/delete_group.d.ts | 6 - .../channel_groups/list_channels.d.ts | 6 - .../endpoints/channel_groups/list_groups.d.ts | 6 - .../channel_groups/remove_channels.d.ts | 6 - lib/types/core/endpoints/fetch_messages.d.ts | 6 - .../endpoints/file_upload/delete_file.d.ts | 6 - .../endpoints/file_upload/download_file.d.ts | 6 - .../file_upload/generate_upload_url.d.ts | 6 - .../endpoints/file_upload/get_file_url.d.ts | 6 - .../endpoints/file_upload/list_files.d.ts | 6 - .../endpoints/file_upload/publish_file.d.ts | 6 - .../core/endpoints/file_upload/send_file.d.ts | 6 - .../endpoints/file_upload/upload-file.d.ts | 6 - .../endpoints/history/delete_messages.d.ts | 6 - .../core/endpoints/history/get_history.d.ts | 6 - .../endpoints/history/message_counts.d.ts | 6 - .../core/endpoints/objects/channel/get.d.ts | 6 - .../endpoints/objects/channel/get_all.d.ts | 6 - .../endpoints/objects/channel/remove.d.ts | 6 - .../core/endpoints/objects/channel/set.d.ts | 6 - .../core/endpoints/objects/member/get.d.ts | 6 - .../core/endpoints/objects/member/set.d.ts | 6 - .../endpoints/objects/membership/get.d.ts | 6 - .../endpoints/objects/membership/set.d.ts | 6 - .../core/endpoints/objects/uuid/get.d.ts | 6 - .../core/endpoints/objects/uuid/get_all.d.ts | 6 - .../core/endpoints/objects/uuid/remove.d.ts | 6 - .../core/endpoints/objects/uuid/set.d.ts | 6 - .../core/endpoints/presence/get_state.d.ts | 6 - .../core/endpoints/presence/heartbeat.d.ts | 6 - .../core/endpoints/presence/here_now.d.ts | 6 - lib/types/core/endpoints/presence/leave.d.ts | 6 - .../core/endpoints/presence/set_state.d.ts | 6 - .../core/endpoints/presence/where_now.d.ts | 6 - lib/types/core/endpoints/publish.d.ts | 69 - .../endpoints/push/add_push_channels.d.ts | 6 - .../endpoints/push/list_push_channels.d.ts | 6 - lib/types/core/endpoints/push/push.d.ts | 6 - .../core/endpoints/push/remove_device.d.ts | 6 - .../endpoints/push/remove_push_channels.d.ts | 6 - lib/types/core/endpoints/signal.d.ts | 28 - lib/types/core/endpoints/subscribe.d.ts | 6 - .../subscriptionUtils/handshake.d.ts | 6 - .../subscriptionUtils/receiveMessages.d.ts | 6 - lib/types/core/endpoints/time.d.ts | 12 - lib/types/core/interfaces/configuration.d.ts | 276 - lib/types/core/interfaces/crypto-module.d.ts | 140 - lib/types/core/interfaces/cryptography.d.ts | 54 - lib/types/core/interfaces/request.d.ts | 1 - lib/types/core/interfaces/transport.d.ts | 61 - lib/types/core/pubnub-channel-groups.d.ts | 86 - lib/types/core/pubnub-common.d.ts | 1213 --- lib/types/core/pubnub-objects.d.ts | 283 - lib/types/core/pubnub-push.d.ts | 64 - lib/types/core/types/api/access-manager.d.ts | 464 - lib/types/core/types/api/app-context.d.ts | 875 -- lib/types/core/types/api/channel-groups.d.ts | 57 - lib/types/core/types/api/file-sharing.d.ts | 357 - lib/types/core/types/api/history.d.ts | 395 - lib/types/core/types/api/index.d.ts | 95 - lib/types/core/types/api/message-action.d.ts | 153 - lib/types/core/types/api/presence.d.ts | 210 - .../core/types/api/push-notifications.d.ts | 48 - lib/types/core/types/api/push.d.ts | 122 - lib/types/core/types/api/subscription.d.ts | 296 - lib/types/core/types/file.d.ts | 104 - lib/types/core/types/transport-request.d.ts | 97 - lib/types/core/types/transport-response.d.ts | 23 - lib/types/core/utils.d.ts | 6 - lib/types/crypto/index.d.ts | 0 .../modules/NodeCryptoModule/ICryptor.d.ts | 86 - .../NodeCryptoModule/ILegacyCryptor.d.ts | 60 - .../NodeCryptoModule/aesCbcCryptor.d.ts | 6 - .../NodeCryptoModule/legacyCryptor.d.ts | 6 - .../NodeCryptoModule/nodeCryptoModule.d.ts | 41 - lib/types/crypto/modules/node.d.ts | 6 - lib/types/entities/Channel.d.ts | 17 - lib/types/entities/ChannelGroup.d.ts | 18 - lib/types/entities/ChannelMetadata.d.ts | 18 - lib/types/entities/SubscribeCapable.d.ts | 86 - lib/types/entities/Subscription.d.ts | 14 - lib/types/entities/SubscriptionSet.d.ts | 53 - lib/types/entities/UserMetadata.d.ts | 18 - lib/types/entities/commonTypes.d.ts | 9 - lib/types/errors/pubnub-api-error.d.ts | 6 - lib/types/errors/pubnub-error.d.ts | 13 - lib/types/event-engine/core/change.d.ts | 6 - lib/types/event-engine/core/dispatcher.d.ts | 6 - lib/types/event-engine/core/engine.d.ts | 6 - lib/types/event-engine/core/handler.d.ts | 6 - lib/types/event-engine/core/index.d.ts | 6 - lib/types/event-engine/core/retryPolicy.d.ts | 64 - lib/types/event-engine/core/state.d.ts | 6 - lib/types/event-engine/core/types.d.ts | 6 - lib/types/event-engine/dispatcher.d.ts | 6 - lib/types/event-engine/effects.d.ts | 6 - lib/types/event-engine/events.d.ts | 6 - lib/types/event-engine/index.d.ts | 6 - .../event-engine/presence/dispatcher.d.ts | 6 - lib/types/event-engine/presence/effects.d.ts | 6 - lib/types/event-engine/presence/events.d.ts | 6 - lib/types/event-engine/presence/presence.d.ts | 6 - .../presence/states/heartbeat_cooldown.d.ts | 6 - .../presence/states/heartbeat_failed.d.ts | 6 - .../presence/states/heartbeat_inactive.d.ts | 6 - .../states/heartbeat_reconnecting.d.ts | 6 - .../presence/states/heartbeat_stopped.d.ts | 6 - .../presence/states/heartbeating.d.ts | 6 - .../event-engine/states/handshake_failed.d.ts | 6 - .../states/handshake_reconnecting.d.ts | 6 - .../states/handshake_stopped.d.ts | 6 - .../event-engine/states/handshaking.d.ts | 6 - .../event-engine/states/receive_failed.d.ts | 6 - .../states/receive_reconnecting.d.ts | 6 - .../event-engine/states/receive_stopped.d.ts | 6 - lib/types/event-engine/states/receiving.d.ts | 6 - .../event-engine/states/unsubscribed.d.ts | 6 - lib/types/file/modules/node.d.ts | 134 - lib/types/file/modules/react-native.d.ts | 135 - lib/types/index.d.ts | 8070 +++++++++++++++++ lib/types/models/Cursor.d.ts | 18 - lib/types/node/components/configuration.d.ts | 54 - lib/types/node/index.d.ts | 41 - lib/types/react_native/configuration.d.ts | 5 - lib/types/react_native/index.d.ts | 17 - lib/types/transport/middleware.d.ts | 6 - lib/types/transport/node-transport.d.ts | 6 - .../transport/web-react-native-transport.d.ts | 6 - package-lock.json | 29 +- package.json | 8 +- src/core/components/configuration.ts | 10 +- src/core/components/push_payload.ts | 2 +- src/core/components/subscription-manager.ts | 2 +- src/core/endpoints/fetch_messages.ts | 4 +- .../endpoints/file_upload/download_file.ts | 4 +- .../endpoints/file_upload/publish_file.ts | 4 +- src/core/endpoints/file_upload/send_file.ts | 4 +- src/core/endpoints/history/get_history.ts | 4 +- src/core/endpoints/publish.ts | 9 +- src/core/endpoints/signal.ts | 2 +- src/core/endpoints/subscribe.ts | 30 +- src/core/interfaces/configuration.ts | 14 +- src/core/interfaces/crypto-module.ts | 12 +- src/core/pubnub-common.ts | 11 +- src/core/types/api/file-sharing.ts | 6 +- src/core/types/api/history.ts | 2 +- src/core/types/api/index.ts | 10 +- src/core/types/api/message-action.ts | 2 +- src/core/types/api/push-notifications.ts | 2 +- src/core/types/api/subscription.ts | 4 +- .../modules/NodeCryptoModule/ICryptor.ts | 4 +- .../NodeCryptoModule/nodeCryptoModule.ts | 19 +- src/errors/pubnub-error.ts | 2 - src/node/components/configuration.ts | 4 +- src/node/index.ts | 9 +- src/transport/web-react-native-transport.ts | 5 +- src/web/components/configuration.ts | 4 +- test/integration/components/crypto.test.ts | 2 +- .../components/subscription_manager.test.ts | 22 +- 200 files changed, 10419 insertions(+), 8391 deletions(-) delete mode 100644 .scripts/types-aggregate.config.json delete mode 100644 lib/types/cbor/common.d.ts delete mode 100644 lib/types/core/components/abort_signal.d.ts delete mode 100644 lib/types/core/components/base64_codec.d.ts delete mode 100644 lib/types/core/components/configuration.d.ts delete mode 100644 lib/types/core/components/cryptography/hmac-sha256.d.ts delete mode 100644 lib/types/core/components/cryptography/index.d.ts delete mode 100644 lib/types/core/components/deduping_manager.d.ts delete mode 100644 lib/types/core/components/eventEmitter.d.ts delete mode 100644 lib/types/core/components/listener_manager.d.ts delete mode 100644 lib/types/core/components/push_payload.d.ts delete mode 100644 lib/types/core/components/reconnection_manager.d.ts delete mode 100644 lib/types/core/components/request.d.ts delete mode 100644 lib/types/core/components/stringify_buffer_keys.d.ts delete mode 100644 lib/types/core/components/subject.d.ts delete mode 100644 lib/types/core/components/subscription-manager.d.ts delete mode 100644 lib/types/core/components/token_manager.d.ts delete mode 100644 lib/types/core/components/uuid.d.ts delete mode 100644 lib/types/core/constants/categories.d.ts delete mode 100644 lib/types/core/constants/operations.d.ts delete mode 100644 lib/types/core/endpoints/access_manager/audit.d.ts delete mode 100644 lib/types/core/endpoints/access_manager/grant.d.ts delete mode 100644 lib/types/core/endpoints/access_manager/grant_token.d.ts delete mode 100644 lib/types/core/endpoints/access_manager/revoke_token.d.ts delete mode 100644 lib/types/core/endpoints/actions/add_message_action.d.ts delete mode 100644 lib/types/core/endpoints/actions/get_message_actions.d.ts delete mode 100644 lib/types/core/endpoints/actions/remove_message_action.d.ts delete mode 100644 lib/types/core/endpoints/channel_groups/add_channels.d.ts delete mode 100644 lib/types/core/endpoints/channel_groups/delete_group.d.ts delete mode 100644 lib/types/core/endpoints/channel_groups/list_channels.d.ts delete mode 100644 lib/types/core/endpoints/channel_groups/list_groups.d.ts delete mode 100644 lib/types/core/endpoints/channel_groups/remove_channels.d.ts delete mode 100644 lib/types/core/endpoints/fetch_messages.d.ts delete mode 100644 lib/types/core/endpoints/file_upload/delete_file.d.ts delete mode 100644 lib/types/core/endpoints/file_upload/download_file.d.ts delete mode 100644 lib/types/core/endpoints/file_upload/generate_upload_url.d.ts delete mode 100644 lib/types/core/endpoints/file_upload/get_file_url.d.ts delete mode 100644 lib/types/core/endpoints/file_upload/list_files.d.ts delete mode 100644 lib/types/core/endpoints/file_upload/publish_file.d.ts delete mode 100644 lib/types/core/endpoints/file_upload/send_file.d.ts delete mode 100644 lib/types/core/endpoints/file_upload/upload-file.d.ts delete mode 100644 lib/types/core/endpoints/history/delete_messages.d.ts delete mode 100644 lib/types/core/endpoints/history/get_history.d.ts delete mode 100644 lib/types/core/endpoints/history/message_counts.d.ts delete mode 100644 lib/types/core/endpoints/objects/channel/get.d.ts delete mode 100644 lib/types/core/endpoints/objects/channel/get_all.d.ts delete mode 100644 lib/types/core/endpoints/objects/channel/remove.d.ts delete mode 100644 lib/types/core/endpoints/objects/channel/set.d.ts delete mode 100644 lib/types/core/endpoints/objects/member/get.d.ts delete mode 100644 lib/types/core/endpoints/objects/member/set.d.ts delete mode 100644 lib/types/core/endpoints/objects/membership/get.d.ts delete mode 100644 lib/types/core/endpoints/objects/membership/set.d.ts delete mode 100644 lib/types/core/endpoints/objects/uuid/get.d.ts delete mode 100644 lib/types/core/endpoints/objects/uuid/get_all.d.ts delete mode 100644 lib/types/core/endpoints/objects/uuid/remove.d.ts delete mode 100644 lib/types/core/endpoints/objects/uuid/set.d.ts delete mode 100644 lib/types/core/endpoints/presence/get_state.d.ts delete mode 100644 lib/types/core/endpoints/presence/heartbeat.d.ts delete mode 100644 lib/types/core/endpoints/presence/here_now.d.ts delete mode 100644 lib/types/core/endpoints/presence/leave.d.ts delete mode 100644 lib/types/core/endpoints/presence/set_state.d.ts delete mode 100644 lib/types/core/endpoints/presence/where_now.d.ts delete mode 100644 lib/types/core/endpoints/publish.d.ts delete mode 100644 lib/types/core/endpoints/push/add_push_channels.d.ts delete mode 100644 lib/types/core/endpoints/push/list_push_channels.d.ts delete mode 100644 lib/types/core/endpoints/push/push.d.ts delete mode 100644 lib/types/core/endpoints/push/remove_device.d.ts delete mode 100644 lib/types/core/endpoints/push/remove_push_channels.d.ts delete mode 100644 lib/types/core/endpoints/signal.d.ts delete mode 100644 lib/types/core/endpoints/subscribe.d.ts delete mode 100644 lib/types/core/endpoints/subscriptionUtils/handshake.d.ts delete mode 100644 lib/types/core/endpoints/subscriptionUtils/receiveMessages.d.ts delete mode 100644 lib/types/core/endpoints/time.d.ts delete mode 100644 lib/types/core/interfaces/configuration.d.ts delete mode 100644 lib/types/core/interfaces/crypto-module.d.ts delete mode 100644 lib/types/core/interfaces/cryptography.d.ts delete mode 100644 lib/types/core/interfaces/request.d.ts delete mode 100644 lib/types/core/interfaces/transport.d.ts delete mode 100644 lib/types/core/pubnub-channel-groups.d.ts delete mode 100644 lib/types/core/pubnub-common.d.ts delete mode 100644 lib/types/core/pubnub-objects.d.ts delete mode 100644 lib/types/core/pubnub-push.d.ts delete mode 100644 lib/types/core/types/api/access-manager.d.ts delete mode 100644 lib/types/core/types/api/app-context.d.ts delete mode 100644 lib/types/core/types/api/channel-groups.d.ts delete mode 100644 lib/types/core/types/api/file-sharing.d.ts delete mode 100644 lib/types/core/types/api/history.d.ts delete mode 100644 lib/types/core/types/api/index.d.ts delete mode 100644 lib/types/core/types/api/message-action.d.ts delete mode 100644 lib/types/core/types/api/presence.d.ts delete mode 100644 lib/types/core/types/api/push-notifications.d.ts delete mode 100644 lib/types/core/types/api/push.d.ts delete mode 100644 lib/types/core/types/api/subscription.d.ts delete mode 100644 lib/types/core/types/file.d.ts delete mode 100644 lib/types/core/types/transport-request.d.ts delete mode 100644 lib/types/core/types/transport-response.d.ts delete mode 100644 lib/types/core/utils.d.ts delete mode 100644 lib/types/crypto/index.d.ts delete mode 100644 lib/types/crypto/modules/NodeCryptoModule/ICryptor.d.ts delete mode 100644 lib/types/crypto/modules/NodeCryptoModule/ILegacyCryptor.d.ts delete mode 100644 lib/types/crypto/modules/NodeCryptoModule/aesCbcCryptor.d.ts delete mode 100644 lib/types/crypto/modules/NodeCryptoModule/legacyCryptor.d.ts delete mode 100644 lib/types/crypto/modules/NodeCryptoModule/nodeCryptoModule.d.ts delete mode 100644 lib/types/crypto/modules/node.d.ts delete mode 100644 lib/types/entities/Channel.d.ts delete mode 100644 lib/types/entities/ChannelGroup.d.ts delete mode 100644 lib/types/entities/ChannelMetadata.d.ts delete mode 100644 lib/types/entities/SubscribeCapable.d.ts delete mode 100644 lib/types/entities/Subscription.d.ts delete mode 100644 lib/types/entities/SubscriptionSet.d.ts delete mode 100644 lib/types/entities/UserMetadata.d.ts delete mode 100644 lib/types/entities/commonTypes.d.ts delete mode 100644 lib/types/errors/pubnub-api-error.d.ts delete mode 100644 lib/types/errors/pubnub-error.d.ts delete mode 100644 lib/types/event-engine/core/change.d.ts delete mode 100644 lib/types/event-engine/core/dispatcher.d.ts delete mode 100644 lib/types/event-engine/core/engine.d.ts delete mode 100644 lib/types/event-engine/core/handler.d.ts delete mode 100644 lib/types/event-engine/core/index.d.ts delete mode 100644 lib/types/event-engine/core/retryPolicy.d.ts delete mode 100644 lib/types/event-engine/core/state.d.ts delete mode 100644 lib/types/event-engine/core/types.d.ts delete mode 100644 lib/types/event-engine/dispatcher.d.ts delete mode 100644 lib/types/event-engine/effects.d.ts delete mode 100644 lib/types/event-engine/events.d.ts delete mode 100644 lib/types/event-engine/index.d.ts delete mode 100644 lib/types/event-engine/presence/dispatcher.d.ts delete mode 100644 lib/types/event-engine/presence/effects.d.ts delete mode 100644 lib/types/event-engine/presence/events.d.ts delete mode 100644 lib/types/event-engine/presence/presence.d.ts delete mode 100644 lib/types/event-engine/presence/states/heartbeat_cooldown.d.ts delete mode 100644 lib/types/event-engine/presence/states/heartbeat_failed.d.ts delete mode 100644 lib/types/event-engine/presence/states/heartbeat_inactive.d.ts delete mode 100644 lib/types/event-engine/presence/states/heartbeat_reconnecting.d.ts delete mode 100644 lib/types/event-engine/presence/states/heartbeat_stopped.d.ts delete mode 100644 lib/types/event-engine/presence/states/heartbeating.d.ts delete mode 100644 lib/types/event-engine/states/handshake_failed.d.ts delete mode 100644 lib/types/event-engine/states/handshake_reconnecting.d.ts delete mode 100644 lib/types/event-engine/states/handshake_stopped.d.ts delete mode 100644 lib/types/event-engine/states/handshaking.d.ts delete mode 100644 lib/types/event-engine/states/receive_failed.d.ts delete mode 100644 lib/types/event-engine/states/receive_reconnecting.d.ts delete mode 100644 lib/types/event-engine/states/receive_stopped.d.ts delete mode 100644 lib/types/event-engine/states/receiving.d.ts delete mode 100644 lib/types/event-engine/states/unsubscribed.d.ts delete mode 100644 lib/types/file/modules/node.d.ts delete mode 100644 lib/types/file/modules/react-native.d.ts create mode 100644 lib/types/index.d.ts delete mode 100644 lib/types/models/Cursor.d.ts delete mode 100644 lib/types/node/components/configuration.d.ts delete mode 100644 lib/types/node/index.d.ts delete mode 100644 lib/types/react_native/configuration.d.ts delete mode 100644 lib/types/react_native/index.d.ts delete mode 100644 lib/types/transport/middleware.d.ts delete mode 100644 lib/types/transport/node-transport.d.ts delete mode 100644 lib/types/transport/web-react-native-transport.d.ts diff --git a/.scripts/types-aggregate.config.json b/.scripts/types-aggregate.config.json deleted file mode 100644 index 7c7050385..000000000 --- a/.scripts/types-aggregate.config.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "excluded": [ - { - "value": "node_modules", - "type": "path" - }, - { - "value": "proxy-agent", - "type": "path" - }, - { - "value": "agent-base", - "type": "path" - }, - { - "value": "http", - "type": "path" - }, - { - "value": "lru-cache", - "type": "path" - }, - { - "value": "net", - "type": "path" - }, - { - "value": "tls", - "type": "path" - }, - { - "value": "stream", - "type": "path" - }, - { - "value": "pac-proxy-agent", - "type": "path" - }, - { - "value": "url", - "type": "path" - }, - { - "value": "http-proxy-agent", - "type": "path" - }, - { - "value": "https-proxy-agent", - "type": "path" - }, - { - "value": "KeySet", - "type": "type" - }, - { - "value": "Payload", - "type": "type" - }, - { - "value": "Query", - "type": "type" - }, - { - "value": "", - "type": "function" - } - ] -} \ No newline at end of file diff --git a/.scripts/types-aggregate.ts b/.scripts/types-aggregate.ts index 5ad650bdb..b6f9c607f 100644 --- a/.scripts/types-aggregate.ts +++ b/.scripts/types-aggregate.ts @@ -1,125 +1,803 @@ +import { program } from 'commander'; import * as ts from 'typescript'; -import { ModuleKind } from 'typescript'; -import minimist from 'minimist'; +import prettier from 'prettier'; import * as fs from 'fs'; -import { builtinModules } from 'module'; +import path from 'path'; -interface ConfigurationExcluded { +// -------------------------------------------------------- +// ------------------------ Types ------------------------- +// -------------------------------------------------------- +// region Types + +type BaseSourceFileImport = { + /** Imported type name. */ value: string; - type: 'path' | 'type' | 'function'; -} + /** Name or path to the module from which type imported. */ + module: string; + /** Import statement. */ + statement: string; + /** Whether this is package type or not. */ + isPackageType: boolean; +}; + +/** Import created with type name and module path. */ +type NamedSourceFileImport = BaseSourceFileImport & { + /** Import type. */ + type: 'name'; +}; + +/** Import created as alias (namespace) to the `*` and module path. */ +type NamespacedSourceFileImport = BaseSourceFileImport & { + /** Import type. */ + type: 'namespace'; +}; + +/** Import created with type name, name as it imported into the code and module path. */ +type AliasedSourceFileImport = BaseSourceFileImport & { + /** Import type. */ + type: 'alias'; + /** Imported type alias name. */ + alias: string; +}; + +/** Package types imported in source file. */ +type SourceFileImport = NamedSourceFileImport | NamespacedSourceFileImport | AliasedSourceFileImport; +// endregion + +// -------------------------------------------------------- +// ---------------------- Helpers ------------------------- +// -------------------------------------------------------- +// region Helpers /** - * Types aggregator script configuration type. + * Load target project TS configuration. + * + * @param configurationPath - Path to the configuration file to load. + * + * @returns Parsed TS configuration file object. */ -interface Configuration { +const loadTSConfiguration = (configurationPath: string) => { + const configFile = ts.readConfigFile(configurationPath, ts.sys.readFile); + + if (configFile.error) { + throw new Error(`${path.basename(configurationPath)} load error: ${configFile.error.messageText}`); + } + + return ts.parseJsonConfigFileContent(configFile.config, ts.sys, path.dirname(configurationPath)); +}; + +/** + * Normalize path of resource relative to the file where it used. + * + * @param workingDirectory - Full path to the working directory. + * @param resourcePath - Source from which another resource accessed relatively. + * @param resourceRelativePath - Path to the target resource which is relative to the source. + * + * @returns Path to the target resource which is relative to the working directory. + */ +const relativeToWorkingDirectoryPath = ( + workingDirectory: string, + resourcePath: string, + resourceRelativePath: string, +) => { + const resourceFullPath = path.resolve(path.dirname(resourcePath), resourceRelativePath); + return `.${resourceFullPath.split(workingDirectory).pop()}`; +}; + +// endregion + +/** + * Project package. + * + * Package used to aggregate definition files in the working directory. + */ +class Package { + /** Package source files with types. */ + private readonly files: SourceFile[] = []; + /** - * List of resources which should be excluded from the aggregated type definition file. + * Create package bundle. + * + * Create package object which contains information about types used in public interface. + * + * @param name - Project name. + * @param workingDirectory - Root folder with subfolders which represent project structure and contains types definition files. + * @param tsConfiguration - Loaded project's TS configuration */ - excluded: ConfigurationExcluded[]; + constructor( + public readonly name: string, + private readonly workingDirectory: string, + private readonly tsConfiguration: ts.ParsedCommandLine, + ) { + this.processTypesInDirectory(workingDirectory); + } + + /** + * Retrieve list of type definition files identified for package. + * + * @returns List of type definition {@link SourceFile} instances. + */ + get typeSourceFiles(): SourceFile[] { + return this.files; + } + + /** + * Retrieve list of all external imports used in the project. + * + * @returns Map of imported module to the module information object. + */ + get externalImports(): Record { + const imports: Record = {}; + this.files.forEach((file) => + Object.entries(file.externalImports).forEach(([module, type]) => (imports[module] ??= type)), + ); + return imports; + } + + /** + * Retrieve source file information for file by its path. + * + * @param filePath - Path to the inside of the project. + * + * @returns SourceFile instance or `undefined` if it can't be found at specified path. + */ + sourceFileAtPath(filePath: string): SourceFile | undefined { + if (filePath.startsWith('./') || filePath.startsWith('../')) + filePath = path.resolve(this.workingDirectory, filePath); + + return this.files.find((file) => file.filePath === filePath); + } + + /** + * Process types in specified directory. + * + * @param directory - Directory inside which types and subfolder should be processed. + */ + private processTypesInDirectory(directory: string) { + if (!fs.existsSync(directory)) return; + + fs.readdirSync(directory).forEach((pathComponent) => { + const resourcePath = path.join(directory, pathComponent); + if (fs.statSync(resourcePath).isDirectory()) this.processTypesInDirectory(resourcePath); + else { + // TODO: IGNORE FILES IN A DIFFERENT WAY + if (pathComponent === 'hmac-sha256.d.ts') return; + if (!fs.existsSync(resourcePath)) return; + + // Filter out internal type definition placeholders. + const fileContent = fs.readFileSync(resourcePath, 'utf8'); + const internalModuleMatch = fileContent.match(/^\/\*\*[\s\S]*?@internal[\s\S]*?\*\//); + if (internalModuleMatch && internalModuleMatch.index !== undefined && internalModuleMatch.index === 0) return; + + this.files.push(new SourceFile(resourcePath, this.workingDirectory, this.tsConfiguration.options)); + } + }); + + // Gather type aliases. + const aliases: Record = {}; + this.files.forEach((file) => { + file.imports + .filter((typeImport) => typeImport.isPackageType && typeImport.type === 'alias') + .forEach((typeImport) => { + const { value, alias } = typeImport as AliasedSourceFileImport; + (aliases[value] ??= []).push(alias); + }); + }); + this.files.forEach((file) => { + file.types + .filter((type) => Object.keys(aliases).includes(type.name)) + .forEach((type) => aliases[type.name].forEach((alias) => type.addAlias(alias))); + }); + } } -// Parse script launch arguments -const args = minimist(process.argv.slice(2), { - string: ['config', 'input', 'output', 'namespace'], - default: { namespace: 'PubNub' }, -}); +/** + * Type definition file. + * + * Object contain information about types and imports declared in it. + */ +class SourceFile { + /** List of package type imports in source file */ + private readonly _imports: SourceFileImport[] = []; + private readonly _types: TypeDefinition[] = []; -// Processing input arguments. -const configFilePath = args.config; -const inputFilePath = args.input; -const outputFilePath = args.output; -const namespace = args.namespace; - -if (configFilePath === undefined || configFilePath.length === 0) throw new Error('Configuration file path is missing.'); -if (inputFilePath === undefined || inputFilePath.length === 0) throw new Error('Input file path is missing.'); -if (outputFilePath === undefined || outputFilePath.length === 0) throw new Error('Output file path is missing.'); -if (namespace === undefined || namespace.length === 0) throw new Error('Namespace is missing.'); - -const configuration: Configuration = JSON.parse(fs.readFileSync(configFilePath, 'utf8')); - -// Setting up TypeScript program. -const program = ts.createProgram([inputFilePath], { - target: ts.ScriptTarget.ES2020, - module: ts.ModuleKind.CommonJS, -}); - -const checker = program.getTypeChecker(); -const visited = new Set(); -let output = `declare namespace ${namespace} {\n\n`; - -const shouldExclude = (nodeName: string, type: ConfigurationExcluded['type']): boolean => { - return configuration.excluded - .filter((entry) => entry.type === type) - .some((entry) => new RegExp(`^${entry.value.replace('*', '.*')}$`).test(nodeName)); -}; + /** + * Create source file from type definition file in the package. + * + * @param filePath - Path to the type definition file which will be analyzed. + * @param workingDirectory - Root folder with subfolders which represent project structure and contains types definition files. + * @param tsCompileOptions - Package's TS parsed configuration object. + */ + constructor( + public readonly filePath: string, + private readonly workingDirectory: string, + private readonly tsCompileOptions: ts.CompilerOptions, + ) { + const source = this.tsSourceFile(); + this.processImports(source); + this.processTypes(source); + } -const getFormattedDocumentationFromNode = (node: ts.Node): string => { - const jsDocs = ts.getJSDocCommentsAndTags(node); + /** + * Retrieve list of imported types and modules. + * + * @returns List of import description objects with details about type and source file location. + */ + get imports() { + return this._imports; + } - // Reformat the documentation by adding leading * - const formattedDocs = jsDocs.map((doc) => { - return doc.getText(); - // const lines = doc - // .getText() - // .split('\n') - // .map((line) => `${line.trim()}`); - // return lines.join('\n'); - }); + /** + * Retrieve list of types imported from external dependencies. + * + * @returns List of import description objects with details about type and source file location. + */ + get externalImports() { + const imports: Record = {}; - return formattedDocs.join('\n'); -}; + this._imports + .filter((importedType) => !importedType.isPackageType) + .forEach((importedType) => { + imports[importedType.value] = importedType; + }); + + return imports; + } + + /** + * Retrieve list of types declared in this source file. + * + * @returns List of pre-processed type definition object instances. + */ + get types() { + return this._types; + } + + /** + * Retrieve type definition by its name. + * + * @param typeName - Name of the type for which type definition should be found. + * + * @returns Type definition object instance or `undefined` if specified type name is not part of source file. + */ + typeByName(typeName: string) { + return this._types.find((type) => type.name === typeName); + } + + /** + * Analyze source file imports for easier types processing during type definition files merge. + * + * @param sourceFile - TypeScript SourceFile object with pre-processed type definition file content. + */ + private processImports(sourceFile: ts.SourceFile) { + const storeImport = ( + type: SourceFileImport['type'], + module: string, + statement: string, + value: string, + alias?: string, + ) => { + const isPackageType = module.startsWith('./') || module.startsWith('../'); + if (isPackageType) module = relativeToWorkingDirectoryPath(this.workingDirectory, this.filePath, module); + if (type !== 'alias') this._imports.push({ type, value, module, statement, isPackageType }); + else if (alias) this._imports.push({ type, value, module, statement, isPackageType, alias }); + else throw new Error('Alias is required for alias import'); + }; + + ts.forEachChild(sourceFile, (node) => { + if (!ts.isImportDeclaration(node)) return; + const { importClause } = node; + if (!importClause) return; + + const moduleName = node.moduleSpecifier.getText(sourceFile).replace(/['"]/g, ''); + const statement = node.getText(sourceFile); + + // Process simple named import (import type specified with default export). + if (importClause.name) storeImport('name', moduleName, statement, importClause.name.getText(sourceFile)); + + // Check whether there is named binding specified for import or not. + const { namedBindings } = importClause; + if (!namedBindings) return; + + if (ts.isNamedImports(namedBindings)) { + namedBindings.elements.forEach((element) => { + const alias = element.name.getText(sourceFile); + const name = element.propertyName ? element.propertyName.getText(sourceFile) : alias; + if (name === alias) storeImport('name', moduleName, statement, name); + else storeImport('alias', moduleName, statement, name, alias); + }); + } else if (ts.isNamespaceImport(namedBindings) && namedBindings.name) { + storeImport('namespace', moduleName, statement, namedBindings.name.getText(sourceFile)); + } + }); + } + + /** + * Analyze source file types for easier types processing during type definition files merge. + * + * @param sourceFile - TypeScript SourceFile object with pre-processed type definition file content. + */ + private processTypes(sourceFile: ts.SourceFile) { + ts.forEachChild(sourceFile, (node) => { + if (!ts.isDeclarationStatement(node)) return; + if ( + !ts.isClassDeclaration(node) && + !ts.isInterfaceDeclaration(node) && + !ts.isTypeAliasDeclaration(node) && + !ts.isEnumDeclaration(node) + ) + return; + if (!node.name) return; + + // Stringify node type. + let type: TypeDefinition['type'] = 'type'; + if (ts.isClassDeclaration(node)) type = 'class'; + else if (ts.isInterfaceDeclaration(node)) type = 'interface'; + else if (ts.isEnumDeclaration(node)) type = 'enum'; -const visitNode = (node: ts.Node, sourceFile: ts.SourceFile) => { - if (ts.isImportDeclaration(node)) { - const importPath = (node.moduleSpecifier as ts.StringLiteral).text; + // Extract type documentation. + const jsDocComments = ts.getJSDocCommentsAndTags(node); + const documentation = jsDocComments.map((comment) => comment.getText(node.getSourceFile())).join('\n'); + this._types.push( + new TypeDefinition( + node.name.getText(sourceFile), + type, + this.tsSourceFile(`${documentation}\n${node.getText(sourceFile)}`), + ), + ); + }); + } + + /** + * Create TypeScript source file with same path as instance but potentially different content (if passed). + * + * @param content - Content which should be used for source file instance instead of current file content. + * @private + */ + private tsSourceFile(content?: string) { + content ??= fs.readFileSync(this.filePath, 'utf8'); - // Ignore Node.js native modules - // if (builtinModules.includes(importPath) || shouldExclude(importPath, 'path')) { - if (shouldExclude(importPath, 'path')) { - return; + // Ensure that `default export` will be carried with type definition to the resulting definition type. + if (content && /^export default\s[a-zA-Z]+;/gm.test(content)) { + const matchType = /^export default\s([a-zA-Z]+);/gm.exec(content); + if (matchType && matchType.length > 0) { + const replaceRegexp = new RegExp(`^((declare\\s)?(enum|class|type|interface)\\s${matchType[1]})`, 'gm'); + content = content.replace(replaceRegexp, `export $1`); + } } - console.log(`~~~~> MODULE: ${importPath}`); - - const resolvedModule = ts.resolveModuleName(importPath, sourceFile.fileName, program.getCompilerOptions(), ts.sys); - if (resolvedModule.resolvedModule) { - const importedFile = resolvedModule.resolvedModule.resolvedFileName; - if (!visited.has(importedFile)) { - visited.add(importedFile); - const importedSourceFile = program.getSourceFile(importedFile); - if (importedSourceFile) { - ts.forEachChild(importedSourceFile, (childNode) => visitNode(childNode, importedSourceFile)); + + return ts.createSourceFile(this.filePath, content, this.tsCompileOptions.target ?? ts.ScriptTarget.ES2015, true); + } +} + +/** + * Type definition from the source file. + */ +class TypeDefinition { + public readonly superclass?: string; + /** List of aliases under which type has been imported by other types. */ + private readonly aliases: string[] = []; + + constructor( + public readonly name: string, + public type: 'class' | 'interface' | 'type' | 'enum', + private readonly sourceFile: ts.SourceFile, + ) { + if (type === 'class') { + const match = sourceFile.getText(this.sourceFile).match(/class PubNub extends ([a-zA-Z]+)[\s|<]/) ?? []; + if (match.length > 1) this.superclass = match[1]; + } + } + + get filePath() { + return this.sourceFile.fileName; + } + + addAlias(alias: string) { + if (!this.aliases.includes(alias)) this.aliases.push(alias); + } + + toString(packageTypes: string[], namespace?: string): string { + const isPackageType = (type: string) => { + if (type.indexOf('.') === -1) return packageTypes.includes(type); + else return packageTypes.includes(type.split('.').pop()!); + }; + + const typeReferenceTransformer = (context: ts.TransformationContext) => { + const visit: ts.Visitor = (node) => { + let replacement: ts.TypeReferenceNode | ts.ExpressionWithTypeArguments | undefined; + + if (namespace && ts.isTypeReferenceNode(node) && isPackageType(node.typeName.getText(this.sourceFile))) { + const typeName = node.typeName.getText(this.sourceFile); + if (namespace) { + const reference = ts.factory.createQualifiedName(ts.factory.createIdentifier(namespace), typeName); + + replacement = ts.factory.createTypeReferenceNode( + reference, + node.typeArguments + ?.map((typeArg) => ts.visitNode(typeArg, visit)) + .filter((typeArg): typeArg is ts.TypeNode => typeArg !== undefined), + ); + } } - } + + if (ts.isTypeQueryNode(node)) { + if (namespace) { + const qualifiedName = ts.factory.createQualifiedName( + ts.factory.createIdentifier(namespace), + node.exprName as ts.Identifier, + ); + + return ts.factory.createTypeQueryNode(qualifiedName); + } + } + + // Checking whether processing superclass information or not. + if (node.parent && ts.isHeritageClause(node.parent) && ts.isExpressionWithTypeArguments(node)) { + const typeName = node.expression.getText(this.sourceFile); + if (namespace) { + let reference = node.expression; + if (this.superclass !== typeName) { + reference = ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(namespace), typeName); + } + + replacement = ts.factory.createExpressionWithTypeArguments( + reference, + node.typeArguments + ?.map((typeArg) => ts.visitNode(typeArg, visit)) + .filter((typeArg): typeArg is ts.TypeNode => typeArg !== undefined), + ); + } + } + + return replacement ?? ts.visitEachChild(node, visit, context); + }; + + return (node: T): T => ts.visitNode(node, visit) as T; + }; + + const aliasedTypeStrings: string[] = []; + if (this.aliases.length > 0) { + const matches = this.sourceFile.getText(this.sourceFile).match(/^(\s*(export\s+)?(declare\s+)?(type|class)\s)/gm); + if (!matches) throw new Error(`Unable to match prefix for '${this.name}' ${this.type}`); + + this.aliases.forEach((alias) => { + if (this.type === 'class' || this.type === 'interface' || this.type === 'enum') + aliasedTypeStrings.push(`/** Re-export aliased type. */\nexport {${this.name} as ${alias}};\n`); + else aliasedTypeStrings.push(`${matches[0]}${alias} = ${this.name};`); + }); + } + + const transformed = ts.transform(this.sourceFile, [typeReferenceTransformer]); + const formatted = ts.createPrinter().printFile(transformed.transformed[0] as ts.SourceFile); + return aliasedTypeStrings.length === 0 ? formatted : `${formatted}\n${aliasedTypeStrings.join('\n')}`; + } +} + +class PackageTypesDefinition { + /** Types grouped by namespaces. */ + private readonly namespaces: Record = {}; + /** List of type names which is defined by package. */ + private readonly packageTypes: string[] = []; + /** List of type names which already has been added to the output. */ + private writtenTypes: string[] = []; + private writingPackageNamespace: boolean = false; + + /** + * Create package types definition. + * + * Responsible for merged types definition generation. + * + * @param projectPackage - Project package object with types information. + * @param workingDirectory - Root folder with subfolders which represent project structure and contains types definition files. + * @param entryPoint - Path to the source file which is package's entry point and source of the public interface. + */ + constructor( + private readonly projectPackage: Package, + private readonly workingDirectory: string, + private readonly entryPoint: string, + ) {} + + writeToFile(filePath: string) { + this.writingPackageNamespace = false; + const resultContent: string[] = []; + this.writtenTypes = []; + + this.associateTypesWithNamespaces(); + this.addExternalImports(resultContent); + + // Retrieve reference to the entry point source file. + const entryPoint = this.projectPackage.sourceFileAtPath(this.entryPoint); + if (!entryPoint) throw new Error(`Can't load type for entry point at path: ${this.entryPoint}`); + + // Identify and add root types. + entryPoint.types.forEach((type) => { + this.addTypeDefinition(type, resultContent, this.projectPackage.name); + + if (type.type !== 'class' || !type.superclass) return; + + const superClassImport = entryPoint.imports.find( + (importType) => importType.isPackageType && importType.value === type.superclass, + ); + if (!superClassImport) return; + + const sourceFile = this.sourceFileForModule(superClassImport.module); + if (!sourceFile) return; + + const superclassType = sourceFile.typeByName(superClassImport.value); + if (superclassType) this.addTypeDefinition(superclassType, resultContent, this.projectPackage.name); + }); + + this.writingPackageNamespace = true; + resultContent.push(`declare namespace ${this.projectPackage.name} {`); + + this.typeSourceFiles + .filter((sourceFile) => sourceFile !== entryPoint) + .forEach((sourceFile) => { + sourceFile.types.forEach((type) => { + this.addTypeDefinition(type, resultContent); + }); + }); + + for (const namespace in this.namespaces) { + resultContent.push(`export namespace ${namespace} {`); + this.namespaces[namespace].forEach((type) => { + // Try to retrieve proper source file for imported module. + const sourceFile = this.sourceFileForModule(type.file); + if (!sourceFile) return; + + const typeDefinition = sourceFile.typeByName(type.type); + if (typeDefinition) this.addTypeDefinition(typeDefinition, resultContent, undefined, true); + // if (typeDefinition) this.addTypeDefinition(typeDefinition, resultContent, namespace, true); + }); + resultContent.push(`}\n\n`); } + + resultContent.push(`}\n\nexport = ${this.projectPackage.name}`); + + prettier + .format(resultContent.join('\n'), { + parser: 'typescript', + semi: true, + printWidth: 120, + singleQuote: true, + trailingComma: 'all', + }) + .then((result) => { + fs.writeFileSync(filePath, result, 'utf-8'); + }); + } + + /** + * Retrieve list of type source files which is specific to the entry point. + */ + private get typeSourceFiles() { + const files: SourceFile[] = []; + const entryPoint = this.sourceFileForModule(this.entryPoint); + if (!entryPoint) throw new Error(`Can't load type for entry point at path: ${this.entryPoint}`); + + const flattenImportedTypes = (sourceFile: SourceFile) => { + sourceFile.imports + .filter((importType) => importType.isPackageType) + .forEach((type) => { + const importedTypeSourceFile = this.sourceFileForModule(type.module); + if (!importedTypeSourceFile) { + console.warn( + `Source file for ${type.module} is missing. File can be ignored as internal, but import is still there.`, + ); + return; + } + + if (!files.includes(importedTypeSourceFile)) { + files.push(importedTypeSourceFile); + flattenImportedTypes(importedTypeSourceFile); + } + }); + }; + flattenImportedTypes(entryPoint); + + return files; + } + + /** + * Aggregate types into corresponding namespaces. + * + * Some types can be imported and used through namespace import syntax and this function allows to bind types to the corresponding namespace. + * + * @returns Record where list of types (name and file path) stored under namespace name as key. + */ + private associateTypesWithNamespaces() { + const project = this.projectPackage; + const namespacedTypes: string[] = []; + + project.typeSourceFiles.forEach((file) => { + file.types.forEach((type) => !this.packageTypes.includes(type.name) && this.packageTypes.push(type.name)); + }); + + project.typeSourceFiles.forEach((file) => { + file.imports + .filter((fileImport) => fileImport.isPackageType) + .forEach((fileImport) => { + if (fileImport.type === 'namespace') { + if (namespacedTypes.includes(fileImport.module)) return; + + // Try to retrieve proper source file for imported module. + const sourceFile = this.sourceFileForModule(fileImport.module); + if (!sourceFile) return; + + namespacedTypes.push(fileImport.module); + sourceFile.types.forEach((sourceFileType) => { + this.namespaces[fileImport.value] = this.namespaces[fileImport.value] ?? []; + this.namespaces[fileImport.value].push({ type: sourceFileType.name, file: fileImport.module }); + }); + } else if (namespacedTypes.includes(fileImport.module)) { + throw new Error(`${fileImport.module} already added as namespace and can't be used separately.`); + } + }); + }); + } + + /** + * Adding external imports required for the package. + * + * @param result - Types definition output lines. + */ + private addExternalImports(result: string[]) { + Object.entries(this.projectPackage.externalImports).forEach(([_, typeImport]) => { + if (!result.includes(typeImport.statement)) result.push(typeImport.statement); + }); + + if (result.length > 1) result.push('\n\n'); + } + + private addPackageImports(imports: SourceFileImport[], result: string[]) { + const processedSourceFiles: SourceFile[] = []; + + imports + .filter((fileImport) => fileImport.isPackageType) + .forEach((type) => { + // Try to retrieve proper source file for imported module. + const sourceFile = this.sourceFileForModule(type.module); + if (!sourceFile) return; + + const typeDefinition = sourceFile.typeByName(type.value); + if (typeDefinition) this.addTypeDefinition(typeDefinition, result); + processedSourceFiles.push(sourceFile); + }); + + processedSourceFiles.forEach((sourceFile) => this.addPackageImports(sourceFile.imports, result)); } - if (ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node) || ts.isClassDeclaration(node)) { - const nodeName = node.name?.getText(); + private addTypeDefinition( + typeDefinition: TypeDefinition, + result: string[], + namespace?: string, + skipNamespaceCheck: boolean = false, + ) { + const typesCacheId = `${typeDefinition.name}-${typeDefinition.filePath}`; + // Check whether type already has been added to the output or not. + if (this.writtenTypes.includes(typesCacheId)) return; + // Check whether namespace member has been added without namespace name. + if (!skipNamespaceCheck && this.isNamespaceMember(typeDefinition)) return; + + let definition = typeDefinition.toString(this.packageTypes, namespace); + + if (this.writingPackageNamespace) { + definition = definition.replace(/\bexport\s+(default\s+)?class\s+/gm, `export class `); + definition = definition.replace(/\bdeclare\s+class\s+/gm, `class `); + definition = definition.replace(/\bexport\s+declare\s+enum\s+/gm, `export enum `); + definition = definition.replace(/\bexport\s+declare\s+abstract\s+class\s+/gm, `export abstract class `); + } else definition = definition.replace(/\bexport\s+declare/g, 'declare'); + + result.push(definition); + + this.writtenTypes.push(typesCacheId); + } - if (nodeName && !shouldExclude(nodeName, 'type') && node.name) { - console.log(`~~~~> ${node.name.text}`); - const symbol = checker.getSymbolAtLocation(node.name); - if (symbol) { - const documentation = getFormattedDocumentationFromNode(node); - const typeString = node.getText(); + /** + * Retrieve module source file. + * + * @param modulePath - Relative path to the module (relative to the working directory). + */ + private sourceFileForModule(modulePath: string) { + const project = this.projectPackage; - output += ` ${documentation ? `${documentation}\n ` : ''}${typeString}\n\n`; + // Try to retrieve proper source file for imported module. + let sourceFile = project.sourceFileAtPath(modulePath); + if (!sourceFile && path.extname(modulePath).length === 0) { + sourceFile = project.sourceFileAtPath(`${modulePath}.d.ts`); + if (!sourceFile) { + let updatedPath = path.join(modulePath, 'index.d.ts'); + if ((modulePath.startsWith('./') || modulePath.startsWith('../')) && !updatedPath.startsWith('.')) + updatedPath = `./${updatedPath}`; + sourceFile = project.sourceFileAtPath(updatedPath); } } + + if (!sourceFile) { + console.warn( + `Source file for ${modulePath} is missing. File can be ignored as internal, but import is still there.`, + ); + } + + return sourceFile; } - ts.forEachChild(node, (childNode) => visitNode(childNode, sourceFile)); -}; + /** + * Check whether specified type is member of any known namespaces. + * + * @param typeDefinition - Type definition which should be checked. + * @returns `true` in case if type has been associated with one of the namespaces. + */ + private isNamespaceMember(typeDefinition: TypeDefinition) { + if (Object.keys(this.namespaces).length === 0) return false; + + // Normalize type source file path. + const extensionMatch = new RegExp(`(.d.ts|${path.extname(typeDefinition.filePath)})$`); + let typeFilePath = typeDefinition.filePath.replace(extensionMatch, ''); + if (!typeFilePath.startsWith('./') && !typeFilePath.startsWith('../')) + typeFilePath = `.${typeFilePath.split(this.workingDirectory).pop()!}`; + + for (const name in this.namespaces) { + const namespace = this.namespaces[name]; + if (namespace.find((type) => type.type === typeDefinition.name && type.file === typeFilePath)) return true; + } -// Process entry point and all related public interfaces. -const sourceFile = program.getSourceFile(inputFilePath); -if (sourceFile && !shouldExclude(inputFilePath, 'path')) { - ts.forEachChild(sourceFile, (node) => visitNode(node, sourceFile)); + return false; + } +} + +export function syntaxKindToName(kind: ts.SyntaxKind) { + return (ts).SyntaxKind[kind]; } -output += '}\n'; +// -------------------------------------------------------- +// -------------------- Configuration ---------------------- +// -------------------------------------------------------- +// region Configuration + +// Parse script launch arguments +const options = program + .option('--package ', 'Name of the package to aggregate types for.') + .option('--working-dir ', 'Path to the processed definition type files root directory.') + .option('--input ', 'Path to the main type definition file.') + .option('--output ', 'Path to the folder or filepath where aggregated type definition file should be saved.') + .option('--ts-config ', "Path to the project's tsconfig.json file.") + .parse() + .opts(); + +if (options.package === undefined || options.package.length === 0) throw new Error('Package file is missing.'); +if (options.workingDir === undefined || options.workingDir.length === 0) + throw new Error('Working directory is missing.'); +if (options.input === undefined || options.input.length === 0) throw new Error('Entry point file is missing.'); +if (options.output === undefined || options.output.length === 0) throw new Error('Output file is missing.'); +if (options.tsConfig === undefined || options.tsConfig.length === 0) throw new Error('tsconfig.json file is missing.'); + +const fullPathFromRelative = (relativePath: string) => + /^(.\/|..\/)/.test(relativePath) ? path.resolve(process.cwd(), relativePath) : relativePath; + +// Processing input arguments. +const packageName = options.package; +const workingDir = fullPathFromRelative(options.workingDir); +const tsConfigFilePath = fullPathFromRelative(options.tsConfig); +const inputFilePath = fullPathFromRelative(options.input); +let outputFilePath = fullPathFromRelative(options.output); +if (path.extname(outputFilePath).length === 0) + outputFilePath = path.resolve(outputFilePath, inputFilePath.split('/').pop()!); + +// endregion + +// -------------------------------------------------------- +// --------------------- Processing ----------------------- +// -------------------------------------------------------- + +const projectPackage = new Package(packageName, workingDir, loadTSConfiguration(tsConfigFilePath)); +const entryPointSourceFile = projectPackage.sourceFileAtPath(inputFilePath); +if (!entryPointSourceFile) throw new Error('Entry point source file not found.'); -fs.writeFileSync(outputFilePath, output, 'utf8'); +// Files loaded into the project. Clean up working directory. +fs.rmSync(workingDir, { recursive: true, force: true }); +fs.mkdirSync(workingDir); -console.log(`Aggregated types saved to ${outputFilePath}`); +const definition = new PackageTypesDefinition(projectPackage, workingDir, inputFilePath); +definition.writeToFile(outputFilePath); diff --git a/dist/web/pubnub.js b/dist/web/pubnub.js index 45fefd7dd..d2a828fa0 100644 --- a/dist/web/pubnub.js +++ b/dist/web/pubnub.js @@ -410,9 +410,7 @@ var obj = { encode: encode, decode: decode }; - if (typeof undefined$1 === "function" && undefined$1.amd) - undefined$1("cbor/cbor", obj); - else if (module.exports) + if (module.exports) module.exports = obj; else if (!global.CBOR) global.CBOR = obj; @@ -514,6 +512,8 @@ // region Helpers /** * Retrieve list of module's cryptors. + * + * @internal */ getAllCryptors() { return [this.defaultCryptor, ...this.cryptors]; @@ -521,10 +521,14 @@ } /** * `String` to {@link ArrayBuffer} response decoder. + * + * @internal */ AbstractCryptoModule.encoder = new TextEncoder(); /** * {@link ArrayBuffer} to {@link string} decoder. + * + * @internal */ AbstractCryptoModule.decoder = new TextDecoder(); @@ -695,6 +699,11 @@ */ PubNubFile.supportsFileUri = false; + /** + * Base64 support module. + * + * @internal + */ const BASE64_CHARMAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; /** * Decode a Base64 encoded string. @@ -874,7 +883,25 @@ })(StatusCategory || (StatusCategory = {})); var StatusCategory$1 = StatusCategory; + /** + * PubNub operation error module. + */ + /** + * PubNub operation error. + * + * When an operation can't be performed or there is an error from the server, this object will be returned. + */ class PubNubError extends Error { + /** + * Create PubNub operation error. + * + * @param message - Message with details about why operation failed. + * @param [status] - Additional information about performed operation. + * + * @returns Configured and ready to use PubNub operation error. + * + * @internal + */ constructor(message, status) { super(message); this.status = status; @@ -883,15 +910,40 @@ Object.setPrototypeOf(this, new.target.prototype); } } + /** + * Create error status object. + * + * @param errorPayload - Additional information which should be attached to the error status object. + * + * @returns Error status object. + * + * @internal + */ function createError(errorPayload) { var _a; (_a = errorPayload.statusCode) !== null && _a !== void 0 ? _a : (errorPayload.statusCode = 0); return Object.assign(Object.assign({}, errorPayload), { statusCode: errorPayload.statusCode, category: StatusCategory$1.PNValidationErrorCategory, error: true }); } + /** + * Create operation arguments validation error status object. + * + * @param message - Information about failed validation requirement. + * @param [statusCode] - Operation HTTP status code. + * + * @returns Operation validation error status object. + * + * @internal + */ function createValidationError(message, statusCode) { - return createError(Object.assign({ message }, (statusCode !== undefined ? { statusCode } : {}))); + return createError(Object.assign({ message }, ({}))); } + /** + * CryptoJS implementation. + * + * @internal + */ + /*eslint-disable */ /* @@ -1935,6 +1987,8 @@ /** * Legacy cryptography module. + * + * @internal */ /** * Convert bytes array to words array. @@ -1942,6 +1996,8 @@ * @param b - Bytes array (buffer) which should be converted. * * @returns Word sized array. + * + * @internal */ /* eslint-disable @typescript-eslint/no-explicit-any */ function bufferToWordArray(b) { @@ -1953,6 +2009,11 @@ // @ts-expect-error Bundled library without types. return CryptoJS$1.lib.WordArray.create(wa, b.length); } + /** + * Legacy cryptography module for files and signature. + * + * @internal + */ class Crypto { constructor(configuration) { this.configuration = configuration; @@ -2201,18 +2262,16 @@ } } - /* global crypto */ /** * Legacy browser cryptography module. + * + * @internal */ - function concatArrayBuffer(ab1, ab2) { - const tmp = new Uint8Array(ab1.byteLength + ab2.byteLength); - tmp.set(new Uint8Array(ab1), 0); - tmp.set(new Uint8Array(ab2), ab1.byteLength); - return tmp.buffer; - } + /* global crypto */ /** * Legacy cryptography implementation for browser-based {@link PubNub} client. + * + * @internal */ class WebCryptography { // -------------------------------------------------------- @@ -2248,7 +2307,7 @@ encryptArrayBuffer(key, buffer) { return __awaiter(this, void 0, void 0, function* () { const abIv = crypto.getRandomValues(new Uint8Array(16)); - return concatArrayBuffer(abIv.buffer, yield crypto.subtle.encrypt({ name: 'AES-CBC', iv: abIv }, key, buffer)); + return this.concatArrayBuffer(abIv.buffer, yield crypto.subtle.encrypt({ name: 'AES-CBC', iv: abIv }, key, buffer)); }); } /** @@ -2264,7 +2323,7 @@ const abIv = crypto.getRandomValues(new Uint8Array(16)); const abPlaintext = WebCryptography.encoder.encode(text).buffer; const abPayload = yield crypto.subtle.encrypt({ name: 'AES-CBC', iv: abIv }, key, abPlaintext); - const ciphertext = concatArrayBuffer(abIv.buffer, abPayload); + const ciphertext = this.concatArrayBuffer(abIv.buffer, abPayload); return WebCryptography.decoder.decode(ciphertext); }); } @@ -2397,6 +2456,20 @@ return crypto.subtle.importKey('raw', abKey, 'AES-CBC', true, ['encrypt', 'decrypt']); }); } + /** + * Join two `ArrayBuffer`s. + * + * @param ab1 - `ArrayBuffer` to which other buffer should be appended. + * @param ab2 - `ArrayBuffer` which should appended to the other buffer. + * + * @returns Buffer which starts with `ab1` elements and appended `ab2`. + */ + concatArrayBuffer(ab1, ab2) { + const tmp = new Uint8Array(ab1.byteLength + ab2.byteLength); + tmp.set(new Uint8Array(ab1), 0); + tmp.set(new Uint8Array(ab2), ab1.byteLength); + return tmp.buffer; + } } /** * Random initialization vector size. @@ -2785,9 +2858,13 @@ /** * REST API endpoint use error module. + * + * @internal */ /** * PubNub REST API call error. + * + * @internal */ class PubNubAPIError extends Error { /** @@ -2981,6 +3058,8 @@ * * Middleware optimize subscription feature requests utilizing `Subscription Worker` if available and not disabled * by user. + * + * @internal */ // endregion /** @@ -3203,6 +3282,11 @@ } } + /** + * PubNub package utilities module. + * + * @internal + */ /** * Percent-encode input string. * @@ -3211,6 +3295,8 @@ * @param input - Source string or number for encoding. * * @returns Percent-encoded string. + * + * @internal */ const encodeString = (input) => { return encodeURIComponent(input).replace(/[!~*'()]/g, (x) => `%${x.charCodeAt(0).toString(16).toUpperCase()}`); @@ -3223,11 +3309,16 @@ * @param [defaultString] - String which should be used in case if {@link names} is empty. * * @returns String which contains encoded names joined by non-encoded `,`. + * + * @internal */ const encodeNames = (names, defaultString) => { const encodedNames = names.map((name) => encodeString(name)); return encodedNames.length ? encodedNames.join(',') : defaultString !== null && defaultString !== void 0 ? defaultString : ''; }; + /** + * @internal + */ const removeSingleOccurrence = (source, elementsToRemove) => { const removed = Object.fromEntries(elementsToRemove.map((prop) => [prop, false])); return source.filter((e) => { @@ -3238,6 +3329,9 @@ return true; }); }; + /** + * @internal + */ const findUniqueCommonElements = (a, b) => { return [...a].filter((value) => b.includes(value) && a.indexOf(value) === a.lastIndexOf(value) && b.indexOf(value) === b.lastIndexOf(value)); }; @@ -3247,6 +3341,8 @@ * @param query - Key / value pairs of the request query parameters. * * @returns Stringified query key / value pairs. + * + * @internal */ const queryStringFromObject = (query) => { return Object.keys(query) @@ -3261,11 +3357,23 @@ /** * Common browser and React Native Transport provider module. + * + * @internal */ /** * Class representing a `fetch`-based browser and React Native transport provider. + * + * @internal */ class WebReactNativeTransport { + /** + * Create and configure transport provider for Web and Rect environments. + * + * @param [keepAlive] - Whether client should try to keep connections open for reuse or not. + * @param logVerbosity - Whether verbose logs should be printed or not. + * + * @internal + */ constructor(keepAlive = false, logVerbosity) { this.keepAlive = keepAlive; this.logVerbosity = logVerbosity; @@ -3297,7 +3405,10 @@ reject(new Error('Request timeout')); }, req.timeout * 1000); }); - return Promise.race([fetch(request, { signal: abortController === null || abortController === void 0 ? void 0 : abortController.signal }), requestTimeout]) + return Promise.race([ + fetch(request, { signal: abortController === null || abortController === void 0 ? void 0 : abortController.signal, credentials: 'omit', cache: 'no-cache' }), + requestTimeout, + ]) .then((response) => response.arrayBuffer().then((arrayBuffer) => [response, arrayBuffer])) .then((response) => { const responseBody = response[1].byteLength > 0 ? response[1] : undefined; @@ -3332,6 +3443,8 @@ * @param req - The {@link TransportRequest} object containing request information. * * @returns Request object generated from the {@link TransportRequest} object. + * + * @internal */ requestFromTransportRequest(req) { return __awaiter(this, void 0, void 0, function* () { @@ -3378,6 +3491,8 @@ * @param request - Platform-specific * @param [elapsed] - How many seconds passed since request processing started. * @param [body] - Service response (if available). + * + * @internal */ logRequestProcessProgress(request, elapsed, body) { if (!this.logVerbosity) @@ -3399,9 +3514,16 @@ } /** * Service {@link ArrayBuffer} response decoder. + * + * @internal */ WebReactNativeTransport.decoder = new TextDecoder(); + /** + * CBOR support module. + * + * @internal + */ /** * Re-map CBOR object keys from potentially C buffer strings to actual strings. * @@ -3572,7 +3694,7 @@ let announceFailedHeartbeats = ANNOUNCE_HEARTBEAT_FAILURE; let fileUploadPublishRetryLimit = FILE_PUBLISH_RETRY_LIMIT; let dedupeOnSubscribe = DEDUPE_ON_SUBSCRIBE; - const maximumCacheSize = DEDUPE_CACHE_SIZE; + let maximumCacheSize = DEDUPE_CACHE_SIZE; let useRequestId = USE_REQUEST_ID; // @ts-expect-error Not documented legacy configuration options. if (configurationCopy.dedupeOnSubscribe !== undefined && typeof configurationCopy.dedupeOnSubscribe === 'boolean') { @@ -3580,6 +3702,11 @@ dedupeOnSubscribe = configurationCopy.dedupeOnSubscribe; } // @ts-expect-error Not documented legacy configuration options. + if (configurationCopy.maximumCacheSize !== undefined && typeof configurationCopy.maximumCacheSize === 'number') { + // @ts-expect-error Not documented legacy configuration options. + maximumCacheSize = configurationCopy.maximumCacheSize; + } + // @ts-expect-error Not documented legacy configuration options. if (configurationCopy.useRequestId !== undefined && typeof configurationCopy.useRequestId === 'boolean') { // @ts-expect-error Not documented legacy configuration options. useRequestId = configurationCopy.useRequestId; @@ -3701,6 +3828,12 @@ var uuidExports = uuid.exports; var uuidGenerator$1 = /*@__PURE__*/getDefaultExportFromCjs(uuidExports); + /** + * Random identifier generator helper module. + * + * @internal + */ + /** @internal */ var uuidGenerator = { createUUID() { if (uuidGenerator$1.uuid) { @@ -3713,6 +3846,8 @@ /** * {@link PubNub} client configuration module. + * + * @internal */ // -------------------------------------------------------- // ----------------------- Defaults ----------------------- @@ -3728,7 +3863,7 @@ * Create {@link PubNub} client private configuration object. * * @param base - User- and platform-provided configuration. - * @param setupCryptoModule - Platform-provided {@link CryptoModule} configuration block. + * @param setupCryptoModule - Platform-provided {@link ICryptoModule} configuration block. * * @returns `PubNub` client private configuration. * @@ -3868,6 +4003,8 @@ /** * PubNub Access Token Manager module. + * + * @internal */ // endregion /** @@ -4033,6 +4170,11 @@ TransportMethod["LOCAL"] = "LOCAL"; })(TransportMethod || (TransportMethod = {})); + /** + * Common PubNub Network Provider middleware module. + * + * @internal + */ /** * Request signature generator. * @@ -4092,6 +4234,11 @@ } } RequestSignature.textDecoder = new TextDecoder('utf-8'); + /** + * Common PubNub Network Provider middleware. + * + * @internal + */ class PubNubMiddleware { constructor(configuration) { this.configuration = configuration; @@ -4360,6 +4507,8 @@ * Subscription reconnection-manager. * * **Note:** Reconnection manger rely on legacy time-based availability check. + * + * @internal */ /** * Network "discovery" manager. @@ -4405,59 +4554,85 @@ } } - /* */ - - const hashCode = (payload) => { - let hash = 0; - if (payload.length === 0) return hash; - for (let i = 0; i < payload.length; i += 1) { - const character = payload.charCodeAt(i); - hash = (hash << 5) - hash + character; // eslint-disable-line - hash = hash & hash; // eslint-disable-line - } - return hash; - }; - + /** + * Messages de-duplication manager module. + * + * @internal + */ /** * Real-time events deduplication manager. * * @internal */ class DedupingManager { - _config; - - hashHistory; - - constructor({ config }) { - this.hashHistory = []; - this._config = config; - } - - getKey(message) { - const hashedPayload = hashCode(JSON.stringify(message.message)).toString(); - const timetoken = message.timetoken; - return `${timetoken}-${hashedPayload}`; - } - - isDuplicate(message) { - return this.hashHistory.includes(this.getKey(message)); - } - - addEntry(message) { - if (this.hashHistory.length >= this._config.maximumCacheSize) { - this.hashHistory.shift(); + /** + * Create and configure real-time events de-duplication manager. + * + * @param config - PubNub client configuration object. + */ + constructor({ maximumCacheSize }) { + this.maximumCacheSize = maximumCacheSize; + this.hashHistory = []; + } + /** + * Compute unique real-time event payload key. + * + * @param message - Received real-time event payload for which unique key should be computed. + * @returns Unique real-time event payload key in messages cache. + */ + getKey(message) { + var _a; + return `${message.timetoken}-${this.hashCode(JSON.stringify((_a = message.message) !== null && _a !== void 0 ? _a : '')).toString()}`; + } + /** + * Check whether there is similar message already received or not. + * + * @param message - Received real-time event payload which should be checked for duplicates. + * @returns `true` in case if similar payload already has been received before. + */ + isDuplicate(message) { + return this.hashHistory.includes(this.getKey(message)); + } + /** + * Store received message to be used later for duplicate detection. + * + * @param message - Received real-time event payload. + */ + addEntry(message) { + if (this.hashHistory.length >= this.maximumCacheSize) { + this.hashHistory.shift(); + } + this.hashHistory.push(this.getKey(message)); + } + /** + * Clean up cached messages. + */ + clearHistory() { + this.hashHistory = []; + } + /** + * Compute message hash sum. + * + * @param payload - Received payload for which hash sum should be computed. + * @returns {number} - Resulting hash sum. + */ + hashCode(payload) { + let hash = 0; + if (payload.length === 0) + return hash; + for (let i = 0; i < payload.length; i += 1) { + const character = payload.charCodeAt(i); + hash = (hash << 5) - hash + character; // eslint-disable-line + hash = hash & hash; // eslint-disable-line + } + return hash; } - - this.hashHistory.push(this.getKey(message)); - } - - clearHistory() { - this.hashHistory = []; - } } /** * Subscription manager module. + * + * @internal */ /** * Subscription loop manager. @@ -4473,7 +4648,7 @@ this.heartbeatCall = heartbeatCall; this.leaveCall = leaveCall; this.reconnectionManager = new ReconnectionManager(time); - this.dedupingManager = new DedupingManager({ config: this.configuration }); + this.dedupingManager = new DedupingManager(this.configuration); this.heartbeatChannelGroups = {}; this.heartbeatChannels = {}; this.presenceChannelGroups = {}; @@ -4727,7 +4902,7 @@ } try { messages.forEach((message) => { - if (dedupeOnSubscribe) { + if (dedupeOnSubscribe && 'message' in message.data && 'timetoken' in message.data) { if (this.dedupingManager.isDuplicate(message.data)) return; this.dedupingManager.addEntry(message.data); @@ -4843,6 +5018,15 @@ * Base notification payload object. */ class BaseNotificationPayload { + /** + * Base notification provider payload object. + * + * @internal + * + * @param payload - Object which contains vendor-specific preformatted push notification payload. + * @param title - Notification main title. + * @param body - Notification body (main messages). + */ constructor(payload, title, body) { this._payload = payload; this.setDefaultPayloadStructure(); @@ -4899,11 +5083,15 @@ } /** * Platform-specific structure initialization. + * + * @internal */ setDefaultPayloadStructure() { } /** * Translate data object into PubNub push notification payload object. * + * @internal + * * @returns Preformatted push notification payload. */ toObject() { @@ -4918,10 +5106,14 @@ super(...arguments); /** * Type of push notification service for which payload will be created. + * + * @internal */ this._apnsPushType = 'apns'; /** * Whether resulting payload should trigger silent notification or not. + * + * @internal */ this._isSilent = false; } @@ -5051,9 +5243,21 @@ set silent(value) { this._isSilent = value; } + /** + * Setup push notification payload default content. + * + * @internal + */ setDefaultPayloadStructure() { this.payload.aps = { alert: {} }; } + /** + * Translate data object into PubNub push notification payload object. + * + * @internal + * + * @returns Preformatted push notification payload. + */ toObject() { const payload = Object.assign({}, this.payload); const { aps } = payload; @@ -5083,6 +5287,8 @@ /** * Create PubNub push notification service APNS2 configuration information object. * + * @internal + * * @param configuration - Source user-provided APNS2 configuration. * * @returns Preformatted for PubNub service APNS2 configuration information. @@ -5105,6 +5311,8 @@ /** * Create PubNub push notification service APNS2 target information object. * + * @internal + * * @param target - Source user-provided data. * * @returns Preformatted for PubNub service APNS2 target information. @@ -5120,7 +5328,7 @@ } } /** - * Message payload for Firebase Clouse Messaging service. + * Message payload for Firebase Cloud Messaging service. */ class FCMNotificationPayload extends BaseNotificationPayload { get payload() { @@ -5218,9 +5426,19 @@ this.payload.notification.icon = value; this._icon = value; } + /** + * Retrieve notifications grouping tag. + * + * @returns Notifications grouping tag. + */ get tag() { return this._tag; } + /** + * Update notifications grouping tag. + * + * @param value - String which will be used to group similar notifications in notification center. + */ set tag(value) { if (!value || !value.length) return; @@ -5237,10 +5455,22 @@ set silent(value) { this._isSilent = value; } + /** + * Setup push notification payload default content. + * + * @internal + */ setDefaultPayloadStructure() { this.payload.notification = {}; this.payload.data = {}; } + /** + * Translate data object into PubNub push notification payload object. + * + * @internal + * + * @returns Preformatted push notification payload. + */ toObject() { let data = Object.assign({}, this.payload.data); let notification = null; @@ -5262,6 +5492,14 @@ } } class NotificationsPayload { + /** + * Create push notification payload holder. + * + * @internal + * + * @param title - String which will be shown at the top of the notification (below app name). + * @param body - String with message which should be shown when user will check notification. + */ constructor(title, body) { this._payload = { apns: {}, fcm: {} }; this._title = title; @@ -5269,6 +5507,12 @@ this.apns = new APNSNotificationPayload(this._payload.apns, title, body); this.fcm = new FCMNotificationPayload(this._payload.fcm, title, body); } + /** + * Enable or disable push notification debugging message. + * + * @param value - Whether debug message from push notification scheduler should be published to the specific + * channel or not. + */ set debugging(value) { this._debugging = value; } @@ -5346,7 +5590,7 @@ * Build notifications platform for requested platforms. * * @param platforms - List of platforms for which payload should be added to final dictionary. Supported values: - * gcm, apns, and apns2. + * fcm, apns, and apns2. * * @returns Object with data, which can be sent with publish method call and trigger remote notifications for * specified platforms. @@ -5371,6 +5615,11 @@ } } + /** + * Network request module. + * + * @internal + */ /** * Base REST API request class. * @@ -5533,7 +5782,9 @@ */ AbstractRequest.decoder = new TextDecoder(); - /* */ + /** + * Endpoint API operation types. + */ var RequestOperation; (function (RequestOperation) { // -------------------------------------------------------- @@ -5768,7 +6019,17 @@ // -------------------------------------------------------- // ---------------- Subscription Utility ------------------ // -------------------------------------------------------- + /** + * Initial event engine subscription handshake operation. + * + * @internal + */ RequestOperation["PNHandshakeOperation"] = "PNHandshakeOperation"; + /** + * Event engine subscription loop operation. + * + * @internal + */ RequestOperation["PNReceiveMessagesOperation"] = "PNReceiveMessagesOperation"; })(RequestOperation || (RequestOperation = {})); var RequestOperation$1 = RequestOperation; @@ -5791,8 +6052,6 @@ // region Types /** * PubNub-defined event types by payload. - * - * @internal */ var PubNubEventType; (function (PubNubEventType) { @@ -6108,6 +6367,11 @@ } } + /** + * Real-time events emitter module. + * + * @internal + */ /** * Real-time events' emitter. * @@ -6276,6 +6540,11 @@ } } + /** + * Event Engine terminate signal listener module. + * + * @internal + */ /** * @internal */ @@ -6305,7 +6574,18 @@ } } - /* eslint-disable @typescript-eslint/no-explicit-any */ + /** + * Event Engine Core state module. + * + * @internal + */ + /** + * Event engine current state object. + * + * State contains current context and list of invocations which should be performed by the Event Engine. + * + * @internal + */ class State { transition(context, event) { var _a; @@ -6337,7 +6617,17 @@ } } + /** + * Event Engine Core module. + * + * @internal + */ /* eslint-disable @typescript-eslint/no-explicit-any */ + /** + * Generic event engine. + * + * @internal + */ class Engine extends Subject { describe(label) { return new State(label); @@ -6397,7 +6687,18 @@ } } - /* eslint-disable @typescript-eslint/no-explicit-any */ + /** + * Event Engine Core Effects dispatcher module. + * + * @internal + */ + /** + * Event Engine effects dispatcher. + * + * Dispatcher responsible for invocation enqueue and dequeue for processing. + * + * @internal + */ class Dispatcher { constructor(dependencies) { this.dependencies = dependencies; @@ -6434,7 +6735,16 @@ } } - /* eslint-disable @typescript-eslint/no-explicit-any */ + /** + * Event Engine Core types module. + * + * @internal + */ + /** + * Create and configure event engine event. + * + * @internal + */ function createEvent(type, fn) { const creator = function (...args) { return { @@ -6445,6 +6755,11 @@ creator.type = type; return creator; } + /** + * Create and configure short-term effect invocation. + * + * @internal + */ function createEffect(type, fn) { const creator = (...args) => { return { type, payload: fn(...args), managed: false }; @@ -6452,6 +6767,11 @@ creator.type = type; return creator; } + /** + * Create and configure long-running effect invocation. + * + * @internal + */ function createManagedEffect(type, fn) { const creator = (...args) => { return { type, payload: fn(...args), managed: true }; @@ -6461,6 +6781,11 @@ return creator; } + /** + * Event Engine managed effects terminate signal module. + * + * @internal + */ class AbortError extends Error { constructor() { super('The operation was aborted.'); @@ -6492,12 +6817,31 @@ } } + /** + * Event Engine Core Effects handler module. + * + * @internal + */ + /** + * Synchronous (short-term) effect invocation handler. + * + * Handler manages effect execution on behalf of effect dispatcher. + * + * @internal + */ class Handler { constructor(payload, dependencies) { this.payload = payload; this.dependencies = dependencies; } } + /** + * Asynchronous (long-running) effect invocation handler. + * + * Handler manages effect execution on behalf of effect dispatcher. + * + * @internal + */ class AsyncHandler extends Handler { constructor(payload, dependencies, asyncFunction) { super(payload, dependencies); @@ -6514,37 +6858,169 @@ this.abortSignal.abort(); } } + /** + * Asynchronous effect invocation handler constructor. + * + * @param handlerFunction - Function which performs asynchronous action and should be called on `start`. + * + * @internal + */ const asyncHandler = (handlerFunction) => (payload, dependencies) => new AsyncHandler(payload, dependencies, handlerFunction); + /** + * Presence Event Engine events module. + * + * @internal + */ + /** + * Reconnect event. + * + * Event is sent each time when user restores real-time updates processing and notifies other present subscribers + * about joining back. + * + * @internal + */ const reconnect$1 = createEvent('RECONNECT', () => ({})); + /** + * Disconnect event. + * + * Event is sent when user wants to temporarily stop real-time updates processing and notifies other present + * subscribers about leaving. + * + * @internal + */ const disconnect$1 = createEvent('DISCONNECT', () => ({})); + /** + * Channel / group join event. + * + * Event is sent when user adds new channels / groups to the active channels / groups list and notifies other present + * subscribers about joining. + * + * @internal + */ const joined = createEvent('JOINED', (channels, groups) => ({ channels, groups, })); + /** + * Channel / group leave event. + * + * Event is sent when user removes channels / groups from the active channels / groups list and notifies other present + * subscribers about leaving. + * + * @internal + */ const left = createEvent('LEFT', (channels, groups) => ({ channels, groups, })); + /** + * Leave all event. + * + * Event is sent when user doesn't want to receive any real-time updates anymore and notifies other + * subscribers on previously active channels / groups about leaving. + * + * @internal + */ const leftAll = createEvent('LEFT_ALL', () => ({})); + /** + * Presence heartbeat success event. + * + * Event is sent by corresponding effect handler if REST API call was successful. + * + * @internal + */ const heartbeatSuccess = createEvent('HEARTBEAT_SUCCESS', (statusCode) => ({ statusCode })); + /** + * Presence heartbeat did fail event. + * + * Event is sent by corresponding effect handler if REST API call failed. + * + * @internal + */ const heartbeatFailure = createEvent('HEARTBEAT_FAILURE', (error) => error); + /** + * Presence heartbeat impossible event. + * + * Event is sent by corresponding effect handler if REST API call exhausted all retry attempt and won't try again. + * + * @internal + */ const heartbeatGiveup = createEvent('HEARTBEAT_GIVEUP', () => ({})); + /** + * Delayed presence heartbeat event. + * + * Event is sent by corresponding effect handler when delay timer between heartbeat calls fired. + * + * @internal + */ const timesUp = createEvent('TIMES_UP', () => ({})); + /** + * Presence Event Engine effects module. + * + * @internal + */ + /** + * Presence heartbeat effect. + * + * Performs presence heartbeat REST API call. + * + * @internal + */ const heartbeat = createEffect('HEARTBEAT', (channels, groups) => ({ channels, groups, })); + /** + * Presence leave effect. + * + * Performs presence leave REST API call. + * + * @internal + */ const leave = createEffect('LEAVE', (channels, groups) => ({ channels, groups, })); + /** + * Emit presence heartbeat REST API call result status effect. + * + * Notify status change event listeners. + * + * @internal + */ /* eslint-disable @typescript-eslint/no-explicit-any */ const emitStatus$1 = createEffect('EMIT_STATUS', (status) => status); + /** + * Heartbeat delay effect. + * + * Delay of configured length (heartbeat interval) before another heartbeat REST API call will be done. + * + * @internal + */ const wait = createManagedEffect('WAIT', () => ({})); + /** + * Delayed heartbeat effect. + * + * Similar to the {@link wait} effect but used in case if previous heartbeat call did fail. + * + * @internal + */ const delayedHeartbeat = createManagedEffect('DELAYED_HEARTBEAT', (context) => context); + /** + * Presence Event Engine effects dispatcher. + * + * @internal + */ + /** + * Presence Event Engine dispatcher. + * + * Dispatcher responsible for presence events handling and corresponding effects execution. + * + * @internal + */ class PresenceEventEngineDispatcher extends Dispatcher { constructor(engine, dependencies) { super(dependencies); @@ -6611,6 +7087,19 @@ } } + /** + * Heartbeat stopped state module. + * + * @internal + */ + /** + * Heartbeat stopped state. + * + * State in which Presence Event Engine still has information about active channels / groups, but doesn't wait for + * delayed heartbeat request sending. + * + * @internal + */ const HeartbeatStoppedState = new State('HEARTBEAT_STOPPED'); HeartbeatStoppedState.on(joined.type, (context, event) => HeartbeatStoppedState.with({ channels: [...context.channels, ...event.payload.channels], @@ -6626,6 +7115,18 @@ })); HeartbeatStoppedState.on(leftAll.type, (context, _) => HeartbeatInactiveState.with(undefined)); + /** + * Waiting next heartbeat state module. + * + * @internal + */ + /** + * Waiting next heartbeat state. + * + * State in which Presence Event Engine is waiting when delay will run out and next heartbeat call should be done. + * + * @internal + */ const HeartbeatCooldownState = new State('HEARTBEAT_COOLDOWN'); HeartbeatCooldownState.onEnter(() => wait()); HeartbeatCooldownState.onExit(() => wait.cancel); @@ -6647,6 +7148,19 @@ }, [leave(context.channels, context.groups)])); HeartbeatCooldownState.on(leftAll.type, (context, _) => HeartbeatInactiveState.with(undefined, [leave(context.channels, context.groups)])); + /** + * Failed to heartbeat state module. + * + * @internal + */ + /** + * Failed to heartbeat state. + * + * State in which Subscription Event Engine waits for user to try to reconnect after all retry attempts has been + * exhausted. + * + * @internal + */ const HeartbeatFailedState = new State('HEARTBEAT_FAILED'); HeartbeatFailedState.on(joined.type, (context, event) => HeartbeatingState.with({ channels: [...context.channels, ...event.payload.channels], @@ -6666,6 +7180,18 @@ }, [leave(context.channels, context.groups)])); HeartbeatFailedState.on(leftAll.type, (context, _) => HeartbeatInactiveState.with(undefined, [leave(context.channels, context.groups)])); + /** + * Retry heartbeat state module. + * + * @internal + */ + /** + * Retry heartbeat state. + * + * State in which Presence Event Engine tries to recover after error which happened before. + * + * @internal + */ const HearbeatReconnectingState = new State('HEARBEAT_RECONNECTING'); HearbeatReconnectingState.onEnter((context) => delayedHeartbeat(context)); HearbeatReconnectingState.onExit(() => delayedHeartbeat.cancel); @@ -6698,6 +7224,18 @@ }); HearbeatReconnectingState.on(leftAll.type, (context, _) => HeartbeatInactiveState.with(undefined, [leave(context.channels, context.groups)])); + /** + * Heartbeating state module. + * + * @internal + */ + /** + * Heartbeating state module. + * + * State in which Presence Event Engine send heartbeat REST API call. + * + * @internal + */ const HeartbeatingState = new State('HEARTBEATING'); HeartbeatingState.onEnter((context) => heartbeat(context.channels, context.groups)); HeartbeatingState.on(heartbeatSuccess.type, (context, event) => { @@ -6725,12 +7263,34 @@ }, [leave(context.channels, context.groups)])); HeartbeatingState.on(leftAll.type, (context, _) => HeartbeatInactiveState.with(undefined, [leave(context.channels, context.groups)])); + /** + * Inactive heratbeating state module. + * + * @internal + */ + /** + * Inactive heratbeating state + * + * State in which Presence Event Engine doesn't process any heartbeat requests (initial state). + * + * @internal + */ const HeartbeatInactiveState = new State('HEARTBEAT_INACTIVE'); HeartbeatInactiveState.on(joined.type, (_, event) => HeartbeatingState.with({ channels: event.payload.channels, groups: event.payload.groups, })); + /** + * Presence Event Engine module. + * + * @internal + */ + /** + * Presence Event Engine Core. + * + * @internal + */ class PresenceEventEngine { get _engine() { return this.engine; @@ -6769,6 +7329,9 @@ } } + /** + * Failed request retry policy. + */ class RetryPolicy { static LinearRetryPolicy(configuration) { return { @@ -6843,20 +7406,87 @@ } } + /** + * Subscribe Event Engine effects module. + * + * @internal + */ + /** + * Initial subscription effect. + * + * Performs subscribe REST API call with `tt=0`. + * + * @internal + */ const handshake = createManagedEffect('HANDSHAKE', (channels, groups) => ({ channels, groups, })); + /** + * Real-time updates receive effect. + * + * Performs sequential subscribe REST API call with `tt` set to the value received from the previous subscribe + * REST API call. + * + * @internal + */ const receiveMessages = createManagedEffect('RECEIVE_MESSAGES', (channels, groups, cursor) => ({ channels, groups, cursor })); + /** + * Emit real-time updates effect. + * + * Notify event listeners about updates for which listener handlers has been provided. + * + * @internal + */ const emitMessages = createEffect('EMIT_MESSAGES', (events) => events); + /** + * Emit subscription status change effect. + * + * Notify status change event listeners. + * + * @internal + */ const emitStatus = createEffect('EMIT_STATUS', (status) => status); + /** + * Real-time updates receive restore effect. + * + * Performs subscribe REST API call with `tt` which has been received before disconnection or error. + * + * @internal + */ const receiveReconnect = createManagedEffect('RECEIVE_RECONNECT', (context) => context); + /** + * Initial subscription restore effect. + * + * Performs subscribe REST API call with `tt=0` after error. + * + * @internal + */ const handshakeReconnect = createManagedEffect('HANDSHAKE_RECONNECT', (context) => context); + /** + * Subscribe Event Engine events module. + * + * @internal + */ + /** + * Subscription list change event. + * + * Event is sent each time when user would like to change list of active channels / groups. + * + * @internal + */ const subscriptionChange = createEvent('SUBSCRIPTION_CHANGED', (channels, groups) => ({ channels, groups, })); + /** + * Subscription loop restore. + * + * Event is sent when user would like to try catch up on missed updates by providing specific timetoken. + * + * @internal + */ const restore = createEvent('SUBSCRIPTION_RESTORED', (channels, groups, timetoken, region) => ({ channels, groups, @@ -6865,33 +7495,136 @@ region: region !== null && region !== void 0 ? region : 0, }, })); + /** + * Initial subscription handshake success event. + * + * Event is sent by corresponding effect handler if REST API call was successful. + * + * @internal + */ const handshakeSuccess = createEvent('HANDSHAKE_SUCCESS', (cursor) => cursor); + /** + * Initial subscription handshake did fail event. + * + * Event is sent by corresponding effect handler if REST API call failed. + * + * @internal + */ const handshakeFailure = createEvent('HANDSHAKE_FAILURE', (error) => error); + /** + * Initial subscription handshake reconnect success event. + * + * Event is sent by corresponding effect handler if REST API call was successful after transition to the failed state. + * + * @internal + */ const handshakeReconnectSuccess = createEvent('HANDSHAKE_RECONNECT_SUCCESS', (cursor) => ({ cursor, })); + /** + * Initial subscription handshake reconnect did fail event. + * + * Event is sent by corresponding effect handler if REST API call did fail while tried to enter to the success state. + * + * @internal + */ const handshakeReconnectFailure = createEvent('HANDSHAKE_RECONNECT_FAILURE', (error) => error); + /** + * Initial subscription handshake impossible event. + * + * Event is sent by corresponding effect handler if REST API call exhausted all retry attempt and won't try again. + * + * @internal + */ const handshakeReconnectGiveup = createEvent('HANDSHAKE_RECONNECT_GIVEUP', (error) => error); + /** + * Subscription successfully received real-time updates event. + * + * Event is sent by corresponding effect handler if REST API call was successful. + * + * @internal + */ const receiveSuccess = createEvent('RECEIVE_SUCCESS', (cursor, events) => ({ cursor, events, })); + /** + * Subscription did fail to receive real-time updates event. + * + * Event is sent by corresponding effect handler if REST API call failed. + * + * @internal + */ const receiveFailure = createEvent('RECEIVE_FAILURE', (error) => error); + /** + * Subscription successfully received real-time updates on reconnection attempt event. + * + * Event is sent by corresponding effect handler if REST API call was successful after transition to the failed state. + * + * @internal + */ const receiveReconnectSuccess = createEvent('RECEIVE_RECONNECT_SUCCESS', (cursor, events) => ({ cursor, events, })); + /** + * Subscription did fail to receive real-time updates on reconnection attempt event. + * + * Event is sent by corresponding effect handler if REST API call did fail while tried to enter to the success state. + * + * @internal + */ const receiveReconnectFailure = createEvent('RECEIVE_RECONNECT_FAILURE', (error) => error); + /** + * Subscription real-time updates received impossible event. + * + * Event is sent by corresponding effect handler if REST API call exhausted all retry attempt and won't try again. + * + * @internal + */ const receiveReconnectGiveup = createEvent('RECEIVING_RECONNECT_GIVEUP', (error) => error); + /** + * Client disconnect event. + * + * Event is sent when user wants to temporarily stop real-time updates receive. + * + * @internal + */ const disconnect = createEvent('DISCONNECT', () => ({})); + /** + * Client reconnect event. + * + * Event is sent when user wants to restore real-time updates receive. + * + * @internal + */ const reconnect = createEvent('RECONNECT', (timetoken, region) => ({ cursor: { timetoken: timetoken !== null && timetoken !== void 0 ? timetoken : '', region: region !== null && region !== void 0 ? region : 0, }, })); + /** + * Completely stop real-time updates receive event. + * + * Event is sent when user doesn't want to receive any real-time updates anymore. + * + * @internal + */ const unsubscribeAll = createEvent('UNSUBSCRIBE_ALL', () => ({})); + /** + * Subscribe Event Engine effects dispatcher. + * + * @internal + */ + /** + * Subscribe Event Engine dispatcher. + * + * Dispatcher responsible for subscription events handling and corresponding effects execution. + * + * @internal + */ class EventEngineDispatcher extends Dispatcher { constructor(engine, dependencies) { super(dependencies); @@ -6995,6 +7728,19 @@ } } + /** + * Failed initial subscription handshake (disconnected) state. + * + * @internal + */ + /** + * Failed initial subscription handshake (disconnected) state. + * + * State in which Subscription Event Engine waits for user to try to reconnect after all retry attempts has been + * exhausted. + * + * @internal + */ const HandshakeFailedState = new State('HANDSHAKE_FAILED'); HandshakeFailedState.on(subscriptionChange.type, (context, event) => HandshakingState.with({ channels: event.payload.channels, @@ -7019,6 +7765,19 @@ }); HandshakeFailedState.on(unsubscribeAll.type, (_) => UnsubscribedState.with()); + /** + * Stopped initial subscription handshake (disconnected) state. + * + * @internal + */ + /** + * Stopped initial subscription handshake (disconnected) state. + * + * State in which Subscription Event Engine still has information about subscription but doesn't have subscription + * cursor for next sequential subscribe REST API call. + * + * @internal + */ const HandshakeStoppedState = new State('HANDSHAKE_STOPPED'); HandshakeStoppedState.on(subscriptionChange.type, (context, event) => HandshakeStoppedState.with({ channels: event.payload.channels, @@ -7039,6 +7798,19 @@ }); HandshakeStoppedState.on(unsubscribeAll.type, (_) => UnsubscribedState.with()); + /** + * Failed to receive real-time updates (disconnected) state. + * + * @internal + */ + /** + * Failed to receive real-time updates (disconnected) state. + * + * State in which Subscription Event Engine waits for user to try to reconnect after all retry attempts has been + * exhausted. + * + * @internal + */ const ReceiveFailedState = new State('RECEIVE_FAILED'); ReceiveFailedState.on(reconnect.type, (context, event) => { var _a; @@ -7066,6 +7838,19 @@ })); ReceiveFailedState.on(unsubscribeAll.type, (_) => UnsubscribedState.with(undefined)); + /** + * Stopped real-time updates (disconnected) state module. + * + * @internal + */ + /** + * Stopped real-time updates (disconnected) state. + * + * State in which Subscription Event Engine still has information about subscription but doesn't process real-time + * updates. + * + * @internal + */ const ReceiveStoppedState = new State('RECEIVE_STOPPED'); ReceiveStoppedState.on(subscriptionChange.type, (context, event) => ReceiveStoppedState.with({ channels: event.payload.channels, @@ -7093,6 +7878,18 @@ }); ReceiveStoppedState.on(unsubscribeAll.type, () => UnsubscribedState.with(undefined)); + /** + * Reconnect to receive real-time updates (disconnected) state. + * + * @internal + */ + /** + * Reconnect to receive real-time updates (disconnected) state. + * + * State in which Subscription Event Engine tries to recover after error which happened before. + * + * @internal + */ const ReceiveReconnectingState = new State('RECEIVE_RECONNECTING'); ReceiveReconnectingState.onEnter((context) => receiveReconnect(context)); ReceiveReconnectingState.onExit(() => receiveReconnect.cancel); @@ -7131,6 +7928,18 @@ })); ReceiveReconnectingState.on(unsubscribeAll.type, (_) => UnsubscribedState.with(undefined, [emitStatus({ category: StatusCategory$1.PNDisconnectedCategory })])); + /** + * Receiving real-time updates (connected) state module. + * + * @internal + */ + /** + * Receiving real-time updates (connected) state. + * + * State in which Subscription Event Engine processes any real-time updates. + * + * @internal + */ const ReceivingState = new State('RECEIVING'); ReceivingState.onEnter((context) => receiveMessages(context.channels, context.groups, context.cursor)); ReceivingState.onExit(() => receiveMessages.cancel); @@ -7174,6 +7983,18 @@ }); ReceivingState.on(unsubscribeAll.type, (_) => UnsubscribedState.with(undefined, [emitStatus({ category: StatusCategory$1.PNDisconnectedCategory })])); + /** + * Retry initial subscription handshake (disconnected) state. + * + * @internal + */ + /** + * Retry initial subscription handshake (disconnected) state. + * + * State in which Subscription Event Engine tries to recover after error which happened before. + * + * @internal + */ const HandshakeReconnectingState = new State('HANDSHAKE_RECONNECTING'); HandshakeReconnectingState.onEnter((context) => handshakeReconnect(context)); HandshakeReconnectingState.onExit(() => handshakeReconnect.cancel); @@ -7222,6 +8043,19 @@ }); HandshakeReconnectingState.on(unsubscribeAll.type, (_) => UnsubscribedState.with(undefined)); + /** + * Initial subscription handshake (disconnected) state. + * + * @internal + */ + /** + * Initial subscription handshake (disconnected) state. + * + * State in which Subscription Event Engine tries to receive subscription cursor for next sequential subscribe REST + * API calls. + * + * @internal + */ const HandshakingState = new State('HANDSHAKING'); HandshakingState.onEnter((context) => handshake(context.channels, context.groups)); HandshakingState.onExit(() => handshake.cancel); @@ -7277,6 +8111,18 @@ }); HandshakingState.on(unsubscribeAll.type, (_) => UnsubscribedState.with()); + /** + * Unsubscribed / disconnected state module. + * + * @internal + */ + /** + * Unsubscribed / disconnected state. + * + * State in which Subscription Event Engine doesn't process any real-time updates. + * + * @internal + */ const UnsubscribedState = new State('UNSUBSCRIBED'); UnsubscribedState.on(subscriptionChange.type, (_, event) => HandshakingState.with({ channels: event.payload.channels, @@ -7290,6 +8136,16 @@ }); }); + /** + * Subscribe Event Engine module. + * + * @internal + */ + /** + * Subscribe Event Engine Core. + * + * @internal + */ class EventEngine { get _engine() { return this.engine; @@ -7531,6 +8387,8 @@ /** * Receive messages subscribe REST API module. + * + * @internal */ /** * Receive messages subscribe request. @@ -7575,6 +8433,8 @@ /** * Handshake subscribe REST API module. + * + * @internal */ /** * Handshake subscribe request. @@ -7606,6 +8466,8 @@ /** * Get Presence State REST API module. + * + * @internal */ // endregion /** @@ -7662,6 +8524,8 @@ /** * Set Presence State REST API module. + * + * @internal */ // endregion /** @@ -7712,6 +8576,8 @@ /** * Announce heartbeat REST API module. + * + * @internal */ // endregion /** @@ -7762,6 +8628,8 @@ /** * Announce leave REST API module. + * + * @internal */ // endregion /** @@ -7814,6 +8682,8 @@ /** * `uuid` presence REST API module. + * + * @internal */ // endregion /** @@ -7854,6 +8724,8 @@ /** * Channels / channel groups presence REST API module. + * + * @internal */ // -------------------------------------------------------- // ----------------------- Defaults ----------------------- @@ -7951,6 +8823,8 @@ /** * Delete messages REST API module. + * + * @internal */ // endregion /** @@ -7995,6 +8869,8 @@ /** * Messages count REST API module. + * + * @internal */ // endregion /** @@ -8047,6 +8923,8 @@ /** * Get history REST API module. + * + * @internal */ // -------------------------------------------------------- // ---------------------- Defaults ------------------------ @@ -8185,6 +9063,8 @@ /** * Fetch messages REST API module. + * + * @internal */ // -------------------------------------------------------- // ---------------------- Defaults ------------------------ @@ -8366,6 +9246,8 @@ /** * Get Message Actions REST API module. + * + * @internal */ // endregion /** @@ -8421,6 +9303,8 @@ /** * Add Message Action REST API module. + * + * @internal */ // endregion /** @@ -8478,6 +9362,8 @@ /** * Remove Message Action REST API module. + * + * @internal */ // endregion /** @@ -8523,6 +9409,8 @@ /** * Publish File Message REST API module. + * + * @internal */ // -------------------------------------------------------- // ----------------------- Defaults ----------------------- @@ -8601,6 +9489,8 @@ /** * File sharing REST API module. + * + * @internal */ // endregion /** @@ -8645,6 +9535,8 @@ /** * Delete file REST API module. + * + * @internal */ // endregion /** @@ -8688,6 +9580,8 @@ /** * List Files REST API module. + * + * @internal */ // -------------------------------------------------------- // ----------------------- Defaults ----------------------- @@ -8742,6 +9636,8 @@ /** * Generate file upload URL REST API request. + * + * @internal */ // endregion /** @@ -8793,6 +9689,8 @@ /** * Upload file REST API request. + * + * @internal */ /** * File Upload request. @@ -8850,6 +9748,11 @@ } } + /** + * Share File API module. + * + * @internal + */ // endregion /** * Send file composed request. @@ -8972,53 +9875,173 @@ } class SubscribeCapable { + /** + * Start receiving real-time updates. + * + * @param subscribeParameters - Additional subscription configuration options which should be used + * for request. + */ subscribe(subscribeParameters) { const timetoken = subscribeParameters === null || subscribeParameters === void 0 ? void 0 : subscribeParameters.timetoken; this.pubnub.subscribe(Object.assign({ channels: this.channelNames, channelGroups: this.groupNames }, (timetoken !== null && timetoken !== '' && { timetoken: timetoken }))); } + /** + * Stop real-time events processing. + */ unsubscribe() { this.pubnub.unsubscribe({ channels: this.channelNames, channelGroups: this.groupNames, }); } + /** + * Set new message handler. + * + * @param onMessageListener - Listener function, which will be called each time when a new message + * is received from the real-time network. + */ set onMessage(onMessageListener) { this.listener.message = onMessageListener; } + /** + * Set new presence events handler. + * + * @param onPresenceListener - Listener function, which will be called each time when a new + * presence event is received from the real-time network. + */ set onPresence(onPresenceListener) { this.listener.presence = onPresenceListener; } + /** + * Set new signal handler. + * + * @param onSignalListener - Listener function, which will be called each time when a new signal + * is received from the real-time network. + */ set onSignal(onSignalListener) { this.listener.signal = onSignalListener; } + /** + * Set new app context event handler. + * + * @param onObjectsListener - Listener function, which will be called each time when a new + * app context event is received from the real-time network. + */ set onObjects(onObjectsListener) { this.listener.objects = onObjectsListener; } + /** + * Set new message reaction event handler. + * + * @param messageActionEventListener - Listener function, which will be called each time when a + * new message reaction event is received from the real-time network. + */ set onMessageAction(messageActionEventListener) { this.listener.messageAction = messageActionEventListener; } + /** + * Set new file handler. + * + * @param fileEventListener - Listener function, which will be called each time when a new file + * is received from the real-time network. + */ set onFile(fileEventListener) { this.listener.file = fileEventListener; } + /** + * Set events handler. + * + * @param listener - Events listener configuration object, which lets specify handlers for multiple + * types of events. + */ addListener(listener) { this.eventEmitter.addListener(listener, this.channelNames.filter((c) => !c.endsWith('-pnpres')), this.groupNames.filter((cg) => !cg.endsWith('-pnpres'))); } + /** + * Remove events handler. + * + * @param listener - Event listener configuration, which should be removed from the list of notified + * listeners. **Important:** Should be the same object which has been passed to the + * {@link addListener}. + */ removeListener(listener) { this.eventEmitter.removeListener(listener, this.channelNames, this.groupNames); } + /** + * Get list of channels which is used for subscription. + * + * @returns List of channel names. + */ get channels() { return this.channelNames.slice(0); } + /** + * Get list of channel groups which is used for subscription. + * + * @returns List of channel group names. + */ get channelGroups() { return this.groupNames.slice(0); } } + /** + * Multiple entities subscription set object which can be used to receive and handle real-time + * updates. + * + * Subscription set object represent collection of per-entity subscription objects and allow + * processing them at once for subscription loop and events handling. + */ class SubscriptionSet extends SubscribeCapable { + /** + * Create entities' subscription set object. + * + * Subscription set object represent collection of per-entity subscription objects and allow + * processing them at once for subscription loop and events handling. + * + * @param channels - List of channels which should be used in subscription loop. + * @param channelGroups - List of channel groups which should be used in subscription loop. + * @param subscriptionOptions - Entities' subscription object configuration. + * @param eventEmitter - Event emitter, which will notify listeners about updates received for + * entities' channels / groups. + * @param pubnub - PubNub instance which will perform subscribe / unsubscribe requests for + * entities. + * + * @returns Ready to use entities' subscription set object. + * + * @internal + */ constructor({ channels = [], channelGroups = [], subscriptionOptions, eventEmitter, pubnub, }) { super(); + /** + * List of channel names for subscription loop. + * + * List of entities' names which can have additional entries depending on from configuration + * options. Presence events observing adds additional name to be used along with entity name. + * + * **Note:** Depending on from the entities' type, they may provide a list of channels which are + * used to receive real-time updates for it. + * + * @internal + */ this.channelNames = []; + /** + * List of channel group names for subscription loop. + * + * List of entities' names which can have additional entries depending on from configuration + * options. Presence events observing adds additional name to be used along with entity name. + * + * **Note:** Depending on from the entities' type, they may provide a list of channels which are + * used to receive real-time updates for it. + * + * @internal + */ this.groupNames = []; + /** + * List of per-entity subscription objects. + * + * @internal + */ this.subscriptionList = []; this.options = subscriptionOptions; this.eventEmitter = eventEmitter; @@ -9036,12 +10059,28 @@ this.listener = {}; eventEmitter.addListener(this.listener, this.channelNames.filter((c) => !c.endsWith('-pnpres')), this.groupNames.filter((cg) => !cg.endsWith('-pnpres'))); } + /** + * Add additional entity's subscription to the subscription set. + * + * **Important:** Changes will be effective only after {@link SubscribeCapable#subscribe} call or + * next subscription loop. + * + * @param subscription - Other entity's subscription object, which should be added. + */ addSubscription(subscription) { this.subscriptionList.push(subscription); this.channelNames = [...this.channelNames, ...subscription.channels]; this.groupNames = [...this.groupNames, ...subscription.channelGroups]; this.eventEmitter.addListener(this.listener, subscription.channels, subscription.channelGroups); } + /** + * Remove entity's subscription object from the set. + * + * **Important:** Changes will be effective only after {@link SubscribeCapable#unsubscribe} call or + * next subscription loop. + * + * @param subscription - Other entity's subscription object, which should be removed. + */ removeSubscription(subscription) { const channelsToRemove = subscription.channels; const groupsToRemove = subscription.channelGroups; @@ -9050,12 +10089,28 @@ this.subscriptionList = this.subscriptionList.filter((s) => s !== subscription); this.eventEmitter.removeListener(this.listener, channelsToRemove, groupsToRemove); } + /** + * Merge with other subscription set object. + * + * **Important:** Changes will be effective only after {@link SubscribeCapable#subscribe} call or + * next subscription loop. + * + * @param subscriptionSet - Other entities' subscription set, which should be joined. + */ addSubscriptionSet(subscriptionSet) { this.subscriptionList = [...this.subscriptionList, ...subscriptionSet.subscriptions]; this.channelNames = [...this.channelNames, ...subscriptionSet.channels]; this.groupNames = [...this.groupNames, ...subscriptionSet.channelGroups]; this.eventEmitter.addListener(this.listener, subscriptionSet.channels, subscriptionSet.channelGroups); } + /** + * Subtract other subscription set object. + * + * **Important:** Changes will be effective only after {@link SubscribeCapable#unsubscribe} call or + * next subscription loop. + * + * @param subscriptionSet - Other entities' subscription set, which should be subtracted. + */ removeSubscriptionSet(subscriptionSet) { const channelsToRemove = subscriptionSet.channels; const groupsToRemove = subscriptionSet.channelGroups; @@ -9064,15 +10119,59 @@ this.subscriptionList = this.subscriptionList.filter((s) => !subscriptionSet.subscriptions.includes(s)); this.eventEmitter.removeListener(this.listener, channelsToRemove, groupsToRemove); } + /** + * Get list of entities' subscription objects registered in subscription set. + * + * @returns Entities' subscription objects list. + */ get subscriptions() { return this.subscriptionList.slice(0); } } + /** + * Single-entity subscription object which can be used to receive and handle real-time updates. + */ class Subscription extends SubscribeCapable { + /** + * Create entity's subscription object. + * + * @param channels - List of channels which should be used in subscription loop. + * @param channelGroups - List of channel groups which should be used in subscription loop. + * @param subscriptionOptions - Per-entity subscription object configuration. + * @param eventEmitter - Event emitter, which will notify listeners about updates received for + * entity channels / groups. + * @param pubnub - PubNub instance which will perform subscribe / unsubscribe requests for entity. + * + * @returns Ready to use entity's subscription object. + * + * @internal + */ constructor({ channels, channelGroups, subscriptionOptions, eventEmitter, pubnub, }) { super(); + /** + * List of channel names for subscription loop. + * + * Entity may have few because of subscription configuration options. Presence events observing + * adds additional name to be used along with entity name. + * + * **Note:** Depending on from the entity type, it may provide a list of channels which are used + * to receive real-time updates for it. + * + * @internal + */ this.channelNames = []; + /** + * List of channel group names for subscription loop. + * + * Entity may have few because of subscription configuration options. Presence events observing + * adds additional name to be used along with entity name. + * + * **Note:** Depending on from the entity type, it may provide a list of channel groups which is + * sed to receive real-time updates for it. + * + * @internal + */ this.groupNames = []; this.channelNames = channels; this.groupNames = channelGroups; @@ -9082,6 +10181,12 @@ this.listener = {}; eventEmitter.addListener(this.listener, this.channelNames.filter((c) => !c.endsWith('-pnpres')), this.groupNames.filter((cg) => !cg.endsWith('-pnpres'))); } + /** + * Merge entities' subscription objects into subscription set. + * + * @param subscription - Other entity's subscription object to be merged with receiver. + * @return Subscription set which contains both receiver and other entities' subscription objects. + */ addSubscription(subscription) { return new SubscriptionSet({ channels: [...this.channelNames, ...subscription.channels], @@ -9093,12 +10198,37 @@ } } + /** + * First-class objects which provides access to the channel app context object-specific APIs. + */ class ChannelMetadata { + /** + * Create channel app context object entity. + * + * @param id - Channel app context object identifier which will be used with subscription loop. + * @param eventEmitter - Event emitter, which will notify listeners about updates received on + * channel's subscription. + * @param pubnub - PubNub instance which will use this entity. + * + * @returns Ready to use channel app context object entity. + * + * @internal + */ constructor(id, eventEmitter, pubnub) { - this.id = id; this.eventEmitter = eventEmitter; this.pubnub = pubnub; + this.id = id; } + /** + * Create channel's app context subscription object for real-time updates. + * + * Create subscription object which can be used to subscribe to the real-time updates sent to the specific channel + * app context object. + * + * @param [subscriptionOptions] - Channel's app context subscription object behavior customization options. + * + * @returns Configured and ready to use channel's app context subscription object. + */ subscription(subscriptionOptions) { { return new Subscription({ @@ -9112,12 +10242,37 @@ } } + /** + * First-class objects which provides access to the channel group-specific APIs. + */ class ChannelGroup { - constructor(channelGroup, eventEmitter, pubnub) { + /** + * Create simple channel entity. + * + * @param name - Name of the channel group which will be used with subscription loop. + * @param eventEmitter - Event emitter, which will notify listeners about updates received on + * channel group's subscription. + * @param pubnub - PubNub instance which will use this entity. + * + * @returns Ready to use channel group entity. + * + * @internal + */ + constructor(name, eventEmitter, pubnub) { this.eventEmitter = eventEmitter; this.pubnub = pubnub; - this.name = channelGroup; + this.name = name; } + /** + * Create channel group's subscription object for real-time updates. + * + * Create subscription object which can be used to subscribe to the real-time updates sent to the channels in + * specific channel group. + * + * @param [subscriptionOptions] - Channel group's subscription object behavior customization options. + * + * @returns Configured and ready to use channel group's subscription object. + */ subscription(subscriptionOptions) { { return new Subscription({ @@ -9131,12 +10286,37 @@ } } + /** + * First-class objects which provides access to the user app context object-specific APIs. + */ class UserMetadata { + /** + * Create user app context object entity. + * + * @param id - User app context object identifier which will be used with subscription loop. + * @param eventEmitter - Event emitter, which will notify listeners about updates received on + * channel's subscription. + * @param pubnub - PubNub instance which will use this entity. + * + * @returns Ready to use user app context object entity. + * + * @internal + */ constructor(id, eventEmitter, pubnub) { - this.id = id; this.eventEmitter = eventEmitter; this.pubnub = pubnub; + this.id = id; } + /** + * Create user's app context subscription object for real-time updates. + * + * Create subscription object which can be used to subscribe to the real-time updates sent to the specific user + * app context object. + * + * @param [subscriptionOptions] - User's app context subscription object behavior customization options. + * + * @returns Configured and ready to use user's app context subscription object. + */ subscription(subscriptionOptions) { { return new Subscription({ @@ -9150,12 +10330,36 @@ } } + /** + * First-class objects which provides access to the channel-specific APIs. + */ class Channel { - constructor(channelName, eventEmitter, pubnub) { + /** + * Create simple channel entity. + * + * @param name - Name of the channel which will be used with subscription loop. + * @param eventEmitter - Event emitter, which will notify listeners about updates received on + * channel's subscription. + * @param pubnub - PubNub instance which will use this entity. + * + * @returns Ready to use channel entity. + * + * @internal + */ + constructor(name, eventEmitter, pubnub) { this.eventEmitter = eventEmitter; this.pubnub = pubnub; - this.name = channelName; + this.name = name; } + /** + * Create channel's subscription object for real-time updates. + * + * Create subscription object which can be used to subscribe to the real-time updates sent to the specific channel. + * + * @param [subscriptionOptions] - Channel's subscription object behavior customization options. + * + * @returns Configured and ready to use channel's subscription object. + */ subscription(subscriptionOptions) { { return new Subscription({ @@ -9171,6 +10375,8 @@ /** * Remove channel group channels REST API module. + * + * @internal */ // endregion /** @@ -9218,6 +10424,8 @@ /** * Add channel group channels REST API module. + * + * @internal */ // endregion /** @@ -9264,6 +10472,8 @@ /** * List channel group channels REST API module. + * + * @internal */ // endregion /** @@ -9304,6 +10514,8 @@ /** * Delete channel group REST API module. + * + * @internal */ // endregion /** @@ -9344,6 +10556,8 @@ /** * List All Channel Groups REST API module. + * + * @internal */ // endregion /** @@ -9382,12 +10596,23 @@ /** * PubNub Channel Groups API module. */ - class PubnubChannelGroups { + /** + * PubNub Stream / Channel group API interface. + */ + class PubNubChannelGroups { + /** + * Create stream / channel group API access object. + * + * @param keySet - PubNub account keys set which should be used for REST API calls. + * @param sendRequest - Function which should be used to send REST API calls. + * + * @internal + */ constructor(keySet, /* eslint-disable @typescript-eslint/no-explicit-any */ sendRequest) { - this.keySet = keySet; this.sendRequest = sendRequest; + this.keySet = keySet; } /** * Fetch channel group channels. @@ -9477,6 +10702,8 @@ /** * Manage channels enabled for device push REST API module. + * + * @internal */ // -------------------------------------------------------- // ----------------------- Defaults ----------------------- @@ -9554,6 +10781,8 @@ /** * Unregister Channels from Device push REST API module. + * + * @internal */ // endregion /** @@ -9581,6 +10810,8 @@ /** * List Device push enabled channels REST API module. + * + * @internal */ // endregion /** @@ -9608,6 +10839,8 @@ /** * Register Channels with Device push REST API module. + * + * @internal */ // endregion /** @@ -9635,6 +10868,8 @@ /** * Unregister Device push REST API module. + * + * @internal */ // endregion /** @@ -9663,12 +10898,23 @@ /** * PubNub Push Notifications API module. */ + /** + * PubNub Push Notifications API interface. + */ class PubNubPushNotifications { + /** + * Create mobile push notifications API access object. + * + * @param keySet - PubNub account keys set which should be used for REST API calls. + * @param sendRequest - Function which should be used to send REST API calls. + * + * @internal + */ constructor(keySet, /* eslint-disable @typescript-eslint/no-explicit-any */ sendRequest) { - this.keySet = keySet; this.sendRequest = sendRequest; + this.keySet = keySet; } /** * Fetch device's push notification enabled channels. @@ -9732,6 +10978,8 @@ /** * Get All Channel Metadata REST API module. + * + * @internal */ // -------------------------------------------------------- // ----------------------- Defaults ----------------------- @@ -9797,6 +11045,8 @@ /** * Remove Channel Metadata REST API module. + * + * @internal */ // endregion /** @@ -9835,6 +11085,8 @@ /** * Get UUID Memberships REST API module. + * + * @internal */ // -------------------------------------------------------- // ----------------------- Defaults ----------------------- @@ -9946,6 +11198,8 @@ /** * Set UUID Memberships REST API module. + * + * @internal */ // -------------------------------------------------------- // ----------------------- Defaults ----------------------- @@ -10052,6 +11306,8 @@ /** * Get All UUID Metadata REST API module. + * + * @internal */ // -------------------------------------------------------- // ----------------------- Defaults ----------------------- @@ -10112,6 +11368,8 @@ /** * Get Channel Metadata REST API module. + * + * @internal */ // -------------------------------------------------------- // ----------------------- Defaults ----------------------- @@ -10168,6 +11426,8 @@ /** * Set Channel Metadata REST API module. + * + * @internal */ // -------------------------------------------------------- // ----------------------- Defaults ----------------------- @@ -10229,6 +11489,8 @@ /** * Remove UUID Metadata REST API module. + * + * @internal */ // endregion /** @@ -10270,6 +11532,8 @@ /** * Get Channel Members REST API module. + * + * @internal */ // -------------------------------------------------------- // ----------------------- Defaults ----------------------- @@ -10378,6 +11642,8 @@ /** * Set Channel Members REST API module. + * + * @internal */ // -------------------------------------------------------- // ----------------------- Defaults ----------------------- @@ -10481,6 +11747,8 @@ /** * Get UUID Metadata REST API module. + * + * @internal */ // -------------------------------------------------------- // ----------------------- Defaults ----------------------- @@ -10539,6 +11807,8 @@ /** * Set UUID Metadata REST API module. + * + * @internal */ // -------------------------------------------------------- // ----------------------- Defaults ----------------------- @@ -10604,13 +11874,24 @@ /** * PubNub Objects API module. */ + /** + * PubNub App Context API interface. + */ class PubNubObjects { + /** + * Create app context API access object. + * + * @param configuration - Extended PubNub client configuration object. + * @param sendRequest - Function which should be used to send REST API calls. + * + * @internal + */ constructor(configuration, /* eslint-disable @typescript-eslint/no-explicit-any */ sendRequest) { + this.keySet = configuration.keySet; this.configuration = configuration; this.sendRequest = sendRequest; - this.keySet = configuration.keySet; } /** * Fetch a paginated list of UUID Metadata objects. @@ -10628,11 +11909,12 @@ /** * Fetch a paginated list of UUID Metadata objects. * - * * @param [parametersOrCallback] - Request configuration parameters or callback from overload. * @param [callback] - Request completion handler callback. * * @returns Asynchronous get all UUID metadata response or `void` in case if `callback` provided. + * + * @internal */ _getAllUUIDMetadata(parametersOrCallback, callback) { return __awaiter(this, void 0, void 0, function* () { @@ -10665,6 +11947,8 @@ * @param [callback] - Request completion handler callback. * * @returns Asynchronous get UUID metadata response or `void` in case if `callback` provided. + * + * @internal */ _getUUIDMetadata(parametersOrCallback, callback) { return __awaiter(this, void 0, void 0, function* () { @@ -10698,6 +11982,8 @@ /** * Update specific UUID Metadata object. * + * @internal + * * @param parameters - Request configuration parameters. Will set UUID metadata for currently * configured PubNub client `uuid` if not set. * @param [callback] - Request completion handler callback. @@ -10732,6 +12018,8 @@ /** * Remove a specific UUID Metadata object. * + * @internal + * * @param [parametersOrCallback] - Request configuration parameters or callback from overload. * @param [callback] - Request completion handler callback. * @@ -10769,6 +12057,8 @@ /** * Fetch a paginated list of Channel Metadata objects. * + * @internal + * * @param [parametersOrCallback] - Request configuration parameters or callback from overload. * @param [callback] - Request completion handler callback. * @@ -10802,6 +12092,8 @@ /** * Fetch Channel Metadata object. * + * @internal + * * @param parameters - Request configuration parameters. * @param [callback] - Request completion handler callback. * @@ -10831,6 +12123,8 @@ /** * Update specific Channel Metadata object. * + * @internal + * * @param parameters - Request configuration parameters. * @param [callback] - Request completion handler callback. * @@ -10861,6 +12155,8 @@ /** * Remove a specific Channel Metadata object. * + * @internal + * * @param parameters - Request configuration parameters. * @param [callback] - Request completion handler callback. * @@ -11151,6 +12447,8 @@ /** * Download File REST API module. + * + * @internal */ // endregion /** @@ -11202,6 +12500,9 @@ } } + /** + * Core PubNub API module. + */ // endregion /** * Platform-agnostic PubNub client core. @@ -11229,6 +12530,14 @@ return uuidGenerator.createUUID(); } // endregion + /** + * Create and configure PubNub client core. + * + * @param configuration - PubNub client core configuration. + * @returns Configured and ready to use PubNub client. + * + * @internal + */ constructor(configuration) { this._configuration = configuration.configuration; this.cryptography = configuration.cryptography; @@ -11237,7 +12546,7 @@ this.crypto = configuration.crypto; // API group entry points initialization. this._objects = new PubNubObjects(this._configuration, this.sendRequest.bind(this)); - this._channelGroups = new PubnubChannelGroups(this._configuration.keySet, this.sendRequest.bind(this)); + this._channelGroups = new PubNubChannelGroups(this._configuration.keySet, this.sendRequest.bind(this)); this._push = new PubNubPushNotifications(this._configuration.keySet, this.sendRequest.bind(this)); { // Prepare for real-time events announcement. @@ -11594,6 +12903,8 @@ /** * Schedule request execution. * + * @internal + * * @param request - REST API request. * @param [callback] - Request completion handler callback. * @@ -11820,6 +13131,8 @@ * * **Note:** Method passed into managers to let them use it when required. * + * @internal + * * @param parameters - Request configuration parameters. * @param callback - Request completion handler callback. */ @@ -11864,6 +13177,8 @@ * * **Note:** Method passed into managers to let them use it when required. * + * @internal + * * @param parameters - Request configuration parameters. * @param callback - Request completion handler callback. */ @@ -11911,6 +13226,8 @@ /** * Event engine handshake subscribe. * + * @internal + * * @param parameters - Request configuration parameters. */ subscribeHandshake(parameters) { @@ -11937,6 +13254,8 @@ /** * Event engine receive messages subscribe. * + * @internal + * * @param parameters - Request configuration parameters. */ subscribeReceiveMessages(parameters) { @@ -12206,6 +13525,8 @@ /** * Announce user presence * + * @internal + * * @param parameters - Desired presence state for provided list of channels and groups. * @param callback - Request completion handler callback. */ @@ -12224,6 +13545,8 @@ /** * Announce user `join` on specified list of channels and groups. * + * @internal + * * @param parameters - List of channels and groups where `join` event should be sent. */ join(parameters) { @@ -12235,6 +13558,8 @@ /** * Announce user `leave` on specified list of channels and groups. * + * @internal + * * @param parameters - List of channels and groups where `leave` event should be sent. */ leave(parameters) { @@ -12243,6 +13568,8 @@ } /** * Announce user `leave` on all subscribed channels. + * + * @internal */ leaveAll() { var _a; @@ -12580,8 +13907,7 @@ * @returns Asynchronous memberships modification response or `void` in case if `callback` provided. * * @deprecated Use {@link PubNubCore#objects.removeMemberships} or {@link PubNubCore#objects.removeChannelMembers} - * methods instead - * from `objects` API group.. + * methods instead from `objects` API group. */ removeMemberships(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { @@ -12934,6 +14260,8 @@ /** * Cbor decoder module. + * + * @internal */ /** * CBOR data decoder. @@ -12970,6 +14298,13 @@ * PubNub client for browser platform. */ class PubNub extends PubNubCore { + /** + * Create and configure PubNub client core. + * + * @param configuration - User-provided PubNub client configuration. + * + * @returns Configured and ready to use PubNub client. + */ constructor(configuration) { var _a; const configurationCopy = setDefaults(configuration); diff --git a/dist/web/pubnub.min.js b/dist/web/pubnub.min.js index 34c4dcc6b..612cdc159 100644 --- a/dist/web/pubnub.min.js +++ b/dist/web/pubnub.min.js @@ -1,2 +1,2 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).PubNub=t()}(this,(function(){"use strict";var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var s={exports:{}};!function(t){!function(e,s){var n=Math.pow(2,-24),r=Math.pow(2,32),i=Math.pow(2,53);var o={encode:function(e){var t,n=new ArrayBuffer(256),o=new DataView(n),a=0;function c(e){for(var s=n.byteLength,r=a+e;s>2,u=0;u>6),r.push(128|63&o)):o<55296?(r.push(224|o>>12),r.push(128|o>>6&63),r.push(128|63&o)):(o=(1023&o)<<10,o|=1023&t.charCodeAt(++n),o+=65536,r.push(240|o>>18),r.push(128|o>>12&63),r.push(128|o>>6&63),r.push(128|63&o))}return d(3,r.length),h(r);default:var p;if(Array.isArray(t))for(d(4,p=t.length),n=0;n>5!==e)throw"Invalid indefinite length element";return s}function f(e,t){for(var s=0;s>10),e.push(56320|1023&n))}}"function"!=typeof t&&(t=function(e){return e}),"function"!=typeof i&&(i=function(){return s});var m=function e(){var r,d,m=l(),b=m>>5,v=31&m;if(7===b)switch(v){case 25:return function(){var e=new ArrayBuffer(4),t=new DataView(e),s=h(),r=32768&s,i=31744&s,o=1023&s;if(31744===i)i=261120;else if(0!==i)i+=114688;else if(0!==o)return o*n;return t.setUint32(0,r<<16|i<<13|o<<13),t.getFloat32(0)}();case 26:return c(o.getFloat32(a),4);case 27:return c(o.getFloat64(a),8)}if((d=g(v))<0&&(b<2||6=0;)S+=d,w.push(u(d));var k=new Uint8Array(S),E=0;for(r=0;r=0;)f(O,d);else f(O,d);return String.fromCharCode.apply(null,O);case 4:var C;if(d<0)for(C=[];!p();)C.push(e());else for(C=new Array(d),r=0;r{const s=new FileReader;s.addEventListener("load",(()=>{if(s.result instanceof ArrayBuffer)return e(s.result)})),s.addEventListener("error",(()=>t(s.error))),s.readAsArrayBuffer(this.data)}))}))}toString(){return i(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{const s=new FileReader;s.addEventListener("load",(()=>{if("string"==typeof s.result)return e(s.result)})),s.addEventListener("error",(()=>{t(s.error)})),s.readAsBinaryString(this.data)}))}))}toStream(){return i(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in Node.js environments.")}))}toFile(){return i(this,void 0,void 0,(function*(){return this.data}))}toFileUri(){return i(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in React Native environments.")}))}toBlob(){return i(this,void 0,void 0,(function*(){return this.data}))}}a.supportsBlob="undefined"!=typeof Blob,a.supportsFile="undefined"!=typeof File,a.supportsBuffer=!1,a.supportsStream=!1,a.supportsString=!0,a.supportsArrayBuffer=!0,a.supportsEncryptFile=!0,a.supportsFileUri=!1;function c(e){const t=e.replace(/==?$/,""),s=Math.floor(t.length/4*3),n=new ArrayBuffer(s),r=new Uint8Array(n);let i=0;function o(){const e=t.charAt(i++),s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(e);if(-1===s)throw new Error(`Illegal character at ${i}: ${t.charAt(i-1)}`);return s}for(let e=0;e>4,c=(15&s)<<4|n>>2,u=(3&n)<<6|i;r[e]=a,64!=n&&(r[e+1]=c),64!=i&&(r[e+2]=u)}return n}function u(e){let t="";const s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=new Uint8Array(e),r=n.byteLength,i=r%3,o=r-i;let a,c,u,l,h;for(let e=0;e>18,c=(258048&h)>>12,u=(4032&h)>>6,l=63&h,t+=s[a]+s[c]+s[u]+s[l];return 1==i?(h=n[o],a=(252&h)>>2,c=(3&h)<<4,t+=s[a]+s[c]+"=="):2==i&&(h=n[o]<<8|n[o+1],a=(64512&h)>>10,c=(1008&h)>>4,u=(15&h)<<2,t+=s[a]+s[c]+s[u]+"="),t}var l;!function(e){e.PNNetworkIssuesCategory="PNNetworkIssuesCategory",e.PNTimeoutCategory="PNTimeoutCategory",e.PNCancelledCategory="PNCancelledCategory",e.PNBadRequestCategory="PNBadRequestCategory",e.PNAccessDeniedCategory="PNAccessDeniedCategory",e.PNValidationErrorCategory="PNValidationErrorCategory",e.PNAcknowledgmentCategory="PNAcknowledgmentCategory",e.PNUnknownCategory="PNUnknownCategory",e.PNNetworkUpCategory="PNNetworkUpCategory",e.PNNetworkDownCategory="PNNetworkDownCategory",e.PNReconnectedCategory="PNReconnectedCategory",e.PNConnectedCategory="PNConnectedCategory",e.PNRequestMessageCountExceededCategory="PNRequestMessageCountExceededCategory",e.PNDisconnectedCategory="PNDisconnectedCategory",e.PNConnectionErrorCategory="PNConnectionErrorCategory",e.PNDisconnectedUnexpectedlyCategory="PNDisconnectedUnexpectedlyCategory"}(l||(l={}));var h=l;class d extends Error{constructor(e,t){super(e),this.status=t,this.name="PubNubError",this.message=e,Object.setPrototypeOf(this,new.target.prototype)}}function p(e,t){return s=Object.assign({message:e},void 0!==t?{statusCode:t}:{}),null!==(n=s.statusCode)&&void 0!==n||(s.statusCode=0),Object.assign(Object.assign({},s),{statusCode:s.statusCode,category:h.PNValidationErrorCategory,error:!0});var s,n}var g,y,f,m,b,v=v||function(e,t){var s={},n=s.lib={},r=function(){},i=n.Base={extend:function(e){r.prototype=this;var t=new r;return e&&t.mixIn(e),t.hasOwnProperty("init")||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},o=n.WordArray=i.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||c).stringify(this)},concat:function(e){var t=this.words,s=e.words,n=this.sigBytes;if(e=e.sigBytes,this.clamp(),n%4)for(var r=0;r>>2]|=(s[r>>>2]>>>24-r%4*8&255)<<24-(n+r)%4*8;else if(65535>>2]=s[r>>>2];else t.push.apply(t,s);return this.sigBytes+=e,this},clamp:function(){var t=this.words,s=this.sigBytes;t[s>>>2]&=4294967295<<32-s%4*8,t.length=e.ceil(s/4)},clone:function(){var e=i.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var s=[],n=0;n>>2]>>>24-n%4*8&255;s.push((r>>>4).toString(16)),s.push((15&r).toString(16))}return s.join("")},parse:function(e){for(var t=e.length,s=[],n=0;n>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new o.init(s,t/2)}},u=a.Latin1={stringify:function(e){var t=e.words;e=e.sigBytes;for(var s=[],n=0;n>>2]>>>24-n%4*8&255));return s.join("")},parse:function(e){for(var t=e.length,s=[],n=0;n>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new o.init(s,t)}},l=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},h=n.BufferedBlockAlgorithm=i.extend({reset:function(){this._data=new o.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=l.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var s=this._data,n=s.words,r=s.sigBytes,i=this.blockSize,a=r/(4*i);if(t=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*i,r=e.min(4*t,r),t){for(var c=0;cu;){var l;e:{l=c;for(var h=e.sqrt(l),d=2;d<=h;d++)if(!(l%d)){l=!1;break e}l=!0}l&&(8>u&&(i[u]=a(e.pow(c,.5))),o[u]=a(e.pow(c,1/3)),u++),c++}var p=[];r=r.SHA256=n.extend({_doReset:function(){this._hash=new s.init(i.slice(0))},_doProcessBlock:function(e,t){for(var s=this._hash.words,n=s[0],r=s[1],i=s[2],a=s[3],c=s[4],u=s[5],l=s[6],h=s[7],d=0;64>d;d++){if(16>d)p[d]=0|e[t+d];else{var g=p[d-15],y=p[d-2];p[d]=((g<<25|g>>>7)^(g<<14|g>>>18)^g>>>3)+p[d-7]+((y<<15|y>>>17)^(y<<13|y>>>19)^y>>>10)+p[d-16]}g=h+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&u^~c&l)+o[d]+p[d],y=((n<<30|n>>>2)^(n<<19|n>>>13)^(n<<10|n>>>22))+(n&r^n&i^r&i),h=l,l=u,u=c,c=a+g|0,a=i,i=r,r=n,n=g+y|0}s[0]=s[0]+n|0,s[1]=s[1]+r|0,s[2]=s[2]+i|0,s[3]=s[3]+a|0,s[4]=s[4]+c|0,s[5]=s[5]+u|0,s[6]=s[6]+l|0,s[7]=s[7]+h|0},_doFinalize:function(){var t=this._data,s=t.words,n=8*this._nDataBytes,r=8*t.sigBytes;return s[r>>>5]|=128<<24-r%32,s[14+(r+64>>>9<<4)]=e.floor(n/4294967296),s[15+(r+64>>>9<<4)]=n,t.sigBytes=4*s.length,this._process(),this._hash},clone:function(){var e=n.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=n._createHelper(r),t.HmacSHA256=n._createHmacHelper(r)}(Math),y=(g=v).enc.Utf8,g.algo.HMAC=g.lib.Base.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=y.parse(t));var s=e.blockSize,n=4*s;t.sigBytes>n&&(t=e.finalize(t)),t.clamp();for(var r=this._oKey=t.clone(),i=this._iKey=t.clone(),o=r.words,a=i.words,c=0;c>>2]>>>24-r%4*8&255)<<16|(t[r+1>>>2]>>>24-(r+1)%4*8&255)<<8|t[r+2>>>2]>>>24-(r+2)%4*8&255,o=0;4>o&&r+.75*o>>6*(3-o)&63));if(t=n.charAt(64))for(;e.length%4;)e.push(t);return e.join("")},parse:function(e){var t=e.length,s=this._map;(n=s.charAt(64))&&-1!=(n=e.indexOf(n))&&(t=n);for(var n=[],r=0,i=0;i>>6-i%4*2;n[r>>>2]|=(o|a)<<24-r%4*8,r++}return m.create(n,r)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},function(e){function t(e,t,s,n,r,i,o){return((e=e+(t&s|~t&n)+r+o)<>>32-i)+t}function s(e,t,s,n,r,i,o){return((e=e+(t&n|s&~n)+r+o)<>>32-i)+t}function n(e,t,s,n,r,i,o){return((e=e+(t^s^n)+r+o)<>>32-i)+t}function r(e,t,s,n,r,i,o){return((e=e+(s^(t|~n))+r+o)<>>32-i)+t}for(var i=v,o=(c=i.lib).WordArray,a=c.Hasher,c=i.algo,u=[],l=0;64>l;l++)u[l]=4294967296*e.abs(e.sin(l+1))|0;c=c.MD5=a.extend({_doReset:function(){this._hash=new o.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,i){for(var o=0;16>o;o++){var a=e[c=i+o];e[c]=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8)}o=this._hash.words;var c=e[i+0],l=(a=e[i+1],e[i+2]),h=e[i+3],d=e[i+4],p=e[i+5],g=e[i+6],y=e[i+7],f=e[i+8],m=e[i+9],b=e[i+10],v=e[i+11],w=e[i+12],S=e[i+13],k=e[i+14],E=e[i+15],O=t(O=o[0],P=o[1],N=o[2],C=o[3],c,7,u[0]),C=t(C,O,P,N,a,12,u[1]),N=t(N,C,O,P,l,17,u[2]),P=t(P,N,C,O,h,22,u[3]);O=t(O,P,N,C,d,7,u[4]),C=t(C,O,P,N,p,12,u[5]),N=t(N,C,O,P,g,17,u[6]),P=t(P,N,C,O,y,22,u[7]),O=t(O,P,N,C,f,7,u[8]),C=t(C,O,P,N,m,12,u[9]),N=t(N,C,O,P,b,17,u[10]),P=t(P,N,C,O,v,22,u[11]),O=t(O,P,N,C,w,7,u[12]),C=t(C,O,P,N,S,12,u[13]),N=t(N,C,O,P,k,17,u[14]),O=s(O,P=t(P,N,C,O,E,22,u[15]),N,C,a,5,u[16]),C=s(C,O,P,N,g,9,u[17]),N=s(N,C,O,P,v,14,u[18]),P=s(P,N,C,O,c,20,u[19]),O=s(O,P,N,C,p,5,u[20]),C=s(C,O,P,N,b,9,u[21]),N=s(N,C,O,P,E,14,u[22]),P=s(P,N,C,O,d,20,u[23]),O=s(O,P,N,C,m,5,u[24]),C=s(C,O,P,N,k,9,u[25]),N=s(N,C,O,P,h,14,u[26]),P=s(P,N,C,O,f,20,u[27]),O=s(O,P,N,C,S,5,u[28]),C=s(C,O,P,N,l,9,u[29]),N=s(N,C,O,P,y,14,u[30]),O=n(O,P=s(P,N,C,O,w,20,u[31]),N,C,p,4,u[32]),C=n(C,O,P,N,f,11,u[33]),N=n(N,C,O,P,v,16,u[34]),P=n(P,N,C,O,k,23,u[35]),O=n(O,P,N,C,a,4,u[36]),C=n(C,O,P,N,d,11,u[37]),N=n(N,C,O,P,y,16,u[38]),P=n(P,N,C,O,b,23,u[39]),O=n(O,P,N,C,S,4,u[40]),C=n(C,O,P,N,c,11,u[41]),N=n(N,C,O,P,h,16,u[42]),P=n(P,N,C,O,g,23,u[43]),O=n(O,P,N,C,m,4,u[44]),C=n(C,O,P,N,w,11,u[45]),N=n(N,C,O,P,E,16,u[46]),O=r(O,P=n(P,N,C,O,l,23,u[47]),N,C,c,6,u[48]),C=r(C,O,P,N,y,10,u[49]),N=r(N,C,O,P,k,15,u[50]),P=r(P,N,C,O,p,21,u[51]),O=r(O,P,N,C,w,6,u[52]),C=r(C,O,P,N,h,10,u[53]),N=r(N,C,O,P,b,15,u[54]),P=r(P,N,C,O,a,21,u[55]),O=r(O,P,N,C,f,6,u[56]),C=r(C,O,P,N,E,10,u[57]),N=r(N,C,O,P,g,15,u[58]),P=r(P,N,C,O,S,21,u[59]),O=r(O,P,N,C,d,6,u[60]),C=r(C,O,P,N,v,10,u[61]),N=r(N,C,O,P,l,15,u[62]),P=r(P,N,C,O,m,21,u[63]);o[0]=o[0]+O|0,o[1]=o[1]+P|0,o[2]=o[2]+N|0,o[3]=o[3]+C|0},_doFinalize:function(){var t=this._data,s=t.words,n=8*this._nDataBytes,r=8*t.sigBytes;s[r>>>5]|=128<<24-r%32;var i=e.floor(n/4294967296);for(s[15+(r+64>>>9<<4)]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),s[14+(r+64>>>9<<4)]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),t.sigBytes=4*(s.length+1),this._process(),s=(t=this._hash).words,n=0;4>n;n++)r=s[n],s[n]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8);return t},clone:function(){var e=a.clone.call(this);return e._hash=this._hash.clone(),e}}),i.MD5=a._createHelper(c),i.HmacMD5=a._createHmacHelper(c)}(Math),function(){var e,t=v,s=(e=t.lib).Base,n=e.WordArray,r=(e=t.algo).EvpKDF=s.extend({cfg:s.extend({keySize:4,hasher:e.MD5,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var s=(a=this.cfg).hasher.create(),r=n.create(),i=r.words,o=a.keySize,a=a.iterations;i.length>>2]}},t.BlockCipher=a.extend({cfg:a.cfg.extend({mode:c,padding:l}),reset:function(){a.reset.call(this);var e=(t=this.cfg).iv,t=t.mode;if(this._xformMode==this._ENC_XFORM_MODE)var s=t.createEncryptor;else s=t.createDecryptor,this._minBufferSize=1;this._mode=s.call(t,this,e&&e.words)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){e.pad(this._data,this.blockSize);var t=this._process(!0)}else t=this._process(!0),e.unpad(t);return t},blockSize:4});var h=t.CipherParams=s.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),d=(c=(p.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext;return((e=e.salt)?n.create([1398893684,1701076831]).concat(e).concat(t):t).toString(i)},parse:function(e){var t=(e=i.parse(e)).words;if(1398893684==t[0]&&1701076831==t[1]){var s=n.create(t.slice(2,4));t.splice(0,4),e.sigBytes-=16}return h.create({ciphertext:e,salt:s})}},t.SerializableCipher=s.extend({cfg:s.extend({format:c}),encrypt:function(e,t,s,n){n=this.cfg.extend(n);var r=e.createEncryptor(s,n);return t=r.finalize(t),r=r.cfg,h.create({ciphertext:t,key:s,iv:r.iv,algorithm:e,mode:r.mode,padding:r.padding,blockSize:e.blockSize,formatter:n.format})},decrypt:function(e,t,s,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),e.createDecryptor(s,n).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}})),p=(p.kdf={}).OpenSSL={execute:function(e,t,s,r){return r||(r=n.random(8)),e=o.create({keySize:t+s}).compute(e,r),s=n.create(e.words.slice(t),4*s),e.sigBytes=4*t,h.create({key:e,iv:s,salt:r})}},g=t.PasswordBasedCipher=d.extend({cfg:d.cfg.extend({kdf:p}),encrypt:function(e,t,s,n){return s=(n=this.cfg.extend(n)).kdf.execute(s,e.keySize,e.ivSize),n.iv=s.iv,(e=d.encrypt.call(this,e,t,s.key,n)).mixIn(s),e},decrypt:function(e,t,s,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),s=n.kdf.execute(s,e.keySize,e.ivSize,t.salt),n.iv=s.iv,d.decrypt.call(this,e,t,s.key,n)}})}(),function(){for(var e=v,t=e.lib.BlockCipher,s=e.algo,n=[],r=[],i=[],o=[],a=[],c=[],u=[],l=[],h=[],d=[],p=[],g=0;256>g;g++)p[g]=128>g?g<<1:g<<1^283;var y=0,f=0;for(g=0;256>g;g++){var m=(m=f^f<<1^f<<2^f<<3^f<<4)>>>8^255&m^99;n[y]=m,r[m]=y;var b=p[y],w=p[b],S=p[w],k=257*p[m]^16843008*m;i[y]=k<<24|k>>>8,o[y]=k<<16|k>>>16,a[y]=k<<8|k>>>24,c[y]=k,k=16843009*S^65537*w^257*b^16843008*y,u[m]=k<<24|k>>>8,l[m]=k<<16|k>>>16,h[m]=k<<8|k>>>24,d[m]=k,y?(y=b^p[p[p[S^b]]],f^=p[p[f]]):y=f=1}var E=[0,1,2,4,8,16,32,64,128,27,54];s=s.AES=t.extend({_doReset:function(){for(var e=(s=this._key).words,t=s.sigBytes/4,s=4*((this._nRounds=t+6)+1),r=this._keySchedule=[],i=0;i>>24]<<24|n[o>>>16&255]<<16|n[o>>>8&255]<<8|n[255&o]):(o=n[(o=o<<8|o>>>24)>>>24]<<24|n[o>>>16&255]<<16|n[o>>>8&255]<<8|n[255&o],o^=E[i/t|0]<<24),r[i]=r[i-t]^o}for(e=this._invKeySchedule=[],t=0;tt||4>=i?o:u[n[o>>>24]]^l[n[o>>>16&255]]^h[n[o>>>8&255]]^d[n[255&o]]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,i,o,a,c,n)},decryptBlock:function(e,t){var s=e[t+1];e[t+1]=e[t+3],e[t+3]=s,this._doCryptBlock(e,t,this._invKeySchedule,u,l,h,d,r),s=e[t+1],e[t+1]=e[t+3],e[t+3]=s},_doCryptBlock:function(e,t,s,n,r,i,o,a){for(var c=this._nRounds,u=e[t]^s[0],l=e[t+1]^s[1],h=e[t+2]^s[2],d=e[t+3]^s[3],p=4,g=1;g>>24]^r[l>>>16&255]^i[h>>>8&255]^o[255&d]^s[p++],f=n[l>>>24]^r[h>>>16&255]^i[d>>>8&255]^o[255&u]^s[p++],m=n[h>>>24]^r[d>>>16&255]^i[u>>>8&255]^o[255&l]^s[p++];d=n[d>>>24]^r[u>>>16&255]^i[l>>>8&255]^o[255&h]^s[p++],u=y,l=f,h=m}y=(a[u>>>24]<<24|a[l>>>16&255]<<16|a[h>>>8&255]<<8|a[255&d])^s[p++],f=(a[l>>>24]<<24|a[h>>>16&255]<<16|a[d>>>8&255]<<8|a[255&u])^s[p++],m=(a[h>>>24]<<24|a[d>>>16&255]<<16|a[u>>>8&255]<<8|a[255&l])^s[p++],d=(a[d>>>24]<<24|a[u>>>16&255]<<16|a[l>>>8&255]<<8|a[255&h])^s[p++],e[t]=y,e[t+1]=f,e[t+2]=m,e[t+3]=d},keySize:8});e.AES=t._createHelper(s)}(),v.mode.ECB=((b=v.lib.BlockCipherMode.extend()).Encryptor=b.extend({processBlock:function(e,t){this._cipher.encryptBlock(e,t)}}),b.Decryptor=b.extend({processBlock:function(e,t){this._cipher.decryptBlock(e,t)}}),b);var w=t(v);class S{constructor({cipherKey:e}){this.cipherKey=e,this.CryptoJS=w,this.encryptedKey=this.CryptoJS.SHA256(e)}encrypt(e){if(0===("string"==typeof e?e:S.decoder.decode(e)).length)throw new Error("encryption error. empty content");const t=this.getIv();return{metadata:t,data:c(this.CryptoJS.AES.encrypt(e,this.encryptedKey,{iv:this.bufferToWordArray(t),mode:this.CryptoJS.mode.CBC}).ciphertext.toString(this.CryptoJS.enc.Base64))}}encryptFileData(e){return i(this,void 0,void 0,(function*(){const t=yield this.getKey(),s=this.getIv();return{data:yield crypto.subtle.encrypt({name:this.algo,iv:s},t,e),metadata:s}}))}decrypt(e){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=this.bufferToWordArray(new Uint8ClampedArray(e.metadata)),s=this.bufferToWordArray(new Uint8ClampedArray(e.data));return S.encoder.encode(this.CryptoJS.AES.decrypt({ciphertext:s},this.encryptedKey,{iv:t,mode:this.CryptoJS.mode.CBC}).toString(this.CryptoJS.enc.Utf8)).buffer}decryptFileData(e){return i(this,void 0,void 0,(function*(){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=yield this.getKey();return crypto.subtle.decrypt({name:this.algo,iv:e.metadata},t,e.data)}))}get identifier(){return"ACRH"}get algo(){return"AES-CBC"}getIv(){return crypto.getRandomValues(new Uint8Array(S.BLOCK_SIZE))}getKey(){return i(this,void 0,void 0,(function*(){const e=S.encoder.encode(this.cipherKey),t=yield crypto.subtle.digest("SHA-256",e.buffer);return crypto.subtle.importKey("raw",t,this.algo,!0,["encrypt","decrypt"])}))}bufferToWordArray(e){const t=[];let s;for(s=0;se.toString(16).padStart(2,"0"))).join(""),n=C.encoder.encode(s.slice(0,32)).buffer;return crypto.subtle.importKey("raw",n,"AES-CBC",!0,["encrypt","decrypt"])}))}}C.IV_LENGTH=16,C.encoder=new TextEncoder,C.decoder=new TextDecoder;class N{constructor(e){this.config=e,this.cryptor=new E(Object.assign({},e)),this.fileCryptor=new C}encrypt(e){const t="string"==typeof e?e:N.decoder.decode(e);return{data:this.cryptor.encrypt(t),metadata:null}}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if(!this.config.cipherKey)throw new d("File encryption error: cipher key not set.");return this.fileCryptor.encryptFile(null===(s=this.config)||void 0===s?void 0:s.cipherKey,e,t)}))}decrypt(e){const t="string"==typeof e.data?e.data:u(e.data);return this.cryptor.decrypt(t)}decryptFile(e,t){return i(this,void 0,void 0,(function*(){if(!this.config.cipherKey)throw new d("File encryption error: cipher key not set.");return this.fileCryptor.decryptFile(this.config.cipherKey,e,t)}))}get identifier(){return""}}N.encoder=new TextEncoder,N.decoder=new TextDecoder;class P extends o{static legacyCryptoModule(e){var t;if(!e.cipherKey)throw new d("Crypto module error: cipher key not set.");return new P({default:new N(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t})),cryptors:[new S({cipherKey:e.cipherKey})]})}static aesCbcCryptoModule(e){var t;if(!e.cipherKey)throw new d("Crypto module error: cipher key not set.");return new P({default:new S({cipherKey:e.cipherKey}),cryptors:[new N(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t}))]})}static withDefaultCryptor(e){return new this({default:e})}encrypt(e){const t=e instanceof ArrayBuffer&&this.defaultCryptor.identifier===P.LEGACY_IDENTIFIER?this.defaultCryptor.encrypt(P.decoder.decode(e)):this.defaultCryptor.encrypt(e);if(!t.metadata)return t.data;if("string"==typeof t.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");const s=this.getHeaderData(t);return this.concatArrayBuffer(s,t.data)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){if(this.defaultCryptor.identifier===M.LEGACY_IDENTIFIER)return this.defaultCryptor.encryptFile(e,t);const s=yield this.getFileData(e),n=yield this.defaultCryptor.encryptFileData(s);if("string"==typeof n.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");return t.create({name:e.name,mimeType:"application/octet-stream",data:this.concatArrayBuffer(this.getHeaderData(n),n.data)})}))}decrypt(e){const t="string"==typeof e?c(e):e,s=M.tryParse(t),n=this.getCryptor(s),r=s.length>0?t.slice(s.length-s.metadataLength,s.length):null;if(t.slice(s.length).byteLength<=0)throw new Error("Decryption error: empty content");return n.decrypt({data:t.slice(s.length),metadata:r})}decryptFile(e,t){return i(this,void 0,void 0,(function*(){const s=yield e.data.arrayBuffer(),n=M.tryParse(s),r=this.getCryptor(n);if((null==r?void 0:r.identifier)===M.LEGACY_IDENTIFIER)return r.decryptFile(e,t);const i=(yield this.getFileData(s)).slice(n.length-n.metadataLength,n.length);return t.create({name:e.name,data:yield this.defaultCryptor.decryptFileData({data:s.slice(n.length),metadata:i})})}))}getCryptorFromId(e){const t=this.getAllCryptors().find((t=>e===t.identifier));if(t)return t;throw Error("Unknown cryptor error")}getCryptor(e){if("string"==typeof e){const t=this.getAllCryptors().find((t=>t.identifier===e));if(t)return t;throw new Error("Unknown cryptor error")}if(e instanceof _)return this.getCryptorFromId(e.identifier)}getHeaderData(e){if(!e.metadata)return;const t=M.from(this.defaultCryptor.identifier,e.metadata),s=new Uint8Array(t.length);let n=0;return s.set(t.data,n),n+=t.length-e.metadata.byteLength,s.set(new Uint8Array(e.metadata),n),s.buffer}concatArrayBuffer(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(new Uint8Array(e),0),s.set(new Uint8Array(t),e.byteLength),s.buffer}getFileData(e){return i(this,void 0,void 0,(function*(){if(e instanceof ArrayBuffer)return e;if(e instanceof a)return e.toArrayBuffer();throw new Error("Cannot decrypt/encrypt file. In browsers file encrypt/decrypt supported for string, ArrayBuffer or Blob")}))}}P.LEGACY_IDENTIFIER="";class M{static from(e,t){if(e!==M.LEGACY_IDENTIFIER)return new _(e,t.byteLength)}static tryParse(e){const t=new Uint8Array(e);let s,n,r=null;if(t.byteLength>=4&&(s=t.slice(0,4),this.decoder.decode(s)!==M.SENTINEL))return P.LEGACY_IDENTIFIER;if(!(t.byteLength>=5))throw new Error("Decryption error: invalid header version");if(r=t[4],r>M.MAX_VERSION)throw new Error("Decryption error: Unknown cryptor error");let i=5+M.IDENTIFIER_LENGTH;if(!(t.byteLength>=i))throw new Error("Decryption error: invalid crypto identifier");n=t.slice(5,i);let o=null;if(!(t.byteLength>=i+1))throw new Error("Decryption error: invalid metadata length");return o=t[i],i+=1,255===o&&t.byteLength>=i+2&&(o=new Uint16Array(t.slice(i,i+2)).reduce(((e,t)=>(e<<8)+t),0)),new _(this.decoder.decode(n),o)}}M.SENTINEL="PNED",M.LEGACY_IDENTIFIER="",M.IDENTIFIER_LENGTH=4,M.VERSION=1,M.MAX_VERSION=1,M.decoder=new TextDecoder;class _{constructor(e,t){this._identifier=e,this._metadataLength=t}get identifier(){return this._identifier}set identifier(e){this._identifier=e}get metadataLength(){return this._metadataLength}set metadataLength(e){this._metadataLength=e}get version(){return M.VERSION}get length(){return M.SENTINEL.length+1+M.IDENTIFIER_LENGTH+(this.metadataLength<255?1:3)+this.metadataLength}get data(){let e=0;const t=new Uint8Array(this.length),s=new TextEncoder;t.set(s.encode(M.SENTINEL)),e+=M.SENTINEL.length,t[e]=this.version,e++,this.identifier&&t.set(s.encode(this.identifier),e);const n=this.metadataLength;return e+=M.IDENTIFIER_LENGTH,n<255?t[e]=n:t.set([255,n>>8,255&n],e),t}}_.IDENTIFIER_LENGTH=4,_.SENTINEL="PNED";class A extends Error{static create(e,t){return e instanceof Error?A.createFromError(e):A.createFromServiceResponse(e,t)}static createFromError(e){let t=h.PNUnknownCategory,s="Unknown error",n="Error";if(!e)return new A(s,t,0);if(e instanceof A)return e;if(e instanceof Error&&(s=e.message,n=e.name),"AbortError"===n||-1!==s.indexOf("Aborted"))t=h.PNCancelledCategory,s="Request cancelled";else if(-1!==s.indexOf("timeout"))t=h.PNTimeoutCategory,s="Request timeout";else if(-1!==s.indexOf("network"))t=h.PNNetworkIssuesCategory,s="Network issues";else if("TypeError"===n)t=-1!==s.indexOf("Load failed")||-1!=s.indexOf("Failed to fetch")?h.PNTimeoutCategory:h.PNBadRequestCategory;else if("FetchError"===n){const n=e.code;["ECONNREFUSED","ENETUNREACH","ENOTFOUND","ECONNRESET","EAI_AGAIN"].includes(n)&&(t=h.PNNetworkIssuesCategory),"ECONNREFUSED"===n?s="Connection refused":"ENETUNREACH"===n?s="Network not reachable":"ENOTFOUND"===n?s="Server not found":"ECONNRESET"===n?s="Connection reset by peer":"EAI_AGAIN"===n?s="Name resolution error":"ETIMEDOUT"===n?(t=h.PNTimeoutCategory,s="Request timeout"):s=`Unknown system error: ${e}`}else"Request timeout"===s&&(t=h.PNTimeoutCategory);return new A(s,t,0,e)}static createFromServiceResponse(e,t){let s,n=h.PNUnknownCategory,r="Unknown error",{status:i}=e;if(null!=t||(t=e.body),402===i?r="Not available for used key set. Contact support@pubnub.com":400===i?(n=h.PNBadRequestCategory,r="Bad request"):403===i&&(n=h.PNAccessDeniedCategory,r="Access denied"),t&&t.byteLength>0){const n=(new TextDecoder).decode(t);if(-1!==e.headers["content-type"].indexOf("text/javascript")||-1!==e.headers["content-type"].indexOf("application/json"))try{const e=JSON.parse(n);"object"!=typeof e||Array.isArray(e)||("error"in e&&(1===e.error||!0===e.error)&&"status"in e&&"number"==typeof e.status&&"message"in e&&"service"in e?(s=e,i=e.status):s=e,"error"in e&&e.error instanceof Error&&(s=e.error))}catch(e){s=n}else if(-1!==e.headers["content-type"].indexOf("xml")){const e=/(.*)<\/Message>/gi.exec(n);r=e?`Upload to bucket failed: ${e[1]}`:"Upload to bucket failed."}else s=n}return new A(r,n,i,s)}constructor(e,t,s,n){super(e),this.category=t,this.statusCode=s,this.errorData=n,this.name="PubNubAPIError"}toStatus(e){return{error:!0,category:this.category,operation:e,statusCode:this.statusCode,errorData:this.errorData}}toPubNubError(e,t){return new d(null!=t?t:this.message,this.toStatus(e))}}class j{constructor(e){this.configuration=e,this.subscriptionWorkerReady=!1,this.workerEventsQueue=[],this.callbacks=new Map,this.setupSubscriptionWorker()}makeSendable(e){if(!e.path.startsWith("/v2/subscribe")&&!e.path.endsWith("/leave"))return this.configuration.transport.makeSendable(e);let t;const s={type:"send-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,logVerbosity:this.configuration.logVerbosity,request:e};return e.cancellable&&(t={abort:()=>{const t={type:"cancel-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,logVerbosity:this.configuration.logVerbosity,identifier:e.identifier};this.scheduleEventPost(t)}}),[new Promise(((t,n)=>{this.callbacks.set(e.identifier,{resolve:t,reject:n}),this.scheduleEventPost(s)})),t]}request(e){return e}scheduleEventPost(e,t=!1){const s=this.sharedSubscriptionWorker;s?s.port.postMessage(e):t?this.workerEventsQueue.splice(0,0,e):this.workerEventsQueue.push(e)}flushScheduledEvents(){const e=this.sharedSubscriptionWorker;if(!e||0===this.workerEventsQueue.length)return;const t=[];for(let e=0;e!t.includes(e))),this.workerEventsQueue.forEach((t=>e.port.postMessage(t))),this.workerEventsQueue=[]}get sharedSubscriptionWorker(){return this.subscriptionWorkerReady?this.subscriptionWorker:null}setupSubscriptionWorker(){"undefined"!=typeof SharedWorker&&(this.subscriptionWorker=new SharedWorker(this.configuration.workerUrl,`/pubnub-${this.configuration.sdkVersion}`),this.subscriptionWorker.port.start(),this.scheduleEventPost({type:"client-register",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,userId:this.configuration.userId,logVerbosity:this.configuration.logVerbosity,workerLogVerbosity:this.configuration.workerLogVerbosity},!0),this.subscriptionWorker.port.onmessage=e=>this.handleWorkerEvent(e))}handleWorkerEvent(e){const{data:t}=e;if("shared-worker-ping"===t.type||"shared-worker-connected"===t.type||"shared-worker-console-log"===t.type||"shared-worker-console-dir"===t.type||t.clientIdentifier===this.configuration.clientIdentifier)if("shared-worker-connected"===t.type)this.subscriptionWorkerReady=!0,this.flushScheduledEvents();else if("shared-worker-console-log"===t.type)console.log(`[SharedWorker] ${t.message}`);else if("shared-worker-console-dir"===t.type)t.message&&console.log(`[SharedWorker] ${t.message}`),console.dir(t.data);else if("shared-worker-ping"===t.type){const{logVerbosity:e,subscriptionKey:t,clientIdentifier:s}=this.configuration;this.scheduleEventPost({type:"client-pong",subscriptionKey:t,clientIdentifier:s,logVerbosity:e})}else if("request-progress-start"===t.type||"request-progress-end"===t.type)this.logRequestProgress(t);else if("request-process-success"===t.type||"request-process-error"===t.type){const{resolve:e,reject:s}=this.callbacks.get(t.identifier);if("request-process-success"===t.type)e({status:t.response.status,url:t.url,headers:t.response.headers,body:t.response.body});else{let e=h.PNUnknownCategory,n="Unknown error";if(t.error)"NETWORK_ISSUE"===t.error.type?e=h.PNNetworkIssuesCategory:"TIMEOUT"===t.error.type?e=h.PNTimeoutCategory:"ABORTED"===t.error.type&&(e=h.PNCancelledCategory),n=`${t.error.message} (${t.identifier})`;else if(t.response)return s(A.create({url:t.url,headers:t.response.headers,body:t.response.body,status:t.response.status},t.response.body));s(new A(n,e,0,new Error(n)))}}}logRequestProgress(e){var t,s;"request-progress-start"===e.type?(console.log("<<<<<"),console.log(`[${e.timestamp}] ${e.url}\n${JSON.stringify(null!==(t=e.query)&&void 0!==t?t:{})}`),console.log("-----")):(console.log(">>>>>>"),console.log(`[${e.timestamp} / ${e.duration}] ${e.url}\n${JSON.stringify(null!==(s=e.query)&&void 0!==s?s:{})}\n${e.response}`),console.log("-----"))}}const I=e=>encodeURIComponent(e).replace(/[!~*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)),R=(e,t)=>{const s=e.map((e=>I(e)));return s.length?s.join(","):null!=t?t:""},U=(e,t)=>{const s=Object.fromEntries(t.map((e=>[e,!1])));return e.filter((e=>!(t.includes(e)&&!s[e])||(s[e]=!0,!1)))},T=(e,t)=>[...e].filter((s=>t.includes(s)&&e.indexOf(s)===e.lastIndexOf(s)&&t.indexOf(s)===t.lastIndexOf(s)));class F{constructor(e=!1,t){this.keepAlive=e,this.logVerbosity=t}makeSendable(e){let t,s;return e.cancellable&&(s=new AbortController,t={abortController:s,abort:()=>null==s?void 0:s.abort()}),[this.requestFromTransportRequest(e).then((t=>{const n=(new Date).getTime();this.logRequestProcessProgress(t);const r=new Promise(((t,s)=>{const n=setTimeout((()=>{clearTimeout(n),s(new Error("Request timeout"))}),1e3*e.timeout)}));return Promise.race([fetch(t,{signal:null==s?void 0:s.signal}),r]).then((e=>e.arrayBuffer().then((t=>[e,t])))).then((e=>{const s=e[1].byteLength>0?e[1]:void 0,{status:r,headers:i}=e[0],o={};i.forEach(((e,t)=>o[t]=e.toLowerCase()));const a={status:r,url:t.url,headers:o,body:s};if(r>=400)throw A.create(a);return this.logRequestProcessProgress(t,(new Date).getTime()-n,s),a})).catch((e=>{throw A.create(e)}))})),t]}request(e){return e}requestFromTransportRequest(e){return i(this,void 0,void 0,(function*(){let t,s=e.path;if(e.formData&&e.formData.length>0){e.queryParameters={};const s=e.body,n=new FormData;for(const{key:t,value:s}of e.formData)n.append(t,s);try{const e=yield s.toArrayBuffer();n.append("file",new Blob([e],{type:"application/octet-stream"}),s.name)}catch(e){try{const e=yield s.toFileUri();n.append("file",e,s.name)}catch(e){}}t=n}else e.body&&("string"==typeof e.body||e.body instanceof ArrayBuffer)&&(t=e.body);var n;return e.queryParameters&&0!==Object.keys(e.queryParameters).length&&(s=`${s}?${n=e.queryParameters,Object.keys(n).map((e=>{const t=n[e];return Array.isArray(t)?t.map((t=>`${e}=${I(t)}`)).join("&"):`${e}=${I(t)}`})).join("&")}`),new Request(`${e.origin}${s}`,{method:e.method,headers:e.headers,redirect:"follow",body:t})}))}logRequestProcessProgress(e,t,s){if(!this.logVerbosity)return;const{protocol:n,host:r,pathname:i,search:o}=new URL(e.url),a=(new Date).toISOString();if(t){const e=s?F.decoder.decode(s):void 0;console.log(">>>>>>"),console.log(`[${a} / ${t}]`,`\n${n}//${r}${i}`,`\n${o}`,`\n${e}`),console.log("-----")}else console.log("<<<<<"),console.log(`[${a}]`,`\n${n}//${r}${i}`,`\n${o}`),console.log("-----")}}function x(e){const t=e=>"object"==typeof e&&null!==e&&e.constructor===Object,s=e=>"number"==typeof e&&isFinite(e);if(!t(e))return e;const n={};return Object.keys(e).forEach((r=>{const i=(e=>"string"==typeof e||e instanceof String)(r);let o=r;const a=e[r];if(i&&r.indexOf(",")>=0){o=r.split(",").map(Number).reduce(((e,t)=>e+String.fromCharCode(t)),"")}else(s(r)||i&&!isNaN(Number(r)))&&(o=String.fromCharCode(s(r)?r:parseInt(r,10)));n[o]=t(a)?x(a):a})),n}F.decoder=new TextDecoder;const D=e=>{var t,s,n;return e.subscriptionWorkerUrl&&"undefined"==typeof SharedWorker&&(e.subscriptionWorkerUrl=null),Object.assign(Object.assign({},(e=>{var t,s,n,r,i,o,a,c,u,l,h,p,g,y;const f=Object.assign({},e);if(null!==(t=f.logVerbosity)&&void 0!==t||(f.logVerbosity=!1),null!==(s=f.ssl)&&void 0!==s||(f.ssl=!0),null!==(n=f.transactionalRequestTimeout)&&void 0!==n||(f.transactionalRequestTimeout=15),null!==(r=f.subscribeRequestTimeout)&&void 0!==r||(f.subscribeRequestTimeout=310),null!==(i=f.restore)&&void 0!==i||(f.restore=!1),null!==(o=f.useInstanceId)&&void 0!==o||(f.useInstanceId=!1),null!==(a=f.suppressLeaveEvents)&&void 0!==a||(f.suppressLeaveEvents=!1),null!==(c=f.requestMessageCountThreshold)&&void 0!==c||(f.requestMessageCountThreshold=100),null!==(u=f.autoNetworkDetection)&&void 0!==u||(f.autoNetworkDetection=!1),null!==(l=f.enableEventEngine)&&void 0!==l||(f.enableEventEngine=!1),null!==(h=f.maintainPresenceState)&&void 0!==h||(f.maintainPresenceState=!0),null!==(p=f.keepAlive)&&void 0!==p||(f.keepAlive=!1),f.userId&&f.uuid)throw new d("PubNub client configuration error: use only 'userId'");if(null!==(g=f.userId)&&void 0!==g||(f.userId=f.uuid),!f.userId)throw new d("PubNub client configuration error: 'userId' not set");if(0===(null===(y=f.userId)||void 0===y?void 0:y.trim().length))throw new d("PubNub client configuration error: 'userId' is empty");f.origin||(f.origin=Array.from({length:20},((e,t)=>`ps${t+1}.pndsn.com`)));const m={subscribeKey:f.subscribeKey,publishKey:f.publishKey,secretKey:f.secretKey};void 0!==f.presenceTimeout&&f.presenceTimeout<20&&(f.presenceTimeout=20,console.log("WARNING: Presence timeout is less than the minimum. Using minimum value: ",20)),void 0!==f.presenceTimeout?f.heartbeatInterval=f.presenceTimeout/2-1:f.presenceTimeout=300;let b=!1,v=!0,w=5,S=!1,k=!0;return void 0!==f.dedupeOnSubscribe&&"boolean"==typeof f.dedupeOnSubscribe&&(S=f.dedupeOnSubscribe),void 0!==f.useRequestId&&"boolean"==typeof f.useRequestId&&(k=f.useRequestId),void 0!==f.announceSuccessfulHeartbeats&&"boolean"==typeof f.announceSuccessfulHeartbeats&&(b=f.announceSuccessfulHeartbeats),void 0!==f.announceFailedHeartbeats&&"boolean"==typeof f.announceFailedHeartbeats&&(v=f.announceFailedHeartbeats),void 0!==f.fileUploadPublishRetryLimit&&"number"==typeof f.fileUploadPublishRetryLimit&&(w=f.fileUploadPublishRetryLimit),Object.assign(Object.assign({},f),{keySet:m,dedupeOnSubscribe:S,maximumCacheSize:100,useRequestId:k,announceSuccessfulHeartbeats:b,announceFailedHeartbeats:v,fileUploadPublishRetryLimit:w})})(e)),{listenToBrowserNetworkEvents:null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t,subscriptionWorkerUrl:e.subscriptionWorkerUrl,subscriptionWorkerLogVerbosity:null!==(s=e.subscriptionWorkerLogVerbosity)&&void 0!==s&&s,keepAlive:null===(n=e.keepAlive)||void 0===n||n})};var q={exports:{}}; -/*! lil-uuid - v0.1 - MIT License - https://github.com/lil-js/uuid */!function(e,t){!function(e){var t="0.1.0",s={3:/^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,4:/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,5:/^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,all:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i};function n(){var e,t,s="";for(e=0;e<32;e++)t=16*Math.random()|0,8!==e&&12!==e&&16!==e&&20!==e||(s+="-"),s+=(12===e?4:16===e?3&t|8:t).toString(16);return s}function r(e,t){var n=s[t||"all"];return n&&n.test(e)||!1}n.isUUID=r,n.VERSION=t,e.uuid=n,e.isUUID=r}(t),null!==e&&(e.exports=t.uuid)}(q,q.exports);var G=t(q.exports),K={createUUID:()=>G.uuid?G.uuid():G()};const $=(e,t)=>{var s,n,r;null===(s=e.retryConfiguration)||void 0===s||s.validate(),null!==(n=e.useRandomIVs)&&void 0!==n||(e.useRandomIVs=true),e.origin=L(null!==(r=e.ssl)&&void 0!==r&&r,e.origin);const i=e.cryptoModule;i&&delete e.cryptoModule;const o=Object.assign(Object.assign({},e),{_pnsdkSuffix:{},_instanceId:`pn-${K.createUUID()}`,_cryptoModule:void 0,_cipherKey:void 0,_setupCryptoModule:t,get instanceId(){if(this.useInstanceId)return this._instanceId},getUserId(){return this.userId},setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this.userId=e},getAuthKey(){return this.authKey},setAuthKey(e){this.authKey=e},getFilterExpression(){return this.filterExpression},setFilterExpression(e){this.filterExpression=e},getCipherKey(){return this._cipherKey},setCipherKey(t){this._cipherKey=t,t||!this._cryptoModule?t&&this._setupCryptoModule&&(this._cryptoModule=this._setupCryptoModule({cipherKey:t,useRandomIVs:e.useRandomIVs,customEncrypt:this.getCustomEncrypt(),customDecrypt:this.getCustomDecrypt()})):this._cryptoModule=void 0},getCryptoModule(){return this._cryptoModule},getUseRandomIVs:()=>e.useRandomIVs,setPresenceTimeout(e){this.heartbeatInterval=e/2-1,this.presenceTimeout=e},getPresenceTimeout(){return this.presenceTimeout},getHeartbeatInterval(){return this.heartbeatInterval},setHeartbeatInterval(e){this.heartbeatInterval=e},getTransactionTimeout(){return this.transactionalRequestTimeout},getSubscribeTimeout(){return this.subscribeRequestTimeout},get PubNubFile(){return e.PubNubFile},get version(){return"8.2.8"},getVersion(){return this.version},_addPnsdkSuffix(e,t){this._pnsdkSuffix[e]=`${t}`},_getPnsdkSuffix(e){const t=Object.values(this._pnsdkSuffix).join(e);return t.length>0?e+t:""},getUUID(){return this.getUserId()},setUUID(e){this.setUserId(e)},getCustomEncrypt:()=>e.customEncrypt,getCustomDecrypt:()=>e.customDecrypt});return e.cipherKey?o.setCipherKey(e.cipherKey):i&&(o._cryptoModule=i),o},L=(e,t)=>{const s=e?"https://":"http://";return"string"==typeof t?`${s}${t}`:`${s}${t[Math.floor(Math.random()*t.length)]}`};class B{constructor(e){this.cbor=e}setToken(e){e&&e.length>0?this.token=e:this.token=void 0}getToken(){return this.token}parseToken(e){const t=this.cbor.decodeToken(e);if(void 0!==t){const e=t.res.uuid?Object.keys(t.res.uuid):[],s=Object.keys(t.res.chan),n=Object.keys(t.res.grp),r=t.pat.uuid?Object.keys(t.pat.uuid):[],i=Object.keys(t.pat.chan),o=Object.keys(t.pat.grp),a={version:t.v,timestamp:t.t,ttl:t.ttl,authorized_uuid:t.uuid,signature:t.sig},c=e.length>0,u=s.length>0,l=n.length>0;if(c||u||l){if(a.resources={},c){const s=a.resources.uuids={};e.forEach((e=>s[e]=this.extractPermissions(t.res.uuid[e])))}if(u){const e=a.resources.channels={};s.forEach((s=>e[s]=this.extractPermissions(t.res.chan[s])))}if(l){const e=a.resources.groups={};n.forEach((s=>e[s]=this.extractPermissions(t.res.grp[s])))}}const h=r.length>0,d=i.length>0,p=o.length>0;if(h||d||p){if(a.patterns={},h){const e=a.patterns.uuids={};r.forEach((s=>e[s]=this.extractPermissions(t.pat.uuid[s])))}if(d){const e=a.patterns.channels={};i.forEach((s=>e[s]=this.extractPermissions(t.pat.chan[s])))}if(p){const e=a.patterns.groups={};o.forEach((s=>e[s]=this.extractPermissions(t.pat.grp[s])))}}return t.meta&&Object.keys(t.meta).length>0&&(a.meta=t.meta),a}}extractPermissions(e){const t={read:!1,write:!1,manage:!1,delete:!1,get:!1,update:!1,join:!1};return 128&~e||(t.join=!0),64&~e||(t.update=!0),32&~e||(t.get=!0),8&~e||(t.delete=!0),4&~e||(t.manage=!0),2&~e||(t.write=!0),1&~e||(t.read=!0),t}}var H;!function(e){e.GET="GET",e.POST="POST",e.PATCH="PATCH",e.DELETE="DELETE",e.LOCAL="LOCAL"}(H||(H={}));class z{constructor(e,t,s){this.publishKey=e,this.secretKey=t,this.hasher=s}signature(e){const t=e.path.startsWith("/publish")?H.GET:e.method;let s=`${t}\n${this.publishKey}\n${e.path}\n${this.queryParameters(e.queryParameters)}\n`;if(t===H.POST||t===H.PATCH){const t=e.body;let n;t&&t instanceof ArrayBuffer?n=z.textDecoder.decode(t):t&&"object"!=typeof t&&(n=t),n&&(s+=n)}return`v2.${this.hasher(s,this.secretKey)}`.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}queryParameters(e){return Object.keys(e).sort().map((t=>{const s=e[t];return Array.isArray(s)?s.sort().map((e=>`${t}=${I(e)}`)).join("&"):`${t}=${I(s)}`})).join("&")}}z.textDecoder=new TextDecoder("utf-8");class V{constructor(e){this.configuration=e;const{clientConfiguration:{keySet:t},shaHMAC:s}=e;t.secretKey&&s&&(this.signatureGenerator=new z(t.publishKey,t.secretKey,s))}makeSendable(e){return this.configuration.transport.makeSendable(this.request(e))}request(e){var t;const{clientConfiguration:s}=this.configuration;return(e=this.configuration.transport.request(e)).queryParameters||(e.queryParameters={}),s.useInstanceId&&(e.queryParameters.instanceid=s.instanceId),e.queryParameters.uuid||(e.queryParameters.uuid=s.userId),s.useRequestId&&(e.queryParameters.requestid=e.identifier),e.queryParameters.pnsdk=this.generatePNSDK(),null!==(t=e.origin)&&void 0!==t||(e.origin=s.origin),this.authenticateRequest(e),this.signRequest(e),e}authenticateRequest(e){var t;if(e.path.startsWith("/v2/auth/")||e.path.startsWith("/v3/pam/")||e.path.startsWith("/time"))return;const{clientConfiguration:s,tokenManager:n}=this.configuration,r=null!==(t=n&&n.getToken())&&void 0!==t?t:s.authKey;r&&(e.queryParameters.auth=r)}signRequest(e){this.signatureGenerator&&!e.path.startsWith("/time")&&(e.queryParameters.timestamp=String(Math.floor((new Date).getTime()/1e3)),e.queryParameters.signature=this.signatureGenerator.signature(e))}generatePNSDK(){const{clientConfiguration:e}=this.configuration;if(e.sdkName)return e.sdkName;let t=`PubNub-JS-${e.sdkFamily}`;e.partnerId&&(t+=`-${e.partnerId}`),t+=`/${e.getVersion()}`;const s=e._getPnsdkSuffix(" ");return s.length>0&&(t+=s),t}}class W{constructor(){this.listeners=[]}addListener(e){this.listeners.includes(e)||this.listeners.push(e)}removeListener(e){this.listeners=this.listeners.filter((t=>t!==e))}removeAllListeners(){this.listeners=[]}announceStatus(e){this.listeners.forEach((t=>{t.status&&t.status(e)}))}announcePresence(e){this.listeners.forEach((t=>{t.presence&&t.presence(e)}))}announceMessage(e){this.listeners.forEach((t=>{t.message&&t.message(e)}))}announceSignal(e){this.listeners.forEach((t=>{t.signal&&t.signal(e)}))}announceMessageAction(e){this.listeners.forEach((t=>{t.messageAction&&t.messageAction(e)}))}announceFile(e){this.listeners.forEach((t=>{t.file&&t.file(e)}))}announceObjects(e){this.listeners.forEach((t=>{t.objects&&t.objects(e)}))}announceNetworkUp(){this.listeners.forEach((e=>{e.status&&e.status({category:h.PNNetworkUpCategory})}))}announceNetworkDown(){this.listeners.forEach((e=>{e.status&&e.status({category:h.PNNetworkDownCategory})}))}announceUser(e){this.listeners.forEach((t=>{t.user&&t.user(e)}))}announceSpace(e){this.listeners.forEach((t=>{t.space&&t.space(e)}))}announceMembership(e){this.listeners.forEach((t=>{t.membership&&t.membership(e)}))}}class J{constructor(e){this.time=e}onReconnect(e){this.callback=e}startPolling(){this.timeTimer=setInterval((()=>this.callTime()),3e3)}stopPolling(){this.timeTimer&&clearInterval(this.timeTimer),this.timeTimer=null}callTime(){this.time((e=>{e.error||(this.stopPolling(),this.callback&&this.callback())}))}}class Q{_config;hashHistory;constructor({config:e}){this.hashHistory=[],this._config=e}getKey(e){const t=(e=>{let t=0;if(0===e.length)return t;for(let s=0;s=this._config.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))}clearHistory(){this.hashHistory=[]}}class Y{constructor(e,t,s,n,r,i,o){this.configuration=e,this.listenerManager=t,this.eventEmitter=s,this.subscribeCall=n,this.heartbeatCall=r,this.leaveCall=i,this.reconnectionManager=new J(o),this.dedupingManager=new Q({config:this.configuration}),this.heartbeatChannelGroups={},this.heartbeatChannels={},this.presenceChannelGroups={},this.presenceChannels={},this.heartbeatTimer=null,this.presenceState={},this.pendingChannelGroupSubscriptions=new Set,this.pendingChannelSubscriptions=new Set,this.channelGroups={},this.channels={},this.currentTimetoken="0",this.lastTimetoken="0",this.storedTimetoken=null,this.subscriptionStatusAnnounced=!1,this.isOnline=!0}get subscribedChannels(){return Object.keys(this.channels)}get subscribedChannelGroups(){return Object.keys(this.channelGroups)}get abort(){return this._subscribeAbort}set abort(e){this._subscribeAbort=e}disconnect(){this.stopSubscribeLoop(),this.stopHeartbeatTimer(),this.reconnectionManager.stopPolling()}reconnect(){this.startSubscribeLoop(),this.startHeartbeatTimer()}subscribe(e){const{channels:t,channelGroups:s,timetoken:n,withPresence:r=!1,withHeartbeats:i=!1}=e;n&&(this.lastTimetoken=this.currentTimetoken,this.currentTimetoken=n),"0"!==this.currentTimetoken&&0!==this.currentTimetoken&&(this.storedTimetoken=this.currentTimetoken,this.currentTimetoken=0),null==t||t.forEach((e=>{this.pendingChannelSubscriptions.add(e),this.channels[e]={},r&&(this.presenceChannels[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannels[e]={})})),null==s||s.forEach((e=>{this.pendingChannelGroupSubscriptions.add(e),this.channelGroups[e]={},r&&(this.presenceChannelGroups[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannelGroups[e]={})})),this.subscriptionStatusAnnounced=!1,this.reconnect()}unsubscribe(e,t){let{channels:s,channelGroups:n}=e;const i=new Set,o=new Set;null==s||s.forEach((e=>{e in this.channels&&(delete this.channels[e],o.add(e),e in this.heartbeatChannels&&delete this.heartbeatChannels[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannels&&(delete this.presenceChannels[e],o.add(e))})),null==n||n.forEach((e=>{e in this.channelGroups&&(delete this.channelGroups[e],i.add(e),e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannelGroups&&(delete this.presenceChannelGroups[e],i.add(e))})),0===o.size&&0===i.size||(!1!==this.configuration.suppressLeaveEvents||t||(n=Array.from(i),s=Array.from(o),this.leaveCall({channels:s,channelGroups:n},(e=>{const{error:t}=e,i=r(e,["error"]);let o;t&&(e.errorData&&"object"==typeof e.errorData&&"message"in e.errorData&&"string"==typeof e.errorData.message?o=e.errorData.message:"message"in e&&"string"==typeof e.message&&(o=e.message)),this.listenerManager.announceStatus(Object.assign(Object.assign({},i),{error:null!=o&&o,affectedChannels:s,affectedChannelGroups:n,currentTimetoken:this.currentTimetoken,lastTimetoken:this.lastTimetoken}))}))),0===Object.keys(this.channels).length&&0===Object.keys(this.presenceChannels).length&&0===Object.keys(this.channelGroups).length&&0===Object.keys(this.presenceChannelGroups).length&&(this.lastTimetoken=0,this.currentTimetoken=0,this.storedTimetoken=null,this.region=null,this.reconnectionManager.stopPolling()),this.reconnect())}unsubscribeAll(e){this.unsubscribe({channels:this.subscribedChannels,channelGroups:this.subscribedChannelGroups},e)}startSubscribeLoop(){this.stopSubscribeLoop();const e=[...Object.keys(this.channelGroups)],t=[...Object.keys(this.channels)];Object.keys(this.presenceChannelGroups).forEach((t=>e.push(`${t}-pnpres`))),Object.keys(this.presenceChannels).forEach((e=>t.push(`${e}-pnpres`))),0===t.length&&0===e.length||this.subscribeCall({channels:t,channelGroups:e,state:this.presenceState,heartbeat:this.configuration.getPresenceTimeout(),timetoken:this.currentTimetoken,region:null!==this.region?this.region:void 0,filterExpression:this.configuration.filterExpression},((e,t)=>{this.processSubscribeResponse(e,t)}))}stopSubscribeLoop(){this._subscribeAbort&&(this._subscribeAbort(),this._subscribeAbort=null)}processSubscribeResponse(e,t){if(e.error){if("object"==typeof e.errorData&&"name"in e.errorData&&"AbortError"===e.errorData.name||e.category===h.PNCancelledCategory)return;return void(e.category===h.PNTimeoutCategory?this.startSubscribeLoop():e.category===h.PNNetworkIssuesCategory?(this.disconnect(),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.listenerManager.announceNetworkDown()),this.reconnectionManager.onReconnect((()=>{this.configuration.autoNetworkDetection&&!this.isOnline&&(this.isOnline=!0,this.listenerManager.announceNetworkUp()),this.reconnect(),this.subscriptionStatusAnnounced=!0;const t={category:h.PNReconnectedCategory,operation:e.operation,lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.listenerManager.announceStatus(t)})),this.reconnectionManager.startPolling(),this.listenerManager.announceStatus(e)):e.category===h.PNBadRequestCategory?(this.stopHeartbeatTimer(),this.listenerManager.announceStatus(e)):this.listenerManager.announceStatus(e))}if(this.storedTimetoken?(this.currentTimetoken=this.storedTimetoken,this.storedTimetoken=null):(this.lastTimetoken=this.currentTimetoken,this.currentTimetoken=t.cursor.timetoken),!this.subscriptionStatusAnnounced){const t={category:h.PNConnectedCategory,operation:e.operation,affectedChannels:Array.from(this.pendingChannelSubscriptions),subscribedChannels:this.subscribedChannels,affectedChannelGroups:Array.from(this.pendingChannelGroupSubscriptions),lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.subscriptionStatusAnnounced=!0,this.listenerManager.announceStatus(t),this.pendingChannelGroupSubscriptions.clear(),this.pendingChannelSubscriptions.clear()}const{messages:s}=t,{requestMessageCountThreshold:n,dedupeOnSubscribe:r}=this.configuration;n&&s.length>=n&&this.listenerManager.announceStatus({category:h.PNRequestMessageCountExceededCategory,operation:e.operation});try{s.forEach((e=>{if(r){if(this.dedupingManager.isDuplicate(e.data))return;this.dedupingManager.addEntry(e.data)}this.eventEmitter.emitEvent(e)}))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}this.region=t.cursor.region,this.startSubscribeLoop()}setState(e){const{state:t,channels:s,channelGroups:n}=e;null==s||s.forEach((e=>e in this.channels&&(this.presenceState[e]=t))),null==n||n.forEach((e=>e in this.channelGroups&&(this.presenceState[e]=t)))}changePresence(e){const{connected:t,channels:s,channelGroups:n}=e;t?(null==s||s.forEach((e=>this.heartbeatChannels[e]={})),null==n||n.forEach((e=>this.heartbeatChannelGroups[e]={}))):(null==s||s.forEach((e=>{e in this.heartbeatChannels&&delete this.heartbeatChannels[e]})),null==n||n.forEach((e=>{e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]})),!1===this.configuration.suppressLeaveEvents&&this.leaveCall({channels:s,channelGroups:n},(e=>this.listenerManager.announceStatus(e)))),this.reconnect()}startHeartbeatTimer(){this.stopHeartbeatTimer();const e=this.configuration.getHeartbeatInterval();e&&0!==e&&(this.sendHeartbeat(),this.heartbeatTimer=setInterval((()=>this.sendHeartbeat()),1e3*e))}stopHeartbeatTimer(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}sendHeartbeat(){const e=Object.keys(this.heartbeatChannelGroups),t=Object.keys(this.heartbeatChannels);0===t.length&&0===e.length||this.heartbeatCall({channels:t,channelGroups:e,heartbeat:this.configuration.getPresenceTimeout(),state:this.presenceState},(e=>{e.error&&this.configuration.announceFailedHeartbeats&&this.listenerManager.announceStatus(e),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.disconnect(),this.listenerManager.announceNetworkDown(),this.reconnect()),!e.error&&this.configuration.announceSuccessfulHeartbeats&&this.listenerManager.announceStatus(e)}))}}class X{constructor(e,t,s){this._payload=e,this.setDefaultPayloadStructure(),this.title=t,this.body=s}get payload(){return this._payload}set title(e){this._title=e}set subtitle(e){this._subtitle=e}set body(e){this._body=e}set badge(e){this._badge=e}set sound(e){this._sound=e}setDefaultPayloadStructure(){}toObject(){return{}}}class Z extends X{constructor(){super(...arguments),this._apnsPushType="apns",this._isSilent=!1}get payload(){return this._payload}set configurations(e){e&&e.length&&(this._configurations=e)}get notification(){return this.payload.aps}get title(){return this._title}set title(e){e&&e.length&&(this.payload.aps.alert.title=e,this._title=e)}get subtitle(){return this._subtitle}set subtitle(e){e&&e.length&&(this.payload.aps.alert.subtitle=e,this._subtitle=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.aps.alert.body=e,this._body=e)}get badge(){return this._badge}set badge(e){null!=e&&(this.payload.aps.badge=e,this._badge=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.aps.sound=e,this._sound=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.aps={alert:{}}}toObject(){const e=Object.assign({},this.payload),{aps:t}=e;let{alert:s}=t;if(this._isSilent&&(t["content-available"]=1),"apns2"===this._apnsPushType){if(!this._configurations||!this._configurations.length)throw new ReferenceError("APNS2 configuration is missing");const t=[];this._configurations.forEach((e=>{t.push(this.objectFromAPNS2Configuration(e))})),t.length&&(e.pn_push=t)}return s&&Object.keys(s).length||delete t.alert,this._isSilent&&(delete t.alert,delete t.badge,delete t.sound,s={}),this._isSilent||s&&Object.keys(s).length?e:null}objectFromAPNS2Configuration(e){if(!e.targets||!e.targets.length)throw new ReferenceError("At least one APNS2 target should be provided");const{collapseId:t,expirationDate:s}=e,n={auth_method:"token",targets:e.targets.map((e=>this.objectFromAPNSTarget(e))),version:"v2"};return t&&t.length&&(n.collapse_id=t),s&&(n.expiration=s.toISOString()),n}objectFromAPNSTarget(e){if(!e.topic||!e.topic.length)throw new TypeError("Target 'topic' undefined.");const{topic:t,environment:s="development",excludedDevices:n=[]}=e,r={topic:t,environment:s};return n.length&&(r.excluded_devices=n),r}}class ee extends X{get payload(){return this._payload}get notification(){return this.payload.notification}get data(){return this.payload.data}get title(){return this._title}set title(e){e&&e.length&&(this.payload.notification.title=e,this._title=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.notification.body=e,this._body=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.notification.sound=e,this._sound=e)}get icon(){return this._icon}set icon(e){e&&e.length&&(this.payload.notification.icon=e,this._icon=e)}get tag(){return this._tag}set tag(e){e&&e.length&&(this.payload.notification.tag=e,this._tag=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.notification={},this.payload.data={}}toObject(){let e=Object.assign({},this.payload.data),t=null;const s={};if(Object.keys(this.payload).length>2){const t=r(this.payload,["notification","data"]);e=Object.assign(Object.assign({},e),t)}return this._isSilent?e.notification=this.payload.notification:t=this.payload.notification,Object.keys(e).length&&(s.data=e),t&&Object.keys(t).length&&(s.notification=t),Object.keys(s).length?s:null}}class te{constructor(e,t){this._payload={apns:{},fcm:{}},this._title=e,this._body=t,this.apns=new Z(this._payload.apns,e,t),this.fcm=new ee(this._payload.fcm,e,t)}set debugging(e){this._debugging=e}get title(){return this._title}get subtitle(){return this._subtitle}set subtitle(e){this._subtitle=e,this.apns.subtitle=e,this.fcm.subtitle=e}get body(){return this._body}get badge(){return this._badge}set badge(e){this._badge=e,this.apns.badge=e,this.fcm.badge=e}get sound(){return this._sound}set sound(e){this._sound=e,this.apns.sound=e,this.fcm.sound=e}buildPayload(e){const t={};if(e.includes("apns")||e.includes("apns2")){this.apns._apnsPushType=e.includes("apns")?"apns":"apns2";const s=this.apns.toObject();s&&Object.keys(s).length&&(t.pn_apns=s)}if(e.includes("fcm")){const e=this.fcm.toObject();e&&Object.keys(e).length&&(t.pn_gcm=e)}return Object.keys(t).length&&this._debugging&&(t.pn_debug=!0),t}}class se{constructor(e){this.params=e,this.requestIdentifier=K.createUUID(),this._cancellationController=null}get cancellationController(){return this._cancellationController}set cancellationController(e){this._cancellationController=e}abort(){this&&this.cancellationController&&this.cancellationController.abort()}operation(){throw Error("Should be implemented by subclass.")}validate(){}parse(e){return i(this,void 0,void 0,(function*(){throw Error("Should be implemented by subclass.")}))}request(){var e,t,s,n;const r={method:null!==(t=null===(e=this.params)||void 0===e?void 0:e.method)&&void 0!==t?t:H.GET,path:this.path,queryParameters:this.queryParameters,cancellable:null!==(n=null===(s=this.params)||void 0===s?void 0:s.cancellable)&&void 0!==n&&n,timeout:1e4,identifier:this.requestIdentifier},i=this.headers;if(i&&(r.headers=i),r.method===H.POST||r.method===H.PATCH){const[e,t]=[this.body,this.formData];t&&(r.formData=t),e&&(r.body=e)}return r}get headers(){}get path(){throw Error("`path` getter should be implemented by subclass.")}get queryParameters(){return{}}get formData(){}get body(){}deserializeResponse(e){const t=e.headers["content-type"];if(!t||-1===t.indexOf("javascript")&&-1===t.indexOf("json"))return;const s=se.decoder.decode(e.body);try{return JSON.parse(s)}catch(e){return void console.error("Error parsing JSON response:",e)}}}var ne;se.decoder=new TextDecoder,function(e){e.PNPublishOperation="PNPublishOperation",e.PNSignalOperation="PNSignalOperation",e.PNSubscribeOperation="PNSubscribeOperation",e.PNUnsubscribeOperation="PNUnsubscribeOperation",e.PNWhereNowOperation="PNWhereNowOperation",e.PNHereNowOperation="PNHereNowOperation",e.PNGlobalHereNowOperation="PNGlobalHereNowOperation",e.PNSetStateOperation="PNSetStateOperation",e.PNGetStateOperation="PNGetStateOperation",e.PNHeartbeatOperation="PNHeartbeatOperation",e.PNAddMessageActionOperation="PNAddActionOperation",e.PNRemoveMessageActionOperation="PNRemoveMessageActionOperation",e.PNGetMessageActionsOperation="PNGetMessageActionsOperation",e.PNTimeOperation="PNTimeOperation",e.PNHistoryOperation="PNHistoryOperation",e.PNDeleteMessagesOperation="PNDeleteMessagesOperation",e.PNFetchMessagesOperation="PNFetchMessagesOperation",e.PNMessageCounts="PNMessageCountsOperation",e.PNGetAllUUIDMetadataOperation="PNGetAllUUIDMetadataOperation",e.PNGetUUIDMetadataOperation="PNGetUUIDMetadataOperation",e.PNSetUUIDMetadataOperation="PNSetUUIDMetadataOperation",e.PNRemoveUUIDMetadataOperation="PNRemoveUUIDMetadataOperation",e.PNGetAllChannelMetadataOperation="PNGetAllChannelMetadataOperation",e.PNGetChannelMetadataOperation="PNGetChannelMetadataOperation",e.PNSetChannelMetadataOperation="PNSetChannelMetadataOperation",e.PNRemoveChannelMetadataOperation="PNRemoveChannelMetadataOperation",e.PNGetMembersOperation="PNGetMembersOperation",e.PNSetMembersOperation="PNSetMembersOperation",e.PNGetMembershipsOperation="PNGetMembershipsOperation",e.PNSetMembershipsOperation="PNSetMembershipsOperation",e.PNListFilesOperation="PNListFilesOperation",e.PNGenerateUploadUrlOperation="PNGenerateUploadUrlOperation",e.PNPublishFileOperation="PNPublishFileOperation",e.PNPublishFileMessageOperation="PNPublishFileMessageOperation",e.PNGetFileUrlOperation="PNGetFileUrlOperation",e.PNDownloadFileOperation="PNDownloadFileOperation",e.PNDeleteFileOperation="PNDeleteFileOperation",e.PNAddPushNotificationEnabledChannelsOperation="PNAddPushNotificationEnabledChannelsOperation",e.PNRemovePushNotificationEnabledChannelsOperation="PNRemovePushNotificationEnabledChannelsOperation",e.PNPushNotificationEnabledChannelsOperation="PNPushNotificationEnabledChannelsOperation",e.PNRemoveAllPushNotificationsOperation="PNRemoveAllPushNotificationsOperation",e.PNChannelGroupsOperation="PNChannelGroupsOperation",e.PNRemoveGroupOperation="PNRemoveGroupOperation",e.PNChannelsForGroupOperation="PNChannelsForGroupOperation",e.PNAddChannelsToGroupOperation="PNAddChannelsToGroupOperation",e.PNRemoveChannelsFromGroupOperation="PNRemoveChannelsFromGroupOperation",e.PNAccessManagerGrant="PNAccessManagerGrant",e.PNAccessManagerGrantToken="PNAccessManagerGrantToken",e.PNAccessManagerAudit="PNAccessManagerAudit",e.PNAccessManagerRevokeToken="PNAccessManagerRevokeToken",e.PNHandshakeOperation="PNHandshakeOperation",e.PNReceiveMessagesOperation="PNReceiveMessagesOperation"}(ne||(ne={}));var re=ne;var ie;!function(e){e[e.Presence=-2]="Presence",e[e.Message=-1]="Message",e[e.Signal=1]="Signal",e[e.AppContext=2]="AppContext",e[e.MessageAction=3]="MessageAction",e[e.Files=4]="Files"}(ie||(ie={}));class oe extends se{constructor(e){var t,s,n,r,i,o;super({cancellable:!0}),this.parameters=e,null!==(t=(r=this.parameters).withPresence)&&void 0!==t||(r.withPresence=false),null!==(s=(i=this.parameters).channelGroups)&&void 0!==s||(i.channelGroups=[]),null!==(n=(o=this.parameters).channels)&&void 0!==n||(o.channels=[])}operation(){return re.PNSubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;return e?t||s?void 0:"`channels` and `channelGroups` both should not be empty":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){let t;try{const s=se.decoder.decode(e.body);t=JSON.parse(s)}catch(e){console.error("Error parsing JSON response:",e)}if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));const s=t.m.filter((e=>{const t=void 0===e.b?e.c:e.b;return this.parameters.channels&&this.parameters.channels.includes(t)||this.parameters.channelGroups&&this.parameters.channelGroups.includes(t)})).map((e=>{let{e:t}=e;return null!=t||(t=e.c.endsWith("-pnpres")?ie.Presence:ie.Message),t!=ie.Signal&&"string"==typeof e.d?t==ie.Message?{type:ie.Message,data:this.messageFromEnvelope(e)}:{type:ie.Files,data:this.fileFromEnvelope(e)}:t==ie.Message?{type:ie.Message,data:this.messageFromEnvelope(e)}:t===ie.Presence?{type:ie.Presence,data:this.presenceEventFromEnvelope(e)}:t==ie.Signal?{type:ie.Signal,data:this.signalFromEnvelope(e)}:t===ie.AppContext?{type:ie.AppContext,data:this.appContextFromEnvelope(e)}:t===ie.MessageAction?{type:ie.MessageAction,data:this.messageActionFromEnvelope(e)}:{type:ie.Files,data:this.fileFromEnvelope(e)}}));return{cursor:{timetoken:t.t.t,region:t.t.r},messages:s}}))}get headers(){return{accept:"text/javascript"}}presenceEventFromEnvelope(e){const{d:t}=e,[s,n]=this.subscriptionChannelFromEnvelope(e),r=s.replace("-pnpres",""),i=null!==n?r:null,o=null!==n?n:r;return"string"!=typeof t&&"data"in t&&(t.state=t.data,delete t.data),Object.assign({channel:r,subscription:n,actualChannel:i,subscribedChannel:o,timetoken:e.p.t},t)}messageFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,r]=this.decryptedData(e.d),i={channel:t,subscription:s,actualChannel:null!==s?t:null,subscribedChannel:null!==s?s:t,timetoken:e.p.t,publisher:e.i,message:n};return e.u&&(i.userMetadata=e.u),r&&(i.error=r),i}signalFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,message:e.d};return e.u&&(n.userMetadata=e.u),n}messageActionFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,event:n.event,data:Object.assign(Object.assign({},n.data),{uuid:e.i})}}appContextFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,message:n}}fileFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,r]=this.decryptedData(e.d);let i=r;const o={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i};return e.u&&(o.userMetadata=e.u),n?"string"==typeof n?null!=i||(i="Unexpected file information payload data type."):(o.message=n.message,n.file&&(o.file={id:n.file.id,name:n.file.name,url:this.parameters.getFileUrl({id:n.file.id,name:n.file.name,channel:t})})):null!=i||(i="File information payload is missing."),i&&(o.error=i),o}subscriptionChannelFromEnvelope(e){return[e.c,void 0===e.b?e.c:e.b]}decryptedData(e){if(!this.parameters.crypto||"string"!=typeof e)return[e,void 0];let t,s;try{const s=this.parameters.crypto.decrypt(e);t=s instanceof ArrayBuffer?JSON.parse(ae.decoder.decode(s)):s}catch(e){t=null,s=`Error while decrypting message content: ${e.message}`}return[null!=t?t:e,s]}}class ae extends oe{get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/subscribe/${t}/${R(null!==(e=null==s?void 0:s.sort())&&void 0!==e?e:[],",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,heartbeat:s,state:n,timetoken:r,region:i}=this.parameters,o={};return e&&e.length>0&&(o["channel-group"]=e.sort().join(",")),t&&t.length>0&&(o["filter-expr"]=t),s&&(o.heartbeat=s),n&&Object.keys(n).length>0&&(o.state=JSON.stringify(n)),void 0!==r&&"string"==typeof r?r.length>0&&"0"!==r&&(o.tt=r):void 0!==r&&r>0&&(o.tt=r),i&&(o.tr=i),o}}class ce{constructor(e){this.listenerManager=e,this.channelListenerMap=new Map,this.groupListenerMap=new Map}emitEvent(e){if(e.type===ie.Message)this.listenerManager.announceMessage(e.data),this.announce("message",e.data,e.data.channel,e.data.subscription);else if(e.type===ie.Signal)this.listenerManager.announceSignal(e.data),this.announce("signal",e.data,e.data.channel,e.data.subscription);else if(e.type===ie.Presence)this.listenerManager.announcePresence(e.data),this.announce("presence",e.data,e.data.channel,e.data.subscription);else if(e.type===ie.AppContext){const{data:t}=e,{message:s}=t;if(this.listenerManager.announceObjects(t),this.announce("objects",t,t.channel,t.subscription),"uuid"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:o,type:a}=s,c=r(s,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===o?"updated":"removed",type:"user"})});this.listenerManager.announceUser(u),this.announce("user",u,u.spaceId,u.subscription)}else if("channel"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:o,type:a}=s,c=r(s,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===o?"updated":"removed",type:"space"})});this.listenerManager.announceSpace(u),this.announce("space",u,u.spaceId,u.subscription)}else if("membership"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:o,data:a}=s,c=r(s,["event","data"]),{uuid:u,channel:l}=a,h=r(a,["uuid","channel"]),d=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===o?"updated":"removed",data:Object.assign(Object.assign({},h),{user:u,space:l})})});this.listenerManager.announceMembership(d),this.announce("membership",d,d.spaceId,d.subscription)}}else e.type===ie.MessageAction?(this.listenerManager.announceMessageAction(e.data),this.announce("messageAction",e.data,e.data.channel,e.data.subscription)):e.type===ie.Files&&(this.listenerManager.announceFile(e.data),this.announce("file",e.data,e.data.channel,e.data.subscription))}addListener(e,t,s){t&&s?(null==t||t.forEach((t=>{if(this.channelListenerMap.has(t)){const s=this.channelListenerMap.get(t);s.includes(e)||s.push(e)}else this.channelListenerMap.set(t,[e])})),null==s||s.forEach((t=>{if(this.groupListenerMap.has(t)){const s=this.groupListenerMap.get(t);s.includes(e)||s.push(e)}else this.groupListenerMap.set(t,[e])}))):this.listenerManager.addListener(e)}removeListener(e,t,s){t&&s?(null==t||t.forEach((t=>{this.channelListenerMap.has(t)&&this.channelListenerMap.set(t,this.channelListenerMap.get(t).filter((t=>t!==e)))})),null==s||s.forEach((t=>{this.groupListenerMap.has(t)&&this.groupListenerMap.set(t,this.groupListenerMap.get(t).filter((t=>t!==e)))}))):this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners(),this.channelListenerMap.clear(),this.groupListenerMap.clear()}announce(e,t,s,n){t&&this.channelListenerMap.has(s)&&this.channelListenerMap.get(s).forEach((s=>{const n=s[e];n&&n(t)})),n&&this.groupListenerMap.has(n)&&this.groupListenerMap.get(n).forEach((s=>{const n=s[e];n&&n(t)}))}}class ue{constructor(e=!1){this.sync=e,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){const t=()=>{this.listeners.forEach((t=>{t(e)}))};this.sync?t():setTimeout(t,0)}}class le{transition(e,t){var s;if(this.transitionMap.has(t.type))return null===(s=this.transitionMap.get(t.type))||void 0===s?void 0:s(e,t)}constructor(e){this.label=e,this.transitionMap=new Map,this.enterEffects=[],this.exitEffects=[]}on(e,t){return this.transitionMap.set(e,t),this}with(e,t){return[this,e,null!=t?t:[]]}onEnter(e){return this.enterEffects.push(e),this}onExit(e){return this.exitEffects.push(e),this}}class he extends ue{describe(e){return new le(e)}start(e,t){this.currentState=e,this.currentContext=t,this.notify({type:"engineStarted",state:e,context:t})}transition(e){if(!this.currentState)throw new Error("Start the engine first");this.notify({type:"eventReceived",event:e});const t=this.currentState.transition(this.currentContext,e);if(t){const[s,n,r]=t;for(const e of this.currentState.exitEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)});const i=this.currentState;this.currentState=s;const o=this.currentContext;this.currentContext=n,this.notify({type:"transitionDone",fromState:i,fromContext:o,toState:s,toContext:n,event:e});for(const e of r)this.notify({type:"invocationDispatched",invocation:e});for(const e of this.currentState.enterEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)})}}}class de{constructor(e){this.dependencies=e,this.instances=new Map,this.handlers=new Map}on(e,t){this.handlers.set(e,t)}dispatch(e){if("CANCEL"===e.type){if(this.instances.has(e.payload)){const t=this.instances.get(e.payload);null==t||t.cancel(),this.instances.delete(e.payload)}return}const t=this.handlers.get(e.type);if(!t)throw new Error(`Unhandled invocation '${e.type}'`);const s=t(e.payload,this.dependencies);e.managed&&this.instances.set(e.type,s),s.start()}dispose(){for(const[e,t]of this.instances.entries())t.cancel(),this.instances.delete(e)}}function pe(e,t){const s=function(...s){return{type:e,payload:null==t?void 0:t(...s)}};return s.type=e,s}function ge(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!1});return s.type=e,s}function ye(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!0});return s.type=e,s.cancel={type:"CANCEL",payload:e,managed:!1},s}class fe extends Error{constructor(){super("The operation was aborted."),this.name="AbortError",Object.setPrototypeOf(this,new.target.prototype)}}class me extends ue{constructor(){super(...arguments),this._aborted=!1}get aborted(){return this._aborted}throwIfAborted(){if(this._aborted)throw new fe}abort(){this._aborted=!0,this.notify(new fe)}}class be{constructor(e,t){this.payload=e,this.dependencies=t}}class ve extends be{constructor(e,t,s){super(e,t),this.asyncFunction=s,this.abortSignal=new me}start(){this.asyncFunction(this.payload,this.abortSignal,this.dependencies).catch((e=>{}))}cancel(){this.abortSignal.abort()}}const we=e=>(t,s)=>new ve(t,s,e),Se=pe("RECONNECT",(()=>({}))),ke=pe("DISCONNECT",(()=>({}))),Ee=pe("JOINED",((e,t)=>({channels:e,groups:t}))),Oe=pe("LEFT",((e,t)=>({channels:e,groups:t}))),Ce=pe("LEFT_ALL",(()=>({}))),Ne=pe("HEARTBEAT_SUCCESS",(e=>({statusCode:e}))),Pe=pe("HEARTBEAT_FAILURE",(e=>e)),Me=pe("HEARTBEAT_GIVEUP",(()=>({}))),_e=pe("TIMES_UP",(()=>({}))),Ae=ge("HEARTBEAT",((e,t)=>({channels:e,groups:t}))),je=ge("LEAVE",((e,t)=>({channels:e,groups:t}))),Ie=ge("EMIT_STATUS",(e=>e)),Re=ye("WAIT",(()=>({}))),Ue=ye("DELAYED_HEARTBEAT",(e=>e));class Te extends de{constructor(e,t){super(t),this.on(Ae.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeat:n,presenceState:r,config:i}){try{yield n(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},i.maintainPresenceState&&{state:r}),{heartbeat:i.presenceTimeout}));e.transition(Ne(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Pe(t))}}}))))),this.on(je.type,we(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{leave:s,config:n}){if(!n.suppressLeaveEvents)try{s({channels:e.channels,channelGroups:e.groups})}catch(e){}}))))),this.on(Re.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeatDelay:n}){return s.throwIfAborted(),yield n(),s.throwIfAborted(),e.transition(_e())}))))),this.on(Ue.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeat:n,retryDelay:r,presenceState:i,config:o}){if(!o.retryConfiguration||!o.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(Me());s.throwIfAborted(),yield r(o.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{yield n(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},o.maintainPresenceState&&{state:i}),{heartbeat:o.presenceTimeout}));return e.transition(Ne(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Pe(t))}}}))))),this.on(Ie.type,we(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s,config:n}){var r;n.announceFailedHeartbeats&&!0===(null===(r=null==e?void 0:e.status)||void 0===r?void 0:r.error)?s(e.status):n.announceSuccessfulHeartbeats&&200===e.statusCode&&s(Object.assign(Object.assign({},e),{operation:re.PNHeartbeatOperation,error:!1}))})))))}}const Fe=new le("HEARTBEAT_STOPPED");Fe.on(Ee.type,((e,t)=>Fe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Fe.on(Oe.type,((e,t)=>Fe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))}))),Fe.on(Se.type,((e,t)=>Ge.with({channels:e.channels,groups:e.groups}))),Fe.on(Ce.type,((e,t)=>Ke.with(void 0)));const xe=new le("HEARTBEAT_COOLDOWN");xe.onEnter((()=>Re())),xe.onExit((()=>Re.cancel)),xe.on(_e.type,((e,t)=>Ge.with({channels:e.channels,groups:e.groups}))),xe.on(Ee.type,((e,t)=>Ge.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),xe.on(Oe.type,((e,t)=>Ge.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[je(t.payload.channels,t.payload.groups)]))),xe.on(ke.type,(e=>Fe.with({channels:e.channels,groups:e.groups},[je(e.channels,e.groups)]))),xe.on(Ce.type,((e,t)=>Ke.with(void 0,[je(e.channels,e.groups)])));const De=new le("HEARTBEAT_FAILED");De.on(Ee.type,((e,t)=>Ge.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),De.on(Oe.type,((e,t)=>Ge.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[je(t.payload.channels,t.payload.groups)]))),De.on(Se.type,((e,t)=>Ge.with({channels:e.channels,groups:e.groups}))),De.on(ke.type,((e,t)=>Fe.with({channels:e.channels,groups:e.groups},[je(e.channels,e.groups)]))),De.on(Ce.type,((e,t)=>Ke.with(void 0,[je(e.channels,e.groups)])));const qe=new le("HEARBEAT_RECONNECTING");qe.onEnter((e=>Ue(e))),qe.onExit((()=>Ue.cancel)),qe.on(Ee.type,((e,t)=>Ge.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),qe.on(Oe.type,((e,t)=>Ge.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[je(t.payload.channels,t.payload.groups)]))),qe.on(ke.type,((e,t)=>{Fe.with({channels:e.channels,groups:e.groups},[je(e.channels,e.groups)])})),qe.on(Ne.type,((e,t)=>xe.with({channels:e.channels,groups:e.groups}))),qe.on(Pe.type,((e,t)=>qe.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),qe.on(Me.type,((e,t)=>De.with({channels:e.channels,groups:e.groups}))),qe.on(Ce.type,((e,t)=>Ke.with(void 0,[je(e.channels,e.groups)])));const Ge=new le("HEARTBEATING");Ge.onEnter((e=>Ae(e.channels,e.groups))),Ge.on(Ne.type,((e,t)=>xe.with({channels:e.channels,groups:e.groups}))),Ge.on(Ee.type,((e,t)=>Ge.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Ge.on(Oe.type,((e,t)=>Ge.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[je(t.payload.channels,t.payload.groups)]))),Ge.on(Pe.type,((e,t)=>qe.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),Ge.on(ke.type,(e=>Fe.with({channels:e.channels,groups:e.groups},[je(e.channels,e.groups)]))),Ge.on(Ce.type,((e,t)=>Ke.with(void 0,[je(e.channels,e.groups)])));const Ke=new le("HEARTBEAT_INACTIVE");Ke.on(Ee.type,((e,t)=>Ge.with({channels:t.payload.channels,groups:t.payload.groups})));class $e{get _engine(){return this.engine}constructor(e){this.dependencies=e,this.engine=new he,this.channels=[],this.groups=[],this.dispatcher=new Te(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(Ke,void 0)}join({channels:e,groups:t}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],this.engine.transition(Ee(this.channels.slice(0),this.groups.slice(0)))}leave({channels:e,groups:t}){this.dependencies.presenceState&&(null==e||e.forEach((e=>delete this.dependencies.presenceState[e])),null==t||t.forEach((e=>delete this.dependencies.presenceState[e]))),this.engine.transition(Oe(null!=e?e:[],null!=t?t:[]))}leaveAll(){this.engine.transition(Ce())}dispose(){this._unsubscribeEngine(),this.dispatcher.dispose()}}class Le{static LinearRetryPolicy(e){return{delay:e.delay,maximumRetry:e.maximumRetry,shouldRetry(e,t){var s;return 403!==(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)&&this.maximumRetry>t},getDelay(e,t){var s;return 1e3*((null!==(s=t.retryAfter)&&void 0!==s?s:this.delay)+Math.random())},getGiveupReason(e,t){var s;return this.maximumRetry<=t?"retry attempts exhaused.":403===(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)?"forbidden operation.":"unknown error"},validate(){if(this.maximumRetry>10)throw new Error("Maximum retry for linear retry policy can not be more than 10")}}}static ExponentialRetryPolicy(e){return{minimumDelay:e.minimumDelay,maximumDelay:e.maximumDelay,maximumRetry:e.maximumRetry,shouldRetry(e,t){var s;return 403!==(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)&&this.maximumRetry>t},getDelay(e,t){var s;return 1e3*((null!==(s=t.retryAfter)&&void 0!==s?s:Math.min(Math.pow(2,e),this.maximumDelay))+Math.random())},getGiveupReason(e,t){var s;return this.maximumRetry<=t?"retry attempts exhausted.":403===(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)?"forbidden operation.":"unknown error"},validate(){if(this.minimumDelay<2)throw new Error("Minimum delay can not be set less than 2 seconds for retry");if(this.maximumDelay)throw new Error("Maximum delay can not be set more than 150 seconds for retry");if(this.maximumRetry>6)throw new Error("Maximum retry for exponential retry policy can not be more than 6")}}}}const Be=ye("HANDSHAKE",((e,t)=>({channels:e,groups:t}))),He=ye("RECEIVE_MESSAGES",((e,t,s)=>({channels:e,groups:t,cursor:s}))),ze=ge("EMIT_MESSAGES",(e=>e)),Ve=ge("EMIT_STATUS",(e=>e)),We=ye("RECEIVE_RECONNECT",(e=>e)),Je=ye("HANDSHAKE_RECONNECT",(e=>e)),Qe=pe("SUBSCRIPTION_CHANGED",((e,t)=>({channels:e,groups:t}))),Ye=pe("SUBSCRIPTION_RESTORED",((e,t,s,n)=>({channels:e,groups:t,cursor:{timetoken:s,region:null!=n?n:0}}))),Xe=pe("HANDSHAKE_SUCCESS",(e=>e)),Ze=pe("HANDSHAKE_FAILURE",(e=>e)),et=pe("HANDSHAKE_RECONNECT_SUCCESS",(e=>({cursor:e}))),tt=pe("HANDSHAKE_RECONNECT_FAILURE",(e=>e)),st=pe("HANDSHAKE_RECONNECT_GIVEUP",(e=>e)),nt=pe("RECEIVE_SUCCESS",((e,t)=>({cursor:e,events:t}))),rt=pe("RECEIVE_FAILURE",(e=>e)),it=pe("RECEIVE_RECONNECT_SUCCESS",((e,t)=>({cursor:e,events:t}))),ot=pe("RECEIVE_RECONNECT_FAILURE",(e=>e)),at=pe("RECEIVING_RECONNECT_GIVEUP",(e=>e)),ct=pe("DISCONNECT",(()=>({}))),ut=pe("RECONNECT",((e,t)=>({cursor:{timetoken:null!=e?e:"",region:null!=t?t:0}}))),lt=pe("UNSUBSCRIBE_ALL",(()=>({})));class ht extends de{constructor(e,t){super(t),this.on(Be.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{handshake:n,presenceState:r,config:i}){s.throwIfAborted();try{const o=yield n(Object.assign({abortSignal:s,channels:t.channels,channelGroups:t.groups,filterExpression:i.filterExpression},i.maintainPresenceState&&{state:r}));return e.transition(Xe(o))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Ze(t))}}}))))),this.on(He.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{receiveMessages:n,config:r}){s.throwIfAborted();try{const i=yield n({abortSignal:s,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:r.filterExpression});e.transition(nt(i.cursor,i.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;if(!s.aborted)return e.transition(rt(t))}}}))))),this.on(ze.type,we(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitMessages:s}){e.length>0&&s(e)}))))),this.on(Ve.type,we(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s}){s(e)}))))),this.on(We.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{receiveMessages:n,delay:r,config:i}){if(!i.retryConfiguration||!i.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(at(new d(i.retryConfiguration?i.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe messages receive.")));s.throwIfAborted(),yield r(i.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{const r=yield n({abortSignal:s,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:i.filterExpression});return e.transition(it(r.cursor,r.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(ot(t))}}}))))),this.on(Je.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{handshake:n,delay:r,presenceState:i,config:o}){if(!o.retryConfiguration||!o.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(st(new d(o.retryConfiguration?o.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe handshake")));s.throwIfAborted(),yield r(o.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{const r=yield n(Object.assign({abortSignal:s,channels:t.channels,channelGroups:t.groups,filterExpression:o.filterExpression},o.maintainPresenceState&&{state:i}));return e.transition(et(r))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(tt(t))}}})))))}}const dt=new le("HANDSHAKE_FAILED");dt.on(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),dt.on(ut.type,((e,t)=>vt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor||e.cursor}))),dt.on(Ye.type,((e,t)=>{var s,n;return vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region?t.payload.cursor.region:null!==(n=null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)&&void 0!==n?n:0}})})),dt.on(lt.type,(e=>wt.with()));const pt=new le("HANDSHAKE_STOPPED");pt.on(Qe.type,((e,t)=>pt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),pt.on(ut.type,((e,t)=>vt.with(Object.assign(Object.assign({},e),{cursor:t.payload.cursor||e.cursor})))),pt.on(Ye.type,((e,t)=>{var s;return pt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)||0}})})),pt.on(lt.type,(e=>wt.with()));const gt=new le("RECEIVE_FAILED");gt.on(ut.type,((e,t)=>{var s;return vt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.payload.cursor.timetoken?null===(s=t.payload.cursor)||void 0===s?void 0:s.timetoken:e.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),gt.on(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),gt.on(Ye.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),gt.on(lt.type,(e=>wt.with(void 0)));const yt=new le("RECEIVE_STOPPED");yt.on(Qe.type,((e,t)=>yt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),yt.on(Ye.type,((e,t)=>yt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),yt.on(ut.type,((e,t)=>{var s;return vt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.payload.cursor.timetoken?null===(s=t.payload.cursor)||void 0===s?void 0:s.timetoken:e.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),yt.on(lt.type,(()=>wt.with(void 0)));const ft=new le("RECEIVE_RECONNECTING");ft.onEnter((e=>We(e))),ft.onExit((()=>We.cancel)),ft.on(it.type,((e,t)=>mt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ze(t.payload.events)]))),ft.on(ot.type,((e,t)=>ft.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),ft.on(at.type,((e,t)=>{var s;return gt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[Ve({category:h.PNDisconnectedUnexpectedlyCategory,error:null===(s=t.payload)||void 0===s?void 0:s.message})])})),ft.on(ct.type,(e=>yt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[Ve({category:h.PNDisconnectedCategory})]))),ft.on(Ye.type,((e,t)=>mt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),ft.on(Qe.type,((e,t)=>mt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),ft.on(lt.type,(e=>wt.with(void 0,[Ve({category:h.PNDisconnectedCategory})])));const mt=new le("RECEIVING");mt.onEnter((e=>He(e.channels,e.groups,e.cursor))),mt.onExit((()=>He.cancel)),mt.on(nt.type,((e,t)=>mt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ze(t.payload.events)]))),mt.on(Qe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?wt.with(void 0):mt.with({cursor:e.cursor,channels:t.payload.channels,groups:t.payload.groups}))),mt.on(Ye.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?wt.with(void 0):mt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),mt.on(rt.type,((e,t)=>ft.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),mt.on(ct.type,(e=>yt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[Ve({category:h.PNDisconnectedCategory})]))),mt.on(lt.type,(e=>wt.with(void 0,[Ve({category:h.PNDisconnectedCategory})])));const bt=new le("HANDSHAKE_RECONNECTING");bt.onEnter((e=>Je(e))),bt.onExit((()=>Je.cancel)),bt.on(et.type,((e,t)=>{var s,n;const r={timetoken:(null===(s=e.cursor)||void 0===s?void 0:s.timetoken)?null===(n=e.cursor)||void 0===n?void 0:n.timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region};return mt.with({channels:e.channels,groups:e.groups,cursor:r},[Ve({category:h.PNConnectedCategory})])})),bt.on(tt.type,((e,t)=>bt.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),bt.on(st.type,((e,t)=>{var s;return dt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[Ve({category:h.PNConnectionErrorCategory,error:null===(s=t.payload)||void 0===s?void 0:s.message})])})),bt.on(ct.type,(e=>pt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),bt.on(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),bt.on(Ye.type,((e,t)=>{var s,n;return vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:(null===(s=t.payload.cursor)||void 0===s?void 0:s.region)||(null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.region)||0}})})),bt.on(lt.type,(e=>wt.with(void 0)));const vt=new le("HANDSHAKING");vt.onEnter((e=>Be(e.channels,e.groups))),vt.onExit((()=>Be.cancel)),vt.on(Qe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?wt.with(void 0):vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),vt.on(Xe.type,((e,t)=>{var s,n;return mt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.timetoken)?null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.timetoken:t.payload.timetoken,region:t.payload.region}},[Ve({category:h.PNConnectedCategory})])})),vt.on(Ze.type,((e,t)=>bt.with({channels:e.channels,groups:e.groups,cursor:e.cursor,attempts:0,reason:t.payload}))),vt.on(ct.type,(e=>pt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),vt.on(Ye.type,((e,t)=>{var s;return vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)||0}})})),vt.on(lt.type,(e=>wt.with()));const wt=new le("UNSUBSCRIBED");wt.on(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups}))),wt.on(Ye.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:t.payload.cursor})));class St{get _engine(){return this.engine}constructor(e){this.engine=new he,this.channels=[],this.groups=[],this.dependencies=e,this.dispatcher=new ht(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(wt,void 0)}subscribe({channels:e,channelGroups:t,timetoken:s,withPresence:n}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],n&&(this.channels.map((e=>this.channels.push(`${e}-pnpres`))),this.groups.map((e=>this.groups.push(`${e}-pnpres`)))),s?this.engine.transition(Ye(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])),s)):this.engine.transition(Qe(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])))),this.dependencies.join&&this.dependencies.join({channels:Array.from(new Set(this.channels.filter((e=>!e.endsWith("-pnpres"))))),groups:Array.from(new Set(this.groups.filter((e=>!e.endsWith("-pnpres")))))})}unsubscribe({channels:e=[],channelGroups:t=[]}){const s=U(this.channels,[...e,...e.map((e=>`${e}-pnpres`))]),n=U(this.groups,[...t,...t.map((e=>`${e}-pnpres`))]);if(new Set(this.channels).size!==new Set(s).size||new Set(this.groups).size!==new Set(n).size){const r=T(this.channels,e),i=T(this.groups,t);this.dependencies.presenceState&&(null==r||r.forEach((e=>delete this.dependencies.presenceState[e])),null==i||i.forEach((e=>delete this.dependencies.presenceState[e]))),this.channels=s,this.groups=n,this.engine.transition(Qe(Array.from(new Set(this.channels.slice(0))),Array.from(new Set(this.groups.slice(0))))),this.dependencies.leave&&this.dependencies.leave({channels:r.slice(0),groups:i.slice(0)})}}unsubscribeAll(){this.channels=[],this.groups=[],this.dependencies.presenceState&&Object.keys(this.dependencies.presenceState).forEach((e=>{delete this.dependencies.presenceState[e]})),this.engine.transition(Qe(this.channels.slice(0),this.groups.slice(0))),this.dependencies.leaveAll&&this.dependencies.leaveAll()}reconnect({timetoken:e,region:t}){this.engine.transition(ut(e,t))}disconnect(){this.engine.transition(ct()),this.dependencies.leaveAll&&this.dependencies.leaveAll()}getSubscribedChannels(){return Array.from(new Set(this.channels.slice(0)))}getSubscribedChannelGroups(){return Array.from(new Set(this.groups.slice(0)))}dispose(){this.disconnect(),this._unsubscribeEngine(),this.dispatcher.dispose()}}class kt extends se{constructor(e){var t,s;super({method:e.sendByPost?H.POST:H.GET}),this.parameters=e,null!==(t=(s=this.parameters).sendByPost)&&void 0!==t||(s.sendByPost=false)}operation(){return re.PNPublishOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[2]}}))}get path(){const{message:e,channel:t,keySet:s}=this.parameters,n=this.prepareMessagePayload(e);return`/publish/${s.publishKey}/${s.subscribeKey}/0/${I(t)}/0${this.parameters.sendByPost?"":`/${I(n)}`}`}get queryParameters(){const{meta:e,replicate:t,storeInHistory:s,ttl:n}=this.parameters,r={};return void 0!==s&&(r.store=s?"1":"0"),void 0!==n&&(r.ttl=n),void 0===t||t||(r.norep="true"),e&&"object"==typeof e&&(r.meta=JSON.stringify(e)),r}get headers(){return{"Content-Type":"application/json"}}get body(){return this.prepareMessagePayload(this.parameters.message)}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof s?s:u(s))}}class Et extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNSignalOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[2]}}))}get path(){const{keySet:{publishKey:e,subscribeKey:t},channel:s,message:n}=this.parameters,r=JSON.stringify(n);return`/signal/${e}/${t}/0/${I(s)}/0/${I(r)}`}}class Ot extends oe{operation(){return re.PNReceiveMessagesOperation}validate(){const e=super.validate();return e||(this.parameters.timetoken?this.parameters.region?void 0:"region can not be empty":"timetoken can not be empty")}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${R(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,timetoken:s,region:n}=this.parameters,r={ee:""};return e&&e.length>0&&(r["channel-group"]=e.sort().join(",")),t&&t.length>0&&(r["filter-expr"]=t),"string"==typeof s?s&&s.length>0&&(r.tt=s):s&&s>0&&(r.tt=s),n&&(r.tr=n),r}}class Ct extends oe{operation(){return re.PNHandshakeOperation}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${R(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,state:s}=this.parameters,n={tt:0,ee:""};return e&&e.length>0&&(n["channel-group"]=e.sort().join(",")),t&&t.length>0&&(n["filter-expr"]=t),s&&Object.keys(s).length>0&&(n.state=JSON.stringify(s)),n}}class Nt extends se{constructor(e){var t,s,n,r;super(),this.parameters=e,null!==(t=(n=this.parameters).channels)&&void 0!==t||(n.channels=[]),null!==(s=(r=this.parameters).channelGroups)&&void 0!==s||(r.channelGroups=[])}operation(){return re.PNGetStateOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;if(!e)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);const{channels:s=[],channelGroups:n=[]}=this.parameters,r={channels:{}};return 1===s.length&&0===n.length?r.channels[s[0]]=t.payload:r.channels=t.payload,r}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${R(null!=s?s:[],",")}/uuid/${t}`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.join(",")}:{}}}class Pt extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNSetStateOperation}validate(){const{keySet:{subscribeKey:e},state:t,channels:s=[],channelGroups:n=[]}=this.parameters;return e?t?0===(null==s?void 0:s.length)&&0===(null==n?void 0:n.length)?"Please provide a list of channels and/or channel-groups":void 0:"Missing State":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return{state:t.payload}}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${R(null!=s?s:[],",")}/uuid/${I(t)}/data`}get queryParameters(){const{channelGroups:e,state:t}=this.parameters,s={state:JSON.stringify(t)};return e&&0!==e.length&&(s["channel-group"]=e.join(",")),s}}class Mt extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNHeartbeatOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?0===t.length&&0===s.length?"Please provide a list of channels and/or channel-groups":void 0:"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channels:t}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${R(null!=t?t:[],",")}/heartbeat`}get queryParameters(){const{channelGroups:e,state:t,heartbeat:s}=this.parameters,n={heartbeat:`${s}`};return e&&0!==e.length&&(n["channel-group"]=e.join(",")),t&&(n.state=JSON.stringify(t)),n}}class _t extends se{constructor(e){super(),this.parameters=e,this.parameters.channelGroups&&(this.parameters.channelGroups=Array.from(new Set(this.parameters.channelGroups))),this.parameters.channels&&(this.parameters.channels=Array.from(new Set(this.parameters.channels)))}operation(){return re.PNUnsubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?0===t.length&&0===s.length?"At least one `channel` or `channel group` should be provided.":void 0:"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return{}}))}get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/presence/sub-key/${t}/channel/${R(null!==(e=null==s?void 0:s.sort())&&void 0!==e?e:[],",")}/leave`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.sort().join(",")}:{}}}class At extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNWhereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t.payload?{channels:t.payload.channels}:{channels:[]}}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/presence/sub-key/${e}/uuid/${I(t)}`}}class jt extends se{constructor(e){var t,s,n,r,i,o;super(),this.parameters=e,null!==(t=(r=this.parameters).queryParameters)&&void 0!==t||(r.queryParameters={}),null!==(s=(i=this.parameters).includeUUIDs)&&void 0!==s||(i.includeUUIDs=true),null!==(n=(o=this.parameters).includeState)&&void 0!==n||(o.includeState=false)}operation(){const{channels:e=[],channelGroups:t=[]}=this.parameters;return 0===e.length&&0===t.length?re.PNGlobalHereNowOperation:re.PNHereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t,s;const n=this.deserializeResponse(e);if(!n)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(n.status>=400)throw A.create(e);const r="occupancy"in n?1:n.payload.total_channels,i="occupancy"in n?n.occupancy:n.payload.total_channels,o={};let a={};if("occupancy"in n){const e=this.parameters.channels[0];a[e]={uuids:null!==(t=n.uuids)&&void 0!==t?t:[],occupancy:i}}else a=null!==(s=n.payload.channels)&&void 0!==s?s:{};return Object.keys(a).forEach((e=>{const t=a[e];o[e]={occupants:this.parameters.includeUUIDs?t.uuids.map((e=>"string"==typeof e?{uuid:e,state:null}:e)):[],name:e,occupancy:t.occupancy}})),{totalChannels:r,totalOccupancy:i,channels:o}}))}get path(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;let n=`/v2/presence/sub-key/${e}`;return(t&&t.length>0||s&&s.length>0)&&(n+=`/channel/${R(null!=t?t:[],",")}`),n}get queryParameters(){const{channelGroups:e,includeUUIDs:t,includeState:s,queryParameters:n}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign({},t?{}:{disable_uuids:"1"}),null!=s&&s?{state:"1"}:{}),e&&e.length>0?{"channel-group":e.join(",")}:{}),n)}}class It extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNDeleteMessagesOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v3/history/sub-key/${e}/channel/${I(t)}`}get queryParameters(){const{start:e,end:t}=this.parameters;return Object.assign(Object.assign({},e?{start:e}:{}),t?{end:t}:{})}}class Rt extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNMessageCounts}validate(){const{keySet:{subscribeKey:e},channels:t,timetoken:s,channelTimetokens:n}=this.parameters;return e?t?s&&n?"`timetoken` and `channelTimetokens` are incompatible together":s||n?n&&n.length>1&&n.length!==t.length?"Length of `channelTimetokens` and `channels` do not match":void 0:"`timetoken` or `channelTimetokens` need to be set":"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return{channels:t.channels}}))}get path(){return`/v3/history/sub-key/${this.parameters.keySet.subscribeKey}/message-counts/${R(this.parameters.channels)}`}get queryParameters(){let{channelTimetokens:e}=this.parameters;return this.parameters.timetoken&&(e=[this.parameters.timetoken]),Object.assign(Object.assign({},1===e.length?{timetoken:e[0]}:{}),e.length>1?{channelsTimetoken:e.join(",")}:{})}}class Ut extends se{constructor(e){var t,s,n;super(),this.parameters=e,e.count?e.count=Math.min(e.count,100):e.count=100,null!==(t=e.stringifiedTimeToken)&&void 0!==t||(e.stringifiedTimeToken=false),null!==(s=e.includeMeta)&&void 0!==s||(e.includeMeta=false),null!==(n=e.logVerbosity)&&void 0!==n||(e.logVerbosity=false)}operation(){return re.PNHistoryOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));const s=t[0],n=t[1],r=t[2];return Array.isArray(s)?{messages:s.map((e=>{const t=this.processPayload(e.message),s={entry:t.payload,timetoken:e.timetoken};return t.error&&(s.error=t.error),e.meta&&(s.meta=e.meta),s})),startTimeToken:n,endTimeToken:r}:{messages:[],startTimeToken:n,endTimeToken:r}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/history/sub-key/${e}/channel/${I(t)}`}get queryParameters(){const{start:e,end:t,reverse:s,count:n,stringifiedTimeToken:r,includeMeta:i}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:n,include_token:"true"},e?{start:e}:{}),t?{end:t}:{}),r?{string_message_token:"true"}:{}),null!=s?{reverse:s.toString()}:{}),i?{include_meta:"true"}:{})}processPayload(e){const{crypto:t,logVerbosity:s}=this.parameters;if(!t||"string"!=typeof e)return{payload:e};let n,r;try{const s=t.decrypt(e);n=s instanceof ArrayBuffer?JSON.parse(Ut.decoder.decode(s)):s}catch(t){s&&console.log("decryption error",t.message),n=e,r=`Error while decrypting message content: ${t.message}`}return{payload:n,error:r}}}var Tt;!function(e){e[e.Message=-1]="Message",e[e.Files=4]="Files"}(Tt||(Tt={}));class Ft extends se{constructor(e){var t,s,n,r,i;super(),this.parameters=e;const o=null!==(t=e.includeMessageActions)&&void 0!==t&&t,a=e.channels.length>1||o?25:100;e.count?e.count=Math.min(e.count,a):e.count=a,e.includeUuid?e.includeUUID=e.includeUuid:null!==(s=e.includeUUID)&&void 0!==s||(e.includeUUID=true),null!==(n=e.stringifiedTimeToken)&&void 0!==n||(e.stringifiedTimeToken=false),null!==(r=e.includeMessageType)&&void 0!==r||(e.includeMessageType=true),null!==(i=e.logVerbosity)&&void 0!==i||(e.logVerbosity=false)}operation(){return re.PNFetchMessagesOperation}validate(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return e?t?void 0!==s&&s&&t.length>1?"History can return actions data for a single channel only. Either pass a single channel or disable the includeMessageActions flag.":void 0:"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t;const s=this.deserializeResponse(e);if(!s)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(s.status>=400)throw A.create(e);const n=null!==(t=s.channels)&&void 0!==t?t:{},r={};return Object.keys(n).forEach((e=>{r[e]=n[e].map((t=>{null===t.message_type&&(t.message_type=Tt.Message);const s=this.processPayload(e,t),n={channel:e,timetoken:t.timetoken,message:s.payload,messageType:t.message_type,uuid:t.uuid};if(t.actions){const e=n;e.actions=t.actions,e.data=t.actions}return t.meta&&(n.meta=t.meta),s.error&&(n.error=s.error),n}))})),s.more?{channels:r,more:s.more}:{channels:r}}))}get path(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return`/v3/${s?"history-with-actions":"history"}/sub-key/${e}/channel/${R(t)}`}get queryParameters(){const{start:e,end:t,count:s,includeMessageType:n,includeMeta:r,includeUUID:i,stringifiedTimeToken:o}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({max:s},e?{start:e}:{}),t?{end:t}:{}),o?{string_message_token:"true"}:{}),void 0!==r&&r?{include_meta:"true"}:{}),i?{include_uuid:"true"}:{}),n?{include_message_type:"true"}:{})}processPayload(e,t){const{crypto:s,logVerbosity:n}=this.parameters;if(!s||"string"!=typeof t.message)return{payload:t.message};let r,i;try{const e=s.decrypt(t.message);r=e instanceof ArrayBuffer?JSON.parse(Ft.decoder.decode(e)):e}catch(e){n&&console.log("decryption error",e.message),r=t.message,i=`Error while decrypting message content: ${e.message}`}if(!i&&r&&t.message_type==Tt.Files&&"object"==typeof r&&this.isFileMessage(r)){const t=r;return{payload:{message:t.message,file:Object.assign(Object.assign({},t.file),{url:this.parameters.getFileUrl({channel:e,id:t.file.id,name:t.file.name})})},error:i}}return{payload:r,error:i}}isFileMessage(e){return void 0!==e.file}}class xt extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNGetMessageActionsOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing message channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);let s=null,n=null;return t.data.length>0&&(s=t.data[0].actionTimetoken,n=t.data[t.data.length-1].actionTimetoken),{data:t.data,more:t.more,start:s,end:n}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/message-actions/${e}/channel/${I(t)}`}get queryParameters(){const{limit:e,start:t,end:s}=this.parameters;return Object.assign(Object.assign(Object.assign({},t?{start:t}:{}),s?{end:s}:{}),e?{limit:e}:{})}}class Dt extends se{constructor(e){super({method:H.POST}),this.parameters=e}operation(){return re.PNAddMessageActionOperation}validate(){const{keySet:{subscribeKey:e},action:t,channel:s,messageTimetoken:n}=this.parameters;return e?s?n?t?t.value?t.type?t.type.length>15?"Action.type value exceed maximum length of 15":void 0:"Missing Action.type":"Missing Action.value":"Missing Action":"Missing message timetoken":"Missing message channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return{data:t.data}}))}get path(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s}=this.parameters;return`/v1/message-actions/${e}/channel/${I(t)}/message/${s}`}get headers(){return{"Content-Type":"application/json"}}get body(){return JSON.stringify(this.parameters.action)}}class qt extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNRemoveMessageActionOperation}validate(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s,actionTimetoken:n}=this.parameters;return e?t?s?n?void 0:"Missing action timetoken":"Missing message timetoken":"Missing message action channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return{data:t.data}}))}get path(){const{keySet:{subscribeKey:e},channel:t,actionTimetoken:s,messageTimetoken:n}=this.parameters;return`/v1/message-actions/${e}/channel/${I(t)}/message/${n}/action/${s}`}}class Gt extends se{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).storeInHistory)&&void 0!==t||(s.storeInHistory=true)}operation(){return re.PNPublishFileMessageOperation}validate(){const{channel:e,fileId:t,fileName:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[2]}}))}get path(){const{message:e,channel:t,keySet:{publishKey:s,subscribeKey:n},fileId:r,fileName:i}=this.parameters,o=Object.assign({file:{name:i,id:r}},e?{message:e}:{});return`/v1/files/publish-file/${s}/${n}/0/${I(t)}/0/${I(this.prepareMessagePayload(o))}`}get queryParameters(){const{storeInHistory:e,ttl:t,meta:s}=this.parameters;return Object.assign(Object.assign({store:e?"1":"0"},t?{ttl:t}:{}),s&&"object"==typeof s?{meta:JSON.stringify(s)}:{})}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof s?s:u(s))}}class Kt extends se{constructor(e){super({method:H.LOCAL}),this.parameters=e}operation(){return re.PNGetFileUrlOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return e.url}))}get path(){const{channel:e,id:t,name:s,keySet:{subscribeKey:n}}=this.parameters;return`/v1/files/${n}/channels/${I(e)}/files/${t}/${s}`}}class $t extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNDeleteFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},id:t,channel:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${I(s)}/files/${t}/${n}`}}class Lt extends se{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).limit)&&void 0!==t||(s.limit=100)}operation(){return re.PNListFilesOperation}validate(){if(!this.parameters.channel)return"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${I(t)}/files`}get queryParameters(){const{limit:e,next:t}=this.parameters;return Object.assign({limit:e},t?{next:t}:{})}}class Bt extends se{constructor(e){super({method:H.POST}),this.parameters=e}operation(){return re.PNGenerateUploadUrlOperation}validate(){return this.parameters.channel?this.parameters.name?void 0:"'name' can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return{id:t.data.id,name:t.data.name,url:t.file_upload_request.url,formFields:t.file_upload_request.form_fields}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${I(t)}/generate-upload-url`}get headers(){return{"Content-Type":"application/json"}}get body(){return JSON.stringify({name:this.parameters.name})}}class Ht extends se{constructor(e){super({method:H.POST}),this.parameters=e;const t=e.file.mimeType;t&&(e.formFields=e.formFields.map((e=>"Content-Type"===e.name?{name:e.name,value:t}:e)))}operation(){return re.PNPublishFileOperation}validate(){const{fileId:e,fileName:t,file:s,uploadUrl:n}=this.parameters;return e?t?s?n?void 0:"Validation failed: file upload 'url' can't be empty":"Validation failed: 'file' can't be empty":"Validation failed: file 'name' can't be empty":"Validation failed: file 'id' can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return{status:e.status,message:e.body?Ht.decoder.decode(e.body):"OK"}}))}request(){return Object.assign(Object.assign({},super.request()),{origin:new URL(this.parameters.uploadUrl).origin,timeout:300})}get path(){const{pathname:e,search:t}=new URL(this.parameters.uploadUrl);return`${e}${t}`}get body(){return this.parameters.file}get formData(){return this.parameters.formFields}}class zt{constructor(e){var t;if(this.parameters=e,this.file=null===(t=this.parameters.PubNubFile)||void 0===t?void 0:t.create(e.file),!this.file)throw new Error("File upload error: unable to create File object.")}process(){return i(this,void 0,void 0,(function*(){let e,t;return this.generateFileUploadUrl().then((s=>(e=s.name,t=s.id,this.uploadFile(s)))).then((e=>{if(204!==e.status)throw new d("Upload to bucket was unsuccessful",{error:!0,statusCode:e.status,category:h.PNUnknownCategory,operation:re.PNPublishFileOperation,errorData:{message:e.message}})})).then((()=>this.publishFileMessage(t,e))).catch((e=>{if(e instanceof d)throw e;const t=e instanceof A?e:A.create(e);throw new d("File upload error.",t.toStatus(re.PNPublishFileOperation))}))}))}generateFileUploadUrl(){return i(this,void 0,void 0,(function*(){const e=new Bt(Object.assign(Object.assign({},this.parameters),{name:this.file.name,keySet:this.parameters.keySet}));return this.parameters.sendRequest(e)}))}uploadFile(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,PubNubFile:s,crypto:n,cryptography:r}=this.parameters,{id:i,name:o,url:a,formFields:c}=e;return this.parameters.PubNubFile.supportsEncryptFile&&(!t&&n?this.file=yield n.encryptFile(this.file,s):t&&r&&(this.file=yield r.encryptFile(t,this.file,s))),this.parameters.sendRequest(new Ht({fileId:i,fileName:o,file:this.file,uploadUrl:a,formFields:c}))}))}publishFileMessage(e,t){return i(this,void 0,void 0,(function*(){var s,n,r,i;let o,a={timetoken:"0"},c=this.parameters.fileUploadPublishRetryLimit,u=!1;do{try{a=yield this.parameters.publishFile(Object.assign(Object.assign({},this.parameters),{fileId:e,fileName:t})),u=!0}catch(e){e instanceof d&&(o=e),c-=1}}while(!u&&c>0);if(u)return{status:200,timetoken:a.timetoken,id:e,name:t};throw new d("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{error:!0,category:null!==(n=null===(s=o.status)||void 0===s?void 0:s.category)&&void 0!==n?n:h.PNUnknownCategory,statusCode:null!==(i=null===(r=o.status)||void 0===r?void 0:r.statusCode)&&void 0!==i?i:0,channel:this.parameters.channel,id:e,name:t})}))}}class Vt{subscribe(e){const t=null==e?void 0:e.timetoken;this.pubnub.subscribe(Object.assign({channels:this.channelNames,channelGroups:this.groupNames},null!==t&&""!==t&&{timetoken:t}))}unsubscribe(){this.pubnub.unsubscribe({channels:this.channelNames,channelGroups:this.groupNames})}set onMessage(e){this.listener.message=e}set onPresence(e){this.listener.presence=e}set onSignal(e){this.listener.signal=e}set onObjects(e){this.listener.objects=e}set onMessageAction(e){this.listener.messageAction=e}set onFile(e){this.listener.file=e}addListener(e){this.eventEmitter.addListener(e,this.channelNames.filter((e=>!e.endsWith("-pnpres"))),this.groupNames.filter((e=>!e.endsWith("-pnpres"))))}removeListener(e){this.eventEmitter.removeListener(e,this.channelNames,this.groupNames)}get channels(){return this.channelNames.slice(0)}get channelGroups(){return this.groupNames.slice(0)}}class Wt extends Vt{constructor({channels:e=[],channelGroups:t=[],subscriptionOptions:s,eventEmitter:n,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.subscriptionList=[],this.options=s,this.eventEmitter=n,this.pubnub=r,e.forEach((e=>{const t=this.pubnub.channel(e).subscription(this.options);this.channelNames=[...this.channelNames,...t.channels],this.subscriptionList.push(t)})),t.forEach((e=>{const t=this.pubnub.channelGroup(e).subscription(this.options);this.groupNames=[...this.groupNames,...t.channelGroups],this.subscriptionList.push(t)})),this.listener={},n.addListener(this.listener,this.channelNames.filter((e=>!e.endsWith("-pnpres"))),this.groupNames.filter((e=>!e.endsWith("-pnpres"))))}addSubscription(e){this.subscriptionList.push(e),this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscription(e){const t=e.channels,s=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!s.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>t!==e)),this.eventEmitter.removeListener(this.listener,t,s)}addSubscriptionSet(e){this.subscriptionList=[...this.subscriptionList,...e.subscriptions],this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscriptionSet(e){const t=e.channels,s=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!s.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>!e.subscriptions.includes(t))),this.eventEmitter.removeListener(this.listener,t,s)}get subscriptions(){return this.subscriptionList.slice(0)}}class Jt extends Vt{constructor({channels:e,channelGroups:t,subscriptionOptions:s,eventEmitter:n,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.channelNames=e,this.groupNames=t,this.options=s,this.pubnub=r,this.eventEmitter=n,this.listener={},n.addListener(this.listener,this.channelNames.filter((e=>!e.endsWith("-pnpres"))),this.groupNames.filter((e=>!e.endsWith("-pnpres"))))}addSubscription(e){return new Wt({channels:[...this.channelNames,...e.channels],channelGroups:[...this.groupNames,...e.channelGroups],subscriptionOptions:Object.assign(Object.assign({},this.options),null==e?void 0:e.options),eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Qt{constructor(e,t,s){this.id=e,this.eventEmitter=t,this.pubnub=s}subscription(e){return new Jt({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Yt{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.name=e}subscription(e){return new Jt({channels:[],channelGroups:(null==e?void 0:e.receivePresenceEvents)?[this.name,`${this.name}-pnpres`]:[this.name],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Xt{constructor(e,t,s){this.id=e,this.eventEmitter=t,this.pubnub=s}subscription(e){return new Jt({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Zt{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.name=e}subscription(e){return new Jt({channels:(null==e?void 0:e.receivePresenceEvents)?[this.name,`${this.name}-pnpres`]:[this.name],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class es extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNRemoveChannelsFromGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${I(t)}`}get queryParameters(){return{remove:this.parameters.channels.join(",")}}}class ts extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNAddChannelsToGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${I(t)}`}get queryParameters(){return{add:this.parameters.channels.join(",")}}}class ss extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNChannelsForGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return{channels:t.payload.channels}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${I(t)}`}}class ns extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNRemoveGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${I(t)}/remove`}}class rs extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNChannelGroupsOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return{groups:t.payload.groups}}))}get path(){return`/v1/channel-registration/sub-key/${this.parameters.keySet.subscribeKey}/channel-group`}}class is{constructor(e,t){this.keySet=e,this.sendRequest=t}listChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new ss(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}listGroups(e){return i(this,void 0,void 0,(function*(){const t=new rs({keySet:this.keySet});return e?this.sendRequest(t,e):this.sendRequest(t)}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new ts(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new es(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}deleteGroup(e,t){return i(this,void 0,void 0,(function*(){const s=new ns(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}}class os extends se{constructor(e){var t,s;super(),this.parameters=e,"apns2"===this.parameters.pushGateway&&(null!==(t=(s=this.parameters).environment)&&void 0!==t||(s.environment="development")),this.parameters.count&&this.parameters.count>1e3&&(this.parameters.count=1e3)}operation(){throw Error("Should be implemented in subclass.")}validate(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;return e?s?"add"!==t&&"remove"!==t||"channels"in this.parameters&&0!==this.parameters.channels.length?n?"apns2"!==this.parameters.pushGateway||this.parameters.topic?void 0:"Missing APNS2 topic":"Missing GW Type (pushGateway: gcm or apns2)":"Missing Channels":"Missing Device ID (device)":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){throw Error("Should be implemented in subclass.")}))}get path(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;let r="apns2"===n?`/v2/push/sub-key/${e}/devices-apns2/${s}`:`/v1/push/sub-key/${e}/devices/${s}`;return"remove-device"===t&&(r=`${r}/remove`),r}get queryParameters(){const{start:e,count:t}=this.parameters;let s=Object.assign(Object.assign({type:this.parameters.pushGateway},e?{start:e}:{}),t&&t>0?{count:t}:{});if("channels"in this.parameters&&(s[this.parameters.action]=this.parameters.channels.join(",")),"apns2"===this.parameters.pushGateway){const{environment:e,topic:t}=this.parameters;s=Object.assign(Object.assign({},s),{environment:e,topic:t})}return s}}class as extends os{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove"}))}operation(){return re.PNRemovePushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{}}))}}class cs extends os{constructor(e){super(Object.assign(Object.assign({},e),{action:"list"}))}operation(){return re.PNPushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{channels:t}}))}}class us extends os{constructor(e){super(Object.assign(Object.assign({},e),{action:"add"}))}operation(){return re.PNAddPushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{}}))}}class ls extends os{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove-device"}))}operation(){return re.PNRemoveAllPushNotificationsOperation}parse(e){return i(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{}}))}}class hs{constructor(e,t){this.keySet=e,this.sendRequest=t}listChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new cs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new us(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new as(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}deleteDevice(e,t){return i(this,void 0,void 0,(function*(){const s=new ls(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}}class ds extends se{constructor(e){var t,s,n,r,i,o;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(i=e.include).customFields)&&void 0!==s||(i.customFields=false),null!==(n=(o=e.include).totalCount)&&void 0!==n||(o.totalCount=false),null!==(r=e.limit)&&void 0!==r||(e.limit=100)}operation(){return re.PNGetAllChannelMetadataOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";return i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(","),count:`${e.totalCount}`},s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class ps extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNRemoveChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${I(t)}`}}class gs extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(l=e.include).customFields)&&void 0!==s||(l.customFields=false),null!==(n=(h=e.include).totalCount)&&void 0!==n||(h.totalCount=false),null!==(r=(d=e.include).statusField)&&void 0!==r||(d.statusField=false),null!==(i=(p=e.include).channelFields)&&void 0!==i||(p.channelFields=false),null!==(o=(g=e.include).customChannelFields)&&void 0!==o||(g.customChannelFields=false),null!==(a=(y=e.include).channelStatusField)&&void 0!==a||(y.channelStatusField=false),null!==(c=(f=e.include).channelTypeField)&&void 0!==c||(f.channelTypeField=false),null!==(u=e.limit)&&void 0!==u||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.PNGetMembershipsOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${I(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const o=[];return e.statusField&&o.push("status"),e.customFields&&o.push("custom"),e.channelFields&&o.push("channel"),e.channelStatusField&&o.push("channel.status"),e.channelTypeField&&o.push("channel.type"),e.customChannelFields&&o.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class ys extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l;super({method:H.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(a=e.include).customFields)&&void 0!==s||(a.customFields=false),null!==(n=(c=e.include).totalCount)&&void 0!==n||(c.totalCount=false),null!==(r=(u=e.include).channelFields)&&void 0!==r||(u.channelFields=false),null!==(i=(l=e.include).customChannelFields)&&void 0!==i||(l.customChannelFields=false),null!==(o=e.limit)&&void 0!==o||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.PNSetMembershipsOperation}validate(){const{uuid:e,channels:t}=this.parameters;return e?t&&0!==t.length?void 0:"Channels cannot be empty":"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${I(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const o=["channel.status","channel.type","status"];return e.customFields&&o.push("custom"),e.channelFields&&o.push("channel"),e.customChannelFields&&o.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{channels:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{channel:{id:e}}:{channel:{id:e.id},status:e.status,custom:e.custom}))})}}class fs extends se{constructor(e){var t,s,n,r;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(r=e.include).customFields)&&void 0!==s||(r.customFields=false),null!==(n=e.limit)&&void 0!==n||(e.limit=100)}operation(){return re.PNGetAllUUIDMetadataOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";return i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(",")},void 0!==e.totalCount?{count:`${e.totalCount}`}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class ms extends se{constructor(e){var t,s,n;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true)}operation(){return re.PNGetChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${I(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}}class bs extends se{constructor(e){var t,s,n;super({method:H.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true)}operation(){return re.PNSetChannelMetadataOperation}validate(){return this.parameters.channel?this.parameters.data?void 0:"Data cannot be empty":"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${I(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class vs extends se{constructor(e){super({method:H.DELETE}),this.parameters=e,this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.PNRemoveUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${I(t)}`}}class ws extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(l=e.include).customFields)&&void 0!==s||(l.customFields=false),null!==(n=(h=e.include).totalCount)&&void 0!==n||(h.totalCount=false),null!==(r=(d=e.include).statusField)&&void 0!==r||(d.statusField=false),null!==(i=(p=e.include).UUIDFields)&&void 0!==i||(p.UUIDFields=false),null!==(o=(g=e.include).customUUIDFields)&&void 0!==o||(g.customUUIDFields=false),null!==(a=(y=e.include).UUIDStatusField)&&void 0!==a||(y.UUIDStatusField=false),null!==(c=(f=e.include).UUIDTypeField)&&void 0!==c||(f.UUIDTypeField=false),null!==(u=e.limit)&&void 0!==u||(e.limit=100)}operation(){return re.PNSetMembersOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${I(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const o=[];return e.statusField&&o.push("status"),e.customFields&&o.push("custom"),e.UUIDFields&&o.push("uuid"),e.UUIDStatusField&&o.push("uuid.status"),e.UUIDTypeField&&o.push("uuid.type"),e.customUUIDFields&&o.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class Ss extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l;super({method:H.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(a=e.include).customFields)&&void 0!==s||(a.customFields=false),null!==(n=(c=e.include).totalCount)&&void 0!==n||(c.totalCount=false),null!==(r=(u=e.include).UUIDFields)&&void 0!==r||(u.UUIDFields=false),null!==(i=(l=e.include).customUUIDFields)&&void 0!==i||(l.customUUIDFields=false),null!==(o=e.limit)&&void 0!==o||(e.limit=100)}operation(){return re.PNSetMembersOperation}validate(){const{channel:e,uuids:t}=this.parameters;return e?t&&0!==t.length?void 0:"UUIDs cannot be empty":"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${I(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const o=["uuid.status","uuid.type","type"];return e.customFields&&o.push("custom"),e.UUIDFields&&o.push("uuid"),e.customUUIDFields&&o.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{uuids:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{uuid:{id:e}}:{uuid:{id:e.id},status:e.status,custom:e.custom}))})}}class ks extends se{constructor(e){var t,s,n;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.PNGetUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${I(t)}`}get queryParameters(){const{include:e}=this.parameters;return{include:["status","type",...e.customFields?["custom"]:[]].join(",")}}}class Es extends se{constructor(e){var t,s,n;super({method:H.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.PNSetUUIDMetadataOperation}validate(){return this.parameters.uuid?this.parameters.data?void 0:"Data cannot be empty":"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${I(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Os{constructor(e,t){this.configuration=e,this.sendRequest=t,this.keySet=e.keySet}getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getAllUUIDMetadata(e,t)}))}_getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const n=new fs(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getUUIDMetadata(e,t)}))}_getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new ks(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._setUUIDMetadata(e,t)}))}_setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new Es(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._removeUUIDMetadata(e,t)}))}_removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new vs(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getAllChannelMetadata(e,t)}))}_getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const n=new ds(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getChannelMetadata(e,t)}))}_getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new ms(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._setChannelMetadata(e,t)}))}_setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new bs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._removeChannelMetadata(e,t)}))}_removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new ps(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const s=new ws(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}setChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const s=new Ss(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const s=new Ss(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new gs(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new ys(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new ys(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n;if("spaceId"in e){const n=e,r={channel:null!==(s=n.spaceId)&&void 0!==s?s:n.channel,filter:n.filter,limit:n.limit,page:n.page,include:Object.assign({},n.include),sort:n.sort?Object.fromEntries(Object.entries(n.sort).map((([e,t])=>[e.replace("user","uuid"),t]))):void 0},i=e=>({status:e.status,data:e.data.map((e=>({user:e.uuid,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getChannelMembers(r,((e,s)=>{t(e,s?i(s):s)})):this.getChannelMembers(r).then(i)}const r=e,i={uuid:null!==(n=r.userId)&&void 0!==n?n:r.uuid,filter:r.filter,limit:r.limit,page:r.page,include:Object.assign({},r.include),sort:r.sort?Object.fromEntries(Object.entries(r.sort).map((([e,t])=>[e.replace("space","channel"),t]))):void 0},o=e=>({status:e.status,data:e.data.map((e=>({space:e.channel,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getMemberships(i,((e,s)=>{t(e,s?o(s):s)})):this.getMemberships(i).then(o)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n,r,i,o,a;if("spaceId"in e){const i=e,o={channel:null!==(s=i.spaceId)&&void 0!==s?s:i.channel,uuids:null!==(r=null===(n=i.users)||void 0===n?void 0:n.map((e=>"string"==typeof e?e:(e.userId,{id:e.userId,custom:e.custom}))))&&void 0!==r?r:i.uuids,limit:0};return t?this.setChannelMembers(o,t):this.setChannelMembers(o)}const c=e,u={uuid:null!==(i=c.userId)&&void 0!==i?i:c.uuid,channels:null!==(a=null===(o=c.spaces)||void 0===o?void 0:o.map((e=>"string"==typeof e?e:{id:e.spaceId,custom:e.custom})))&&void 0!==a?a:c.channels,limit:0};return t?this.setMemberships(u,t):this.setMemberships(u)}))}}class Cs extends se{constructor(){super()}operation(){return re.PNTimeOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[0]}}))}get path(){return"/time/0"}}class Ns extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNDownloadFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,crypto:s,cryptography:n,name:r,PubNubFile:i}=this.parameters,o=e.headers["content-type"];let a,c=e.body;return i.supportsEncryptFile&&(t||s)&&(t&&n?c=yield n.decrypt(t,c):!t&&s&&(a=yield s.decryptFile(i.create({data:c,name:r,mimeType:o}),i))),a||i.create({data:c,name:r,mimeType:o})}))}get path(){const{keySet:{subscribeKey:e},channel:t,id:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${I(t)}/files/${s}/${n}`}}class Ps{static notificationPayload(e,t){return new te(e,t)}static generateUUID(){return K.createUUID()}constructor(e){if(this._configuration=e.configuration,this.cryptography=e.cryptography,this.tokenManager=e.tokenManager,this.transport=e.transport,this.crypto=e.crypto,this._objects=new Os(this._configuration,this.sendRequest.bind(this)),this._channelGroups=new is(this._configuration.keySet,this.sendRequest.bind(this)),this._push=new hs(this._configuration.keySet,this.sendRequest.bind(this)),this.listenerManager=new W,this.eventEmitter=new ce(this.listenerManager),this._configuration.enableEventEngine){let e=this._configuration.getHeartbeatInterval();this.presenceState={},e&&(this.presenceEventEngine=new $e({heartbeat:this.heartbeat.bind(this),leave:e=>this.makeUnsubscribe(e,(()=>{})),heartbeatDelay:()=>new Promise(((t,s)=>{e=this._configuration.getHeartbeatInterval(),e?setTimeout(t,1e3*e):s(new d("Heartbeat interval has been reset."))})),retryDelay:e=>new Promise((t=>setTimeout(t,e))),emitStatus:e=>this.listenerManager.announceStatus(e),config:this._configuration,presenceState:this.presenceState})),this.eventEngine=new St({handshake:this.subscribeHandshake.bind(this),receiveMessages:this.subscribeReceiveMessages.bind(this),delay:e=>new Promise((t=>setTimeout(t,e))),join:this.join.bind(this),leave:this.leave.bind(this),leaveAll:this.leaveAll.bind(this),presenceState:this.presenceState,config:this._configuration,emitMessages:e=>{try{e.forEach((e=>this.eventEmitter.emitEvent(e)))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}},emitStatus:e=>this.listenerManager.announceStatus(e)})}else this.subscriptionManager=new Y(this._configuration,this.listenerManager,this.eventEmitter,this.makeSubscribe.bind(this),this.heartbeat.bind(this),this.makeUnsubscribe.bind(this),this.time.bind(this))}get configuration(){return this._configuration}get _config(){return this.configuration}get authKey(){var e;return null!==(e=this._configuration.authKey)&&void 0!==e?e:void 0}getAuthKey(){return this.authKey}setAuthKey(e){this._configuration.setAuthKey(e)}get userId(){return this._configuration.userId}set userId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}getUserId(){return this._configuration.userId}setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}get filterExpression(){var e;return null!==(e=this._configuration.getFilterExpression())&&void 0!==e?e:void 0}getFilterExpression(){return this.filterExpression}set filterExpression(e){this._configuration.setFilterExpression(e)}setFilterExpression(e){this.filterExpression=e}get cipherKey(){return this._configuration.getCipherKey()}set cipherKey(e){this._configuration.setCipherKey(e)}setCipherKey(e){this.cipherKey=e}set heartbeatInterval(e){this._configuration.setHeartbeatInterval(e)}setHeartbeatInterval(e){this.heartbeatInterval=e}getVersion(){return this._configuration.getVersion()}_addPnsdkSuffix(e,t){this._configuration._addPnsdkSuffix(e,t)}getUUID(){return this.userId}setUUID(e){this.userId=e}get customEncrypt(){return this._configuration.getCustomEncrypt()}get customDecrypt(){return this._configuration.getCustomDecrypt()}channel(e){return new Zt(e,this.eventEmitter,this)}channelGroup(e){return new Yt(e,this.eventEmitter,this)}channelMetadata(e){return new Qt(e,this.eventEmitter,this)}userMetadata(e){return new Xt(e,this.eventEmitter,this)}subscriptionSet(e){return new Wt(Object.assign(Object.assign({},e),{eventEmitter:this.eventEmitter,pubnub:this}))}sendRequest(e,t){return i(this,void 0,void 0,(function*(){const s=e.validate();if(s){if(t)return t(p(s),null);throw new d("Validation failed, check status for details",p(s))}const n=e.request();n.formData&&n.formData.length>0?n.timeout=300:e.operation()===re.PNSubscribeOperation?n.timeout=this._configuration.getSubscribeTimeout():n.timeout=this._configuration.getTransactionTimeout();const r={error:!1,operation:e.operation(),category:h.PNAcknowledgmentCategory,statusCode:0},[i,o]=this.transport.makeSendable(n);return e.cancellationController=o||null,i.then((t=>{if(r.statusCode=t.status,200!==t.status&&204!==t.status){const e=t.headers["content-type"];if(e||-1!==e.indexOf("javascript")||-1!==e.indexOf("json")){const e=JSON.parse(Ps.decoder.decode(t.body));"object"==typeof e&&"error"in e&&e.error&&"object"==typeof e.error&&(r.errorData=e.error)}}return e.parse(t)})).then((e=>t?t(r,e):e)).catch((s=>{const n=s instanceof A?s:A.create(s);if(t)return t(n.toStatus(e.operation()),null);throw n.toPubNubError(e.operation(),"REST API request processing error, check status for details")}))}))}destroy(e){this.subscriptionManager?(this.subscriptionManager.unsubscribeAll(e),this.subscriptionManager.disconnect()):this.eventEngine&&this.eventEngine.dispose()}stop(){this.destroy()}addListener(e){this.listenerManager.addListener(e)}removeListener(e){this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners()}publish(e,t){return i(this,void 0,void 0,(function*(){{const s=new kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}signal(e,t){return i(this,void 0,void 0,(function*(){{const s=new Et(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}fire(e,t){return i(this,void 0,void 0,(function*(){return null!=t||(t=()=>{}),this.publish(Object.assign(Object.assign({},e),{replicate:!1,storeInHistory:!1}),t)}))}getSubscribedChannels(){return this.subscriptionManager?this.subscriptionManager.subscribedChannels:this.eventEngine?this.eventEngine.getSubscribedChannels():[]}getSubscribedChannelGroups(){return this.subscriptionManager?this.subscriptionManager.subscribedChannelGroups:this.eventEngine?this.eventEngine.getSubscribedChannelGroups():[]}subscribe(e){this.subscriptionManager?this.subscriptionManager.subscribe(e):this.eventEngine&&this.eventEngine.subscribe(e)}makeSubscribe(e,t){{const s=new ae(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));if(this.sendRequest(s,((e,n)=>{var r;this.subscriptionManager&&(null===(r=this.subscriptionManager.abort)||void 0===r?void 0:r.identifier)===s.requestIdentifier&&(this.subscriptionManager.abort=null),t(e,n)})),this.subscriptionManager){const e=()=>s.abort();e.identifier=s.requestIdentifier,this.subscriptionManager.abort=e}}}unsubscribe(e){this.subscriptionManager?this.subscriptionManager.unsubscribe(e):this.eventEngine&&this.eventEngine.unsubscribe(e)}makeUnsubscribe(e,t){this.sendRequest(new _t(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),t)}unsubscribeAll(){this.subscriptionManager?this.subscriptionManager.unsubscribeAll():this.eventEngine&&this.eventEngine.unsubscribeAll()}disconnect(){this.subscriptionManager?this.subscriptionManager.disconnect():this.eventEngine&&this.eventEngine.disconnect()}reconnect(e){this.subscriptionManager?this.subscriptionManager.reconnect():this.eventEngine&&this.eventEngine.reconnect(null!=e?e:{})}subscribeHandshake(e){return i(this,void 0,void 0,(function*(){{const t=new Ct(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((e=>{t.abort()}));return this.sendRequest(t).then((e=>(s(),e.cursor)))}}))}subscribeReceiveMessages(e){return i(this,void 0,void 0,(function*(){{const t=new Ot(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((e=>{t.abort()}));return this.sendRequest(t).then((e=>(s(),e)))}}))}getMessageActions(e,t){return i(this,void 0,void 0,(function*(){{const s=new xt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}addMessageAction(e,t){return i(this,void 0,void 0,(function*(){{const s=new Dt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}removeMessageAction(e,t){return i(this,void 0,void 0,(function*(){{const s=new qt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}fetchMessages(e,t){return i(this,void 0,void 0,(function*(){{const s=new Ft(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}deleteMessages(e,t){return i(this,void 0,void 0,(function*(){{const s=new It(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}messageCounts(e,t){return i(this,void 0,void 0,(function*(){{const s=new Rt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}history(e,t){return i(this,void 0,void 0,(function*(){{const s=new Ut(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}hereNow(e,t){return i(this,void 0,void 0,(function*(){{const s=new jt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}whereNow(e,t){return i(this,void 0,void 0,(function*(){var s;{const n=new At({uuid:null!==(s=e.uuid)&&void 0!==s?s:this._configuration.userId,keySet:this._configuration.keySet});return t?this.sendRequest(n,t):this.sendRequest(n)}}))}getState(e,t){return i(this,void 0,void 0,(function*(){var s;{const n=new Nt(Object.assign(Object.assign({},e),{uuid:null!==(s=e.uuid)&&void 0!==s?s:this._configuration.userId,keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}setState(e,t){return i(this,void 0,void 0,(function*(){var s,n;{const{keySet:r,userId:i}=this._configuration,o=this._configuration.getPresenceTimeout();let a;if(this._configuration.enableEventEngine&&this.presenceState){const t=this.presenceState;null===(s=e.channels)||void 0===s||s.forEach((s=>t[s]=e.state)),"channelGroups"in e&&(null===(n=e.channelGroups)||void 0===n||n.forEach((s=>t[s]=e.state)))}return a="withHeartbeat"in e?new Mt(Object.assign(Object.assign({},e),{keySet:r,heartbeat:o})):new Pt(Object.assign(Object.assign({},e),{keySet:r,uuid:i})),this.subscriptionManager&&this.subscriptionManager.setState(e),t?this.sendRequest(a,t):this.sendRequest(a)}}))}presence(e){var t;null===(t=this.subscriptionManager)||void 0===t||t.changePresence(e)}heartbeat(e,t){return i(this,void 0,void 0,(function*(){{const s=new Mt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}join(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.join(e)}leave(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.leave(e)}leaveAll(){var e;null===(e=this.presenceEventEngine)||void 0===e||e.leaveAll()}grantToken(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant Token error: PAM module disabled")}))}revokeToken(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Revoke Token error: PAM module disabled")}))}get token(){return this.tokenManager&&this.tokenManager.getToken()}getToken(){return this.token}set token(e){this.tokenManager&&this.tokenManager.setToken(e)}setToken(e){this.token=e}parseToken(e){return this.tokenManager&&this.tokenManager.parseToken(e)}grant(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant error: PAM module disabled")}))}audit(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant Permissions error: PAM module disabled")}))}get objects(){return this._objects}fetchUsers(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getAllUUIDMetadata(e,t)}))}fetchUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getUUIDMetadata(e,t)}))}createUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}updateUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}removeUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._removeUUIDMetadata(e,t)}))}fetchSpaces(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getAllChannelMetadata(e,t)}))}fetchSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getChannelMetadata(e,t)}))}createSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}updateSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}removeSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._removeChannelMetadata(e,t)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.fetchMemberships(e,t)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}updateMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n,r;{if("spaceId"in e){const r=e,i={channel:null!==(s=r.spaceId)&&void 0!==s?s:r.channel,uuids:null!==(n=r.userIds)&&void 0!==n?n:r.uuids,limit:0};return t?this.objects.removeChannelMembers(i,t):this.objects.removeChannelMembers(i)}const i=e,o={uuid:i.userId,channels:null!==(r=i.spaceIds)&&void 0!==r?r:i.channels,limit:0};return t?this.objects.removeMemberships(o,t):this.objects.removeMemberships(o)}}))}get channelGroups(){return this._channelGroups}get push(){return this._push}sendFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const s=new zt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,fileUploadPublishRetryLimit:this._configuration.fileUploadPublishRetryLimit,file:e.file,sendRequest:this.sendRequest.bind(this),publishFile:this.publishFile.bind(this),crypto:this._configuration.getCryptoModule(),cryptography:this.cryptography?this.cryptography:void 0})),n={error:!1,operation:re.PNPublishFileOperation,category:h.PNAcknowledgmentCategory,statusCode:0};return s.process().then((e=>(n.statusCode=e.status,t?t(n,e):e))).catch((e=>{let s;throw e instanceof d?s=e.status:e instanceof A&&(s=e.toStatus(n.operation)),t&&s&&t(s,null),new d("REST API request processing error, check status for details",s)}))}}))}publishFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const s=new Gt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}listFiles(e,t){return i(this,void 0,void 0,(function*(){{const s=new Lt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}getFileUrl(e){var t;{const s=this.transport.request(new Kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})).request()),n=null!==(t=s.queryParameters)&&void 0!==t?t:{},r=Object.keys(n).map((e=>{const t=n[e];return Array.isArray(t)?t.map((t=>`${e}=${I(t)}`)).join("&"):`${e}=${I(t)}`})).join("&");return`${s.origin}${s.path}?${r}`}}downloadFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const s=new Ns(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,cryptography:this.cryptography?this.cryptography:void 0,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):yield this.sendRequest(s)}}))}deleteFile(e,t){return i(this,void 0,void 0,(function*(){{const s=new $t(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}time(e){return i(this,void 0,void 0,(function*(){const t=new Cs;return e?this.sendRequest(t,e):this.sendRequest(t)}))}encrypt(e,t){const s=this._configuration.getCryptoModule();if(!t&&s&&"string"==typeof e){const t=s.encrypt(e);return"string"==typeof t?t:u(t)}if(!this.crypto)throw new Error("Encryption error: cypher key not set");return this.crypto.encrypt(e,t)}decrypt(e,t){const s=this._configuration.getCryptoModule();if(!t&&s){const t=s.decrypt(e);return t instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(t)):t}if(!this.crypto)throw new Error("Decryption error: cypher key not set");return this.crypto.decrypt(e,t)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File encryption error. File constructor not configured.");if("string"!=typeof e&&!this._configuration.getCryptoModule())throw new Error("File encryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File encryption error. File encryption not available");return this.cryptography.encryptFile(e,t,this._configuration.PubNubFile)}return null===(s=this._configuration.getCryptoModule())||void 0===s?void 0:s.encryptFile(t,this._configuration.PubNubFile)}))}decryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File decryption error. File constructor not configured.");if("string"==typeof e&&!this._configuration.getCryptoModule())throw new Error("File decryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File decryption error. File decryption not available");return this.cryptography.decryptFile(e,t,this._configuration.PubNubFile)}return null===(s=this._configuration.getCryptoModule())||void 0===s?void 0:s.decryptFile(t,this._configuration.PubNubFile)}))}}Ps.decoder=new TextDecoder,Ps.OPERATIONS=re,Ps.CATEGORIES=h,Ps.ExponentialRetryPolicy=Le.ExponentialRetryPolicy,Ps.LinearRetryPolicy=Le.LinearRetryPolicy;class Ms{constructor(e,t){this.decode=e,this.base64ToBinary=t}decodeToken(e){let t="";e.length%4==3?t="=":e.length%4==2&&(t="==");const s=e.replace(/-/gi,"+").replace(/_/gi,"/")+t,n=this.decode(this.base64ToBinary(s));return"object"==typeof n?n:void 0}}class _s extends Ps{constructor(e){var t;const s=D(e),r=Object.assign(Object.assign({},s),{sdkFamily:"Web"});r.PubNubFile=a;const i=$(r,(e=>{if(e.cipherKey)return new P({default:new N(Object.assign({},e)),cryptors:[new S({cipherKey:e.cipherKey})]})}));let o,u,l;o=new B(new Ms((e=>x(n.decode(e))),c)),(i.getCipherKey()||i.secretKey)&&(u=new E({secretKey:i.secretKey,cipherKey:i.getCipherKey(),useRandomIVs:i.getUseRandomIVs(),customEncrypt:i.getCustomEncrypt(),customDecrypt:i.getCustomDecrypt()})),l=new C;let h=new F(i.keepAlive,i.logVerbosity);s.subscriptionWorkerUrl&&(h=new j({clientIdentifier:i._instanceId,subscriptionKey:i.subscribeKey,userId:i.getUserId(),workerUrl:s.subscriptionWorkerUrl,sdkVersion:i.getVersion(),logVerbosity:i.logVerbosity,workerLogVerbosity:r.subscriptionWorkerLogVerbosity,transport:h}));super({configuration:i,transport:new V({clientConfiguration:i,tokenManager:o,transport:h}),cryptography:l,tokenManager:o,crypto:u}),(null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t)&&(window.addEventListener("offline",(()=>{this.networkDownDetected()})),window.addEventListener("online",(()=>{this.networkUpDetected()})))}networkDownDetected(){this.listenerManager.announceNetworkDown(),this._configuration.restore?this.disconnect():this.destroy(!0)}networkUpDetected(){this.listenerManager.announceNetworkUp(),this.reconnect()}}return _s.CryptoModule=P,_s})); +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).PubNub=t()}(this,(function(){"use strict";var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var s={exports:{}};!function(t){!function(e,s){var n=Math.pow(2,-24),r=Math.pow(2,32),i=Math.pow(2,53);var o={encode:function(e){var t,n=new ArrayBuffer(256),o=new DataView(n),a=0;function c(e){for(var s=n.byteLength,r=a+e;s>2,u=0;u>6),r.push(128|63&o)):o<55296?(r.push(224|o>>12),r.push(128|o>>6&63),r.push(128|63&o)):(o=(1023&o)<<10,o|=1023&t.charCodeAt(++n),o+=65536,r.push(240|o>>18),r.push(128|o>>12&63),r.push(128|o>>6&63),r.push(128|63&o))}return d(3,r.length),h(r);default:var p;if(Array.isArray(t))for(d(4,p=t.length),n=0;n>5!==e)throw"Invalid indefinite length element";return s}function f(e,t){for(var s=0;s>10),e.push(56320|1023&n))}}"function"!=typeof t&&(t=function(e){return e}),"function"!=typeof i&&(i=function(){return s});var m=function e(){var r,d,m=l(),b=m>>5,v=31&m;if(7===b)switch(v){case 25:return function(){var e=new ArrayBuffer(4),t=new DataView(e),s=h(),r=32768&s,i=31744&s,o=1023&s;if(31744===i)i=261120;else if(0!==i)i+=114688;else if(0!==o)return o*n;return t.setUint32(0,r<<16|i<<13|o<<13),t.getFloat32(0)}();case 26:return c(o.getFloat32(a),4);case 27:return c(o.getFloat64(a),8)}if((d=g(v))<0&&(b<2||6=0;)S+=d,w.push(u(d));var k=new Uint8Array(S),E=0;for(r=0;r=0;)f(O,d);else f(O,d);return String.fromCharCode.apply(null,O);case 4:var C;if(d<0)for(C=[];!p();)C.push(e());else for(C=new Array(d),r=0;r{const s=new FileReader;s.addEventListener("load",(()=>{if(s.result instanceof ArrayBuffer)return e(s.result)})),s.addEventListener("error",(()=>t(s.error))),s.readAsArrayBuffer(this.data)}))}))}toString(){return i(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{const s=new FileReader;s.addEventListener("load",(()=>{if("string"==typeof s.result)return e(s.result)})),s.addEventListener("error",(()=>{t(s.error)})),s.readAsBinaryString(this.data)}))}))}toStream(){return i(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in Node.js environments.")}))}toFile(){return i(this,void 0,void 0,(function*(){return this.data}))}toFileUri(){return i(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in React Native environments.")}))}toBlob(){return i(this,void 0,void 0,(function*(){return this.data}))}}a.supportsBlob="undefined"!=typeof Blob,a.supportsFile="undefined"!=typeof File,a.supportsBuffer=!1,a.supportsStream=!1,a.supportsString=!0,a.supportsArrayBuffer=!0,a.supportsEncryptFile=!0,a.supportsFileUri=!1;function c(e){const t=e.replace(/==?$/,""),s=Math.floor(t.length/4*3),n=new ArrayBuffer(s),r=new Uint8Array(n);let i=0;function o(){const e=t.charAt(i++),s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(e);if(-1===s)throw new Error(`Illegal character at ${i}: ${t.charAt(i-1)}`);return s}for(let e=0;e>4,c=(15&s)<<4|n>>2,u=(3&n)<<6|i;r[e]=a,64!=n&&(r[e+1]=c),64!=i&&(r[e+2]=u)}return n}function u(e){let t="";const s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=new Uint8Array(e),r=n.byteLength,i=r%3,o=r-i;let a,c,u,l,h;for(let e=0;e>18,c=(258048&h)>>12,u=(4032&h)>>6,l=63&h,t+=s[a]+s[c]+s[u]+s[l];return 1==i?(h=n[o],a=(252&h)>>2,c=(3&h)<<4,t+=s[a]+s[c]+"=="):2==i&&(h=n[o]<<8|n[o+1],a=(64512&h)>>10,c=(1008&h)>>4,u=(15&h)<<2,t+=s[a]+s[c]+s[u]+"="),t}var l;!function(e){e.PNNetworkIssuesCategory="PNNetworkIssuesCategory",e.PNTimeoutCategory="PNTimeoutCategory",e.PNCancelledCategory="PNCancelledCategory",e.PNBadRequestCategory="PNBadRequestCategory",e.PNAccessDeniedCategory="PNAccessDeniedCategory",e.PNValidationErrorCategory="PNValidationErrorCategory",e.PNAcknowledgmentCategory="PNAcknowledgmentCategory",e.PNUnknownCategory="PNUnknownCategory",e.PNNetworkUpCategory="PNNetworkUpCategory",e.PNNetworkDownCategory="PNNetworkDownCategory",e.PNReconnectedCategory="PNReconnectedCategory",e.PNConnectedCategory="PNConnectedCategory",e.PNRequestMessageCountExceededCategory="PNRequestMessageCountExceededCategory",e.PNDisconnectedCategory="PNDisconnectedCategory",e.PNConnectionErrorCategory="PNConnectionErrorCategory",e.PNDisconnectedUnexpectedlyCategory="PNDisconnectedUnexpectedlyCategory"}(l||(l={}));var h=l;class d extends Error{constructor(e,t){super(e),this.status=t,this.name="PubNubError",this.message=e,Object.setPrototypeOf(this,new.target.prototype)}}function p(e,t){return s=Object.assign({message:e},{}),null!==(n=s.statusCode)&&void 0!==n||(s.statusCode=0),Object.assign(Object.assign({},s),{statusCode:s.statusCode,category:h.PNValidationErrorCategory,error:!0});var s,n}var g,y,f,m,b,v=v||function(e,t){var s={},n=s.lib={},r=function(){},i=n.Base={extend:function(e){r.prototype=this;var t=new r;return e&&t.mixIn(e),t.hasOwnProperty("init")||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},o=n.WordArray=i.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||c).stringify(this)},concat:function(e){var t=this.words,s=e.words,n=this.sigBytes;if(e=e.sigBytes,this.clamp(),n%4)for(var r=0;r>>2]|=(s[r>>>2]>>>24-r%4*8&255)<<24-(n+r)%4*8;else if(65535>>2]=s[r>>>2];else t.push.apply(t,s);return this.sigBytes+=e,this},clamp:function(){var t=this.words,s=this.sigBytes;t[s>>>2]&=4294967295<<32-s%4*8,t.length=e.ceil(s/4)},clone:function(){var e=i.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var s=[],n=0;n>>2]>>>24-n%4*8&255;s.push((r>>>4).toString(16)),s.push((15&r).toString(16))}return s.join("")},parse:function(e){for(var t=e.length,s=[],n=0;n>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new o.init(s,t/2)}},u=a.Latin1={stringify:function(e){var t=e.words;e=e.sigBytes;for(var s=[],n=0;n>>2]>>>24-n%4*8&255));return s.join("")},parse:function(e){for(var t=e.length,s=[],n=0;n>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new o.init(s,t)}},l=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},h=n.BufferedBlockAlgorithm=i.extend({reset:function(){this._data=new o.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=l.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var s=this._data,n=s.words,r=s.sigBytes,i=this.blockSize,a=r/(4*i);if(t=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*i,r=e.min(4*t,r),t){for(var c=0;cu;){var l;e:{l=c;for(var h=e.sqrt(l),d=2;d<=h;d++)if(!(l%d)){l=!1;break e}l=!0}l&&(8>u&&(i[u]=a(e.pow(c,.5))),o[u]=a(e.pow(c,1/3)),u++),c++}var p=[];r=r.SHA256=n.extend({_doReset:function(){this._hash=new s.init(i.slice(0))},_doProcessBlock:function(e,t){for(var s=this._hash.words,n=s[0],r=s[1],i=s[2],a=s[3],c=s[4],u=s[5],l=s[6],h=s[7],d=0;64>d;d++){if(16>d)p[d]=0|e[t+d];else{var g=p[d-15],y=p[d-2];p[d]=((g<<25|g>>>7)^(g<<14|g>>>18)^g>>>3)+p[d-7]+((y<<15|y>>>17)^(y<<13|y>>>19)^y>>>10)+p[d-16]}g=h+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&u^~c&l)+o[d]+p[d],y=((n<<30|n>>>2)^(n<<19|n>>>13)^(n<<10|n>>>22))+(n&r^n&i^r&i),h=l,l=u,u=c,c=a+g|0,a=i,i=r,r=n,n=g+y|0}s[0]=s[0]+n|0,s[1]=s[1]+r|0,s[2]=s[2]+i|0,s[3]=s[3]+a|0,s[4]=s[4]+c|0,s[5]=s[5]+u|0,s[6]=s[6]+l|0,s[7]=s[7]+h|0},_doFinalize:function(){var t=this._data,s=t.words,n=8*this._nDataBytes,r=8*t.sigBytes;return s[r>>>5]|=128<<24-r%32,s[14+(r+64>>>9<<4)]=e.floor(n/4294967296),s[15+(r+64>>>9<<4)]=n,t.sigBytes=4*s.length,this._process(),this._hash},clone:function(){var e=n.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=n._createHelper(r),t.HmacSHA256=n._createHmacHelper(r)}(Math),y=(g=v).enc.Utf8,g.algo.HMAC=g.lib.Base.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=y.parse(t));var s=e.blockSize,n=4*s;t.sigBytes>n&&(t=e.finalize(t)),t.clamp();for(var r=this._oKey=t.clone(),i=this._iKey=t.clone(),o=r.words,a=i.words,c=0;c>>2]>>>24-r%4*8&255)<<16|(t[r+1>>>2]>>>24-(r+1)%4*8&255)<<8|t[r+2>>>2]>>>24-(r+2)%4*8&255,o=0;4>o&&r+.75*o>>6*(3-o)&63));if(t=n.charAt(64))for(;e.length%4;)e.push(t);return e.join("")},parse:function(e){var t=e.length,s=this._map;(n=s.charAt(64))&&-1!=(n=e.indexOf(n))&&(t=n);for(var n=[],r=0,i=0;i>>6-i%4*2;n[r>>>2]|=(o|a)<<24-r%4*8,r++}return m.create(n,r)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},function(e){function t(e,t,s,n,r,i,o){return((e=e+(t&s|~t&n)+r+o)<>>32-i)+t}function s(e,t,s,n,r,i,o){return((e=e+(t&n|s&~n)+r+o)<>>32-i)+t}function n(e,t,s,n,r,i,o){return((e=e+(t^s^n)+r+o)<>>32-i)+t}function r(e,t,s,n,r,i,o){return((e=e+(s^(t|~n))+r+o)<>>32-i)+t}for(var i=v,o=(c=i.lib).WordArray,a=c.Hasher,c=i.algo,u=[],l=0;64>l;l++)u[l]=4294967296*e.abs(e.sin(l+1))|0;c=c.MD5=a.extend({_doReset:function(){this._hash=new o.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,i){for(var o=0;16>o;o++){var a=e[c=i+o];e[c]=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8)}o=this._hash.words;var c=e[i+0],l=(a=e[i+1],e[i+2]),h=e[i+3],d=e[i+4],p=e[i+5],g=e[i+6],y=e[i+7],f=e[i+8],m=e[i+9],b=e[i+10],v=e[i+11],w=e[i+12],S=e[i+13],k=e[i+14],E=e[i+15],O=t(O=o[0],P=o[1],N=o[2],C=o[3],c,7,u[0]),C=t(C,O,P,N,a,12,u[1]),N=t(N,C,O,P,l,17,u[2]),P=t(P,N,C,O,h,22,u[3]);O=t(O,P,N,C,d,7,u[4]),C=t(C,O,P,N,p,12,u[5]),N=t(N,C,O,P,g,17,u[6]),P=t(P,N,C,O,y,22,u[7]),O=t(O,P,N,C,f,7,u[8]),C=t(C,O,P,N,m,12,u[9]),N=t(N,C,O,P,b,17,u[10]),P=t(P,N,C,O,v,22,u[11]),O=t(O,P,N,C,w,7,u[12]),C=t(C,O,P,N,S,12,u[13]),N=t(N,C,O,P,k,17,u[14]),O=s(O,P=t(P,N,C,O,E,22,u[15]),N,C,a,5,u[16]),C=s(C,O,P,N,g,9,u[17]),N=s(N,C,O,P,v,14,u[18]),P=s(P,N,C,O,c,20,u[19]),O=s(O,P,N,C,p,5,u[20]),C=s(C,O,P,N,b,9,u[21]),N=s(N,C,O,P,E,14,u[22]),P=s(P,N,C,O,d,20,u[23]),O=s(O,P,N,C,m,5,u[24]),C=s(C,O,P,N,k,9,u[25]),N=s(N,C,O,P,h,14,u[26]),P=s(P,N,C,O,f,20,u[27]),O=s(O,P,N,C,S,5,u[28]),C=s(C,O,P,N,l,9,u[29]),N=s(N,C,O,P,y,14,u[30]),O=n(O,P=s(P,N,C,O,w,20,u[31]),N,C,p,4,u[32]),C=n(C,O,P,N,f,11,u[33]),N=n(N,C,O,P,v,16,u[34]),P=n(P,N,C,O,k,23,u[35]),O=n(O,P,N,C,a,4,u[36]),C=n(C,O,P,N,d,11,u[37]),N=n(N,C,O,P,y,16,u[38]),P=n(P,N,C,O,b,23,u[39]),O=n(O,P,N,C,S,4,u[40]),C=n(C,O,P,N,c,11,u[41]),N=n(N,C,O,P,h,16,u[42]),P=n(P,N,C,O,g,23,u[43]),O=n(O,P,N,C,m,4,u[44]),C=n(C,O,P,N,w,11,u[45]),N=n(N,C,O,P,E,16,u[46]),O=r(O,P=n(P,N,C,O,l,23,u[47]),N,C,c,6,u[48]),C=r(C,O,P,N,y,10,u[49]),N=r(N,C,O,P,k,15,u[50]),P=r(P,N,C,O,p,21,u[51]),O=r(O,P,N,C,w,6,u[52]),C=r(C,O,P,N,h,10,u[53]),N=r(N,C,O,P,b,15,u[54]),P=r(P,N,C,O,a,21,u[55]),O=r(O,P,N,C,f,6,u[56]),C=r(C,O,P,N,E,10,u[57]),N=r(N,C,O,P,g,15,u[58]),P=r(P,N,C,O,S,21,u[59]),O=r(O,P,N,C,d,6,u[60]),C=r(C,O,P,N,v,10,u[61]),N=r(N,C,O,P,l,15,u[62]),P=r(P,N,C,O,m,21,u[63]);o[0]=o[0]+O|0,o[1]=o[1]+P|0,o[2]=o[2]+N|0,o[3]=o[3]+C|0},_doFinalize:function(){var t=this._data,s=t.words,n=8*this._nDataBytes,r=8*t.sigBytes;s[r>>>5]|=128<<24-r%32;var i=e.floor(n/4294967296);for(s[15+(r+64>>>9<<4)]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),s[14+(r+64>>>9<<4)]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),t.sigBytes=4*(s.length+1),this._process(),s=(t=this._hash).words,n=0;4>n;n++)r=s[n],s[n]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8);return t},clone:function(){var e=a.clone.call(this);return e._hash=this._hash.clone(),e}}),i.MD5=a._createHelper(c),i.HmacMD5=a._createHmacHelper(c)}(Math),function(){var e,t=v,s=(e=t.lib).Base,n=e.WordArray,r=(e=t.algo).EvpKDF=s.extend({cfg:s.extend({keySize:4,hasher:e.MD5,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var s=(a=this.cfg).hasher.create(),r=n.create(),i=r.words,o=a.keySize,a=a.iterations;i.length>>2]}},t.BlockCipher=a.extend({cfg:a.cfg.extend({mode:c,padding:l}),reset:function(){a.reset.call(this);var e=(t=this.cfg).iv,t=t.mode;if(this._xformMode==this._ENC_XFORM_MODE)var s=t.createEncryptor;else s=t.createDecryptor,this._minBufferSize=1;this._mode=s.call(t,this,e&&e.words)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){e.pad(this._data,this.blockSize);var t=this._process(!0)}else t=this._process(!0),e.unpad(t);return t},blockSize:4});var h=t.CipherParams=s.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),d=(c=(p.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext;return((e=e.salt)?n.create([1398893684,1701076831]).concat(e).concat(t):t).toString(i)},parse:function(e){var t=(e=i.parse(e)).words;if(1398893684==t[0]&&1701076831==t[1]){var s=n.create(t.slice(2,4));t.splice(0,4),e.sigBytes-=16}return h.create({ciphertext:e,salt:s})}},t.SerializableCipher=s.extend({cfg:s.extend({format:c}),encrypt:function(e,t,s,n){n=this.cfg.extend(n);var r=e.createEncryptor(s,n);return t=r.finalize(t),r=r.cfg,h.create({ciphertext:t,key:s,iv:r.iv,algorithm:e,mode:r.mode,padding:r.padding,blockSize:e.blockSize,formatter:n.format})},decrypt:function(e,t,s,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),e.createDecryptor(s,n).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}})),p=(p.kdf={}).OpenSSL={execute:function(e,t,s,r){return r||(r=n.random(8)),e=o.create({keySize:t+s}).compute(e,r),s=n.create(e.words.slice(t),4*s),e.sigBytes=4*t,h.create({key:e,iv:s,salt:r})}},g=t.PasswordBasedCipher=d.extend({cfg:d.cfg.extend({kdf:p}),encrypt:function(e,t,s,n){return s=(n=this.cfg.extend(n)).kdf.execute(s,e.keySize,e.ivSize),n.iv=s.iv,(e=d.encrypt.call(this,e,t,s.key,n)).mixIn(s),e},decrypt:function(e,t,s,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),s=n.kdf.execute(s,e.keySize,e.ivSize,t.salt),n.iv=s.iv,d.decrypt.call(this,e,t,s.key,n)}})}(),function(){for(var e=v,t=e.lib.BlockCipher,s=e.algo,n=[],r=[],i=[],o=[],a=[],c=[],u=[],l=[],h=[],d=[],p=[],g=0;256>g;g++)p[g]=128>g?g<<1:g<<1^283;var y=0,f=0;for(g=0;256>g;g++){var m=(m=f^f<<1^f<<2^f<<3^f<<4)>>>8^255&m^99;n[y]=m,r[m]=y;var b=p[y],w=p[b],S=p[w],k=257*p[m]^16843008*m;i[y]=k<<24|k>>>8,o[y]=k<<16|k>>>16,a[y]=k<<8|k>>>24,c[y]=k,k=16843009*S^65537*w^257*b^16843008*y,u[m]=k<<24|k>>>8,l[m]=k<<16|k>>>16,h[m]=k<<8|k>>>24,d[m]=k,y?(y=b^p[p[p[S^b]]],f^=p[p[f]]):y=f=1}var E=[0,1,2,4,8,16,32,64,128,27,54];s=s.AES=t.extend({_doReset:function(){for(var e=(s=this._key).words,t=s.sigBytes/4,s=4*((this._nRounds=t+6)+1),r=this._keySchedule=[],i=0;i>>24]<<24|n[o>>>16&255]<<16|n[o>>>8&255]<<8|n[255&o]):(o=n[(o=o<<8|o>>>24)>>>24]<<24|n[o>>>16&255]<<16|n[o>>>8&255]<<8|n[255&o],o^=E[i/t|0]<<24),r[i]=r[i-t]^o}for(e=this._invKeySchedule=[],t=0;tt||4>=i?o:u[n[o>>>24]]^l[n[o>>>16&255]]^h[n[o>>>8&255]]^d[n[255&o]]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,i,o,a,c,n)},decryptBlock:function(e,t){var s=e[t+1];e[t+1]=e[t+3],e[t+3]=s,this._doCryptBlock(e,t,this._invKeySchedule,u,l,h,d,r),s=e[t+1],e[t+1]=e[t+3],e[t+3]=s},_doCryptBlock:function(e,t,s,n,r,i,o,a){for(var c=this._nRounds,u=e[t]^s[0],l=e[t+1]^s[1],h=e[t+2]^s[2],d=e[t+3]^s[3],p=4,g=1;g>>24]^r[l>>>16&255]^i[h>>>8&255]^o[255&d]^s[p++],f=n[l>>>24]^r[h>>>16&255]^i[d>>>8&255]^o[255&u]^s[p++],m=n[h>>>24]^r[d>>>16&255]^i[u>>>8&255]^o[255&l]^s[p++];d=n[d>>>24]^r[u>>>16&255]^i[l>>>8&255]^o[255&h]^s[p++],u=y,l=f,h=m}y=(a[u>>>24]<<24|a[l>>>16&255]<<16|a[h>>>8&255]<<8|a[255&d])^s[p++],f=(a[l>>>24]<<24|a[h>>>16&255]<<16|a[d>>>8&255]<<8|a[255&u])^s[p++],m=(a[h>>>24]<<24|a[d>>>16&255]<<16|a[u>>>8&255]<<8|a[255&l])^s[p++],d=(a[d>>>24]<<24|a[u>>>16&255]<<16|a[l>>>8&255]<<8|a[255&h])^s[p++],e[t]=y,e[t+1]=f,e[t+2]=m,e[t+3]=d},keySize:8});e.AES=t._createHelper(s)}(),v.mode.ECB=((b=v.lib.BlockCipherMode.extend()).Encryptor=b.extend({processBlock:function(e,t){this._cipher.encryptBlock(e,t)}}),b.Decryptor=b.extend({processBlock:function(e,t){this._cipher.decryptBlock(e,t)}}),b);var w=t(v);class S{constructor({cipherKey:e}){this.cipherKey=e,this.CryptoJS=w,this.encryptedKey=this.CryptoJS.SHA256(e)}encrypt(e){if(0===("string"==typeof e?e:S.decoder.decode(e)).length)throw new Error("encryption error. empty content");const t=this.getIv();return{metadata:t,data:c(this.CryptoJS.AES.encrypt(e,this.encryptedKey,{iv:this.bufferToWordArray(t),mode:this.CryptoJS.mode.CBC}).ciphertext.toString(this.CryptoJS.enc.Base64))}}encryptFileData(e){return i(this,void 0,void 0,(function*(){const t=yield this.getKey(),s=this.getIv();return{data:yield crypto.subtle.encrypt({name:this.algo,iv:s},t,e),metadata:s}}))}decrypt(e){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=this.bufferToWordArray(new Uint8ClampedArray(e.metadata)),s=this.bufferToWordArray(new Uint8ClampedArray(e.data));return S.encoder.encode(this.CryptoJS.AES.decrypt({ciphertext:s},this.encryptedKey,{iv:t,mode:this.CryptoJS.mode.CBC}).toString(this.CryptoJS.enc.Utf8)).buffer}decryptFileData(e){return i(this,void 0,void 0,(function*(){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=yield this.getKey();return crypto.subtle.decrypt({name:this.algo,iv:e.metadata},t,e.data)}))}get identifier(){return"ACRH"}get algo(){return"AES-CBC"}getIv(){return crypto.getRandomValues(new Uint8Array(S.BLOCK_SIZE))}getKey(){return i(this,void 0,void 0,(function*(){const e=S.encoder.encode(this.cipherKey),t=yield crypto.subtle.digest("SHA-256",e.buffer);return crypto.subtle.importKey("raw",t,this.algo,!0,["encrypt","decrypt"])}))}bufferToWordArray(e){const t=[];let s;for(s=0;se.toString(16).padStart(2,"0"))).join(""),n=O.encoder.encode(s.slice(0,32)).buffer;return crypto.subtle.importKey("raw",n,"AES-CBC",!0,["encrypt","decrypt"])}))}concatArrayBuffer(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(new Uint8Array(e),0),s.set(new Uint8Array(t),e.byteLength),s.buffer}}O.IV_LENGTH=16,O.encoder=new TextEncoder,O.decoder=new TextDecoder;class C{constructor(e){this.config=e,this.cryptor=new E(Object.assign({},e)),this.fileCryptor=new O}encrypt(e){const t="string"==typeof e?e:C.decoder.decode(e);return{data:this.cryptor.encrypt(t),metadata:null}}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if(!this.config.cipherKey)throw new d("File encryption error: cipher key not set.");return this.fileCryptor.encryptFile(null===(s=this.config)||void 0===s?void 0:s.cipherKey,e,t)}))}decrypt(e){const t="string"==typeof e.data?e.data:u(e.data);return this.cryptor.decrypt(t)}decryptFile(e,t){return i(this,void 0,void 0,(function*(){if(!this.config.cipherKey)throw new d("File encryption error: cipher key not set.");return this.fileCryptor.decryptFile(this.config.cipherKey,e,t)}))}get identifier(){return""}}C.encoder=new TextEncoder,C.decoder=new TextDecoder;class N extends o{static legacyCryptoModule(e){var t;if(!e.cipherKey)throw new d("Crypto module error: cipher key not set.");return new N({default:new C(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t})),cryptors:[new S({cipherKey:e.cipherKey})]})}static aesCbcCryptoModule(e){var t;if(!e.cipherKey)throw new d("Crypto module error: cipher key not set.");return new N({default:new S({cipherKey:e.cipherKey}),cryptors:[new C(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t}))]})}static withDefaultCryptor(e){return new this({default:e})}encrypt(e){const t=e instanceof ArrayBuffer&&this.defaultCryptor.identifier===N.LEGACY_IDENTIFIER?this.defaultCryptor.encrypt(N.decoder.decode(e)):this.defaultCryptor.encrypt(e);if(!t.metadata)return t.data;if("string"==typeof t.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");const s=this.getHeaderData(t);return this.concatArrayBuffer(s,t.data)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){if(this.defaultCryptor.identifier===P.LEGACY_IDENTIFIER)return this.defaultCryptor.encryptFile(e,t);const s=yield this.getFileData(e),n=yield this.defaultCryptor.encryptFileData(s);if("string"==typeof n.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");return t.create({name:e.name,mimeType:"application/octet-stream",data:this.concatArrayBuffer(this.getHeaderData(n),n.data)})}))}decrypt(e){const t="string"==typeof e?c(e):e,s=P.tryParse(t),n=this.getCryptor(s),r=s.length>0?t.slice(s.length-s.metadataLength,s.length):null;if(t.slice(s.length).byteLength<=0)throw new Error("Decryption error: empty content");return n.decrypt({data:t.slice(s.length),metadata:r})}decryptFile(e,t){return i(this,void 0,void 0,(function*(){const s=yield e.data.arrayBuffer(),n=P.tryParse(s),r=this.getCryptor(n);if((null==r?void 0:r.identifier)===P.LEGACY_IDENTIFIER)return r.decryptFile(e,t);const i=(yield this.getFileData(s)).slice(n.length-n.metadataLength,n.length);return t.create({name:e.name,data:yield this.defaultCryptor.decryptFileData({data:s.slice(n.length),metadata:i})})}))}getCryptorFromId(e){const t=this.getAllCryptors().find((t=>e===t.identifier));if(t)return t;throw Error("Unknown cryptor error")}getCryptor(e){if("string"==typeof e){const t=this.getAllCryptors().find((t=>t.identifier===e));if(t)return t;throw new Error("Unknown cryptor error")}if(e instanceof M)return this.getCryptorFromId(e.identifier)}getHeaderData(e){if(!e.metadata)return;const t=P.from(this.defaultCryptor.identifier,e.metadata),s=new Uint8Array(t.length);let n=0;return s.set(t.data,n),n+=t.length-e.metadata.byteLength,s.set(new Uint8Array(e.metadata),n),s.buffer}concatArrayBuffer(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(new Uint8Array(e),0),s.set(new Uint8Array(t),e.byteLength),s.buffer}getFileData(e){return i(this,void 0,void 0,(function*(){if(e instanceof ArrayBuffer)return e;if(e instanceof a)return e.toArrayBuffer();throw new Error("Cannot decrypt/encrypt file. In browsers file encrypt/decrypt supported for string, ArrayBuffer or Blob")}))}}N.LEGACY_IDENTIFIER="";class P{static from(e,t){if(e!==P.LEGACY_IDENTIFIER)return new M(e,t.byteLength)}static tryParse(e){const t=new Uint8Array(e);let s,n,r=null;if(t.byteLength>=4&&(s=t.slice(0,4),this.decoder.decode(s)!==P.SENTINEL))return N.LEGACY_IDENTIFIER;if(!(t.byteLength>=5))throw new Error("Decryption error: invalid header version");if(r=t[4],r>P.MAX_VERSION)throw new Error("Decryption error: Unknown cryptor error");let i=5+P.IDENTIFIER_LENGTH;if(!(t.byteLength>=i))throw new Error("Decryption error: invalid crypto identifier");n=t.slice(5,i);let o=null;if(!(t.byteLength>=i+1))throw new Error("Decryption error: invalid metadata length");return o=t[i],i+=1,255===o&&t.byteLength>=i+2&&(o=new Uint16Array(t.slice(i,i+2)).reduce(((e,t)=>(e<<8)+t),0)),new M(this.decoder.decode(n),o)}}P.SENTINEL="PNED",P.LEGACY_IDENTIFIER="",P.IDENTIFIER_LENGTH=4,P.VERSION=1,P.MAX_VERSION=1,P.decoder=new TextDecoder;class M{constructor(e,t){this._identifier=e,this._metadataLength=t}get identifier(){return this._identifier}set identifier(e){this._identifier=e}get metadataLength(){return this._metadataLength}set metadataLength(e){this._metadataLength=e}get version(){return P.VERSION}get length(){return P.SENTINEL.length+1+P.IDENTIFIER_LENGTH+(this.metadataLength<255?1:3)+this.metadataLength}get data(){let e=0;const t=new Uint8Array(this.length),s=new TextEncoder;t.set(s.encode(P.SENTINEL)),e+=P.SENTINEL.length,t[e]=this.version,e++,this.identifier&&t.set(s.encode(this.identifier),e);const n=this.metadataLength;return e+=P.IDENTIFIER_LENGTH,n<255?t[e]=n:t.set([255,n>>8,255&n],e),t}}M.IDENTIFIER_LENGTH=4,M.SENTINEL="PNED";class A extends Error{static create(e,t){return e instanceof Error?A.createFromError(e):A.createFromServiceResponse(e,t)}static createFromError(e){let t=h.PNUnknownCategory,s="Unknown error",n="Error";if(!e)return new A(s,t,0);if(e instanceof A)return e;if(e instanceof Error&&(s=e.message,n=e.name),"AbortError"===n||-1!==s.indexOf("Aborted"))t=h.PNCancelledCategory,s="Request cancelled";else if(-1!==s.indexOf("timeout"))t=h.PNTimeoutCategory,s="Request timeout";else if(-1!==s.indexOf("network"))t=h.PNNetworkIssuesCategory,s="Network issues";else if("TypeError"===n)t=-1!==s.indexOf("Load failed")||-1!=s.indexOf("Failed to fetch")?h.PNTimeoutCategory:h.PNBadRequestCategory;else if("FetchError"===n){const n=e.code;["ECONNREFUSED","ENETUNREACH","ENOTFOUND","ECONNRESET","EAI_AGAIN"].includes(n)&&(t=h.PNNetworkIssuesCategory),"ECONNREFUSED"===n?s="Connection refused":"ENETUNREACH"===n?s="Network not reachable":"ENOTFOUND"===n?s="Server not found":"ECONNRESET"===n?s="Connection reset by peer":"EAI_AGAIN"===n?s="Name resolution error":"ETIMEDOUT"===n?(t=h.PNTimeoutCategory,s="Request timeout"):s=`Unknown system error: ${e}`}else"Request timeout"===s&&(t=h.PNTimeoutCategory);return new A(s,t,0,e)}static createFromServiceResponse(e,t){let s,n=h.PNUnknownCategory,r="Unknown error",{status:i}=e;if(null!=t||(t=e.body),402===i?r="Not available for used key set. Contact support@pubnub.com":400===i?(n=h.PNBadRequestCategory,r="Bad request"):403===i&&(n=h.PNAccessDeniedCategory,r="Access denied"),t&&t.byteLength>0){const n=(new TextDecoder).decode(t);if(-1!==e.headers["content-type"].indexOf("text/javascript")||-1!==e.headers["content-type"].indexOf("application/json"))try{const e=JSON.parse(n);"object"!=typeof e||Array.isArray(e)||("error"in e&&(1===e.error||!0===e.error)&&"status"in e&&"number"==typeof e.status&&"message"in e&&"service"in e?(s=e,i=e.status):s=e,"error"in e&&e.error instanceof Error&&(s=e.error))}catch(e){s=n}else if(-1!==e.headers["content-type"].indexOf("xml")){const e=/(.*)<\/Message>/gi.exec(n);r=e?`Upload to bucket failed: ${e[1]}`:"Upload to bucket failed."}else s=n}return new A(r,n,i,s)}constructor(e,t,s,n){super(e),this.category=t,this.statusCode=s,this.errorData=n,this.name="PubNubAPIError"}toStatus(e){return{error:!0,category:this.category,operation:e,statusCode:this.statusCode,errorData:this.errorData}}toPubNubError(e,t){return new d(null!=t?t:this.message,this.toStatus(e))}}class _{constructor(e){this.configuration=e,this.subscriptionWorkerReady=!1,this.workerEventsQueue=[],this.callbacks=new Map,this.setupSubscriptionWorker()}makeSendable(e){if(!e.path.startsWith("/v2/subscribe")&&!e.path.endsWith("/leave"))return this.configuration.transport.makeSendable(e);let t;const s={type:"send-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,logVerbosity:this.configuration.logVerbosity,request:e};return e.cancellable&&(t={abort:()=>{const t={type:"cancel-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,logVerbosity:this.configuration.logVerbosity,identifier:e.identifier};this.scheduleEventPost(t)}}),[new Promise(((t,n)=>{this.callbacks.set(e.identifier,{resolve:t,reject:n}),this.scheduleEventPost(s)})),t]}request(e){return e}scheduleEventPost(e,t=!1){const s=this.sharedSubscriptionWorker;s?s.port.postMessage(e):t?this.workerEventsQueue.splice(0,0,e):this.workerEventsQueue.push(e)}flushScheduledEvents(){const e=this.sharedSubscriptionWorker;if(!e||0===this.workerEventsQueue.length)return;const t=[];for(let e=0;e!t.includes(e))),this.workerEventsQueue.forEach((t=>e.port.postMessage(t))),this.workerEventsQueue=[]}get sharedSubscriptionWorker(){return this.subscriptionWorkerReady?this.subscriptionWorker:null}setupSubscriptionWorker(){"undefined"!=typeof SharedWorker&&(this.subscriptionWorker=new SharedWorker(this.configuration.workerUrl,`/pubnub-${this.configuration.sdkVersion}`),this.subscriptionWorker.port.start(),this.scheduleEventPost({type:"client-register",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,userId:this.configuration.userId,logVerbosity:this.configuration.logVerbosity,workerLogVerbosity:this.configuration.workerLogVerbosity},!0),this.subscriptionWorker.port.onmessage=e=>this.handleWorkerEvent(e))}handleWorkerEvent(e){const{data:t}=e;if("shared-worker-ping"===t.type||"shared-worker-connected"===t.type||"shared-worker-console-log"===t.type||"shared-worker-console-dir"===t.type||t.clientIdentifier===this.configuration.clientIdentifier)if("shared-worker-connected"===t.type)this.subscriptionWorkerReady=!0,this.flushScheduledEvents();else if("shared-worker-console-log"===t.type)console.log(`[SharedWorker] ${t.message}`);else if("shared-worker-console-dir"===t.type)t.message&&console.log(`[SharedWorker] ${t.message}`),console.dir(t.data);else if("shared-worker-ping"===t.type){const{logVerbosity:e,subscriptionKey:t,clientIdentifier:s}=this.configuration;this.scheduleEventPost({type:"client-pong",subscriptionKey:t,clientIdentifier:s,logVerbosity:e})}else if("request-progress-start"===t.type||"request-progress-end"===t.type)this.logRequestProgress(t);else if("request-process-success"===t.type||"request-process-error"===t.type){const{resolve:e,reject:s}=this.callbacks.get(t.identifier);if("request-process-success"===t.type)e({status:t.response.status,url:t.url,headers:t.response.headers,body:t.response.body});else{let e=h.PNUnknownCategory,n="Unknown error";if(t.error)"NETWORK_ISSUE"===t.error.type?e=h.PNNetworkIssuesCategory:"TIMEOUT"===t.error.type?e=h.PNTimeoutCategory:"ABORTED"===t.error.type&&(e=h.PNCancelledCategory),n=`${t.error.message} (${t.identifier})`;else if(t.response)return s(A.create({url:t.url,headers:t.response.headers,body:t.response.body,status:t.response.status},t.response.body));s(new A(n,e,0,new Error(n)))}}}logRequestProgress(e){var t,s;"request-progress-start"===e.type?(console.log("<<<<<"),console.log(`[${e.timestamp}] ${e.url}\n${JSON.stringify(null!==(t=e.query)&&void 0!==t?t:{})}`),console.log("-----")):(console.log(">>>>>>"),console.log(`[${e.timestamp} / ${e.duration}] ${e.url}\n${JSON.stringify(null!==(s=e.query)&&void 0!==s?s:{})}\n${e.response}`),console.log("-----"))}}const j=e=>encodeURIComponent(e).replace(/[!~*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)),I=(e,t)=>{const s=e.map((e=>j(e)));return s.length?s.join(","):null!=t?t:""},R=(e,t)=>{const s=Object.fromEntries(t.map((e=>[e,!1])));return e.filter((e=>!(t.includes(e)&&!s[e])||(s[e]=!0,!1)))},U=(e,t)=>[...e].filter((s=>t.includes(s)&&e.indexOf(s)===e.lastIndexOf(s)&&t.indexOf(s)===t.lastIndexOf(s)));class T{constructor(e=!1,t){this.keepAlive=e,this.logVerbosity=t}makeSendable(e){let t,s;return e.cancellable&&(s=new AbortController,t={abortController:s,abort:()=>null==s?void 0:s.abort()}),[this.requestFromTransportRequest(e).then((t=>{const n=(new Date).getTime();this.logRequestProcessProgress(t);const r=new Promise(((t,s)=>{const n=setTimeout((()=>{clearTimeout(n),s(new Error("Request timeout"))}),1e3*e.timeout)}));return Promise.race([fetch(t,{signal:null==s?void 0:s.signal,credentials:"omit",cache:"no-cache"}),r]).then((e=>e.arrayBuffer().then((t=>[e,t])))).then((e=>{const s=e[1].byteLength>0?e[1]:void 0,{status:r,headers:i}=e[0],o={};i.forEach(((e,t)=>o[t]=e.toLowerCase()));const a={status:r,url:t.url,headers:o,body:s};if(r>=400)throw A.create(a);return this.logRequestProcessProgress(t,(new Date).getTime()-n,s),a})).catch((e=>{throw A.create(e)}))})),t]}request(e){return e}requestFromTransportRequest(e){return i(this,void 0,void 0,(function*(){let t,s=e.path;if(e.formData&&e.formData.length>0){e.queryParameters={};const s=e.body,n=new FormData;for(const{key:t,value:s}of e.formData)n.append(t,s);try{const e=yield s.toArrayBuffer();n.append("file",new Blob([e],{type:"application/octet-stream"}),s.name)}catch(e){try{const e=yield s.toFileUri();n.append("file",e,s.name)}catch(e){}}t=n}else e.body&&("string"==typeof e.body||e.body instanceof ArrayBuffer)&&(t=e.body);var n;return e.queryParameters&&0!==Object.keys(e.queryParameters).length&&(s=`${s}?${n=e.queryParameters,Object.keys(n).map((e=>{const t=n[e];return Array.isArray(t)?t.map((t=>`${e}=${j(t)}`)).join("&"):`${e}=${j(t)}`})).join("&")}`),new Request(`${e.origin}${s}`,{method:e.method,headers:e.headers,redirect:"follow",body:t})}))}logRequestProcessProgress(e,t,s){if(!this.logVerbosity)return;const{protocol:n,host:r,pathname:i,search:o}=new URL(e.url),a=(new Date).toISOString();if(t){const e=s?T.decoder.decode(s):void 0;console.log(">>>>>>"),console.log(`[${a} / ${t}]`,`\n${n}//${r}${i}`,`\n${o}`,`\n${e}`),console.log("-----")}else console.log("<<<<<"),console.log(`[${a}]`,`\n${n}//${r}${i}`,`\n${o}`),console.log("-----")}}function F(e){const t=e=>"object"==typeof e&&null!==e&&e.constructor===Object,s=e=>"number"==typeof e&&isFinite(e);if(!t(e))return e;const n={};return Object.keys(e).forEach((r=>{const i=(e=>"string"==typeof e||e instanceof String)(r);let o=r;const a=e[r];if(i&&r.indexOf(",")>=0){o=r.split(",").map(Number).reduce(((e,t)=>e+String.fromCharCode(t)),"")}else(s(r)||i&&!isNaN(Number(r)))&&(o=String.fromCharCode(s(r)?r:parseInt(r,10)));n[o]=t(a)?F(a):a})),n}T.decoder=new TextDecoder;const x=e=>{var t,s,n;return e.subscriptionWorkerUrl&&"undefined"==typeof SharedWorker&&(e.subscriptionWorkerUrl=null),Object.assign(Object.assign({},(e=>{var t,s,n,r,i,o,a,c,u,l,h,p,g,y;const f=Object.assign({},e);if(null!==(t=f.logVerbosity)&&void 0!==t||(f.logVerbosity=!1),null!==(s=f.ssl)&&void 0!==s||(f.ssl=!0),null!==(n=f.transactionalRequestTimeout)&&void 0!==n||(f.transactionalRequestTimeout=15),null!==(r=f.subscribeRequestTimeout)&&void 0!==r||(f.subscribeRequestTimeout=310),null!==(i=f.restore)&&void 0!==i||(f.restore=!1),null!==(o=f.useInstanceId)&&void 0!==o||(f.useInstanceId=!1),null!==(a=f.suppressLeaveEvents)&&void 0!==a||(f.suppressLeaveEvents=!1),null!==(c=f.requestMessageCountThreshold)&&void 0!==c||(f.requestMessageCountThreshold=100),null!==(u=f.autoNetworkDetection)&&void 0!==u||(f.autoNetworkDetection=!1),null!==(l=f.enableEventEngine)&&void 0!==l||(f.enableEventEngine=!1),null!==(h=f.maintainPresenceState)&&void 0!==h||(f.maintainPresenceState=!0),null!==(p=f.keepAlive)&&void 0!==p||(f.keepAlive=!1),f.userId&&f.uuid)throw new d("PubNub client configuration error: use only 'userId'");if(null!==(g=f.userId)&&void 0!==g||(f.userId=f.uuid),!f.userId)throw new d("PubNub client configuration error: 'userId' not set");if(0===(null===(y=f.userId)||void 0===y?void 0:y.trim().length))throw new d("PubNub client configuration error: 'userId' is empty");f.origin||(f.origin=Array.from({length:20},((e,t)=>`ps${t+1}.pndsn.com`)));const m={subscribeKey:f.subscribeKey,publishKey:f.publishKey,secretKey:f.secretKey};void 0!==f.presenceTimeout&&f.presenceTimeout<20&&(f.presenceTimeout=20,console.log("WARNING: Presence timeout is less than the minimum. Using minimum value: ",20)),void 0!==f.presenceTimeout?f.heartbeatInterval=f.presenceTimeout/2-1:f.presenceTimeout=300;let b=!1,v=!0,w=5,S=!1,k=100,E=!0;return void 0!==f.dedupeOnSubscribe&&"boolean"==typeof f.dedupeOnSubscribe&&(S=f.dedupeOnSubscribe),void 0!==f.maximumCacheSize&&"number"==typeof f.maximumCacheSize&&(k=f.maximumCacheSize),void 0!==f.useRequestId&&"boolean"==typeof f.useRequestId&&(E=f.useRequestId),void 0!==f.announceSuccessfulHeartbeats&&"boolean"==typeof f.announceSuccessfulHeartbeats&&(b=f.announceSuccessfulHeartbeats),void 0!==f.announceFailedHeartbeats&&"boolean"==typeof f.announceFailedHeartbeats&&(v=f.announceFailedHeartbeats),void 0!==f.fileUploadPublishRetryLimit&&"number"==typeof f.fileUploadPublishRetryLimit&&(w=f.fileUploadPublishRetryLimit),Object.assign(Object.assign({},f),{keySet:m,dedupeOnSubscribe:S,maximumCacheSize:k,useRequestId:E,announceSuccessfulHeartbeats:b,announceFailedHeartbeats:v,fileUploadPublishRetryLimit:w})})(e)),{listenToBrowserNetworkEvents:null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t,subscriptionWorkerUrl:e.subscriptionWorkerUrl,subscriptionWorkerLogVerbosity:null!==(s=e.subscriptionWorkerLogVerbosity)&&void 0!==s&&s,keepAlive:null===(n=e.keepAlive)||void 0===n||n})};var D={exports:{}}; +/*! lil-uuid - v0.1 - MIT License - https://github.com/lil-js/uuid */!function(e,t){!function(e){var t="0.1.0",s={3:/^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,4:/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,5:/^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,all:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i};function n(){var e,t,s="";for(e=0;e<32;e++)t=16*Math.random()|0,8!==e&&12!==e&&16!==e&&20!==e||(s+="-"),s+=(12===e?4:16===e?3&t|8:t).toString(16);return s}function r(e,t){var n=s[t||"all"];return n&&n.test(e)||!1}n.isUUID=r,n.VERSION=t,e.uuid=n,e.isUUID=r}(t),null!==e&&(e.exports=t.uuid)}(D,D.exports);var q=t(D.exports),G={createUUID:()=>q.uuid?q.uuid():q()};const K=(e,t)=>{var s,n,r;null===(s=e.retryConfiguration)||void 0===s||s.validate(),null!==(n=e.useRandomIVs)&&void 0!==n||(e.useRandomIVs=true),e.origin=$(null!==(r=e.ssl)&&void 0!==r&&r,e.origin);const i=e.cryptoModule;i&&delete e.cryptoModule;const o=Object.assign(Object.assign({},e),{_pnsdkSuffix:{},_instanceId:`pn-${G.createUUID()}`,_cryptoModule:void 0,_cipherKey:void 0,_setupCryptoModule:t,get instanceId(){if(this.useInstanceId)return this._instanceId},getUserId(){return this.userId},setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this.userId=e},getAuthKey(){return this.authKey},setAuthKey(e){this.authKey=e},getFilterExpression(){return this.filterExpression},setFilterExpression(e){this.filterExpression=e},getCipherKey(){return this._cipherKey},setCipherKey(t){this._cipherKey=t,t||!this._cryptoModule?t&&this._setupCryptoModule&&(this._cryptoModule=this._setupCryptoModule({cipherKey:t,useRandomIVs:e.useRandomIVs,customEncrypt:this.getCustomEncrypt(),customDecrypt:this.getCustomDecrypt()})):this._cryptoModule=void 0},getCryptoModule(){return this._cryptoModule},getUseRandomIVs:()=>e.useRandomIVs,setPresenceTimeout(e){this.heartbeatInterval=e/2-1,this.presenceTimeout=e},getPresenceTimeout(){return this.presenceTimeout},getHeartbeatInterval(){return this.heartbeatInterval},setHeartbeatInterval(e){this.heartbeatInterval=e},getTransactionTimeout(){return this.transactionalRequestTimeout},getSubscribeTimeout(){return this.subscribeRequestTimeout},get PubNubFile(){return e.PubNubFile},get version(){return"8.2.8"},getVersion(){return this.version},_addPnsdkSuffix(e,t){this._pnsdkSuffix[e]=`${t}`},_getPnsdkSuffix(e){const t=Object.values(this._pnsdkSuffix).join(e);return t.length>0?e+t:""},getUUID(){return this.getUserId()},setUUID(e){this.setUserId(e)},getCustomEncrypt:()=>e.customEncrypt,getCustomDecrypt:()=>e.customDecrypt});return e.cipherKey?o.setCipherKey(e.cipherKey):i&&(o._cryptoModule=i),o},$=(e,t)=>{const s=e?"https://":"http://";return"string"==typeof t?`${s}${t}`:`${s}${t[Math.floor(Math.random()*t.length)]}`};class L{constructor(e){this.cbor=e}setToken(e){e&&e.length>0?this.token=e:this.token=void 0}getToken(){return this.token}parseToken(e){const t=this.cbor.decodeToken(e);if(void 0!==t){const e=t.res.uuid?Object.keys(t.res.uuid):[],s=Object.keys(t.res.chan),n=Object.keys(t.res.grp),r=t.pat.uuid?Object.keys(t.pat.uuid):[],i=Object.keys(t.pat.chan),o=Object.keys(t.pat.grp),a={version:t.v,timestamp:t.t,ttl:t.ttl,authorized_uuid:t.uuid,signature:t.sig},c=e.length>0,u=s.length>0,l=n.length>0;if(c||u||l){if(a.resources={},c){const s=a.resources.uuids={};e.forEach((e=>s[e]=this.extractPermissions(t.res.uuid[e])))}if(u){const e=a.resources.channels={};s.forEach((s=>e[s]=this.extractPermissions(t.res.chan[s])))}if(l){const e=a.resources.groups={};n.forEach((s=>e[s]=this.extractPermissions(t.res.grp[s])))}}const h=r.length>0,d=i.length>0,p=o.length>0;if(h||d||p){if(a.patterns={},h){const e=a.patterns.uuids={};r.forEach((s=>e[s]=this.extractPermissions(t.pat.uuid[s])))}if(d){const e=a.patterns.channels={};i.forEach((s=>e[s]=this.extractPermissions(t.pat.chan[s])))}if(p){const e=a.patterns.groups={};o.forEach((s=>e[s]=this.extractPermissions(t.pat.grp[s])))}}return t.meta&&Object.keys(t.meta).length>0&&(a.meta=t.meta),a}}extractPermissions(e){const t={read:!1,write:!1,manage:!1,delete:!1,get:!1,update:!1,join:!1};return 128&~e||(t.join=!0),64&~e||(t.update=!0),32&~e||(t.get=!0),8&~e||(t.delete=!0),4&~e||(t.manage=!0),2&~e||(t.write=!0),1&~e||(t.read=!0),t}}var B,H;!function(e){e.GET="GET",e.POST="POST",e.PATCH="PATCH",e.DELETE="DELETE",e.LOCAL="LOCAL"}(B||(B={}));class z{constructor(e,t,s){this.publishKey=e,this.secretKey=t,this.hasher=s}signature(e){const t=e.path.startsWith("/publish")?B.GET:e.method;let s=`${t}\n${this.publishKey}\n${e.path}\n${this.queryParameters(e.queryParameters)}\n`;if(t===B.POST||t===B.PATCH){const t=e.body;let n;t&&t instanceof ArrayBuffer?n=z.textDecoder.decode(t):t&&"object"!=typeof t&&(n=t),n&&(s+=n)}return`v2.${this.hasher(s,this.secretKey)}`.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}queryParameters(e){return Object.keys(e).sort().map((t=>{const s=e[t];return Array.isArray(s)?s.sort().map((e=>`${t}=${j(e)}`)).join("&"):`${t}=${j(s)}`})).join("&")}}z.textDecoder=new TextDecoder("utf-8");class V{constructor(e){this.configuration=e;const{clientConfiguration:{keySet:t},shaHMAC:s}=e;t.secretKey&&s&&(this.signatureGenerator=new z(t.publishKey,t.secretKey,s))}makeSendable(e){return this.configuration.transport.makeSendable(this.request(e))}request(e){var t;const{clientConfiguration:s}=this.configuration;return(e=this.configuration.transport.request(e)).queryParameters||(e.queryParameters={}),s.useInstanceId&&(e.queryParameters.instanceid=s.instanceId),e.queryParameters.uuid||(e.queryParameters.uuid=s.userId),s.useRequestId&&(e.queryParameters.requestid=e.identifier),e.queryParameters.pnsdk=this.generatePNSDK(),null!==(t=e.origin)&&void 0!==t||(e.origin=s.origin),this.authenticateRequest(e),this.signRequest(e),e}authenticateRequest(e){var t;if(e.path.startsWith("/v2/auth/")||e.path.startsWith("/v3/pam/")||e.path.startsWith("/time"))return;const{clientConfiguration:s,tokenManager:n}=this.configuration,r=null!==(t=n&&n.getToken())&&void 0!==t?t:s.authKey;r&&(e.queryParameters.auth=r)}signRequest(e){this.signatureGenerator&&!e.path.startsWith("/time")&&(e.queryParameters.timestamp=String(Math.floor((new Date).getTime()/1e3)),e.queryParameters.signature=this.signatureGenerator.signature(e))}generatePNSDK(){const{clientConfiguration:e}=this.configuration;if(e.sdkName)return e.sdkName;let t=`PubNub-JS-${e.sdkFamily}`;e.partnerId&&(t+=`-${e.partnerId}`),t+=`/${e.getVersion()}`;const s=e._getPnsdkSuffix(" ");return s.length>0&&(t+=s),t}}class W{constructor(){this.listeners=[]}addListener(e){this.listeners.includes(e)||this.listeners.push(e)}removeListener(e){this.listeners=this.listeners.filter((t=>t!==e))}removeAllListeners(){this.listeners=[]}announceStatus(e){this.listeners.forEach((t=>{t.status&&t.status(e)}))}announcePresence(e){this.listeners.forEach((t=>{t.presence&&t.presence(e)}))}announceMessage(e){this.listeners.forEach((t=>{t.message&&t.message(e)}))}announceSignal(e){this.listeners.forEach((t=>{t.signal&&t.signal(e)}))}announceMessageAction(e){this.listeners.forEach((t=>{t.messageAction&&t.messageAction(e)}))}announceFile(e){this.listeners.forEach((t=>{t.file&&t.file(e)}))}announceObjects(e){this.listeners.forEach((t=>{t.objects&&t.objects(e)}))}announceNetworkUp(){this.listeners.forEach((e=>{e.status&&e.status({category:h.PNNetworkUpCategory})}))}announceNetworkDown(){this.listeners.forEach((e=>{e.status&&e.status({category:h.PNNetworkDownCategory})}))}announceUser(e){this.listeners.forEach((t=>{t.user&&t.user(e)}))}announceSpace(e){this.listeners.forEach((t=>{t.space&&t.space(e)}))}announceMembership(e){this.listeners.forEach((t=>{t.membership&&t.membership(e)}))}}class J{constructor(e){this.time=e}onReconnect(e){this.callback=e}startPolling(){this.timeTimer=setInterval((()=>this.callTime()),3e3)}stopPolling(){this.timeTimer&&clearInterval(this.timeTimer),this.timeTimer=null}callTime(){this.time((e=>{e.error||(this.stopPolling(),this.callback&&this.callback())}))}}class Q{constructor({maximumCacheSize:e}){this.maximumCacheSize=e,this.hashHistory=[]}getKey(e){var t;return`${e.timetoken}-${this.hashCode(JSON.stringify(null!==(t=e.message)&&void 0!==t?t:"")).toString()}`}isDuplicate(e){return this.hashHistory.includes(this.getKey(e))}addEntry(e){this.hashHistory.length>=this.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))}clearHistory(){this.hashHistory=[]}hashCode(e){let t=0;if(0===e.length)return t;for(let s=0;s{this.pendingChannelSubscriptions.add(e),this.channels[e]={},r&&(this.presenceChannels[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannels[e]={})})),null==s||s.forEach((e=>{this.pendingChannelGroupSubscriptions.add(e),this.channelGroups[e]={},r&&(this.presenceChannelGroups[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannelGroups[e]={})})),this.subscriptionStatusAnnounced=!1,this.reconnect()}unsubscribe(e,t){let{channels:s,channelGroups:n}=e;const i=new Set,o=new Set;null==s||s.forEach((e=>{e in this.channels&&(delete this.channels[e],o.add(e),e in this.heartbeatChannels&&delete this.heartbeatChannels[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannels&&(delete this.presenceChannels[e],o.add(e))})),null==n||n.forEach((e=>{e in this.channelGroups&&(delete this.channelGroups[e],i.add(e),e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannelGroups&&(delete this.presenceChannelGroups[e],i.add(e))})),0===o.size&&0===i.size||(!1!==this.configuration.suppressLeaveEvents||t||(n=Array.from(i),s=Array.from(o),this.leaveCall({channels:s,channelGroups:n},(e=>{const{error:t}=e,i=r(e,["error"]);let o;t&&(e.errorData&&"object"==typeof e.errorData&&"message"in e.errorData&&"string"==typeof e.errorData.message?o=e.errorData.message:"message"in e&&"string"==typeof e.message&&(o=e.message)),this.listenerManager.announceStatus(Object.assign(Object.assign({},i),{error:null!=o&&o,affectedChannels:s,affectedChannelGroups:n,currentTimetoken:this.currentTimetoken,lastTimetoken:this.lastTimetoken}))}))),0===Object.keys(this.channels).length&&0===Object.keys(this.presenceChannels).length&&0===Object.keys(this.channelGroups).length&&0===Object.keys(this.presenceChannelGroups).length&&(this.lastTimetoken=0,this.currentTimetoken=0,this.storedTimetoken=null,this.region=null,this.reconnectionManager.stopPolling()),this.reconnect())}unsubscribeAll(e){this.unsubscribe({channels:this.subscribedChannels,channelGroups:this.subscribedChannelGroups},e)}startSubscribeLoop(){this.stopSubscribeLoop();const e=[...Object.keys(this.channelGroups)],t=[...Object.keys(this.channels)];Object.keys(this.presenceChannelGroups).forEach((t=>e.push(`${t}-pnpres`))),Object.keys(this.presenceChannels).forEach((e=>t.push(`${e}-pnpres`))),0===t.length&&0===e.length||this.subscribeCall({channels:t,channelGroups:e,state:this.presenceState,heartbeat:this.configuration.getPresenceTimeout(),timetoken:this.currentTimetoken,region:null!==this.region?this.region:void 0,filterExpression:this.configuration.filterExpression},((e,t)=>{this.processSubscribeResponse(e,t)}))}stopSubscribeLoop(){this._subscribeAbort&&(this._subscribeAbort(),this._subscribeAbort=null)}processSubscribeResponse(e,t){if(e.error){if("object"==typeof e.errorData&&"name"in e.errorData&&"AbortError"===e.errorData.name||e.category===h.PNCancelledCategory)return;return void(e.category===h.PNTimeoutCategory?this.startSubscribeLoop():e.category===h.PNNetworkIssuesCategory?(this.disconnect(),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.listenerManager.announceNetworkDown()),this.reconnectionManager.onReconnect((()=>{this.configuration.autoNetworkDetection&&!this.isOnline&&(this.isOnline=!0,this.listenerManager.announceNetworkUp()),this.reconnect(),this.subscriptionStatusAnnounced=!0;const t={category:h.PNReconnectedCategory,operation:e.operation,lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.listenerManager.announceStatus(t)})),this.reconnectionManager.startPolling(),this.listenerManager.announceStatus(e)):e.category===h.PNBadRequestCategory?(this.stopHeartbeatTimer(),this.listenerManager.announceStatus(e)):this.listenerManager.announceStatus(e))}if(this.storedTimetoken?(this.currentTimetoken=this.storedTimetoken,this.storedTimetoken=null):(this.lastTimetoken=this.currentTimetoken,this.currentTimetoken=t.cursor.timetoken),!this.subscriptionStatusAnnounced){const t={category:h.PNConnectedCategory,operation:e.operation,affectedChannels:Array.from(this.pendingChannelSubscriptions),subscribedChannels:this.subscribedChannels,affectedChannelGroups:Array.from(this.pendingChannelGroupSubscriptions),lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.subscriptionStatusAnnounced=!0,this.listenerManager.announceStatus(t),this.pendingChannelGroupSubscriptions.clear(),this.pendingChannelSubscriptions.clear()}const{messages:s}=t,{requestMessageCountThreshold:n,dedupeOnSubscribe:r}=this.configuration;n&&s.length>=n&&this.listenerManager.announceStatus({category:h.PNRequestMessageCountExceededCategory,operation:e.operation});try{s.forEach((e=>{if(r&&"message"in e.data&&"timetoken"in e.data){if(this.dedupingManager.isDuplicate(e.data))return;this.dedupingManager.addEntry(e.data)}this.eventEmitter.emitEvent(e)}))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}this.region=t.cursor.region,this.startSubscribeLoop()}setState(e){const{state:t,channels:s,channelGroups:n}=e;null==s||s.forEach((e=>e in this.channels&&(this.presenceState[e]=t))),null==n||n.forEach((e=>e in this.channelGroups&&(this.presenceState[e]=t)))}changePresence(e){const{connected:t,channels:s,channelGroups:n}=e;t?(null==s||s.forEach((e=>this.heartbeatChannels[e]={})),null==n||n.forEach((e=>this.heartbeatChannelGroups[e]={}))):(null==s||s.forEach((e=>{e in this.heartbeatChannels&&delete this.heartbeatChannels[e]})),null==n||n.forEach((e=>{e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]})),!1===this.configuration.suppressLeaveEvents&&this.leaveCall({channels:s,channelGroups:n},(e=>this.listenerManager.announceStatus(e)))),this.reconnect()}startHeartbeatTimer(){this.stopHeartbeatTimer();const e=this.configuration.getHeartbeatInterval();e&&0!==e&&(this.sendHeartbeat(),this.heartbeatTimer=setInterval((()=>this.sendHeartbeat()),1e3*e))}stopHeartbeatTimer(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}sendHeartbeat(){const e=Object.keys(this.heartbeatChannelGroups),t=Object.keys(this.heartbeatChannels);0===t.length&&0===e.length||this.heartbeatCall({channels:t,channelGroups:e,heartbeat:this.configuration.getPresenceTimeout(),state:this.presenceState},(e=>{e.error&&this.configuration.announceFailedHeartbeats&&this.listenerManager.announceStatus(e),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.disconnect(),this.listenerManager.announceNetworkDown(),this.reconnect()),!e.error&&this.configuration.announceSuccessfulHeartbeats&&this.listenerManager.announceStatus(e)}))}}class X{constructor(e,t,s){this._payload=e,this.setDefaultPayloadStructure(),this.title=t,this.body=s}get payload(){return this._payload}set title(e){this._title=e}set subtitle(e){this._subtitle=e}set body(e){this._body=e}set badge(e){this._badge=e}set sound(e){this._sound=e}setDefaultPayloadStructure(){}toObject(){return{}}}class Z extends X{constructor(){super(...arguments),this._apnsPushType="apns",this._isSilent=!1}get payload(){return this._payload}set configurations(e){e&&e.length&&(this._configurations=e)}get notification(){return this.payload.aps}get title(){return this._title}set title(e){e&&e.length&&(this.payload.aps.alert.title=e,this._title=e)}get subtitle(){return this._subtitle}set subtitle(e){e&&e.length&&(this.payload.aps.alert.subtitle=e,this._subtitle=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.aps.alert.body=e,this._body=e)}get badge(){return this._badge}set badge(e){null!=e&&(this.payload.aps.badge=e,this._badge=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.aps.sound=e,this._sound=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.aps={alert:{}}}toObject(){const e=Object.assign({},this.payload),{aps:t}=e;let{alert:s}=t;if(this._isSilent&&(t["content-available"]=1),"apns2"===this._apnsPushType){if(!this._configurations||!this._configurations.length)throw new ReferenceError("APNS2 configuration is missing");const t=[];this._configurations.forEach((e=>{t.push(this.objectFromAPNS2Configuration(e))})),t.length&&(e.pn_push=t)}return s&&Object.keys(s).length||delete t.alert,this._isSilent&&(delete t.alert,delete t.badge,delete t.sound,s={}),this._isSilent||s&&Object.keys(s).length?e:null}objectFromAPNS2Configuration(e){if(!e.targets||!e.targets.length)throw new ReferenceError("At least one APNS2 target should be provided");const{collapseId:t,expirationDate:s}=e,n={auth_method:"token",targets:e.targets.map((e=>this.objectFromAPNSTarget(e))),version:"v2"};return t&&t.length&&(n.collapse_id=t),s&&(n.expiration=s.toISOString()),n}objectFromAPNSTarget(e){if(!e.topic||!e.topic.length)throw new TypeError("Target 'topic' undefined.");const{topic:t,environment:s="development",excludedDevices:n=[]}=e,r={topic:t,environment:s};return n.length&&(r.excluded_devices=n),r}}class ee extends X{get payload(){return this._payload}get notification(){return this.payload.notification}get data(){return this.payload.data}get title(){return this._title}set title(e){e&&e.length&&(this.payload.notification.title=e,this._title=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.notification.body=e,this._body=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.notification.sound=e,this._sound=e)}get icon(){return this._icon}set icon(e){e&&e.length&&(this.payload.notification.icon=e,this._icon=e)}get tag(){return this._tag}set tag(e){e&&e.length&&(this.payload.notification.tag=e,this._tag=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.notification={},this.payload.data={}}toObject(){let e=Object.assign({},this.payload.data),t=null;const s={};if(Object.keys(this.payload).length>2){const t=r(this.payload,["notification","data"]);e=Object.assign(Object.assign({},e),t)}return this._isSilent?e.notification=this.payload.notification:t=this.payload.notification,Object.keys(e).length&&(s.data=e),t&&Object.keys(t).length&&(s.notification=t),Object.keys(s).length?s:null}}class te{constructor(e,t){this._payload={apns:{},fcm:{}},this._title=e,this._body=t,this.apns=new Z(this._payload.apns,e,t),this.fcm=new ee(this._payload.fcm,e,t)}set debugging(e){this._debugging=e}get title(){return this._title}get subtitle(){return this._subtitle}set subtitle(e){this._subtitle=e,this.apns.subtitle=e,this.fcm.subtitle=e}get body(){return this._body}get badge(){return this._badge}set badge(e){this._badge=e,this.apns.badge=e,this.fcm.badge=e}get sound(){return this._sound}set sound(e){this._sound=e,this.apns.sound=e,this.fcm.sound=e}buildPayload(e){const t={};if(e.includes("apns")||e.includes("apns2")){this.apns._apnsPushType=e.includes("apns")?"apns":"apns2";const s=this.apns.toObject();s&&Object.keys(s).length&&(t.pn_apns=s)}if(e.includes("fcm")){const e=this.fcm.toObject();e&&Object.keys(e).length&&(t.pn_gcm=e)}return Object.keys(t).length&&this._debugging&&(t.pn_debug=!0),t}}class se{constructor(e){this.params=e,this.requestIdentifier=G.createUUID(),this._cancellationController=null}get cancellationController(){return this._cancellationController}set cancellationController(e){this._cancellationController=e}abort(){this&&this.cancellationController&&this.cancellationController.abort()}operation(){throw Error("Should be implemented by subclass.")}validate(){}parse(e){return i(this,void 0,void 0,(function*(){throw Error("Should be implemented by subclass.")}))}request(){var e,t,s,n;const r={method:null!==(t=null===(e=this.params)||void 0===e?void 0:e.method)&&void 0!==t?t:B.GET,path:this.path,queryParameters:this.queryParameters,cancellable:null!==(n=null===(s=this.params)||void 0===s?void 0:s.cancellable)&&void 0!==n&&n,timeout:1e4,identifier:this.requestIdentifier},i=this.headers;if(i&&(r.headers=i),r.method===B.POST||r.method===B.PATCH){const[e,t]=[this.body,this.formData];t&&(r.formData=t),e&&(r.body=e)}return r}get headers(){}get path(){throw Error("`path` getter should be implemented by subclass.")}get queryParameters(){return{}}get formData(){}get body(){}deserializeResponse(e){const t=e.headers["content-type"];if(!t||-1===t.indexOf("javascript")&&-1===t.indexOf("json"))return;const s=se.decoder.decode(e.body);try{return JSON.parse(s)}catch(e){return void console.error("Error parsing JSON response:",e)}}}se.decoder=new TextDecoder,function(e){e.PNPublishOperation="PNPublishOperation",e.PNSignalOperation="PNSignalOperation",e.PNSubscribeOperation="PNSubscribeOperation",e.PNUnsubscribeOperation="PNUnsubscribeOperation",e.PNWhereNowOperation="PNWhereNowOperation",e.PNHereNowOperation="PNHereNowOperation",e.PNGlobalHereNowOperation="PNGlobalHereNowOperation",e.PNSetStateOperation="PNSetStateOperation",e.PNGetStateOperation="PNGetStateOperation",e.PNHeartbeatOperation="PNHeartbeatOperation",e.PNAddMessageActionOperation="PNAddActionOperation",e.PNRemoveMessageActionOperation="PNRemoveMessageActionOperation",e.PNGetMessageActionsOperation="PNGetMessageActionsOperation",e.PNTimeOperation="PNTimeOperation",e.PNHistoryOperation="PNHistoryOperation",e.PNDeleteMessagesOperation="PNDeleteMessagesOperation",e.PNFetchMessagesOperation="PNFetchMessagesOperation",e.PNMessageCounts="PNMessageCountsOperation",e.PNGetAllUUIDMetadataOperation="PNGetAllUUIDMetadataOperation",e.PNGetUUIDMetadataOperation="PNGetUUIDMetadataOperation",e.PNSetUUIDMetadataOperation="PNSetUUIDMetadataOperation",e.PNRemoveUUIDMetadataOperation="PNRemoveUUIDMetadataOperation",e.PNGetAllChannelMetadataOperation="PNGetAllChannelMetadataOperation",e.PNGetChannelMetadataOperation="PNGetChannelMetadataOperation",e.PNSetChannelMetadataOperation="PNSetChannelMetadataOperation",e.PNRemoveChannelMetadataOperation="PNRemoveChannelMetadataOperation",e.PNGetMembersOperation="PNGetMembersOperation",e.PNSetMembersOperation="PNSetMembersOperation",e.PNGetMembershipsOperation="PNGetMembershipsOperation",e.PNSetMembershipsOperation="PNSetMembershipsOperation",e.PNListFilesOperation="PNListFilesOperation",e.PNGenerateUploadUrlOperation="PNGenerateUploadUrlOperation",e.PNPublishFileOperation="PNPublishFileOperation",e.PNPublishFileMessageOperation="PNPublishFileMessageOperation",e.PNGetFileUrlOperation="PNGetFileUrlOperation",e.PNDownloadFileOperation="PNDownloadFileOperation",e.PNDeleteFileOperation="PNDeleteFileOperation",e.PNAddPushNotificationEnabledChannelsOperation="PNAddPushNotificationEnabledChannelsOperation",e.PNRemovePushNotificationEnabledChannelsOperation="PNRemovePushNotificationEnabledChannelsOperation",e.PNPushNotificationEnabledChannelsOperation="PNPushNotificationEnabledChannelsOperation",e.PNRemoveAllPushNotificationsOperation="PNRemoveAllPushNotificationsOperation",e.PNChannelGroupsOperation="PNChannelGroupsOperation",e.PNRemoveGroupOperation="PNRemoveGroupOperation",e.PNChannelsForGroupOperation="PNChannelsForGroupOperation",e.PNAddChannelsToGroupOperation="PNAddChannelsToGroupOperation",e.PNRemoveChannelsFromGroupOperation="PNRemoveChannelsFromGroupOperation",e.PNAccessManagerGrant="PNAccessManagerGrant",e.PNAccessManagerGrantToken="PNAccessManagerGrantToken",e.PNAccessManagerAudit="PNAccessManagerAudit",e.PNAccessManagerRevokeToken="PNAccessManagerRevokeToken",e.PNHandshakeOperation="PNHandshakeOperation",e.PNReceiveMessagesOperation="PNReceiveMessagesOperation"}(H||(H={}));var ne=H;var re;!function(e){e[e.Presence=-2]="Presence",e[e.Message=-1]="Message",e[e.Signal=1]="Signal",e[e.AppContext=2]="AppContext",e[e.MessageAction=3]="MessageAction",e[e.Files=4]="Files"}(re||(re={}));class ie extends se{constructor(e){var t,s,n,r,i,o;super({cancellable:!0}),this.parameters=e,null!==(t=(r=this.parameters).withPresence)&&void 0!==t||(r.withPresence=false),null!==(s=(i=this.parameters).channelGroups)&&void 0!==s||(i.channelGroups=[]),null!==(n=(o=this.parameters).channels)&&void 0!==n||(o.channels=[])}operation(){return ne.PNSubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;return e?t||s?void 0:"`channels` and `channelGroups` both should not be empty":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){let t;try{const s=se.decoder.decode(e.body);t=JSON.parse(s)}catch(e){console.error("Error parsing JSON response:",e)}if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));const s=t.m.filter((e=>{const t=void 0===e.b?e.c:e.b;return this.parameters.channels&&this.parameters.channels.includes(t)||this.parameters.channelGroups&&this.parameters.channelGroups.includes(t)})).map((e=>{let{e:t}=e;return null!=t||(t=e.c.endsWith("-pnpres")?re.Presence:re.Message),t!=re.Signal&&"string"==typeof e.d?t==re.Message?{type:re.Message,data:this.messageFromEnvelope(e)}:{type:re.Files,data:this.fileFromEnvelope(e)}:t==re.Message?{type:re.Message,data:this.messageFromEnvelope(e)}:t===re.Presence?{type:re.Presence,data:this.presenceEventFromEnvelope(e)}:t==re.Signal?{type:re.Signal,data:this.signalFromEnvelope(e)}:t===re.AppContext?{type:re.AppContext,data:this.appContextFromEnvelope(e)}:t===re.MessageAction?{type:re.MessageAction,data:this.messageActionFromEnvelope(e)}:{type:re.Files,data:this.fileFromEnvelope(e)}}));return{cursor:{timetoken:t.t.t,region:t.t.r},messages:s}}))}get headers(){return{accept:"text/javascript"}}presenceEventFromEnvelope(e){const{d:t}=e,[s,n]=this.subscriptionChannelFromEnvelope(e),r=s.replace("-pnpres",""),i=null!==n?r:null,o=null!==n?n:r;return"string"!=typeof t&&"data"in t&&(t.state=t.data,delete t.data),Object.assign({channel:r,subscription:n,actualChannel:i,subscribedChannel:o,timetoken:e.p.t},t)}messageFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,r]=this.decryptedData(e.d),i={channel:t,subscription:s,actualChannel:null!==s?t:null,subscribedChannel:null!==s?s:t,timetoken:e.p.t,publisher:e.i,message:n};return e.u&&(i.userMetadata=e.u),r&&(i.error=r),i}signalFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,message:e.d};return e.u&&(n.userMetadata=e.u),n}messageActionFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,event:n.event,data:Object.assign(Object.assign({},n.data),{uuid:e.i})}}appContextFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,message:n}}fileFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,r]=this.decryptedData(e.d);let i=r;const o={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i};return e.u&&(o.userMetadata=e.u),n?"string"==typeof n?null!=i||(i="Unexpected file information payload data type."):(o.message=n.message,n.file&&(o.file={id:n.file.id,name:n.file.name,url:this.parameters.getFileUrl({id:n.file.id,name:n.file.name,channel:t})})):null!=i||(i="File information payload is missing."),i&&(o.error=i),o}subscriptionChannelFromEnvelope(e){return[e.c,void 0===e.b?e.c:e.b]}decryptedData(e){if(!this.parameters.crypto||"string"!=typeof e)return[e,void 0];let t,s;try{const s=this.parameters.crypto.decrypt(e);t=s instanceof ArrayBuffer?JSON.parse(oe.decoder.decode(s)):s}catch(e){t=null,s=`Error while decrypting message content: ${e.message}`}return[null!=t?t:e,s]}}class oe extends ie{get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/subscribe/${t}/${I(null!==(e=null==s?void 0:s.sort())&&void 0!==e?e:[],",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,heartbeat:s,state:n,timetoken:r,region:i}=this.parameters,o={};return e&&e.length>0&&(o["channel-group"]=e.sort().join(",")),t&&t.length>0&&(o["filter-expr"]=t),s&&(o.heartbeat=s),n&&Object.keys(n).length>0&&(o.state=JSON.stringify(n)),void 0!==r&&"string"==typeof r?r.length>0&&"0"!==r&&(o.tt=r):void 0!==r&&r>0&&(o.tt=r),i&&(o.tr=i),o}}class ae{constructor(e){this.listenerManager=e,this.channelListenerMap=new Map,this.groupListenerMap=new Map}emitEvent(e){if(e.type===re.Message)this.listenerManager.announceMessage(e.data),this.announce("message",e.data,e.data.channel,e.data.subscription);else if(e.type===re.Signal)this.listenerManager.announceSignal(e.data),this.announce("signal",e.data,e.data.channel,e.data.subscription);else if(e.type===re.Presence)this.listenerManager.announcePresence(e.data),this.announce("presence",e.data,e.data.channel,e.data.subscription);else if(e.type===re.AppContext){const{data:t}=e,{message:s}=t;if(this.listenerManager.announceObjects(t),this.announce("objects",t,t.channel,t.subscription),"uuid"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:o,type:a}=s,c=r(s,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===o?"updated":"removed",type:"user"})});this.listenerManager.announceUser(u),this.announce("user",u,u.spaceId,u.subscription)}else if("channel"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:o,type:a}=s,c=r(s,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===o?"updated":"removed",type:"space"})});this.listenerManager.announceSpace(u),this.announce("space",u,u.spaceId,u.subscription)}else if("membership"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:o,data:a}=s,c=r(s,["event","data"]),{uuid:u,channel:l}=a,h=r(a,["uuid","channel"]),d=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===o?"updated":"removed",data:Object.assign(Object.assign({},h),{user:u,space:l})})});this.listenerManager.announceMembership(d),this.announce("membership",d,d.spaceId,d.subscription)}}else e.type===re.MessageAction?(this.listenerManager.announceMessageAction(e.data),this.announce("messageAction",e.data,e.data.channel,e.data.subscription)):e.type===re.Files&&(this.listenerManager.announceFile(e.data),this.announce("file",e.data,e.data.channel,e.data.subscription))}addListener(e,t,s){t&&s?(null==t||t.forEach((t=>{if(this.channelListenerMap.has(t)){const s=this.channelListenerMap.get(t);s.includes(e)||s.push(e)}else this.channelListenerMap.set(t,[e])})),null==s||s.forEach((t=>{if(this.groupListenerMap.has(t)){const s=this.groupListenerMap.get(t);s.includes(e)||s.push(e)}else this.groupListenerMap.set(t,[e])}))):this.listenerManager.addListener(e)}removeListener(e,t,s){t&&s?(null==t||t.forEach((t=>{this.channelListenerMap.has(t)&&this.channelListenerMap.set(t,this.channelListenerMap.get(t).filter((t=>t!==e)))})),null==s||s.forEach((t=>{this.groupListenerMap.has(t)&&this.groupListenerMap.set(t,this.groupListenerMap.get(t).filter((t=>t!==e)))}))):this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners(),this.channelListenerMap.clear(),this.groupListenerMap.clear()}announce(e,t,s,n){t&&this.channelListenerMap.has(s)&&this.channelListenerMap.get(s).forEach((s=>{const n=s[e];n&&n(t)})),n&&this.groupListenerMap.has(n)&&this.groupListenerMap.get(n).forEach((s=>{const n=s[e];n&&n(t)}))}}class ce{constructor(e=!1){this.sync=e,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){const t=()=>{this.listeners.forEach((t=>{t(e)}))};this.sync?t():setTimeout(t,0)}}class ue{transition(e,t){var s;if(this.transitionMap.has(t.type))return null===(s=this.transitionMap.get(t.type))||void 0===s?void 0:s(e,t)}constructor(e){this.label=e,this.transitionMap=new Map,this.enterEffects=[],this.exitEffects=[]}on(e,t){return this.transitionMap.set(e,t),this}with(e,t){return[this,e,null!=t?t:[]]}onEnter(e){return this.enterEffects.push(e),this}onExit(e){return this.exitEffects.push(e),this}}class le extends ce{describe(e){return new ue(e)}start(e,t){this.currentState=e,this.currentContext=t,this.notify({type:"engineStarted",state:e,context:t})}transition(e){if(!this.currentState)throw new Error("Start the engine first");this.notify({type:"eventReceived",event:e});const t=this.currentState.transition(this.currentContext,e);if(t){const[s,n,r]=t;for(const e of this.currentState.exitEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)});const i=this.currentState;this.currentState=s;const o=this.currentContext;this.currentContext=n,this.notify({type:"transitionDone",fromState:i,fromContext:o,toState:s,toContext:n,event:e});for(const e of r)this.notify({type:"invocationDispatched",invocation:e});for(const e of this.currentState.enterEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)})}}}class he{constructor(e){this.dependencies=e,this.instances=new Map,this.handlers=new Map}on(e,t){this.handlers.set(e,t)}dispatch(e){if("CANCEL"===e.type){if(this.instances.has(e.payload)){const t=this.instances.get(e.payload);null==t||t.cancel(),this.instances.delete(e.payload)}return}const t=this.handlers.get(e.type);if(!t)throw new Error(`Unhandled invocation '${e.type}'`);const s=t(e.payload,this.dependencies);e.managed&&this.instances.set(e.type,s),s.start()}dispose(){for(const[e,t]of this.instances.entries())t.cancel(),this.instances.delete(e)}}function de(e,t){const s=function(...s){return{type:e,payload:null==t?void 0:t(...s)}};return s.type=e,s}function pe(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!1});return s.type=e,s}function ge(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!0});return s.type=e,s.cancel={type:"CANCEL",payload:e,managed:!1},s}class ye extends Error{constructor(){super("The operation was aborted."),this.name="AbortError",Object.setPrototypeOf(this,new.target.prototype)}}class fe extends ce{constructor(){super(...arguments),this._aborted=!1}get aborted(){return this._aborted}throwIfAborted(){if(this._aborted)throw new ye}abort(){this._aborted=!0,this.notify(new ye)}}class me{constructor(e,t){this.payload=e,this.dependencies=t}}class be extends me{constructor(e,t,s){super(e,t),this.asyncFunction=s,this.abortSignal=new fe}start(){this.asyncFunction(this.payload,this.abortSignal,this.dependencies).catch((e=>{}))}cancel(){this.abortSignal.abort()}}const ve=e=>(t,s)=>new be(t,s,e),we=de("RECONNECT",(()=>({}))),Se=de("DISCONNECT",(()=>({}))),ke=de("JOINED",((e,t)=>({channels:e,groups:t}))),Ee=de("LEFT",((e,t)=>({channels:e,groups:t}))),Oe=de("LEFT_ALL",(()=>({}))),Ce=de("HEARTBEAT_SUCCESS",(e=>({statusCode:e}))),Ne=de("HEARTBEAT_FAILURE",(e=>e)),Pe=de("HEARTBEAT_GIVEUP",(()=>({}))),Me=de("TIMES_UP",(()=>({}))),Ae=pe("HEARTBEAT",((e,t)=>({channels:e,groups:t}))),_e=pe("LEAVE",((e,t)=>({channels:e,groups:t}))),je=pe("EMIT_STATUS",(e=>e)),Ie=ge("WAIT",(()=>({}))),Re=ge("DELAYED_HEARTBEAT",(e=>e));class Ue extends he{constructor(e,t){super(t),this.on(Ae.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeat:n,presenceState:r,config:i}){try{yield n(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},i.maintainPresenceState&&{state:r}),{heartbeat:i.presenceTimeout}));e.transition(Ce(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Ne(t))}}}))))),this.on(_e.type,ve(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{leave:s,config:n}){if(!n.suppressLeaveEvents)try{s({channels:e.channels,channelGroups:e.groups})}catch(e){}}))))),this.on(Ie.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeatDelay:n}){return s.throwIfAborted(),yield n(),s.throwIfAborted(),e.transition(Me())}))))),this.on(Re.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeat:n,retryDelay:r,presenceState:i,config:o}){if(!o.retryConfiguration||!o.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(Pe());s.throwIfAborted(),yield r(o.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{yield n(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},o.maintainPresenceState&&{state:i}),{heartbeat:o.presenceTimeout}));return e.transition(Ce(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Ne(t))}}}))))),this.on(je.type,ve(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s,config:n}){var r;n.announceFailedHeartbeats&&!0===(null===(r=null==e?void 0:e.status)||void 0===r?void 0:r.error)?s(e.status):n.announceSuccessfulHeartbeats&&200===e.statusCode&&s(Object.assign(Object.assign({},e),{operation:ne.PNHeartbeatOperation,error:!1}))})))))}}const Te=new ue("HEARTBEAT_STOPPED");Te.on(ke.type,((e,t)=>Te.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Te.on(Ee.type,((e,t)=>Te.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))}))),Te.on(we.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),Te.on(Oe.type,((e,t)=>Ge.with(void 0)));const Fe=new ue("HEARTBEAT_COOLDOWN");Fe.onEnter((()=>Ie())),Fe.onExit((()=>Ie.cancel)),Fe.on(Me.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),Fe.on(ke.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Fe.on(Ee.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[_e(t.payload.channels,t.payload.groups)]))),Fe.on(Se.type,(e=>Te.with({channels:e.channels,groups:e.groups},[_e(e.channels,e.groups)]))),Fe.on(Oe.type,((e,t)=>Ge.with(void 0,[_e(e.channels,e.groups)])));const xe=new ue("HEARTBEAT_FAILED");xe.on(ke.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),xe.on(Ee.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[_e(t.payload.channels,t.payload.groups)]))),xe.on(we.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),xe.on(Se.type,((e,t)=>Te.with({channels:e.channels,groups:e.groups},[_e(e.channels,e.groups)]))),xe.on(Oe.type,((e,t)=>Ge.with(void 0,[_e(e.channels,e.groups)])));const De=new ue("HEARBEAT_RECONNECTING");De.onEnter((e=>Re(e))),De.onExit((()=>Re.cancel)),De.on(ke.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),De.on(Ee.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[_e(t.payload.channels,t.payload.groups)]))),De.on(Se.type,((e,t)=>{Te.with({channels:e.channels,groups:e.groups},[_e(e.channels,e.groups)])})),De.on(Ce.type,((e,t)=>Fe.with({channels:e.channels,groups:e.groups}))),De.on(Ne.type,((e,t)=>De.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),De.on(Pe.type,((e,t)=>xe.with({channels:e.channels,groups:e.groups}))),De.on(Oe.type,((e,t)=>Ge.with(void 0,[_e(e.channels,e.groups)])));const qe=new ue("HEARTBEATING");qe.onEnter((e=>Ae(e.channels,e.groups))),qe.on(Ce.type,((e,t)=>Fe.with({channels:e.channels,groups:e.groups}))),qe.on(ke.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),qe.on(Ee.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[_e(t.payload.channels,t.payload.groups)]))),qe.on(Ne.type,((e,t)=>De.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),qe.on(Se.type,(e=>Te.with({channels:e.channels,groups:e.groups},[_e(e.channels,e.groups)]))),qe.on(Oe.type,((e,t)=>Ge.with(void 0,[_e(e.channels,e.groups)])));const Ge=new ue("HEARTBEAT_INACTIVE");Ge.on(ke.type,((e,t)=>qe.with({channels:t.payload.channels,groups:t.payload.groups})));class Ke{get _engine(){return this.engine}constructor(e){this.dependencies=e,this.engine=new le,this.channels=[],this.groups=[],this.dispatcher=new Ue(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(Ge,void 0)}join({channels:e,groups:t}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],this.engine.transition(ke(this.channels.slice(0),this.groups.slice(0)))}leave({channels:e,groups:t}){this.dependencies.presenceState&&(null==e||e.forEach((e=>delete this.dependencies.presenceState[e])),null==t||t.forEach((e=>delete this.dependencies.presenceState[e]))),this.engine.transition(Ee(null!=e?e:[],null!=t?t:[]))}leaveAll(){this.engine.transition(Oe())}dispose(){this._unsubscribeEngine(),this.dispatcher.dispose()}}class $e{static LinearRetryPolicy(e){return{delay:e.delay,maximumRetry:e.maximumRetry,shouldRetry(e,t){var s;return 403!==(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)&&this.maximumRetry>t},getDelay(e,t){var s;return 1e3*((null!==(s=t.retryAfter)&&void 0!==s?s:this.delay)+Math.random())},getGiveupReason(e,t){var s;return this.maximumRetry<=t?"retry attempts exhaused.":403===(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)?"forbidden operation.":"unknown error"},validate(){if(this.maximumRetry>10)throw new Error("Maximum retry for linear retry policy can not be more than 10")}}}static ExponentialRetryPolicy(e){return{minimumDelay:e.minimumDelay,maximumDelay:e.maximumDelay,maximumRetry:e.maximumRetry,shouldRetry(e,t){var s;return 403!==(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)&&this.maximumRetry>t},getDelay(e,t){var s;return 1e3*((null!==(s=t.retryAfter)&&void 0!==s?s:Math.min(Math.pow(2,e),this.maximumDelay))+Math.random())},getGiveupReason(e,t){var s;return this.maximumRetry<=t?"retry attempts exhausted.":403===(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)?"forbidden operation.":"unknown error"},validate(){if(this.minimumDelay<2)throw new Error("Minimum delay can not be set less than 2 seconds for retry");if(this.maximumDelay)throw new Error("Maximum delay can not be set more than 150 seconds for retry");if(this.maximumRetry>6)throw new Error("Maximum retry for exponential retry policy can not be more than 6")}}}}const Le=ge("HANDSHAKE",((e,t)=>({channels:e,groups:t}))),Be=ge("RECEIVE_MESSAGES",((e,t,s)=>({channels:e,groups:t,cursor:s}))),He=pe("EMIT_MESSAGES",(e=>e)),ze=pe("EMIT_STATUS",(e=>e)),Ve=ge("RECEIVE_RECONNECT",(e=>e)),We=ge("HANDSHAKE_RECONNECT",(e=>e)),Je=de("SUBSCRIPTION_CHANGED",((e,t)=>({channels:e,groups:t}))),Qe=de("SUBSCRIPTION_RESTORED",((e,t,s,n)=>({channels:e,groups:t,cursor:{timetoken:s,region:null!=n?n:0}}))),Ye=de("HANDSHAKE_SUCCESS",(e=>e)),Xe=de("HANDSHAKE_FAILURE",(e=>e)),Ze=de("HANDSHAKE_RECONNECT_SUCCESS",(e=>({cursor:e}))),et=de("HANDSHAKE_RECONNECT_FAILURE",(e=>e)),tt=de("HANDSHAKE_RECONNECT_GIVEUP",(e=>e)),st=de("RECEIVE_SUCCESS",((e,t)=>({cursor:e,events:t}))),nt=de("RECEIVE_FAILURE",(e=>e)),rt=de("RECEIVE_RECONNECT_SUCCESS",((e,t)=>({cursor:e,events:t}))),it=de("RECEIVE_RECONNECT_FAILURE",(e=>e)),ot=de("RECEIVING_RECONNECT_GIVEUP",(e=>e)),at=de("DISCONNECT",(()=>({}))),ct=de("RECONNECT",((e,t)=>({cursor:{timetoken:null!=e?e:"",region:null!=t?t:0}}))),ut=de("UNSUBSCRIBE_ALL",(()=>({})));class lt extends he{constructor(e,t){super(t),this.on(Le.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{handshake:n,presenceState:r,config:i}){s.throwIfAborted();try{const o=yield n(Object.assign({abortSignal:s,channels:t.channels,channelGroups:t.groups,filterExpression:i.filterExpression},i.maintainPresenceState&&{state:r}));return e.transition(Ye(o))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Xe(t))}}}))))),this.on(Be.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{receiveMessages:n,config:r}){s.throwIfAborted();try{const i=yield n({abortSignal:s,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:r.filterExpression});e.transition(st(i.cursor,i.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;if(!s.aborted)return e.transition(nt(t))}}}))))),this.on(He.type,ve(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitMessages:s}){e.length>0&&s(e)}))))),this.on(ze.type,ve(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s}){s(e)}))))),this.on(Ve.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{receiveMessages:n,delay:r,config:i}){if(!i.retryConfiguration||!i.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(ot(new d(i.retryConfiguration?i.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe messages receive.")));s.throwIfAborted(),yield r(i.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{const r=yield n({abortSignal:s,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:i.filterExpression});return e.transition(rt(r.cursor,r.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(it(t))}}}))))),this.on(We.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{handshake:n,delay:r,presenceState:i,config:o}){if(!o.retryConfiguration||!o.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(tt(new d(o.retryConfiguration?o.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe handshake")));s.throwIfAborted(),yield r(o.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{const r=yield n(Object.assign({abortSignal:s,channels:t.channels,channelGroups:t.groups,filterExpression:o.filterExpression},o.maintainPresenceState&&{state:i}));return e.transition(Ze(r))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(et(t))}}})))))}}const ht=new ue("HANDSHAKE_FAILED");ht.on(Je.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),ht.on(ct.type,((e,t)=>bt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor||e.cursor}))),ht.on(Qe.type,((e,t)=>{var s,n;return bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region?t.payload.cursor.region:null!==(n=null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)&&void 0!==n?n:0}})})),ht.on(ut.type,(e=>vt.with()));const dt=new ue("HANDSHAKE_STOPPED");dt.on(Je.type,((e,t)=>dt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),dt.on(ct.type,((e,t)=>bt.with(Object.assign(Object.assign({},e),{cursor:t.payload.cursor||e.cursor})))),dt.on(Qe.type,((e,t)=>{var s;return dt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)||0}})})),dt.on(ut.type,(e=>vt.with()));const pt=new ue("RECEIVE_FAILED");pt.on(ct.type,((e,t)=>{var s;return bt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.payload.cursor.timetoken?null===(s=t.payload.cursor)||void 0===s?void 0:s.timetoken:e.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),pt.on(Je.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),pt.on(Qe.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),pt.on(ut.type,(e=>vt.with(void 0)));const gt=new ue("RECEIVE_STOPPED");gt.on(Je.type,((e,t)=>gt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),gt.on(Qe.type,((e,t)=>gt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),gt.on(ct.type,((e,t)=>{var s;return bt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.payload.cursor.timetoken?null===(s=t.payload.cursor)||void 0===s?void 0:s.timetoken:e.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),gt.on(ut.type,(()=>vt.with(void 0)));const yt=new ue("RECEIVE_RECONNECTING");yt.onEnter((e=>Ve(e))),yt.onExit((()=>Ve.cancel)),yt.on(rt.type,((e,t)=>ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[He(t.payload.events)]))),yt.on(it.type,((e,t)=>yt.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),yt.on(ot.type,((e,t)=>{var s;return pt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[ze({category:h.PNDisconnectedUnexpectedlyCategory,error:null===(s=t.payload)||void 0===s?void 0:s.message})])})),yt.on(at.type,(e=>gt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[ze({category:h.PNDisconnectedCategory})]))),yt.on(Qe.type,((e,t)=>ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),yt.on(Je.type,((e,t)=>ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),yt.on(ut.type,(e=>vt.with(void 0,[ze({category:h.PNDisconnectedCategory})])));const ft=new ue("RECEIVING");ft.onEnter((e=>Be(e.channels,e.groups,e.cursor))),ft.onExit((()=>Be.cancel)),ft.on(st.type,((e,t)=>ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[He(t.payload.events)]))),ft.on(Je.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?vt.with(void 0):ft.with({cursor:e.cursor,channels:t.payload.channels,groups:t.payload.groups}))),ft.on(Qe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?vt.with(void 0):ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),ft.on(nt.type,((e,t)=>yt.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),ft.on(at.type,(e=>gt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[ze({category:h.PNDisconnectedCategory})]))),ft.on(ut.type,(e=>vt.with(void 0,[ze({category:h.PNDisconnectedCategory})])));const mt=new ue("HANDSHAKE_RECONNECTING");mt.onEnter((e=>We(e))),mt.onExit((()=>We.cancel)),mt.on(Ze.type,((e,t)=>{var s,n;const r={timetoken:(null===(s=e.cursor)||void 0===s?void 0:s.timetoken)?null===(n=e.cursor)||void 0===n?void 0:n.timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region};return ft.with({channels:e.channels,groups:e.groups,cursor:r},[ze({category:h.PNConnectedCategory})])})),mt.on(et.type,((e,t)=>mt.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),mt.on(tt.type,((e,t)=>{var s;return ht.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[ze({category:h.PNConnectionErrorCategory,error:null===(s=t.payload)||void 0===s?void 0:s.message})])})),mt.on(at.type,(e=>dt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),mt.on(Je.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),mt.on(Qe.type,((e,t)=>{var s,n;return bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:(null===(s=t.payload.cursor)||void 0===s?void 0:s.region)||(null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.region)||0}})})),mt.on(ut.type,(e=>vt.with(void 0)));const bt=new ue("HANDSHAKING");bt.onEnter((e=>Le(e.channels,e.groups))),bt.onExit((()=>Le.cancel)),bt.on(Je.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?vt.with(void 0):bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),bt.on(Ye.type,((e,t)=>{var s,n;return ft.with({channels:e.channels,groups:e.groups,cursor:{timetoken:(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.timetoken)?null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.timetoken:t.payload.timetoken,region:t.payload.region}},[ze({category:h.PNConnectedCategory})])})),bt.on(Xe.type,((e,t)=>mt.with({channels:e.channels,groups:e.groups,cursor:e.cursor,attempts:0,reason:t.payload}))),bt.on(at.type,(e=>dt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),bt.on(Qe.type,((e,t)=>{var s;return bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)||0}})})),bt.on(ut.type,(e=>vt.with()));const vt=new ue("UNSUBSCRIBED");vt.on(Je.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups}))),vt.on(Qe.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:t.payload.cursor})));class wt{get _engine(){return this.engine}constructor(e){this.engine=new le,this.channels=[],this.groups=[],this.dependencies=e,this.dispatcher=new lt(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(vt,void 0)}subscribe({channels:e,channelGroups:t,timetoken:s,withPresence:n}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],n&&(this.channels.map((e=>this.channels.push(`${e}-pnpres`))),this.groups.map((e=>this.groups.push(`${e}-pnpres`)))),s?this.engine.transition(Qe(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])),s)):this.engine.transition(Je(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])))),this.dependencies.join&&this.dependencies.join({channels:Array.from(new Set(this.channels.filter((e=>!e.endsWith("-pnpres"))))),groups:Array.from(new Set(this.groups.filter((e=>!e.endsWith("-pnpres")))))})}unsubscribe({channels:e=[],channelGroups:t=[]}){const s=R(this.channels,[...e,...e.map((e=>`${e}-pnpres`))]),n=R(this.groups,[...t,...t.map((e=>`${e}-pnpres`))]);if(new Set(this.channels).size!==new Set(s).size||new Set(this.groups).size!==new Set(n).size){const r=U(this.channels,e),i=U(this.groups,t);this.dependencies.presenceState&&(null==r||r.forEach((e=>delete this.dependencies.presenceState[e])),null==i||i.forEach((e=>delete this.dependencies.presenceState[e]))),this.channels=s,this.groups=n,this.engine.transition(Je(Array.from(new Set(this.channels.slice(0))),Array.from(new Set(this.groups.slice(0))))),this.dependencies.leave&&this.dependencies.leave({channels:r.slice(0),groups:i.slice(0)})}}unsubscribeAll(){this.channels=[],this.groups=[],this.dependencies.presenceState&&Object.keys(this.dependencies.presenceState).forEach((e=>{delete this.dependencies.presenceState[e]})),this.engine.transition(Je(this.channels.slice(0),this.groups.slice(0))),this.dependencies.leaveAll&&this.dependencies.leaveAll()}reconnect({timetoken:e,region:t}){this.engine.transition(ct(e,t))}disconnect(){this.engine.transition(at()),this.dependencies.leaveAll&&this.dependencies.leaveAll()}getSubscribedChannels(){return Array.from(new Set(this.channels.slice(0)))}getSubscribedChannelGroups(){return Array.from(new Set(this.groups.slice(0)))}dispose(){this.disconnect(),this._unsubscribeEngine(),this.dispatcher.dispose()}}class St extends se{constructor(e){var t,s;super({method:e.sendByPost?B.POST:B.GET}),this.parameters=e,null!==(t=(s=this.parameters).sendByPost)&&void 0!==t||(s.sendByPost=false)}operation(){return ne.PNPublishOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[2]}}))}get path(){const{message:e,channel:t,keySet:s}=this.parameters,n=this.prepareMessagePayload(e);return`/publish/${s.publishKey}/${s.subscribeKey}/0/${j(t)}/0${this.parameters.sendByPost?"":`/${j(n)}`}`}get queryParameters(){const{meta:e,replicate:t,storeInHistory:s,ttl:n}=this.parameters,r={};return void 0!==s&&(r.store=s?"1":"0"),void 0!==n&&(r.ttl=n),void 0===t||t||(r.norep="true"),e&&"object"==typeof e&&(r.meta=JSON.stringify(e)),r}get headers(){return{"Content-Type":"application/json"}}get body(){return this.prepareMessagePayload(this.parameters.message)}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof s?s:u(s))}}class kt extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNSignalOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[2]}}))}get path(){const{keySet:{publishKey:e,subscribeKey:t},channel:s,message:n}=this.parameters,r=JSON.stringify(n);return`/signal/${e}/${t}/0/${j(s)}/0/${j(r)}`}}class Et extends ie{operation(){return ne.PNReceiveMessagesOperation}validate(){const e=super.validate();return e||(this.parameters.timetoken?this.parameters.region?void 0:"region can not be empty":"timetoken can not be empty")}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${I(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,timetoken:s,region:n}=this.parameters,r={ee:""};return e&&e.length>0&&(r["channel-group"]=e.sort().join(",")),t&&t.length>0&&(r["filter-expr"]=t),"string"==typeof s?s&&s.length>0&&(r.tt=s):s&&s>0&&(r.tt=s),n&&(r.tr=n),r}}class Ot extends ie{operation(){return ne.PNHandshakeOperation}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${I(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,state:s}=this.parameters,n={tt:0,ee:""};return e&&e.length>0&&(n["channel-group"]=e.sort().join(",")),t&&t.length>0&&(n["filter-expr"]=t),s&&Object.keys(s).length>0&&(n.state=JSON.stringify(s)),n}}class Ct extends se{constructor(e){var t,s,n,r;super(),this.parameters=e,null!==(t=(n=this.parameters).channels)&&void 0!==t||(n.channels=[]),null!==(s=(r=this.parameters).channelGroups)&&void 0!==s||(r.channelGroups=[])}operation(){return ne.PNGetStateOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;if(!e)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);const{channels:s=[],channelGroups:n=[]}=this.parameters,r={channels:{}};return 1===s.length&&0===n.length?r.channels[s[0]]=t.payload:r.channels=t.payload,r}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${I(null!=s?s:[],",")}/uuid/${t}`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.join(",")}:{}}}class Nt extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNSetStateOperation}validate(){const{keySet:{subscribeKey:e},state:t,channels:s=[],channelGroups:n=[]}=this.parameters;return e?t?0===(null==s?void 0:s.length)&&0===(null==n?void 0:n.length)?"Please provide a list of channels and/or channel-groups":void 0:"Missing State":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return{state:t.payload}}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${I(null!=s?s:[],",")}/uuid/${j(t)}/data`}get queryParameters(){const{channelGroups:e,state:t}=this.parameters,s={state:JSON.stringify(t)};return e&&0!==e.length&&(s["channel-group"]=e.join(",")),s}}class Pt extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNHeartbeatOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?0===t.length&&0===s.length?"Please provide a list of channels and/or channel-groups":void 0:"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channels:t}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${I(null!=t?t:[],",")}/heartbeat`}get queryParameters(){const{channelGroups:e,state:t,heartbeat:s}=this.parameters,n={heartbeat:`${s}`};return e&&0!==e.length&&(n["channel-group"]=e.join(",")),t&&(n.state=JSON.stringify(t)),n}}class Mt extends se{constructor(e){super(),this.parameters=e,this.parameters.channelGroups&&(this.parameters.channelGroups=Array.from(new Set(this.parameters.channelGroups))),this.parameters.channels&&(this.parameters.channels=Array.from(new Set(this.parameters.channels)))}operation(){return ne.PNUnsubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?0===t.length&&0===s.length?"At least one `channel` or `channel group` should be provided.":void 0:"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return{}}))}get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/presence/sub-key/${t}/channel/${I(null!==(e=null==s?void 0:s.sort())&&void 0!==e?e:[],",")}/leave`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.sort().join(",")}:{}}}class At extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNWhereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t.payload?{channels:t.payload.channels}:{channels:[]}}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/presence/sub-key/${e}/uuid/${j(t)}`}}class _t extends se{constructor(e){var t,s,n,r,i,o;super(),this.parameters=e,null!==(t=(r=this.parameters).queryParameters)&&void 0!==t||(r.queryParameters={}),null!==(s=(i=this.parameters).includeUUIDs)&&void 0!==s||(i.includeUUIDs=true),null!==(n=(o=this.parameters).includeState)&&void 0!==n||(o.includeState=false)}operation(){const{channels:e=[],channelGroups:t=[]}=this.parameters;return 0===e.length&&0===t.length?ne.PNGlobalHereNowOperation:ne.PNHereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t,s;const n=this.deserializeResponse(e);if(!n)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(n.status>=400)throw A.create(e);const r="occupancy"in n?1:n.payload.total_channels,i="occupancy"in n?n.occupancy:n.payload.total_channels,o={};let a={};if("occupancy"in n){const e=this.parameters.channels[0];a[e]={uuids:null!==(t=n.uuids)&&void 0!==t?t:[],occupancy:i}}else a=null!==(s=n.payload.channels)&&void 0!==s?s:{};return Object.keys(a).forEach((e=>{const t=a[e];o[e]={occupants:this.parameters.includeUUIDs?t.uuids.map((e=>"string"==typeof e?{uuid:e,state:null}:e)):[],name:e,occupancy:t.occupancy}})),{totalChannels:r,totalOccupancy:i,channels:o}}))}get path(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;let n=`/v2/presence/sub-key/${e}`;return(t&&t.length>0||s&&s.length>0)&&(n+=`/channel/${I(null!=t?t:[],",")}`),n}get queryParameters(){const{channelGroups:e,includeUUIDs:t,includeState:s,queryParameters:n}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign({},t?{}:{disable_uuids:"1"}),null!=s&&s?{state:"1"}:{}),e&&e.length>0?{"channel-group":e.join(",")}:{}),n)}}class jt extends se{constructor(e){super({method:B.DELETE}),this.parameters=e}operation(){return ne.PNDeleteMessagesOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v3/history/sub-key/${e}/channel/${j(t)}`}get queryParameters(){const{start:e,end:t}=this.parameters;return Object.assign(Object.assign({},e?{start:e}:{}),t?{end:t}:{})}}class It extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNMessageCounts}validate(){const{keySet:{subscribeKey:e},channels:t,timetoken:s,channelTimetokens:n}=this.parameters;return e?t?s&&n?"`timetoken` and `channelTimetokens` are incompatible together":s||n?n&&n.length>1&&n.length!==t.length?"Length of `channelTimetokens` and `channels` do not match":void 0:"`timetoken` or `channelTimetokens` need to be set":"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return{channels:t.channels}}))}get path(){return`/v3/history/sub-key/${this.parameters.keySet.subscribeKey}/message-counts/${I(this.parameters.channels)}`}get queryParameters(){let{channelTimetokens:e}=this.parameters;return this.parameters.timetoken&&(e=[this.parameters.timetoken]),Object.assign(Object.assign({},1===e.length?{timetoken:e[0]}:{}),e.length>1?{channelsTimetoken:e.join(",")}:{})}}class Rt extends se{constructor(e){var t,s,n;super(),this.parameters=e,e.count?e.count=Math.min(e.count,100):e.count=100,null!==(t=e.stringifiedTimeToken)&&void 0!==t||(e.stringifiedTimeToken=false),null!==(s=e.includeMeta)&&void 0!==s||(e.includeMeta=false),null!==(n=e.logVerbosity)&&void 0!==n||(e.logVerbosity=false)}operation(){return ne.PNHistoryOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));const s=t[0],n=t[1],r=t[2];return Array.isArray(s)?{messages:s.map((e=>{const t=this.processPayload(e.message),s={entry:t.payload,timetoken:e.timetoken};return t.error&&(s.error=t.error),e.meta&&(s.meta=e.meta),s})),startTimeToken:n,endTimeToken:r}:{messages:[],startTimeToken:n,endTimeToken:r}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/history/sub-key/${e}/channel/${j(t)}`}get queryParameters(){const{start:e,end:t,reverse:s,count:n,stringifiedTimeToken:r,includeMeta:i}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:n,include_token:"true"},e?{start:e}:{}),t?{end:t}:{}),r?{string_message_token:"true"}:{}),null!=s?{reverse:s.toString()}:{}),i?{include_meta:"true"}:{})}processPayload(e){const{crypto:t,logVerbosity:s}=this.parameters;if(!t||"string"!=typeof e)return{payload:e};let n,r;try{const s=t.decrypt(e);n=s instanceof ArrayBuffer?JSON.parse(Rt.decoder.decode(s)):s}catch(t){s&&console.log("decryption error",t.message),n=e,r=`Error while decrypting message content: ${t.message}`}return{payload:n,error:r}}}var Ut;!function(e){e[e.Message=-1]="Message",e[e.Files=4]="Files"}(Ut||(Ut={}));class Tt extends se{constructor(e){var t,s,n,r,i;super(),this.parameters=e;const o=null!==(t=e.includeMessageActions)&&void 0!==t&&t,a=e.channels.length>1||o?25:100;e.count?e.count=Math.min(e.count,a):e.count=a,e.includeUuid?e.includeUUID=e.includeUuid:null!==(s=e.includeUUID)&&void 0!==s||(e.includeUUID=true),null!==(n=e.stringifiedTimeToken)&&void 0!==n||(e.stringifiedTimeToken=false),null!==(r=e.includeMessageType)&&void 0!==r||(e.includeMessageType=true),null!==(i=e.logVerbosity)&&void 0!==i||(e.logVerbosity=false)}operation(){return ne.PNFetchMessagesOperation}validate(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return e?t?void 0!==s&&s&&t.length>1?"History can return actions data for a single channel only. Either pass a single channel or disable the includeMessageActions flag.":void 0:"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t;const s=this.deserializeResponse(e);if(!s)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(s.status>=400)throw A.create(e);const n=null!==(t=s.channels)&&void 0!==t?t:{},r={};return Object.keys(n).forEach((e=>{r[e]=n[e].map((t=>{null===t.message_type&&(t.message_type=Ut.Message);const s=this.processPayload(e,t),n={channel:e,timetoken:t.timetoken,message:s.payload,messageType:t.message_type,uuid:t.uuid};if(t.actions){const e=n;e.actions=t.actions,e.data=t.actions}return t.meta&&(n.meta=t.meta),s.error&&(n.error=s.error),n}))})),s.more?{channels:r,more:s.more}:{channels:r}}))}get path(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return`/v3/${s?"history-with-actions":"history"}/sub-key/${e}/channel/${I(t)}`}get queryParameters(){const{start:e,end:t,count:s,includeMessageType:n,includeMeta:r,includeUUID:i,stringifiedTimeToken:o}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({max:s},e?{start:e}:{}),t?{end:t}:{}),o?{string_message_token:"true"}:{}),void 0!==r&&r?{include_meta:"true"}:{}),i?{include_uuid:"true"}:{}),n?{include_message_type:"true"}:{})}processPayload(e,t){const{crypto:s,logVerbosity:n}=this.parameters;if(!s||"string"!=typeof t.message)return{payload:t.message};let r,i;try{const e=s.decrypt(t.message);r=e instanceof ArrayBuffer?JSON.parse(Tt.decoder.decode(e)):e}catch(e){n&&console.log("decryption error",e.message),r=t.message,i=`Error while decrypting message content: ${e.message}`}if(!i&&r&&t.message_type==Ut.Files&&"object"==typeof r&&this.isFileMessage(r)){const t=r;return{payload:{message:t.message,file:Object.assign(Object.assign({},t.file),{url:this.parameters.getFileUrl({channel:e,id:t.file.id,name:t.file.name})})},error:i}}return{payload:r,error:i}}isFileMessage(e){return void 0!==e.file}}class Ft extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNGetMessageActionsOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing message channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);let s=null,n=null;return t.data.length>0&&(s=t.data[0].actionTimetoken,n=t.data[t.data.length-1].actionTimetoken),{data:t.data,more:t.more,start:s,end:n}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/message-actions/${e}/channel/${j(t)}`}get queryParameters(){const{limit:e,start:t,end:s}=this.parameters;return Object.assign(Object.assign(Object.assign({},t?{start:t}:{}),s?{end:s}:{}),e?{limit:e}:{})}}class xt extends se{constructor(e){super({method:B.POST}),this.parameters=e}operation(){return ne.PNAddMessageActionOperation}validate(){const{keySet:{subscribeKey:e},action:t,channel:s,messageTimetoken:n}=this.parameters;return e?s?n?t?t.value?t.type?t.type.length>15?"Action.type value exceed maximum length of 15":void 0:"Missing Action.type":"Missing Action.value":"Missing Action":"Missing message timetoken":"Missing message channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return{data:t.data}}))}get path(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s}=this.parameters;return`/v1/message-actions/${e}/channel/${j(t)}/message/${s}`}get headers(){return{"Content-Type":"application/json"}}get body(){return JSON.stringify(this.parameters.action)}}class Dt extends se{constructor(e){super({method:B.DELETE}),this.parameters=e}operation(){return ne.PNRemoveMessageActionOperation}validate(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s,actionTimetoken:n}=this.parameters;return e?t?s?n?void 0:"Missing action timetoken":"Missing message timetoken":"Missing message action channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return{data:t.data}}))}get path(){const{keySet:{subscribeKey:e},channel:t,actionTimetoken:s,messageTimetoken:n}=this.parameters;return`/v1/message-actions/${e}/channel/${j(t)}/message/${n}/action/${s}`}}class qt extends se{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).storeInHistory)&&void 0!==t||(s.storeInHistory=true)}operation(){return ne.PNPublishFileMessageOperation}validate(){const{channel:e,fileId:t,fileName:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[2]}}))}get path(){const{message:e,channel:t,keySet:{publishKey:s,subscribeKey:n},fileId:r,fileName:i}=this.parameters,o=Object.assign({file:{name:i,id:r}},e?{message:e}:{});return`/v1/files/publish-file/${s}/${n}/0/${j(t)}/0/${j(this.prepareMessagePayload(o))}`}get queryParameters(){const{storeInHistory:e,ttl:t,meta:s}=this.parameters;return Object.assign(Object.assign({store:e?"1":"0"},t?{ttl:t}:{}),s&&"object"==typeof s?{meta:JSON.stringify(s)}:{})}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof s?s:u(s))}}class Gt extends se{constructor(e){super({method:B.LOCAL}),this.parameters=e}operation(){return ne.PNGetFileUrlOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return e.url}))}get path(){const{channel:e,id:t,name:s,keySet:{subscribeKey:n}}=this.parameters;return`/v1/files/${n}/channels/${j(e)}/files/${t}/${s}`}}class Kt extends se{constructor(e){super({method:B.DELETE}),this.parameters=e}operation(){return ne.PNDeleteFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},id:t,channel:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${j(s)}/files/${t}/${n}`}}class $t extends se{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).limit)&&void 0!==t||(s.limit=100)}operation(){return ne.PNListFilesOperation}validate(){if(!this.parameters.channel)return"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${j(t)}/files`}get queryParameters(){const{limit:e,next:t}=this.parameters;return Object.assign({limit:e},t?{next:t}:{})}}class Lt extends se{constructor(e){super({method:B.POST}),this.parameters=e}operation(){return ne.PNGenerateUploadUrlOperation}validate(){return this.parameters.channel?this.parameters.name?void 0:"'name' can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return{id:t.data.id,name:t.data.name,url:t.file_upload_request.url,formFields:t.file_upload_request.form_fields}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${j(t)}/generate-upload-url`}get headers(){return{"Content-Type":"application/json"}}get body(){return JSON.stringify({name:this.parameters.name})}}class Bt extends se{constructor(e){super({method:B.POST}),this.parameters=e;const t=e.file.mimeType;t&&(e.formFields=e.formFields.map((e=>"Content-Type"===e.name?{name:e.name,value:t}:e)))}operation(){return ne.PNPublishFileOperation}validate(){const{fileId:e,fileName:t,file:s,uploadUrl:n}=this.parameters;return e?t?s?n?void 0:"Validation failed: file upload 'url' can't be empty":"Validation failed: 'file' can't be empty":"Validation failed: file 'name' can't be empty":"Validation failed: file 'id' can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return{status:e.status,message:e.body?Bt.decoder.decode(e.body):"OK"}}))}request(){return Object.assign(Object.assign({},super.request()),{origin:new URL(this.parameters.uploadUrl).origin,timeout:300})}get path(){const{pathname:e,search:t}=new URL(this.parameters.uploadUrl);return`${e}${t}`}get body(){return this.parameters.file}get formData(){return this.parameters.formFields}}class Ht{constructor(e){var t;if(this.parameters=e,this.file=null===(t=this.parameters.PubNubFile)||void 0===t?void 0:t.create(e.file),!this.file)throw new Error("File upload error: unable to create File object.")}process(){return i(this,void 0,void 0,(function*(){let e,t;return this.generateFileUploadUrl().then((s=>(e=s.name,t=s.id,this.uploadFile(s)))).then((e=>{if(204!==e.status)throw new d("Upload to bucket was unsuccessful",{error:!0,statusCode:e.status,category:h.PNUnknownCategory,operation:ne.PNPublishFileOperation,errorData:{message:e.message}})})).then((()=>this.publishFileMessage(t,e))).catch((e=>{if(e instanceof d)throw e;const t=e instanceof A?e:A.create(e);throw new d("File upload error.",t.toStatus(ne.PNPublishFileOperation))}))}))}generateFileUploadUrl(){return i(this,void 0,void 0,(function*(){const e=new Lt(Object.assign(Object.assign({},this.parameters),{name:this.file.name,keySet:this.parameters.keySet}));return this.parameters.sendRequest(e)}))}uploadFile(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,PubNubFile:s,crypto:n,cryptography:r}=this.parameters,{id:i,name:o,url:a,formFields:c}=e;return this.parameters.PubNubFile.supportsEncryptFile&&(!t&&n?this.file=yield n.encryptFile(this.file,s):t&&r&&(this.file=yield r.encryptFile(t,this.file,s))),this.parameters.sendRequest(new Bt({fileId:i,fileName:o,file:this.file,uploadUrl:a,formFields:c}))}))}publishFileMessage(e,t){return i(this,void 0,void 0,(function*(){var s,n,r,i;let o,a={timetoken:"0"},c=this.parameters.fileUploadPublishRetryLimit,u=!1;do{try{a=yield this.parameters.publishFile(Object.assign(Object.assign({},this.parameters),{fileId:e,fileName:t})),u=!0}catch(e){e instanceof d&&(o=e),c-=1}}while(!u&&c>0);if(u)return{status:200,timetoken:a.timetoken,id:e,name:t};throw new d("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{error:!0,category:null!==(n=null===(s=o.status)||void 0===s?void 0:s.category)&&void 0!==n?n:h.PNUnknownCategory,statusCode:null!==(i=null===(r=o.status)||void 0===r?void 0:r.statusCode)&&void 0!==i?i:0,channel:this.parameters.channel,id:e,name:t})}))}}class zt{subscribe(e){const t=null==e?void 0:e.timetoken;this.pubnub.subscribe(Object.assign({channels:this.channelNames,channelGroups:this.groupNames},null!==t&&""!==t&&{timetoken:t}))}unsubscribe(){this.pubnub.unsubscribe({channels:this.channelNames,channelGroups:this.groupNames})}set onMessage(e){this.listener.message=e}set onPresence(e){this.listener.presence=e}set onSignal(e){this.listener.signal=e}set onObjects(e){this.listener.objects=e}set onMessageAction(e){this.listener.messageAction=e}set onFile(e){this.listener.file=e}addListener(e){this.eventEmitter.addListener(e,this.channelNames.filter((e=>!e.endsWith("-pnpres"))),this.groupNames.filter((e=>!e.endsWith("-pnpres"))))}removeListener(e){this.eventEmitter.removeListener(e,this.channelNames,this.groupNames)}get channels(){return this.channelNames.slice(0)}get channelGroups(){return this.groupNames.slice(0)}}class Vt extends zt{constructor({channels:e=[],channelGroups:t=[],subscriptionOptions:s,eventEmitter:n,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.subscriptionList=[],this.options=s,this.eventEmitter=n,this.pubnub=r,e.forEach((e=>{const t=this.pubnub.channel(e).subscription(this.options);this.channelNames=[...this.channelNames,...t.channels],this.subscriptionList.push(t)})),t.forEach((e=>{const t=this.pubnub.channelGroup(e).subscription(this.options);this.groupNames=[...this.groupNames,...t.channelGroups],this.subscriptionList.push(t)})),this.listener={},n.addListener(this.listener,this.channelNames.filter((e=>!e.endsWith("-pnpres"))),this.groupNames.filter((e=>!e.endsWith("-pnpres"))))}addSubscription(e){this.subscriptionList.push(e),this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscription(e){const t=e.channels,s=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!s.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>t!==e)),this.eventEmitter.removeListener(this.listener,t,s)}addSubscriptionSet(e){this.subscriptionList=[...this.subscriptionList,...e.subscriptions],this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscriptionSet(e){const t=e.channels,s=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!s.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>!e.subscriptions.includes(t))),this.eventEmitter.removeListener(this.listener,t,s)}get subscriptions(){return this.subscriptionList.slice(0)}}class Wt extends zt{constructor({channels:e,channelGroups:t,subscriptionOptions:s,eventEmitter:n,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.channelNames=e,this.groupNames=t,this.options=s,this.pubnub=r,this.eventEmitter=n,this.listener={},n.addListener(this.listener,this.channelNames.filter((e=>!e.endsWith("-pnpres"))),this.groupNames.filter((e=>!e.endsWith("-pnpres"))))}addSubscription(e){return new Vt({channels:[...this.channelNames,...e.channels],channelGroups:[...this.groupNames,...e.channelGroups],subscriptionOptions:Object.assign(Object.assign({},this.options),null==e?void 0:e.options),eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Jt{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.id=e}subscription(e){return new Wt({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Qt{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.name=e}subscription(e){return new Wt({channels:[],channelGroups:(null==e?void 0:e.receivePresenceEvents)?[this.name,`${this.name}-pnpres`]:[this.name],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Yt{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.id=e}subscription(e){return new Wt({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Xt{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.name=e}subscription(e){return new Wt({channels:(null==e?void 0:e.receivePresenceEvents)?[this.name,`${this.name}-pnpres`]:[this.name],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Zt extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNRemoveChannelsFromGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${j(t)}`}get queryParameters(){return{remove:this.parameters.channels.join(",")}}}class es extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNAddChannelsToGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${j(t)}`}get queryParameters(){return{add:this.parameters.channels.join(",")}}}class ts extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNChannelsForGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return{channels:t.payload.channels}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${j(t)}`}}class ss extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNRemoveGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${j(t)}/remove`}}class ns extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNChannelGroupsOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return{groups:t.payload.groups}}))}get path(){return`/v1/channel-registration/sub-key/${this.parameters.keySet.subscribeKey}/channel-group`}}class rs{constructor(e,t){this.sendRequest=t,this.keySet=e}listChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new ts(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}listGroups(e){return i(this,void 0,void 0,(function*(){const t=new ns({keySet:this.keySet});return e?this.sendRequest(t,e):this.sendRequest(t)}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new es(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new Zt(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}deleteGroup(e,t){return i(this,void 0,void 0,(function*(){const s=new ss(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}}class is extends se{constructor(e){var t,s;super(),this.parameters=e,"apns2"===this.parameters.pushGateway&&(null!==(t=(s=this.parameters).environment)&&void 0!==t||(s.environment="development")),this.parameters.count&&this.parameters.count>1e3&&(this.parameters.count=1e3)}operation(){throw Error("Should be implemented in subclass.")}validate(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;return e?s?"add"!==t&&"remove"!==t||"channels"in this.parameters&&0!==this.parameters.channels.length?n?"apns2"!==this.parameters.pushGateway||this.parameters.topic?void 0:"Missing APNS2 topic":"Missing GW Type (pushGateway: gcm or apns2)":"Missing Channels":"Missing Device ID (device)":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){throw Error("Should be implemented in subclass.")}))}get path(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;let r="apns2"===n?`/v2/push/sub-key/${e}/devices-apns2/${s}`:`/v1/push/sub-key/${e}/devices/${s}`;return"remove-device"===t&&(r=`${r}/remove`),r}get queryParameters(){const{start:e,count:t}=this.parameters;let s=Object.assign(Object.assign({type:this.parameters.pushGateway},e?{start:e}:{}),t&&t>0?{count:t}:{});if("channels"in this.parameters&&(s[this.parameters.action]=this.parameters.channels.join(",")),"apns2"===this.parameters.pushGateway){const{environment:e,topic:t}=this.parameters;s=Object.assign(Object.assign({},s),{environment:e,topic:t})}return s}}class os extends is{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove"}))}operation(){return ne.PNRemovePushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{}}))}}class as extends is{constructor(e){super(Object.assign(Object.assign({},e),{action:"list"}))}operation(){return ne.PNPushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{channels:t}}))}}class cs extends is{constructor(e){super(Object.assign(Object.assign({},e),{action:"add"}))}operation(){return ne.PNAddPushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{}}))}}class us extends is{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove-device"}))}operation(){return ne.PNRemoveAllPushNotificationsOperation}parse(e){return i(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{}}))}}class ls{constructor(e,t){this.sendRequest=t,this.keySet=e}listChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new as(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new cs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new os(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}deleteDevice(e,t){return i(this,void 0,void 0,(function*(){const s=new us(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}}class hs extends se{constructor(e){var t,s,n,r,i,o;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(i=e.include).customFields)&&void 0!==s||(i.customFields=false),null!==(n=(o=e.include).totalCount)&&void 0!==n||(o.totalCount=false),null!==(r=e.limit)&&void 0!==r||(e.limit=100)}operation(){return ne.PNGetAllChannelMetadataOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";return i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(","),count:`${e.totalCount}`},s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class ds extends se{constructor(e){super({method:B.DELETE}),this.parameters=e}operation(){return ne.PNRemoveChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${j(t)}`}}class ps extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(l=e.include).customFields)&&void 0!==s||(l.customFields=false),null!==(n=(h=e.include).totalCount)&&void 0!==n||(h.totalCount=false),null!==(r=(d=e.include).statusField)&&void 0!==r||(d.statusField=false),null!==(i=(p=e.include).channelFields)&&void 0!==i||(p.channelFields=false),null!==(o=(g=e.include).customChannelFields)&&void 0!==o||(g.customChannelFields=false),null!==(a=(y=e.include).channelStatusField)&&void 0!==a||(y.channelStatusField=false),null!==(c=(f=e.include).channelTypeField)&&void 0!==c||(f.channelTypeField=false),null!==(u=e.limit)&&void 0!==u||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ne.PNGetMembershipsOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${j(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const o=[];return e.statusField&&o.push("status"),e.customFields&&o.push("custom"),e.channelFields&&o.push("channel"),e.channelStatusField&&o.push("channel.status"),e.channelTypeField&&o.push("channel.type"),e.customChannelFields&&o.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class gs extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l;super({method:B.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(a=e.include).customFields)&&void 0!==s||(a.customFields=false),null!==(n=(c=e.include).totalCount)&&void 0!==n||(c.totalCount=false),null!==(r=(u=e.include).channelFields)&&void 0!==r||(u.channelFields=false),null!==(i=(l=e.include).customChannelFields)&&void 0!==i||(l.customChannelFields=false),null!==(o=e.limit)&&void 0!==o||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ne.PNSetMembershipsOperation}validate(){const{uuid:e,channels:t}=this.parameters;return e?t&&0!==t.length?void 0:"Channels cannot be empty":"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${j(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const o=["channel.status","channel.type","status"];return e.customFields&&o.push("custom"),e.channelFields&&o.push("channel"),e.customChannelFields&&o.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{channels:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{channel:{id:e}}:{channel:{id:e.id},status:e.status,custom:e.custom}))})}}class ys extends se{constructor(e){var t,s,n,r;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(r=e.include).customFields)&&void 0!==s||(r.customFields=false),null!==(n=e.limit)&&void 0!==n||(e.limit=100)}operation(){return ne.PNGetAllUUIDMetadataOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";return i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(",")},void 0!==e.totalCount?{count:`${e.totalCount}`}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class fs extends se{constructor(e){var t,s,n;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true)}operation(){return ne.PNGetChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${j(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}}class ms extends se{constructor(e){var t,s,n;super({method:B.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true)}operation(){return ne.PNSetChannelMetadataOperation}validate(){return this.parameters.channel?this.parameters.data?void 0:"Data cannot be empty":"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${j(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class bs extends se{constructor(e){super({method:B.DELETE}),this.parameters=e,this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ne.PNRemoveUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${j(t)}`}}class vs extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(l=e.include).customFields)&&void 0!==s||(l.customFields=false),null!==(n=(h=e.include).totalCount)&&void 0!==n||(h.totalCount=false),null!==(r=(d=e.include).statusField)&&void 0!==r||(d.statusField=false),null!==(i=(p=e.include).UUIDFields)&&void 0!==i||(p.UUIDFields=false),null!==(o=(g=e.include).customUUIDFields)&&void 0!==o||(g.customUUIDFields=false),null!==(a=(y=e.include).UUIDStatusField)&&void 0!==a||(y.UUIDStatusField=false),null!==(c=(f=e.include).UUIDTypeField)&&void 0!==c||(f.UUIDTypeField=false),null!==(u=e.limit)&&void 0!==u||(e.limit=100)}operation(){return ne.PNSetMembersOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${j(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const o=[];return e.statusField&&o.push("status"),e.customFields&&o.push("custom"),e.UUIDFields&&o.push("uuid"),e.UUIDStatusField&&o.push("uuid.status"),e.UUIDTypeField&&o.push("uuid.type"),e.customUUIDFields&&o.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class ws extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l;super({method:B.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(a=e.include).customFields)&&void 0!==s||(a.customFields=false),null!==(n=(c=e.include).totalCount)&&void 0!==n||(c.totalCount=false),null!==(r=(u=e.include).UUIDFields)&&void 0!==r||(u.UUIDFields=false),null!==(i=(l=e.include).customUUIDFields)&&void 0!==i||(l.customUUIDFields=false),null!==(o=e.limit)&&void 0!==o||(e.limit=100)}operation(){return ne.PNSetMembersOperation}validate(){const{channel:e,uuids:t}=this.parameters;return e?t&&0!==t.length?void 0:"UUIDs cannot be empty":"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${j(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const o=["uuid.status","uuid.type","type"];return e.customFields&&o.push("custom"),e.UUIDFields&&o.push("uuid"),e.customUUIDFields&&o.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{uuids:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{uuid:{id:e}}:{uuid:{id:e.id},status:e.status,custom:e.custom}))})}}class Ss extends se{constructor(e){var t,s,n;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ne.PNGetUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${j(t)}`}get queryParameters(){const{include:e}=this.parameters;return{include:["status","type",...e.customFields?["custom"]:[]].join(",")}}}class ks extends se{constructor(e){var t,s,n;super({method:B.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ne.PNSetUUIDMetadataOperation}validate(){return this.parameters.uuid?this.parameters.data?void 0:"Data cannot be empty":"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw A.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${j(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Es{constructor(e,t){this.keySet=e.keySet,this.configuration=e,this.sendRequest=t}getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getAllUUIDMetadata(e,t)}))}_getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const n=new ys(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getUUIDMetadata(e,t)}))}_getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new Ss(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._setUUIDMetadata(e,t)}))}_setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new ks(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._removeUUIDMetadata(e,t)}))}_removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new bs(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getAllChannelMetadata(e,t)}))}_getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const n=new hs(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getChannelMetadata(e,t)}))}_getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new fs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._setChannelMetadata(e,t)}))}_setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new ms(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._removeChannelMetadata(e,t)}))}_removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new ds(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const s=new vs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}setChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const s=new ws(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const s=new ws(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new ps(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new gs(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new gs(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n;if("spaceId"in e){const n=e,r={channel:null!==(s=n.spaceId)&&void 0!==s?s:n.channel,filter:n.filter,limit:n.limit,page:n.page,include:Object.assign({},n.include),sort:n.sort?Object.fromEntries(Object.entries(n.sort).map((([e,t])=>[e.replace("user","uuid"),t]))):void 0},i=e=>({status:e.status,data:e.data.map((e=>({user:e.uuid,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getChannelMembers(r,((e,s)=>{t(e,s?i(s):s)})):this.getChannelMembers(r).then(i)}const r=e,i={uuid:null!==(n=r.userId)&&void 0!==n?n:r.uuid,filter:r.filter,limit:r.limit,page:r.page,include:Object.assign({},r.include),sort:r.sort?Object.fromEntries(Object.entries(r.sort).map((([e,t])=>[e.replace("space","channel"),t]))):void 0},o=e=>({status:e.status,data:e.data.map((e=>({space:e.channel,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getMemberships(i,((e,s)=>{t(e,s?o(s):s)})):this.getMemberships(i).then(o)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n,r,i,o,a;if("spaceId"in e){const i=e,o={channel:null!==(s=i.spaceId)&&void 0!==s?s:i.channel,uuids:null!==(r=null===(n=i.users)||void 0===n?void 0:n.map((e=>"string"==typeof e?e:(e.userId,{id:e.userId,custom:e.custom}))))&&void 0!==r?r:i.uuids,limit:0};return t?this.setChannelMembers(o,t):this.setChannelMembers(o)}const c=e,u={uuid:null!==(i=c.userId)&&void 0!==i?i:c.uuid,channels:null!==(a=null===(o=c.spaces)||void 0===o?void 0:o.map((e=>"string"==typeof e?e:{id:e.spaceId,custom:e.custom})))&&void 0!==a?a:c.channels,limit:0};return t?this.setMemberships(u,t):this.setMemberships(u)}))}}class Os extends se{constructor(){super()}operation(){return ne.PNTimeOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[0]}}))}get path(){return"/time/0"}}class Cs extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNDownloadFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,crypto:s,cryptography:n,name:r,PubNubFile:i}=this.parameters,o=e.headers["content-type"];let a,c=e.body;return i.supportsEncryptFile&&(t||s)&&(t&&n?c=yield n.decrypt(t,c):!t&&s&&(a=yield s.decryptFile(i.create({data:c,name:r,mimeType:o}),i))),a||i.create({data:c,name:r,mimeType:o})}))}get path(){const{keySet:{subscribeKey:e},channel:t,id:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${j(t)}/files/${s}/${n}`}}class Ns{static notificationPayload(e,t){return new te(e,t)}static generateUUID(){return G.createUUID()}constructor(e){if(this._configuration=e.configuration,this.cryptography=e.cryptography,this.tokenManager=e.tokenManager,this.transport=e.transport,this.crypto=e.crypto,this._objects=new Es(this._configuration,this.sendRequest.bind(this)),this._channelGroups=new rs(this._configuration.keySet,this.sendRequest.bind(this)),this._push=new ls(this._configuration.keySet,this.sendRequest.bind(this)),this.listenerManager=new W,this.eventEmitter=new ae(this.listenerManager),this._configuration.enableEventEngine){let e=this._configuration.getHeartbeatInterval();this.presenceState={},e&&(this.presenceEventEngine=new Ke({heartbeat:this.heartbeat.bind(this),leave:e=>this.makeUnsubscribe(e,(()=>{})),heartbeatDelay:()=>new Promise(((t,s)=>{e=this._configuration.getHeartbeatInterval(),e?setTimeout(t,1e3*e):s(new d("Heartbeat interval has been reset."))})),retryDelay:e=>new Promise((t=>setTimeout(t,e))),emitStatus:e=>this.listenerManager.announceStatus(e),config:this._configuration,presenceState:this.presenceState})),this.eventEngine=new wt({handshake:this.subscribeHandshake.bind(this),receiveMessages:this.subscribeReceiveMessages.bind(this),delay:e=>new Promise((t=>setTimeout(t,e))),join:this.join.bind(this),leave:this.leave.bind(this),leaveAll:this.leaveAll.bind(this),presenceState:this.presenceState,config:this._configuration,emitMessages:e=>{try{e.forEach((e=>this.eventEmitter.emitEvent(e)))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}},emitStatus:e=>this.listenerManager.announceStatus(e)})}else this.subscriptionManager=new Y(this._configuration,this.listenerManager,this.eventEmitter,this.makeSubscribe.bind(this),this.heartbeat.bind(this),this.makeUnsubscribe.bind(this),this.time.bind(this))}get configuration(){return this._configuration}get _config(){return this.configuration}get authKey(){var e;return null!==(e=this._configuration.authKey)&&void 0!==e?e:void 0}getAuthKey(){return this.authKey}setAuthKey(e){this._configuration.setAuthKey(e)}get userId(){return this._configuration.userId}set userId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}getUserId(){return this._configuration.userId}setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}get filterExpression(){var e;return null!==(e=this._configuration.getFilterExpression())&&void 0!==e?e:void 0}getFilterExpression(){return this.filterExpression}set filterExpression(e){this._configuration.setFilterExpression(e)}setFilterExpression(e){this.filterExpression=e}get cipherKey(){return this._configuration.getCipherKey()}set cipherKey(e){this._configuration.setCipherKey(e)}setCipherKey(e){this.cipherKey=e}set heartbeatInterval(e){this._configuration.setHeartbeatInterval(e)}setHeartbeatInterval(e){this.heartbeatInterval=e}getVersion(){return this._configuration.getVersion()}_addPnsdkSuffix(e,t){this._configuration._addPnsdkSuffix(e,t)}getUUID(){return this.userId}setUUID(e){this.userId=e}get customEncrypt(){return this._configuration.getCustomEncrypt()}get customDecrypt(){return this._configuration.getCustomDecrypt()}channel(e){return new Xt(e,this.eventEmitter,this)}channelGroup(e){return new Qt(e,this.eventEmitter,this)}channelMetadata(e){return new Jt(e,this.eventEmitter,this)}userMetadata(e){return new Yt(e,this.eventEmitter,this)}subscriptionSet(e){return new Vt(Object.assign(Object.assign({},e),{eventEmitter:this.eventEmitter,pubnub:this}))}sendRequest(e,t){return i(this,void 0,void 0,(function*(){const s=e.validate();if(s){if(t)return t(p(s),null);throw new d("Validation failed, check status for details",p(s))}const n=e.request();n.formData&&n.formData.length>0?n.timeout=300:e.operation()===ne.PNSubscribeOperation?n.timeout=this._configuration.getSubscribeTimeout():n.timeout=this._configuration.getTransactionTimeout();const r={error:!1,operation:e.operation(),category:h.PNAcknowledgmentCategory,statusCode:0},[i,o]=this.transport.makeSendable(n);return e.cancellationController=o||null,i.then((t=>{if(r.statusCode=t.status,200!==t.status&&204!==t.status){const e=t.headers["content-type"];if(e||-1!==e.indexOf("javascript")||-1!==e.indexOf("json")){const e=JSON.parse(Ns.decoder.decode(t.body));"object"==typeof e&&"error"in e&&e.error&&"object"==typeof e.error&&(r.errorData=e.error)}}return e.parse(t)})).then((e=>t?t(r,e):e)).catch((s=>{const n=s instanceof A?s:A.create(s);if(t)return t(n.toStatus(e.operation()),null);throw n.toPubNubError(e.operation(),"REST API request processing error, check status for details")}))}))}destroy(e){this.subscriptionManager?(this.subscriptionManager.unsubscribeAll(e),this.subscriptionManager.disconnect()):this.eventEngine&&this.eventEngine.dispose()}stop(){this.destroy()}addListener(e){this.listenerManager.addListener(e)}removeListener(e){this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners()}publish(e,t){return i(this,void 0,void 0,(function*(){{const s=new St(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}signal(e,t){return i(this,void 0,void 0,(function*(){{const s=new kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}fire(e,t){return i(this,void 0,void 0,(function*(){return null!=t||(t=()=>{}),this.publish(Object.assign(Object.assign({},e),{replicate:!1,storeInHistory:!1}),t)}))}getSubscribedChannels(){return this.subscriptionManager?this.subscriptionManager.subscribedChannels:this.eventEngine?this.eventEngine.getSubscribedChannels():[]}getSubscribedChannelGroups(){return this.subscriptionManager?this.subscriptionManager.subscribedChannelGroups:this.eventEngine?this.eventEngine.getSubscribedChannelGroups():[]}subscribe(e){this.subscriptionManager?this.subscriptionManager.subscribe(e):this.eventEngine&&this.eventEngine.subscribe(e)}makeSubscribe(e,t){{const s=new oe(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));if(this.sendRequest(s,((e,n)=>{var r;this.subscriptionManager&&(null===(r=this.subscriptionManager.abort)||void 0===r?void 0:r.identifier)===s.requestIdentifier&&(this.subscriptionManager.abort=null),t(e,n)})),this.subscriptionManager){const e=()=>s.abort();e.identifier=s.requestIdentifier,this.subscriptionManager.abort=e}}}unsubscribe(e){this.subscriptionManager?this.subscriptionManager.unsubscribe(e):this.eventEngine&&this.eventEngine.unsubscribe(e)}makeUnsubscribe(e,t){this.sendRequest(new Mt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),t)}unsubscribeAll(){this.subscriptionManager?this.subscriptionManager.unsubscribeAll():this.eventEngine&&this.eventEngine.unsubscribeAll()}disconnect(){this.subscriptionManager?this.subscriptionManager.disconnect():this.eventEngine&&this.eventEngine.disconnect()}reconnect(e){this.subscriptionManager?this.subscriptionManager.reconnect():this.eventEngine&&this.eventEngine.reconnect(null!=e?e:{})}subscribeHandshake(e){return i(this,void 0,void 0,(function*(){{const t=new Ot(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((e=>{t.abort()}));return this.sendRequest(t).then((e=>(s(),e.cursor)))}}))}subscribeReceiveMessages(e){return i(this,void 0,void 0,(function*(){{const t=new Et(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((e=>{t.abort()}));return this.sendRequest(t).then((e=>(s(),e)))}}))}getMessageActions(e,t){return i(this,void 0,void 0,(function*(){{const s=new Ft(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}addMessageAction(e,t){return i(this,void 0,void 0,(function*(){{const s=new xt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}removeMessageAction(e,t){return i(this,void 0,void 0,(function*(){{const s=new Dt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}fetchMessages(e,t){return i(this,void 0,void 0,(function*(){{const s=new Tt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}deleteMessages(e,t){return i(this,void 0,void 0,(function*(){{const s=new jt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}messageCounts(e,t){return i(this,void 0,void 0,(function*(){{const s=new It(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}history(e,t){return i(this,void 0,void 0,(function*(){{const s=new Rt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}hereNow(e,t){return i(this,void 0,void 0,(function*(){{const s=new _t(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}whereNow(e,t){return i(this,void 0,void 0,(function*(){var s;{const n=new At({uuid:null!==(s=e.uuid)&&void 0!==s?s:this._configuration.userId,keySet:this._configuration.keySet});return t?this.sendRequest(n,t):this.sendRequest(n)}}))}getState(e,t){return i(this,void 0,void 0,(function*(){var s;{const n=new Ct(Object.assign(Object.assign({},e),{uuid:null!==(s=e.uuid)&&void 0!==s?s:this._configuration.userId,keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}setState(e,t){return i(this,void 0,void 0,(function*(){var s,n;{const{keySet:r,userId:i}=this._configuration,o=this._configuration.getPresenceTimeout();let a;if(this._configuration.enableEventEngine&&this.presenceState){const t=this.presenceState;null===(s=e.channels)||void 0===s||s.forEach((s=>t[s]=e.state)),"channelGroups"in e&&(null===(n=e.channelGroups)||void 0===n||n.forEach((s=>t[s]=e.state)))}return a="withHeartbeat"in e?new Pt(Object.assign(Object.assign({},e),{keySet:r,heartbeat:o})):new Nt(Object.assign(Object.assign({},e),{keySet:r,uuid:i})),this.subscriptionManager&&this.subscriptionManager.setState(e),t?this.sendRequest(a,t):this.sendRequest(a)}}))}presence(e){var t;null===(t=this.subscriptionManager)||void 0===t||t.changePresence(e)}heartbeat(e,t){return i(this,void 0,void 0,(function*(){{const s=new Pt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}join(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.join(e)}leave(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.leave(e)}leaveAll(){var e;null===(e=this.presenceEventEngine)||void 0===e||e.leaveAll()}grantToken(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant Token error: PAM module disabled")}))}revokeToken(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Revoke Token error: PAM module disabled")}))}get token(){return this.tokenManager&&this.tokenManager.getToken()}getToken(){return this.token}set token(e){this.tokenManager&&this.tokenManager.setToken(e)}setToken(e){this.token=e}parseToken(e){return this.tokenManager&&this.tokenManager.parseToken(e)}grant(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant error: PAM module disabled")}))}audit(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant Permissions error: PAM module disabled")}))}get objects(){return this._objects}fetchUsers(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getAllUUIDMetadata(e,t)}))}fetchUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getUUIDMetadata(e,t)}))}createUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}updateUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}removeUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._removeUUIDMetadata(e,t)}))}fetchSpaces(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getAllChannelMetadata(e,t)}))}fetchSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getChannelMetadata(e,t)}))}createSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}updateSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}removeSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._removeChannelMetadata(e,t)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.fetchMemberships(e,t)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}updateMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n,r;{if("spaceId"in e){const r=e,i={channel:null!==(s=r.spaceId)&&void 0!==s?s:r.channel,uuids:null!==(n=r.userIds)&&void 0!==n?n:r.uuids,limit:0};return t?this.objects.removeChannelMembers(i,t):this.objects.removeChannelMembers(i)}const i=e,o={uuid:i.userId,channels:null!==(r=i.spaceIds)&&void 0!==r?r:i.channels,limit:0};return t?this.objects.removeMemberships(o,t):this.objects.removeMemberships(o)}}))}get channelGroups(){return this._channelGroups}get push(){return this._push}sendFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const s=new Ht(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,fileUploadPublishRetryLimit:this._configuration.fileUploadPublishRetryLimit,file:e.file,sendRequest:this.sendRequest.bind(this),publishFile:this.publishFile.bind(this),crypto:this._configuration.getCryptoModule(),cryptography:this.cryptography?this.cryptography:void 0})),n={error:!1,operation:ne.PNPublishFileOperation,category:h.PNAcknowledgmentCategory,statusCode:0};return s.process().then((e=>(n.statusCode=e.status,t?t(n,e):e))).catch((e=>{let s;throw e instanceof d?s=e.status:e instanceof A&&(s=e.toStatus(n.operation)),t&&s&&t(s,null),new d("REST API request processing error, check status for details",s)}))}}))}publishFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const s=new qt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}listFiles(e,t){return i(this,void 0,void 0,(function*(){{const s=new $t(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}getFileUrl(e){var t;{const s=this.transport.request(new Gt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})).request()),n=null!==(t=s.queryParameters)&&void 0!==t?t:{},r=Object.keys(n).map((e=>{const t=n[e];return Array.isArray(t)?t.map((t=>`${e}=${j(t)}`)).join("&"):`${e}=${j(t)}`})).join("&");return`${s.origin}${s.path}?${r}`}}downloadFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const s=new Cs(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,cryptography:this.cryptography?this.cryptography:void 0,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):yield this.sendRequest(s)}}))}deleteFile(e,t){return i(this,void 0,void 0,(function*(){{const s=new Kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}time(e){return i(this,void 0,void 0,(function*(){const t=new Os;return e?this.sendRequest(t,e):this.sendRequest(t)}))}encrypt(e,t){const s=this._configuration.getCryptoModule();if(!t&&s&&"string"==typeof e){const t=s.encrypt(e);return"string"==typeof t?t:u(t)}if(!this.crypto)throw new Error("Encryption error: cypher key not set");return this.crypto.encrypt(e,t)}decrypt(e,t){const s=this._configuration.getCryptoModule();if(!t&&s){const t=s.decrypt(e);return t instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(t)):t}if(!this.crypto)throw new Error("Decryption error: cypher key not set");return this.crypto.decrypt(e,t)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File encryption error. File constructor not configured.");if("string"!=typeof e&&!this._configuration.getCryptoModule())throw new Error("File encryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File encryption error. File encryption not available");return this.cryptography.encryptFile(e,t,this._configuration.PubNubFile)}return null===(s=this._configuration.getCryptoModule())||void 0===s?void 0:s.encryptFile(t,this._configuration.PubNubFile)}))}decryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File decryption error. File constructor not configured.");if("string"==typeof e&&!this._configuration.getCryptoModule())throw new Error("File decryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File decryption error. File decryption not available");return this.cryptography.decryptFile(e,t,this._configuration.PubNubFile)}return null===(s=this._configuration.getCryptoModule())||void 0===s?void 0:s.decryptFile(t,this._configuration.PubNubFile)}))}}Ns.decoder=new TextDecoder,Ns.OPERATIONS=ne,Ns.CATEGORIES=h,Ns.ExponentialRetryPolicy=$e.ExponentialRetryPolicy,Ns.LinearRetryPolicy=$e.LinearRetryPolicy;class Ps{constructor(e,t){this.decode=e,this.base64ToBinary=t}decodeToken(e){let t="";e.length%4==3?t="=":e.length%4==2&&(t="==");const s=e.replace(/-/gi,"+").replace(/_/gi,"/")+t,n=this.decode(this.base64ToBinary(s));return"object"==typeof n?n:void 0}}class Ms extends Ns{constructor(e){var t;const s=x(e),r=Object.assign(Object.assign({},s),{sdkFamily:"Web"});r.PubNubFile=a;const i=K(r,(e=>{if(e.cipherKey)return new N({default:new C(Object.assign({},e)),cryptors:[new S({cipherKey:e.cipherKey})]})}));let o,u,l;o=new L(new Ps((e=>F(n.decode(e))),c)),(i.getCipherKey()||i.secretKey)&&(u=new E({secretKey:i.secretKey,cipherKey:i.getCipherKey(),useRandomIVs:i.getUseRandomIVs(),customEncrypt:i.getCustomEncrypt(),customDecrypt:i.getCustomDecrypt()})),l=new O;let h=new T(i.keepAlive,i.logVerbosity);s.subscriptionWorkerUrl&&(h=new _({clientIdentifier:i._instanceId,subscriptionKey:i.subscribeKey,userId:i.getUserId(),workerUrl:s.subscriptionWorkerUrl,sdkVersion:i.getVersion(),logVerbosity:i.logVerbosity,workerLogVerbosity:r.subscriptionWorkerLogVerbosity,transport:h}));super({configuration:i,transport:new V({clientConfiguration:i,tokenManager:o,transport:h}),cryptography:l,tokenManager:o,crypto:u}),(null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t)&&(window.addEventListener("offline",(()=>{this.networkDownDetected()})),window.addEventListener("online",(()=>{this.networkUpDetected()})))}networkDownDetected(){this.listenerManager.announceNetworkDown(),this._configuration.restore?this.disconnect():this.destroy(!0)}networkUpDetected(){this.listenerManager.announceNetworkUp(),this.reconnect()}}return Ms.CryptoModule=N,Ms})); diff --git a/dist/web/pubnub.worker.js b/dist/web/pubnub.worker.js index abe7ea21d..5708ecbad 100644 --- a/dist/web/pubnub.worker.js +++ b/dist/web/pubnub.worker.js @@ -89,6 +89,12 @@ var uuidExports = uuid.exports; var uuidGenerator$1 = /*@__PURE__*/getDefaultExportFromCjs(uuidExports); + /** + * Random identifier generator helper module. + * + * @internal + */ + /** @internal */ var uuidGenerator = { createUUID() { if (uuidGenerator$1.uuid) { @@ -105,6 +111,8 @@ * * Service worker provides support for PubNub subscription feature to give better user experience across * multiple opened pages. + * + * @internal */ /** * How often PING request should be sent to the PubNub clients. diff --git a/lib/core/components/configuration.js b/lib/core/components/configuration.js index 36724fbe4..04332168b 100644 --- a/lib/core/components/configuration.js +++ b/lib/core/components/configuration.js @@ -24,7 +24,7 @@ const USE_RANDOM_INITIALIZATION_VECTOR = true; * Create {@link PubNub} client private configuration object. * * @param base - User- and platform-provided configuration. - * @param setupCryptoModule - Platform-provided {@link CryptoModule} configuration block. + * @param setupCryptoModule - Platform-provided {@link ICryptoModule} configuration block. * * @returns `PubNub` client private configuration. * diff --git a/lib/core/components/push_payload.js b/lib/core/components/push_payload.js index 0c6c0bfe3..2573a983c 100644 --- a/lib/core/components/push_payload.js +++ b/lib/core/components/push_payload.js @@ -333,7 +333,7 @@ class APNSNotificationPayload extends BaseNotificationPayload { } exports.APNSNotificationPayload = APNSNotificationPayload; /** - * Message payload for Firebase Clouse Messaging service. + * Message payload for Firebase Cloud Messaging service. */ class FCMNotificationPayload extends BaseNotificationPayload { get payload() { diff --git a/lib/core/endpoints/subscribe.js b/lib/core/endpoints/subscribe.js index 21df60513..bb2d2e4c7 100644 --- a/lib/core/endpoints/subscribe.js +++ b/lib/core/endpoints/subscribe.js @@ -1,8 +1,6 @@ "use strict"; /** * Subscription REST API module. - * - * @internal */ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } @@ -37,8 +35,6 @@ const WITH_PRESENCE = false; // region Types /** * PubNub-defined event types by payload. - * - * @internal */ var PubNubEventType; (function (PubNubEventType) { diff --git a/lib/core/interfaces/configuration.js b/lib/core/interfaces/configuration.js index cc1b1d96d..c11ca0d07 100644 --- a/lib/core/interfaces/configuration.js +++ b/lib/core/interfaces/configuration.js @@ -138,7 +138,7 @@ const setDefaults = (configuration) => { let announceFailedHeartbeats = ANNOUNCE_HEARTBEAT_FAILURE; let fileUploadPublishRetryLimit = FILE_PUBLISH_RETRY_LIMIT; let dedupeOnSubscribe = DEDUPE_ON_SUBSCRIBE; - const maximumCacheSize = DEDUPE_CACHE_SIZE; + let maximumCacheSize = DEDUPE_CACHE_SIZE; let useRequestId = USE_REQUEST_ID; // @ts-expect-error Not documented legacy configuration options. if (configurationCopy.dedupeOnSubscribe !== undefined && typeof configurationCopy.dedupeOnSubscribe === 'boolean') { @@ -146,6 +146,11 @@ const setDefaults = (configuration) => { dedupeOnSubscribe = configurationCopy.dedupeOnSubscribe; } // @ts-expect-error Not documented legacy configuration options. + if (configurationCopy.maximumCacheSize !== undefined && typeof configurationCopy.maximumCacheSize === 'number') { + // @ts-expect-error Not documented legacy configuration options. + maximumCacheSize = configurationCopy.maximumCacheSize; + } + // @ts-expect-error Not documented legacy configuration options. if (configurationCopy.useRequestId !== undefined && typeof configurationCopy.useRequestId === 'boolean') { // @ts-expect-error Not documented legacy configuration options. useRequestId = configurationCopy.useRequestId; diff --git a/lib/core/pubnub-common.js b/lib/core/pubnub-common.js index 26e8f95ee..988a5a186 100644 --- a/lib/core/pubnub-common.js +++ b/lib/core/pubnub-common.js @@ -1670,8 +1670,7 @@ class PubNubCore { * @returns Asynchronous memberships modification response or `void` in case if `callback` provided. * * @deprecated Use {@link PubNubCore#objects.removeMemberships} or {@link PubNubCore#objects.removeChannelMembers} - * methods instead - * from `objects` API group.. + * methods instead from `objects` API group. */ removeMemberships(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { diff --git a/lib/crypto/modules/NodeCryptoModule/nodeCryptoModule.js b/lib/crypto/modules/NodeCryptoModule/nodeCryptoModule.js index f2e389690..0b12321b5 100644 --- a/lib/crypto/modules/NodeCryptoModule/nodeCryptoModule.js +++ b/lib/crypto/modules/NodeCryptoModule/nodeCryptoModule.js @@ -15,7 +15,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); -exports.CryptoModule = exports.AesCbcCryptor = exports.LegacyCryptor = void 0; +exports.NodeCryptoModule = exports.AesCbcCryptor = exports.LegacyCryptor = void 0; const stream_1 = require("stream"); const buffer_1 = require("buffer"); const crypto_module_1 = require("../../../core/interfaces/crypto-module"); @@ -28,7 +28,7 @@ exports.LegacyCryptor = legacyCryptor_1.default; /** * CryptoModule for Node.js platform. */ -class CryptoModule extends crypto_module_1.AbstractCryptoModule { +class NodeCryptoModule extends crypto_module_1.AbstractCryptoModule { // -------------------------------------------------------- // --------------- Convenience functions ------------------ // ------------------------------------------------------- @@ -70,15 +70,15 @@ class CryptoModule extends crypto_module_1.AbstractCryptoModule { // region Encryption encrypt(data) { // Encrypt data. - const encrypted = data instanceof ArrayBuffer && this.defaultCryptor.identifier === CryptoModule.LEGACY_IDENTIFIER - ? this.defaultCryptor.encrypt(CryptoModule.decoder.decode(data)) + const encrypted = data instanceof ArrayBuffer && this.defaultCryptor.identifier === NodeCryptoModule.LEGACY_IDENTIFIER + ? this.defaultCryptor.encrypt(NodeCryptoModule.decoder.decode(data)) : this.defaultCryptor.encrypt(data); if (!encrypted.metadata) return encrypted.data; const headerData = this.getHeaderData(encrypted); // Write encrypted data payload content. const encryptedData = typeof encrypted.data === 'string' - ? CryptoModule.encoder.encode(encrypted.data).buffer + ? NodeCryptoModule.encoder.encode(encrypted.data).buffer : encrypted.data.buffer.slice(encrypted.data.byteOffset, encrypted.data.byteOffset + encrypted.data.length); return this.concatArrayBuffer(headerData, encryptedData); } @@ -95,7 +95,7 @@ class CryptoModule extends crypto_module_1.AbstractCryptoModule { return File.create({ name: file.name, mimeType: 'application/octet-stream', - data: buffer_1.Buffer.from(typeof encryptedData === 'string' ? CryptoModule.encoder.encode(encryptedData) : encryptedData), + data: buffer_1.Buffer.from(typeof encryptedData === 'string' ? NodeCryptoModule.encoder.encode(encryptedData) : encryptedData), }); } if (file.data instanceof stream_1.Readable) { @@ -151,7 +151,7 @@ class CryptoModule extends crypto_module_1.AbstractCryptoModule { * If It's legacy one then redirect it. * (as long as we support legacy need to check on instance type) */ - if ((cryptor === null || cryptor === void 0 ? void 0 : cryptor.identifier) === CryptoModule.LEGACY_IDENTIFIER) + if ((cryptor === null || cryptor === void 0 ? void 0 : cryptor.identifier) === NodeCryptoModule.LEGACY_IDENTIFIER) return cryptor.decryptFile(file, File); return File.create({ name: file.name, @@ -181,7 +181,7 @@ class CryptoModule extends crypto_module_1.AbstractCryptoModule { * @internal */ getLegacyCryptor() { - return this.getCryptorFromId(CryptoModule.LEGACY_IDENTIFIER); + return this.getCryptorFromId(NodeCryptoModule.LEGACY_IDENTIFIER); } /** * Retrieve registered cryptor by its identifier. @@ -325,11 +325,11 @@ class CryptoModule extends crypto_module_1.AbstractCryptoModule { }); } } -exports.CryptoModule = CryptoModule; +exports.NodeCryptoModule = NodeCryptoModule; /** * {@link LegacyCryptor|Legacy} cryptor identifier. */ -CryptoModule.LEGACY_IDENTIFIER = ''; +NodeCryptoModule.LEGACY_IDENTIFIER = ''; /** * CryptorHeader Utility * @@ -374,7 +374,7 @@ class CryptorHeader { if (encryptedData.byteLength >= 4) { sentinel = encryptedData.slice(0, 4); if (!this.isSentinel(sentinel)) - return CryptoModule.LEGACY_IDENTIFIER; + return NodeCryptoModule.LEGACY_IDENTIFIER; } if (encryptedData.byteLength >= 5) version = encryptedDataView.getInt8(4); diff --git a/lib/errors/pubnub-error.js b/lib/errors/pubnub-error.js index b4ed5057d..3d30c79ac 100644 --- a/lib/errors/pubnub-error.js +++ b/lib/errors/pubnub-error.js @@ -1,8 +1,6 @@ "use strict"; /** * PubNub operation error module. - * - * @internal */ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; diff --git a/lib/node/index.js b/lib/node/index.js index 6c8be2883..bd2eb87c7 100644 --- a/lib/node/index.js +++ b/lib/node/index.js @@ -38,7 +38,7 @@ class PubNub extends pubnub_common_1.PubNubCore { if (!cryptoConfiguration.cipherKey) return undefined; if (process.env.CRYPTO_MODULE !== 'disabled') { - return new nodeCryptoModule_1.CryptoModule({ + return new nodeCryptoModule_1.NodeCryptoModule({ default: new nodeCryptoModule_1.LegacyCryptor(Object.assign({}, cryptoConfiguration)), cryptors: [new nodeCryptoModule_1.AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })], }); @@ -106,5 +106,5 @@ class PubNub extends pubnub_common_1.PubNubCore { * Data encryption / decryption module constructor. */ // @ts-expect-error Allowed to simplify interface when module can be disabled. -PubNub.CryptoModule = process.env.CRYPTO_MODULE !== 'disabled' ? nodeCryptoModule_1.CryptoModule : undefined; +PubNub.CryptoModule = process.env.CRYPTO_MODULE !== 'disabled' ? nodeCryptoModule_1.NodeCryptoModule : undefined; module.exports = PubNub; diff --git a/lib/transport/web-react-native-transport.js b/lib/transport/web-react-native-transport.js index 386d27779..53ce793f6 100644 --- a/lib/transport/web-react-native-transport.js +++ b/lib/transport/web-react-native-transport.js @@ -62,7 +62,10 @@ class WebReactNativeTransport { reject(new Error('Request timeout')); }, req.timeout * 1000); }); - return Promise.race([fetch(request, { signal: abortController === null || abortController === void 0 ? void 0 : abortController.signal }), requestTimeout]) + return Promise.race([ + fetch(request, { signal: abortController === null || abortController === void 0 ? void 0 : abortController.signal, credentials: 'omit', cache: 'no-cache' }), + requestTimeout, + ]) .then((response) => response.arrayBuffer().then((arrayBuffer) => [response, arrayBuffer])) .then((response) => { const responseBody = response[1].byteLength > 0 ? response[1] : undefined; diff --git a/lib/types/cbor/common.d.ts b/lib/types/cbor/common.d.ts deleted file mode 100644 index 760c25f31..000000000 --- a/lib/types/cbor/common.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Cbor decoder module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/components/abort_signal.d.ts b/lib/types/core/components/abort_signal.d.ts deleted file mode 100644 index 9fe047fba..000000000 --- a/lib/types/core/components/abort_signal.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -/** - * Event Engine managed effects terminate signal module. - * - * @internal - */ -export declare class AbortError extends Error { - name: string; - constructor(); -} diff --git a/lib/types/core/components/base64_codec.d.ts b/lib/types/core/components/base64_codec.d.ts deleted file mode 100644 index 3278e499f..000000000 --- a/lib/types/core/components/base64_codec.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Base64 support module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/components/configuration.d.ts b/lib/types/core/components/configuration.d.ts deleted file mode 100644 index 7b9e09346..000000000 --- a/lib/types/core/components/configuration.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * {@link PubNub} client configuration module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/components/cryptography/hmac-sha256.d.ts b/lib/types/core/components/cryptography/hmac-sha256.d.ts deleted file mode 100644 index 112f25199..000000000 --- a/lib/types/core/components/cryptography/hmac-sha256.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -export namespace mode { - let ECB: any; -} diff --git a/lib/types/core/components/cryptography/index.d.ts b/lib/types/core/components/cryptography/index.d.ts deleted file mode 100644 index 5b1e412b9..000000000 --- a/lib/types/core/components/cryptography/index.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Legacy cryptography module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/components/deduping_manager.d.ts b/lib/types/core/components/deduping_manager.d.ts deleted file mode 100644 index 1dacf8d48..000000000 --- a/lib/types/core/components/deduping_manager.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Messages de-duplication manager module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/components/eventEmitter.d.ts b/lib/types/core/components/eventEmitter.d.ts deleted file mode 100644 index 8a5e59643..000000000 --- a/lib/types/core/components/eventEmitter.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Real-time events emitter module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/components/listener_manager.d.ts b/lib/types/core/components/listener_manager.d.ts deleted file mode 100644 index 054904377..000000000 --- a/lib/types/core/components/listener_manager.d.ts +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Events listener manager module. - */ -import * as Subscription from '../types/api/subscription'; -import { Status, StatusEvent } from '../types/api'; -/** - * Real-time events listener. - */ -export type Listener = { - /** - * Real-time message events listener. - * - * @param message - Received message. - */ - message?: (message: Subscription.Message) => void; - /** - * Real-time message signal listener. - * - * @param signal - Received signal. - */ - signal?: (signal: Subscription.Signal) => void; - /** - * Real-time presence change events listener. - * - * @param presence - Received presence chane information. - */ - presence?: (presence: Subscription.Presence) => void; - /** - * Real-time App Context Objects change events listener. - * - * @param object - Changed App Context Object information. - */ - objects?: (object: Subscription.AppContextObject) => void; - /** - * Real-time message actions events listener. - * - * @param action - Message action information. - */ - messageAction?: (action: Subscription.MessageAction) => void; - /** - * Real-time file share events listener. - * - * @param file - Shared file information. - */ - file?: (file: Subscription.File) => void; - /** - * Real-time PubNub client status change event. - * - * @param status - PubNub client status information - */ - status?: (status: Status | StatusEvent) => void; - /** - * Real-time User App Context Objects change events listener. - * - * @param user - User App Context Object information. - * - * @deprecated Use {@link objects} listener callback instead. - */ - user?: (user: Subscription.UserAppContextObject) => void; - /** - * Real-time Space App Context Objects change events listener. - * - * @param space - Space App Context Object information. - * - * @deprecated Use {@link objects} listener callback instead. - */ - space?: (space: Subscription.SpaceAppContextObject) => void; - /** - * Real-time VSP Membership App Context Objects change events listener. - * - * @param membership - VSP Membership App Context Object information. - * - * @deprecated Use {@link objects} listener callback instead. - */ - membership?: (membership: Subscription.VSPMembershipAppContextObject) => void; -}; diff --git a/lib/types/core/components/push_payload.d.ts b/lib/types/core/components/push_payload.d.ts deleted file mode 100644 index 3e58c0246..000000000 --- a/lib/types/core/components/push_payload.d.ts +++ /dev/null @@ -1,543 +0,0 @@ -/** - * Payload for `pn_apns` field in published message. - */ -type APNSPayload = { - /** - * Payload for Apple Push Notification Service. - */ - aps: { - /** - * Configuration of visual notification representation. - */ - alert?: { - /** - * First line title. - * - * Title which is shown in bold on the first line of notification bubble. - */ - title?: string; - /** - * Second line title. - * - * Subtitle which is shown under main title with smaller font. - */ - subtitle?: string; - /** - * Notification body. - * - * Body which is shown to the user after interaction with notification. - */ - body?: string; - }; - /** - * Unread notifications count badge value. - */ - badge?: number | null; - /** - * Name of the file from resource bundle which should be played when notification received. - */ - sound?: string; - /** - * Silent notification flag. - */ - 'content-available'?: 1; - }; - /** - * APNS2 payload recipients information. - */ - pn_push: PubNubAPNS2Configuration[]; -}; -/** - * APNS2 configuration type. - */ -type APNS2Configuration = { - /** - * Notification group / collapse identifier. Value will be used in APNS POST request as `apns-collapse-id` header - * value. - */ - collapseId?: string; - /** - * Date till which APNS will try to deliver notification to target device. Value will be used in APNS POST request as - * `apns-expiration` header value. - */ - expirationDate?: Date; - /** - * List of topics which should receive this notification. - */ - targets: APNS2Target[]; -}; -/** - * Preformatted for PubNub service `APNS2` configuration type. - */ -type PubNubAPNS2Configuration = { - /** - * PubNub service authentication method for APNS. - */ - auth_method: 'token'; - /** - * Target entities which should receive notification. - */ - targets: PubNubAPNS2Target[]; - /** - * Notifications group collapse identifier. - */ - collapse_id?: string; - /** - * Notification receive expiration date. - * - * Date after which notification won't be delivered. - */ - expiration?: string; - /** - * APNS protocol version. - */ - version: 'v2'; -}; -/** - * APNS2 configuration target type. - */ -type APNS2Target = { - /** - * Notifications topic name (usually it is bundle identifier of application for Apple platform). - * - * **Important:** Required only if `pushGateway` is set to `apns2`. - */ - topic: string; - /** - * Environment within which registered devices to which notifications should be delivered. - * - * Available: - * - `development` - * - `production` - * - * @default `development` - */ - environment?: 'development' | 'production'; - /** - * List of devices (their push tokens) to which this notification shouldn't be delivered. - */ - excludedDevices?: string[]; -}; -/** - * Preformatted for PubNub service `APNS2` configuration target type. - */ -type PubNubAPNS2Target = Omit & { - /** - * List of devices (their push tokens) to which this notification shouldn't be delivered. - */ - excluded_devices?: string[]; -}; -/** - * Payload for `pn_gcm` field in published message. - */ -type FCMPayload = { - /** - * Configuration of visual notification representation. - */ - notification?: { - /** - * First line title. - * - * Title which is shown in bold on the first line of notification bubble. - */ - title?: string; - /** - * Notification body. - * - * Body which is shown to the user after interaction with notification. - */ - body?: string; - /** - * Name of the icon file from resource bundle which should be shown on notification. - */ - icon?: string; - /** - * Name of the file from resource bundle which should be played when notification received. - */ - sound?: string; - tag?: string; - }; - /** - * Configuration of data notification. - * - * Silent notification configuration. - */ - data?: { - notification?: FCMPayload['notification']; - }; -}; -/** - * Base notification payload object. - */ -declare class BaseNotificationPayload { - /** - * Retrieve resulting notification payload content for message. - * - * @returns Preformatted push notification payload data. - */ - get payload(): unknown; - /** - * Update notification title. - * - * @param value - New notification title. - */ - set title(value: string | undefined); - /** - * Update notification subtitle. - * - * @param value - New second-line notification title. - */ - set subtitle(value: string | undefined); - /** - * Update notification body. - * - * @param value - Update main notification message (shown when expanded). - */ - set body(value: string | undefined); - /** - * Update application badge number. - * - * @param value - Number which should be shown in application badge upon receiving notification. - */ - set badge(value: number | null | undefined); - /** - * Update notification sound. - * - * @param value - Name of the sound file which should be played upon notification receive. - */ - set sound(value: string | undefined); -} -/** - * Message payload for Apple Push Notification Service. - */ -export declare class APNSNotificationPayload extends BaseNotificationPayload { - get payload(): APNSPayload; - /** - * Update notification receivers configuration. - * - * @param value - New APNS2 configurations. - */ - set configurations(value: APNS2Configuration[]); - /** - * Notification payload. - * - * @returns Platform-specific part of PubNub notification payload. - */ - get notification(): { - /** - * Configuration of visual notification representation. - */ - alert?: { - /** - * First line title. - * - * Title which is shown in bold on the first line of notification bubble. - */ - title?: string | undefined; - /** - * Second line title. - * - * Subtitle which is shown under main title with smaller font. - */ - subtitle?: string | undefined; - /** - * Notification body. - * - * Body which is shown to the user after interaction with notification. - */ - body?: string | undefined; - } | undefined; - /** - * Unread notifications count badge value. - */ - badge?: number | null | undefined; - /** - * Name of the file from resource bundle which should be played when notification received. - */ - sound?: string | undefined; - /** - * Silent notification flag. - */ - 'content-available'?: 1 | undefined; - }; - /** - * Notification title. - * - * @returns Main notification title. - */ - get title(): string | undefined; - /** - * Update notification title. - * - * @param value - New notification title. - */ - set title(value: string | undefined); - /** - * Notification subtitle. - * - * @returns Second-line notification title. - */ - get subtitle(): string | undefined; - /** - * Update notification subtitle. - * - * @param value - New second-line notification title. - */ - set subtitle(value: string | undefined); - /** - * Notification body. - * - * @returns Main notification message (shown when expanded). - */ - get body(): string | undefined; - /** - * Update notification body. - * - * @param value - Update main notification message (shown when expanded). - */ - set body(value: string | undefined); - /** - * Retrieve unread notifications number. - * - * @returns Number of unread notifications which should be shown on application badge. - */ - get badge(): number | null | undefined; - /** - * Update application badge number. - * - * @param value - Number which should be shown in application badge upon receiving notification. - */ - set badge(value: number | null | undefined); - /** - * Retrieve notification sound file. - * - * @returns Notification sound file name from resource bundle. - */ - get sound(): string | undefined; - /** - * Update notification sound. - * - * @param value - Name of the sound file which should be played upon notification receive. - */ - set sound(value: string | undefined); - /** - * Set whether notification should be silent or not. - * - * `content-available` notification type will be used to deliver silent notification if set to `true`. - * - * @param value - Whether notification should be sent as silent or not. - */ - set silent(value: boolean); -} -/** - * Message payload for Firebase Clouse Messaging service. - */ -export declare class FCMNotificationPayload extends BaseNotificationPayload { - get payload(): FCMPayload; - /** - * Notification payload. - * - * @returns Platform-specific part of PubNub notification payload. - */ - get notification(): { - /** - * First line title. - * - * Title which is shown in bold on the first line of notification bubble. - */ - title?: string | undefined; - /** - * Notification body. - * - * Body which is shown to the user after interaction with notification. - */ - body?: string | undefined; - /** - * Name of the icon file from resource bundle which should be shown on notification. - */ - icon?: string | undefined; - /** - * Name of the file from resource bundle which should be played when notification received. - */ - sound?: string | undefined; - tag?: string | undefined; - } | undefined; - /** - * Silent notification payload. - * - * @returns Silent notification payload (data notification). - */ - get data(): { - notification?: { - /** - * First line title. - * - * Title which is shown in bold on the first line of notification bubble. - */ - title?: string | undefined; - /** - * Notification body. - * - * Body which is shown to the user after interaction with notification. - */ - body?: string | undefined; - /** - * Name of the icon file from resource bundle which should be shown on notification. - */ - icon?: string | undefined; - /** - * Name of the file from resource bundle which should be played when notification received. - */ - sound?: string | undefined; - tag?: string | undefined; - } | undefined; - } | undefined; - /** - * Notification title. - * - * @returns Main notification title. - */ - get title(): string | undefined; - /** - * Update notification title. - * - * @param value - New notification title. - */ - set title(value: string | undefined); - /** - * Notification body. - * - * @returns Main notification message (shown when expanded). - */ - get body(): string | undefined; - /** - * Update notification body. - * - * @param value - Update main notification message (shown when expanded). - */ - set body(value: string | undefined); - /** - * Retrieve notification sound file. - * - * @returns Notification sound file name from resource bundle. - */ - get sound(): string | undefined; - /** - * Update notification sound. - * - * @param value - Name of the sound file which should be played upon notification receive. - */ - set sound(value: string | undefined); - /** - * Retrieve notification icon file. - * - * @returns Notification icon file name from resource bundle. - */ - get icon(): string | undefined; - /** - * Update notification icon. - * - * @param value - Name of the icon file which should be shown on notification. - */ - set icon(value: string | undefined); - /** - * Retrieve notifications grouping tag. - * - * @returns Notifications grouping tag. - */ - get tag(): string | undefined; - /** - * Update notifications grouping tag. - * - * @param value - String which will be used to group similar notifications in notification center. - */ - set tag(value: string | undefined); - /** - * Set whether notification should be silent or not. - * - * All notification data will be sent under `data` field if set to `true`. - * - * @param value - Whether notification should be sent as silent or not. - */ - set silent(value: boolean); -} -declare class NotificationsPayload { - /** - * APNS-specific message payload. - */ - apns: APNSNotificationPayload; - /** - * FCM-specific message payload. - */ - fcm: FCMNotificationPayload; - /** - * Enable or disable push notification debugging message. - * - * @param value - Whether debug message from push notification scheduler should be published to the specific - * channel or not. - */ - set debugging(value: boolean); - /** - * Notification title. - * - * @returns Main notification title. - */ - get title(): string; - /** - * Notification subtitle. - * - * @returns Second-line notification title. - */ - get subtitle(): string | undefined; - /** - * Update notification subtitle. - * - * @param value - New second-line notification title. - */ - set subtitle(value: string | undefined); - /** - * Notification body. - * - * @returns Main notification message (shown when expanded). - */ - get body(): string; - /** - * Retrieve unread notifications number. - * - * @returns Number of unread notifications which should be shown on application badge. - */ - get badge(): number | undefined; - /** - * Update application badge number. - * - * @param value - Number which should be shown in application badge upon receiving notification. - */ - set badge(value: number | undefined); - /** - * Retrieve notification sound file. - * - * @returns Notification sound file name from resource bundle. - */ - get sound(): string | undefined; - /** - * Update notification sound. - * - * @param value - Name of the sound file which should be played upon notification receive. - */ - set sound(value: string | undefined); - /** - * Build notifications platform for requested platforms. - * - * @param platforms - List of platforms for which payload should be added to final dictionary. Supported values: - * fcm, apns, and apns2. - * - * @returns Object with data, which can be sent with publish method call and trigger remote notifications for - * specified platforms. - */ - buildPayload(platforms: ('apns' | 'apns2' | 'fcm')[]): { - pn_apns?: APNSPayload | undefined; - pn_gcm?: FCMPayload | undefined; - pn_debug?: boolean | undefined; - }; -} -export default NotificationsPayload; diff --git a/lib/types/core/components/reconnection_manager.d.ts b/lib/types/core/components/reconnection_manager.d.ts deleted file mode 100644 index c6ba75bab..000000000 --- a/lib/types/core/components/reconnection_manager.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -/** - * Subscription reconnection-manager. - * - * **Note:** Reconnection manger rely on legacy time-based availability check. - * - * @internal - */ -export {}; diff --git a/lib/types/core/components/request.d.ts b/lib/types/core/components/request.d.ts deleted file mode 100644 index ce267e635..000000000 --- a/lib/types/core/components/request.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Network request module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/components/stringify_buffer_keys.d.ts b/lib/types/core/components/stringify_buffer_keys.d.ts deleted file mode 100644 index 0d3101543..000000000 --- a/lib/types/core/components/stringify_buffer_keys.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * CBOR support module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/components/subject.d.ts b/lib/types/core/components/subject.d.ts deleted file mode 100644 index b9f1e5b5d..000000000 --- a/lib/types/core/components/subject.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Event Engine terminate signal listener module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/components/subscription-manager.d.ts b/lib/types/core/components/subscription-manager.d.ts deleted file mode 100644 index 26783389e..000000000 --- a/lib/types/core/components/subscription-manager.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Subscription manager module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/components/token_manager.d.ts b/lib/types/core/components/token_manager.d.ts deleted file mode 100644 index bfd6ab89f..000000000 --- a/lib/types/core/components/token_manager.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * PubNub Access Token Manager module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/components/uuid.d.ts b/lib/types/core/components/uuid.d.ts deleted file mode 100644 index 5b90c8c3d..000000000 --- a/lib/types/core/components/uuid.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Random identifier generator helper module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/constants/categories.d.ts b/lib/types/core/constants/categories.d.ts deleted file mode 100644 index bc372ba22..000000000 --- a/lib/types/core/constants/categories.d.ts +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Request processing status categories. - */ -declare enum StatusCategory { - /** - * Call failed when network was unable to complete the call. - */ - PNNetworkIssuesCategory = "PNNetworkIssuesCategory", - /** - * Network call timed out. - */ - PNTimeoutCategory = "PNTimeoutCategory", - /** - * Request has been cancelled. - */ - PNCancelledCategory = "PNCancelledCategory", - /** - * Server responded with bad response. - */ - PNBadRequestCategory = "PNBadRequestCategory", - /** - * Server responded with access denied. - */ - PNAccessDeniedCategory = "PNAccessDeniedCategory", - /** - * Incomplete parameters provided for used endpoint. - */ - PNValidationErrorCategory = "PNValidationErrorCategory", - /** - * PubNub request acknowledgment status. - * - * Some API endpoints respond with request processing status w/o useful data. - */ - PNAcknowledgmentCategory = "PNAcknowledgmentCategory", - /** - * Something strange happened; please check the logs. - */ - PNUnknownCategory = "PNUnknownCategory", - /** - * SDK will announce when the network appears to be connected again. - */ - PNNetworkUpCategory = "PNNetworkUpCategory", - /** - * SDK will announce when the network appears to down. - */ - PNNetworkDownCategory = "PNNetworkDownCategory", - /** - * PubNub client reconnected to the real-time updates stream. - */ - PNReconnectedCategory = "PNReconnectedCategory", - /** - * PubNub client connected to the real-time updates stream. - */ - PNConnectedCategory = "PNConnectedCategory", - /** - * Received real-time updates exceed specified threshold. - * - * After temporary disconnection and catchup, this category means that potentially some - * real-time updates have been pushed into `storage` and need to be requested separately. - */ - PNRequestMessageCountExceededCategory = "PNRequestMessageCountExceededCategory", - /** - * PubNub client disconnected from the real-time updates streams. - */ - PNDisconnectedCategory = "PNDisconnectedCategory", - /** - * PubNub client wasn't able to connect to the real-time updates streams. - */ - PNConnectionErrorCategory = "PNConnectionErrorCategory", - /** - * PubNub client unexpectedly disconnected from the real-time updates streams. - */ - PNDisconnectedUnexpectedlyCategory = "PNDisconnectedUnexpectedlyCategory" -} -export default StatusCategory; diff --git a/lib/types/core/constants/operations.d.ts b/lib/types/core/constants/operations.d.ts deleted file mode 100644 index da958bd22..000000000 --- a/lib/types/core/constants/operations.d.ts +++ /dev/null @@ -1,204 +0,0 @@ -/** - * Endpoint API operation types. - */ -declare enum RequestOperation { - /** - * Data publish REST API operation. - */ - PNPublishOperation = "PNPublishOperation", - /** - * Signal sending REST API operation. - */ - PNSignalOperation = "PNSignalOperation", - /** - * Subscribe for real-time updates REST API operation. - * - * User's presence change on specified entities will trigger `join` event. - */ - PNSubscribeOperation = "PNSubscribeOperation", - /** - * Unsubscribe from real-time updates REST API operation. - * - * User's presence change on specified entities will trigger `leave` event. - */ - PNUnsubscribeOperation = "PNUnsubscribeOperation", - /** - * Fetch user's presence information REST API operation. - */ - PNWhereNowOperation = "PNWhereNowOperation", - /** - * Fetch channel's presence information REST API operation. - */ - PNHereNowOperation = "PNHereNowOperation", - /** - * Fetch global presence information REST API operation. - */ - PNGlobalHereNowOperation = "PNGlobalHereNowOperation", - /** - * Update user's information associated with specified channel REST API operation. - */ - PNSetStateOperation = "PNSetStateOperation", - /** - * Fetch user's information associated with the specified channel REST API operation. - */ - PNGetStateOperation = "PNGetStateOperation", - /** - * Announce presence on managed channels REST API operation. - */ - PNHeartbeatOperation = "PNHeartbeatOperation", - /** - * Add a reaction to the specified message REST API operation. - */ - PNAddMessageActionOperation = "PNAddActionOperation", - /** - * Remove reaction from the specified message REST API operation. - */ - PNRemoveMessageActionOperation = "PNRemoveMessageActionOperation", - /** - * Fetch reactions for specific message REST API operation. - */ - PNGetMessageActionsOperation = "PNGetMessageActionsOperation", - PNTimeOperation = "PNTimeOperation", - /** - * Channel history REST API operation. - */ - PNHistoryOperation = "PNHistoryOperation", - /** - * Delete messages from channel history REST API operation. - */ - PNDeleteMessagesOperation = "PNDeleteMessagesOperation", - /** - * History for channels REST API operation. - */ - PNFetchMessagesOperation = "PNFetchMessagesOperation", - /** - * Number of messages for channels in specified time frame REST API operation. - */ - PNMessageCounts = "PNMessageCountsOperation", - /** - * Fetch users metadata REST API operation. - */ - PNGetAllUUIDMetadataOperation = "PNGetAllUUIDMetadataOperation", - /** - * Fetch user metadata REST API operation. - */ - PNGetUUIDMetadataOperation = "PNGetUUIDMetadataOperation", - /** - * Set user metadata REST API operation. - */ - PNSetUUIDMetadataOperation = "PNSetUUIDMetadataOperation", - /** - * Remove user metadata REST API operation. - */ - PNRemoveUUIDMetadataOperation = "PNRemoveUUIDMetadataOperation", - /** - * Fetch channels metadata REST API operation. - */ - PNGetAllChannelMetadataOperation = "PNGetAllChannelMetadataOperation", - /** - * Fetch channel metadata REST API operation. - */ - PNGetChannelMetadataOperation = "PNGetChannelMetadataOperation", - /** - * Set channel metadata REST API operation. - */ - PNSetChannelMetadataOperation = "PNSetChannelMetadataOperation", - /** - * Remove channel metadata REST API operation. - */ - PNRemoveChannelMetadataOperation = "PNRemoveChannelMetadataOperation", - /** - * Fetch channel members REST API operation. - */ - PNGetMembersOperation = "PNGetMembersOperation", - /** - * Update channel members REST API operation. - */ - PNSetMembersOperation = "PNSetMembersOperation", - /** - * Fetch channel memberships REST API operation. - */ - PNGetMembershipsOperation = "PNGetMembershipsOperation", - /** - * Update channel memberships REST API operation. - */ - PNSetMembershipsOperation = "PNSetMembershipsOperation", - /** - * Fetch list of files sent to the channel REST API operation. - */ - PNListFilesOperation = "PNListFilesOperation", - /** - * Retrieve file upload URL REST API operation. - */ - PNGenerateUploadUrlOperation = "PNGenerateUploadUrlOperation", - /** - * Upload file to the channel REST API operation. - */ - PNPublishFileOperation = "PNPublishFileOperation", - /** - * Publish File Message to the channel REST API operation. - */ - PNPublishFileMessageOperation = "PNPublishFileMessageOperation", - /** - * Retrieve file download URL REST API operation. - */ - PNGetFileUrlOperation = "PNGetFileUrlOperation", - /** - * Download file from the channel REST API operation. - */ - PNDownloadFileOperation = "PNDownloadFileOperation", - /** - * Delete file sent to the channel REST API operation. - */ - PNDeleteFileOperation = "PNDeleteFileOperation", - /** - * Register channels with device push notifications REST API operation. - */ - PNAddPushNotificationEnabledChannelsOperation = "PNAddPushNotificationEnabledChannelsOperation", - /** - * Unregister channels with device push notifications REST API operation. - */ - PNRemovePushNotificationEnabledChannelsOperation = "PNRemovePushNotificationEnabledChannelsOperation", - /** - * Fetch list of channels with enabled push notifications for device REST API operation. - */ - PNPushNotificationEnabledChannelsOperation = "PNPushNotificationEnabledChannelsOperation", - /** - * Disable push notifications for device REST API operation. - */ - PNRemoveAllPushNotificationsOperation = "PNRemoveAllPushNotificationsOperation", - /** - * Fetch channels groups list REST API operation. - */ - PNChannelGroupsOperation = "PNChannelGroupsOperation", - /** - * Remove specified channel group REST API operation. - */ - PNRemoveGroupOperation = "PNRemoveGroupOperation", - /** - * Fetch list of channels for the specified channel group REST API operation. - */ - PNChannelsForGroupOperation = "PNChannelsForGroupOperation", - /** - * Add list of channels to the specified channel group REST API operation. - */ - PNAddChannelsToGroupOperation = "PNAddChannelsToGroupOperation", - /** - * Remove list of channels from the specified channel group REST API operation. - */ - PNRemoveChannelsFromGroupOperation = "PNRemoveChannelsFromGroupOperation", - /** - * Generate authorized token REST API operation. - */ - PNAccessManagerGrant = "PNAccessManagerGrant", - /** - * Generate authorized token REST API operation. - */ - PNAccessManagerGrantToken = "PNAccessManagerGrantToken", - PNAccessManagerAudit = "PNAccessManagerAudit", - /** - * Revoke authorized token REST API operation. - */ - PNAccessManagerRevokeToken = "PNAccessManagerRevokeToken" -} -export default RequestOperation; diff --git a/lib/types/core/endpoints/access_manager/audit.d.ts b/lib/types/core/endpoints/access_manager/audit.d.ts deleted file mode 100644 index bdff1fc95..000000000 --- a/lib/types/core/endpoints/access_manager/audit.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * PAM Audit REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/access_manager/grant.d.ts b/lib/types/core/endpoints/access_manager/grant.d.ts deleted file mode 100644 index 6ec06a085..000000000 --- a/lib/types/core/endpoints/access_manager/grant.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * PAM Grant REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/access_manager/grant_token.d.ts b/lib/types/core/endpoints/access_manager/grant_token.d.ts deleted file mode 100644 index d6d836532..000000000 --- a/lib/types/core/endpoints/access_manager/grant_token.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * PAM Grant Token REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/access_manager/revoke_token.d.ts b/lib/types/core/endpoints/access_manager/revoke_token.d.ts deleted file mode 100644 index 184fde3d2..000000000 --- a/lib/types/core/endpoints/access_manager/revoke_token.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * PAM Revoke Token REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/actions/add_message_action.d.ts b/lib/types/core/endpoints/actions/add_message_action.d.ts deleted file mode 100644 index 05cc3b940..000000000 --- a/lib/types/core/endpoints/actions/add_message_action.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Add Message Action REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/actions/get_message_actions.d.ts b/lib/types/core/endpoints/actions/get_message_actions.d.ts deleted file mode 100644 index b05917221..000000000 --- a/lib/types/core/endpoints/actions/get_message_actions.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Get Message Actions REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/actions/remove_message_action.d.ts b/lib/types/core/endpoints/actions/remove_message_action.d.ts deleted file mode 100644 index 8fcd31e7a..000000000 --- a/lib/types/core/endpoints/actions/remove_message_action.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Remove Message Action REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/channel_groups/add_channels.d.ts b/lib/types/core/endpoints/channel_groups/add_channels.d.ts deleted file mode 100644 index 81a171868..000000000 --- a/lib/types/core/endpoints/channel_groups/add_channels.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Add channel group channels REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/channel_groups/delete_group.d.ts b/lib/types/core/endpoints/channel_groups/delete_group.d.ts deleted file mode 100644 index 4f6387f4c..000000000 --- a/lib/types/core/endpoints/channel_groups/delete_group.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Delete channel group REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/channel_groups/list_channels.d.ts b/lib/types/core/endpoints/channel_groups/list_channels.d.ts deleted file mode 100644 index 66c446a58..000000000 --- a/lib/types/core/endpoints/channel_groups/list_channels.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * List channel group channels REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/channel_groups/list_groups.d.ts b/lib/types/core/endpoints/channel_groups/list_groups.d.ts deleted file mode 100644 index 171b98547..000000000 --- a/lib/types/core/endpoints/channel_groups/list_groups.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * List All Channel Groups REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/channel_groups/remove_channels.d.ts b/lib/types/core/endpoints/channel_groups/remove_channels.d.ts deleted file mode 100644 index ec38ab5e3..000000000 --- a/lib/types/core/endpoints/channel_groups/remove_channels.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Remove channel group channels REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/fetch_messages.d.ts b/lib/types/core/endpoints/fetch_messages.d.ts deleted file mode 100644 index 136a31fcb..000000000 --- a/lib/types/core/endpoints/fetch_messages.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Fetch messages REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/file_upload/delete_file.d.ts b/lib/types/core/endpoints/file_upload/delete_file.d.ts deleted file mode 100644 index 9ee935ebd..000000000 --- a/lib/types/core/endpoints/file_upload/delete_file.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Delete file REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/file_upload/download_file.d.ts b/lib/types/core/endpoints/file_upload/download_file.d.ts deleted file mode 100644 index c6337079a..000000000 --- a/lib/types/core/endpoints/file_upload/download_file.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Download File REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/file_upload/generate_upload_url.d.ts b/lib/types/core/endpoints/file_upload/generate_upload_url.d.ts deleted file mode 100644 index f42250bde..000000000 --- a/lib/types/core/endpoints/file_upload/generate_upload_url.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Generate file upload URL REST API request. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/file_upload/get_file_url.d.ts b/lib/types/core/endpoints/file_upload/get_file_url.d.ts deleted file mode 100644 index 8049bf162..000000000 --- a/lib/types/core/endpoints/file_upload/get_file_url.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * File sharing REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/file_upload/list_files.d.ts b/lib/types/core/endpoints/file_upload/list_files.d.ts deleted file mode 100644 index 44723ab7b..000000000 --- a/lib/types/core/endpoints/file_upload/list_files.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * List Files REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/file_upload/publish_file.d.ts b/lib/types/core/endpoints/file_upload/publish_file.d.ts deleted file mode 100644 index 2f3ec1f75..000000000 --- a/lib/types/core/endpoints/file_upload/publish_file.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Publish File Message REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/file_upload/send_file.d.ts b/lib/types/core/endpoints/file_upload/send_file.d.ts deleted file mode 100644 index bd94883b6..000000000 --- a/lib/types/core/endpoints/file_upload/send_file.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Share File API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/file_upload/upload-file.d.ts b/lib/types/core/endpoints/file_upload/upload-file.d.ts deleted file mode 100644 index 904240440..000000000 --- a/lib/types/core/endpoints/file_upload/upload-file.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Upload file REST API request. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/history/delete_messages.d.ts b/lib/types/core/endpoints/history/delete_messages.d.ts deleted file mode 100644 index f1235dabd..000000000 --- a/lib/types/core/endpoints/history/delete_messages.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Delete messages REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/history/get_history.d.ts b/lib/types/core/endpoints/history/get_history.d.ts deleted file mode 100644 index ec6f80599..000000000 --- a/lib/types/core/endpoints/history/get_history.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Get history REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/history/message_counts.d.ts b/lib/types/core/endpoints/history/message_counts.d.ts deleted file mode 100644 index c244dd6b6..000000000 --- a/lib/types/core/endpoints/history/message_counts.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Messages count REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/objects/channel/get.d.ts b/lib/types/core/endpoints/objects/channel/get.d.ts deleted file mode 100644 index 204439b20..000000000 --- a/lib/types/core/endpoints/objects/channel/get.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Get Channel Metadata REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/objects/channel/get_all.d.ts b/lib/types/core/endpoints/objects/channel/get_all.d.ts deleted file mode 100644 index 44b014bbf..000000000 --- a/lib/types/core/endpoints/objects/channel/get_all.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Get All Channel Metadata REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/objects/channel/remove.d.ts b/lib/types/core/endpoints/objects/channel/remove.d.ts deleted file mode 100644 index 004ef984a..000000000 --- a/lib/types/core/endpoints/objects/channel/remove.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Remove Channel Metadata REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/objects/channel/set.d.ts b/lib/types/core/endpoints/objects/channel/set.d.ts deleted file mode 100644 index 02a9ac78b..000000000 --- a/lib/types/core/endpoints/objects/channel/set.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Set Channel Metadata REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/objects/member/get.d.ts b/lib/types/core/endpoints/objects/member/get.d.ts deleted file mode 100644 index 8a27f494b..000000000 --- a/lib/types/core/endpoints/objects/member/get.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Get Channel Members REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/objects/member/set.d.ts b/lib/types/core/endpoints/objects/member/set.d.ts deleted file mode 100644 index b7cc3e799..000000000 --- a/lib/types/core/endpoints/objects/member/set.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Set Channel Members REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/objects/membership/get.d.ts b/lib/types/core/endpoints/objects/membership/get.d.ts deleted file mode 100644 index f789b877a..000000000 --- a/lib/types/core/endpoints/objects/membership/get.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Get UUID Memberships REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/objects/membership/set.d.ts b/lib/types/core/endpoints/objects/membership/set.d.ts deleted file mode 100644 index deab13f88..000000000 --- a/lib/types/core/endpoints/objects/membership/set.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Set UUID Memberships REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/objects/uuid/get.d.ts b/lib/types/core/endpoints/objects/uuid/get.d.ts deleted file mode 100644 index 12ac24a90..000000000 --- a/lib/types/core/endpoints/objects/uuid/get.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Get UUID Metadata REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/objects/uuid/get_all.d.ts b/lib/types/core/endpoints/objects/uuid/get_all.d.ts deleted file mode 100644 index d0ac3daa1..000000000 --- a/lib/types/core/endpoints/objects/uuid/get_all.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Get All UUID Metadata REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/objects/uuid/remove.d.ts b/lib/types/core/endpoints/objects/uuid/remove.d.ts deleted file mode 100644 index 9bdcdc4b5..000000000 --- a/lib/types/core/endpoints/objects/uuid/remove.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Remove UUID Metadata REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/objects/uuid/set.d.ts b/lib/types/core/endpoints/objects/uuid/set.d.ts deleted file mode 100644 index 6f91aea70..000000000 --- a/lib/types/core/endpoints/objects/uuid/set.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Set UUID Metadata REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/presence/get_state.d.ts b/lib/types/core/endpoints/presence/get_state.d.ts deleted file mode 100644 index 9e3d9ff6f..000000000 --- a/lib/types/core/endpoints/presence/get_state.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Get Presence State REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/presence/heartbeat.d.ts b/lib/types/core/endpoints/presence/heartbeat.d.ts deleted file mode 100644 index 3ee062597..000000000 --- a/lib/types/core/endpoints/presence/heartbeat.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Announce heartbeat REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/presence/here_now.d.ts b/lib/types/core/endpoints/presence/here_now.d.ts deleted file mode 100644 index aec1bc377..000000000 --- a/lib/types/core/endpoints/presence/here_now.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Channels / channel groups presence REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/presence/leave.d.ts b/lib/types/core/endpoints/presence/leave.d.ts deleted file mode 100644 index cf2b889a0..000000000 --- a/lib/types/core/endpoints/presence/leave.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Announce leave REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/presence/set_state.d.ts b/lib/types/core/endpoints/presence/set_state.d.ts deleted file mode 100644 index 21b38b6a2..000000000 --- a/lib/types/core/endpoints/presence/set_state.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Set Presence State REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/presence/where_now.d.ts b/lib/types/core/endpoints/presence/where_now.d.ts deleted file mode 100644 index 9e94e1a45..000000000 --- a/lib/types/core/endpoints/presence/where_now.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * `uuid` presence REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/publish.d.ts b/lib/types/core/endpoints/publish.d.ts deleted file mode 100644 index f313eb4c5..000000000 --- a/lib/types/core/endpoints/publish.d.ts +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Publish REST API module. - */ -import { CryptoModule } from '../interfaces/crypto-module'; -import { Payload } from '../types/api'; -/** - * Request configuration parameters. - */ -export type PublishParameters = { - /** - * Channel name to publish messages to. - */ - channel: string; - /** - * Data which should be sent to the `channel`. - * - * The message may be any valid JSON type including objects, arrays, strings, and numbers. - */ - message: Payload; - /** - * Whether published data should be available with `Storage API` later or not. - * - * @default `true` - */ - storeInHistory?: boolean; - /** - * Whether message should be sent as part of request POST body or not. - * - * @default `false` - */ - sendByPost?: boolean; - /** - * Metadata, which should be associated with published data. - * - * Associated metadata can be utilized by message filtering feature. - */ - meta?: Payload; - /** - * Specify duration during which data will be available with `Storage API`. - * - * - If `storeInHistory` = `true`, and `ttl` = `0`, the `message` is stored with no expiry time. - * - If `storeInHistory` = `true` and `ttl` = `X` (`X` is an Integer value), the `message` is - * stored with an expiry time of `X` hours. - * - If `storeInHistory` = `false`, the `ttl` parameter is ignored. - * - If `ttl` is not specified, then expiration of the `message` defaults back to the expiry value - * for the key. - */ - ttl?: number; - /** - * Whether published data should be replicated across all data centers or not. - * - * @default `true` - * @deprecated - */ - replicate?: boolean; - /** - * Indexed signature for deprecated parameters. - */ - [key: string]: string | number | boolean | undefined | Payload | CryptoModule; -}; -/** - * Service success response. - */ -export type PublishResponse = { - /** - * High-precision time when published data has been received by the PubNub service. - */ - timetoken: string; -}; diff --git a/lib/types/core/endpoints/push/add_push_channels.d.ts b/lib/types/core/endpoints/push/add_push_channels.d.ts deleted file mode 100644 index 7343774a2..000000000 --- a/lib/types/core/endpoints/push/add_push_channels.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Register Channels with Device push REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/push/list_push_channels.d.ts b/lib/types/core/endpoints/push/list_push_channels.d.ts deleted file mode 100644 index 9a279c01f..000000000 --- a/lib/types/core/endpoints/push/list_push_channels.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * List Device push enabled channels REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/push/push.d.ts b/lib/types/core/endpoints/push/push.d.ts deleted file mode 100644 index 141bbefcf..000000000 --- a/lib/types/core/endpoints/push/push.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Manage channels enabled for device push REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/push/remove_device.d.ts b/lib/types/core/endpoints/push/remove_device.d.ts deleted file mode 100644 index d5e559bb9..000000000 --- a/lib/types/core/endpoints/push/remove_device.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Unregister Device push REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/push/remove_push_channels.d.ts b/lib/types/core/endpoints/push/remove_push_channels.d.ts deleted file mode 100644 index 18e8bd0f1..000000000 --- a/lib/types/core/endpoints/push/remove_push_channels.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Unregister Channels from Device push REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/signal.d.ts b/lib/types/core/endpoints/signal.d.ts deleted file mode 100644 index 9238bd206..000000000 --- a/lib/types/core/endpoints/signal.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Signal REST API module. - */ -import { Payload } from '../types/api'; -/** - * Request configuration parameters. - */ -export type SignalParameters = { - /** - * Channel name to publish signal to. - */ - channel: string; - /** - * Data which should be sent to the `channel`. - * - * The message may be any valid JSON type including objects, arrays, strings, and numbers. - */ - message: Payload; -}; -/** - * Service success response. - */ -export type SignalResponse = { - /** - * High-precision time when published data has been received by the PubNub service. - */ - timetoken: string; -}; diff --git a/lib/types/core/endpoints/subscribe.d.ts b/lib/types/core/endpoints/subscribe.d.ts deleted file mode 100644 index 3b16762a8..000000000 --- a/lib/types/core/endpoints/subscribe.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Subscription REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/subscriptionUtils/handshake.d.ts b/lib/types/core/endpoints/subscriptionUtils/handshake.d.ts deleted file mode 100644 index f4cecd2f9..000000000 --- a/lib/types/core/endpoints/subscriptionUtils/handshake.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Handshake subscribe REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/subscriptionUtils/receiveMessages.d.ts b/lib/types/core/endpoints/subscriptionUtils/receiveMessages.d.ts deleted file mode 100644 index 39e55f4c2..000000000 --- a/lib/types/core/endpoints/subscriptionUtils/receiveMessages.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Receive messages subscribe REST API module. - * - * @internal - */ -export {}; diff --git a/lib/types/core/endpoints/time.d.ts b/lib/types/core/endpoints/time.d.ts deleted file mode 100644 index cda43e5ea..000000000 --- a/lib/types/core/endpoints/time.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -/** - * Time REST API module. - */ -/** - * Service success response. - */ -export type TimeResponse = { - /** - * High-precision time when published data has been received by the PubNub service. - */ - timetoken: string; -}; diff --git a/lib/types/core/interfaces/configuration.d.ts b/lib/types/core/interfaces/configuration.d.ts deleted file mode 100644 index 63ce7b036..000000000 --- a/lib/types/core/interfaces/configuration.d.ts +++ /dev/null @@ -1,276 +0,0 @@ -/** - * {@link PubNub} client configuration module. - */ -import { RequestRetryPolicy } from '../../event-engine/core/retryPolicy'; -/** - * Base user-provided PubNub client configuration. - */ -export type UserConfiguration = { - /** - * Specifies the `subscribeKey` to be used for subscribing to a channel and message publishing. - */ - subscribeKey: string; - /** - * Specifies the `subscribe_key` to be used for subscribing to a channel and message publishing. - * - * @deprecated Use the {@link subscribeKey} instead. - */ - subscribe_key?: string; - /** - * Specifies the `publishKey` to be used for publishing messages to a channel. - */ - publishKey?: string; - /** - * Specifies the `publish_key` to be used for publishing messages to a channel. - * - * @deprecated Use the {@link publishKey} instead. - */ - publish_key?: string; - /** - * Specifies the `secretKey` to be used for request signatures computation. - */ - secretKey?: string; - /** - * Specifies the `secret_key` to be used for request signatures computation. - * - * @deprecated Use the {@link secretKey} instead. - */ - secret_key?: string; - /** - * Unique PubNub client user identifier. - * - * Unique `userId` to identify the user or the device that connects to PubNub. - * It's a UTF-8 encoded string of up to 64 alphanumeric characters. - * - * If you don't set the `userId`, you won't be able to connect to PubNub. - */ - userId?: string; - /** - * If Access Manager enabled, this key will be used on all requests. - */ - authKey?: string | null; - /** - * Log HTTP information. - * - * @default `false` - */ - logVerbosity?: boolean; - /** - * If set to true, requests will be made over HTTPS. - * - * @default `true` for v4.20.0 onwards, `false` before v4.20.0 - */ - ssl?: boolean; - /** - * If a custom domain is required, SDK accepts it here. - * - * @default `ps.pndsn.com` - */ - origin?: string | string[]; - /** - * How long the server will consider the client alive for presence.The value is in seconds. - * - * @default `300` - */ - presenceTimeout?: number; - /** - * How often the client will announce itself to server.The value is in seconds. - * - * @default `not set` - */ - heartbeatInterval?: number; - /** - * Transactional requests timeout in milliseconds. - * - * Maximum duration for which PubNub client should wait for transactional request completion. - * - * @default `15` seconds - */ - transactionalRequestTimeout?: number; - /** - * Subscription requests timeout in milliseconds. - * - * Maximum duration for which PubNub client should wait for subscription request completion. - * - * @default `310` seconds - */ - subscribeRequestTimeout?: number; - /** - * `true` to allow catch up on the front-end applications. - * - * @default `false` - */ - restore?: boolean; - /** - * Whether to include the PubNub object instance ID in outgoing requests. - * - * @default `false` - */ - useInstanceId?: boolean; - /** - * When `true` the SDK doesn't send out the leave requests. - * - * @default `false` - */ - suppressLeaveEvents?: boolean; - /** - * `PNRequestMessageCountExceededCategory` is thrown when the number of messages into the - * payload is above of `requestMessageCountThreshold`. - * - * @default `100` - */ - requestMessageCountThreshold?: number; - /** - * This flag announces when the network is down or up using the states `PNNetworkDownCategory` - * and `PNNetworkUpCategory`. - * - * @default `false` - */ - autoNetworkDetection?: boolean; - /** - * Whether to use the standardized workflows for subscribe and presence. - * - * Note that the `maintainPresenceState` parameter is set to true by default, so make sure to - * disable it if you don't need to maintain presence state. For more information, refer to the - * param description in this table. - * - * - * @default `false` - */ - enableEventEngine?: boolean; - /** - * Custom reconnection configuration parameters. - * - * `retryConfiguration: policy` is the type of policy to be used. - * - * Available values: - * - `PubNub.LinearRetryPolicy({ delay, maximumRetry })` - * - `PubNub.ExponentialRetryPolicy({ minimumDelay, maximumDelay, maximumRetry })` - * - * For more information, refer to - * {@link /docs/general/setup/connection-management#reconnection-policy|Reconnection Policy}. JavaScript doesn't - * support excluding endpoints. - * - * @default `not set` - */ - retryConfiguration?: RequestRetryPolicy; - /** - * Whether the `state` set using `setState()` should be maintained for the current `userId`. - * This option works only when `enableEventEngine` is set to `true`. - * - * @default `true` - */ - maintainPresenceState?: boolean; - /** - * `UUID` to use. You should set a unique `UUID` to identify the user or the device that - * connects to PubNub. - * If you don't set the `UUID`, you won't be able to connect to PubNub. - * - * @deprecated Use {@link userId} instead. - */ - uuid?: string; - /** - * If set to `true`, SDK will use the same TCP connection for each HTTP request, instead of - * opening a new one for each new request. - * - * @default `false` - */ - keepAlive?: boolean; - /** - * If the SDK is running as part of another SDK built atop of it, allow a custom `pnsdk` with - * name and version. - */ - sdkName?: string; - /** - * If the SDK is operated by a partner, allow a custom `pnsdk` item for them. - */ - partnerId?: string; -}; -/** - * User-provided configuration object interface. - * - * Interface contains limited set of settings manipulation and access. - */ -export interface ClientConfiguration { - /** - * Get a PubNub client user identifier. - * - * @returns Current PubNub client user identifier. - */ - getUserId(): string; - /** - * Change the current PubNub client user identifier. - * - * **Important:** Change won't affect ongoing REST API calls. - * - * @param value - New PubNub client user identifier. - * - * @throws Error empty user identifier has been provided. - */ - setUserId(value: string): void; - /** - * Change REST API endpoint access authorization key. - * - * @param authKey - New authorization key which should be used with new requests. - */ - setAuthKey(authKey: string | null): void; - /** - * Real-time updates filtering expression. - * - * @returns Filtering expression. - */ - getFilterExpression(): string | undefined | null; - /** - * Update real-time updates filtering expression. - * - * @param expression - New expression which should be used or `undefined` to disable filtering. - */ - setFilterExpression(expression: string | null | undefined): void; - /** - * Change data encryption / decryption key. - * - * @param key - New key which should be used for data encryption / decryption. - */ - setCipherKey(key: string | undefined): void; - /** - * Get PubNub SDK version. - * - * @returns Current SDK version. - */ - get version(): string; - /** - * Get PubNub SDK version. - * - * @returns Current SDK version. - */ - getVersion(): string; - /** - * Add framework's prefix. - * - * @param name - Name of the framework which would want to add own data into `pnsdk` suffix. - * @param suffix - Suffix with information about framework. - */ - _addPnsdkSuffix(name: string, suffix: string | number): void; - /** - * Get a PubNub client user identifier. - * - * @returns Current PubNub client user identifier. - * - * @deprecated Use the {@link getUserId} or {@link userId} getter instead. - */ - getUUID(): string; - /** - * Change the current PubNub client user identifier. - * - * **Important:** Change won't affect ongoing REST API calls. - * - * @param value - New PubNub client user identifier. - * - * @returns {Configuration} Reference to the configuration instance for easier chaining. - * - * @throws Error empty user identifier has been provided. - * - * @deprecated Use the {@link setUserId} or {@link userId} setter instead. - */ - setUUID(value: string): void; -} diff --git a/lib/types/core/interfaces/crypto-module.d.ts b/lib/types/core/interfaces/crypto-module.d.ts deleted file mode 100644 index 7141a48c9..000000000 --- a/lib/types/core/interfaces/crypto-module.d.ts +++ /dev/null @@ -1,140 +0,0 @@ -/** - * Crypto module. - */ -import { PubNubFileConstructor, PubNubFileInterface } from '../types/file'; -import { Payload } from '../types/api'; -/** - * Crypto module configuration. - */ -export type CryptoModuleConfiguration = { - default: C; - cryptors?: C[]; -}; -export type CryptorConfiguration = { - /** - * Data encryption / decryption key. - */ - cipherKey?: string; - /** - * Request sign secret key. - */ - secretKey?: string; - /** - * Whether random initialization vector should be used or not. - * - * @default `true` - */ - useRandomIVs?: boolean; - /** - * Custom data encryption method. - * - * @deprecated Instead use {@link cryptoModule} for data encryption. - */ - customEncrypt?: (data: string | Payload) => string; - /** - * Custom data decryption method. - * - * @deprecated Instead use {@link cryptoModule} for data decryption. - */ - customDecrypt?: (data: string) => string; -}; -/** - * Base crypto module interface. - */ -export interface CryptoModule { - /** - * Encrypt data. - * - * @param data - Data which should be encrypted using `CryptoModule`. - * - * @returns Data encryption result. - */ - encrypt(data: ArrayBuffer | string): ArrayBuffer | string; - /** - * Encrypt file object. - * - * @param file - File object with data for encryption. - * @param File - File object constructor to create instance for encrypted data representation. - * - * @returns Asynchronous file encryption result. - */ - encryptFile(file: PubNubFileInterface, File: PubNubFileConstructor): Promise; - /** - * Encrypt data. - * - * @param data - Dta which should be encrypted using `CryptoModule`. - * - * @returns Data decryption result. - */ - decrypt(data: ArrayBuffer | string): ArrayBuffer | Payload | null; - /** - * Decrypt file object. - * - * @param file - Encrypted file object with data for decryption. - * @param File - File object constructor to create instance for decrypted data representation. - * - * @returns Asynchronous file decryption result. - */ - decryptFile(file: PubNubFileInterface, File: PubNubFileConstructor): Promise; -} -export declare abstract class AbstractCryptoModule implements CryptoModule { - defaultCryptor: C; - cryptors: C[]; - /** - * Construct crypto module with legacy cryptor for encryption and both legacy and AES-CBC - * cryptors for decryption. - * - * @param config Cryptors configuration options. - * - * @returns Crypto module which encrypts data using legacy cryptor. - * - * @throws Error if `config.cipherKey` not set. - */ - static legacyCryptoModule(config: CryptorConfiguration): CryptoModule; - /** - * Construct crypto module with AES-CBC cryptor for encryption and both AES-CBC and legacy - * cryptors for decryption. - * - * @param config Cryptors configuration options. - * - * @returns Crypto module which encrypts data using AES-CBC cryptor. - * - * @throws Error if `config.cipherKey` not set. - */ - static aesCbcCryptoModule(config: CryptorConfiguration): CryptoModule; - constructor(configuration: CryptoModuleConfiguration); - /** - * Encrypt data. - * - * @param data - Data which should be encrypted using {@link CryptoModule}. - * - * @returns Data encryption result. - */ - abstract encrypt(data: ArrayBuffer | string): ArrayBuffer | string; - /** - * Encrypt file object. - * - * @param file - File object with data for encryption. - * @param File - File object constructor to create instance for encrypted data representation. - * - * @returns Asynchronous file encryption result. - */ - abstract encryptFile(file: PubNubFileInterface, File: PubNubFileConstructor): Promise; - /** - * Encrypt data. - * - * @param data - Dta which should be encrypted using `CryptoModule`. - * - * @returns Data decryption result. - */ - abstract decrypt(data: ArrayBuffer | string): ArrayBuffer | Payload | null; - /** - * Decrypt file object. - * - * @param file - Encrypted file object with data for decryption. - * @param File - File object constructor to create instance for decrypted data representation. - * - * @returns Asynchronous file decryption result. - */ - abstract decryptFile(file: PubNubFileInterface, File: PubNubFileConstructor): Promise; -} diff --git a/lib/types/core/interfaces/cryptography.d.ts b/lib/types/core/interfaces/cryptography.d.ts deleted file mode 100644 index 9b73050a5..000000000 --- a/lib/types/core/interfaces/cryptography.d.ts +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Legacy Cryptography module interface. - */ -import { PubNubFileConstructor, PubNubFileInterface } from '../types/file'; -export interface Cryptography { - /** - * Encrypt provided source data using specific encryption {@link key}. - * - * @param key - Data encryption key.
**Note:** Same key should be used to `decrypt` data. - * @param input - Source data for encryption. - * - * @returns Encrypted data as object or stream (depending on from source data type). - * - * @throws Error if unknown data type has been passed. - */ - encrypt(key: string, input: Types): Promise; - /** - * Decrypt provided encrypted data using specific decryption {@link key}. - * - * @param key - Data decryption key.
**Note:** Should be the same as used to `encrypt` data. - * @param input - Encrypted data for decryption. - * - * @returns Decrypted data as object or stream (depending on from encrypted data type). - * - * @throws Error if unknown data type has been passed. - */ - decrypt(key: string, input: Types): Promise; - /** - * Encrypt provided `PubNub` File object using specific encryption {@link key}. - * - * @param key - Key for `PubNub` File object encryption.
**Note:** Same key should be - * used to `decrypt` data. - * @param file - Source `PubNub` File object for encryption. - * @param File - Class constructor for `PubNub` File object. - * - * @returns Encrypted data as `PubNub` File object. - * - * @throws Error if file is empty or contains unsupported data type. - */ - encryptFile(key: string, file: PubNubFileInterface, File: PubNubFileConstructor): Promise; - /** - * Decrypt provided `PubNub` File object using specific decryption {@link key}. - * - * @param key - Key for `PubNub` File object decryption.
**Note:** Should be the same - * as used to `encrypt` data. - * @param file - Encrypted `PubNub` File object for decryption. - * @param File - Class constructor for `PubNub` File object. - * - * @returns Decrypted data as `PubNub` File object. - * - * @throws Error if file is empty or contains unsupported data type. - */ - decryptFile(key: string, file: PubNubFileInterface, File: PubNubFileConstructor): Promise; -} diff --git a/lib/types/core/interfaces/request.d.ts b/lib/types/core/interfaces/request.d.ts deleted file mode 100644 index cb0ff5c3b..000000000 --- a/lib/types/core/interfaces/request.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/lib/types/core/interfaces/transport.d.ts b/lib/types/core/interfaces/transport.d.ts deleted file mode 100644 index 82ec357eb..000000000 --- a/lib/types/core/interfaces/transport.d.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { CancellationController, TransportRequest } from '../types/transport-request'; -import { TransportResponse } from '../types/transport-response'; -/** - * Represents the configuration options for keeping the transport connection alive. - */ -export type TransportKeepAlive = { - /** - * The time interval in milliseconds for keeping the connection alive. - * - * @default 1000 - */ - keepAliveMsecs?: number; - /** - * The maximum number of sockets allowed per host. - * - * @default Infinity - */ - maxSockets?: number; - /** - * The maximum number of open and free sockets in the pool per host. - * - * @default 256 - */ - maxFreeSockets?: number; - /** - * Timeout in milliseconds, after which the `idle` socket will be closed. - * - * @default 30000 - */ - timeout?: number; -}; -/** - * This interface is used to send requests to the PubNub API. - * - * You can implement this interface for your types, or use one of the provided modules to use a - * transport library. - * - * @interface - */ -export interface Transport { - /** - * Make request sendable. - * - * @param req - The transport request to be processed. - * - * @returns - A promise that resolves to a transport response and request cancellation - * controller (if required). - */ - makeSendable(req: TransportRequest): [Promise, CancellationController | undefined]; - /** - * Pre-processed request. - * - * Transport implementation may pre-process original transport requests before making - * platform-specific request objects from it. - * - * @param req - Transport request provided by the PubNub client. - * - * @returns Transport request with updated properties (if it was required). - */ - request(req: TransportRequest): TransportRequest; -} diff --git a/lib/types/core/pubnub-channel-groups.d.ts b/lib/types/core/pubnub-channel-groups.d.ts deleted file mode 100644 index d0ec3b1eb..000000000 --- a/lib/types/core/pubnub-channel-groups.d.ts +++ /dev/null @@ -1,86 +0,0 @@ -/** - * PubNub Channel Groups API module. - */ -import { ResultCallback, StatusCallback } from './types/api'; -import * as ChannelGroups from './types/api/channel-groups'; -/** - * PubNub Stream / Channel group API interface. - */ -export default class PubNubChannelGroups { - /** - * Fetch channel group channels. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - listChannels(parameters: ChannelGroups.ListChannelGroupChannelsParameters, callback: ResultCallback): void; - /** - * Fetch channel group channels. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous get channel group channels response. - */ - listChannels(parameters: ChannelGroups.ListChannelGroupChannelsParameters): Promise; - /** - * Fetch all channel groups. - * - * @param callback - Request completion handler callback. - * - * @deprecated - */ - listGroups(callback: ResultCallback): void; - /** - * Fetch all channel groups. - * - * @returns Asynchronous get all channel groups response. - * - * @deprecated - */ - listGroups(): Promise; - /** - * Add channels to the channel group. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - addChannels(parameters: ChannelGroups.ManageChannelGroupChannelsParameters, callback: StatusCallback): void; - /** - * Add channels to the channel group. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous add channels to the channel group response. - */ - addChannels(parameters: ChannelGroups.ManageChannelGroupChannelsParameters): Promise>; - /** - * Remove channels from the channel group. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - removeChannels(parameters: ChannelGroups.ManageChannelGroupChannelsParameters, callback: StatusCallback): void; - /** - * Remove channels from the channel group. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous remove channels from the channel group response. - */ - removeChannels(parameters: ChannelGroups.ManageChannelGroupChannelsParameters): Promise>; - /** - * Remove channel group. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - deleteGroup(parameters: ChannelGroups.DeleteChannelGroupParameters, callback: StatusCallback): void; - /** - * Remove channel group. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous remove channel group response. - */ - deleteGroup(parameters: ChannelGroups.DeleteChannelGroupParameters): Promise>; -} diff --git a/lib/types/core/pubnub-common.d.ts b/lib/types/core/pubnub-common.d.ts deleted file mode 100644 index c42874191..000000000 --- a/lib/types/core/pubnub-common.d.ts +++ /dev/null @@ -1,1213 +0,0 @@ -/** - * Core PubNub API module. - */ -import { Listener } from './components/listener_manager'; -import NotificationsPayload from './components/push_payload'; -import { Payload, ResultCallback } from './types/api'; -import { ClientConfiguration } from './interfaces/configuration'; -import RequestOperation from './constants/operations'; -import StatusCategory from './constants/categories'; -import { RetryPolicy } from '../event-engine/core/retryPolicy'; -import * as Publish from './endpoints/publish'; -import * as Signal from './endpoints/signal'; -import * as Subscription from './types/api/subscription'; -import * as Presence from './types/api/presence'; -import * as History from './types/api/history'; -import * as MessageAction from './types/api/message-action'; -import * as FileSharing from './types/api/file-sharing'; -import { PubNubFileInterface } from './types/file'; -import * as PAM from './types/api/access-manager'; -import { SubscriptionOptions } from '../entities/commonTypes'; -import { ChannelMetadata } from '../entities/ChannelMetadata'; -import { SubscriptionSet } from '../entities/SubscriptionSet'; -import { ChannelGroup } from '../entities/ChannelGroup'; -import { UserMetadata } from '../entities/UserMetadata'; -import { Channel } from '../entities/Channel'; -import PubNubChannelGroups from './pubnub-channel-groups'; -import PubNubPushNotifications from './pubnub-push'; -import * as AppContext from './types/api/app-context'; -import PubNubObjects from './pubnub-objects'; -import * as Time from './endpoints/time'; -/** - * Platform-agnostic PubNub client core. - */ -export declare class PubNubCore = Record> { - /** - * Type of REST API endpoint which reported status. - */ - static OPERATIONS: typeof RequestOperation; - /** - * API call status category. - */ - static CATEGORIES: typeof StatusCategory; - /** - * Exponential retry policy constructor. - */ - static ExponentialRetryPolicy: typeof RetryPolicy.ExponentialRetryPolicy; - /** - * Linear retry policy constructor. - */ - static LinearRetryPolicy: typeof RetryPolicy.LinearRetryPolicy; - /** - * Construct notification payload which will trigger push notification. - * - * @param title - Title which will be shown on notification. - * @param body - Payload which will be sent as part of notification. - * - * @returns Pre-formatted message payload which will trigger push notification. - */ - static notificationPayload(title: string, body: string): NotificationsPayload; - /** - * Generate unique identifier. - * - * @returns Unique identifier. - */ - static generateUUID(): any; - /** - * PubNub client configuration. - * - * @returns Currently user PubNub client configuration. - */ - get configuration(): ClientConfiguration; - /** - * Current PubNub client configuration. - * - * @returns Currently user PubNub client configuration. - * - * @deprecated Use {@link configuration} getter instead. - */ - get _config(): ClientConfiguration; - /** - * REST API endpoint access authorization key. - * - * It is required to have `authorization key` with required permissions to access REST API - * endpoints when `PAM` enabled for user key set. - */ - get authKey(): string | undefined; - /** - * REST API endpoint access authorization key. - * - * It is required to have `authorization key` with required permissions to access REST API - * endpoints when `PAM` enabled for user key set. - */ - getAuthKey(): string | undefined; - /** - * Change REST API endpoint access authorization key. - * - * @param authKey - New authorization key which should be used with new requests. - */ - setAuthKey(authKey: string): void; - /** - * Get a PubNub client user identifier. - * - * @returns Current PubNub client user identifier. - */ - get userId(): string; - /** - * Change the current PubNub client user identifier. - * - * **Important:** Change won't affect ongoing REST API calls. - * - * @param value - New PubNub client user identifier. - * - * @throws Error empty user identifier has been provided. - */ - set userId(value: string); - /** - * Get a PubNub client user identifier. - * - * @returns Current PubNub client user identifier. - */ - getUserId(): string; - /** - * Change the current PubNub client user identifier. - * - * **Important:** Change won't affect ongoing REST API calls. - * - * @param value - New PubNub client user identifier. - * - * @throws Error empty user identifier has been provided. - */ - setUserId(value: string): void; - /** - * Real-time updates filtering expression. - * - * @returns Filtering expression. - */ - get filterExpression(): string | undefined; - /** - * Real-time updates filtering expression. - * - * @returns Filtering expression. - */ - getFilterExpression(): string | undefined; - /** - * Update real-time updates filtering expression. - * - * @param expression - New expression which should be used or `undefined` to disable filtering. - */ - set filterExpression(expression: string | null | undefined); - /** - * Update real-time updates filtering expression. - * - * @param expression - New expression which should be used or `undefined` to disable filtering. - */ - setFilterExpression(expression: string | null): void; - /** - * Dta encryption / decryption key. - * - * @returns Currently used key for data encryption / decryption. - */ - get cipherKey(): string | undefined; - /** - * Change data encryption / decryption key. - * - * @param key - New key which should be used for data encryption / decryption. - */ - set cipherKey(key: string | undefined); - /** - * Change data encryption / decryption key. - * - * @param key - New key which should be used for data encryption / decryption. - */ - setCipherKey(key: string): void; - /** - * Change heartbeat requests interval. - * - * @param interval - New presence request heartbeat intervals. - */ - set heartbeatInterval(interval: number); - /** - * Change heartbeat requests interval. - * - * @param interval - New presence request heartbeat intervals. - */ - setHeartbeatInterval(interval: number): void; - /** - * Get PubNub SDK version. - * - * @returns Current SDK version. - */ - getVersion(): string; - /** - * Add framework's prefix. - * - * @param name - Name of the framework which would want to add own data into `pnsdk` suffix. - * @param suffix - Suffix with information about framework. - */ - _addPnsdkSuffix(name: string, suffix: string | number): void; - /** - * Get a PubNub client user identifier. - * - * @returns Current PubNub client user identifier. - * - * @deprecated Use the {@link getUserId} or {@link userId} getter instead. - */ - getUUID(): string; - /** - * Change the current PubNub client user identifier. - * - * **Important:** Change won't affect ongoing REST API calls. - * - * @param value - New PubNub client user identifier. - * - * @throws Error empty user identifier has been provided. - * - * @deprecated Use the {@link PubNubCore#setUserId} or {@link PubNubCore#userId} setter instead. - */ - setUUID(value: string): void; - /** - * Custom data encryption method. - * - * @deprecated Instead use {@link cryptoModule} for data encryption. - */ - get customEncrypt(): ((data: string) => string) | undefined; - /** - * Custom data decryption method. - * - * @deprecated Instead use {@link cryptoModule} for data decryption. - */ - get customDecrypt(): ((data: string) => string) | undefined; - /** - * Create a `Channel` entity. - * - * Entity can be used for the interaction with the following API: - * - `subscribe` - * - * @param name - Unique channel name. - * @returns `Channel` entity. - */ - channel(name: string): Channel; - /** - * Create a `ChannelGroup` entity. - * - * Entity can be used for the interaction with the following API: - * - `subscribe` - * - * @param name - Unique channel group name. - * @returns `ChannelGroup` entity. - */ - channelGroup(name: string): ChannelGroup; - /** - * Create a `ChannelMetadata` entity. - * - * Entity can be used for the interaction with the following API: - * - `subscribe` - * - * @param id - Unique channel metadata object identifier. - * @returns `ChannelMetadata` entity. - */ - channelMetadata(id: string): ChannelMetadata; - /** - * Create a `UserMetadata` entity. - * - * Entity can be used for the interaction with the following API: - * - `subscribe` - * - * @param id - Unique user metadata object identifier. - * @returns `UserMetadata` entity. - */ - userMetadata(id: string): UserMetadata; - /** - * Create subscriptions set object. - * - * @param parameters - Subscriptions set configuration parameters. - */ - subscriptionSet(parameters: { - channels?: string[]; - channelGroups?: string[]; - subscriptionOptions?: SubscriptionOptions; - }): SubscriptionSet; - /** - * Unsubscribe from all channels and groups. - * - * @param [isOffline] - Whether `offline` presence should be notified or not. - */ - destroy(isOffline?: boolean): void; - /** - * Unsubscribe from all channels and groups. - * - * @deprecated Use {@link destroy} method instead. - */ - stop(): void; - /** - * Register real-time events listener. - * - * @param listener - Listener with event callbacks to handle different types of events. - */ - addListener(listener: Listener): void; - /** - * Remove real-time event listener. - * - * @param listener - Event listeners which should be removed. - */ - removeListener(listener: Listener): void; - /** - * Clear all real-time event listeners. - */ - removeAllListeners(): void; - /** - * Publish data to a specific channel. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - publish(parameters: Publish.PublishParameters, callback: ResultCallback): void; - /** - * Publish data to a specific channel. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous publish data response. - */ - publish(parameters: Publish.PublishParameters): Promise; - /** - * Signal data to a specific channel. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - signal(parameters: Signal.SignalParameters, callback: ResultCallback): void; - /** - * Signal data to a specific channel. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous signal data response. - */ - signal(parameters: Signal.SignalParameters): Promise; - /** - * `Fire` a data to a specific channel. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - * - * @deprecated Use {@link publish} method instead. - */ - fire(parameters: Publish.PublishParameters, callback: ResultCallback): void; - /** - * `Fire` a data to a specific channel. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous signal data response. - * - * @deprecated Use {@link publish} method instead. - */ - fire(parameters: Publish.PublishParameters): Promise; - /** - * Get list of channels on which PubNub client currently subscribed. - * - * @returns List of active channels. - */ - getSubscribedChannels(): string[]; - /** - * Get list of channel groups on which PubNub client currently subscribed. - * - * @returns List of active channel groups. - */ - getSubscribedChannelGroups(): string[]; - /** - * Subscribe to specified channels and groups real-time events. - * - * @param parameters - Request configuration parameters. - */ - subscribe(parameters: Subscription.SubscribeParameters): void; - /** - * Unsubscribe from specified channels and groups real-time events. - * - * @param parameters - Request configuration parameters. - */ - unsubscribe(parameters: Presence.PresenceLeaveParameters): void; - /** - * Unsubscribe from all channels and groups. - */ - unsubscribeAll(): void; - /** - * Temporarily disconnect from real-time events stream. - */ - disconnect(): void; - /** - * Restore connection to the real-time events stream. - * - * @param parameters - Reconnection catch up configuration. **Note:** available only with - * enabled event engine. - */ - reconnect(parameters?: { - timetoken?: string; - region?: number; - }): void; - /** - * Get reactions to a specific message. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - getMessageActions(parameters: MessageAction.GetMessageActionsParameters, callback: ResultCallback): void; - /** - * Get reactions to a specific message. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous get reactions response. - */ - getMessageActions(parameters: MessageAction.GetMessageActionsParameters): Promise; - /** - * Add a reaction to a specific message. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - addMessageAction(parameters: MessageAction.AddMessageActionParameters, callback: ResultCallback): void; - /** - * Add a reaction to a specific message. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous add a reaction response. - */ - addMessageAction(parameters: MessageAction.AddMessageActionParameters): Promise; - /** - * Remove a reaction from a specific message. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - removeMessageAction(parameters: MessageAction.RemoveMessageActionParameters, callback: ResultCallback): void; - /** - * Remove a reaction from a specific message. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous remove a reaction response. - */ - removeMessageAction(parameters: MessageAction.RemoveMessageActionParameters): Promise; - /** - * Fetch messages history for channels. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - fetchMessages(parameters: History.FetchMessagesParameters, callback: ResultCallback): void; - /** - * Fetch messages history for channels. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous fetch messages response. - */ - fetchMessages(parameters: History.FetchMessagesParameters): Promise; - /** - * Delete messages from the channel history. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - * - * @deprecated - */ - deleteMessages(parameters: History.DeleteMessagesParameters, callback: ResultCallback): void; - /** - * Delete messages from the channel history. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous delete messages response. - * - * @deprecated - */ - deleteMessages(parameters: History.DeleteMessagesParameters): Promise; - /** - * Count messages from the channels' history. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - messageCounts(parameters: History.MessageCountParameters, callback: ResultCallback): void; - /** - * Count messages from the channels' history. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous count messages response. - */ - messageCounts(parameters: History.MessageCountParameters): Promise; - /** - * Fetch single channel history. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - * - * @deprecated - */ - history(parameters: History.GetHistoryParameters, callback: ResultCallback): void; - /** - * Fetch single channel history. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous fetch channel history response. - * - * @deprecated - */ - history(parameters: History.GetHistoryParameters): Promise; - /** - * Get channel's presence information. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - hereNow(parameters: Presence.HereNowParameters, callback: ResultCallback): void; - /** - * Get channel presence information. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous get channel's presence response. - */ - hereNow(parameters: Presence.HereNowParameters): Promise; - /** - * Get user's presence information. - * - * Get list of channels to which `uuid` currently subscribed. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - whereNow(parameters: Presence.WhereNowParameters, callback: ResultCallback): void; - /** - * Get user's presence information. - * - * Get list of channels to which `uuid` currently subscribed. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous get user's presence response. - */ - whereNow(parameters: Presence.WhereNowParameters): Promise; - /** - * Get associated user's data for channels and groups. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - getState(parameters: Presence.GetPresenceStateParameters, callback: ResultCallback): void; - /** - * Get associated user's data for channels and groups. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous get associated user's data response. - */ - getState(parameters: Presence.GetPresenceStateParameters): Promise; - /** - * Set associated user's data for channels and groups. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - setState(parameters: Presence.SetPresenceStateParameters | Presence.SetPresenceStateWithHeartbeatParameters, callback: ResultCallback): void; - /** - * Set associated user's data for channels and groups. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous set associated user's data response. - */ - setState(parameters: Presence.SetPresenceStateParameters | Presence.SetPresenceStateWithHeartbeatParameters): Promise; - /** - * Manual presence management. - * - * @param parameters - Desired presence state for provided list of channels and groups. - */ - presence(parameters: { - connected: boolean; - channels?: string[]; - channelGroups?: string[]; - }): void; - /** - * Grant token permission. - * - * Generate access token with requested permissions. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - grantToken(parameters: PAM.GrantTokenParameters, callback: ResultCallback): void; - /** - * Grant token permission. - * - * Generate access token with requested permissions. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous grant token response. - */ - grantToken(parameters: PAM.GrantTokenParameters): Promise; - /** - * Revoke token permission. - * - * @param token - Access token for which permissions should be revoked. - * @param callback - Request completion handler callback. - */ - revokeToken(token: PAM.RevokeParameters, callback: ResultCallback): void; - /** - * Revoke token permission. - * - * @param token - Access token for which permissions should be revoked. - * - * @returns Asynchronous revoke token response. - */ - revokeToken(token: PAM.RevokeParameters): Promise; - /** - * Get current access token. - * - * @returns Previously configured access token using {@link setToken} method. - */ - get token(): string | undefined; - /** - * Get current access token. - * - * @returns Previously configured access token using {@link setToken} method. - */ - getToken(): string | undefined; - /** - * Set current access token. - * - * @param token - New access token which should be used with next REST API endpoint calls. - */ - set token(token: string | undefined); - /** - * Set current access token. - * - * @param token - New access token which should be used with next REST API endpoint calls. - */ - setToken(token: string | undefined): void; - /** - * Parse access token. - * - * Parse token to see what permissions token owner has. - * - * @param token - Token which should be parsed. - * - * @returns Token's permissions information for the resources. - */ - parseToken(token: string): { - version: number; - timestamp: number; - ttl: number; - resources?: Partial>> | undefined; - patterns?: Partial>> | undefined; - authorized_uuid?: string | undefined; - signature: ArrayBuffer; - meta?: Payload | undefined; - } | undefined; - /** - * Grant auth key(s) permission. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - * - * @deprecated Use {@link grantToken} and {@link setToken} methods instead. - */ - grant(parameters: PAM.GrantParameters, callback: ResultCallback): void; - /** - * Grant auth key(s) permission. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous grant auth key(s) permissions response. - * - * @deprecated Use {@link grantToken} and {@link setToken} methods instead. - */ - grant(parameters: PAM.GrantParameters): Promise; - /** - * Audit auth key(s) permission. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - * - * @deprecated - */ - audit(parameters: PAM.AuditParameters, callback: ResultCallback): void; - /** - * Audit auth key(s) permission. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous audit auth key(s) permissions response. - * - * @deprecated - */ - audit(parameters: PAM.AuditParameters): Promise; - /** - * PubNub App Context API group. - */ - get objects(): PubNubObjects; - /** - * Fetch a paginated list of User objects. - * - * @param callback - Request completion handler callback. - * - * @deprecated Use {@link PubNubCore#objects.getAllUUIDMetadata} method instead. - */ - fetchUsers(callback: ResultCallback>): void; - /** - * Fetch a paginated list of User objects. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - * - * @deprecated Use {@link PubNubCore#objects.getAllUUIDMetadata} method instead. - */ - fetchUsers(parameters: AppContext.GetAllMetadataParameters>, callback: ResultCallback>): void; - /** - * Fetch a paginated list of User objects. - * - * @param [parameters] - Request configuration parameters. - * - * @returns Asynchronous get all User objects response. - * - * @deprecated Use {@link PubNubCore#objects.getAllUUIDMetadata} method instead. - */ - fetchUsers(parameters?: AppContext.GetAllMetadataParameters>): Promise>; - /** - * Fetch User object for currently configured PubNub client `uuid`. - * - * @param callback - Request completion handler callback. - * - * @deprecated Use {@link PubNubCore#objects.getUUIDMetadata} method instead. - */ - fetchUser(callback: ResultCallback>): void; - /** - * Fetch User object for currently configured PubNub client `uuid`. - * - * @param parameters - Request configuration parameters. Will fetch User object for currently - * configured PubNub client `uuid` if not set. - * @param callback - Request completion handler callback. - * - * @deprecated Use {@link PubNubCore#objects.getUUIDMetadata} method instead. - */ - fetchUser(parameters: AppContext.GetUUIDMetadataParameters, callback: ResultCallback>): void; - /** - * Fetch User object for currently configured PubNub client `uuid`. - * - * @param [parameters] - Request configuration parameters. Will fetch User object for currently - * configured PubNub client `uuid` if not set. - * - * @returns Asynchronous get User object response. - * - * @deprecated Use {@link PubNubCore#objects.getUUIDMetadata} method instead. - */ - fetchUser(parameters?: AppContext.GetUUIDMetadataParameters): Promise>; - /** - * Create User object. - * - * @param parameters - Request configuration parameters. Will create User object for currently - * configured PubNub client `uuid` if not set. - * @param callback - Request completion handler callback. - * - * @deprecated Use {@link PubNubCore#objects.setUUIDMetadata} method instead. - */ - createUser(parameters: AppContext.SetUUIDMetadataParameters, callback: ResultCallback>): void; - /** - * Create User object. - * - * @param parameters - Request configuration parameters. Will create User object for currently - * configured PubNub client `uuid` if not set. - * - * @returns Asynchronous create User object response. - * - * @deprecated Use {@link PubNubCore#objects.setUUIDMetadata} method instead. - */ - createUser(parameters: AppContext.SetUUIDMetadataParameters): Promise>; - /** - * Update User object. - * - * @param parameters - Request configuration parameters. Will update User object for currently - * configured PubNub client `uuid` if not set. - * @param callback - Request completion handler callback. - * - * @deprecated Use {@link PubNubCore#objects.setUUIDMetadata} method instead. - */ - updateUser(parameters: AppContext.SetUUIDMetadataParameters, callback: ResultCallback>): void; - /** - * Update User object. - * - * @param parameters - Request configuration parameters. Will update User object for currently - * configured PubNub client `uuid` if not set. - * - * @returns Asynchronous update User object response. - * - * @deprecated Use {@link PubNubCore#objects.setUUIDMetadata} method instead. - */ - updateUser(parameters: AppContext.SetUUIDMetadataParameters): Promise>; - /** - * Remove a specific User object. - * - * @param callback - Request completion handler callback. Will remove User object for currently - * configured PubNub client `uuid` if not set. - * - * @deprecated Use {@link PubNubCore#objects.removeUUIDMetadata} method instead. - */ - removeUser(callback: ResultCallback): void; - /** - * Remove a specific User object. - * - * @param parameters - Request configuration parameters. Will remove User object for currently - * configured PubNub client `uuid` if not set. - * @param callback - Request completion handler callback. - * - * @deprecated Use {@link PubNubCore#objects.removeUUIDMetadata} method instead. - */ - removeUser(parameters: AppContext.RemoveUUIDMetadataParameters, callback: ResultCallback): void; - /** - * Remove a specific User object. - * - * @param [parameters] - Request configuration parameters. Will remove User object for currently - * configured PubNub client `uuid` if not set. - * - * @returns Asynchronous User object remove response. - * - * @deprecated Use {@link PubNubCore#objects.removeUUIDMetadata} method instead. - */ - removeUser(parameters?: AppContext.RemoveUUIDMetadataParameters): Promise; - /** - * Fetch a paginated list of Space objects. - * - * @param callback - Request completion handler callback. - * - * @deprecated Use {@link PubNubCore#objects.getAllChannelMetadata} method instead. - */ - fetchSpaces(callback: ResultCallback>): void; - /** - * Fetch a paginated list of Space objects. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - * - * @deprecated Use {@link PubNubCore#objects.getAllChannelMetadata} method instead. - */ - fetchSpaces(parameters: AppContext.GetAllMetadataParameters>, callback: ResultCallback>): void; - /** - * Fetch a paginated list of Space objects. - * - * @param [parameters] - Request configuration parameters. - * - * @returns Asynchronous get all Space objects response. - * - * @deprecated Use {@link PubNubCore#objects.getAllChannelMetadata} method instead. - */ - fetchSpaces(parameters?: AppContext.GetAllMetadataParameters>): Promise>; - /** - * Fetch a specific Space object. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - * - * @deprecated Use {@link PubNubCore#objects.getChannelMetadata} method instead. - */ - fetchSpace(parameters: AppContext.GetChannelMetadataParameters, callback: ResultCallback>): void; - /** - * Fetch a specific Space object. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous get Channel metadata response. - * - * @deprecated Use {@link PubNubCore#objects.getChannelMetadata} method instead. - */ - fetchSpace(parameters: AppContext.GetChannelMetadataParameters): Promise>; - /** - * Create specific Space object. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - * - * @deprecated Use {@link PubNubCore#objects.setChannelMetadata} method instead. - */ - createSpace(parameters: AppContext.SetChannelMetadataParameters, callback: ResultCallback>): void; - /** - * Create specific Space object. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous create Space object response. - * - * @deprecated Use {@link PubNubCore#objects.setChannelMetadata} method instead. - */ - createSpace(parameters: AppContext.SetChannelMetadataParameters): Promise>; - /** - * Update specific Space object. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - * - * @deprecated Use {@link PubNubCore#objects.setChannelMetadata} method instead. - */ - updateSpace(parameters: AppContext.SetChannelMetadataParameters, callback: ResultCallback>): void; - /** - * Update specific Space object. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous update Space object response. - * - * @deprecated Use {@link PubNubCore#objects.setChannelMetadata} method instead. - */ - updateSpace(parameters: AppContext.SetChannelMetadataParameters): Promise>; - /** - * Remove Space object. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - * - * @deprecated Use {@link PubNubCore#objects.removeChannelMetadata} method instead. - */ - removeSpace(parameters: AppContext.RemoveChannelMetadataParameters, callback: ResultCallback): void; - /** - * Remove a specific Space object. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous Space object remove response. - * - * @deprecated Use {@link PubNubCore#objects.removeChannelMetadata} method instead. - */ - removeSpace(parameters: AppContext.RemoveChannelMetadataParameters): Promise; - /** - * Fetch paginated list of specific Space members or specific User memberships. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - * - * @deprecated Use {@link PubNubCore#objects.getChannelMembers} or {@link PubNubCore#objects.getMemberships} - * methods instead. - */ - fetchMemberships(parameters: AppContext.GetMembershipsParameters | AppContext.GetMembersParameters, callback: ResultCallback | AppContext.UserMembersResponse>): void; - /** - * Fetch paginated list of specific Space members or specific User memberships. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous get specific Space members or specific User memberships response. - * - * @deprecated Use {@link PubNubCore#objects.getChannelMembers} or {@link PubNubCore#objects.getMemberships} - * methods instead. - */ - fetchMemberships(parameters: AppContext.GetMembershipsParameters | AppContext.GetMembersParameters): Promise | AppContext.UserMembersResponse>; - /** - * Add members to specific Space or memberships specific User. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - * - * @deprecated Use {@link PubNubCore#objects.setChannelMembers} or {@link PubNubCore#objects.setMemberships} - * methods instead. - */ - addMemberships(parameters: AppContext.SetMembershipsParameters | AppContext.SetChannelMembersParameters, callback: ResultCallback | AppContext.SetMembersResponse>): void; - /** - * Add members to specific Space or memberships specific User. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous add members to specific Space or memberships specific User response. - * - * @deprecated Use {@link PubNubCore#objects.setChannelMembers} or {@link PubNubCore#objects.setMemberships} - * methods instead. - */ - addMemberships(parameters: AppContext.SetMembershipsParameters | AppContext.SetChannelMembersParameters): Promise | AppContext.SetMembersResponse>; - /** - * Update specific Space members or User memberships. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - * - * @deprecated Use {@link PubNubCore#objects.setChannelMembers} or {@link PubNubCore#objects.setMemberships} - * methods instead. - */ - updateMemberships(parameters: AppContext.SetMembershipsParameters | AppContext.SetChannelMembersParameters, callback: ResultCallback | AppContext.SetMembersResponse>): void; - /** - * Update specific Space members or User memberships. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous update Space members or User memberships response. - * - * @deprecated Use {@link PubNubCore#objects.setChannelMembers} or {@link PubNubCore#objects.setMemberships} - * methods instead. - */ - updateMemberships(parameters: AppContext.SetMembershipsParameters | AppContext.SetChannelMembersParameters): Promise | AppContext.SetMembersResponse>; - /** - * Remove User membership. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - * - * @deprecated Use {@link PubNubCore#objects.removeMemberships} or {@link PubNubCore#objects.removeChannelMembers} - * methods instead - * from `objects` API group.. - */ - removeMemberships(parameters: AppContext.RemoveMembersParameters | AppContext.RemoveMembershipsParameters, callback: ResultCallback | AppContext.RemoveMembershipsResponse>): void; - /** - * Remove User membership. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous memberships modification response. - * - * @deprecated Use {@link PubNubCore#objects.removeMemberships} or {@link PubNubCore#objects.removeChannelMembers} - * methods instead - * from `objects` API group.. - */ - removeMemberships(parameters: AppContext.RemoveMembersParameters | AppContext.RemoveMembershipsParameters): Promise>; - /** - * PubNub Channel Groups API group. - */ - get channelGroups(): PubNubChannelGroups; - /** - * PubNub Push Notifications API group. - */ - get push(): PubNubPushNotifications; - /** - * Share file to a specific channel. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - sendFile(parameters: FileSharing.SendFileParameters, callback: ResultCallback): void; - /** - * Share file to a specific channel. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous file sharing response. - */ - sendFile(parameters: FileSharing.SendFileParameters): Promise; - /** - * Publish file message to a specific channel. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - publishFile(parameters: FileSharing.PublishFileMessageParameters, callback: ResultCallback): void; - /** - * Publish file message to a specific channel. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous publish file message response. - */ - publishFile(parameters: FileSharing.PublishFileMessageParameters): Promise; - /** - * Retrieve list of shared files in specific channel. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - listFiles(parameters: FileSharing.ListFilesParameters, callback: ResultCallback): void; - /** - * Retrieve list of shared files in specific channel. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous shared files list response. - */ - listFiles(parameters: FileSharing.ListFilesParameters): Promise; - /** - * Get file download Url. - * - * @param parameters - Request configuration parameters. - * - * @returns File download Url. - */ - getFileUrl(parameters: FileSharing.FileUrlParameters): FileSharing.FileUrlResponse; - /** - * Download shared file from specific channel. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - downloadFile(parameters: FileSharing.DownloadFileParameters, callback: ResultCallback): void; - /** - * Download shared file from specific channel. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous download shared file response. - */ - downloadFile(parameters: FileSharing.DownloadFileParameters): Promise; - /** - * Delete shared file from specific channel. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - deleteFile(parameters: FileSharing.DeleteFileParameters, callback: ResultCallback): void; - /** - * Delete shared file from specific channel. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous delete shared file response. - */ - deleteFile(parameters: FileSharing.DeleteFileParameters): Promise; - /** - Get current high-precision timetoken. - * - * @param callback - Request completion handler callback. - */ - time(callback: ResultCallback): void; - /** - * Get current high-precision timetoken. - * - * @returns Asynchronous get current timetoken response. - */ - time(): Promise; - /** - * Encrypt data. - * - * @param data - Stringified data which should be encrypted using `CryptoModule`. - * @deprecated - * @param [customCipherKey] - Cipher key which should be used to encrypt data. **Deprecated:** - * use {@link Configuration#cryptoModule|cryptoModule} instead. - * - * @returns Data encryption result as a string. - */ - encrypt(data: string | Payload, customCipherKey?: string): string; - /** - * Decrypt data. - * - * @param data - Stringified data which should be encrypted using `CryptoModule`. - * @param [customCipherKey] - Cipher key which should be used to decrypt data. **Deprecated:** - * use {@link Configuration#cryptoModule|cryptoModule} instead. - * - * @returns Data decryption result as an object. - */ - decrypt(data: string, customCipherKey?: string): Payload | null; - /** - * Encrypt file content. - * - * @param file - File which should be encrypted using `CryptoModule`. - * - * @returns Asynchronous file encryption result. - * - * @throws Error if source file not provided. - * @throws File constructor not provided. - * @throws Crypto module is missing (if non-legacy flow used). - */ - encryptFile(file: PubNubFileInterface): Promise; - /** - * Encrypt file content. - * - * @param key - Cipher key which should be used to encrypt data. - * @param file - File which should be encrypted using legacy cryptography. - * - * @returns Asynchronous file encryption result. - * - * @throws Error if source file not provided. - * @throws File constructor not provided. - * @throws Crypto module is missing (if non-legacy flow used). - */ - encryptFile(key: string, file: PubNubFileInterface): Promise; - /** - * Decrypt file content. - * - * @param file - File which should be decrypted using legacy cryptography. - * - * @returns Asynchronous file decryption result. - * - * @throws Error if source file not provided. - * @throws File constructor not provided. - * @throws Crypto module is missing (if non-legacy flow used). - */ - decryptFile(file: PubNubFileInterface): Promise; - /** - * Decrypt file content. - * - * @param key - Cipher key which should be used to decrypt data. - * @param [file] - File which should be decrypted using legacy cryptography. - * - * @returns Asynchronous file decryption result. - * - * @throws Error if source file not provided. - * @throws File constructor not provided. - * @throws Crypto module is missing (if non-legacy flow used). - */ - decryptFile(key: string | PubNubFileInterface, file?: PubNubFileInterface): Promise; -} diff --git a/lib/types/core/pubnub-objects.d.ts b/lib/types/core/pubnub-objects.d.ts deleted file mode 100644 index 5bbff4424..000000000 --- a/lib/types/core/pubnub-objects.d.ts +++ /dev/null @@ -1,283 +0,0 @@ -/** - * PubNub Objects API module. - */ -import { ResultCallback } from './types/api'; -import * as AppContext from './types/api/app-context'; -/** - * PubNub App Context API interface. - */ -export default class PubNubObjects { - /** - * Fetch a paginated list of UUID Metadata objects. - * - * @param callback - Request completion handler callback. - */ - getAllUUIDMetadata(callback: ResultCallback>): void; - /** - * Fetch a paginated list of UUID Metadata objects. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - getAllUUIDMetadata(parameters: AppContext.GetAllMetadataParameters>, callback: ResultCallback>): void; - /** - * Fetch a paginated list of UUID Metadata objects. - * - * @param [parameters] - Request configuration parameters. - * - * @returns Asynchronous get all UUID metadata response. - */ - getAllUUIDMetadata(parameters?: AppContext.GetAllMetadataParameters>): Promise>; - /** - * Fetch UUID Metadata object for currently configured PubNub client `uuid`. - * - * @param callback - Request completion handler callback. - */ - getUUIDMetadata(callback: ResultCallback>): void; - /** - * Fetch a specific UUID Metadata object. - * - * @param parameters - Request configuration parameters. Will fetch UUID metadata object for - * currently configured PubNub client `uuid` if not set. - * @param callback - Request completion handler callback. - */ - getUUIDMetadata(parameters: AppContext.GetUUIDMetadataParameters, callback: ResultCallback>): void; - /** - * Fetch a specific UUID Metadata object. - * - * @param [parameters] - Request configuration parameters. Will fetch UUID Metadata object for - * currently configured PubNub client `uuid` if not set. - * - * @returns Asynchronous get UUID metadata response. - */ - getUUIDMetadata(parameters?: AppContext.GetUUIDMetadataParameters): Promise>; - /** - * Update specific UUID Metadata object. - * - * @param parameters - Request configuration parameters. Will set UUID metadata for currently - * configured PubNub client `uuid` if not set. - * @param callback - Request completion handler callback. - */ - setUUIDMetadata(parameters: AppContext.SetUUIDMetadataParameters, callback: ResultCallback>): void; - /** - * Update specific UUID Metadata object. - * - * @param parameters - Request configuration parameters. Will set UUID metadata for currently - * configured PubNub client `uuid` if not set. - * - * @returns Asynchronous set UUID metadata response. - */ - setUUIDMetadata(parameters: AppContext.SetUUIDMetadataParameters): Promise>; - /** - * Remove UUID Metadata object for currently configured PubNub client `uuid`. - * - * @param callback - Request completion handler callback. - */ - removeUUIDMetadata(callback: ResultCallback): void; - /** - * Remove a specific UUID Metadata object. - * - * @param parameters - Request configuration parameters. Will remove UUID metadata for currently - * configured PubNub client `uuid` if not set. - * @param callback - Request completion handler callback. - */ - removeUUIDMetadata(parameters: AppContext.RemoveUUIDMetadataParameters, callback: ResultCallback): void; - /** - * Remove a specific UUID Metadata object. - * - * @param [parameters] - Request configuration parameters. Will remove UUID metadata for currently - * configured PubNub client `uuid` if not set. - * - * @returns Asynchronous UUID metadata remove response. - */ - removeUUIDMetadata(parameters?: AppContext.RemoveUUIDMetadataParameters): Promise; - /** - * Fetch a paginated list of Channel Metadata objects. - * - * @param callback - Request completion handler callback. - */ - getAllChannelMetadata(callback: ResultCallback>): void; - /** - * Fetch a paginated list of Channel Metadata objects. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - getAllChannelMetadata(parameters: AppContext.GetAllMetadataParameters>, callback: ResultCallback>): void; - /** - * Fetch a paginated list of Channel Metadata objects. - * - * @param [parameters] - Request configuration parameters. - * - * @returns Asynchronous get all Channel metadata response. - */ - getAllChannelMetadata(parameters?: AppContext.GetAllMetadataParameters>): Promise>; - /** - * Fetch Channel Metadata object. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - getChannelMetadata(parameters: AppContext.GetChannelMetadataParameters, callback: ResultCallback>): void; - /** - * Fetch a specific Channel Metadata object. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous get Channel metadata response. - */ - getChannelMetadata(parameters: AppContext.GetChannelMetadataParameters): Promise>; - /** - * Update specific Channel Metadata object. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - setChannelMetadata(parameters: AppContext.SetChannelMetadataParameters, callback: ResultCallback>): void; - /** - * Update specific Channel Metadata object. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous set Channel metadata response. - */ - setChannelMetadata(parameters: AppContext.SetChannelMetadataParameters): Promise>; - /** - * Remove Channel Metadata object. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - removeChannelMetadata(parameters: AppContext.RemoveChannelMetadataParameters, callback: ResultCallback): void; - /** - * Remove a specific Channel Metadata object. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous Channel metadata remove response. - */ - removeChannelMetadata(parameters: AppContext.RemoveChannelMetadataParameters): Promise; - /** - * Fetch a paginated list of Channel Member objects. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - getChannelMembers(parameters: AppContext.GetMembersParameters, callback: ResultCallback>): void; - /** - * Fetch a paginated list of Channel Member objects. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous get Channel Members response. - */ - getChannelMembers(parameters: AppContext.GetMembersParameters): Promise>; - /** - * Update specific Channel Members list. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - setChannelMembers(parameters: AppContext.SetChannelMembersParameters, callback: ResultCallback>): void; - /** - * Update specific Channel Members list. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous update Channel Members list response. - */ - setChannelMembers(parameters: AppContext.SetChannelMembersParameters): Promise>; - /** - * Remove Members from the Channel. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - removeChannelMembers(parameters: AppContext.RemoveMembersParameters, callback: ResultCallback>): void; - /** - * Remove Members from the Channel. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous Channel Members remove response. - */ - removeChannelMembers(parameters: AppContext.RemoveMembersParameters): Promise>; - /** - * Fetch a specific UUID Memberships list for currently configured PubNub client `uuid`. - * - * @param callback - Request completion handler callback. - * - * @returns Asynchronous get UUID Memberships list response or `void` in case if `callback` - * provided. - */ - getMemberships(callback: ResultCallback>): void; - /** - * Fetch a specific UUID Memberships list. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - getMemberships(parameters: AppContext.GetMembershipsParameters, callback: ResultCallback>): void; - /** - * Fetch a specific UUID Memberships list. - * - * @param [parameters] - Request configuration parameters. Will fetch UUID Memberships list for - * currently configured PubNub client `uuid` if not set. - * - * @returns Asynchronous get UUID Memberships list response. - */ - getMemberships(parameters?: AppContext.GetMembershipsParameters): Promise>; - /** - * Update specific UUID Memberships list. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - setMemberships(parameters: AppContext.SetMembershipsParameters, callback: ResultCallback>): void; - /** - * Update specific UUID Memberships list. - * - * @param parameters - Request configuration parameters or callback from overload. - * - * @returns Asynchronous update UUID Memberships list response. - */ - setMemberships(parameters: AppContext.SetMembershipsParameters): Promise>; - /** - * Remove a specific UUID Memberships. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - removeMemberships(parameters: AppContext.RemoveMembershipsParameters, callback: ResultCallback>): void; - /** - * Remove a specific UUID Memberships. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous UUID Memberships remove response. - */ - removeMemberships(parameters: AppContext.RemoveMembershipsParameters): Promise>; - /** - * Fetch paginated list of specific Space members or specific User memberships. - * - * @param parameters - Request configuration parameters. - * @param [callback] - Request completion handler callback. - * - * @returns Asynchronous get specific Space members or specific User memberships response. - * - * @deprecated Use {@link PubNubObjects#getChannelMembers} or {@link PubNubObjects#getMemberships} methods instead. - */ - fetchMemberships(parameters: AppContext.GetMembershipsParameters | AppContext.GetMembersParameters, callback?: ResultCallback | AppContext.UserMembersResponse>): Promise | AppContext.UserMembersResponse | void>; - /** - * Add members to specific Space or memberships specific User. - * - * @param parameters - Request configuration parameters. - * @param [callback] - Request completion handler callback. - * - * @returns Asynchronous add members to specific Space or memberships specific User response or - * `void` in case if `callback` provided. - * - * @deprecated Use {@link PubNubObjects#setChannelMembers} or {@link PubNubObjects#setMemberships} methods instead. - */ - addMemberships(parameters: AppContext.SetMembershipsParameters | AppContext.SetChannelMembersParameters, callback?: ResultCallback | AppContext.SetMembersResponse>): Promise | AppContext.SetMembersResponse | void>; -} diff --git a/lib/types/core/pubnub-push.d.ts b/lib/types/core/pubnub-push.d.ts deleted file mode 100644 index 5e384656a..000000000 --- a/lib/types/core/pubnub-push.d.ts +++ /dev/null @@ -1,64 +0,0 @@ -/** - * PubNub Push Notifications API module. - */ -import { ResultCallback, StatusCallback } from './types/api'; -import * as Push from './types/api/push'; -/** - * PubNub Push Notifications API interface. - */ -export default class PubNubPushNotifications { - /** - * Fetch device's push notification enabled channels. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - listChannels(parameters: Push.ListDeviceChannelsParameters, callback: ResultCallback): void; - /** - * Fetch device's push notification enabled channels. - * - * @param parameters - Request configuration parameters. - * - * @returns Asynchronous get device channels response. - */ - listChannels(parameters: Push.ListDeviceChannelsParameters): Promise; - /** - * Enable push notifications on channels for device. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - addChannels(parameters: Push.ManageDeviceChannelsParameters, callback: StatusCallback): void; - /** - * Enable push notifications on channels for device. - * - * @param parameters - Request configuration parameters. - */ - addChannels(parameters: Push.ManageDeviceChannelsParameters): Promise; - /** - * Disable push notifications on channels for device. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - removeChannels(parameters: Push.ManageDeviceChannelsParameters, callback: StatusCallback): void; - /** - * Disable push notifications on channels for device. - * - * @param parameters - Request configuration parameters. - */ - removeChannels(parameters: Push.ManageDeviceChannelsParameters): Promise; - /** - * Disable push notifications for device. - * - * @param parameters - Request configuration parameters. - * @param callback - Request completion handler callback. - */ - deleteDevice(parameters: Push.RemoveDeviceParameters, callback: StatusCallback): void; - /** - * Disable push notifications for device. - * - * @param parameters - Request configuration parameters. - */ - deleteDevice(parameters: Push.RemoveDeviceParameters): Promise; -} diff --git a/lib/types/core/types/api/access-manager.d.ts b/lib/types/core/types/api/access-manager.d.ts deleted file mode 100644 index bf85bda51..000000000 --- a/lib/types/core/types/api/access-manager.d.ts +++ /dev/null @@ -1,464 +0,0 @@ -/** - * Metadata which will be associated with access token. - */ -export type Metadata = Record; -/** - * Channel-specific token permissions. - */ -export type ChannelTokenPermissions = { - /** - * Whether `read` operations are permitted for corresponding level or not. - */ - read?: boolean; - /** - * Whether `write` operations are permitted for corresponding level or not. - */ - write?: boolean; - /** - * Whether `get` operations are permitted for corresponding level or not. - */ - get?: boolean; - /** - * Whether `manage` operations are permitted for corresponding level or not. - */ - manage?: boolean; - /** - * Whether `update` operations are permitted for corresponding level or not. - */ - update?: boolean; - /** - * Whether `join` operations are permitted for corresponding level or not. - */ - join?: boolean; - /** - * Whether `delete` operations are permitted for corresponding level or not. - */ - delete?: boolean; -}; -/** - * Space-specific token permissions. - */ -type SpaceTokenPermissions = ChannelTokenPermissions; -/** - * Channel group-specific token permissions. - */ -export type ChannelGroupTokenPermissions = { - /** - * Whether `read` operations are permitted for corresponding level or not. - */ - read?: boolean; - /** - * Whether `manage` operations are permitted for corresponding level or not. - */ - manage?: boolean; -}; -/** - * Uuid-specific token permissions. - */ -export type UuidTokenPermissions = { - /** - * Whether `get` operations are permitted for corresponding level or not. - */ - get?: boolean; - /** - * Whether `update` operations are permitted for corresponding level or not. - */ - update?: boolean; - /** - * Whether `delete` operations are permitted for corresponding level or not. - */ - delete?: boolean; -}; -/** - * User-specific token permissions. - */ -type UserTokenPermissions = UuidTokenPermissions; -/** - * Generate access token with permissions. - * - * Generate time-limited access token with required permissions for App Context objects. - */ -export type ObjectsGrantTokenParameters = { - /** - * Total number of minutes for which the token is valid. - * - * The minimum allowed value is `1`. - * The maximum is `43,200` minutes (`30` days). - */ - ttl: number; - /** - * Object containing resource permissions. - */ - resources?: { - /** - * Object containing `spaces` metadata permissions. - */ - spaces?: Record; - /** - * Object containing `users` permissions. - */ - users?: Record; - }; - /** - * Object containing permissions to multiple resources specified by a RegEx pattern. - */ - patterns?: { - /** - * Object containing `spaces` metadata permissions. - */ - spaces?: Record; - /** - * Object containing `users` permissions. - */ - users?: Record; - }; - /** - * Extra metadata to be published with the request. - * - * **Important:** Values must be scalar only; `arrays` or `objects` aren't supported. - */ - meta?: Metadata; - /** - * Single `userId` which is authorized to use the token to make API requests to PubNub. - */ - authorizedUserId?: string; -}; -/** - * Generate token with permissions. - * - * Generate time-limited access token with required permissions for resources. - */ -export type GrantTokenParameters = { - /** - * Total number of minutes for which the token is valid. - * - * The minimum allowed value is `1`. - * The maximum is `43,200` minutes (`30` days). - */ - ttl: number; - /** - * Object containing resource permissions. - */ - resources?: { - /** - * Object containing `uuid` metadata permissions. - */ - uuids?: Record; - /** - * Object containing `channel` permissions. - */ - channels?: Record; - /** - * Object containing `channel group` permissions. - */ - groups?: Record; - }; - /** - * Object containing permissions to multiple resources specified by a RegEx pattern. - */ - patterns?: { - /** - * Object containing `uuid` metadata permissions to apply to all `uuids` matching the RegEx - * pattern. - */ - uuids?: Record; - /** - * Object containing `channel` permissions to apply to all `channels` matching the RegEx - * pattern. - */ - channels?: Record; - /** - * Object containing `channel group` permissions to apply to all `channel groups` matching the - * RegEx pattern. - */ - groups?: Record; - }; - /** - * Extra metadata to be published with the request. - * - * **Important:** Values must be scalar only; `arrays` or `objects` aren't supported. - */ - meta?: Metadata; - /** - * Single `uuid` which is authorized to use the token to make API requests to PubNub. - */ - authorized_uuid?: string; -}; -/** - * Response with generated access token. - */ -export type GrantTokenResponse = string; -/** - * Access token for which permissions should be revoked. - */ -export type RevokeParameters = string; -/** - * Response with revoked access token. - */ -export type RevokeTokenResponse = Record; -/** - * Channel-specific permissions. - * - * Permissions include objects to the App Context Channel object as well. - */ -type ChannelPermissions = { - /** - * Whether `read` operations are permitted for corresponding level or not. - */ - r?: 0 | 1; - /** - * Whether `write` operations are permitted for corresponding level or not. - */ - w?: 0 | 1; - /** - * Whether `delete` operations are permitted for corresponding level or not. - */ - d?: 0 | 1; - /** - * Whether `get` operations are permitted for corresponding level or not. - */ - g?: 0 | 1; - /** - * Whether `update` operations are permitted for corresponding level or not. - */ - u?: 0 | 1; - /** - * Whether `manage` operations are permitted for corresponding level or not. - */ - m?: 0 | 1; - /** - * Whether `join` operations are permitted for corresponding level or not. - */ - j?: 0 | 1; - /** - * Duration for which permissions has been granted. - */ - ttl?: number; -}; -/** - * Channel group-specific permissions. - */ -type ChannelGroupPermissions = { - /** - * Whether `read` operations are permitted for corresponding level or not. - */ - r?: 0 | 1; - /** - * Whether `manage` operations are permitted for corresponding level or not. - */ - m?: 0 | 1; - /** - * Duration for which permissions has been granted. - */ - ttl?: number; -}; -/** - * App Context User-specific permissions. - */ -type UserPermissions = { - /** - * Whether `get` operations are permitted for corresponding level or not. - */ - g?: 0 | 1; - /** - * Whether `update` operations are permitted for corresponding level or not. - */ - u?: 0 | 1; - /** - * Whether `delete` operations are permitted for corresponding level or not. - */ - d?: 0 | 1; - /** - * Duration for which permissions has been granted. - */ - ttl?: number; -}; -/** - * Common permissions audit response content. - */ -type BaseAuditResponse = { - /** - * Permissions level. - */ - level: Level; - /** - * Subscription key at which permissions has been granted. - */ - subscribe_key: string; - /** - * Duration for which permissions has been granted. - */ - ttl?: number; -}; -/** - * Auth keys permissions for specified `level`. - */ -type AuthKeysPermissions = { - /** - * Auth keys-based permissions for specified `level` permission. - */ - auths: Record; -}; -/** - * Single channel permissions audit result. - */ -type ChannelPermissionsResponse = BaseAuditResponse<'channel+auth'> & { - /** - * Name of channel for which permissions audited. - */ - channel: string; -} & AuthKeysPermissions; -/** - * Multiple channels permissions audit result. - */ -type ChannelsPermissionsResponse = BaseAuditResponse<'channel'> & { - /** - * Per-channel permissions. - */ - channels: Record>; -}; -/** - * Single channel group permissions result. - */ -type ChannelGroupPermissionsResponse = BaseAuditResponse<'channel-group+auth'> & { - /** - * Name of channel group for which permissions audited. - */ - 'channel-group': string; -} & AuthKeysPermissions; -/** - * Multiple channel groups permissions audit result. - */ -type ChannelGroupsPermissionsResponse = BaseAuditResponse<'channel'> & { - /** - * Per-channel group permissions. - */ - 'channel-groups': Record>; -}; -/** - * App Context User permissions audit result. - */ -type UserPermissionsResponse = BaseAuditResponse<'user'> & { - /** - * Name of channel for which `user` permissions audited. - */ - channel: string; -} & AuthKeysPermissions; -/** - * Global sub-key level permissions audit result. - */ -type SubKeyPermissionsResponse = BaseAuditResponse<'subkey'> & { - /** - * Per-channel permissions. - */ - channels: Record>; - /** - * Per-channel group permissions. - */ - 'channel-groups': Record>; - /** - * Per-object permissions. - */ - objects: Record>; -}; -/** - * Response with permission information. - */ -export type PermissionsResponse = ChannelPermissionsResponse | ChannelsPermissionsResponse | ChannelGroupPermissionsResponse | ChannelGroupsPermissionsResponse | UserPermissionsResponse | SubKeyPermissionsResponse; -/** - * Audit permissions for provided auth keys / global permissions. - * - * Audit permissions on specific channel and / or channel group for the set of auth keys. - */ -export type AuditParameters = { - /** - * Name of channel for which channel-based permissions should be checked for {@link authKeys}. - */ - channel?: string; - /** - * Name of channel group for which channel group-based permissions should be checked for {@link authKeys}. - */ - channelGroup?: string; - /** - * List of auth keys for which permissions should be checked. - * - * Leave this empty to check channel / group -based permissions or global permissions. - * - * @default `[]` - */ - authKeys?: string[]; -}; -/** - * Grant permissions for provided auth keys / global permissions. - * - * Grant permissions on specific channel and / or channel group for the set of auth keys. - */ -export type GrantParameters = { - /** - * List of channels for which permissions should be granted. - */ - channels?: string[]; - /** - * List of channel groups for which permissions should be granted. - */ - channelGroups?: string[]; - /** - * List of App Context UUID for which permissions should be granted. - */ - uuids?: string[]; - /** - * List of auth keys for which permissions should be granted on specified objects. - * - * Leave this empty to grant channel / group -based permissions or global permissions. - */ - authKeys?: string[]; - /** - * Whether `read` operations are permitted for corresponding level or not. - * - * @default `false` - */ - read?: boolean; - /** - * Whether `write` operations are permitted for corresponding level or not. - * - * @default `false` - */ - write?: boolean; - /** - * Whether `delete` operations are permitted for corresponding level or not. - * - * @default `false` - */ - delete?: boolean; - /** - * Whether `get` operations are permitted for corresponding level or not. - * - * @default `false` - */ - get?: boolean; - /** - * Whether `update` operations are permitted for corresponding level or not. - * - * @default `false` - */ - update?: boolean; - /** - * Whether `manage` operations are permitted for corresponding level or not. - * - * @default `false` - */ - manage?: boolean; - /** - * Whether `join` operations are permitted for corresponding level or not. - * - * @default `false` - */ - join?: boolean; - /** - * For how long permissions should be effective (in minutes). - * - * @default `1440` - */ - ttl?: number; -}; -export {}; diff --git a/lib/types/core/types/api/app-context.d.ts b/lib/types/core/types/api/app-context.d.ts deleted file mode 100644 index 2017fdcf7..000000000 --- a/lib/types/core/types/api/app-context.d.ts +++ /dev/null @@ -1,875 +0,0 @@ -/** - * Partial nullability helper type. - */ -type PartialNullable = { - [P in keyof T]?: T[P] | null; -}; -/** - * Custom data which should be associated with metadata objects or their relation. - */ -export type CustomData = { - [key: string]: string | number | boolean | null; -}; -/** - * Type provides shape of App Context parameters which is common to the all objects types to - * be updated. - */ -type ObjectParameters = { - custom?: Custom; -}; -/** - * Type provides shape of App Context object which is common to the all objects types received - * from the PubNub service. - */ -export type ObjectData = { - /** - * Unique App Context object identifier. - * - * **Important:** For channel it is different from the channel metadata object name. - */ - id: string; - /** - * Last date and time when App Context object has been updated. - * - * String built from date using ISO 8601. - */ - updated: string; - /** - * App Context version hash. - */ - eTag: string; - /** - * Additional data associated with App Context object. - * - * **Important:** Values must be scalars; only arrays or objects are supported. - * {@link /docs/sdks/javascript/api-reference/objects#app-context-filtering-language-definition|App Context - * filtering language} doesn’t support filtering by custom properties. - */ - custom?: Custom | null; -}; -/** - * Type provides shape of object which let establish relation between metadata objects. - */ -type ObjectsRelation = { - /** - * App Context object unique identifier. - */ - id: string; - /** - * App Context objects relation status. - */ - status?: string; - /** - * Additional data associated with App Context object relation (membership or members). - * - * **Important:** Values must be scalars; only arrays or objects are supported. - * {@link /docs/sdks/javascript/api-reference/objects#app-context-filtering-language-definition|App Context - * filtering language} doesn’t support filtering by custom properties. - */ - custom?: Custom; -}; -/** - * Response page cursor. - */ -type Page = { - /** - * Random string returned from the server, indicating a specific position in a data set. - * - * Used for forward pagination, it fetches the next page, allowing you to continue from where - * you left off. - */ - next?: string; - /** - * Random string returned from the server, indicating a specific position in a data set. - * - * Used for backward pagination, it fetches the previous page, enabling access to earlier - * data. - * - * **Important:** Ignored if the `next` parameter is supplied. - */ - prev?: string; -}; -/** - * Metadata objects include options. - * - * Allows to configure what additional information should be included into service response. - */ -type IncludeOptions = { - /** - * Whether to include total number of App Context objects in the response. - * - * @default `false` - */ - totalCount?: boolean; - /** - * Whether to include App Context object `custom` field in the response. - * - * @default `false` - */ - customFields?: boolean; -}; -/** - * Membership objects include options. - * - * Allows to configure what additional information should be included into service response. - */ -type MembershipsIncludeOptions = IncludeOptions & { - /** - * Whether to include all {@link ChannelMetadata} fields in the response. - * - * @default `false` - */ - channelFields?: boolean; - /** - * Whether to include {@link ChannelMetadata} `custom` field in the response. - * - * @default `false` - */ - customChannelFields?: boolean; - /** - * Whether to include the membership's status field in the response. - * - * @default `false` - */ - statusField?: boolean; - /** - * Whether to include the channel's status field in the response. - * - * @default `false` - */ - channelStatusField?: boolean; - /** - * Whether to include channel's type fields in the response. - * - * @default `false` - */ - channelTypeField?: boolean; -}; -/** - * Members objects include options. - * - * Allows to configure what additional information should be included into service response. - */ -type MembersIncludeOptions = IncludeOptions & { - /** - * Whether to include all {@link UUIMetadata} fields in the response. - * - * @default `false` - */ - UUIDFields?: boolean; - /** - * Whether to include {@link UUIMetadata} `custom` field in the response. - * - * @default `false` - */ - customUUIDFields?: boolean; - /** - * Whether to include the members's status field in the response. - * - * @default `false` - */ - statusField?: boolean; - /** - * Whether to include the user's status field in the response. - * - * @default `false` - */ - UUIDStatusField?: boolean; - /** - * Whether to include user's type fields in the response. - * - * @default `false` - */ - UUIDTypeField?: boolean; -}; -/** - * Type provides shape of App Context parameters which is common to the all objects types to - * fetch them by pages. - */ -type PagedRequestParameters = { - /** - * Fields which can be additionally included into response. - */ - include?: Include; - /** - * Expression used to filter the results. - * - * Only objects whose properties satisfy the given expression are returned. The filter language is - * {@link /docs/sdks/javascript/api-reference/objects#app-context-filtering-language-definition|defined here}. - */ - filter?: string; - /** - * Fetched App Context objects sorting options. - */ - sort?: Sort; - /** - * Number of objects to return in response. - * - * **Important:** Maximum for this API is `100` objects per-response. - * - * @default `100` - */ - limit?: number; - /** - * Response pagination configuration. - */ - page?: Page; -}; -/** - * Type provides shape of App Context object fetch response which is common to the all objects - * types received from the PubNub service. - */ -type ObjectResponse = { - /** - * App Context objects list fetch result status code. - */ - status: number; - /** - * Received App Context object information. - */ - data: ObjectType; -}; -/** - * Type provides shape of App Context objects fetch response which is common to the all - * objects types received from the PubNub service. - */ -type PagedResponse = ObjectResponse & { - /** - * Total number of App Context objects in the response. - */ - totalCount?: number; - /** - * Random string returned from the server, indicating a specific position in a data set. - * - * Used for forward pagination, it fetches the next page, allowing you to continue from where - * you left off. - */ - next?: string; - /** - * Random string returned from the server, indicating a specific position in a data set. - * - * Used for backward pagination, it fetches the previous page, enabling access to earlier - * data. - * - * **Important:** Ignored if the `next` parameter is supplied. - */ - prev?: string; -}; -/** - * Key-value pair of a property to sort by, and a sort direction. - */ -type MetadataSortingOptions = keyof Omit | ({ - [K in keyof Omit]?: 'asc' | 'desc' | null; -} & { - [key: `custom.${string}`]: 'asc' | 'desc' | null; -}); -/** - * Key-value pair of a property to sort by, and a sort direction. - */ -type MembershipsSortingOptions = 'channel.id' | 'channel.name' | 'channel.description' | 'channel.updated' | 'space.id' | 'space.name' | 'space.description' | 'space.updated' | 'updated' | { - /** - * Sort results by channel's `id` in ascending (`asc`) or descending (`desc`) order. - * - * Specify `null` for default sorting direction (ascending). - */ - 'channel.id'?: 'asc' | 'desc' | null; - /** - * Sort results by channel's `name` in ascending (`asc`) or descending (`desc`) order. - * - * Specify `null` for default sorting direction (ascending). - */ - 'channel.name'?: 'asc' | 'desc' | null; - /** - * Sort results by channel's `description` in ascending (`asc`) or descending (`desc`) order. - * - * Specify `null` for default sorting direction (ascending). - */ - 'channel.description'?: 'asc' | 'desc' | null; - /** - * Sort results by channel's `update` in ascending (`asc`) or descending (`desc`) order. - * - * Specify `null` for default sorting direction (ascending). - */ - 'channel.updated'?: 'asc' | 'desc' | null; - /** - * Sort results by channel's `id` in ascending (`asc`) or descending (`desc`) order. - * - * Specify `null` for default sorting direction (ascending). - * - * @deprecated Use `channel.id` instead. - */ - 'space.id'?: 'asc' | 'desc' | null; - /** - * Sort results by channel's `name` in ascending (`asc`) or descending (`desc`) order. - * - * Specify `null` for default sorting direction (ascending). - * - * @deprecated Use `channel.name` instead. - */ - 'space.name'?: 'asc' | 'desc' | null; - /** - * Sort results by channel's `description` in ascending (`asc`) or descending (`desc`) order. - * - * Specify `null` for default sorting direction (ascending). - * - * @deprecated Use `channel.name` instead. - */ - 'space.description'?: 'asc' | 'desc' | null; - /** - * Sort results by channel's `update` in ascending (`asc`) or descending (`desc`) order. - * - * Specify `null` for default sorting direction (ascending). - * - * @deprecated Use `channel.updated` instead. - */ - 'space.updated'?: 'asc' | 'desc' | null; - /** - * Sort results by `updated` in ascending (`asc`) or descending (`desc`) order. - * - * Specify `null` for default sorting direction (ascending). - */ - updated?: 'asc' | 'desc' | null; -}; -/** - * Key-value pair of a property to sort by, and a sort direction. - */ -type MembersSortingOptions = 'uuid.id' | 'uuid.name' | 'uuid.updated' | 'user.id' | 'user.name' | 'user.updated' | 'updated' | { - /** - * Sort results by user's `id` in ascending (`asc`) or descending (`desc`) order. - * - * Specify `null` for default sorting direction (ascending). - */ - 'uuid.id'?: 'asc' | 'desc' | null; - /** - * Sort results by user's `name` in ascending (`asc`) or descending (`desc`) order. - * - * Specify `null` for default sorting direction (ascending). - */ - 'uuid.name'?: 'asc' | 'desc' | null; - /** - * Sort results by user's `update` in ascending (`asc`) or descending (`desc`) order. - * - * Specify `null` for default sorting direction (ascending). - */ - 'uuid.updated'?: 'asc' | 'desc' | null; - /** - * Sort results by user's `id` in ascending (`asc`) or descending (`desc`) order. - * - * Specify `null` for default sorting direction (ascending). - * - * @deprecated Use `uuid.id` instead. - */ - 'user.id'?: 'asc' | 'desc' | null; - /** - * Sort results by user's `name` in ascending (`asc`) or descending (`desc`) order. - * - * Specify `null` for default sorting direction (ascending). - * - * @deprecated Use `uuid.name` instead. - */ - 'user.name'?: 'asc' | 'desc' | null; - /** - * Sort results by user's `update` in ascending (`asc`) or descending (`desc`) order. - * - * Specify `null` for default sorting direction (ascending). - * - * @deprecated Use `uuid.updated` instead. - */ - 'user.updated'?: 'asc' | 'desc' | null; - /** - * Sort results by `updated` in ascending (`asc`) or descending (`desc`) order. - * - * Specify `null` for default sorting direction (ascending). - */ - updated?: 'asc' | 'desc' | null; -}; -/** - * Fetch All UUID or Channel Metadata request parameters. - */ -export type GetAllMetadataParameters = PagedRequestParameters>; -/** - * Type which describes own UUID metadata object fields. - */ -type UUIDMetadataFields = { - /** - * Display name for the user. - */ - name?: string; - /** - * The user's email address. - */ - email?: string; - /** - * User's identifier in an external system. - */ - externalId?: string; - /** - * The URL of the user's profile picture. - */ - profileUrl?: string; - /** - * User's object type information. - */ - type?: string; - /** - * User's object status. - */ - status?: string; -}; -/** - * Updated UUID metadata object. - * - * Type represents updated UUID metadata object which will be pushed to the PubNub service. - */ -type UUIDMetadata = ObjectParameters & Partial; -/** - * Received UUID metadata object. - * - * Type represents UUID metadata retrieved from the PubNub service. - */ -export type UUIDMetadataObject = ObjectData & PartialNullable; -/** - * Response with fetched page of UUID metadata objects. - */ -export type GetAllUUIDMetadataResponse = PagedResponse>; -/** - * Fetch UUID Metadata request parameters. - */ -export type GetUUIDMetadataParameters = { - /** - * Unique user identifier. - * - * **Important:** If not supplied then current user's uuid is used. - * - * @default Current `uuid`. - */ - uuid?: string; - /** - * Unique user identifier. - * - * **Important:** If not supplied then current user's uuid is used. - * - * @default Current `userId`. - * - * @deprecated Use `getUUIDMetadata()` method instead. - */ - userId?: string; - /** - * Fields which can be additionally included into response. - */ - include?: Omit; -}; -/** - * Response with requested UUID metadata object. - */ -export type GetUUIDMetadataResponse = ObjectResponse>; -/** - * Update UUID Metadata request parameters. - */ -export type SetUUIDMetadataParameters = { - /** - * Unique user identifier. - * - * **Important:** If not supplied then current user's uuid is used. - * - * @default Current `uuid`. - */ - uuid?: string; - /** - * Unique user identifier. - * - * **Important:** If not supplied then current user's uuid is used. - * - * @default Current `userId`. - * - * @deprecated Use `setUUIDMetadata()` method instead. - */ - userId?: string; - /** - * Metadata, which should be associated with UUID. - */ - data: UUIDMetadata; - /** - * Fields which can be additionally included into response. - */ - include?: Omit; -}; -/** - * Response with result of the UUID metadata object update. - */ -export type SetUUIDMetadataResponse = ObjectResponse>; -/** - * Remove UUID Metadata request parameters. - */ -export type RemoveUUIDMetadataParameters = { - /** - * Unique user identifier. - * - * **Important:** If not supplied then current user's uuid is used. - * - * @default Current `uuid`. - */ - uuid?: string; - /** - * Unique user identifier. - * - * **Important:** If not supplied then current user's uuid is used. - * - * @default Current `userId`. - * - * @deprecated Use `removeUUIDMetadata()` method instead. - */ - userId?: string; -}; -/** - * Response with result of the UUID metadata removal. - */ -export type RemoveUUIDMetadataResponse = ObjectResponse>; -/** - * Type which describes own Channel metadata object fields. - */ -type ChannelMetadataFields = { - /** - * Name of a channel. - */ - name?: string; - /** - * Description of a channel. - */ - description?: string; - /** - * Channel's object type information. - */ - type?: string; - /** - * Channel's object status. - */ - status?: string; -}; -/** - * Updated channel metadata object. - * - * Type represents updated channel metadata object which will be pushed to the PubNub service. - */ -type ChannelMetadata = ObjectParameters & Partial; -/** - * Received channel metadata object. - * - * Type represents chanel metadata retrieved from the PubNub service. - */ -export type ChannelMetadataObject = ObjectData & PartialNullable; -/** - * Response with fetched page of channel metadata objects. - */ -export type GetAllChannelMetadataResponse = PagedResponse>; -/** - * Fetch Channel Metadata request parameters. - */ -export type GetChannelMetadataParameters = { - /** - * Channel name. - */ - channel: string; - /** - * Space identifier. - * - * @deprecated Use `getChannelMetadata()` method instead. - */ - spaceId?: string; - /** - * Fields which can be additionally included into response. - */ - include?: Omit; -}; -/** - * Response with requested channel metadata object. - */ -export type GetChannelMetadataResponse = ObjectResponse>; -/** - * Update Channel Metadata request parameters. - */ -export type SetChannelMetadataParameters = { - /** - * Channel name. - */ - channel: string; - /** - * Space identifier. - * - * @deprecated Use `setChannelMetadata()` method instead. - */ - spaceId?: string; - /** - * Metadata, which should be associated with UUID. - */ - data: ChannelMetadata; - /** - * Fields which can be additionally included into response. - */ - include?: Omit; -}; -/** - * Response with result of the channel metadata object update. - */ -export type SetChannelMetadataResponse = ObjectResponse>; -/** - * Remove Channel Metadata request parameters. - */ -export type RemoveChannelMetadataParameters = { - /** - * Channel name. - */ - channel: string; - /** - * Space identifier. - * - * @deprecated Use `removeChannelMetadata()` method instead. - */ - spaceId?: string; -}; -/** - * Response with result of the channel metadata removal. - */ -export type RemoveChannelMetadataResponse = ObjectResponse>; -/** - * Related channel metadata object. - * - * Type represents chanel metadata which has been used to create membership relation with UUID. - */ -type MembershipsObject = Omit, 'id'> & { - channel: ChannelMetadataObject | { - id: string; - }; -}; -/** - * Response with fetched page of UUID membership objects. - */ -type MembershipsResponse = PagedResponse>; -/** - * Fetch Memberships request parameters. - */ -export type GetMembershipsParameters = PagedRequestParameters & { - /** - * Unique user identifier. - * - * **Important:** If not supplied then current user's uuid is used. - * - * @default Current `uuid`. - */ - uuid?: string; - /** - * Unique user identifier. - * - * **Important:** If not supplied then current user's uuid is used. - * - * @default Current `uuidId`. - * - * @deprecated Use `uuid` field instead. - */ - userId?: string; -}; -/** - * Response with requested channel memberships information. - */ -export type GetMembershipsResponse = MembershipsResponse; -/** - * Update Memberships request parameters. - */ -export type SetMembershipsParameters = PagedRequestParameters, MembershipsSortingOptions> & { - /** - * Unique user identifier. - * - * **Important:** If not supplied then current user's uuid is used. - * - * @default Current `uuid`. - */ - uuid?: string; - /** - * Unique user identifier. - * - * **Important:** If not supplied then current user's uuid is used. - * - * @default Current `userId`. - * - * @deprecated Use `uuid` field instead. - */ - userId?: string; - /** - * List of channels with which UUID membership should be established. - */ - channels: Array>; - /** - * List of channels with which UUID membership should be established. - * - * @deprecated Use `channels` field instead. - */ - spaces?: Array, 'id'> & { - /** - * Unique Space object identifier. - */ - spaceId: string; - })>; -}; -/** - * Response with requested channel memberships information change. - */ -export type SetMembershipsResponse = MembershipsResponse; -/** - * Remove Memberships request parameters. - */ -export type RemoveMembershipsParameters = PagedRequestParameters & { - /** - * Unique user identifier. - * - * **Important:** If not supplied then current user's uuid is used. - * - * @default Current `uuid`. - */ - uuid?: string; - /** - * Unique user identifier. - * - * **Important:** If not supplied then current user's uuid is used. - * - * @default Current `userId`. - * - * @deprecated Use {@link uuid} field instead. - */ - userId?: string; - /** - * List of channels for which membership which UUID should be removed. - */ - channels: string[]; - /** - * List of space names for which membership which UUID should be removed. - * - * @deprecated Use {@link channels} field instead. - */ - spaceIds?: string[]; -}; -/** - * Response with remaining memberships. - */ -export type RemoveMembershipsResponse = MembershipsResponse; -/** - * Related UUID metadata object. - * - * Type represents UUID metadata which has been used to when added members to the channel. - */ -type MembersObject = Omit, 'id'> & { - uuid: UUIDMetadataObject | { - id: string; - }; -}; -/** - * Response with fetched page of channel member objects. - */ -type MembersResponse = PagedResponse>; -/** - * Fetch Members request parameters. - */ -export type GetMembersParameters = PagedRequestParameters & { - /** - * Channel name. - */ - channel: string; - /** - * Space identifier. - * - * @deprecated Use `channel` field instead. - */ - spaceId?: string; -}; -/** - * Response with requested channel memberships information. - */ -export type GetMembersResponse = MembersResponse; -/** - * Update Members request parameters. - */ -export type SetChannelMembersParameters = PagedRequestParameters, MembersSortingOptions> & { - /** - * Channel name. - */ - channel: string; - /** - * Space identifier. - * - * @deprecated Use `channel` field instead. - */ - spaceId?: string; - /** - * List of UUIDs which should be added as `channel` members. - */ - uuids: Array>; - /** - * List of UUIDs which should be added as `channel` members. - * - * @deprecated Use `uuids` field instead. - */ - users?: Array, 'id'> & { - /** - * Unique User object identifier. - */ - userId: string; - })>; -}; -/** - * Response with requested channel members information change. - */ -export type SetMembersResponse = MembersResponse; -/** - * Remove Members request parameters. - */ -export type RemoveMembersParameters = PagedRequestParameters & { - /** - * Channel name. - */ - channel: string; - /** - * Space identifier. - * - * @deprecated Use {@link channel} field instead. - */ - spaceId?: string; - /** - * List of UUIDs which should be removed from the `channel` members list. - * removed. - */ - uuids: string[]; - /** - * List of user identifiers which should be removed from the `channel` members list. - * removed. - * - * @deprecated Use {@link uuids} field instead. - */ - userIds?: string[]; -}; -/** - * Response with remaining members. - */ -export type RemoveMembersResponse = MembersResponse; -/** - * Related User metadata object. - * - * Type represents User metadata which has been used to when added members to the Space. - */ -type UserMembersObject = Omit, 'id'> & { - user: UUIDMetadataObject | { - id: string; - }; -}; -/** - * Response with fetched page of Space member objects. - */ -export type UserMembersResponse = PagedResponse>; -type SpaceMembershipObject = Omit, 'id'> & { - space: ChannelMetadataObject | { - id: string; - }; -}; -/** - * Response with fetched page of User membership objects. - */ -export type SpaceMembershipsResponse = PagedResponse>; -export {}; diff --git a/lib/types/core/types/api/channel-groups.d.ts b/lib/types/core/types/api/channel-groups.d.ts deleted file mode 100644 index 80cd4717a..000000000 --- a/lib/types/core/types/api/channel-groups.d.ts +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Add or remove Channels to the channel group request parameters. - */ -export type ManageChannelGroupChannelsParameters = { - /** - * Name of the channel group for which channels list should be changed. - */ - channelGroup: string; - /** - * List of channels to be added or removed. - */ - channels: string[]; -}; -/** - * Channel group channels list manage response. - */ -export type ManageChannelGroupChannelsResponse = Record; -/** - * Response with result of the all channel groups list. - */ -export type ListAllChannelGroupsResponse = { - /** - * All channel groups with channels. - */ - groups: string[]; -}; -/** - * List Channel Group Channels request parameters. - */ -export type ListChannelGroupChannelsParameters = { - /** - * Name of the channel group for which list of channels should be retrieved. - */ - channelGroup: string; -}; -/** - * Response with result of the list channel group channels. - */ -export type ListChannelGroupChannelsResponse = { - /** - * List of the channels registered withing specified channel group. - */ - channels: string[]; -}; -/** - * Delete Channel Group request parameters. - */ -export type DeleteChannelGroupParameters = { - /** - * Name of the channel group which should be removed. - */ - channelGroup: string; -}; -/** - * Delete channel group response. - */ -export type DeleteChannelGroupResponse = Record; diff --git a/lib/types/core/types/api/file-sharing.d.ts b/lib/types/core/types/api/file-sharing.d.ts deleted file mode 100644 index 5bc19beee..000000000 --- a/lib/types/core/types/api/file-sharing.d.ts +++ /dev/null @@ -1,357 +0,0 @@ -/** - * File Sharing REST API module. - */ -import { PubNubFileInterface } from '../file'; -import { Payload } from './index'; -/** - * Shared file object. - */ -export type SharedFile = { - /** - * Name with which file has been stored. - */ - name: string; - /** - * Unique service-assigned file identifier. - */ - id: string; - /** - * Shared file size. - */ - size: number; - /** - * ISO 8601 time string when file has been shared. - */ - created: string; -}; -/** - * List Files request parameters. - */ -export type ListFilesParameters = { - /** - * Name of channel for which list of files should be requested. - */ - channel: string; - /** - * How many entries return with single response. - */ - limit?: number; - /** - * Next files list page token. - */ - next?: string; -}; -/** - * List Files request response. - */ -export type ListFilesResponse = { - /** - * Files list fetch result status code. - */ - status: number; - /** - * List of fetched file objects. - */ - data: SharedFile[]; - /** - * Next files list page token. - */ - next: string; - /** - * Number of retrieved files. - */ - count: number; -}; -/** - * Send File request parameters. - */ -export type SendFileParameters = Omit & { - /** - * Channel to send the file to. - */ - channel: string; - /** - * File to send. - */ - file: FileParameters; -}; -/** - * Send File request response. - */ -export type SendFileResponse = PublishFileMessageResponse & { - /** - * Send file request processing status code. - */ - status: number; - /** - * Actual file name under which file has been stored. - * - * File name and unique {@link id} can be used to download file from the channel later. - * - * **Important:** Actual file name may be different from the one which has been used during file - * upload. - */ - name: string; - /** - * Unique file identifier. - * - * Unique file identifier and it's {@link name} can be used to download file from the channel - * later. - */ - id: string; -}; -/** - * Upload File request parameters. - */ -export type UploadFileParameters = { - /** - * Unique file identifier. - * - * Unique file identifier, and it's {@link fileName} can be used to download file from the channel - * later. - */ - fileId: string; - /** - * Actual file name under which file has been stored. - * - * File name and unique {@link fileId} can be used to download file from the channel later. - * - * **Note:** Actual file name may be different from the one which has been used during file - * upload. - */ - fileName: string; - /** - * File which should be uploaded. - */ - file: PubNubFileInterface; - /** - * Pre-signed file upload Url. - */ - uploadUrl: string; - /** - * An array of form fields to be used in the pre-signed POST request. - * - * **Important:** Form data fields should be passed in exact same order as received from - * the PubNub service. - */ - formFields: { - /** - * Form data field name. - */ - name: string; - /** - * Form data field value. - */ - value: string; - }[]; -}; -/** - * Upload File request response. - */ -export type UploadFileResponse = { - /** - * Upload File request processing status code. - */ - status: number; - /** - * Service processing result response. - */ - message: Payload; -}; -/** - * Generate File Upload URL request parameters. - */ -export type GenerateFileUploadUrlParameters = { - /** - * Name of channel to which file should be uploaded. - */ - channel: string; - /** - * Actual name of the file which should be uploaded. - */ - name: string; -}; -/** - * Generation File Upload URL request response. - */ -export type GenerateFileUploadUrlResponse = { - /** - * Unique file identifier. - * - * Unique file identifier, and it's {@link name} can be used to download file from the channel - * later. - */ - id: string; - /** - * Actual file name under which file has been stored. - * - * File name and unique {@link id} can be used to download file from the channel later. - * - * **Note:** Actual file name may be different from the one which has been used during file - * upload. - */ - name: string; - /** - * Pre-signed URL for file upload. - */ - url: string; - /** - * An array of form fields to be used in the pre-signed POST request. - * - * **Important:** Form data fields should be passed in exact same order as received from - * the PubNub service. - */ - formFields: { - /** - * Form data field name. - */ - name: string; - /** - * Form data field value. - */ - value: string; - }[]; -}; -/** - * Publish File Message request parameters. - */ -export type PublishFileMessageParameters = { - /** - * Name of channel to which file has been sent. - */ - channel: string; - /** - * File annotation message. - */ - message?: Payload; - /** - * Custom file and message encryption key. - * - * @deprecated Use {@link Configuration#cryptoModule|cryptoModule} configured for PubNub client - * instance or encrypt file prior {@link PubNub#sendFile|sendFile} method call. - */ - cipherKey?: string; - /** - * Unique file identifier. - * - * Unique file identifier, and it's {@link fileName} can be used to download file from the channel - * later. - */ - fileId: string; - /** - * Actual file name under which file has been stored. - * - * File name and unique {@link fileId} can be used to download file from the channel later. - * - * **Note:** Actual file name may be different from the one which has been used during file - * upload. - */ - fileName: string; - /** - * Whether published file messages should be stored in the channel's history. - * - * **Note:** If `storeInHistory` not specified, then the history configuration on the key is - * used. - * - * @default `true` - */ - storeInHistory?: boolean; - /** - * How long the message should be stored in the channel's history. - * - * **Note:** If not specified, defaults to the key set's retention value. - * - * @default `0` - */ - ttl?: number; - /** - * Metadata, which should be associated with published file. - * - * Associated metadata can be utilized by message filtering feature. - */ - meta?: Payload; -}; -/** - * Publish File Message request response. - */ -export type PublishFileMessageResponse = { - /** - * High-precision time when published file message has been received by the PubNub service. - */ - timetoken: string; -}; -/** - * Download File request parameters. - */ -export type DownloadFileParameters = FileUrlParameters & { - /** - * Custom file and message encryption key. - * - * @deprecated Use {@link Configuration#cryptoModule|cryptoModule} configured for PubNub client - * instance or encrypt file prior {@link PubNub#sendFile|sendFile} method call. - */ - cipherKey?: string; -}; -/** - * Generate File download Url request parameters. - */ -export type FileUrlParameters = { - /** - * Name of channel where file has been sent. - */ - channel: string; - /** - * Unique file identifier. - * - * Unique file identifier and it's {@link name} can be used to download file from the channel - * later. - */ - id: string; - /** - * Actual file name under which file has been stored. - * - * File name and unique {@link id} can be used to download file from the channel later. - * - * **Important:** Actual file name may be different from the one which has been used during file - * upload. - */ - name: string; -}; -/** - * Generate File Download Url response. - */ -export type FileUrlResponse = string; -/** - * Delete File request parameters. - */ -export type DeleteFileParameters = { - /** - * Name of channel where file has been sent. - */ - channel: string; - /** - * Unique file identifier. - * - * Unique file identifier and it's {@link name} can be used to download file from the channel - * later. - */ - id: string; - /** - * Actual file name under which file has been stored. - * - * File name and unique {@link id} can be used to download file from the channel later. - * - * **Important:** Actual file name may be different from the one which has been used during file - * upload. - */ - name: string; -}; -/** - * Delete File request response. - */ -export type DeleteFileResponse = { - /** - * Delete File request processing status code. - */ - status: number; -}; diff --git a/lib/types/core/types/api/history.d.ts b/lib/types/core/types/api/history.d.ts deleted file mode 100644 index 9ae00f1c2..000000000 --- a/lib/types/core/types/api/history.d.ts +++ /dev/null @@ -1,395 +0,0 @@ -import { Payload } from './index'; -/** - * Get history request parameters. - */ -export type GetHistoryParameters = { - /** - * Channel to return history messages from. - */ - channel: string; - /** - * Specifies the number of historical messages to return. - * - * **Note:** Maximum `100` messages can be returned in single response. - * - * @default `100` - */ - count?: number; - /** - * Whether message `meta` information should be fetched or not. - * - * @default `false` - */ - includeMeta?: boolean; - /** - * Timetoken delimiting the `start` of `time` slice (exclusive) to pull messages from. - */ - start?: string; - /** - * Timetoken delimiting the `end` of `time` slice (inclusive) to pull messages from. - */ - end?: string; - /** - * Whether timeline should traverse in reverse starting with the oldest message first or not. - * - * If both `start` and `end` arguments are provided, `reverse` is ignored and messages are - * returned starting with the newest message. - */ - reverse?: boolean; - /** - * Whether message timetokens should be stringified or not. - * - * @default `false` - */ - stringifiedTimeToken?: boolean; -}; -/** - * Get history response. - */ -export type GetHistoryResponse = { - /** - * List of previously published messages. - */ - messages: { - /** - * Message payload (decrypted). - */ - entry: Payload; - /** - * When message has been received by PubNub service. - */ - timetoken: string | number; - /** - * Additional data which has been published along with message to be used with real-time - * events filter expression. - */ - meta?: Payload; - /** - * Message decryption error (if attempt has been done). - */ - error?: string; - }[]; - /** - * Received messages timeline start. - */ - startTimeToken: string | number; - /** - * Received messages timeline end. - */ - endTimeToken: string | number; -}; -/** - * PubNub-defined message type. - * - * Types of messages which can be retrieved with fetch messages REST API. - */ -export declare enum PubNubMessageType { - /** - * Regular message. - */ - Message = -1, - /** - * File message. - */ - Files = 4 -} -/** - * Per-message actions information. - */ -export type Actions = { - /** - * Message action type. - */ - [t: string]: { - /** - * Message action value. - */ - [v: string]: { - /** - * Unique identifier of the user which reacted on message. - */ - uuid: string; - /** - * High-precision PubNub timetoken with time when {@link uuid} reacted on message. - */ - actionTimetoken: string; - }; - }; -}; -/** - * Additional message actions fetch information. - */ -export type MoreActions = { - /** - * Prepared fetch messages with actions REST API URL. - */ - url: string; - /** - * Next page time offset. - */ - start: string; - /** - * Number of messages to retrieve with next page. - */ - max: number; -}; -/** - * Common content of the fetched message. - */ -type BaseFetchedMessage = { - /** - * Name of channel for which message has been retrieved. - */ - channel: string; - /** - * When message has been received by PubNub service. - */ - timetoken: string | number; - /** - * Message publisher unique identifier. - */ - uuid?: string; - /** - * Additional data which has been published along with message to be used with real-time - * events filter expression. - */ - meta?: Payload; - /** - * Message decryption error (if attempt has been done). - */ - error?: string; -}; -/** - * Regular message published to the channel. - */ -export type RegularMessage = BaseFetchedMessage & { - /** - * Message payload (decrypted). - */ - message: Payload; - /** - * PubNub-defined message type. - */ - messageType?: PubNubMessageType.Message; -}; -/** - * File message published to the channel. - */ -export type FileMessage = BaseFetchedMessage & { - /** - * Message payload (decrypted). - */ - message: { - /** - * File annotation message. - */ - message?: Payload; - /** - * File information. - */ - file: { - /** - * Unique file identifier. - */ - id: string; - /** - * Name with which file has been stored. - */ - name: string; - /** - * File's content mime-type. - */ - 'mime-type': string; - /** - * Stored file size. - */ - size: number; - /** - * Pre-computed file download Url. - */ - url: string; - }; - }; - /** - * PubNub-defined message type. - */ - messageType?: PubNubMessageType.Files; -}; -/** - * Fetched message entry in channel messages list. - */ -export type FetchedMessage = RegularMessage | FileMessage; -/** - * Fetched with actions message entry in channel messages list. - */ -export type FetchedMessageWithActions = FetchedMessage & { - /** - * List of message reactions. - */ - actions?: Actions; - /** - * List of message reactions. - * - * @deprecated Use {@link actions} field instead. - */ - data?: Actions; -}; -/** - * Fetch messages request parameters. - */ -export type FetchMessagesParameters = { - /** - * Specifies channels to return history messages from. - * - * **Note:** Maximum of `500` channels are allowed. - */ - channels: string[]; - /** - * Specifies the number of historical messages to return per channel. - * - * **Note:** Default is `100` per single channel and `25` per multiple channels or per - * single channel if {@link includeMessageActions} is used. - * - * @default `100` or `25` - */ - count?: number; - /** - * Whether message type should be returned with each history message or not. - * - * @default `true` - */ - includeMessageType?: boolean; - /** - * Whether publisher `uuid` should be returned with each history message or not. - * - * @default `true` - */ - includeUUID?: boolean; - /** - * Whether publisher `uuid` should be returned with each history message or not. - * - * @deprecated Use {@link includeUUID} property instead. - */ - includeUuid?: boolean; - /** - * Whether message `meta` information should be fetched or not. - * - * @default `false` - */ - includeMeta?: boolean; - /** - * Whether message-added message actions should be fetched or not. - * - * If used, the limit of messages retrieved will be `25` per single channel. - * - * Each message can have a maximum of `25000` actions attached to it. Consider the example of - * querying for 10 messages. The first five messages have 5000 actions attached to each of - * them. The API will return the first 5 messages and all their 25000 actions. The response - * will also include a `more` link to get the remaining 5 messages. - * - * **Important:** Truncation will happen if the number of actions on the messages returned - * is > 25000. - * - * @default `false` - * - * @throws Exception if API is called with more than one channel. - */ - includeMessageActions?: boolean; - /** - * Timetoken delimiting the `start` of `time` slice (exclusive) to pull messages from. - */ - start?: string; - /** - * Timetoken delimiting the `end` of `time` slice (inclusive) to pull messages from. - */ - end?: string; - /** - * Whether message timetokens should be stringified or not. - * - * @default `false` - */ - stringifiedTimeToken?: boolean; -}; -/** - * Fetch messages response. - */ -export type FetchMessagesForChannelsResponse = { - /** - * List of previously published messages per requested channel. - */ - channels: { - [p: string]: FetchedMessage[]; - }; -}; -/** - * Fetch messages with reactions response. - */ -export type FetchMessagesWithActionsResponse = { - channels: { - [p: string]: FetchedMessageWithActions[]; - }; - /** - * Additional message actions fetch information. - */ - more: MoreActions; -}; -/** - * Fetch messages response. - */ -export type FetchMessagesResponse = FetchMessagesForChannelsResponse | FetchMessagesWithActionsResponse; -/** - * Message count request parameters. - */ -export type MessageCountParameters = { - /** - * The channels to fetch the message count. - */ - channels: string[]; - /** - * List of timetokens, in order of the {@link channels} list. - * - * Specify a single timetoken to apply it to all channels. Otherwise, the list of timetokens - * must be the same length as the list of {@link channels}, or the function returns an error - * flag. - */ - channelTimetokens?: string[]; - /** - * High-precision PubNub timetoken starting from which number of messages should be counted. - * - * Same timetoken will be used to count messages for each passed {@link channels}. - * - * @deprecated Use {@link channelTimetokens} field instead. - */ - timetoken?: string; -}; -/** - * Message count response. - */ -export type MessageCountResponse = { - /** - * Map of channel names to the number of counted messages. - */ - channels: Record; -}; -/** - * Delete messages from channel parameters. - */ -export type DeleteMessagesParameters = { - /** - * Specifies channel messages to be deleted from history. - */ - channel: string; - /** - * Timetoken delimiting the start of time slice (exclusive) to delete messages from. - */ - start?: string; - /** - * Timetoken delimiting the end of time slice (inclusive) to delete messages from. - */ - end?: string; -}; -/** - * Delete messages from channel response. - */ -export type DeleteMessagesResponse = Record; -export {}; diff --git a/lib/types/core/types/api/index.d.ts b/lib/types/core/types/api/index.d.ts deleted file mode 100644 index f934c8bc5..000000000 --- a/lib/types/core/types/api/index.d.ts +++ /dev/null @@ -1,95 +0,0 @@ -import RequestOperation from '../../constants/operations'; -import StatusCategory from '../../constants/categories'; -/** - * Endpoint call completion block with result. - * - * **Note:** Endpoints which return consumable data use this callback. - */ -export type ResultCallback = (status: Status, response: ResponseType | null) => void; -/** - * Endpoint acknowledgment completion block. - * - * **Note:** Endpoints which return only acknowledgment or error status use this callback. - */ -export type StatusCallback = (status: Status) => void; -/** - * REST API endpoint processing status. - * - * **Note:** Used as {@link ResultCallback} and {@link StatusCallback} callbacks first argument type and - * {@link PubNubError} instance `status` field value type. - */ -export type Status = { - /** - * Whether status represent error or not. - */ - error: boolean; - /** - * API call status category. - */ - category: StatusCategory; - /** - * Type of REST API endpoint which reported status. - */ - operation?: RequestOperation; - /** - * REST API response status code. - */ - statusCode: number; - /** - * Error data provided by REST API. - */ - errorData?: Error | Payload; - /** - * Additional status information. - */ - [p: string]: Payload | Error | undefined; -}; -/** - * Real-time PubNub client status change event. - */ -export type StatusEvent = { - /** - * API call status category. - */ - category: StatusCategory; - /** - * Type of REST API endpoint which reported status. - */ - operation?: RequestOperation; - /** - * Information about error. - */ - error?: string | boolean; - /** - * List of channels for which status update announced. - */ - affectedChannels?: string[]; - /** - * List of currently subscribed channels. - * - * List of channels from which PubNub client receives real-time updates. - */ - subscribedChannels?: string[]; - /** - * List of channel groups for which status update announced. - */ - affectedChannelGroups?: string[]; - /** - * High-precision timetoken which has been used with previous subscription loop. - */ - lastTimetoken?: number | string; - /** - * High-precision timetoken which is used for current subscription loop. - */ - currentTimetoken?: number | string; -}; -/** - * General payload type. - * - * Type should be used for: - * * generic messages and signals content, - * * published message metadata. - */ -export type Payload = string | number | boolean | { - [key: string]: Payload | null; -} | Payload[]; diff --git a/lib/types/core/types/api/message-action.d.ts b/lib/types/core/types/api/message-action.d.ts deleted file mode 100644 index 7ad1941a8..000000000 --- a/lib/types/core/types/api/message-action.d.ts +++ /dev/null @@ -1,153 +0,0 @@ -/** - * Message reaction object type. - */ -export type MessageAction = { - /** - * What feature this message action represents. - */ - type: string; - /** - * Value which should be stored along with message action. - */ - value: string; - /** - * Unique identifier of the user which added message action. - */ - uuid: string; - /** - * Timetoken of when message reaction has been added. - * - * **Note:** This token required when it will be required to remove raction. - */ - actionTimetoken: string; - /** - * Timetoken of message to which `action` has been added. - */ - messageTimetoken: string; -}; -/** - * More message actions fetch information. - */ -export type MoreMessageActions = { - /** - * Prepared REST API url to fetch next page with message actions. - */ - url: string; - /** - * Message action timetoken denoting the start of the range requested with next page. - * - * **Note:** Return values will be less than {@link start}. - */ - start: string; - /** - * Message action timetoken denoting the end of the range requested with next page. - * - * **Note:** Return values will be greater than or equal to {@link end}. - */ - end: string; - /** - * Number of message actions to return in next response. - */ - limit: number; -}; -/** - * Add Message Action request parameters. - */ -export type AddMessageActionParameters = { - /** - * Name of channel which stores the message for which {@link action} should be added. - */ - channel: string; - /** - * Timetoken of message for which {@link action} should be added. - */ - messageTimetoken: string; - /** - * Message `action` information. - */ - action: { - /** - * What feature this message action represents. - */ - type: string; - /** - * Value which should be stored along with message action. - */ - value: string; - }; -}; -/** - * Response with added message action object. - */ -export type AddMessageActionResponse = { - data: MessageAction; -}; -/** - * Get Message Actions request parameters. - */ -export type GetMessageActionsParameters = { - /** - * Name of channel from which list of messages `actions` should be retrieved. - */ - channel: string; - /** - * Message action timetoken denoting the start of the range requested. - * - * **Note:** Return values will be less than {@link start}. - */ - start?: string; - /** - * Message action timetoken denoting the end of the range requested. - * - * **Note:** Return values will be greater than or equal to {@link end}. - */ - end?: string; - /** - * Number of message actions to return in response. - */ - limit?: number; -}; -/** - * Response with message actions in specific `channel`. - */ -export type GetMessageActionsResponse = { - /** - * Retrieved list of message actions. - */ - data: MessageAction[]; - /** - * Received message actions time frame start. - */ - start: string | null; - /** - * Received message actions time frame end. - */ - end: string | null; - /** - * More message actions fetch information. - */ - more?: MoreMessageActions; -}; -/** - * Remove Message Action request parameters. - */ -export type RemoveMessageActionParameters = { - /** - * Name of channel which store message for which `action` should be removed. - */ - channel: string; - /** - * Timetoken of message for which `action` should be removed. - */ - messageTimetoken: string; - /** - * Action addition timetoken. - */ - actionTimetoken: string; -}; -/** - * Response with message remove result. - */ -export type RemoveMessageActionResponse = { - data: Record; -}; diff --git a/lib/types/core/types/api/presence.d.ts b/lib/types/core/types/api/presence.d.ts deleted file mode 100644 index 28519378d..000000000 --- a/lib/types/core/types/api/presence.d.ts +++ /dev/null @@ -1,210 +0,0 @@ -import { Payload } from './index'; -/** - * Associated presence state fetch parameters. - */ -export type GetPresenceStateParameters = { - /** - * The subscriber uuid to get the current state. - * - * @default `current uuid` - */ - uuid?: string; - /** - * List of channels for which state associated with {@link uuid} should be retrieved. - * - * **Important:** Either {@link channels} or {@link channelGroups} should be provided; - */ - channels?: string[]; - /** - * List of channel groups for which state associated with {@link uuid} should be retrieved. - * - * **Important:** Either {@link channels} or {@link channelGroups} should be provided; - */ - channelGroups?: string[]; -}; -/** - * Associated presence state fetch response. - */ -export type GetPresenceStateResponse = { - /** - * Channels map to state which `uuid` has associated with them. - */ - channels: Record; -}; -/** - * Associate presence state parameters. - */ -export type SetPresenceStateParameters = { - /** - * List of channels for which state should be associated with {@link uuid}. - */ - channels?: string[]; - /** - * List of channel groups for which state should be associated with {@link uuid}. - */ - channelGroups?: string[]; - /** - * State which should be associated with `uuid` on provided list of {@link channels} and {@link channelGroups}. - */ - state: Payload; -}; -/** - * Associate presence state parameters using heartbeat. - */ -export type SetPresenceStateWithHeartbeatParameters = { - /** - * List of channels for which state should be associated with {@link uuid}. - */ - channels?: string[]; - /** - * State which should be associated with `uuid` on provided list of {@link channels}. - */ - state: Payload; - /** - * Whether `presence/heartbeat` REST API should be used to manage state or not. - * - * @default `false` - */ - withHeartbeat: boolean; -}; -/** - * Associate presence state response. - */ -export type SetPresenceStateResponse = { - /** - * State which has been associated with `uuid` on provided list of channels and groups. - */ - state: Payload; -}; -/** - * Announce heartbeat parameters. - */ -export type PresenceHeartbeatParameters = { - /** - * How long the server will consider the client alive for presence.The value is in seconds. - */ - heartbeat: number; - /** - * List of channels for which heartbeat should be announced for {@link uuid}. - */ - channels?: string[]; - /** - * List of channel groups for which heartbeat should be announced for {@link uuid}. - */ - channelGroups?: string[]; - /** - * State which should be associated with `uuid` on provided list of {@link channels} and {@link channelGroups}. - */ - state?: Payload; -}; -/** - * Announce heartbeat response. - */ -export type PresenceHeartbeatResponse = Record; -/** - * Presence leave parameters. - */ -export type PresenceLeaveParameters = { - /** - * List of channels for which `uuid` should be marked as `offline`. - */ - channels?: string[]; - /** - /** - * List of channel groups for which `uuid` should be marked as `offline`. - */ - channelGroups?: string[]; -}; -/** - * Presence leave response. - */ -export type PresenceLeaveResponse = Record; -/** - * Channel / channel group presence fetch parameters.. - */ -export type HereNowParameters = { - /** - * List of channels for which presence should be retrieved. - */ - channels?: string[]; - /** - * List of channel groups for which presence should be retrieved. - */ - channelGroups?: string[]; - /** - * Whether `uuid` information should be included in response or not. - * - * **Note:** Only occupancy information will be returned if both {@link includeUUIDs} and {@link includeState} is - * set to `false`. - * - * @default `true` - */ - includeUUIDs?: boolean; - /** - * Whether state associated with `uuid` should be included in response or not. - * - * @default `false`. - */ - includeState?: boolean; - /** - * Additional query parameters. - */ - queryParameters?: Record; -}; -/** - * `uuid` where now response. - */ -export type HereNowResponse = { - /** - * Total number of channels for which presence information received. - */ - totalChannels: number; - /** - * Total occupancy for all retrieved channels. - */ - totalOccupancy: number; - /** - * List of channels to which `uuid` currently subscribed. - */ - channels: { - [p: string]: { - /** - * List of received channel subscribers. - * - * **Note:** Field is missing if `uuid` and `state` not included. - */ - occupants: { - uuid: string; - state?: Payload | null; - }[]; - /** - * Name of channel for which presence information retrieved. - */ - name: string; - /** - * Total number of active subscribers in single channel. - */ - occupancy: number; - }; - }; -}; -/** - * `uuid` where now parameters. - */ -export type WhereNowParameters = { - /** - * The subscriber uuid to get the current state. - * - * @default `current uuid` - */ - uuid?: string; -}; -/** - * `uuid` where now response. - */ -export type WhereNowResponse = { - /** - * Channels map to state which `uuid` has associated with them. - */ - channels: string[]; -}; diff --git a/lib/types/core/types/api/push-notifications.d.ts b/lib/types/core/types/api/push-notifications.d.ts deleted file mode 100644 index 57ab65076..000000000 --- a/lib/types/core/types/api/push-notifications.d.ts +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Type of Push Notifications gateway which should be used with Push Notifications REST API. - */ -type PushGateway = 'apns2' | 'gcm'; -/** - * Basic information required by Push Notifications REST API about device. - */ -type DevicePush = { - /** - * Device ID for which list of registered channel push notifications will be changed. - */ - device: string; - /** - * Push Notifications gateway to use. - * - * **Important:** Depends from the source of `device` token and can be `apns2` (for token - * provided during device registration using Apple's framework) or `gcm` (when used Firebase - * or similar framework to receive token). - */ - pushGateway: PushGateway; -}; -/** - * Register and unregister push notifications for device request parameters. - */ -export type ManageDeviceChannelsParameters = { - /** - * List of channels to be added or removed. - */ - channels: string[]; -} & DevicePush; -/** - * List Device Channels request parameters. - */ -export type ListDeviceChannelsParameters = DevicePush; -/** - * Response with result of the list device channels. - */ -export type ListDeviceChannelsResponse = { - /** - * List of the channels for which `device` will receive push notifications. - */ - channels: string[]; -}; -/** - * Delete Push Notification for device request parameters. - */ -export type DeleteDeviceParameters = DevicePush; -export {}; diff --git a/lib/types/core/types/api/push.d.ts b/lib/types/core/types/api/push.d.ts deleted file mode 100644 index 6d67ed8cf..000000000 --- a/lib/types/core/types/api/push.d.ts +++ /dev/null @@ -1,122 +0,0 @@ -/** - * Common managed channels push notification parameters. - */ -type ManagedDeviceChannels = { - /** - * Channels to register or unregister with mobile push notifications. - */ - channels: string[]; - /** - * The device ID to associate with mobile push notifications. - */ - device: string; - /** - * Starting channel for pagination. - * - * **Note:** Use the last channel from the previous page request. - */ - start?: string; - /** - * Number of channels to return for pagination. - * - * **Note:** maximum of 1000 tokens at a time. - * - * @default `500` - */ - count?: number; -}; -/** - * List all FCM device push notification enabled channels parameters. - */ -type ListFCMDeviceChannelsParameters = Omit; -/** - * List all APNS device push notification enabled channels parameters. - * - * @deprecated Use `APNS2`-based endpoints. - */ -type ListAPNSDeviceChannelsParameters = Omit; -/** - * List all APNS2 device push notification enabled channels parameters. - */ -type ListAPNS2DeviceChannelsParameters = Omit; -/** - * List all device push notification enabled channels parameters. - */ -export type ListDeviceChannelsParameters = ListFCMDeviceChannelsParameters | ListAPNSDeviceChannelsParameters | ListAPNS2DeviceChannelsParameters; -/** - * List all device push notification enabled channels response. - */ -export type ListDeviceChannelsResponse = { - /** - * List of channels registered for device push notifications. - */ - channels: string[]; -}; -/** - * Manage FCM device push notification enabled channels parameters. - */ -type ManageFCMDeviceChannelsParameters = ManagedDeviceChannels & { - /** - * Push Notifications gateway type. - */ - pushGateway: 'gcm'; -}; -/** - * Manage APNS device push notification enabled channels parameters. - * - * @deprecated Use `APNS2`-based endpoints. - */ -type ManageAPNSDeviceChannelsParameters = ManagedDeviceChannels & { - /** - * Push Notifications gateway type. - */ - pushGateway: 'apns'; -}; -/** - * Manage APNS2 device push notification enabled channels parameters. - */ -type ManageAPNS2DeviceChannelsParameters = ManagedDeviceChannels & { - /** - * Push Notifications gateway type. - */ - pushGateway: 'apns2'; - /** - * Environment within which device should manage list of channels with enabled notifications. - */ - environment?: 'development' | 'production'; - /** - * Notifications topic name (usually it is bundle identifier of application for Apple platform). - */ - topic: string; -}; -/** - * Manage device push notification enabled channels parameters. - */ -export type ManageDeviceChannelsParameters = ManageFCMDeviceChannelsParameters | ManageAPNSDeviceChannelsParameters | ManageAPNS2DeviceChannelsParameters; -/** - * Manage device push notification enabled channels response. - */ -export type ManageDeviceChannelsResponse = Record; -/** - * Remove all FCM device push notification enabled channels parameters. - */ -type RemoveFCMDeviceParameters = Omit; -/** - * Manage APNS device push notification enabled channels parameters. - * - * @deprecated Use `APNS2`-based endpoints. - */ -type RemoveAPNSDeviceParameters = Omit; -/** - * Manage APNS2 device push notification enabled channels parameters. - */ -type RemoveAPNS2DeviceParameters = Omit; -/** - * Remove all device push notification enabled channels parameters. - */ -export type RemoveDeviceParameters = RemoveFCMDeviceParameters | RemoveAPNSDeviceParameters | RemoveAPNS2DeviceParameters; -/** - * Remove all device push notification enabled channels response. - */ -export type RemoveDeviceResponse = Record; -export {}; diff --git a/lib/types/core/types/api/subscription.d.ts b/lib/types/core/types/api/subscription.d.ts deleted file mode 100644 index 0c8e1e19e..000000000 --- a/lib/types/core/types/api/subscription.d.ts +++ /dev/null @@ -1,296 +0,0 @@ -import { RequestParameters as SubscribeRequestParameters, VSPMembershipObjectData, AppContextObjectData, MessageActionData, PubNubEventType, SpaceObjectData, UserObjectData, PresenceData, FileData } from '../../endpoints/subscribe'; -import { AbortSignal } from '../../components/abort_signal'; -import { Payload } from './index'; -/** - * Time cursor. - * - * Cursor used by subscription loop to identify point in time after which updates will be - * delivered. - */ -export type SubscriptionCursor = { - /** - * PubNub high-precision timestamp. - * - * Aside of specifying exact time of receiving data / event this token used to catchup / - * follow on real-time updates. - */ - timetoken: string | number; - /** - * Data center region for which `timetoken` has been generated. - */ - region?: number; -}; -/** - * Common real-time event. - */ -type Event = { - /** - * Channel to which real-time event has been sent. - */ - channel: string; - /** - * Actual subscription at which real-time event has been received. - * - * PubNub client provide various ways to subscribe to the real-time stream: channel groups, - * wildcard subscription, and spaces. - * - * **Note:** Value will be `null` if it is the same as {@link channel}. - */ - subscription: string | null; - /** - * High-precision PubNub timetoken with time when event has been received by PubNub services. - */ - timetoken: string; -}; -/** - * Common legacy real-time event for backward compatibility. - */ -type LegacyEvent = Event & { - /** - * Channel to which real-time event has been sent. - * - * @deprecated Use {@link channel} field instead. - */ - actualChannel?: string | null; - /** - * Actual subscription at which real-time event has been received. - * - * @deprecated Use {@link subscription} field instead. - */ - subscribedChannel?: string; -}; -/** - * Presence change real-time event. - */ -export type Presence = LegacyEvent & PresenceData; -/** - * Extended presence real-time event. - * - * Type extended for listener manager support. - */ -type PresenceEvent = { - type: PubNubEventType.Presence; - data: Presence; -}; -/** - * Common published data information. - */ -type PublishedData = { - /** - * Unique identifier of the user which sent data. - */ - publisher?: string; - /** - * Additional user-provided metadata which can be used with real-time filtering expression. - */ - userMetadata?: { - [p: string]: Payload; - }; - /** - * Sent data. - */ - message: Payload; -}; -/** - * Real-time message event. - */ -export type Message = LegacyEvent & PublishedData & { - /** - * Decryption error message in case of failure. - */ - error?: string; -}; -/** - * Extended real-time message event. - * - * Type extended for listener manager support. - */ -type MessageEvent = { - type: PubNubEventType.Message; - data: Message; -}; -/** - * Real-time signal event. - */ -export type Signal = Event & PublishedData; -/** - * Extended real-time signal event. - * - * Type extended for listener manager support. - */ -type SignalEvent = { - type: PubNubEventType.Signal; - data: Signal; -}; -/** - * Message action real-time event. - */ -export type MessageAction = Event & Omit & { - /** - * Unique identifier of the user which added message reaction. - * - * @deprecated Use `data.uuid` field instead. - */ - publisher?: string; - data: MessageActionData['data'] & { - /** - * Unique identifier of the user which added message reaction. - */ - uuid: string; - }; -}; -/** - * Extended message action real-time event. - * - * Type extended for listener manager support. - */ -type MessageActionEvent = { - type: PubNubEventType.MessageAction; - data: MessageAction; -}; -/** - * App Context Object change real-time event. - */ -export type AppContextObject = Event & { - /** - * Information about App Context object for which event received. - */ - message: AppContextObjectData; -}; -/** - * `User` App Context Object change real-time event. - */ -export type UserAppContextObject = Omit & { - /** - * Space to which real-time event has been sent. - */ - spaceId: string; - /** - * Information about User Object for which event received. - */ - message: UserObjectData; -}; -/** - * `Space` App Context Object change real-time event. - */ -export type SpaceAppContextObject = Omit & { - /** - * Space to which real-time event has been sent. - */ - spaceId: string; - /** - * Information about `Space` Object for which event received. - */ - message: SpaceObjectData; -}; -/** - * VSP `Membership` App Context Object change real-time event. - */ -export type VSPMembershipAppContextObject = Omit & { - /** - * Space to which real-time event has been sent. - */ - spaceId: string; - /** - * Information about `Membership` Object for which event received. - */ - message: VSPMembershipObjectData; -}; -/** - * Extended App Context Object change real-time event. - * - * Type extended for listener manager support. - */ -type AppContextEvent = { - type: PubNubEventType.AppContext; - data: AppContextObject; -}; -/** - * File real-time event. - */ -export type File = Event & Omit & Omit & { - /** - * Message which has been associated with uploaded file. - */ - message?: Payload; - /** - * Information about uploaded file. - */ - file?: FileData['file'] & { - /** - * File download url. - */ - url: string; - }; - /** - * Decryption error message in case of failure. - */ - error?: string; -}; -/** - * Extended File real-time event. - * - * Type extended for listener manager support. - */ -type FileEvent = { - type: PubNubEventType.Files; - data: File; -}; -/** - * Cancelable subscribe request parameters. - */ -export type CancelableSubscribeParameters = Omit & { - /** - * Long-poll request termination signal. - */ - abortSignal: AbortSignal; -}; -/** - * Subscribe request parameters. - */ -export type SubscribeParameters = { - /** - * List of channels from which real-time events should be delivered. - * - * @default `,` if {@link channelGroups} is set. - */ - channels?: string[]; - /** - * List of channel groups from which real-time events should be retrieved. - */ - channelGroups?: string[]; - /** - * Next subscription loop timetoken. - */ - timetoken?: string | number; - /** - * Whether should subscribe to channels / groups presence announcements or not. - * - * @default `false` - */ - withPresence?: boolean; - /** - * Presence information which should be associated with `userId`. - * - * `state` information will be associated with `userId` on channels mentioned as keys in - * this object. - * - * @deprecated Use set state methods to specify associated user's data instead of passing to - * subscribe. - */ - state?: Record; - /** - * Whether should subscribe to channels / groups presence announcements or not. - * - * @default `false` - */ - withHeartbeats?: boolean; -}; -/** - * Service success response. - */ -export type SubscriptionResponse = { - cursor: SubscriptionCursor; - messages: (PresenceEvent | MessageEvent | SignalEvent | MessageActionEvent | AppContextEvent | FileEvent)[]; -}; -export {}; diff --git a/lib/types/core/types/file.d.ts b/lib/types/core/types/file.d.ts deleted file mode 100644 index 774a161da..000000000 --- a/lib/types/core/types/file.d.ts +++ /dev/null @@ -1,104 +0,0 @@ -/** - * {@link PubNub} File object interface module. - */ -/** - * Base file constructor parameters. - * - * Minimum set of parameters which can be p - */ -export type PubNubBasicFileParameters = { - data: string | ArrayBuffer; - name: string; - mimeType?: string; -}; -/** - * Platform-agnostic {@link PubNub} File object. - * - * Interface describes share of {@link PubNub} File which is required by {@link PubNub} core to - * perform required actions. - */ -export interface PubNubFileInterface { - /** - * Actual file name. - */ - name: string; - /** - * File mime-type. - */ - mimeType?: string; - /** - * File content length. - */ - contentLength?: number; - /** - * Convert {@link PubNub} file object content to {@link ArrayBuffer}. - * - * @returns Asynchronous results of conversion to the {@link ArrayBuffer}. - * - * @throws Error if provided {@link PubNub} File object content is not supported for this - * operation. - */ - toArrayBuffer(): Promise; - /** - * Convert {@link PubNub} File object content to file `Uri`. - * - * @returns Asynchronous results of conversion to file `Uri`. - * - * @throws Error if provided {@link PubNub} File object content is not supported for this - * operation. - */ - toFileUri(): Promise>; -} -/** - * {@link PubNub} File object class interface. - */ -export interface PubNubFileConstructor { - /** - * Whether {@link Blob} data supported by platform or not. - */ - supportsBlob: boolean; - /** - * Whether {@link File} data supported by platform or not. - */ - supportsFile: boolean; - /** - * Whether {@link Buffer} data supported by platform or not. - */ - supportsBuffer: boolean; - /** - * Whether {@link Stream} data supported by platform or not. - */ - supportsStream: boolean; - /** - * Whether {@link String} data supported by platform or not. - */ - supportsString: boolean; - /** - * Whether {@link ArrayBuffer} supported by platform or not. - */ - supportsArrayBuffer: boolean; - /** - * Whether {@link PubNub} File object encryption supported or not. - */ - supportsEncryptFile: boolean; - /** - * Whether `File Uri` data supported by platform or not. - */ - supportsFileUri: boolean; - /** - * {@link PubNub} File object constructor. - * - * @param file - File instantiation parameters (can be raw data or structured object). - * - * @returns Constructed platform-specific {@link PubNub} File object. - */ - create(file: ConstructorParameters): File; - /** - * {@link PubNub} File object constructor. - * - * @param file - File instantiation parameters (can be raw data or structured object). - * - * @returns Constructed platform-specific {@link PubNub} File object. - */ - new (file: ConstructorParameters): File; -} diff --git a/lib/types/core/types/transport-request.d.ts b/lib/types/core/types/transport-request.d.ts deleted file mode 100644 index 09ddc24f4..000000000 --- a/lib/types/core/types/transport-request.d.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { PubNubFileInterface } from './file'; -import { Query } from './api'; -/** - * Enum representing possible transport methods for HTTP requests. - * - * @enum {number} - */ -export declare enum TransportMethod { - /** - * Request will be sent using `GET` method. - */ - GET = "GET", - /** - * Request will be sent using `POST` method. - */ - POST = "POST", - /** - * Request will be sent using `PATCH` method. - */ - PATCH = "PATCH", - /** - * Request will be sent using `DELETE` method. - */ - DELETE = "DELETE", - /** - * Local request. - * - * Request won't be sent to the service and probably used to compute URL. - */ - LOCAL = "LOCAL" -} -/** - * Request cancellation controller. - */ -export type CancellationController = { - /** - * Request cancellation / abort function. - */ - abort: () => void; -}; -/** - * This object represents a request to be sent to the PubNub API. - * - * This struct represents a request to be sent to the PubNub API. It is used by the transport - * provider which implements {@link Transport} interface. - * - * All fields are representing certain parts of the request that can be used to prepare one. - */ -export type TransportRequest = { - /** - * Remote host name. - */ - origin?: string; - /** - * Remote resource path. - */ - path: string; - /** - * Query parameters to be sent with the request. - */ - queryParameters?: Query; - /** - * Transport request HTTP method. - */ - method: TransportMethod; - /** - * Headers to be sent with the request. - */ - headers?: Record; - /** - * Multipart form data fields. - * - * **Important:** `Content-Type` header should be sent the {@link body} data type when - * `multipart/form-data` should request should be sent. - */ - formData?: Record[]; - /** - * Body to be sent with the request. - */ - body?: ArrayBuffer | PubNubFileInterface | string; - /** - * For how long request should wait response from the server. - * - * @default `10` seconds. - */ - timeout: number; - /** - * Whether request can be cancelled or not. - * - * @default `false`. - */ - cancellable: boolean; - /** - * Unique request identifier. - */ - identifier: string; -}; diff --git a/lib/types/core/types/transport-response.d.ts b/lib/types/core/types/transport-response.d.ts deleted file mode 100644 index 359aa8712..000000000 --- a/lib/types/core/types/transport-response.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Represents a transport response from a service. - */ -export type TransportResponse = { - /** - * Full remote resource URL used to retrieve response. - */ - url: string; - /** - * Service response status code. - */ - status: number; - /** - * Service response headers. - * - * **Important:** Header names are in lowercase. - */ - headers: Record; - /** - * Service response body. - */ - body?: ArrayBuffer; -}; diff --git a/lib/types/core/utils.d.ts b/lib/types/core/utils.d.ts deleted file mode 100644 index 49a47712f..000000000 --- a/lib/types/core/utils.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * PubNub package utilities module. - * - * @internal - */ -export {}; diff --git a/lib/types/crypto/index.d.ts b/lib/types/crypto/index.d.ts deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/types/crypto/modules/NodeCryptoModule/ICryptor.d.ts b/lib/types/crypto/modules/NodeCryptoModule/ICryptor.d.ts deleted file mode 100644 index 30a6c7bee..000000000 --- a/lib/types/crypto/modules/NodeCryptoModule/ICryptor.d.ts +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Cryptor module. - */ -/// -/// -/** - * Data encrypted by {@link CryptoModule}. - */ -export type EncryptedDataType = { - /** - * Encrypted data. - */ - data: Buffer | string; - /** - * Used cryptor's metadata. - */ - metadata: Buffer | null; -}; -/** - * {@link Readable} stream encrypted by {@link CryptoModule}. - */ -export type EncryptedStream = { - /** - * Stream with encrypted content. - */ - stream: NodeJS.ReadableStream; - /** - * Length of encrypted data in {@link Readable} stream. - */ - metadataLength: number; - /** - * Used cryptor's metadata. - */ - metadata?: Buffer | undefined; -}; -/** - * Cryptor algorithm interface. - */ -export interface ICryptor { - /** - * Cryptor unique identifier. - * - * @returns Cryptor identifier. - */ - get identifier(): string; - /** - * Encrypt provided source data. - * - * @param data - Source data for encryption. - * - * @returns Encrypted data object. - * - * @throws Error if unknown data type has been passed. - */ - encrypt(data: BufferSource | string): EncryptedDataType; - /** - * Encrypt provided source {@link Readable} stream. - * - * @param stream - Stream for encryption. - * - * @returns Encrypted stream object. - * - * @throws Error if unknown data type has been passed. - */ - encryptStream(stream: NodeJS.ReadableStream): Promise; - /** - * Decrypt provided encrypted data object. - * - * @param data - Encrypted data object for decryption. - * - * @returns Decrypted data. - * - * @throws Error if unknown data type has been passed. - */ - decrypt(data: EncryptedDataType): ArrayBuffer; - /** - * Decrypt provided encrypted stream object. - * - * @param stream - Encrypted stream object for decryption. - * - * @returns Decrypted data as {@link Readable} stream. - * - * @throws Error if unknown data type has been passed. - */ - decryptStream(stream: EncryptedStream): Promise; -} diff --git a/lib/types/crypto/modules/NodeCryptoModule/ILegacyCryptor.d.ts b/lib/types/crypto/modules/NodeCryptoModule/ILegacyCryptor.d.ts deleted file mode 100644 index 5b3ea2f2f..000000000 --- a/lib/types/crypto/modules/NodeCryptoModule/ILegacyCryptor.d.ts +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Legacy cryptor module. - */ -import PubNubFile, { PubNubFileParameters } from '../../../file/modules/node'; -import { PubNubFileConstructor } from '../../../core/types/file'; -import { Payload } from '../../../core/types/api'; -import { EncryptedDataType } from './ICryptor'; -/** - * Legacy cryptor algorithm interface. - */ -export interface ILegacyCryptor { - /** - * Cryptor unique identifier. - */ - get identifier(): string; - /** - * Encrypt provided source data. - * - * @param data - Source data for encryption. - * - * @returns Encrypted data object. - * - * @throws Error if unknown data type has been passed. - */ - encrypt(data: string): EncryptedDataType; - /** - * Encrypt provided source {@link PubNub} File object. - * - * @param file - Source {@link PubNub} File object for encryption. - * @param File - Class constructor for {@link PubNub} File object. - * - * @returns Encrypted data as {@link PubNub} File object. - * - * @throws Error if file is empty or contains unsupported data type. - * @throws Error if cipher key not set. - */ - encryptFile(file: PubNubFile, File: PubNubFileConstructor): Promise; - /** - * Decrypt provided encrypted data object. - * - * @param data - Encrypted data object for decryption. - * - * @returns Decrypted data. - * - * @throws Error if unknown data type has been passed. - */ - decrypt(data: EncryptedDataType): Payload | null; - /** - * Decrypt provided encrypted {@link PubNub} File object. - * - * @param file - Encrypted {@link PubNub} File object for decryption. - * @param File - Class constructor for {@link PubNub} File object. - * - * @returns Decrypted data as {@link PubNub} File object. - * - * @throws Error if file is empty or contains unsupported data type. - * @throws Error if cipher key not set. - */ - decryptFile(file: PubNubFile, File: PubNubFileConstructor): Promise; -} diff --git a/lib/types/crypto/modules/NodeCryptoModule/aesCbcCryptor.d.ts b/lib/types/crypto/modules/NodeCryptoModule/aesCbcCryptor.d.ts deleted file mode 100644 index c6a837e6b..000000000 --- a/lib/types/crypto/modules/NodeCryptoModule/aesCbcCryptor.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * AES-CBC cryptor module. - * - * @internal - */ -export {}; diff --git a/lib/types/crypto/modules/NodeCryptoModule/legacyCryptor.d.ts b/lib/types/crypto/modules/NodeCryptoModule/legacyCryptor.d.ts deleted file mode 100644 index ca05be521..000000000 --- a/lib/types/crypto/modules/NodeCryptoModule/legacyCryptor.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Legacy cryptor module. - * - * @internal - */ -export {}; diff --git a/lib/types/crypto/modules/NodeCryptoModule/nodeCryptoModule.d.ts b/lib/types/crypto/modules/NodeCryptoModule/nodeCryptoModule.d.ts deleted file mode 100644 index b1e292f44..000000000 --- a/lib/types/crypto/modules/NodeCryptoModule/nodeCryptoModule.d.ts +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Node.js crypto module. - */ -import { AbstractCryptoModule, CryptorConfiguration } from '../../../core/interfaces/crypto-module'; -import PubNubFile, { PubNubFileParameters } from '../../../file/modules/node'; -import { PubNubFileConstructor } from '../../../core/types/file'; -import { ICryptor } from './ICryptor'; -import { ILegacyCryptor } from './ILegacyCryptor'; -import AesCbcCryptor from './aesCbcCryptor'; -import LegacyCryptor from './legacyCryptor'; -/** - * Re-export bundled cryptors. - */ -export { LegacyCryptor, AesCbcCryptor }; -/** - * Crypto module cryptors interface. - */ -type CryptorType = ICryptor | ILegacyCryptor; -/** - * CryptoModule for Node.js platform. - */ -export declare class CryptoModule extends AbstractCryptoModule { - /** - * {@link LegacyCryptor|Legacy} cryptor identifier. - */ - static LEGACY_IDENTIFIER: string; - static legacyCryptoModule(config: CryptorConfiguration): CryptoModule; - static aesCbcCryptoModule(config: CryptorConfiguration): CryptoModule; - /** - * Construct crypto module with `cryptor` as default for data encryption and decryption. - * - * @param defaultCryptor - Default cryptor for data encryption and decryption. - * - * @returns Crypto module with pre-configured default cryptor. - */ - static withDefaultCryptor(defaultCryptor: CryptorType): CryptoModule; - encrypt(data: ArrayBuffer | string): string | ArrayBuffer; - encryptFile(file: PubNubFile, File: PubNubFileConstructor): Promise; - decrypt(data: ArrayBuffer | string): ArrayBuffer | import("../../../core/types/api").Payload | null; - decryptFile(file: PubNubFile, File: PubNubFileConstructor): Promise; -} diff --git a/lib/types/crypto/modules/node.d.ts b/lib/types/crypto/modules/node.d.ts deleted file mode 100644 index 5112adfe9..000000000 --- a/lib/types/crypto/modules/node.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Legacy Node.js cryptography module. - * - * @internal - */ -export {}; diff --git a/lib/types/entities/Channel.d.ts b/lib/types/entities/Channel.d.ts deleted file mode 100644 index a7bc0c9af..000000000 --- a/lib/types/entities/Channel.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { SubscriptionOptions } from './commonTypes'; -import { Subscription } from './Subscription'; -/** - * First-class objects which provides access to the channel-specific APIs. - */ -export declare class Channel { - /** - * Create channel's subscription object for real-time updates. - * - * Create subscription object which can be used to subscribe to the real-time updates sent to the specific channel. - * - * @param [subscriptionOptions] - Channel's subscription object behavior customization options. - * - * @returns Configured and ready to use channel's subscription object. - */ - subscription(subscriptionOptions?: SubscriptionOptions): Subscription; -} diff --git a/lib/types/entities/ChannelGroup.d.ts b/lib/types/entities/ChannelGroup.d.ts deleted file mode 100644 index 6261fb584..000000000 --- a/lib/types/entities/ChannelGroup.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { SubscriptionOptions } from './commonTypes'; -import { Subscription } from './Subscription'; -/** - * First-class objects which provides access to the channel group-specific APIs. - */ -export declare class ChannelGroup { - /** - * Create channel group's subscription object for real-time updates. - * - * Create subscription object which can be used to subscribe to the real-time updates sent to the channels in - * specific channel group. - * - * @param [subscriptionOptions] - Channel group's subscription object behavior customization options. - * - * @returns Configured and ready to use channel group's subscription object. - */ - subscription(subscriptionOptions?: SubscriptionOptions): Subscription; -} diff --git a/lib/types/entities/ChannelMetadata.d.ts b/lib/types/entities/ChannelMetadata.d.ts deleted file mode 100644 index 0c157cc14..000000000 --- a/lib/types/entities/ChannelMetadata.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { SubscriptionOptions } from './commonTypes'; -import { Subscription } from './Subscription'; -/** - * First-class objects which provides access to the channel app context object-specific APIs. - */ -export declare class ChannelMetadata { - /** - * Create channel's app context subscription object for real-time updates. - * - * Create subscription object which can be used to subscribe to the real-time updates sent to the specific channel - * app context object. - * - * @param [subscriptionOptions] - Channel's app context subscription object behavior customization options. - * - * @returns Configured and ready to use channel's app context subscription object. - */ - subscription(subscriptionOptions?: SubscriptionOptions): Subscription; -} diff --git a/lib/types/entities/SubscribeCapable.d.ts b/lib/types/entities/SubscribeCapable.d.ts deleted file mode 100644 index b0c5089fb..000000000 --- a/lib/types/entities/SubscribeCapable.d.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { Listener } from '../core/components/listener_manager'; -import * as Subscription from '../core/types/api/subscription'; -export declare abstract class SubscribeCapable { - /** - * Start receiving real-time updates. - * - * @param subscribeParameters - Additional subscription configuration options which should be used - * for request. - */ - subscribe(subscribeParameters?: { - timetoken?: string; - }): void; - /** - * Stop real-time events processing. - */ - unsubscribe(): void; - /** - * Set new message handler. - * - * @param onMessageListener - Listener function, which will be called each time when a new message - * is received from the real-time network. - */ - set onMessage(onMessageListener: (messageEvent: Subscription.Message) => void); - /** - * Set new presence events handler. - * - * @param onPresenceListener - Listener function, which will be called each time when a new - * presence event is received from the real-time network. - */ - set onPresence(onPresenceListener: (presenceEvent: Subscription.Presence) => void); - /** - * Set new signal handler. - * - * @param onSignalListener - Listener function, which will be called each time when a new signal - * is received from the real-time network. - */ - set onSignal(onSignalListener: (signalEvent: Subscription.Signal) => void); - /** - * Set new app context event handler. - * - * @param onObjectsListener - Listener function, which will be called each time when a new - * app context event is received from the real-time network. - */ - set onObjects(onObjectsListener: (objectsEvent: Subscription.AppContextObject) => void); - /** - * Set new message reaction event handler. - * - * @param messageActionEventListener - Listener function, which will be called each time when a - * new message reaction event is received from the real-time network. - */ - set onMessageAction(messageActionEventListener: (messageActionEvent: Subscription.MessageAction) => void); - /** - * Set new file handler. - * - * @param fileEventListener - Listener function, which will be called each time when a new file - * is received from the real-time network. - */ - set onFile(fileEventListener: (fileEvent: Subscription.File) => void); - /** - * Set events handler. - * - * @param listener - Events listener configuration object, which lets specify handlers for multiple - * types of events. - */ - addListener(listener: Listener): void; - /** - * Remove events handler. - * - * @param listener - Event listener configuration, which should be removed from the list of notified - * listeners. **Important:** Should be the same object which has been passed to the - * {@link addListener}. - */ - removeListener(listener: Listener): void; - /** - * Get list of channels which is used for subscription. - * - * @returns List of channel names. - */ - get channels(): string[]; - /** - * Get list of channel groups which is used for subscription. - * - * @returns List of channel group names. - */ - get channelGroups(): string[]; -} diff --git a/lib/types/entities/Subscription.d.ts b/lib/types/entities/Subscription.d.ts deleted file mode 100644 index 40797f2e0..000000000 --- a/lib/types/entities/Subscription.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { SubscribeCapable } from './SubscribeCapable'; -import { SubscriptionSet } from './SubscriptionSet'; -/** - * Single-entity subscription object which can be used to receive and handle real-time updates. - */ -export declare class Subscription extends SubscribeCapable { - /** - * Merge entities' subscription objects into subscription set. - * - * @param subscription - Other entity's subscription object to be merged with receiver. - * @return Subscription set which contains both receiver and other entities' subscription objects. - */ - addSubscription(subscription: Subscription): SubscriptionSet; -} diff --git a/lib/types/entities/SubscriptionSet.d.ts b/lib/types/entities/SubscriptionSet.d.ts deleted file mode 100644 index 18fd2f62e..000000000 --- a/lib/types/entities/SubscriptionSet.d.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { SubscribeCapable } from './SubscribeCapable'; -import { Subscription } from './Subscription'; -/** - * Multiple entities subscription set object which can be used to receive and handle real-time - * updates. - * - * Subscription set object represent collection of per-entity subscription objects and allow - * processing them at once for subscription loop and events handling. - */ -export declare class SubscriptionSet extends SubscribeCapable { - /** - * Add additional entity's subscription to the subscription set. - * - * **Important:** Changes will be effective only after {@link SubscribeCapable#subscribe} call or - * next subscription loop. - * - * @param subscription - Other entity's subscription object, which should be added. - */ - addSubscription(subscription: Subscription): void; - /** - * Remove entity's subscription object from the set. - * - * **Important:** Changes will be effective only after {@link SubscribeCapable#unsubscribe} call or - * next subscription loop. - * - * @param subscription - Other entity's subscription object, which should be removed. - */ - removeSubscription(subscription: Subscription): void; - /** - * Merge with other subscription set object. - * - * **Important:** Changes will be effective only after {@link SubscribeCapable#subscribe} call or - * next subscription loop. - * - * @param subscriptionSet - Other entities' subscription set, which should be joined. - */ - addSubscriptionSet(subscriptionSet: SubscriptionSet): void; - /** - * Subtract other subscription set object. - * - * **Important:** Changes will be effective only after {@link SubscribeCapable#unsubscribe} call or - * next subscription loop. - * - * @param subscriptionSet - Other entities' subscription set, which should be subtracted. - */ - removeSubscriptionSet(subscriptionSet: SubscriptionSet): void; - /** - * Get list of entities' subscription objects registered in subscription set. - * - * @returns Entities' subscription objects list. - */ - get subscriptions(): Subscription[]; -} diff --git a/lib/types/entities/UserMetadata.d.ts b/lib/types/entities/UserMetadata.d.ts deleted file mode 100644 index a855fcc30..000000000 --- a/lib/types/entities/UserMetadata.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { SubscriptionOptions } from './commonTypes'; -import { Subscription } from './Subscription'; -/** - * First-class objects which provides access to the user app context object-specific APIs. - */ -export declare class UserMetadata { - /** - * Create user's app context subscription object for real-time updates. - * - * Create subscription object which can be used to subscribe to the real-time updates sent to the specific user - * app context object. - * - * @param [subscriptionOptions] - User's app context subscription object behavior customization options. - * - * @returns Configured and ready to use user's app context subscription object. - */ - subscription(subscriptionOptions?: SubscriptionOptions): Subscription; -} diff --git a/lib/types/entities/commonTypes.d.ts b/lib/types/entities/commonTypes.d.ts deleted file mode 100644 index 3b79cc5aa..000000000 --- a/lib/types/entities/commonTypes.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -/** - * PubNub entity subscription configuration options. - */ -export type SubscriptionOptions = { - /** - * Whether presence events for entity should be received or not. - */ - receivePresenceEvents?: boolean; -}; diff --git a/lib/types/errors/pubnub-api-error.d.ts b/lib/types/errors/pubnub-api-error.d.ts deleted file mode 100644 index 38666c66a..000000000 --- a/lib/types/errors/pubnub-api-error.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * REST API endpoint use error module. - * - * @internal - */ -export {}; diff --git a/lib/types/errors/pubnub-error.d.ts b/lib/types/errors/pubnub-error.d.ts deleted file mode 100644 index 5fcebf380..000000000 --- a/lib/types/errors/pubnub-error.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -/** - * PubNub operation error module. - * - * @internal - */ -/** - * PubNub operation error. - * - * When an operation can't be performed or there is an error from the server, this object will be returned. - */ -export declare class PubNubError extends Error { - status?: Status | undefined; -} diff --git a/lib/types/event-engine/core/change.d.ts b/lib/types/event-engine/core/change.d.ts deleted file mode 100644 index b07502bf1..000000000 --- a/lib/types/event-engine/core/change.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Event Engine Core state change module. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/core/dispatcher.d.ts b/lib/types/event-engine/core/dispatcher.d.ts deleted file mode 100644 index d2be84d87..000000000 --- a/lib/types/event-engine/core/dispatcher.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Event Engine Core Effects dispatcher module. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/core/engine.d.ts b/lib/types/event-engine/core/engine.d.ts deleted file mode 100644 index 4d8ba8475..000000000 --- a/lib/types/event-engine/core/engine.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Event Engine Core module. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/core/handler.d.ts b/lib/types/event-engine/core/handler.d.ts deleted file mode 100644 index 9d9e77b2f..000000000 --- a/lib/types/event-engine/core/handler.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Event Engine Core Effects handler module. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/core/index.d.ts b/lib/types/event-engine/core/index.d.ts deleted file mode 100644 index 6fe2f3182..000000000 --- a/lib/types/event-engine/core/index.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Event Engine module. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/core/retryPolicy.d.ts b/lib/types/event-engine/core/retryPolicy.d.ts deleted file mode 100644 index a9b23adf2..000000000 --- a/lib/types/event-engine/core/retryPolicy.d.ts +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Failed requests retry module. - */ -import { PubNubError } from '../../errors/pubnub-error'; -/** - * Failed request retry policy. - */ -export declare class RetryPolicy { - static LinearRetryPolicy(configuration: LinearRetryPolicyConfiguration): RequestRetryPolicy & LinearRetryPolicyConfiguration; - static ExponentialRetryPolicy(configuration: ExponentialRetryPolicyConfiguration): RequestRetryPolicy & ExponentialRetryPolicyConfiguration; -} -export type RequestRetryPolicy = { - /** - * Check whether failed request can be retried. - * - * @param reason - Request processing failure reason. - * @param attempt - Number of sequential failure. - * - * @returns `true` if another request retry attempt can be done. - */ - shouldRetry(reason: PubNubError & { - retryAfter?: number; - }, attempt: number): boolean; - /** - * Computed delay for next request retry attempt. - * - * @param attempt - Number of sequential failure. - * @param reason - Request processing failure reason. - * - * @returns Delay before next request retry attempt in milliseconds. - */ - getDelay(attempt: number, reason: PubNubError & { - retryAfter?: number; - }): number; - /** - * Identify reason why another retry attempt can't be made. - * - * @param reason - Request processing failure reason. - * @param attempt - Number of sequential failure. - * - * @returns Give up reason. - */ - getGiveupReason(reason: PubNubError & { - retryAfter?: number; - }, attempt: number): string; - /** - * Validate retry policy parameters. - * - * @throws Error if `minimum` delay is smaller than 2 seconds for `exponential` retry policy. - * @throws Error if `maximum` delay is larger than 150 seconds for `exponential` retry policy. - * @throws Error if `maximumRetry` attempts is larger than 6 for `exponential` retry policy. - * @throws Error if `maximumRetry` attempts is larger than 10 for `linear` retry policy. - */ - validate(): void; -}; -export type LinearRetryPolicyConfiguration = { - delay: number; - maximumRetry: number; -}; -export type ExponentialRetryPolicyConfiguration = { - minimumDelay: number; - maximumDelay: number; - maximumRetry: number; -}; diff --git a/lib/types/event-engine/core/state.d.ts b/lib/types/event-engine/core/state.d.ts deleted file mode 100644 index f95271ba3..000000000 --- a/lib/types/event-engine/core/state.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Event Engine Core state module. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/core/types.d.ts b/lib/types/event-engine/core/types.d.ts deleted file mode 100644 index cd2ff5976..000000000 --- a/lib/types/event-engine/core/types.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Event Engine Core types module. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/dispatcher.d.ts b/lib/types/event-engine/dispatcher.d.ts deleted file mode 100644 index d85481c19..000000000 --- a/lib/types/event-engine/dispatcher.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Subscribe Event Engine effects dispatcher. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/effects.d.ts b/lib/types/event-engine/effects.d.ts deleted file mode 100644 index adab7821c..000000000 --- a/lib/types/event-engine/effects.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Subscribe Event Engine effects module. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/events.d.ts b/lib/types/event-engine/events.d.ts deleted file mode 100644 index 5f975dccd..000000000 --- a/lib/types/event-engine/events.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Subscribe Event Engine events module. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/index.d.ts b/lib/types/event-engine/index.d.ts deleted file mode 100644 index 2b4c757e3..000000000 --- a/lib/types/event-engine/index.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Subscribe Event Engine module. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/presence/dispatcher.d.ts b/lib/types/event-engine/presence/dispatcher.d.ts deleted file mode 100644 index 6439c189d..000000000 --- a/lib/types/event-engine/presence/dispatcher.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Presence Event Engine effects dispatcher. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/presence/effects.d.ts b/lib/types/event-engine/presence/effects.d.ts deleted file mode 100644 index 5bcd68363..000000000 --- a/lib/types/event-engine/presence/effects.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Presence Event Engine effects module. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/presence/events.d.ts b/lib/types/event-engine/presence/events.d.ts deleted file mode 100644 index 4bb737594..000000000 --- a/lib/types/event-engine/presence/events.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Presence Event Engine events module. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/presence/presence.d.ts b/lib/types/event-engine/presence/presence.d.ts deleted file mode 100644 index 442a09e5d..000000000 --- a/lib/types/event-engine/presence/presence.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Presence Event Engine module. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/presence/states/heartbeat_cooldown.d.ts b/lib/types/event-engine/presence/states/heartbeat_cooldown.d.ts deleted file mode 100644 index cb2055c4f..000000000 --- a/lib/types/event-engine/presence/states/heartbeat_cooldown.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Waiting next heartbeat state module. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/presence/states/heartbeat_failed.d.ts b/lib/types/event-engine/presence/states/heartbeat_failed.d.ts deleted file mode 100644 index f504be6ef..000000000 --- a/lib/types/event-engine/presence/states/heartbeat_failed.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Failed to heartbeat state module. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/presence/states/heartbeat_inactive.d.ts b/lib/types/event-engine/presence/states/heartbeat_inactive.d.ts deleted file mode 100644 index ba030ff24..000000000 --- a/lib/types/event-engine/presence/states/heartbeat_inactive.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Inactive heratbeating state module. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/presence/states/heartbeat_reconnecting.d.ts b/lib/types/event-engine/presence/states/heartbeat_reconnecting.d.ts deleted file mode 100644 index 6678dbd47..000000000 --- a/lib/types/event-engine/presence/states/heartbeat_reconnecting.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Retry heartbeat state module. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/presence/states/heartbeat_stopped.d.ts b/lib/types/event-engine/presence/states/heartbeat_stopped.d.ts deleted file mode 100644 index 1a74e92e7..000000000 --- a/lib/types/event-engine/presence/states/heartbeat_stopped.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Heartbeat stopped state module. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/presence/states/heartbeating.d.ts b/lib/types/event-engine/presence/states/heartbeating.d.ts deleted file mode 100644 index 954069a5c..000000000 --- a/lib/types/event-engine/presence/states/heartbeating.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Heartbeating state module. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/states/handshake_failed.d.ts b/lib/types/event-engine/states/handshake_failed.d.ts deleted file mode 100644 index 045ed55a6..000000000 --- a/lib/types/event-engine/states/handshake_failed.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Failed initial subscription handshake (disconnected) state. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/states/handshake_reconnecting.d.ts b/lib/types/event-engine/states/handshake_reconnecting.d.ts deleted file mode 100644 index a3ae44377..000000000 --- a/lib/types/event-engine/states/handshake_reconnecting.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Retry initial subscription handshake (disconnected) state. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/states/handshake_stopped.d.ts b/lib/types/event-engine/states/handshake_stopped.d.ts deleted file mode 100644 index c9fd56cea..000000000 --- a/lib/types/event-engine/states/handshake_stopped.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Stopped initial subscription handshake (disconnected) state. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/states/handshaking.d.ts b/lib/types/event-engine/states/handshaking.d.ts deleted file mode 100644 index 6dd12eb87..000000000 --- a/lib/types/event-engine/states/handshaking.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Initial subscription handshake (disconnected) state. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/states/receive_failed.d.ts b/lib/types/event-engine/states/receive_failed.d.ts deleted file mode 100644 index 80a4f413a..000000000 --- a/lib/types/event-engine/states/receive_failed.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Failed to receive real-time updates (disconnected) state. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/states/receive_reconnecting.d.ts b/lib/types/event-engine/states/receive_reconnecting.d.ts deleted file mode 100644 index 15da36363..000000000 --- a/lib/types/event-engine/states/receive_reconnecting.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Reconnect to receive real-time updates (disconnected) state. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/states/receive_stopped.d.ts b/lib/types/event-engine/states/receive_stopped.d.ts deleted file mode 100644 index 6a4a2667b..000000000 --- a/lib/types/event-engine/states/receive_stopped.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Stopped real-time updates (disconnected) state module. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/states/receiving.d.ts b/lib/types/event-engine/states/receiving.d.ts deleted file mode 100644 index 5abca2d7e..000000000 --- a/lib/types/event-engine/states/receiving.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Receiving real-time updates (connected) state module. - * - * @internal - */ -export {}; diff --git a/lib/types/event-engine/states/unsubscribed.d.ts b/lib/types/event-engine/states/unsubscribed.d.ts deleted file mode 100644 index 094757b52..000000000 --- a/lib/types/event-engine/states/unsubscribed.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Unsubscribed / disconnected state module. - * - * @internal - */ -export {}; diff --git a/lib/types/file/modules/node.d.ts b/lib/types/file/modules/node.d.ts deleted file mode 100644 index 344f76fe5..000000000 --- a/lib/types/file/modules/node.d.ts +++ /dev/null @@ -1,134 +0,0 @@ -/** - * Node.js {@link PubNub} File object module. - */ -/// -/// -import { Readable, PassThrough } from 'stream'; -import { Buffer } from 'buffer'; -import { PubNubFileInterface } from '../../core/types/file'; -/** - * PubNub File instance creation parameters. - */ -export type PubNubFileParameters = { - /** - * Readable stream represents file object content. - */ - stream?: Readable; - /** - * Buffer or string represents file object content. - */ - data?: Buffer | ArrayBuffer | string; - /** - * String {@link PubNubFileParameters#data|data} encoding. - * - * @default `utf8` - */ - encoding?: StringEncoding; - /** - * File object name. - */ - name: string; - /** - * File object content type. - */ - mimeType?: string; -}; -/** - * Node.js implementation for {@link PubNub} File object. - * - * **Important:** Class should implement constructor and class fields from {@link PubNubFileConstructor}. - */ -export default class PubNubFile implements PubNubFileInterface { - /** - * Whether {@link Blob} data supported by platform or not. - */ - static supportsBlob: boolean; - /** - * Whether {@link File} data supported by platform or not. - */ - static supportsFile: boolean; - /** - * Whether {@link Buffer} data supported by platform or not. - */ - static supportsBuffer: boolean; - /** - * Whether {@link Stream} data supported by platform or not. - */ - static supportsStream: boolean; - /** - * Whether {@link String} data supported by platform or not. - */ - static supportsString: boolean; - /** - * Whether {@link ArrayBuffer} supported by platform or not. - */ - static supportsArrayBuffer: boolean; - /** - * Whether {@link PubNub} File object encryption supported or not. - */ - static supportsEncryptFile: boolean; - /** - * Whether `File Uri` data supported by platform or not. - */ - static supportsFileUri: boolean; - /** - * File object content source. - */ - readonly data: Readable | Buffer; - /** - * File object content length. - */ - contentLength?: number; - /** - * File object content type. - */ - mimeType: string; - /** - * File object name. - */ - name: string; - static create(file: PubNubFileParameters): PubNubFile; - constructor(file: PubNubFileParameters); - /** - * Convert {@link PubNub} File object content to {@link Buffer}. - * - * @returns Asynchronous results of conversion to the {@link Buffer}. - */ - toBuffer(): Promise; - /** - * Convert {@link PubNub} File object content to {@link ArrayBuffer}. - * - * @returns Asynchronous results of conversion to the {@link ArrayBuffer}. - */ - toArrayBuffer(): Promise; - /** - * Convert {@link PubNub} File object content to {@link string}. - * - * @returns Asynchronous results of conversion to the {@link string}. - */ - toString(encoding?: BufferEncoding): Promise; - /** - * Convert {@link PubNub} File object content to {@link Readable} stream. - * - * @returns Asynchronous results of conversion to the {@link Readable} stream. - */ - toStream(): Promise; - /** - * Convert {@link PubNub} File object content to {@link File}. - * - * @throws Error because {@link File} not available in Node.js environment. - */ - toFile(): Promise; - /** - * Convert {@link PubNub} File object content to file `Uri`. - * - * @throws Error because file `Uri` not available in Node.js environment. - */ - toFileUri(): Promise>; - /** - * Convert {@link PubNub} File object content to {@link Blob}. - * - * @throws Error because {@link Blob} not available in Node.js environment. - */ - toBlob(): Promise; -} diff --git a/lib/types/file/modules/react-native.d.ts b/lib/types/file/modules/react-native.d.ts deleted file mode 100644 index 51531b6ea..000000000 --- a/lib/types/file/modules/react-native.d.ts +++ /dev/null @@ -1,135 +0,0 @@ -/** - * React Native {@link PubNub} File object module. - */ -import { PubNubFileInterface } from '../../core/types/file'; -/** - * File path-based file. - */ -type FileUri = { - uri: string; - name: string; - mimeType?: string; -}; -/** - * Asynchronously fetched file content. - */ -type ReadableFile = { - arrayBuffer: () => Promise; - blob: () => Promise; - text: () => Promise; -}; -/** - * PubNub File instance creation parameters. - */ -export type PubNubFileParameters = File | FileUri | ReadableFile | { - data: string | Blob | ArrayBuffer | ArrayBufferView; - name: string; - mimeType?: string; -}; -export declare class PubNubFile implements PubNubFileInterface { - /** - * Whether {@link Blob} data supported by platform or not. - */ - static supportsBlob: boolean; - /** - * Whether {@link File} data supported by platform or not. - */ - static supportsFile: boolean; - /** - * Whether {@link Buffer} data supported by platform or not. - */ - static supportsBuffer: boolean; - /** - * Whether {@link Stream} data supported by platform or not. - */ - static supportsStream: boolean; - /** - * Whether {@link String} data supported by platform or not. - */ - static supportsString: boolean; - /** - * Whether {@link ArrayBuffer} supported by platform or not. - */ - static supportsArrayBuffer: boolean; - /** - * Whether {@link PubNub} File object encryption supported or not. - */ - static supportsEncryptFile: boolean; - /** - * Whether `File Uri` data supported by platform or not. - */ - static supportsFileUri: boolean; - /** - * File object content source. - */ - readonly data: File | FileUri | ReadableFile; - /** - * File object content length. - */ - contentLength?: number; - /** - * File object content type. - */ - mimeType: string; - /** - * File object name. - */ - name: string; - static create(file: PubNubFileParameters): PubNubFile; - constructor(file: PubNubFileParameters); - /** - * Convert {@link PubNub} File object content to {@link Buffer}. - * - * @throws Error because {@link Buffer} not available in React Native environment. - */ - toBuffer(): Promise; - /** - * Convert {@link PubNub} File object content to {@link ArrayBuffer}. - * - * @returns Asynchronous results of conversion to the {@link ArrayBuffer}. - * - * @throws Error if provided {@link PubNub} File object content is not supported for this - * operation. - */ - toArrayBuffer(): Promise; - /** - * Convert {@link PubNub} File object content to {@link string}. - * - * @returns Asynchronous results of conversion to the {@link string}. - */ - toString(): Promise; - /** - * Convert {@link PubNub} File object content to {@link Readable} stream. - * - * @throws Error because {@link Readable} stream not available in React Native environment. - */ - toStream(): Promise; - /** - * Convert {@link PubNub} File object content to {@link File}. - * - * @returns Asynchronous results of conversion to the {@link File}. - * - * @throws Error if provided {@link PubNub} File object content is not supported for this - * operation. - */ - toFile(): Promise; - /** - * Convert {@link PubNub} File object content to file `Uri`. - * - * @returns Asynchronous results of conversion to file `Uri`. - * - * @throws Error if provided {@link PubNub} File object content is not supported for this - * operation. - */ - toFileUri(): Promise; - /** - * Convert {@link PubNub} File object content to {@link Blob}. - * - * @returns Asynchronous results of conversion to the {@link Blob}. - * - * @throws Error if provided {@link PubNub} File object content is not supported for this - * operation. - */ - toBlob(): Promise; -} -export default PubNubFile; diff --git a/lib/types/index.d.ts b/lib/types/index.d.ts new file mode 100644 index 000000000..6b23afece --- /dev/null +++ b/lib/types/index.d.ts @@ -0,0 +1,8070 @@ +import { Readable, PassThrough } from 'stream'; +import { Buffer } from 'buffer'; +import { ProxyAgentOptions } from 'proxy-agent'; + +/** + * PubNub client for Node.js platform. + */ +declare class PubNub extends PubNubCore< + string | ArrayBuffer | Buffer | Readable, + PubNub.PubNubFileParameters, + PubNub.PubNubFile +> { + /** + * Data encryption / decryption module constructor. + */ + static CryptoModule: typeof PubNub.CryptoModuleType; + /** + * PubNub File constructor. + */ + File: PubNub.PubNubFileConstructor; + /** + * Create and configure PubNub client core. + * + * @param configuration - User-provided PubNub client configuration. + * + * @returns Configured and ready to use PubNub client. + */ + constructor(configuration: PubNub.PubNubConfiguration); + /** + * Update request proxy configuration. + * + * @param configuration - Updated request proxy configuration. + * + * @throws An error if {@link PubNub} client already configured to use `keepAlive`. + * `keepAlive` and `proxy` can't be used simultaneously. + */ + setProxy(configuration?: ProxyAgentOptions): void; +} + +/** + * Platform-agnostic PubNub client core. + */ +declare class PubNubCore< + CryptographyTypes, + FileConstructorParameters, + PlatformFile extends Partial = Record, +> { + /** + * Type of REST API endpoint which reported status. + */ + static OPERATIONS: typeof PubNub.RequestOperation; + /** + * API call status category. + */ + static CATEGORIES: typeof PubNub.StatusCategory; + /** + * Exponential retry policy constructor. + */ + static ExponentialRetryPolicy: typeof PubNub.RetryPolicy.ExponentialRetryPolicy; + /** + * Linear retry policy constructor. + */ + static LinearRetryPolicy: typeof PubNub.RetryPolicy.LinearRetryPolicy; + /** + * Construct notification payload which will trigger push notification. + * + * @param title - Title which will be shown on notification. + * @param body - Payload which will be sent as part of notification. + * + * @returns Pre-formatted message payload which will trigger push notification. + */ + static notificationPayload(title: string, body: string): PubNub.NotificationsPayload; + /** + * Generate unique identifier. + * + * @returns Unique identifier. + */ + static generateUUID(): any; + /** + * PubNub client configuration. + * + * @returns Currently user PubNub client configuration. + */ + get configuration(): PubNub.ClientConfiguration; + /** + * Current PubNub client configuration. + * + * @returns Currently user PubNub client configuration. + * + * @deprecated Use {@link configuration} getter instead. + */ + get _config(): PubNub.ClientConfiguration; + /** + * REST API endpoint access authorization key. + * + * It is required to have `authorization key` with required permissions to access REST API + * endpoints when `PAM` enabled for user key set. + */ + get authKey(): string | undefined; + /** + * REST API endpoint access authorization key. + * + * It is required to have `authorization key` with required permissions to access REST API + * endpoints when `PAM` enabled for user key set. + */ + getAuthKey(): string | undefined; + /** + * Change REST API endpoint access authorization key. + * + * @param authKey - New authorization key which should be used with new requests. + */ + setAuthKey(authKey: string): void; + /** + * Get a PubNub client user identifier. + * + * @returns Current PubNub client user identifier. + */ + get userId(): string; + /** + * Change the current PubNub client user identifier. + * + * **Important:** Change won't affect ongoing REST API calls. + * + * @param value - New PubNub client user identifier. + * + * @throws Error empty user identifier has been provided. + */ + set userId(value: string); + /** + * Get a PubNub client user identifier. + * + * @returns Current PubNub client user identifier. + */ + getUserId(): string; + /** + * Change the current PubNub client user identifier. + * + * **Important:** Change won't affect ongoing REST API calls. + * + * @param value - New PubNub client user identifier. + * + * @throws Error empty user identifier has been provided. + */ + setUserId(value: string): void; + /** + * Real-time updates filtering expression. + * + * @returns Filtering expression. + */ + get filterExpression(): string | undefined; + /** + * Real-time updates filtering expression. + * + * @returns Filtering expression. + */ + getFilterExpression(): string | undefined; + /** + * Update real-time updates filtering expression. + * + * @param expression - New expression which should be used or `undefined` to disable filtering. + */ + set filterExpression(expression: string | null | undefined); + /** + * Update real-time updates filtering expression. + * + * @param expression - New expression which should be used or `undefined` to disable filtering. + */ + setFilterExpression(expression: string | null): void; + /** + * Dta encryption / decryption key. + * + * @returns Currently used key for data encryption / decryption. + */ + get cipherKey(): string | undefined; + /** + * Change data encryption / decryption key. + * + * @param key - New key which should be used for data encryption / decryption. + */ + set cipherKey(key: string | undefined); + /** + * Change data encryption / decryption key. + * + * @param key - New key which should be used for data encryption / decryption. + */ + setCipherKey(key: string): void; + /** + * Change heartbeat requests interval. + * + * @param interval - New presence request heartbeat intervals. + */ + set heartbeatInterval(interval: number); + /** + * Change heartbeat requests interval. + * + * @param interval - New presence request heartbeat intervals. + */ + setHeartbeatInterval(interval: number): void; + /** + * Get PubNub SDK version. + * + * @returns Current SDK version. + */ + getVersion(): string; + /** + * Add framework's prefix. + * + * @param name - Name of the framework which would want to add own data into `pnsdk` suffix. + * @param suffix - Suffix with information about framework. + */ + _addPnsdkSuffix(name: string, suffix: string | number): void; + /** + * Get a PubNub client user identifier. + * + * @returns Current PubNub client user identifier. + * + * @deprecated Use the {@link getUserId} or {@link userId} getter instead. + */ + getUUID(): string; + /** + * Change the current PubNub client user identifier. + * + * **Important:** Change won't affect ongoing REST API calls. + * + * @param value - New PubNub client user identifier. + * + * @throws Error empty user identifier has been provided. + * + * @deprecated Use the {@link PubNubCore#setUserId} or {@link PubNubCore#userId} setter instead. + */ + setUUID(value: string): void; + /** + * Custom data encryption method. + * + * @deprecated Instead use {@link cryptoModule} for data encryption. + */ + get customEncrypt(): ((data: string) => string) | undefined; + /** + * Custom data decryption method. + * + * @deprecated Instead use {@link cryptoModule} for data decryption. + */ + get customDecrypt(): ((data: string) => string) | undefined; + /** + * Create a `Channel` entity. + * + * Entity can be used for the interaction with the following API: + * - `subscribe` + * + * @param name - Unique channel name. + * @returns `Channel` entity. + */ + channel(name: string): PubNub.Channel; + /** + * Create a `ChannelGroup` entity. + * + * Entity can be used for the interaction with the following API: + * - `subscribe` + * + * @param name - Unique channel group name. + * @returns `ChannelGroup` entity. + */ + channelGroup(name: string): PubNub.ChannelGroup; + /** + * Create a `ChannelMetadata` entity. + * + * Entity can be used for the interaction with the following API: + * - `subscribe` + * + * @param id - Unique channel metadata object identifier. + * @returns `ChannelMetadata` entity. + */ + channelMetadata(id: string): PubNub.ChannelMetadata; + /** + * Create a `UserMetadata` entity. + * + * Entity can be used for the interaction with the following API: + * - `subscribe` + * + * @param id - Unique user metadata object identifier. + * @returns `UserMetadata` entity. + */ + userMetadata(id: string): PubNub.UserMetadata; + /** + * Create subscriptions set object. + * + * @param parameters - Subscriptions set configuration parameters. + */ + subscriptionSet(parameters: { + channels?: string[]; + channelGroups?: string[]; + subscriptionOptions?: PubNub.SubscriptionOptions; + }): PubNub.SubscriptionSet; + /** + * Unsubscribe from all channels and groups. + * + * @param [isOffline] - Whether `offline` presence should be notified or not. + */ + destroy(isOffline?: boolean): void; + /** + * Unsubscribe from all channels and groups. + * + * @deprecated Use {@link destroy} method instead. + */ + stop(): void; + /** + * Register real-time events listener. + * + * @param listener - Listener with event callbacks to handle different types of events. + */ + addListener(listener: PubNub.Listener): void; + /** + * Remove real-time event listener. + * + * @param listener - Event listeners which should be removed. + */ + removeListener(listener: PubNub.Listener): void; + /** + * Clear all real-time event listeners. + */ + removeAllListeners(): void; + /** + * Publish data to a specific channel. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + publish( + parameters: PubNub.Publish.PublishParameters, + callback: PubNub.ResultCallback, + ): void; + /** + * Publish data to a specific channel. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous publish data response. + */ + publish(parameters: PubNub.Publish.PublishParameters): Promise; + /** + * Signal data to a specific channel. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + signal( + parameters: PubNub.Signal.SignalParameters, + callback: PubNub.ResultCallback, + ): void; + /** + * Signal data to a specific channel. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous signal data response. + */ + signal(parameters: PubNub.Signal.SignalParameters): Promise; + /** + * `Fire` a data to a specific channel. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link publish} method instead. + */ + fire( + parameters: PubNub.Publish.PublishParameters, + callback: PubNub.ResultCallback, + ): void; + /** + * `Fire` a data to a specific channel. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous signal data response. + * + * @deprecated Use {@link publish} method instead. + */ + fire(parameters: PubNub.Publish.PublishParameters): Promise; + /** + * Get list of channels on which PubNub client currently subscribed. + * + * @returns List of active channels. + */ + getSubscribedChannels(): string[]; + /** + * Get list of channel groups on which PubNub client currently subscribed. + * + * @returns List of active channel groups. + */ + getSubscribedChannelGroups(): string[]; + /** + * Subscribe to specified channels and groups real-time events. + * + * @param parameters - Request configuration parameters. + */ + subscribe(parameters: PubNub.Subscription.SubscribeParameters): void; + /** + * Unsubscribe from specified channels and groups real-time events. + * + * @param parameters - Request configuration parameters. + */ + unsubscribe(parameters: PubNub.Presence.PresenceLeaveParameters): void; + /** + * Unsubscribe from all channels and groups. + */ + unsubscribeAll(): void; + /** + * Temporarily disconnect from real-time events stream. + */ + disconnect(): void; + /** + * Restore connection to the real-time events stream. + * + * @param parameters - Reconnection catch up configuration. **Note:** available only with + * enabled event engine. + */ + reconnect(parameters?: { timetoken?: string; region?: number }): void; + /** + * Get reactions to a specific message. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + getMessageActions( + parameters: PubNub.MessageAction.GetMessageActionsParameters, + callback: PubNub.ResultCallback, + ): void; + /** + * Get reactions to a specific message. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous get reactions response. + */ + getMessageActions( + parameters: PubNub.MessageAction.GetMessageActionsParameters, + ): Promise; + /** + * Add a reaction to a specific message. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + addMessageAction( + parameters: PubNub.MessageAction.AddMessageActionParameters, + callback: PubNub.ResultCallback, + ): void; + /** + * Add a reaction to a specific message. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous add a reaction response. + */ + addMessageAction( + parameters: PubNub.MessageAction.AddMessageActionParameters, + ): Promise; + /** + * Remove a reaction from a specific message. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + removeMessageAction( + parameters: PubNub.MessageAction.RemoveMessageActionParameters, + callback: PubNub.ResultCallback, + ): void; + /** + * Remove a reaction from a specific message. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous remove a reaction response. + */ + removeMessageAction( + parameters: PubNub.MessageAction.RemoveMessageActionParameters, + ): Promise; + /** + * Fetch messages history for channels. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + fetchMessages( + parameters: PubNub.History.FetchMessagesParameters, + callback: PubNub.ResultCallback, + ): void; + /** + * Fetch messages history for channels. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous fetch messages response. + */ + fetchMessages(parameters: PubNub.History.FetchMessagesParameters): Promise; + /** + * Delete messages from the channel history. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated + */ + deleteMessages( + parameters: PubNub.History.DeleteMessagesParameters, + callback: PubNub.ResultCallback, + ): void; + /** + * Delete messages from the channel history. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous delete messages response. + * + * @deprecated + */ + deleteMessages(parameters: PubNub.History.DeleteMessagesParameters): Promise; + /** + * Count messages from the channels' history. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + messageCounts( + parameters: PubNub.History.MessageCountParameters, + callback: PubNub.ResultCallback, + ): void; + /** + * Count messages from the channels' history. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous count messages response. + */ + messageCounts(parameters: PubNub.History.MessageCountParameters): Promise; + /** + * Fetch single channel history. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated + */ + history( + parameters: PubNub.History.GetHistoryParameters, + callback: PubNub.ResultCallback, + ): void; + /** + * Fetch single channel history. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous fetch channel history response. + * + * @deprecated + */ + history(parameters: PubNub.History.GetHistoryParameters): Promise; + /** + * Get channel's presence information. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + hereNow( + parameters: PubNub.Presence.HereNowParameters, + callback: PubNub.ResultCallback, + ): void; + /** + * Get channel presence information. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous get channel's presence response. + */ + hereNow(parameters: PubNub.Presence.HereNowParameters): Promise; + /** + * Get user's presence information. + * + * Get list of channels to which `uuid` currently subscribed. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + whereNow( + parameters: PubNub.Presence.WhereNowParameters, + callback: PubNub.ResultCallback, + ): void; + /** + * Get user's presence information. + * + * Get list of channels to which `uuid` currently subscribed. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous get user's presence response. + */ + whereNow(parameters: PubNub.Presence.WhereNowParameters): Promise; + /** + * Get associated user's data for channels and groups. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + getState( + parameters: PubNub.Presence.GetPresenceStateParameters, + callback: PubNub.ResultCallback, + ): void; + /** + * Get associated user's data for channels and groups. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous get associated user's data response. + */ + getState(parameters: PubNub.Presence.GetPresenceStateParameters): Promise; + /** + * Set associated user's data for channels and groups. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + setState( + parameters: PubNub.Presence.SetPresenceStateParameters | PubNub.Presence.SetPresenceStateWithHeartbeatParameters, + callback: PubNub.ResultCallback< + PubNub.Presence.SetPresenceStateResponse | PubNub.Presence.PresenceHeartbeatResponse + >, + ): void; + /** + * Set associated user's data for channels and groups. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous set associated user's data response. + */ + setState( + parameters: PubNub.Presence.SetPresenceStateParameters | PubNub.Presence.SetPresenceStateWithHeartbeatParameters, + ): Promise; + /** + * Manual presence management. + * + * @param parameters - Desired presence state for provided list of channels and groups. + */ + presence(parameters: { connected: boolean; channels?: string[]; channelGroups?: string[] }): void; + /** + * Grant token permission. + * + * Generate access token with requested permissions. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + grantToken( + parameters: PubNub.PAM.GrantTokenParameters, + callback: PubNub.ResultCallback, + ): void; + /** + * Grant token permission. + * + * Generate access token with requested permissions. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous grant token response. + */ + grantToken(parameters: PubNub.PAM.GrantTokenParameters): Promise; + /** + * Revoke token permission. + * + * @param token - Access token for which permissions should be revoked. + * @param callback - Request completion handler callback. + */ + revokeToken( + token: PubNub.PAM.RevokeParameters, + callback: PubNub.ResultCallback, + ): void; + /** + * Revoke token permission. + * + * @param token - Access token for which permissions should be revoked. + * + * @returns Asynchronous revoke token response. + */ + revokeToken(token: PubNub.PAM.RevokeParameters): Promise; + /** + * Get current access token. + * + * @returns Previously configured access token using {@link setToken} method. + */ + get token(): string | undefined; + /** + * Get current access token. + * + * @returns Previously configured access token using {@link setToken} method. + */ + getToken(): string | undefined; + /** + * Set current access token. + * + * @param token - New access token which should be used with next REST API endpoint calls. + */ + set token(token: string | undefined); + /** + * Set current access token. + * + * @param token - New access token which should be used with next REST API endpoint calls. + */ + setToken(token: string | undefined): void; + /** + * Parse access token. + * + * Parse token to see what permissions token owner has. + * + * @param token - Token which should be parsed. + * + * @returns Token's permissions information for the resources. + */ + parseToken(token: string): + | { + version: number; + timestamp: number; + ttl: number; + resources?: + | Partial< + Record< + 'groups' | 'channels' | 'uuids', + Record< + string, + | { + read: boolean; + write: boolean; + manage: boolean; + delete: boolean; + get: boolean; + update: boolean; + join: boolean; + } + | undefined + > + > + > + | undefined; + patterns?: + | Partial< + Record< + 'groups' | 'channels' | 'uuids', + Record< + string, + | { + read: boolean; + write: boolean; + manage: boolean; + delete: boolean; + get: boolean; + update: boolean; + join: boolean; + } + | undefined + > + > + > + | undefined; + authorized_uuid?: string | undefined; + signature: ArrayBuffer; + meta?: PubNub.Payload | undefined; + } + | undefined; + /** + * Grant auth key(s) permission. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link grantToken} and {@link setToken} methods instead. + */ + grant(parameters: PubNub.PAM.GrantParameters, callback: PubNub.ResultCallback): void; + /** + * Grant auth key(s) permission. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous grant auth key(s) permissions response. + * + * @deprecated Use {@link grantToken} and {@link setToken} methods instead. + */ + grant(parameters: PubNub.PAM.GrantParameters): Promise; + /** + * Audit auth key(s) permission. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated + */ + audit(parameters: PubNub.PAM.AuditParameters, callback: PubNub.ResultCallback): void; + /** + * Audit auth key(s) permission. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous audit auth key(s) permissions response. + * + * @deprecated + */ + audit(parameters: PubNub.PAM.AuditParameters): Promise; + /** + * PubNub App Context API group. + */ + get objects(): PubNub.PubNubObjects; + /** + * Fetch a paginated list of User objects. + * + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.getAllUUIDMetadata} method instead. + */ + fetchUsers( + callback: PubNub.ResultCallback>, + ): void; + /** + * Fetch a paginated list of User objects. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.getAllUUIDMetadata} method instead. + */ + fetchUsers( + parameters: PubNub.AppContext.GetAllMetadataParameters>, + callback: PubNub.ResultCallback>, + ): void; + /** + * Fetch a paginated list of User objects. + * + * @param [parameters] - Request configuration parameters. + * + * @returns Asynchronous get all User objects response. + * + * @deprecated Use {@link PubNubCore#objects.getAllUUIDMetadata} method instead. + */ + fetchUsers( + parameters?: PubNub.AppContext.GetAllMetadataParameters>, + ): Promise>; + /** + * Fetch User object for currently configured PubNub client `uuid`. + * + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.getUUIDMetadata} method instead. + */ + fetchUser( + callback: PubNub.ResultCallback>, + ): void; + /** + * Fetch User object for currently configured PubNub client `uuid`. + * + * @param parameters - Request configuration parameters. Will fetch User object for currently + * configured PubNub client `uuid` if not set. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.getUUIDMetadata} method instead. + */ + fetchUser( + parameters: PubNub.AppContext.GetUUIDMetadataParameters, + callback: PubNub.ResultCallback>, + ): void; + /** + * Fetch User object for currently configured PubNub client `uuid`. + * + * @param [parameters] - Request configuration parameters. Will fetch User object for currently + * configured PubNub client `uuid` if not set. + * + * @returns Asynchronous get User object response. + * + * @deprecated Use {@link PubNubCore#objects.getUUIDMetadata} method instead. + */ + fetchUser( + parameters?: PubNub.AppContext.GetUUIDMetadataParameters, + ): Promise>; + /** + * Create User object. + * + * @param parameters - Request configuration parameters. Will create User object for currently + * configured PubNub client `uuid` if not set. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.setUUIDMetadata} method instead. + */ + createUser( + parameters: PubNub.AppContext.SetUUIDMetadataParameters, + callback: PubNub.ResultCallback>, + ): void; + /** + * Create User object. + * + * @param parameters - Request configuration parameters. Will create User object for currently + * configured PubNub client `uuid` if not set. + * + * @returns Asynchronous create User object response. + * + * @deprecated Use {@link PubNubCore#objects.setUUIDMetadata} method instead. + */ + createUser( + parameters: PubNub.AppContext.SetUUIDMetadataParameters, + ): Promise>; + /** + * Update User object. + * + * @param parameters - Request configuration parameters. Will update User object for currently + * configured PubNub client `uuid` if not set. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.setUUIDMetadata} method instead. + */ + updateUser( + parameters: PubNub.AppContext.SetUUIDMetadataParameters, + callback: PubNub.ResultCallback>, + ): void; + /** + * Update User object. + * + * @param parameters - Request configuration parameters. Will update User object for currently + * configured PubNub client `uuid` if not set. + * + * @returns Asynchronous update User object response. + * + * @deprecated Use {@link PubNubCore#objects.setUUIDMetadata} method instead. + */ + updateUser( + parameters: PubNub.AppContext.SetUUIDMetadataParameters, + ): Promise>; + /** + * Remove a specific User object. + * + * @param callback - Request completion handler callback. Will remove User object for currently + * configured PubNub client `uuid` if not set. + * + * @deprecated Use {@link PubNubCore#objects.removeUUIDMetadata} method instead. + */ + removeUser(callback: PubNub.ResultCallback): void; + /** + * Remove a specific User object. + * + * @param parameters - Request configuration parameters. Will remove User object for currently + * configured PubNub client `uuid` if not set. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.removeUUIDMetadata} method instead. + */ + removeUser( + parameters: PubNub.AppContext.RemoveUUIDMetadataParameters, + callback: PubNub.ResultCallback, + ): void; + /** + * Remove a specific User object. + * + * @param [parameters] - Request configuration parameters. Will remove User object for currently + * configured PubNub client `uuid` if not set. + * + * @returns Asynchronous User object remove response. + * + * @deprecated Use {@link PubNubCore#objects.removeUUIDMetadata} method instead. + */ + removeUser( + parameters?: PubNub.AppContext.RemoveUUIDMetadataParameters, + ): Promise; + /** + * Fetch a paginated list of Space objects. + * + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.getAllChannelMetadata} method instead. + */ + fetchSpaces( + callback: PubNub.ResultCallback>, + ): void; + /** + * Fetch a paginated list of Space objects. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.getAllChannelMetadata} method instead. + */ + fetchSpaces( + parameters: PubNub.AppContext.GetAllMetadataParameters>, + callback: PubNub.ResultCallback>, + ): void; + /** + * Fetch a paginated list of Space objects. + * + * @param [parameters] - Request configuration parameters. + * + * @returns Asynchronous get all Space objects response. + * + * @deprecated Use {@link PubNubCore#objects.getAllChannelMetadata} method instead. + */ + fetchSpaces( + parameters?: PubNub.AppContext.GetAllMetadataParameters>, + ): Promise>; + /** + * Fetch a specific Space object. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.getChannelMetadata} method instead. + */ + fetchSpace( + parameters: PubNub.AppContext.GetChannelMetadataParameters, + callback: PubNub.ResultCallback>, + ): void; + /** + * Fetch a specific Space object. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous get Channel metadata response. + * + * @deprecated Use {@link PubNubCore#objects.getChannelMetadata} method instead. + */ + fetchSpace( + parameters: PubNub.AppContext.GetChannelMetadataParameters, + ): Promise>; + /** + * Create specific Space object. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.setChannelMetadata} method instead. + */ + createSpace( + parameters: PubNub.AppContext.SetChannelMetadataParameters, + callback: PubNub.ResultCallback>, + ): void; + /** + * Create specific Space object. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous create Space object response. + * + * @deprecated Use {@link PubNubCore#objects.setChannelMetadata} method instead. + */ + createSpace( + parameters: PubNub.AppContext.SetChannelMetadataParameters, + ): Promise>; + /** + * Update specific Space object. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.setChannelMetadata} method instead. + */ + updateSpace( + parameters: PubNub.AppContext.SetChannelMetadataParameters, + callback: PubNub.ResultCallback>, + ): void; + /** + * Update specific Space object. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous update Space object response. + * + * @deprecated Use {@link PubNubCore#objects.setChannelMetadata} method instead. + */ + updateSpace( + parameters: PubNub.AppContext.SetChannelMetadataParameters, + ): Promise>; + /** + * Remove Space object. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.removeChannelMetadata} method instead. + */ + removeSpace( + parameters: PubNub.AppContext.RemoveChannelMetadataParameters, + callback: PubNub.ResultCallback, + ): void; + /** + * Remove a specific Space object. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous Space object remove response. + * + * @deprecated Use {@link PubNubCore#objects.removeChannelMetadata} method instead. + */ + removeSpace( + parameters: PubNub.AppContext.RemoveChannelMetadataParameters, + ): Promise; + /** + * Fetch paginated list of specific Space members or specific User memberships. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.getChannelMembers} or {@link PubNubCore#objects.getMemberships} + * methods instead. + */ + fetchMemberships< + RelationCustom extends PubNub.AppContext.CustomData = PubNub.AppContext.CustomData, + MetadataCustom extends PubNub.AppContext.CustomData = PubNub.AppContext.CustomData, + >( + parameters: PubNub.AppContext.GetMembershipsParameters | PubNub.AppContext.GetMembersParameters, + callback: PubNub.ResultCallback< + | PubNub.AppContext.SpaceMembershipsResponse + | PubNub.AppContext.UserMembersResponse + >, + ): void; + /** + * Fetch paginated list of specific Space members or specific User memberships. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous get specific Space members or specific User memberships response. + * + * @deprecated Use {@link PubNubCore#objects.getChannelMembers} or {@link PubNubCore#objects.getMemberships} + * methods instead. + */ + fetchMemberships< + RelationCustom extends PubNub.AppContext.CustomData = PubNub.AppContext.CustomData, + MetadataCustom extends PubNub.AppContext.CustomData = PubNub.AppContext.CustomData, + >( + parameters: PubNub.AppContext.GetMembershipsParameters | PubNub.AppContext.GetMembersParameters, + ): Promise< + | PubNub.AppContext.SpaceMembershipsResponse + | PubNub.AppContext.UserMembersResponse + >; + /** + * Add members to specific Space or memberships specific User. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.setChannelMembers} or {@link PubNubCore#objects.setMemberships} + * methods instead. + */ + addMemberships< + Custom extends PubNub.AppContext.CustomData = PubNub.AppContext.CustomData, + MetadataCustom extends PubNub.AppContext.CustomData = PubNub.AppContext.CustomData, + >( + parameters: + | PubNub.AppContext.SetMembershipsParameters + | PubNub.AppContext.SetChannelMembersParameters, + callback: PubNub.ResultCallback< + | PubNub.AppContext.SetMembershipsResponse + | PubNub.AppContext.SetMembersResponse + >, + ): void; + /** + * Add members to specific Space or memberships specific User. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous add members to specific Space or memberships specific User response. + * + * @deprecated Use {@link PubNubCore#objects.setChannelMembers} or {@link PubNubCore#objects.setMemberships} + * methods instead. + */ + addMemberships< + Custom extends PubNub.AppContext.CustomData = PubNub.AppContext.CustomData, + MetadataCustom extends PubNub.AppContext.CustomData = PubNub.AppContext.CustomData, + >( + parameters: + | PubNub.AppContext.SetMembershipsParameters + | PubNub.AppContext.SetChannelMembersParameters, + ): Promise< + | PubNub.AppContext.SetMembershipsResponse + | PubNub.AppContext.SetMembersResponse + >; + /** + * Update specific Space members or User memberships. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.setChannelMembers} or {@link PubNubCore#objects.setMemberships} + * methods instead. + */ + updateMemberships< + Custom extends PubNub.AppContext.CustomData = PubNub.AppContext.CustomData, + MetadataCustom extends PubNub.AppContext.CustomData = PubNub.AppContext.CustomData, + >( + parameters: + | PubNub.AppContext.SetMembershipsParameters + | PubNub.AppContext.SetChannelMembersParameters, + callback: PubNub.ResultCallback< + | PubNub.AppContext.SetMembershipsResponse + | PubNub.AppContext.SetMembersResponse + >, + ): void; + /** + * Update specific Space members or User memberships. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous update Space members or User memberships response. + * + * @deprecated Use {@link PubNubCore#objects.setChannelMembers} or {@link PubNubCore#objects.setMemberships} + * methods instead. + */ + updateMemberships< + Custom extends PubNub.AppContext.CustomData = PubNub.AppContext.CustomData, + MetadataCustom extends PubNub.AppContext.CustomData = PubNub.AppContext.CustomData, + >( + parameters: + | PubNub.AppContext.SetMembershipsParameters + | PubNub.AppContext.SetChannelMembersParameters, + ): Promise< + | PubNub.AppContext.SetMembershipsResponse + | PubNub.AppContext.SetMembersResponse + >; + /** + * Remove User membership. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.removeMemberships} or {@link PubNubCore#objects.removeChannelMembers} + * methods instead from `objects` API group. + */ + removeMemberships< + RelationCustom extends PubNub.AppContext.CustomData = PubNub.AppContext.CustomData, + MetadataCustom extends PubNub.AppContext.CustomData = PubNub.AppContext.CustomData, + >( + parameters: PubNub.AppContext.RemoveMembersParameters | PubNub.AppContext.RemoveMembershipsParameters, + callback: PubNub.ResultCallback< + | PubNub.AppContext.RemoveMembersResponse + | PubNub.AppContext.RemoveMembershipsResponse + >, + ): void; + /** + * Remove User membership. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous memberships modification response. + * + * @deprecated Use {@link PubNubCore#objects.removeMemberships} or {@link PubNubCore#objects.removeChannelMembers} + * methods instead from `objects` API group. + */ + removeMemberships< + RelationCustom extends PubNub.AppContext.CustomData = PubNub.AppContext.CustomData, + MetadataCustom extends PubNub.AppContext.CustomData = PubNub.AppContext.CustomData, + >( + parameters: PubNub.AppContext.RemoveMembersParameters | PubNub.AppContext.RemoveMembershipsParameters, + ): Promise>; + /** + * PubNub Channel Groups API group. + */ + get channelGroups(): PubNub.PubNubChannelGroups; + /** + * PubNub Push Notifications API group. + */ + get push(): PubNub.PubNubPushNotifications; + /** + * Share file to a specific channel. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + sendFile( + parameters: PubNub.FileSharing.SendFileParameters, + callback: PubNub.ResultCallback, + ): void; + /** + * Share file to a specific channel. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous file sharing response. + */ + sendFile( + parameters: PubNub.FileSharing.SendFileParameters, + ): Promise; + /** + * Publish file message to a specific channel. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + publishFile( + parameters: PubNub.FileSharing.PublishFileMessageParameters, + callback: PubNub.ResultCallback, + ): void; + /** + * Publish file message to a specific channel. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous publish file message response. + */ + publishFile( + parameters: PubNub.FileSharing.PublishFileMessageParameters, + ): Promise; + /** + * Retrieve list of shared files in specific channel. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + listFiles( + parameters: PubNub.FileSharing.ListFilesParameters, + callback: PubNub.ResultCallback, + ): void; + /** + * Retrieve list of shared files in specific channel. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous shared files list response. + */ + listFiles(parameters: PubNub.FileSharing.ListFilesParameters): Promise; + /** + * Get file download Url. + * + * @param parameters - Request configuration parameters. + * + * @returns File download Url. + */ + getFileUrl(parameters: PubNub.FileSharing.FileUrlParameters): PubNub.FileSharing.FileUrlResponse; + /** + * Download shared file from specific channel. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + downloadFile( + parameters: PubNub.FileSharing.DownloadFileParameters, + callback: PubNub.ResultCallback, + ): void; + /** + * Download shared file from specific channel. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous download shared file response. + */ + downloadFile(parameters: PubNub.FileSharing.DownloadFileParameters): Promise; + /** + * Delete shared file from specific channel. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + deleteFile( + parameters: PubNub.FileSharing.DeleteFileParameters, + callback: PubNub.ResultCallback, + ): void; + /** + * Delete shared file from specific channel. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous delete shared file response. + */ + deleteFile(parameters: PubNub.FileSharing.DeleteFileParameters): Promise; + /** + Get current high-precision timetoken. + * + * @param callback - Request completion handler callback. + */ + time(callback: PubNub.ResultCallback): void; + /** + * Get current high-precision timetoken. + * + * @returns Asynchronous get current timetoken response. + */ + time(): Promise; + /** + * Encrypt data. + * + * @param data - Stringified data which should be encrypted using `CryptoModule`. + * @deprecated + * @param [customCipherKey] - Cipher key which should be used to encrypt data. **Deprecated:** + * use {@link Configuration#cryptoModule|cryptoModule} instead. + * + * @returns Data encryption result as a string. + */ + encrypt(data: string | PubNub.Payload, customCipherKey?: string): string; + /** + * Decrypt data. + * + * @param data - Stringified data which should be encrypted using `CryptoModule`. + * @param [customCipherKey] - Cipher key which should be used to decrypt data. **Deprecated:** + * use {@link Configuration#cryptoModule|cryptoModule} instead. + * + * @returns Data decryption result as an object. + */ + decrypt(data: string, customCipherKey?: string): PubNub.Payload | null; + /** + * Encrypt file content. + * + * @param file - File which should be encrypted using `CryptoModule`. + * + * @returns Asynchronous file encryption result. + * + * @throws Error if source file not provided. + * @throws File constructor not provided. + * @throws Crypto module is missing (if non-legacy flow used). + */ + encryptFile(file: PubNub.PubNubFileInterface): Promise; + /** + * Encrypt file content. + * + * @param key - Cipher key which should be used to encrypt data. + * @param file - File which should be encrypted using legacy cryptography. + * + * @returns Asynchronous file encryption result. + * + * @throws Error if source file not provided. + * @throws File constructor not provided. + * @throws Crypto module is missing (if non-legacy flow used). + */ + encryptFile(key: string, file: PubNub.PubNubFileInterface): Promise; + /** + * Decrypt file content. + * + * @param file - File which should be decrypted using legacy cryptography. + * + * @returns Asynchronous file decryption result. + * + * @throws Error if source file not provided. + * @throws File constructor not provided. + * @throws Crypto module is missing (if non-legacy flow used). + */ + decryptFile(file: PubNub.PubNubFileInterface): Promise; + /** + * Decrypt file content. + * + * @param key - Cipher key which should be used to decrypt data. + * @param [file] - File which should be decrypted using legacy cryptography. + * + * @returns Asynchronous file decryption result. + * + * @throws Error if source file not provided. + * @throws File constructor not provided. + * @throws Crypto module is missing (if non-legacy flow used). + */ + decryptFile( + key: string | PubNub.PubNubFileInterface, + file?: PubNub.PubNubFileInterface, + ): Promise; +} + +declare namespace PubNub { + /** + * Crypto module cryptors interface. + */ + type CryptorType = ICryptor | ILegacyCryptor; + + /** + * CryptoModule for Node.js platform. + */ + export class NodeCryptoModule extends AbstractCryptoModule { + /** + * {@link LegacyCryptor|Legacy} cryptor identifier. + */ + static LEGACY_IDENTIFIER: string; + static legacyCryptoModule(config: CryptorConfiguration): NodeCryptoModule; + static aesCbcCryptoModule(config: CryptorConfiguration): NodeCryptoModule; + /** + * Construct crypto module with `cryptor` as default for data encryption and decryption. + * + * @param defaultCryptor - Default cryptor for data encryption and decryption. + * + * @returns Crypto module with pre-configured default cryptor. + */ + static withDefaultCryptor(defaultCryptor: CryptorType): NodeCryptoModule; + encrypt(data: ArrayBuffer | string): string | ArrayBuffer; + encryptFile( + file: PubNubFile, + File: PubNubFileConstructor, + ): Promise; + decrypt(data: ArrayBuffer | string): ArrayBuffer | Payload | null; + decryptFile( + file: PubNubFile, + File: PubNubFileConstructor, + ): Promise; + } + + /** Re-export aliased type. */ + export { NodeCryptoModule as CryptoModuleType }; + + /** + * Crypto module configuration. + */ + export type CryptoModuleConfiguration = { + default: C; + cryptors?: C[]; + }; + + export type CryptorConfiguration = { + /** + * Data encryption / decryption key. + */ + cipherKey?: string; + /** + * Request sign secret key. + */ + secretKey?: string; + /** + * Whether random initialization vector should be used or not. + * + * @default `true` + */ + useRandomIVs?: boolean; + /** + * Custom data encryption method. + * + * @deprecated Instead use {@link cryptoModule} for data encryption. + */ + customEncrypt?: (data: string | Payload) => string; + /** + * Custom data decryption method. + * + * @deprecated Instead use {@link cryptoModule} for data decryption. + */ + customDecrypt?: (data: string) => string; + }; + + /** + * Base crypto module interface. + */ + export interface ICryptoModule { + /** + * Encrypt data. + * + * @param data - Data which should be encrypted using `CryptoModule`. + * + * @returns Data encryption result. + */ + encrypt(data: ArrayBuffer | string): ArrayBuffer | string; + /** + * Encrypt file object. + * + * @param file - File object with data for encryption. + * @param File - File object constructor to create instance for encrypted data representation. + * + * @returns Asynchronous file encryption result. + */ + encryptFile( + file: PubNubFileInterface, + File: PubNubFileConstructor, + ): Promise; + /** + * Encrypt data. + * + * @param data - Dta which should be encrypted using `CryptoModule`. + * + * @returns Data decryption result. + */ + decrypt(data: ArrayBuffer | string): ArrayBuffer | Payload | null; + /** + * Decrypt file object. + * + * @param file - Encrypted file object with data for decryption. + * @param File - File object constructor to create instance for decrypted data representation. + * + * @returns Asynchronous file decryption result. + */ + decryptFile( + file: PubNubFileInterface, + File: PubNubFileConstructor, + ): Promise; + } + + export abstract class AbstractCryptoModule implements ICryptoModule { + defaultCryptor: C; + cryptors: C[]; + /** + * Construct crypto module with legacy cryptor for encryption and both legacy and AES-CBC + * cryptors for decryption. + * + * @param config Cryptors configuration options. + * + * @returns Crypto module which encrypts data using legacy cryptor. + * + * @throws Error if `config.cipherKey` not set. + */ + static legacyCryptoModule(config: CryptorConfiguration): ICryptoModule; + /** + * Construct crypto module with AES-CBC cryptor for encryption and both AES-CBC and legacy + * cryptors for decryption. + * + * @param config Cryptors configuration options. + * + * @returns Crypto module which encrypts data using AES-CBC cryptor. + * + * @throws Error if `config.cipherKey` not set. + */ + static aesCbcCryptoModule(config: CryptorConfiguration): ICryptoModule; + constructor(configuration: CryptoModuleConfiguration); + /** + * Encrypt data. + * + * @param data - Data which should be encrypted using {@link ICryptoModule}. + * + * @returns Data encryption result. + */ + abstract encrypt(data: ArrayBuffer | string): ArrayBuffer | string; + /** + * Encrypt file object. + * + * @param file - File object with data for encryption. + * @param File - File object constructor to create instance for encrypted data representation. + * + * @returns Asynchronous file encryption result. + */ + abstract encryptFile( + file: PubNubFileInterface, + File: PubNubFileConstructor, + ): Promise; + /** + * Encrypt data. + * + * @param data - Dta which should be encrypted using `ICryptoModule`. + * + * @returns Data decryption result. + */ + abstract decrypt(data: ArrayBuffer | string): ArrayBuffer | Payload | null; + /** + * Decrypt file object. + * + * @param file - Encrypted file object with data for decryption. + * @param File - File object constructor to create instance for decrypted data representation. + * + * @returns Asynchronous file decryption result. + */ + abstract decryptFile( + file: PubNubFileInterface, + File: PubNubFileConstructor, + ): Promise; + } + + /** + * Base file constructor parameters. + * + * Minimum set of parameters which can be p + */ + export type PubNubBasicFileParameters = { + data: string | ArrayBuffer; + name: string; + mimeType?: string; + }; + + /** + * Platform-agnostic {@link PubNub} File object. + * + * Interface describes share of {@link PubNub} File which is required by {@link PubNub} core to + * perform required actions. + */ + export interface PubNubFileInterface { + /** + * Actual file name. + */ + name: string; + /** + * File mime-type. + */ + mimeType?: string; + /** + * File content length. + */ + contentLength?: number; + /** + * Convert {@link PubNub} file object content to {@link ArrayBuffer}. + * + * @returns Asynchronous results of conversion to the {@link ArrayBuffer}. + * + * @throws Error if provided {@link PubNub} File object content is not supported for this + * operation. + */ + toArrayBuffer(): Promise; + /** + * Convert {@link PubNub} File object content to file `Uri`. + * + * @returns Asynchronous results of conversion to file `Uri`. + * + * @throws Error if provided {@link PubNub} File object content is not supported for this + * operation. + */ + toFileUri(): Promise>; + } + + /** + * {@link PubNub} File object class interface. + */ + export interface PubNubFileConstructor { + /** + * Whether {@link Blob} data supported by platform or not. + */ + supportsBlob: boolean; + /** + * Whether {@link File} data supported by platform or not. + */ + supportsFile: boolean; + /** + * Whether {@link Buffer} data supported by platform or not. + */ + supportsBuffer: boolean; + /** + * Whether {@link Stream} data supported by platform or not. + */ + supportsStream: boolean; + /** + * Whether {@link String} data supported by platform or not. + */ + supportsString: boolean; + /** + * Whether {@link ArrayBuffer} supported by platform or not. + */ + supportsArrayBuffer: boolean; + /** + * Whether {@link PubNub} File object encryption supported or not. + */ + supportsEncryptFile: boolean; + /** + * Whether `File Uri` data supported by platform or not. + */ + supportsFileUri: boolean; + /** + * {@link PubNub} File object constructor. + * + * @param file - File instantiation parameters (can be raw data or structured object). + * + * @returns Constructed platform-specific {@link PubNub} File object. + */ + create(file: ConstructorParameters): File; + /** + * {@link PubNub} File object constructor. + * + * @param file - File instantiation parameters (can be raw data or structured object). + * + * @returns Constructed platform-specific {@link PubNub} File object. + */ + new (file: ConstructorParameters): File; + } + + /** + * Endpoint call completion block with result. + * + * **Note:** Endpoints which return consumable data use this callback. + */ + export type ResultCallback = (status: Status, response: ResponseType | null) => void; + + /** + * Endpoint acknowledgment completion block. + * + * **Note:** Endpoints which return only acknowledgment or error status use this callback. + */ + export type StatusCallback = (status: Status) => void; + + /** + * REST API endpoint processing status. + * + * **Note:** Used as {@link ResultCallback} and {@link StatusCallback} callbacks first argument type and + * {@link PubNubError} instance `status` field value type. + */ + export type Status = { + /** + * Whether status represent error or not. + */ + error: boolean; + /** + * API call status category. + */ + category: StatusCategory; + /** + * Type of REST API endpoint which reported status. + */ + operation?: RequestOperation; + /** + * REST API response status code. + */ + statusCode: number; + /** + * Error data provided by REST API. + */ + errorData?: Error | Payload; + /** + * Additional status information. + */ + [p: string]: Payload | Error | undefined; + }; + + /** + * Real-time PubNub client status change event. + */ + export type StatusEvent = { + /** + * API call status category. + */ + category: StatusCategory; + /** + * Type of REST API endpoint which reported status. + */ + operation?: RequestOperation; + /** + * Information about error. + */ + error?: string | boolean; + /** + * List of channels for which status update announced. + */ + affectedChannels?: string[]; + /** + * List of currently subscribed channels. + * + * List of channels from which PubNub client receives real-time updates. + */ + subscribedChannels?: string[]; + /** + * List of channel groups for which status update announced. + */ + affectedChannelGroups?: string[]; + /** + * High-precision timetoken which has been used with previous subscription loop. + */ + lastTimetoken?: number | string; + /** + * High-precision timetoken which is used for current subscription loop. + */ + currentTimetoken?: number | string; + }; + + /** + * {@link TransportRequest} query parameter type. + */ + export type Query = Record; + + /** + * General payload type. + * + * Type should be used for: + * * generic messages and signals content, + * * published message metadata. + */ + export type Payload = + | string + | number + | boolean + | { + toJSON: () => Payload; + } + | { + [key: string]: Payload | null; + } + | Payload[]; + + /** + * Endpoint API operation types. + */ + export enum RequestOperation { + /** + * Data publish REST API operation. + */ + PNPublishOperation = 'PNPublishOperation', + /** + * Signal sending REST API operation. + */ + PNSignalOperation = 'PNSignalOperation', + /** + * Subscribe for real-time updates REST API operation. + * + * User's presence change on specified entities will trigger `join` event. + */ + PNSubscribeOperation = 'PNSubscribeOperation', + /** + * Unsubscribe from real-time updates REST API operation. + * + * User's presence change on specified entities will trigger `leave` event. + */ + PNUnsubscribeOperation = 'PNUnsubscribeOperation', + /** + * Fetch user's presence information REST API operation. + */ + PNWhereNowOperation = 'PNWhereNowOperation', + /** + * Fetch channel's presence information REST API operation. + */ + PNHereNowOperation = 'PNHereNowOperation', + /** + * Fetch global presence information REST API operation. + */ + PNGlobalHereNowOperation = 'PNGlobalHereNowOperation', + /** + * Update user's information associated with specified channel REST API operation. + */ + PNSetStateOperation = 'PNSetStateOperation', + /** + * Fetch user's information associated with the specified channel REST API operation. + */ + PNGetStateOperation = 'PNGetStateOperation', + /** + * Announce presence on managed channels REST API operation. + */ + PNHeartbeatOperation = 'PNHeartbeatOperation', + /** + * Add a reaction to the specified message REST API operation. + */ + PNAddMessageActionOperation = 'PNAddActionOperation', + /** + * Remove reaction from the specified message REST API operation. + */ + PNRemoveMessageActionOperation = 'PNRemoveMessageActionOperation', + /** + * Fetch reactions for specific message REST API operation. + */ + PNGetMessageActionsOperation = 'PNGetMessageActionsOperation', + PNTimeOperation = 'PNTimeOperation', + /** + * Channel history REST API operation. + */ + PNHistoryOperation = 'PNHistoryOperation', + /** + * Delete messages from channel history REST API operation. + */ + PNDeleteMessagesOperation = 'PNDeleteMessagesOperation', + /** + * History for channels REST API operation. + */ + PNFetchMessagesOperation = 'PNFetchMessagesOperation', + /** + * Number of messages for channels in specified time frame REST API operation. + */ + PNMessageCounts = 'PNMessageCountsOperation', + /** + * Fetch users metadata REST API operation. + */ + PNGetAllUUIDMetadataOperation = 'PNGetAllUUIDMetadataOperation', + /** + * Fetch user metadata REST API operation. + */ + PNGetUUIDMetadataOperation = 'PNGetUUIDMetadataOperation', + /** + * Set user metadata REST API operation. + */ + PNSetUUIDMetadataOperation = 'PNSetUUIDMetadataOperation', + /** + * Remove user metadata REST API operation. + */ + PNRemoveUUIDMetadataOperation = 'PNRemoveUUIDMetadataOperation', + /** + * Fetch channels metadata REST API operation. + */ + PNGetAllChannelMetadataOperation = 'PNGetAllChannelMetadataOperation', + /** + * Fetch channel metadata REST API operation. + */ + PNGetChannelMetadataOperation = 'PNGetChannelMetadataOperation', + /** + * Set channel metadata REST API operation. + */ + PNSetChannelMetadataOperation = 'PNSetChannelMetadataOperation', + /** + * Remove channel metadata REST API operation. + */ + PNRemoveChannelMetadataOperation = 'PNRemoveChannelMetadataOperation', + /** + * Fetch channel members REST API operation. + */ + PNGetMembersOperation = 'PNGetMembersOperation', + /** + * Update channel members REST API operation. + */ + PNSetMembersOperation = 'PNSetMembersOperation', + /** + * Fetch channel memberships REST API operation. + */ + PNGetMembershipsOperation = 'PNGetMembershipsOperation', + /** + * Update channel memberships REST API operation. + */ + PNSetMembershipsOperation = 'PNSetMembershipsOperation', + /** + * Fetch list of files sent to the channel REST API operation. + */ + PNListFilesOperation = 'PNListFilesOperation', + /** + * Retrieve file upload URL REST API operation. + */ + PNGenerateUploadUrlOperation = 'PNGenerateUploadUrlOperation', + /** + * Upload file to the channel REST API operation. + */ + PNPublishFileOperation = 'PNPublishFileOperation', + /** + * Publish File Message to the channel REST API operation. + */ + PNPublishFileMessageOperation = 'PNPublishFileMessageOperation', + /** + * Retrieve file download URL REST API operation. + */ + PNGetFileUrlOperation = 'PNGetFileUrlOperation', + /** + * Download file from the channel REST API operation. + */ + PNDownloadFileOperation = 'PNDownloadFileOperation', + /** + * Delete file sent to the channel REST API operation. + */ + PNDeleteFileOperation = 'PNDeleteFileOperation', + /** + * Register channels with device push notifications REST API operation. + */ + PNAddPushNotificationEnabledChannelsOperation = 'PNAddPushNotificationEnabledChannelsOperation', + /** + * Unregister channels with device push notifications REST API operation. + */ + PNRemovePushNotificationEnabledChannelsOperation = 'PNRemovePushNotificationEnabledChannelsOperation', + /** + * Fetch list of channels with enabled push notifications for device REST API operation. + */ + PNPushNotificationEnabledChannelsOperation = 'PNPushNotificationEnabledChannelsOperation', + /** + * Disable push notifications for device REST API operation. + */ + PNRemoveAllPushNotificationsOperation = 'PNRemoveAllPushNotificationsOperation', + /** + * Fetch channels groups list REST API operation. + */ + PNChannelGroupsOperation = 'PNChannelGroupsOperation', + /** + * Remove specified channel group REST API operation. + */ + PNRemoveGroupOperation = 'PNRemoveGroupOperation', + /** + * Fetch list of channels for the specified channel group REST API operation. + */ + PNChannelsForGroupOperation = 'PNChannelsForGroupOperation', + /** + * Add list of channels to the specified channel group REST API operation. + */ + PNAddChannelsToGroupOperation = 'PNAddChannelsToGroupOperation', + /** + * Remove list of channels from the specified channel group REST API operation. + */ + PNRemoveChannelsFromGroupOperation = 'PNRemoveChannelsFromGroupOperation', + /** + * Generate authorized token REST API operation. + */ + PNAccessManagerGrant = 'PNAccessManagerGrant', + /** + * Generate authorized token REST API operation. + */ + PNAccessManagerGrantToken = 'PNAccessManagerGrantToken', + PNAccessManagerAudit = 'PNAccessManagerAudit', + /** + * Revoke authorized token REST API operation. + */ + PNAccessManagerRevokeToken = 'PNAccessManagerRevokeToken', + } + + /** + * Request processing status categories. + */ + export enum StatusCategory { + /** + * Call failed when network was unable to complete the call. + */ + PNNetworkIssuesCategory = 'PNNetworkIssuesCategory', + /** + * Network call timed out. + */ + PNTimeoutCategory = 'PNTimeoutCategory', + /** + * Request has been cancelled. + */ + PNCancelledCategory = 'PNCancelledCategory', + /** + * Server responded with bad response. + */ + PNBadRequestCategory = 'PNBadRequestCategory', + /** + * Server responded with access denied. + */ + PNAccessDeniedCategory = 'PNAccessDeniedCategory', + /** + * Incomplete parameters provided for used endpoint. + */ + PNValidationErrorCategory = 'PNValidationErrorCategory', + /** + * PubNub request acknowledgment status. + * + * Some API endpoints respond with request processing status w/o useful data. + */ + PNAcknowledgmentCategory = 'PNAcknowledgmentCategory', + /** + * Something strange happened; please check the logs. + */ + PNUnknownCategory = 'PNUnknownCategory', + /** + * SDK will announce when the network appears to be connected again. + */ + PNNetworkUpCategory = 'PNNetworkUpCategory', + /** + * SDK will announce when the network appears to down. + */ + PNNetworkDownCategory = 'PNNetworkDownCategory', + /** + * PubNub client reconnected to the real-time updates stream. + */ + PNReconnectedCategory = 'PNReconnectedCategory', + /** + * PubNub client connected to the real-time updates stream. + */ + PNConnectedCategory = 'PNConnectedCategory', + /** + * Received real-time updates exceed specified threshold. + * + * After temporary disconnection and catchup, this category means that potentially some + * real-time updates have been pushed into `storage` and need to be requested separately. + */ + PNRequestMessageCountExceededCategory = 'PNRequestMessageCountExceededCategory', + /** + * PubNub client disconnected from the real-time updates streams. + */ + PNDisconnectedCategory = 'PNDisconnectedCategory', + /** + * PubNub client wasn't able to connect to the real-time updates streams. + */ + PNConnectionErrorCategory = 'PNConnectionErrorCategory', + /** + * PubNub client unexpectedly disconnected from the real-time updates streams. + */ + PNDisconnectedUnexpectedlyCategory = 'PNDisconnectedUnexpectedlyCategory', + } + + /** + * PubNub File instance creation parameters. + */ + export type PubNubFileParameters = { + /** + * Readable stream represents file object content. + */ + stream?: Readable; + /** + * Buffer or string represents file object content. + */ + data?: Buffer | ArrayBuffer | string; + /** + * String {@link PubNubFileParameters#data|data} encoding. + * + * @default `utf8` + */ + encoding?: StringEncoding; + /** + * File object name. + */ + name: string; + /** + * File object content type. + */ + mimeType?: string; + }; + + /** + * Node.js implementation for {@link PubNub} File object. + * + * **Important:** Class should implement constructor and class fields from {@link PubNubFileConstructor}. + */ + export class PubNubFile implements PubNubFileInterface { + /** + * Whether {@link Blob} data supported by platform or not. + */ + static supportsBlob: boolean; + /** + * Whether {@link File} data supported by platform or not. + */ + static supportsFile: boolean; + /** + * Whether {@link Buffer} data supported by platform or not. + */ + static supportsBuffer: boolean; + /** + * Whether {@link Stream} data supported by platform or not. + */ + static supportsStream: boolean; + /** + * Whether {@link String} data supported by platform or not. + */ + static supportsString: boolean; + /** + * Whether {@link ArrayBuffer} supported by platform or not. + */ + static supportsArrayBuffer: boolean; + /** + * Whether {@link PubNub} File object encryption supported or not. + */ + static supportsEncryptFile: boolean; + /** + * Whether `File Uri` data supported by platform or not. + */ + static supportsFileUri: boolean; + /** + * File object content source. + */ + readonly data: Readable | Buffer; + /** + * File object content length. + */ + contentLength?: number; + /** + * File object content type. + */ + mimeType: string; + /** + * File object name. + */ + name: string; + static create(file: PubNubFileParameters): PubNubFile; + constructor(file: PubNubFileParameters); + /** + * Convert {@link PubNub} File object content to {@link Buffer}. + * + * @returns Asynchronous results of conversion to the {@link Buffer}. + */ + toBuffer(): Promise; + /** + * Convert {@link PubNub} File object content to {@link ArrayBuffer}. + * + * @returns Asynchronous results of conversion to the {@link ArrayBuffer}. + */ + toArrayBuffer(): Promise; + /** + * Convert {@link PubNub} File object content to {@link string}. + * + * @returns Asynchronous results of conversion to the {@link string}. + */ + toString(encoding?: BufferEncoding): Promise; + /** + * Convert {@link PubNub} File object content to {@link Readable} stream. + * + * @returns Asynchronous results of conversion to the {@link Readable} stream. + */ + toStream(): Promise; + /** + * Convert {@link PubNub} File object content to {@link File}. + * + * @throws Error because {@link File} not available in Node.js environment. + */ + toFile(): Promise; + /** + * Convert {@link PubNub} File object content to file `Uri`. + * + * @throws Error because file `Uri` not available in Node.js environment. + */ + toFileUri(): Promise>; + /** + * Convert {@link PubNub} File object content to {@link Blob}. + * + * @throws Error because {@link Blob} not available in Node.js environment. + */ + toBlob(): Promise; + } + + /** + * Data encrypted by {@link NodeCryptoModule}. + */ + export type EncryptedDataType = { + /** + * Encrypted data. + */ + data: Buffer | string; + /** + * Used cryptor's metadata. + */ + metadata: Buffer | null; + }; + + /** + * {@link Readable} stream encrypted by {@link NodeCryptoModule}. + */ + export type EncryptedStream = { + /** + * Stream with encrypted content. + */ + stream: NodeJS.ReadableStream; + /** + * Length of encrypted data in {@link Readable} stream. + */ + metadataLength: number; + /** + * Used cryptor's metadata. + */ + metadata?: Buffer | undefined; + }; + + /** + * Cryptor algorithm interface. + */ + export interface ICryptor { + /** + * Cryptor unique identifier. + * + * @returns Cryptor identifier. + */ + get identifier(): string; + /** + * Encrypt provided source data. + * + * @param data - Source data for encryption. + * + * @returns Encrypted data object. + * + * @throws Error if unknown data type has been passed. + */ + encrypt(data: BufferSource | string): EncryptedDataType; + /** + * Encrypt provided source {@link Readable} stream. + * + * @param stream - Stream for encryption. + * + * @returns Encrypted stream object. + * + * @throws Error if unknown data type has been passed. + */ + encryptStream(stream: NodeJS.ReadableStream): Promise; + /** + * Decrypt provided encrypted data object. + * + * @param data - Encrypted data object for decryption. + * + * @returns Decrypted data. + * + * @throws Error if unknown data type has been passed. + */ + decrypt(data: EncryptedDataType): ArrayBuffer; + /** + * Decrypt provided encrypted stream object. + * + * @param stream - Encrypted stream object for decryption. + * + * @returns Decrypted data as {@link Readable} stream. + * + * @throws Error if unknown data type has been passed. + */ + decryptStream(stream: EncryptedStream): Promise; + } + + /** + * Legacy cryptor algorithm interface. + */ + export interface ILegacyCryptor { + /** + * Cryptor unique identifier. + */ + get identifier(): string; + /** + * Encrypt provided source data. + * + * @param data - Source data for encryption. + * + * @returns Encrypted data object. + * + * @throws Error if unknown data type has been passed. + */ + encrypt(data: string): EncryptedDataType; + /** + * Encrypt provided source {@link PubNub} File object. + * + * @param file - Source {@link PubNub} File object for encryption. + * @param File - Class constructor for {@link PubNub} File object. + * + * @returns Encrypted data as {@link PubNub} File object. + * + * @throws Error if file is empty or contains unsupported data type. + * @throws Error if cipher key not set. + */ + encryptFile( + file: PubNubFile, + File: PubNubFileConstructor, + ): Promise; + /** + * Decrypt provided encrypted data object. + * + * @param data - Encrypted data object for decryption. + * + * @returns Decrypted data. + * + * @throws Error if unknown data type has been passed. + */ + decrypt(data: EncryptedDataType): Payload | null; + /** + * Decrypt provided encrypted {@link PubNub} File object. + * + * @param file - Encrypted {@link PubNub} File object for decryption. + * @param File - Class constructor for {@link PubNub} File object. + * + * @returns Decrypted data as {@link PubNub} File object. + * + * @throws Error if file is empty or contains unsupported data type. + * @throws Error if cipher key not set. + */ + decryptFile( + file: PubNubFile, + File: PubNubFileConstructor, + ): Promise; + } + + /** + * NodeJS platform PubNub client configuration. + */ + export type PubNubConfiguration = UserConfiguration & { + /** + * Set a custom parameters for setting your connection `keepAlive` if this is set to `true`. + */ + keepAliveSettings?: TransportKeepAlive; + /** + * The cryptography module used for encryption and decryption of messages and files. Takes the + * {@link cipherKey} and {@link useRandomIVs} parameters as arguments. + * + * For more information, refer to the + * {@link /docs/sdks/javascript/api-reference/configuration#cryptomodule|cryptoModule} section. + * + * @default `not set` + */ + cryptoModule?: ICryptoModule; + /** + * If passed, will encrypt the payloads. + * + * @deprecated Pass it to {@link cryptoModule} instead. + */ + cipherKey?: string; + /** + * When `true` the initialization vector (IV) is random for all requests (not just for file + * upload). + * When `false` the IV is hard-coded for all requests except for file upload. + * + * @default `true` + * + * @deprecated Pass it to {@link cryptoModule} instead. + */ + useRandomIVs?: boolean; + /** + * Custom data encryption method. + * + * @deprecated Instead use {@link cryptoModule} for data encryption. + */ + customEncrypt?: (data: string | Payload) => string; + /** + * Custom data decryption method. + * + * @deprecated Instead use {@link cryptoModule} for data decryption. + */ + customDecrypt?: (data: string) => string; + }; + + /** + * Base user-provided PubNub client configuration. + */ + export type UserConfiguration = { + /** + * Specifies the `subscribeKey` to be used for subscribing to a channel and message publishing. + */ + subscribeKey: string; + /** + * Specifies the `subscribe_key` to be used for subscribing to a channel and message publishing. + * + * @deprecated Use the {@link subscribeKey} instead. + */ + subscribe_key?: string; + /** + * Specifies the `publishKey` to be used for publishing messages to a channel. + */ + publishKey?: string; + /** + * Specifies the `publish_key` to be used for publishing messages to a channel. + * + * @deprecated Use the {@link publishKey} instead. + */ + publish_key?: string; + /** + * Specifies the `secretKey` to be used for request signatures computation. + */ + secretKey?: string; + /** + * Specifies the `secret_key` to be used for request signatures computation. + * + * @deprecated Use the {@link secretKey} instead. + */ + secret_key?: string; + /** + * Unique PubNub client user identifier. + * + * Unique `userId` to identify the user or the device that connects to PubNub. + * It's a UTF-8 encoded string of up to 64 alphanumeric characters. + * + * If you don't set the `userId`, you won't be able to connect to PubNub. + */ + userId?: string; + /** + * If Access Manager enabled, this key will be used on all requests. + */ + authKey?: string | null; + /** + * Log HTTP information. + * + * @default `false` + */ + logVerbosity?: boolean; + /** + * If set to true, requests will be made over HTTPS. + * + * @default `true` for v4.20.0 onwards, `false` before v4.20.0 + */ + ssl?: boolean; + /** + * If a custom domain is required, SDK accepts it here. + * + * @default `ps.pndsn.com` + */ + origin?: string | string[]; + /** + * How long the server will consider the client alive for presence.The value is in seconds. + * + * @default `300` + */ + presenceTimeout?: number; + /** + * How often the client will announce itself to server.The value is in seconds. + * + * @default `not set` + */ + heartbeatInterval?: number; + /** + * Transactional requests timeout in milliseconds. + * + * Maximum duration for which PubNub client should wait for transactional request completion. + * + * @default `15` seconds + */ + transactionalRequestTimeout?: number; + /** + * Subscription requests timeout in milliseconds. + * + * Maximum duration for which PubNub client should wait for subscription request completion. + * + * @default `310` seconds + */ + subscribeRequestTimeout?: number; + /** + * `true` to allow catch up on the front-end applications. + * + * @default `false` + */ + restore?: boolean; + /** + * Whether to include the PubNub object instance ID in outgoing requests. + * + * @default `false` + */ + useInstanceId?: boolean; + /** + * When `true` the SDK doesn't send out the leave requests. + * + * @default `false` + */ + suppressLeaveEvents?: boolean; + /** + * `PNRequestMessageCountExceededCategory` is thrown when the number of messages into the + * payload is above of `requestMessageCountThreshold`. + * + * @default `100` + */ + requestMessageCountThreshold?: number; + /** + * This flag announces when the network is down or up using the states `PNNetworkDownCategory` + * and `PNNetworkUpCategory`. + * + * @default `false` + */ + autoNetworkDetection?: boolean; + /** + * Whether to use the standardized workflows for subscribe and presence. + * + * Note that the `maintainPresenceState` parameter is set to true by default, so make sure to + * disable it if you don't need to maintain presence state. For more information, refer to the + * param description in this table. + * + * + * @default `false` + */ + enableEventEngine?: boolean; + /** + * Custom reconnection configuration parameters. + * + * `retryConfiguration: policy` is the type of policy to be used. + * + * Available values: + * - `PubNub.LinearRetryPolicy({ delay, maximumRetry })` + * - `PubNub.ExponentialRetryPolicy({ minimumDelay, maximumDelay, maximumRetry })` + * + * For more information, refer to + * {@link /docs/general/setup/connection-management#reconnection-policy|Reconnection Policy}. JavaScript doesn't + * support excluding endpoints. + * + * @default `not set` + */ + retryConfiguration?: RequestRetryPolicy; + /** + * Whether the `state` set using `setState()` should be maintained for the current `userId`. + * This option works only when `enableEventEngine` is set to `true`. + * + * @default `true` + */ + maintainPresenceState?: boolean; + /** + * `UUID` to use. You should set a unique `UUID` to identify the user or the device that + * connects to PubNub. + * If you don't set the `UUID`, you won't be able to connect to PubNub. + * + * @deprecated Use {@link userId} instead. + */ + uuid?: string; + /** + * If set to `true`, SDK will use the same TCP connection for each HTTP request, instead of + * opening a new one for each new request. + * + * @default `false` + */ + keepAlive?: boolean; + /** + * If the SDK is running as part of another SDK built atop of it, allow a custom `pnsdk` with + * name and version. + */ + sdkName?: string; + /** + * If the SDK is operated by a partner, allow a custom `pnsdk` item for them. + */ + partnerId?: string; + }; + + /** + * User-provided configuration object interface. + * + * Interface contains limited set of settings manipulation and access. + */ + export interface ClientConfiguration { + /** + * Get a PubNub client user identifier. + * + * @returns Current PubNub client user identifier. + */ + getUserId(): string; + /** + * Change the current PubNub client user identifier. + * + * **Important:** Change won't affect ongoing REST API calls. + * + * @param value - New PubNub client user identifier. + * + * @throws Error empty user identifier has been provided. + */ + setUserId(value: string): void; + /** + * Change REST API endpoint access authorization key. + * + * @param authKey - New authorization key which should be used with new requests. + */ + setAuthKey(authKey: string | null): void; + /** + * Real-time updates filtering expression. + * + * @returns Filtering expression. + */ + getFilterExpression(): string | undefined | null; + /** + * Update real-time updates filtering expression. + * + * @param expression - New expression which should be used or `undefined` to disable filtering. + */ + setFilterExpression(expression: string | null | undefined): void; + /** + * Change data encryption / decryption key. + * + * @param key - New key which should be used for data encryption / decryption. + */ + setCipherKey(key: string | undefined): void; + /** + * Get PubNub SDK version. + * + * @returns Current SDK version. + */ + get version(): string; + /** + * Get PubNub SDK version. + * + * @returns Current SDK version. + */ + getVersion(): string; + /** + * Add framework's prefix. + * + * @param name - Name of the framework which would want to add own data into `pnsdk` suffix. + * @param suffix - Suffix with information about framework. + */ + _addPnsdkSuffix(name: string, suffix: string | number): void; + /** + * Get a PubNub client user identifier. + * + * @returns Current PubNub client user identifier. + * + * @deprecated Use the {@link getUserId} or {@link userId} getter instead. + */ + getUUID(): string; + /** + * Change the current PubNub client user identifier. + * + * **Important:** Change won't affect ongoing REST API calls. + * + * @param value - New PubNub client user identifier. + * + * @returns {Configuration} Reference to the configuration instance for easier chaining. + * + * @throws Error empty user identifier has been provided. + * + * @deprecated Use the {@link setUserId} or {@link userId} setter instead. + */ + setUUID(value: string): void; + } + + /** + * Failed request retry policy. + */ + export class RetryPolicy { + static LinearRetryPolicy( + configuration: LinearRetryPolicyConfiguration, + ): RequestRetryPolicy & LinearRetryPolicyConfiguration; + static ExponentialRetryPolicy( + configuration: ExponentialRetryPolicyConfiguration, + ): RequestRetryPolicy & ExponentialRetryPolicyConfiguration; + } + + export type RequestRetryPolicy = { + /** + * Check whether failed request can be retried. + * + * @param reason - Request processing failure reason. + * @param attempt - Number of sequential failure. + * + * @returns `true` if another request retry attempt can be done. + */ + shouldRetry( + reason: PubNubError & { + retryAfter?: number; + }, + attempt: number, + ): boolean; + /** + * Computed delay for next request retry attempt. + * + * @param attempt - Number of sequential failure. + * @param reason - Request processing failure reason. + * + * @returns Delay before next request retry attempt in milliseconds. + */ + getDelay( + attempt: number, + reason: PubNubError & { + retryAfter?: number; + }, + ): number; + /** + * Identify reason why another retry attempt can't be made. + * + * @param reason - Request processing failure reason. + * @param attempt - Number of sequential failure. + * + * @returns Give up reason. + */ + getGiveupReason( + reason: PubNubError & { + retryAfter?: number; + }, + attempt: number, + ): string; + /** + * Validate retry policy parameters. + * + * @throws Error if `minimum` delay is smaller than 2 seconds for `exponential` retry policy. + * @throws Error if `maximum` delay is larger than 150 seconds for `exponential` retry policy. + * @throws Error if `maximumRetry` attempts is larger than 6 for `exponential` retry policy. + * @throws Error if `maximumRetry` attempts is larger than 10 for `linear` retry policy. + */ + validate(): void; + }; + + export type LinearRetryPolicyConfiguration = { + delay: number; + maximumRetry: number; + }; + + export type ExponentialRetryPolicyConfiguration = { + minimumDelay: number; + maximumDelay: number; + maximumRetry: number; + }; + + /** + * PubNub operation error. + * + * When an operation can't be performed or there is an error from the server, this object will be returned. + */ + export class PubNubError extends Error { + status?: Status | undefined; + } + + /** + * Represents the configuration options for keeping the transport connection alive. + */ + export type TransportKeepAlive = { + /** + * The time interval in milliseconds for keeping the connection alive. + * + * @default 1000 + */ + keepAliveMsecs?: number; + /** + * The maximum number of sockets allowed per host. + * + * @default Infinity + */ + maxSockets?: number; + /** + * The maximum number of open and free sockets in the pool per host. + * + * @default 256 + */ + maxFreeSockets?: number; + /** + * Timeout in milliseconds, after which the `idle` socket will be closed. + * + * @default 30000 + */ + timeout?: number; + }; + + /** + * This interface is used to send requests to the PubNub API. + * + * You can implement this interface for your types, or use one of the provided modules to use a + * transport library. + * + * @interface + */ + export interface Transport { + /** + * Make request sendable. + * + * @param req - The transport request to be processed. + * + * @returns - A promise that resolves to a transport response and request cancellation + * controller (if required). + */ + makeSendable(req: TransportRequest): [Promise, CancellationController | undefined]; + /** + * Pre-processed request. + * + * Transport implementation may pre-process original transport requests before making + * platform-specific request objects from it. + * + * @param req - Transport request provided by the PubNub client. + * + * @returns Transport request with updated properties (if it was required). + */ + request(req: TransportRequest): TransportRequest; + } + + /** + * Enum representing possible transport methods for HTTP requests. + * + * @enum {number} + */ + export enum TransportMethod { + /** + * Request will be sent using `GET` method. + */ + GET = 'GET', + /** + * Request will be sent using `POST` method. + */ + POST = 'POST', + /** + * Request will be sent using `PATCH` method. + */ + PATCH = 'PATCH', + /** + * Request will be sent using `DELETE` method. + */ + DELETE = 'DELETE', + /** + * Local request. + * + * Request won't be sent to the service and probably used to compute URL. + */ + LOCAL = 'LOCAL', + } + + /** + * Request cancellation controller. + */ + export type CancellationController = { + /** + * Request cancellation / abort function. + */ + abort: () => void; + }; + + /** + * This object represents a request to be sent to the PubNub API. + * + * This struct represents a request to be sent to the PubNub API. It is used by the transport + * provider which implements {@link Transport} interface. + * + * All fields are representing certain parts of the request that can be used to prepare one. + */ + export type TransportRequest = { + /** + * Remote host name. + */ + origin?: string; + /** + * Remote resource path. + */ + path: string; + /** + * Query parameters to be sent with the request. + */ + queryParameters?: Query; + /** + * Transport request HTTP method. + */ + method: TransportMethod; + /** + * Headers to be sent with the request. + */ + headers?: Record; + /** + * Multipart form data fields. + * + * **Important:** `Content-Type` header should be sent the {@link body} data type when + * `multipart/form-data` should request should be sent. + */ + formData?: Record[]; + /** + * Body to be sent with the request. + */ + body?: ArrayBuffer | PubNubFileInterface | string; + /** + * For how long request should wait response from the server. + * + * @default `10` seconds. + */ + timeout: number; + /** + * Whether request can be cancelled or not. + * + * @default `false`. + */ + cancellable: boolean; + /** + * Unique request identifier. + */ + identifier: string; + }; + + /** + * Represents a transport response from a service. + */ + export type TransportResponse = { + /** + * Full remote resource URL used to retrieve response. + */ + url: string; + /** + * Service response status code. + */ + status: number; + /** + * Service response headers. + * + * **Important:** Header names are in lowercase. + */ + headers: Record; + /** + * Service response body. + */ + body?: ArrayBuffer; + }; + + /** + * Real-time events listener. + */ + export type Listener = { + /** + * Real-time message events listener. + * + * @param message - Received message. + */ + message?: (message: Subscription.Message) => void; + /** + * Real-time message signal listener. + * + * @param signal - Received signal. + */ + signal?: (signal: Subscription.Signal) => void; + /** + * Real-time presence change events listener. + * + * @param presence - Received presence chane information. + */ + presence?: (presence: Subscription.Presence) => void; + /** + * Real-time App Context Objects change events listener. + * + * @param object - Changed App Context Object information. + */ + objects?: (object: Subscription.AppContextObject) => void; + /** + * Real-time message actions events listener. + * + * @param action - Message action information. + */ + messageAction?: (action: Subscription.MessageAction) => void; + /** + * Real-time file share events listener. + * + * @param file - Shared file information. + */ + file?: (file: Subscription.File) => void; + /** + * Real-time PubNub client status change event. + * + * @param status - PubNub client status information + */ + status?: (status: Status | StatusEvent) => void; + /** + * Real-time User App Context Objects change events listener. + * + * @param user - User App Context Object information. + * + * @deprecated Use {@link objects} listener callback instead. + */ + user?: (user: Subscription.UserAppContextObject) => void; + /** + * Real-time Space App Context Objects change events listener. + * + * @param space - Space App Context Object information. + * + * @deprecated Use {@link objects} listener callback instead. + */ + space?: (space: Subscription.SpaceAppContextObject) => void; + /** + * Real-time VSP Membership App Context Objects change events listener. + * + * @param membership - VSP Membership App Context Object information. + * + * @deprecated Use {@link objects} listener callback instead. + */ + membership?: (membership: Subscription.VSPMembershipAppContextObject) => void; + }; + + /** + * PubNub-defined event types by payload. + */ + export enum PubNubEventType { + /** + * Presence change event. + */ + Presence = -2, + /** + * Regular message event. + * + * **Note:** This is default type assigned for non-presence events if `e` field is missing. + */ + Message = -1, + /** + * Signal data event. + */ + Signal = 1, + /** + * App Context object event. + */ + AppContext = 2, + /** + * Message reaction event. + */ + MessageAction = 3, + /** + * Files event. + */ + Files = 4, + } + + /** + * Periodical presence change service response. + */ + type PresenceIntervalData = { + /** + * Periodical subscribed channels and groups presence change announcement. + */ + action: 'interval'; + /** + * Unix timestamp when presence event has been triggered. + */ + timestamp: number; + /** + * The current occupancy after the presence change is updated. + */ + occupancy: number; + /** + * The list of unique user identifiers that `joined` the channel since the last interval + * presence update. + */ + join?: string[]; + /** + * The list of unique user identifiers that `left` the channel since the last interval + * presence update. + */ + leave?: string[]; + /** + * The list of unique user identifiers that `timeout` the channel since the last interval + * presence update. + */ + timeout?: string[]; + }; + + /** + * Subscribed user presence information change service response. + */ + type PresenceChangeData = { + /** + * Change if user's presence. + * + * User's presence may change between: `join`, `leave` and `timeout`. + */ + action: 'join' | 'leave' | 'timeout'; + /** + * Unix timestamp when presence event has been triggered. + */ + timestamp: number; + /** + * Unique identification of the user for whom presence information changed. + */ + uuid: string; + /** + * The current occupancy after the presence change is updated. + */ + occupancy: number; + /** + * The user's state associated with the channel has been updated. + * + * @deprecated Use set state methods to specify associated user's data instead of passing to + * subscribe. + */ + data?: { + [p: string]: Payload; + }; + }; + + /** + * Associated user presence state change service response. + */ + type PresenceStateChangeData = { + /** + * Subscribed user associated presence state change. + */ + action: 'state-change'; + /** + * Unix timestamp when presence event has been triggered. + */ + timestamp: number; + /** + * Unique identification of the user for whom associated presence state has been changed. + */ + uuid: string; + /** + * The user's state associated with the channel has been updated. + */ + state: { + [p: string]: Payload; + }; + }; + + /** + * Channel presence service response. + */ + export type PresenceData = PresenceIntervalData | PresenceChangeData | PresenceStateChangeData; + + /** + * Message reaction change service response. + */ + export type MessageActionData = { + /** + * The type of event that happened during the message action update. + * + * Possible values are: + * - `added` - action has been added to the message + * - `removed` - action has been removed from message + */ + event: 'added' | 'removed'; + /** + * Information about message action for which update has been generated. + */ + data: { + /** + * Timetoken of message for which action has been added / removed. + */ + messageTimetoken: string; + /** + * Timetoken of message action which has been added / removed. + */ + actionTimetoken: string; + /** + * Message action type. + */ + type: string; + /** + * Value associated with message action {@link type}. + */ + value: string; + }; + /** + * Name of service which generated update for message action. + */ + source: string; + /** + * Version of service which generated update for message action. + */ + version: string; + }; + + /** + * VSP Objects change events. + */ + type AppContextVSPEvents = 'updated' | 'removed'; + + /** + * App Context Objects change events. + */ + type AppContextEvents = 'set' | 'delete'; + + /** + * Common real-time App Context Object service response. + */ + type ObjectData = { + /** + * The type of event that happened during the object update. + */ + event: Event; + /** + * App Context object type. + */ + type: Type; + /** + * App Context object information. + * + * App Context object can be one of: + * - `channel` / `space` + * - `uuid` / `user` + * - `membership` + */ + data: AppContextObject; + /** + * Name of service which generated update for object. + */ + source: string; + /** + * Version of service which generated update for object. + */ + version: string; + }; + + /** + * `Channel` object change real-time service response. + */ + type ChannelObjectData = ObjectData< + AppContextEvents, + 'channel', + AppContext.ChannelMetadataObject + >; + + /** + * `Space` object change real-time service response. + */ + export type SpaceObjectData = ObjectData< + AppContextVSPEvents, + 'space', + AppContext.ChannelMetadataObject + >; + + /** + * `Uuid` object change real-time service response. + */ + type UuidObjectData = ObjectData>; + + /** + * `User` object change real-time service response. + */ + export type UserObjectData = ObjectData< + AppContextVSPEvents, + 'user', + AppContext.UUIDMetadataObject + >; + + /** + * `Membership` object change real-time service response. + */ + type MembershipObjectData = ObjectData< + AppContextEvents, + 'membership', + Omit, 'id'> & { + /** + * `Uuid` object which has been used to create relationship with `channel`. + */ + uuid: { + /** + * Unique `user` object identifier. + */ + id: string; + }; + /** + * `Channel` object which has been used to create relationship with `uuid`. + */ + channel: { + /** + * Unique `channel` object identifier. + */ + id: string; + }; + } + >; + + /** + * VSP `Membership` object change real-time service response. + */ + export type VSPMembershipObjectData = ObjectData< + AppContextVSPEvents, + 'membership', + Omit, 'id'> & { + /** + * `User` object which has been used to create relationship with `space`. + */ + user: { + /** + * Unique `user` object identifier. + */ + id: string; + }; + /** + * `Space` object which has been used to create relationship with `user`. + */ + space: { + /** + * Unique `channel` object identifier. + */ + id: string; + }; + } + >; + + /** + * App Context service response. + */ + export type AppContextObjectData = ChannelObjectData | UuidObjectData | MembershipObjectData; + + /** + * File service response. + */ + export type FileData = { + /** + * Message which has been associated with uploaded file. + */ + message?: Payload; + /** + * Information about uploaded file. + */ + file: { + /** + * Unique identifier of uploaded file. + */ + id: string; + /** + * Actual name with which file has been stored. + */ + name: string; + }; + }; + + /** + * Payload for `pn_apns` field in published message. + */ + type APNSPayload = { + /** + * Payload for Apple Push Notification Service. + */ + aps: { + /** + * Configuration of visual notification representation. + */ + alert?: { + /** + * First line title. + * + * Title which is shown in bold on the first line of notification bubble. + */ + title?: string; + /** + * Second line title. + * + * Subtitle which is shown under main title with smaller font. + */ + subtitle?: string; + /** + * Notification body. + * + * Body which is shown to the user after interaction with notification. + */ + body?: string; + }; + /** + * Unread notifications count badge value. + */ + badge?: number | null; + /** + * Name of the file from resource bundle which should be played when notification received. + */ + sound?: string; + /** + * Silent notification flag. + */ + 'content-available'?: 1; + }; + /** + * APNS2 payload recipients information. + */ + pn_push: PubNubAPNS2Configuration[]; + }; + + /** + * APNS2 configuration type. + */ + type APNS2Configuration = { + /** + * Notification group / collapse identifier. Value will be used in APNS POST request as `apns-collapse-id` header + * value. + */ + collapseId?: string; + /** + * Date till which APNS will try to deliver notification to target device. Value will be used in APNS POST request as + * `apns-expiration` header value. + */ + expirationDate?: Date; + /** + * List of topics which should receive this notification. + */ + targets: APNS2Target[]; + }; + + /** + * Preformatted for PubNub service `APNS2` configuration type. + */ + type PubNubAPNS2Configuration = { + /** + * PubNub service authentication method for APNS. + */ + auth_method: 'token'; + /** + * Target entities which should receive notification. + */ + targets: PubNubAPNS2Target[]; + /** + * Notifications group collapse identifier. + */ + collapse_id?: string; + /** + * Notification receive expiration date. + * + * Date after which notification won't be delivered. + */ + expiration?: string; + /** + * APNS protocol version. + */ + version: 'v2'; + }; + + /** + * APNS2 configuration target type. + */ + type APNS2Target = { + /** + * Notifications topic name (usually it is bundle identifier of application for Apple platform). + * + * **Important:** Required only if `pushGateway` is set to `apns2`. + */ + topic: string; + /** + * Environment within which registered devices to which notifications should be delivered. + * + * Available: + * - `development` + * - `production` + * + * @default `development` + */ + environment?: 'development' | 'production'; + /** + * List of devices (their push tokens) to which this notification shouldn't be delivered. + */ + excludedDevices?: string[]; + }; + + /** + * Preformatted for PubNub service `APNS2` configuration target type. + */ + type PubNubAPNS2Target = Omit & { + /** + * List of devices (their push tokens) to which this notification shouldn't be delivered. + */ + excluded_devices?: string[]; + }; + + /** + * Payload for `pn_gcm` field in published message. + */ + type FCMPayload = { + /** + * Configuration of visual notification representation. + */ + notification?: { + /** + * First line title. + * + * Title which is shown in bold on the first line of notification bubble. + */ + title?: string; + /** + * Notification body. + * + * Body which is shown to the user after interaction with notification. + */ + body?: string; + /** + * Name of the icon file from resource bundle which should be shown on notification. + */ + icon?: string; + /** + * Name of the file from resource bundle which should be played when notification received. + */ + sound?: string; + tag?: string; + }; + /** + * Configuration of data notification. + * + * Silent notification configuration. + */ + data?: { + notification?: FCMPayload['notification']; + }; + }; + + /** + * Base notification payload object. + */ + class BaseNotificationPayload { + /** + * Retrieve resulting notification payload content for message. + * + * @returns Preformatted push notification payload data. + */ + get payload(): unknown; + /** + * Update notification title. + * + * @param value - New notification title. + */ + set title(value: string | undefined); + /** + * Update notification subtitle. + * + * @param value - New second-line notification title. + */ + set subtitle(value: string | undefined); + /** + * Update notification body. + * + * @param value - Update main notification message (shown when expanded). + */ + set body(value: string | undefined); + /** + * Update application badge number. + * + * @param value - Number which should be shown in application badge upon receiving notification. + */ + set badge(value: number | null | undefined); + /** + * Update notification sound. + * + * @param value - Name of the sound file which should be played upon notification receive. + */ + set sound(value: string | undefined); + } + + /** + * Message payload for Apple Push Notification Service. + */ + export class APNSNotificationPayload extends BaseNotificationPayload { + get payload(): APNSPayload; + /** + * Update notification receivers configuration. + * + * @param value - New APNS2 configurations. + */ + set configurations(value: APNS2Configuration[]); + /** + * Notification payload. + * + * @returns Platform-specific part of PubNub notification payload. + */ + get notification(): { + /** + * Configuration of visual notification representation. + */ + alert?: + | { + /** + * First line title. + * + * Title which is shown in bold on the first line of notification bubble. + */ + title?: string | undefined; + /** + * Second line title. + * + * Subtitle which is shown under main title with smaller font. + */ + subtitle?: string | undefined; + /** + * Notification body. + * + * Body which is shown to the user after interaction with notification. + */ + body?: string | undefined; + } + | undefined; + /** + * Unread notifications count badge value. + */ + badge?: number | null | undefined; + /** + * Name of the file from resource bundle which should be played when notification received. + */ + sound?: string | undefined; + /** + * Silent notification flag. + */ + 'content-available'?: 1 | undefined; + }; + /** + * Notification title. + * + * @returns Main notification title. + */ + get title(): string | undefined; + /** + * Update notification title. + * + * @param value - New notification title. + */ + set title(value: string | undefined); + /** + * Notification subtitle. + * + * @returns Second-line notification title. + */ + get subtitle(): string | undefined; + /** + * Update notification subtitle. + * + * @param value - New second-line notification title. + */ + set subtitle(value: string | undefined); + /** + * Notification body. + * + * @returns Main notification message (shown when expanded). + */ + get body(): string | undefined; + /** + * Update notification body. + * + * @param value - Update main notification message (shown when expanded). + */ + set body(value: string | undefined); + /** + * Retrieve unread notifications number. + * + * @returns Number of unread notifications which should be shown on application badge. + */ + get badge(): number | null | undefined; + /** + * Update application badge number. + * + * @param value - Number which should be shown in application badge upon receiving notification. + */ + set badge(value: number | null | undefined); + /** + * Retrieve notification sound file. + * + * @returns Notification sound file name from resource bundle. + */ + get sound(): string | undefined; + /** + * Update notification sound. + * + * @param value - Name of the sound file which should be played upon notification receive. + */ + set sound(value: string | undefined); + /** + * Set whether notification should be silent or not. + * + * `content-available` notification type will be used to deliver silent notification if set to `true`. + * + * @param value - Whether notification should be sent as silent or not. + */ + set silent(value: boolean); + } + + /** + * Message payload for Firebase Cloud Messaging service. + */ + export class FCMNotificationPayload extends BaseNotificationPayload { + get payload(): FCMPayload; + /** + * Notification payload. + * + * @returns Platform-specific part of PubNub notification payload. + */ + get notification(): + | { + /** + * First line title. + * + * Title which is shown in bold on the first line of notification bubble. + */ + title?: string | undefined; + /** + * Notification body. + * + * Body which is shown to the user after interaction with notification. + */ + body?: string | undefined; + /** + * Name of the icon file from resource bundle which should be shown on notification. + */ + icon?: string | undefined; + /** + * Name of the file from resource bundle which should be played when notification received. + */ + sound?: string | undefined; + tag?: string | undefined; + } + | undefined; + /** + * Silent notification payload. + * + * @returns Silent notification payload (data notification). + */ + get data(): + | { + notification?: + | { + /** + * First line title. + * + * Title which is shown in bold on the first line of notification bubble. + */ + title?: string | undefined; + /** + * Notification body. + * + * Body which is shown to the user after interaction with notification. + */ + body?: string | undefined; + /** + * Name of the icon file from resource bundle which should be shown on notification. + */ + icon?: string | undefined; + /** + * Name of the file from resource bundle which should be played when notification received. + */ + sound?: string | undefined; + tag?: string | undefined; + } + | undefined; + } + | undefined; + /** + * Notification title. + * + * @returns Main notification title. + */ + get title(): string | undefined; + /** + * Update notification title. + * + * @param value - New notification title. + */ + set title(value: string | undefined); + /** + * Notification body. + * + * @returns Main notification message (shown when expanded). + */ + get body(): string | undefined; + /** + * Update notification body. + * + * @param value - Update main notification message (shown when expanded). + */ + set body(value: string | undefined); + /** + * Retrieve notification sound file. + * + * @returns Notification sound file name from resource bundle. + */ + get sound(): string | undefined; + /** + * Update notification sound. + * + * @param value - Name of the sound file which should be played upon notification receive. + */ + set sound(value: string | undefined); + /** + * Retrieve notification icon file. + * + * @returns Notification icon file name from resource bundle. + */ + get icon(): string | undefined; + /** + * Update notification icon. + * + * @param value - Name of the icon file which should be shown on notification. + */ + set icon(value: string | undefined); + /** + * Retrieve notifications grouping tag. + * + * @returns Notifications grouping tag. + */ + get tag(): string | undefined; + /** + * Update notifications grouping tag. + * + * @param value - String which will be used to group similar notifications in notification center. + */ + set tag(value: string | undefined); + /** + * Set whether notification should be silent or not. + * + * All notification data will be sent under `data` field if set to `true`. + * + * @param value - Whether notification should be sent as silent or not. + */ + set silent(value: boolean); + } + + export class NotificationsPayload { + /** + * APNS-specific message payload. + */ + apns: APNSNotificationPayload; + /** + * FCM-specific message payload. + */ + fcm: FCMNotificationPayload; + /** + * Enable or disable push notification debugging message. + * + * @param value - Whether debug message from push notification scheduler should be published to the specific + * channel or not. + */ + set debugging(value: boolean); + /** + * Notification title. + * + * @returns Main notification title. + */ + get title(): string; + /** + * Notification subtitle. + * + * @returns Second-line notification title. + */ + get subtitle(): string | undefined; + /** + * Update notification subtitle. + * + * @param value - New second-line notification title. + */ + set subtitle(value: string | undefined); + /** + * Notification body. + * + * @returns Main notification message (shown when expanded). + */ + get body(): string; + /** + * Retrieve unread notifications number. + * + * @returns Number of unread notifications which should be shown on application badge. + */ + get badge(): number | undefined; + /** + * Update application badge number. + * + * @param value - Number which should be shown in application badge upon receiving notification. + */ + set badge(value: number | undefined); + /** + * Retrieve notification sound file. + * + * @returns Notification sound file name from resource bundle. + */ + get sound(): string | undefined; + /** + * Update notification sound. + * + * @param value - Name of the sound file which should be played upon notification receive. + */ + set sound(value: string | undefined); + /** + * Build notifications platform for requested platforms. + * + * @param platforms - List of platforms for which payload should be added to final dictionary. Supported values: + * fcm, apns, and apns2. + * + * @returns Object with data, which can be sent with publish method call and trigger remote notifications for + * specified platforms. + */ + buildPayload(platforms: ('apns' | 'apns2' | 'fcm')[]): { + pn_apns?: APNSPayload | undefined; + pn_gcm?: FCMPayload | undefined; + pn_debug?: boolean | undefined; + }; + } + + /** + * PubNub entity subscription configuration options. + */ + export type SubscriptionOptions = { + /** + * Whether presence events for entity should be received or not. + */ + receivePresenceEvents?: boolean; + }; + + /** + * First-class objects which provides access to the channel app context object-specific APIs. + */ + export class ChannelMetadata { + /** + * Create channel's app context subscription object for real-time updates. + * + * Create subscription object which can be used to subscribe to the real-time updates sent to the specific channel + * app context object. + * + * @param [subscriptionOptions] - Channel's app context subscription object behavior customization options. + * + * @returns Configured and ready to use channel's app context subscription object. + */ + subscription(subscriptionOptions?: SubscriptionOptions): Subscription; + } + + /** + * Single-entity subscription object which can be used to receive and handle real-time updates. + */ + export class Subscription extends SubscribeCapable { + /** + * Merge entities' subscription objects into subscription set. + * + * @param subscription - Other entity's subscription object to be merged with receiver. + * @return Subscription set which contains both receiver and other entities' subscription objects. + */ + addSubscription(subscription: Subscription): SubscriptionSet; + } + + export abstract class SubscribeCapable { + /** + * Start receiving real-time updates. + * + * @param subscribeParameters - Additional subscription configuration options which should be used + * for request. + */ + subscribe(subscribeParameters?: { timetoken?: string }): void; + /** + * Stop real-time events processing. + */ + unsubscribe(): void; + /** + * Set new message handler. + * + * @param onMessageListener - Listener function, which will be called each time when a new message + * is received from the real-time network. + */ + set onMessage(onMessageListener: (messageEvent: Subscription.Message) => void); + /** + * Set new presence events handler. + * + * @param onPresenceListener - Listener function, which will be called each time when a new + * presence event is received from the real-time network. + */ + set onPresence(onPresenceListener: (presenceEvent: Subscription.Presence) => void); + /** + * Set new signal handler. + * + * @param onSignalListener - Listener function, which will be called each time when a new signal + * is received from the real-time network. + */ + set onSignal(onSignalListener: (signalEvent: Subscription.Signal) => void); + /** + * Set new app context event handler. + * + * @param onObjectsListener - Listener function, which will be called each time when a new + * app context event is received from the real-time network. + */ + set onObjects(onObjectsListener: (objectsEvent: Subscription.AppContextObject) => void); + /** + * Set new message reaction event handler. + * + * @param messageActionEventListener - Listener function, which will be called each time when a + * new message reaction event is received from the real-time network. + */ + set onMessageAction(messageActionEventListener: (messageActionEvent: Subscription.MessageAction) => void); + /** + * Set new file handler. + * + * @param fileEventListener - Listener function, which will be called each time when a new file + * is received from the real-time network. + */ + set onFile(fileEventListener: (fileEvent: Subscription.File) => void); + /** + * Set events handler. + * + * @param listener - Events listener configuration object, which lets specify handlers for multiple + * types of events. + */ + addListener(listener: Listener): void; + /** + * Remove events handler. + * + * @param listener - Event listener configuration, which should be removed from the list of notified + * listeners. **Important:** Should be the same object which has been passed to the + * {@link addListener}. + */ + removeListener(listener: Listener): void; + /** + * Get list of channels which is used for subscription. + * + * @returns List of channel names. + */ + get channels(): string[]; + /** + * Get list of channel groups which is used for subscription. + * + * @returns List of channel group names. + */ + get channelGroups(): string[]; + } + + /** + * Multiple entities subscription set object which can be used to receive and handle real-time + * updates. + * + * Subscription set object represent collection of per-entity subscription objects and allow + * processing them at once for subscription loop and events handling. + */ + export class SubscriptionSet extends SubscribeCapable { + /** + * Add additional entity's subscription to the subscription set. + * + * **Important:** Changes will be effective only after {@link SubscribeCapable#subscribe} call or + * next subscription loop. + * + * @param subscription - Other entity's subscription object, which should be added. + */ + addSubscription(subscription: Subscription): void; + /** + * Remove entity's subscription object from the set. + * + * **Important:** Changes will be effective only after {@link SubscribeCapable#unsubscribe} call or + * next subscription loop. + * + * @param subscription - Other entity's subscription object, which should be removed. + */ + removeSubscription(subscription: Subscription): void; + /** + * Merge with other subscription set object. + * + * **Important:** Changes will be effective only after {@link SubscribeCapable#subscribe} call or + * next subscription loop. + * + * @param subscriptionSet - Other entities' subscription set, which should be joined. + */ + addSubscriptionSet(subscriptionSet: SubscriptionSet): void; + /** + * Subtract other subscription set object. + * + * **Important:** Changes will be effective only after {@link SubscribeCapable#unsubscribe} call or + * next subscription loop. + * + * @param subscriptionSet - Other entities' subscription set, which should be subtracted. + */ + removeSubscriptionSet(subscriptionSet: SubscriptionSet): void; + /** + * Get list of entities' subscription objects registered in subscription set. + * + * @returns Entities' subscription objects list. + */ + get subscriptions(): Subscription[]; + } + + /** + * First-class objects which provides access to the channel group-specific APIs. + */ + export class ChannelGroup { + /** + * Create channel group's subscription object for real-time updates. + * + * Create subscription object which can be used to subscribe to the real-time updates sent to the channels in + * specific channel group. + * + * @param [subscriptionOptions] - Channel group's subscription object behavior customization options. + * + * @returns Configured and ready to use channel group's subscription object. + */ + subscription(subscriptionOptions?: SubscriptionOptions): Subscription; + } + + /** + * First-class objects which provides access to the user app context object-specific APIs. + */ + export class UserMetadata { + /** + * Create user's app context subscription object for real-time updates. + * + * Create subscription object which can be used to subscribe to the real-time updates sent to the specific user + * app context object. + * + * @param [subscriptionOptions] - User's app context subscription object behavior customization options. + * + * @returns Configured and ready to use user's app context subscription object. + */ + subscription(subscriptionOptions?: SubscriptionOptions): Subscription; + } + + /** + * First-class objects which provides access to the channel-specific APIs. + */ + export class Channel { + /** + * Create channel's subscription object for real-time updates. + * + * Create subscription object which can be used to subscribe to the real-time updates sent to the specific channel. + * + * @param [subscriptionOptions] - Channel's subscription object behavior customization options. + * + * @returns Configured and ready to use channel's subscription object. + */ + subscription(subscriptionOptions?: SubscriptionOptions): Subscription; + } + + /** + * PubNub Stream / Channel group API interface. + */ + export class PubNubChannelGroups { + /** + * Fetch channel group channels. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + listChannels( + parameters: ChannelGroups.ListChannelGroupChannelsParameters, + callback: ResultCallback, + ): void; + /** + * Fetch channel group channels. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous get channel group channels response. + */ + listChannels( + parameters: ChannelGroups.ListChannelGroupChannelsParameters, + ): Promise; + /** + * Fetch all channel groups. + * + * @param callback - Request completion handler callback. + * + * @deprecated + */ + listGroups(callback: ResultCallback): void; + /** + * Fetch all channel groups. + * + * @returns Asynchronous get all channel groups response. + * + * @deprecated + */ + listGroups(): Promise; + /** + * Add channels to the channel group. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + addChannels(parameters: ChannelGroups.ManageChannelGroupChannelsParameters, callback: StatusCallback): void; + /** + * Add channels to the channel group. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous add channels to the channel group response. + */ + addChannels(parameters: ChannelGroups.ManageChannelGroupChannelsParameters): Promise>; + /** + * Remove channels from the channel group. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + removeChannels(parameters: ChannelGroups.ManageChannelGroupChannelsParameters, callback: StatusCallback): void; + /** + * Remove channels from the channel group. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous remove channels from the channel group response. + */ + removeChannels(parameters: ChannelGroups.ManageChannelGroupChannelsParameters): Promise>; + /** + * Remove channel group. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + deleteGroup(parameters: ChannelGroups.DeleteChannelGroupParameters, callback: StatusCallback): void; + /** + * Remove channel group. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous remove channel group response. + */ + deleteGroup(parameters: ChannelGroups.DeleteChannelGroupParameters): Promise>; + } + + /** + * PubNub Push Notifications API interface. + */ + export class PubNubPushNotifications { + /** + * Fetch device's push notification enabled channels. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + listChannels( + parameters: Push.ListDeviceChannelsParameters, + callback: ResultCallback, + ): void; + /** + * Fetch device's push notification enabled channels. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous get device channels response. + */ + listChannels(parameters: Push.ListDeviceChannelsParameters): Promise; + /** + * Enable push notifications on channels for device. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + addChannels(parameters: Push.ManageDeviceChannelsParameters, callback: StatusCallback): void; + /** + * Enable push notifications on channels for device. + * + * @param parameters - Request configuration parameters. + */ + addChannels(parameters: Push.ManageDeviceChannelsParameters): Promise; + /** + * Disable push notifications on channels for device. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + removeChannels(parameters: Push.ManageDeviceChannelsParameters, callback: StatusCallback): void; + /** + * Disable push notifications on channels for device. + * + * @param parameters - Request configuration parameters. + */ + removeChannels(parameters: Push.ManageDeviceChannelsParameters): Promise; + /** + * Disable push notifications for device. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + deleteDevice(parameters: Push.RemoveDeviceParameters, callback: StatusCallback): void; + /** + * Disable push notifications for device. + * + * @param parameters - Request configuration parameters. + */ + deleteDevice(parameters: Push.RemoveDeviceParameters): Promise; + } + + /** + * PubNub App Context API interface. + */ + export class PubNubObjects { + /** + * Fetch a paginated list of UUID Metadata objects. + * + * @param callback - Request completion handler callback. + */ + getAllUUIDMetadata( + callback: ResultCallback>, + ): void; + /** + * Fetch a paginated list of UUID Metadata objects. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + getAllUUIDMetadata( + parameters: AppContext.GetAllMetadataParameters>, + callback: ResultCallback>, + ): void; + /** + * Fetch a paginated list of UUID Metadata objects. + * + * @param [parameters] - Request configuration parameters. + * + * @returns Asynchronous get all UUID metadata response. + */ + getAllUUIDMetadata( + parameters?: AppContext.GetAllMetadataParameters>, + ): Promise>; + /** + * Fetch UUID Metadata object for currently configured PubNub client `uuid`. + * + * @param callback - Request completion handler callback. + */ + getUUIDMetadata( + callback: ResultCallback>, + ): void; + /** + * Fetch a specific UUID Metadata object. + * + * @param parameters - Request configuration parameters. Will fetch UUID metadata object for + * currently configured PubNub client `uuid` if not set. + * @param callback - Request completion handler callback. + */ + getUUIDMetadata( + parameters: AppContext.GetUUIDMetadataParameters, + callback: ResultCallback>, + ): void; + /** + * Fetch a specific UUID Metadata object. + * + * @param [parameters] - Request configuration parameters. Will fetch UUID Metadata object for + * currently configured PubNub client `uuid` if not set. + * + * @returns Asynchronous get UUID metadata response. + */ + getUUIDMetadata( + parameters?: AppContext.GetUUIDMetadataParameters, + ): Promise>; + /** + * Update specific UUID Metadata object. + * + * @param parameters - Request configuration parameters. Will set UUID metadata for currently + * configured PubNub client `uuid` if not set. + * @param callback - Request completion handler callback. + */ + setUUIDMetadata( + parameters: AppContext.SetUUIDMetadataParameters, + callback: ResultCallback>, + ): void; + /** + * Update specific UUID Metadata object. + * + * @param parameters - Request configuration parameters. Will set UUID metadata for currently + * configured PubNub client `uuid` if not set. + * + * @returns Asynchronous set UUID metadata response. + */ + setUUIDMetadata( + parameters: AppContext.SetUUIDMetadataParameters, + ): Promise>; + /** + * Remove UUID Metadata object for currently configured PubNub client `uuid`. + * + * @param callback - Request completion handler callback. + */ + removeUUIDMetadata(callback: ResultCallback): void; + /** + * Remove a specific UUID Metadata object. + * + * @param parameters - Request configuration parameters. Will remove UUID metadata for currently + * configured PubNub client `uuid` if not set. + * @param callback - Request completion handler callback. + */ + removeUUIDMetadata( + parameters: AppContext.RemoveUUIDMetadataParameters, + callback: ResultCallback, + ): void; + /** + * Remove a specific UUID Metadata object. + * + * @param [parameters] - Request configuration parameters. Will remove UUID metadata for currently + * configured PubNub client `uuid` if not set. + * + * @returns Asynchronous UUID metadata remove response. + */ + removeUUIDMetadata( + parameters?: AppContext.RemoveUUIDMetadataParameters, + ): Promise; + /** + * Fetch a paginated list of Channel Metadata objects. + * + * @param callback - Request completion handler callback. + */ + getAllChannelMetadata( + callback: ResultCallback>, + ): void; + /** + * Fetch a paginated list of Channel Metadata objects. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + getAllChannelMetadata( + parameters: AppContext.GetAllMetadataParameters>, + callback: ResultCallback>, + ): void; + /** + * Fetch a paginated list of Channel Metadata objects. + * + * @param [parameters] - Request configuration parameters. + * + * @returns Asynchronous get all Channel metadata response. + */ + getAllChannelMetadata( + parameters?: AppContext.GetAllMetadataParameters>, + ): Promise>; + /** + * Fetch Channel Metadata object. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + getChannelMetadata( + parameters: AppContext.GetChannelMetadataParameters, + callback: ResultCallback>, + ): void; + /** + * Fetch a specific Channel Metadata object. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous get Channel metadata response. + */ + getChannelMetadata( + parameters: AppContext.GetChannelMetadataParameters, + ): Promise>; + /** + * Update specific Channel Metadata object. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + setChannelMetadata( + parameters: AppContext.SetChannelMetadataParameters, + callback: ResultCallback>, + ): void; + /** + * Update specific Channel Metadata object. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous set Channel metadata response. + */ + setChannelMetadata( + parameters: AppContext.SetChannelMetadataParameters, + ): Promise>; + /** + * Remove Channel Metadata object. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + removeChannelMetadata( + parameters: AppContext.RemoveChannelMetadataParameters, + callback: ResultCallback, + ): void; + /** + * Remove a specific Channel Metadata object. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous Channel metadata remove response. + */ + removeChannelMetadata( + parameters: AppContext.RemoveChannelMetadataParameters, + ): Promise; + /** + * Fetch a paginated list of Channel Member objects. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + getChannelMembers< + MemberCustom extends AppContext.CustomData = AppContext.CustomData, + UUIDCustom extends AppContext.CustomData = AppContext.CustomData, + >( + parameters: AppContext.GetMembersParameters, + callback: ResultCallback>, + ): void; + /** + * Fetch a paginated list of Channel Member objects. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous get Channel Members response. + */ + getChannelMembers< + MemberCustom extends AppContext.CustomData = AppContext.CustomData, + UUIDCustom extends AppContext.CustomData = AppContext.CustomData, + >(parameters: AppContext.GetMembersParameters): Promise>; + /** + * Update specific Channel Members list. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + setChannelMembers< + MemberCustom extends AppContext.CustomData = AppContext.CustomData, + UUIDCustom extends AppContext.CustomData = AppContext.CustomData, + >( + parameters: AppContext.SetChannelMembersParameters, + callback: ResultCallback>, + ): void; + /** + * Update specific Channel Members list. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous update Channel Members list response. + */ + setChannelMembers< + MemberCustom extends AppContext.CustomData = AppContext.CustomData, + UUIDCustom extends AppContext.CustomData = AppContext.CustomData, + >( + parameters: AppContext.SetChannelMembersParameters, + ): Promise>; + /** + * Remove Members from the Channel. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + removeChannelMembers< + MemberCustom extends AppContext.CustomData = AppContext.CustomData, + UUIDCustom extends AppContext.CustomData = AppContext.CustomData, + >( + parameters: AppContext.RemoveMembersParameters, + callback: ResultCallback>, + ): void; + /** + * Remove Members from the Channel. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous Channel Members remove response. + */ + removeChannelMembers< + MemberCustom extends AppContext.CustomData = AppContext.CustomData, + UUIDCustom extends AppContext.CustomData = AppContext.CustomData, + >( + parameters: AppContext.RemoveMembersParameters, + ): Promise>; + /** + * Fetch a specific UUID Memberships list for currently configured PubNub client `uuid`. + * + * @param callback - Request completion handler callback. + * + * @returns Asynchronous get UUID Memberships list response or `void` in case if `callback` + * provided. + */ + getMemberships< + MembershipCustom extends AppContext.CustomData = AppContext.CustomData, + ChannelCustom extends AppContext.CustomData = AppContext.CustomData, + >(callback: ResultCallback>): void; + /** + * Fetch a specific UUID Memberships list. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + getMemberships< + MembershipCustom extends AppContext.CustomData = AppContext.CustomData, + ChannelCustom extends AppContext.CustomData = AppContext.CustomData, + >( + parameters: AppContext.GetMembershipsParameters, + callback: ResultCallback>, + ): void; + /** + * Fetch a specific UUID Memberships list. + * + * @param [parameters] - Request configuration parameters. Will fetch UUID Memberships list for + * currently configured PubNub client `uuid` if not set. + * + * @returns Asynchronous get UUID Memberships list response. + */ + getMemberships< + MembershipCustom extends AppContext.CustomData = AppContext.CustomData, + ChannelCustom extends AppContext.CustomData = AppContext.CustomData, + >( + parameters?: AppContext.GetMembershipsParameters, + ): Promise>; + /** + * Update specific UUID Memberships list. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + setMemberships< + MembershipCustom extends AppContext.CustomData = AppContext.CustomData, + ChannelCustom extends AppContext.CustomData = AppContext.CustomData, + >( + parameters: AppContext.SetMembershipsParameters, + callback: ResultCallback>, + ): void; + /** + * Update specific UUID Memberships list. + * + * @param parameters - Request configuration parameters or callback from overload. + * + * @returns Asynchronous update UUID Memberships list response. + */ + setMemberships< + MembershipCustom extends AppContext.CustomData = AppContext.CustomData, + ChannelCustom extends AppContext.CustomData = AppContext.CustomData, + >( + parameters: AppContext.SetMembershipsParameters, + ): Promise>; + /** + * Remove a specific UUID Memberships. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ + removeMemberships< + MembershipCustom extends AppContext.CustomData = AppContext.CustomData, + ChannelCustom extends AppContext.CustomData = AppContext.CustomData, + >( + parameters: AppContext.RemoveMembershipsParameters, + callback: ResultCallback>, + ): void; + /** + * Remove a specific UUID Memberships. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous UUID Memberships remove response. + */ + removeMemberships< + MembershipCustom extends AppContext.CustomData = AppContext.CustomData, + ChannelCustom extends AppContext.CustomData = AppContext.CustomData, + >( + parameters: AppContext.RemoveMembershipsParameters, + ): Promise>; + /** + * Fetch paginated list of specific Space members or specific User memberships. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get specific Space members or specific User memberships response. + * + * @deprecated Use {@link PubNubObjects#getChannelMembers} or {@link PubNubObjects#getMemberships} methods instead. + */ + fetchMemberships< + RelationCustom extends AppContext.CustomData = AppContext.CustomData, + MetadataCustom extends AppContext.CustomData = AppContext.CustomData, + >( + parameters: AppContext.GetMembershipsParameters | AppContext.GetMembersParameters, + callback?: ResultCallback< + | AppContext.SpaceMembershipsResponse + | AppContext.UserMembersResponse + >, + ): Promise< + | AppContext.SpaceMembershipsResponse + | AppContext.UserMembersResponse + | void + >; + /** + * Add members to specific Space or memberships specific User. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous add members to specific Space or memberships specific User response or + * `void` in case if `callback` provided. + * + * @deprecated Use {@link PubNubObjects#setChannelMembers} or {@link PubNubObjects#setMemberships} methods instead. + */ + addMemberships< + Custom extends AppContext.CustomData = AppContext.CustomData, + MetadataCustom extends AppContext.CustomData = AppContext.CustomData, + >( + parameters: AppContext.SetMembershipsParameters | AppContext.SetChannelMembersParameters, + callback?: ResultCallback< + | AppContext.SetMembershipsResponse + | AppContext.SetMembersResponse + >, + ): Promise< + | AppContext.SetMembershipsResponse + | AppContext.SetMembersResponse + | void + >; + } + + export namespace Subscription { + /** + * Time cursor. + * + * Cursor used by subscription loop to identify point in time after which updates will be + * delivered. + */ + export type SubscriptionCursor = { + /** + * PubNub high-precision timestamp. + * + * Aside of specifying exact time of receiving data / event this token used to catchup / + * follow on real-time updates. + */ + timetoken: string | number; + /** + * Data center region for which `timetoken` has been generated. + */ + region?: number; + }; + + /** + * Common real-time event. + */ + type Event = { + /** + * Channel to which real-time event has been sent. + */ + channel: string; + /** + * Actual subscription at which real-time event has been received. + * + * PubNub client provide various ways to subscribe to the real-time stream: channel groups, + * wildcard subscription, and spaces. + * + * **Note:** Value will be `null` if it is the same as {@link channel}. + */ + subscription: string | null; + /** + * High-precision PubNub timetoken with time when event has been received by PubNub services. + */ + timetoken: string; + }; + + /** + * Common legacy real-time event for backward compatibility. + */ + type LegacyEvent = Event & { + /** + * Channel to which real-time event has been sent. + * + * @deprecated Use {@link channel} field instead. + */ + actualChannel?: string | null; + /** + * Actual subscription at which real-time event has been received. + * + * @deprecated Use {@link subscription} field instead. + */ + subscribedChannel?: string; + }; + + /** + * Presence change real-time event. + */ + export type Presence = LegacyEvent & PresenceData; + + /** + * Extended presence real-time event. + * + * Type extended for listener manager support. + */ + type PresenceEvent = { + type: PubNubEventType.Presence; + data: Presence; + }; + + /** + * Common published data information. + */ + type PublishedData = { + /** + * Unique identifier of the user which sent data. + */ + publisher?: string; + /** + * Additional user-provided metadata which can be used with real-time filtering expression. + */ + userMetadata?: { + [p: string]: Payload; + }; + /** + * Sent data. + */ + message: Payload; + }; + + /** + * Real-time message event. + */ + export type Message = LegacyEvent & + PublishedData & { + /** + * Decryption error message in case of failure. + */ + error?: string; + }; + + /** + * Extended real-time message event. + * + * Type extended for listener manager support. + */ + type MessageEvent = { + type: PubNubEventType.Message; + data: Message; + }; + + /** + * Real-time signal event. + */ + export type Signal = Event & PublishedData; + + /** + * Extended real-time signal event. + * + * Type extended for listener manager support. + */ + type SignalEvent = { + type: PubNubEventType.Signal; + data: Signal; + }; + + /** + * Message action real-time event. + */ + export type MessageAction = Event & + Omit & { + /** + * Unique identifier of the user which added message reaction. + * + * @deprecated Use `data.uuid` field instead. + */ + publisher?: string; + data: MessageActionData['data'] & { + /** + * Unique identifier of the user which added message reaction. + */ + uuid: string; + }; + }; + + /** + * Extended message action real-time event. + * + * Type extended for listener manager support. + */ + type MessageActionEvent = { + type: PubNubEventType.MessageAction; + data: MessageAction; + }; + + /** + * App Context Object change real-time event. + */ + export type AppContextObject = Event & { + /** + * Information about App Context object for which event received. + */ + message: AppContextObjectData; + }; + + /** + * `User` App Context Object change real-time event. + */ + export type UserAppContextObject = Omit & { + /** + * Space to which real-time event has been sent. + */ + spaceId: string; + /** + * Information about User Object for which event received. + */ + message: UserObjectData; + }; + + /** + * `Space` App Context Object change real-time event. + */ + export type SpaceAppContextObject = Omit & { + /** + * Space to which real-time event has been sent. + */ + spaceId: string; + /** + * Information about `Space` Object for which event received. + */ + message: SpaceObjectData; + }; + + /** + * VSP `Membership` App Context Object change real-time event. + */ + export type VSPMembershipAppContextObject = Omit & { + /** + * Space to which real-time event has been sent. + */ + spaceId: string; + /** + * Information about `Membership` Object for which event received. + */ + message: VSPMembershipObjectData; + }; + + /** + * Extended App Context Object change real-time event. + * + * Type extended for listener manager support. + */ + type AppContextEvent = { + type: PubNubEventType.AppContext; + data: AppContextObject; + }; + + /** + * File real-time event. + */ + export type File = Event & + Omit & + Omit & { + /** + * Message which has been associated with uploaded file. + */ + message?: Payload; + /** + * Information about uploaded file. + */ + file?: FileData['file'] & { + /** + * File download url. + */ + url: string; + }; + /** + * Decryption error message in case of failure. + */ + error?: string; + }; + + /** + * Extended File real-time event. + * + * Type extended for listener manager support. + */ + type FileEvent = { + type: PubNubEventType.Files; + data: File; + }; + + /** + * Subscribe request parameters. + */ + export type SubscribeParameters = { + /** + * List of channels from which real-time events should be delivered. + * + * @default `,` if {@link channelGroups} is set. + */ + channels?: string[]; + /** + * List of channel groups from which real-time events should be retrieved. + */ + channelGroups?: string[]; + /** + * Next subscription loop timetoken. + */ + timetoken?: string | number; + /** + * Whether should subscribe to channels / groups presence announcements or not. + * + * @default `false` + */ + withPresence?: boolean; + /** + * Presence information which should be associated with `userId`. + * + * `state` information will be associated with `userId` on channels mentioned as keys in + * this object. + * + * @deprecated Use set state methods to specify associated user's data instead of passing to + * subscribe. + */ + state?: Record; + /** + * Whether should subscribe to channels / groups presence announcements or not. + * + * @default `false` + */ + withHeartbeats?: boolean; + }; + + /** + * Service success response. + */ + export type SubscriptionResponse = { + cursor: SubscriptionCursor; + messages: (PresenceEvent | MessageEvent | SignalEvent | MessageActionEvent | AppContextEvent | FileEvent)[]; + }; + } + + export namespace AppContext { + /** + * Partial nullability helper type. + */ + type PartialNullable = { + [P in keyof T]?: T[P] | null; + }; + + /** + * Custom data which should be associated with metadata objects or their relation. + */ + export type CustomData = { + [key: string]: string | number | boolean | null; + }; + + /** + * Type provides shape of App Context parameters which is common to the all objects types to + * be updated. + */ + type ObjectParameters = { + custom?: Custom; + }; + + /** + * Type provides shape of App Context object which is common to the all objects types received + * from the PubNub service. + */ + export type ObjectData = { + /** + * Unique App Context object identifier. + * + * **Important:** For channel it is different from the channel metadata object name. + */ + id: string; + /** + * Last date and time when App Context object has been updated. + * + * String built from date using ISO 8601. + */ + updated: string; + /** + * App Context version hash. + */ + eTag: string; + /** + * Additional data associated with App Context object. + * + * **Important:** Values must be scalars; only arrays or objects are supported. + * {@link /docs/sdks/javascript/api-reference/objects#app-context-filtering-language-definition|App Context + * filtering language} doesn’t support filtering by custom properties. + */ + custom?: Custom | null; + }; + + /** + * Type provides shape of object which let establish relation between metadata objects. + */ + type ObjectsRelation = { + /** + * App Context object unique identifier. + */ + id: string; + /** + * App Context objects relation status. + */ + status?: string; + /** + * Additional data associated with App Context object relation (membership or members). + * + * **Important:** Values must be scalars; only arrays or objects are supported. + * {@link /docs/sdks/javascript/api-reference/objects#app-context-filtering-language-definition|App Context + * filtering language} doesn’t support filtering by custom properties. + */ + custom?: Custom; + }; + + /** + * Response page cursor. + */ + type Page = { + /** + * Random string returned from the server, indicating a specific position in a data set. + * + * Used for forward pagination, it fetches the next page, allowing you to continue from where + * you left off. + */ + next?: string; + /** + * Random string returned from the server, indicating a specific position in a data set. + * + * Used for backward pagination, it fetches the previous page, enabling access to earlier + * data. + * + * **Important:** Ignored if the `next` parameter is supplied. + */ + prev?: string; + }; + + /** + * Metadata objects include options. + * + * Allows to configure what additional information should be included into service response. + */ + type IncludeOptions = { + /** + * Whether to include total number of App Context objects in the response. + * + * @default `false` + */ + totalCount?: boolean; + /** + * Whether to include App Context object `custom` field in the response. + * + * @default `false` + */ + customFields?: boolean; + }; + + /** + * Membership objects include options. + * + * Allows to configure what additional information should be included into service response. + */ + type MembershipsIncludeOptions = IncludeOptions & { + /** + * Whether to include all {@link ChannelMetadata} fields in the response. + * + * @default `false` + */ + channelFields?: boolean; + /** + * Whether to include {@link ChannelMetadata} `custom` field in the response. + * + * @default `false` + */ + customChannelFields?: boolean; + /** + * Whether to include the membership's status field in the response. + * + * @default `false` + */ + statusField?: boolean; + /** + * Whether to include the channel's status field in the response. + * + * @default `false` + */ + channelStatusField?: boolean; + /** + * Whether to include channel's type fields in the response. + * + * @default `false` + */ + channelTypeField?: boolean; + }; + + /** + * Members objects include options. + * + * Allows to configure what additional information should be included into service response. + */ + type MembersIncludeOptions = IncludeOptions & { + /** + * Whether to include all {@link UUIMetadata} fields in the response. + * + * @default `false` + */ + UUIDFields?: boolean; + /** + * Whether to include {@link UUIMetadata} `custom` field in the response. + * + * @default `false` + */ + customUUIDFields?: boolean; + /** + * Whether to include the members's status field in the response. + * + * @default `false` + */ + statusField?: boolean; + /** + * Whether to include the user's status field in the response. + * + * @default `false` + */ + UUIDStatusField?: boolean; + /** + * Whether to include user's type fields in the response. + * + * @default `false` + */ + UUIDTypeField?: boolean; + }; + + /** + * Type provides shape of App Context parameters which is common to the all objects types to + * fetch them by pages. + */ + type PagedRequestParameters = { + /** + * Fields which can be additionally included into response. + */ + include?: Include; + /** + * Expression used to filter the results. + * + * Only objects whose properties satisfy the given expression are returned. The filter language is + * {@link /docs/sdks/javascript/api-reference/objects#app-context-filtering-language-definition|defined here}. + */ + filter?: string; + /** + * Fetched App Context objects sorting options. + */ + sort?: Sort; + /** + * Number of objects to return in response. + * + * **Important:** Maximum for this API is `100` objects per-response. + * + * @default `100` + */ + limit?: number; + /** + * Response pagination configuration. + */ + page?: Page; + }; + + /** + * Type provides shape of App Context object fetch response which is common to the all objects + * types received from the PubNub service. + */ + type ObjectResponse = { + /** + * App Context objects list fetch result status code. + */ + status: number; + /** + * Received App Context object information. + */ + data: ObjectType; + }; + + /** + * Type provides shape of App Context objects fetch response which is common to the all + * objects types received from the PubNub service. + */ + type PagedResponse = ObjectResponse & { + /** + * Total number of App Context objects in the response. + */ + totalCount?: number; + /** + * Random string returned from the server, indicating a specific position in a data set. + * + * Used for forward pagination, it fetches the next page, allowing you to continue from where + * you left off. + */ + next?: string; + /** + * Random string returned from the server, indicating a specific position in a data set. + * + * Used for backward pagination, it fetches the previous page, enabling access to earlier + * data. + * + * **Important:** Ignored if the `next` parameter is supplied. + */ + prev?: string; + }; + + /** + * Key-value pair of a property to sort by, and a sort direction. + */ + type MetadataSortingOptions = + | keyof Omit + | ({ + [K in keyof Omit]?: 'asc' | 'desc' | null; + } & { + [key: `custom.${string}`]: 'asc' | 'desc' | null; + }); + + /** + * Key-value pair of a property to sort by, and a sort direction. + */ + type MembershipsSortingOptions = + | 'channel.id' + | 'channel.name' + | 'channel.description' + | 'channel.updated' + | 'space.id' + | 'space.name' + | 'space.description' + | 'space.updated' + | 'updated' + | { + /** + * Sort results by channel's `id` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + */ + 'channel.id'?: 'asc' | 'desc' | null; + /** + * Sort results by channel's `name` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + */ + 'channel.name'?: 'asc' | 'desc' | null; + /** + * Sort results by channel's `description` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + */ + 'channel.description'?: 'asc' | 'desc' | null; + /** + * Sort results by channel's `update` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + */ + 'channel.updated'?: 'asc' | 'desc' | null; + /** + * Sort results by channel's `id` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + * + * @deprecated Use `channel.id` instead. + */ + 'space.id'?: 'asc' | 'desc' | null; + /** + * Sort results by channel's `name` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + * + * @deprecated Use `channel.name` instead. + */ + 'space.name'?: 'asc' | 'desc' | null; + /** + * Sort results by channel's `description` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + * + * @deprecated Use `channel.name` instead. + */ + 'space.description'?: 'asc' | 'desc' | null; + /** + * Sort results by channel's `update` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + * + * @deprecated Use `channel.updated` instead. + */ + 'space.updated'?: 'asc' | 'desc' | null; + /** + * Sort results by `updated` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + */ + updated?: 'asc' | 'desc' | null; + }; + + /** + * Key-value pair of a property to sort by, and a sort direction. + */ + type MembersSortingOptions = + | 'uuid.id' + | 'uuid.name' + | 'uuid.updated' + | 'user.id' + | 'user.name' + | 'user.updated' + | 'updated' + | { + /** + * Sort results by user's `id` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + */ + 'uuid.id'?: 'asc' | 'desc' | null; + /** + * Sort results by user's `name` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + */ + 'uuid.name'?: 'asc' | 'desc' | null; + /** + * Sort results by user's `update` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + */ + 'uuid.updated'?: 'asc' | 'desc' | null; + /** + * Sort results by user's `id` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + * + * @deprecated Use `uuid.id` instead. + */ + 'user.id'?: 'asc' | 'desc' | null; + /** + * Sort results by user's `name` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + * + * @deprecated Use `uuid.name` instead. + */ + 'user.name'?: 'asc' | 'desc' | null; + /** + * Sort results by user's `update` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + * + * @deprecated Use `uuid.updated` instead. + */ + 'user.updated'?: 'asc' | 'desc' | null; + /** + * Sort results by `updated` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + */ + updated?: 'asc' | 'desc' | null; + }; + + /** + * Fetch All UUID or Channel Metadata request parameters. + */ + export type GetAllMetadataParameters = PagedRequestParameters< + IncludeOptions, + MetadataSortingOptions + >; + + /** + * Type which describes own UUID metadata object fields. + */ + type UUIDMetadataFields = { + /** + * Display name for the user. + */ + name?: string; + /** + * The user's email address. + */ + email?: string; + /** + * User's identifier in an external system. + */ + externalId?: string; + /** + * The URL of the user's profile picture. + */ + profileUrl?: string; + /** + * User's object type information. + */ + type?: string; + /** + * User's object status. + */ + status?: string; + }; + + /** + * Updated UUID metadata object. + * + * Type represents updated UUID metadata object which will be pushed to the PubNub service. + */ + type UUIDMetadata = ObjectParameters & Partial; + + /** + * Received UUID metadata object. + * + * Type represents UUID metadata retrieved from the PubNub service. + */ + export type UUIDMetadataObject = ObjectData & + PartialNullable; + + /** + * Response with fetched page of UUID metadata objects. + */ + export type GetAllUUIDMetadataResponse = PagedResponse>; + + /** + * Fetch UUID Metadata request parameters. + */ + export type GetUUIDMetadataParameters = { + /** + * Unique user identifier. + * + * **Important:** If not supplied then current user's uuid is used. + * + * @default Current `uuid`. + */ + uuid?: string; + /** + * Unique user identifier. + * + * **Important:** If not supplied then current user's uuid is used. + * + * @default Current `userId`. + * + * @deprecated Use `getUUIDMetadata()` method instead. + */ + userId?: string; + /** + * Fields which can be additionally included into response. + */ + include?: Omit; + }; + + /** + * Response with requested UUID metadata object. + */ + export type GetUUIDMetadataResponse = ObjectResponse>; + + /** + * Update UUID Metadata request parameters. + */ + export type SetUUIDMetadataParameters = { + /** + * Unique user identifier. + * + * **Important:** If not supplied then current user's uuid is used. + * + * @default Current `uuid`. + */ + uuid?: string; + /** + * Unique user identifier. + * + * **Important:** If not supplied then current user's uuid is used. + * + * @default Current `userId`. + * + * @deprecated Use `setUUIDMetadata()` method instead. + */ + userId?: string; + /** + * Metadata, which should be associated with UUID. + */ + data: UUIDMetadata; + /** + * Fields which can be additionally included into response. + */ + include?: Omit; + }; + + /** + * Response with result of the UUID metadata object update. + */ + export type SetUUIDMetadataResponse = ObjectResponse>; + + /** + * Remove UUID Metadata request parameters. + */ + export type RemoveUUIDMetadataParameters = { + /** + * Unique user identifier. + * + * **Important:** If not supplied then current user's uuid is used. + * + * @default Current `uuid`. + */ + uuid?: string; + /** + * Unique user identifier. + * + * **Important:** If not supplied then current user's uuid is used. + * + * @default Current `userId`. + * + * @deprecated Use `removeUUIDMetadata()` method instead. + */ + userId?: string; + }; + + /** + * Response with result of the UUID metadata removal. + */ + export type RemoveUUIDMetadataResponse = ObjectResponse>; + + /** + * Type which describes own Channel metadata object fields. + */ + type ChannelMetadataFields = { + /** + * Name of a channel. + */ + name?: string; + /** + * Description of a channel. + */ + description?: string; + /** + * Channel's object type information. + */ + type?: string; + /** + * Channel's object status. + */ + status?: string; + }; + + /** + * Updated channel metadata object. + * + * Type represents updated channel metadata object which will be pushed to the PubNub service. + */ + type ChannelMetadata = ObjectParameters & Partial; + + /** + * Received channel metadata object. + * + * Type represents chanel metadata retrieved from the PubNub service. + */ + export type ChannelMetadataObject = ObjectData & + PartialNullable; + + /** + * Response with fetched page of channel metadata objects. + */ + export type GetAllChannelMetadataResponse = PagedResponse>; + + /** + * Fetch Channel Metadata request parameters. + */ + export type GetChannelMetadataParameters = { + /** + * Channel name. + */ + channel: string; + /** + * Space identifier. + * + * @deprecated Use `getChannelMetadata()` method instead. + */ + spaceId?: string; + /** + * Fields which can be additionally included into response. + */ + include?: Omit; + }; + + /** + * Response with requested channel metadata object. + */ + export type GetChannelMetadataResponse = ObjectResponse>; + + /** + * Update Channel Metadata request parameters. + */ + export type SetChannelMetadataParameters = { + /** + * Channel name. + */ + channel: string; + /** + * Space identifier. + * + * @deprecated Use `setChannelMetadata()` method instead. + */ + spaceId?: string; + /** + * Metadata, which should be associated with UUID. + */ + data: ChannelMetadata; + /** + * Fields which can be additionally included into response. + */ + include?: Omit; + }; + + /** + * Response with result of the channel metadata object update. + */ + export type SetChannelMetadataResponse = ObjectResponse>; + + /** + * Remove Channel Metadata request parameters. + */ + export type RemoveChannelMetadataParameters = { + /** + * Channel name. + */ + channel: string; + /** + * Space identifier. + * + * @deprecated Use `removeChannelMetadata()` method instead. + */ + spaceId?: string; + }; + + /** + * Response with result of the channel metadata removal. + */ + export type RemoveChannelMetadataResponse = ObjectResponse>; + + /** + * Related channel metadata object. + * + * Type represents chanel metadata which has been used to create membership relation with UUID. + */ + type MembershipsObject = Omit< + ObjectData, + 'id' + > & { + channel: + | ChannelMetadataObject + | { + id: string; + }; + }; + + /** + * Response with fetched page of UUID membership objects. + */ + type MembershipsResponse = PagedResponse< + MembershipsObject + >; + + /** + * Fetch Memberships request parameters. + */ + export type GetMembershipsParameters = PagedRequestParameters< + MembershipsIncludeOptions, + MembershipsSortingOptions + > & { + /** + * Unique user identifier. + * + * **Important:** If not supplied then current user's uuid is used. + * + * @default Current `uuid`. + */ + uuid?: string; + /** + * Unique user identifier. + * + * **Important:** If not supplied then current user's uuid is used. + * + * @default Current `uuidId`. + * + * @deprecated Use `uuid` field instead. + */ + userId?: string; + }; + + /** + * Response with requested channel memberships information. + */ + export type GetMembershipsResponse< + MembershipCustom extends CustomData, + ChannelCustom extends CustomData, + > = MembershipsResponse; + + /** + * Update Memberships request parameters. + */ + export type SetMembershipsParameters = PagedRequestParameters< + Omit, + MembershipsSortingOptions + > & { + /** + * Unique user identifier. + * + * **Important:** If not supplied then current user's uuid is used. + * + * @default Current `uuid`. + */ + uuid?: string; + /** + * Unique user identifier. + * + * **Important:** If not supplied then current user's uuid is used. + * + * @default Current `userId`. + * + * @deprecated Use `uuid` field instead. + */ + userId?: string; + /** + * List of channels with which UUID membership should be established. + */ + channels: Array>; + /** + * List of channels with which UUID membership should be established. + * + * @deprecated Use `channels` field instead. + */ + spaces?: Array< + | string + | (Omit, 'id'> & { + /** + * Unique Space object identifier. + */ + spaceId: string; + }) + >; + }; + + /** + * Response with requested channel memberships information change. + */ + export type SetMembershipsResponse< + MembershipCustom extends CustomData, + ChannelCustom extends CustomData, + > = MembershipsResponse; + + /** + * Remove Memberships request parameters. + */ + export type RemoveMembershipsParameters = PagedRequestParameters< + MembershipsIncludeOptions, + MembershipsSortingOptions + > & { + /** + * Unique user identifier. + * + * **Important:** If not supplied then current user's uuid is used. + * + * @default Current `uuid`. + */ + uuid?: string; + /** + * Unique user identifier. + * + * **Important:** If not supplied then current user's uuid is used. + * + * @default Current `userId`. + * + * @deprecated Use {@link uuid} field instead. + */ + userId?: string; + /** + * List of channels for which membership which UUID should be removed. + */ + channels: string[]; + /** + * List of space names for which membership which UUID should be removed. + * + * @deprecated Use {@link channels} field instead. + */ + spaceIds?: string[]; + }; + + /** + * Response with remaining memberships. + */ + export type RemoveMembershipsResponse< + MembershipCustom extends CustomData, + ChannelCustom extends CustomData, + > = MembershipsResponse; + + /** + * Related UUID metadata object. + * + * Type represents UUID metadata which has been used to when added members to the channel. + */ + type MembersObject = Omit< + ObjectData, + 'id' + > & { + uuid: + | UUIDMetadataObject + | { + id: string; + }; + }; + + /** + * Response with fetched page of channel member objects. + */ + type MembersResponse = PagedResponse< + MembersObject + >; + + /** + * Fetch Members request parameters. + */ + export type GetMembersParameters = PagedRequestParameters & { + /** + * Channel name. + */ + channel: string; + /** + * Space identifier. + * + * @deprecated Use `channel` field instead. + */ + spaceId?: string; + }; + + /** + * Response with requested channel memberships information. + */ + export type GetMembersResponse = MembersResponse< + MembersCustom, + UUIDCustom + >; + + /** + * Update Members request parameters. + */ + export type SetChannelMembersParameters = PagedRequestParameters< + Omit, + MembersSortingOptions + > & { + /** + * Channel name. + */ + channel: string; + /** + * Space identifier. + * + * @deprecated Use `channel` field instead. + */ + spaceId?: string; + /** + * List of UUIDs which should be added as `channel` members. + */ + uuids: Array>; + /** + * List of UUIDs which should be added as `channel` members. + * + * @deprecated Use `uuids` field instead. + */ + users?: Array< + | string + | (Omit, 'id'> & { + /** + * Unique User object identifier. + */ + userId: string; + }) + >; + }; + + /** + * Response with requested channel members information change. + */ + export type SetMembersResponse = MembersResponse< + MemberCustom, + UUIDCustom + >; + + /** + * Remove Members request parameters. + */ + export type RemoveMembersParameters = PagedRequestParameters & { + /** + * Channel name. + */ + channel: string; + /** + * Space identifier. + * + * @deprecated Use {@link channel} field instead. + */ + spaceId?: string; + /** + * List of UUIDs which should be removed from the `channel` members list. + * removed. + */ + uuids: string[]; + /** + * List of user identifiers which should be removed from the `channel` members list. + * removed. + * + * @deprecated Use {@link uuids} field instead. + */ + userIds?: string[]; + }; + + /** + * Response with remaining members. + */ + export type RemoveMembersResponse = MembersResponse< + MemberCustom, + UUIDCustom + >; + + /** + * Related User metadata object. + * + * Type represents User metadata which has been used to when added members to the Space. + */ + type UserMembersObject = Omit< + ObjectData, + 'id' + > & { + user: + | UUIDMetadataObject + | { + id: string; + }; + }; + + /** + * Response with fetched page of Space member objects. + */ + export type UserMembersResponse = PagedResponse< + UserMembersObject + >; + + type SpaceMembershipObject = Omit< + ObjectData, + 'id' + > & { + space: + | ChannelMetadataObject + | { + id: string; + }; + }; + + /** + * Response with fetched page of User membership objects. + */ + export type SpaceMembershipsResponse< + MembershipCustom extends CustomData, + ChannelCustom extends CustomData, + > = PagedResponse>; + } + + export namespace ChannelGroups { + /** + * Add or remove Channels to the channel group request parameters. + */ + export type ManageChannelGroupChannelsParameters = { + /** + * Name of the channel group for which channels list should be changed. + */ + channelGroup: string; + /** + * List of channels to be added or removed. + */ + channels: string[]; + }; + + /** + * Channel group channels list manage response. + */ + export type ManageChannelGroupChannelsResponse = Record; + + /** + * Response with result of the all channel groups list. + */ + export type ListAllChannelGroupsResponse = { + /** + * All channel groups with channels. + */ + groups: string[]; + }; + + /** + * List Channel Group Channels request parameters. + */ + export type ListChannelGroupChannelsParameters = { + /** + * Name of the channel group for which list of channels should be retrieved. + */ + channelGroup: string; + }; + + /** + * Response with result of the list channel group channels. + */ + export type ListChannelGroupChannelsResponse = { + /** + * List of the channels registered withing specified channel group. + */ + channels: string[]; + }; + + /** + * Delete Channel Group request parameters. + */ + export type DeleteChannelGroupParameters = { + /** + * Name of the channel group which should be removed. + */ + channelGroup: string; + }; + + /** + * Delete channel group response. + */ + export type DeleteChannelGroupResponse = Record; + } + + export namespace Publish { + /** + * Request configuration parameters. + */ + export type PublishParameters = { + /** + * Channel name to publish messages to. + */ + channel: string; + /** + * Data which should be sent to the `channel`. + * + * The message may be any valid JSON type including objects, arrays, strings, and numbers. + */ + message: Payload; + /** + * Whether published data should be available with `Storage API` later or not. + * + * @default `true` + */ + storeInHistory?: boolean; + /** + * Whether message should be sent as part of request POST body or not. + * + * @default `false` + */ + sendByPost?: boolean; + /** + * Metadata, which should be associated with published data. + * + * Associated metadata can be utilized by message filtering feature. + */ + meta?: Payload; + /** + * Specify duration during which data will be available with `Storage API`. + * + * - If `storeInHistory` = `true`, and `ttl` = `0`, the `message` is stored with no expiry time. + * - If `storeInHistory` = `true` and `ttl` = `X` (`X` is an Integer value), the `message` is + * stored with an expiry time of `X` hours. + * - If `storeInHistory` = `false`, the `ttl` parameter is ignored. + * - If `ttl` is not specified, then expiration of the `message` defaults back to the expiry value + * for the key. + */ + ttl?: number; + /** + * Whether published data should be replicated across all data centers or not. + * + * @default `true` + * @deprecated + */ + replicate?: boolean; + }; + + /** + * Service success response. + */ + export type PublishResponse = { + /** + * High-precision time when published data has been received by the PubNub service. + */ + timetoken: string; + }; + } + + export namespace Signal { + /** + * Request configuration parameters. + */ + export type SignalParameters = { + /** + * Channel name to publish signal to. + */ + channel: string; + /** + * Data which should be sent to the `channel`. + * + * The message may be any valid JSON type including objects, arrays, strings, and numbers. + */ + message: Payload; + }; + + /** + * Service success response. + */ + export type SignalResponse = { + /** + * High-precision time when published data has been received by the PubNub service. + */ + timetoken: string; + }; + } + + export namespace Presence { + /** + * Associated presence state fetch parameters. + */ + export type GetPresenceStateParameters = { + /** + * The subscriber uuid to get the current state. + * + * @default `current uuid` + */ + uuid?: string; + /** + * List of channels for which state associated with {@link uuid} should be retrieved. + * + * **Important:** Either {@link channels} or {@link channelGroups} should be provided; + */ + channels?: string[]; + /** + * List of channel groups for which state associated with {@link uuid} should be retrieved. + * + * **Important:** Either {@link channels} or {@link channelGroups} should be provided; + */ + channelGroups?: string[]; + }; + + /** + * Associated presence state fetch response. + */ + export type GetPresenceStateResponse = { + /** + * Channels map to state which `uuid` has associated with them. + */ + channels: Record; + }; + + /** + * Associate presence state parameters. + */ + export type SetPresenceStateParameters = { + /** + * List of channels for which state should be associated with {@link uuid}. + */ + channels?: string[]; + /** + * List of channel groups for which state should be associated with {@link uuid}. + */ + channelGroups?: string[]; + /** + * State which should be associated with `uuid` on provided list of {@link channels} and {@link channelGroups}. + */ + state: Payload; + }; + + /** + * Associate presence state parameters using heartbeat. + */ + export type SetPresenceStateWithHeartbeatParameters = { + /** + * List of channels for which state should be associated with {@link uuid}. + */ + channels?: string[]; + /** + * State which should be associated with `uuid` on provided list of {@link channels}. + */ + state: Payload; + /** + * Whether `presence/heartbeat` REST API should be used to manage state or not. + * + * @default `false` + */ + withHeartbeat: boolean; + }; + + /** + * Associate presence state response. + */ + export type SetPresenceStateResponse = { + /** + * State which has been associated with `uuid` on provided list of channels and groups. + */ + state: Payload; + }; + + /** + * Announce heartbeat parameters. + */ + export type PresenceHeartbeatParameters = { + /** + * How long the server will consider the client alive for presence.The value is in seconds. + */ + heartbeat: number; + /** + * List of channels for which heartbeat should be announced for {@link uuid}. + */ + channels?: string[]; + /** + * List of channel groups for which heartbeat should be announced for {@link uuid}. + */ + channelGroups?: string[]; + /** + * State which should be associated with `uuid` on provided list of {@link channels} and {@link channelGroups}. + */ + state?: Payload; + }; + + /** + * Announce heartbeat response. + */ + export type PresenceHeartbeatResponse = Record; + + /** + * Presence leave parameters. + */ + export type PresenceLeaveParameters = { + /** + * List of channels for which `uuid` should be marked as `offline`. + */ + channels?: string[]; + /** + /** + * List of channel groups for which `uuid` should be marked as `offline`. + */ + channelGroups?: string[]; + }; + + /** + * Presence leave response. + */ + export type PresenceLeaveResponse = Record; + + /** + * Channel / channel group presence fetch parameters.. + */ + export type HereNowParameters = { + /** + * List of channels for which presence should be retrieved. + */ + channels?: string[]; + /** + * List of channel groups for which presence should be retrieved. + */ + channelGroups?: string[]; + /** + * Whether `uuid` information should be included in response or not. + * + * **Note:** Only occupancy information will be returned if both {@link includeUUIDs} and {@link includeState} is + * set to `false`. + * + * @default `true` + */ + includeUUIDs?: boolean; + /** + * Whether state associated with `uuid` should be included in response or not. + * + * @default `false`. + */ + includeState?: boolean; + /** + * Additional query parameters. + */ + queryParameters?: Record; + }; + + /** + * `uuid` where now response. + */ + export type HereNowResponse = { + /** + * Total number of channels for which presence information received. + */ + totalChannels: number; + /** + * Total occupancy for all retrieved channels. + */ + totalOccupancy: number; + /** + * List of channels to which `uuid` currently subscribed. + */ + channels: { + [p: string]: { + /** + * List of received channel subscribers. + * + * **Note:** Field is missing if `uuid` and `state` not included. + */ + occupants: { + uuid: string; + state?: Payload | null; + }[]; + /** + * Name of channel for which presence information retrieved. + */ + name: string; + /** + * Total number of active subscribers in single channel. + */ + occupancy: number; + }; + }; + }; + + /** + * `uuid` where now parameters. + */ + export type WhereNowParameters = { + /** + * The subscriber uuid to get the current state. + * + * @default `current uuid` + */ + uuid?: string; + }; + + /** + * `uuid` where now response. + */ + export type WhereNowResponse = { + /** + * Channels map to state which `uuid` has associated with them. + */ + channels: string[]; + }; + } + + export namespace History { + /** + * Get history request parameters. + */ + export type GetHistoryParameters = { + /** + * Channel to return history messages from. + */ + channel: string; + /** + * Specifies the number of historical messages to return. + * + * **Note:** Maximum `100` messages can be returned in single response. + * + * @default `100` + */ + count?: number; + /** + * Whether message `meta` information should be fetched or not. + * + * @default `false` + */ + includeMeta?: boolean; + /** + * Timetoken delimiting the `start` of `time` slice (exclusive) to pull messages from. + */ + start?: string; + /** + * Timetoken delimiting the `end` of `time` slice (inclusive) to pull messages from. + */ + end?: string; + /** + * Whether timeline should traverse in reverse starting with the oldest message first or not. + * + * If both `start` and `end` arguments are provided, `reverse` is ignored and messages are + * returned starting with the newest message. + */ + reverse?: boolean; + /** + * Whether message timetokens should be stringified or not. + * + * @default `false` + */ + stringifiedTimeToken?: boolean; + }; + + /** + * Get history response. + */ + export type GetHistoryResponse = { + /** + * List of previously published messages. + */ + messages: { + /** + * Message payload (decrypted). + */ + entry: Payload; + /** + * When message has been received by PubNub service. + */ + timetoken: string | number; + /** + * Additional data which has been published along with message to be used with real-time + * events filter expression. + */ + meta?: Payload; + /** + * Message decryption error (if attempt has been done). + */ + error?: string; + }[]; + /** + * Received messages timeline start. + */ + startTimeToken: string | number; + /** + * Received messages timeline end. + */ + endTimeToken: string | number; + }; + + /** + * PubNub-defined message type. + * + * Types of messages which can be retrieved with fetch messages REST API. + */ + export enum PubNubMessageType { + /** + * Regular message. + */ + Message = -1, + /** + * File message. + */ + Files = 4, + } + + /** + * Per-message actions information. + */ + export type Actions = { + /** + * Message action type. + */ + [t: string]: { + /** + * Message action value. + */ + [v: string]: { + /** + * Unique identifier of the user which reacted on message. + */ + uuid: string; + /** + * High-precision PubNub timetoken with time when {@link uuid} reacted on message. + */ + actionTimetoken: string; + }[]; + }; + }; + + /** + * Additional message actions fetch information. + */ + export type MoreActions = { + /** + * Prepared fetch messages with actions REST API URL. + */ + url: string; + /** + * Next page time offset. + */ + start: string; + /** + * Number of messages to retrieve with next page. + */ + max: number; + }; + + /** + * Common content of the fetched message. + */ + type BaseFetchedMessage = { + /** + * Name of channel for which message has been retrieved. + */ + channel: string; + /** + * When message has been received by PubNub service. + */ + timetoken: string | number; + /** + * Message publisher unique identifier. + */ + uuid?: string; + /** + * Additional data which has been published along with message to be used with real-time + * events filter expression. + */ + meta?: Payload; + /** + * Message decryption error (if attempt has been done). + */ + error?: string; + }; + + /** + * Regular message published to the channel. + */ + export type RegularMessage = BaseFetchedMessage & { + /** + * Message payload (decrypted). + */ + message: Payload; + /** + * PubNub-defined message type. + */ + messageType?: PubNubMessageType.Message; + }; + + /** + * File message published to the channel. + */ + export type FileMessage = BaseFetchedMessage & { + /** + * Message payload (decrypted). + */ + message: { + /** + * File annotation message. + */ + message?: Payload; + /** + * File information. + */ + file: { + /** + * Unique file identifier. + */ + id: string; + /** + * Name with which file has been stored. + */ + name: string; + /** + * File's content mime-type. + */ + 'mime-type': string; + /** + * Stored file size. + */ + size: number; + /** + * Pre-computed file download Url. + */ + url: string; + }; + }; + /** + * PubNub-defined message type. + */ + messageType?: PubNubMessageType.Files; + }; + + /** + * Fetched message entry in channel messages list. + */ + export type FetchedMessage = RegularMessage | FileMessage; + + /** + * Fetched with actions message entry in channel messages list. + */ + export type FetchedMessageWithActions = FetchedMessage & { + /** + * List of message reactions. + */ + actions?: Actions; + /** + * List of message reactions. + * + * @deprecated Use {@link actions} field instead. + */ + data?: Actions; + }; + + /** + * Fetch messages request parameters. + */ + export type FetchMessagesParameters = { + /** + * Specifies channels to return history messages from. + * + * **Note:** Maximum of `500` channels are allowed. + */ + channels: string[]; + /** + * Specifies the number of historical messages to return per channel. + * + * **Note:** Default is `100` per single channel and `25` per multiple channels or per + * single channel if {@link includeMessageActions} is used. + * + * @default `100` or `25` + */ + count?: number; + /** + * Whether message type should be returned with each history message or not. + * + * @default `true` + */ + includeMessageType?: boolean; + /** + * Whether publisher `uuid` should be returned with each history message or not. + * + * @default `true` + */ + includeUUID?: boolean; + /** + * Whether publisher `uuid` should be returned with each history message or not. + * + * @deprecated Use {@link includeUUID} property instead. + */ + includeUuid?: boolean; + /** + * Whether message `meta` information should be fetched or not. + * + * @default `false` + */ + includeMeta?: boolean; + /** + * Whether message-added message actions should be fetched or not. + * + * If used, the limit of messages retrieved will be `25` per single channel. + * + * Each message can have a maximum of `25000` actions attached to it. Consider the example of + * querying for 10 messages. The first five messages have 5000 actions attached to each of + * them. The API will return the first 5 messages and all their 25000 actions. The response + * will also include a `more` link to get the remaining 5 messages. + * + * **Important:** Truncation will happen if the number of actions on the messages returned + * is > 25000. + * + * @default `false` + * + * @throws Exception if API is called with more than one channel. + */ + includeMessageActions?: boolean; + /** + * Timetoken delimiting the `start` of `time` slice (exclusive) to pull messages from. + */ + start?: string; + /** + * Timetoken delimiting the `end` of `time` slice (inclusive) to pull messages from. + */ + end?: string; + /** + * Whether message timetokens should be stringified or not. + * + * @default `false` + */ + stringifiedTimeToken?: boolean; + }; + + /** + * Fetch messages response. + */ + export type FetchMessagesForChannelsResponse = { + /** + * List of previously published messages per requested channel. + */ + channels: { + [p: string]: FetchedMessage[]; + }; + }; + + /** + * Fetch messages with reactions response. + */ + export type FetchMessagesWithActionsResponse = { + channels: { + [p: string]: FetchedMessageWithActions[]; + }; + /** + * Additional message actions fetch information. + */ + more: MoreActions; + }; + + /** + * Fetch messages response. + */ + export type FetchMessagesResponse = FetchMessagesForChannelsResponse | FetchMessagesWithActionsResponse; + + /** + * Message count request parameters. + */ + export type MessageCountParameters = { + /** + * The channels to fetch the message count. + */ + channels: string[]; + /** + * List of timetokens, in order of the {@link channels} list. + * + * Specify a single timetoken to apply it to all channels. Otherwise, the list of timetokens + * must be the same length as the list of {@link channels}, or the function returns an error + * flag. + */ + channelTimetokens?: string[]; + /** + * High-precision PubNub timetoken starting from which number of messages should be counted. + * + * Same timetoken will be used to count messages for each passed {@link channels}. + * + * @deprecated Use {@link channelTimetokens} field instead. + */ + timetoken?: string; + }; + + /** + * Message count response. + */ + export type MessageCountResponse = { + /** + * Map of channel names to the number of counted messages. + */ + channels: Record; + }; + + /** + * Delete messages from channel parameters. + */ + export type DeleteMessagesParameters = { + /** + * Specifies channel messages to be deleted from history. + */ + channel: string; + /** + * Timetoken delimiting the start of time slice (exclusive) to delete messages from. + */ + start?: string; + /** + * Timetoken delimiting the end of time slice (inclusive) to delete messages from. + */ + end?: string; + }; + + /** + * Delete messages from channel response. + */ + export type DeleteMessagesResponse = Record; + } + + export namespace MessageAction { + /** + * Message reaction object type. + */ + export type MessageAction = { + /** + * What feature this message action represents. + */ + type: string; + /** + * Value which should be stored along with message action. + */ + value: string; + /** + * Unique identifier of the user which added message action. + */ + uuid: string; + /** + * Timetoken of when message reaction has been added. + * + * **Note:** This token required when it will be required to remove reaction. + */ + actionTimetoken: string; + /** + * Timetoken of message to which `action` has been added. + */ + messageTimetoken: string; + }; + + /** + * More message actions fetch information. + */ + export type MoreMessageActions = { + /** + * Prepared REST API url to fetch next page with message actions. + */ + url: string; + /** + * Message action timetoken denoting the start of the range requested with next page. + * + * **Note:** Return values will be less than {@link start}. + */ + start: string; + /** + * Message action timetoken denoting the end of the range requested with next page. + * + * **Note:** Return values will be greater than or equal to {@link end}. + */ + end: string; + /** + * Number of message actions to return in next response. + */ + limit: number; + }; + + /** + * Add Message Action request parameters. + */ + export type AddMessageActionParameters = { + /** + * Name of channel which stores the message for which {@link action} should be added. + */ + channel: string; + /** + * Timetoken of message for which {@link action} should be added. + */ + messageTimetoken: string; + /** + * Message `action` information. + */ + action: { + /** + * What feature this message action represents. + */ + type: string; + /** + * Value which should be stored along with message action. + */ + value: string; + }; + }; + + /** + * Response with added message action object. + */ + export type AddMessageActionResponse = { + data: MessageAction; + }; + + /** + * Get Message Actions request parameters. + */ + export type GetMessageActionsParameters = { + /** + * Name of channel from which list of messages `actions` should be retrieved. + */ + channel: string; + /** + * Message action timetoken denoting the start of the range requested. + * + * **Note:** Return values will be less than {@link start}. + */ + start?: string; + /** + * Message action timetoken denoting the end of the range requested. + * + * **Note:** Return values will be greater than or equal to {@link end}. + */ + end?: string; + /** + * Number of message actions to return in response. + */ + limit?: number; + }; + + /** + * Response with message actions in specific `channel`. + */ + export type GetMessageActionsResponse = { + /** + * Retrieved list of message actions. + */ + data: MessageAction[]; + /** + * Received message actions time frame start. + */ + start: string | null; + /** + * Received message actions time frame end. + */ + end: string | null; + /** + * More message actions fetch information. + */ + more?: MoreMessageActions; + }; + + /** + * Remove Message Action request parameters. + */ + export type RemoveMessageActionParameters = { + /** + * Name of channel which store message for which `action` should be removed. + */ + channel: string; + /** + * Timetoken of message for which `action` should be removed. + */ + messageTimetoken: string; + /** + * Action addition timetoken. + */ + actionTimetoken: string; + }; + + /** + * Response with message remove result. + */ + export type RemoveMessageActionResponse = { + data: Record; + }; + } + + export namespace FileSharing { + /** + * Shared file object. + */ + export type SharedFile = { + /** + * Name with which file has been stored. + */ + name: string; + /** + * Unique service-assigned file identifier. + */ + id: string; + /** + * Shared file size. + */ + size: number; + /** + * ISO 8601 time string when file has been shared. + */ + created: string; + }; + + /** + * List Files request parameters. + */ + export type ListFilesParameters = { + /** + * Name of channel for which list of files should be requested. + */ + channel: string; + /** + * How many entries return with single response. + */ + limit?: number; + /** + * Next files list page token. + */ + next?: string; + }; + + /** + * List Files request response. + */ + export type ListFilesResponse = { + /** + * Files list fetch result status code. + */ + status: number; + /** + * List of fetched file objects. + */ + data: SharedFile[]; + /** + * Next files list page token. + */ + next: string; + /** + * Number of retrieved files. + */ + count: number; + }; + + /** + * Send File request parameters. + */ + export type SendFileParameters = Omit & { + /** + * Channel to send the file to. + */ + channel: string; + /** + * File to send. + */ + file: FileParameters; + }; + + /** + * Send File request response. + */ + export type SendFileResponse = PublishFileMessageResponse & { + /** + * Send file request processing status code. + */ + status: number; + /** + * Actual file name under which file has been stored. + * + * File name and unique {@link id} can be used to download file from the channel later. + * + * **Important:** Actual file name may be different from the one which has been used during file + * upload. + */ + name: string; + /** + * Unique file identifier. + * + * Unique file identifier, and it's {@link name} can be used to download file from the channel + * later. + */ + id: string; + }; + + /** + * Upload File request parameters. + */ + export type UploadFileParameters = { + /** + * Unique file identifier. + * + * Unique file identifier, and it's {@link fileName} can be used to download file from the channel + * later. + */ + fileId: string; + /** + * Actual file name under which file has been stored. + * + * File name and unique {@link fileId} can be used to download file from the channel later. + * + * **Note:** Actual file name may be different from the one which has been used during file + * upload. + */ + fileName: string; + /** + * File which should be uploaded. + */ + file: PubNubFileInterface; + /** + * Pre-signed file upload Url. + */ + uploadUrl: string; + /** + * An array of form fields to be used in the pre-signed POST request. + * + * **Important:** Form data fields should be passed in exact same order as received from + * the PubNub service. + */ + formFields: { + /** + * Form data field name. + */ + name: string; + /** + * Form data field value. + */ + value: string; + }[]; + }; + + /** + * Upload File request response. + */ + export type UploadFileResponse = { + /** + * Upload File request processing status code. + */ + status: number; + /** + * Service processing result response. + */ + message: Payload; + }; + + /** + * Generate File Upload URL request parameters. + */ + export type GenerateFileUploadUrlParameters = { + /** + * Name of channel to which file should be uploaded. + */ + channel: string; + /** + * Actual name of the file which should be uploaded. + */ + name: string; + }; + + /** + * Generation File Upload URL request response. + */ + export type GenerateFileUploadUrlResponse = { + /** + * Unique file identifier. + * + * Unique file identifier, and it's {@link name} can be used to download file from the channel + * later. + */ + id: string; + /** + * Actual file name under which file has been stored. + * + * File name and unique {@link id} can be used to download file from the channel later. + * + * **Note:** Actual file name may be different from the one which has been used during file + * upload. + */ + name: string; + /** + * Pre-signed URL for file upload. + */ + url: string; + /** + * An array of form fields to be used in the pre-signed POST request. + * + * **Important:** Form data fields should be passed in exact same order as received from + * the PubNub service. + */ + formFields: { + /** + * Form data field name. + */ + name: string; + /** + * Form data field value. + */ + value: string; + }[]; + }; + + /** + * Publish File Message request parameters. + */ + export type PublishFileMessageParameters = { + /** + * Name of channel to which file has been sent. + */ + channel: string; + /** + * File annotation message. + */ + message?: Payload; + /** + * Custom file and message encryption key. + * + * @deprecated Use {@link Configuration#cryptoModule|cryptoModule} configured for PubNub client + * instance or encrypt file prior {@link PubNub#sendFile|sendFile} method call. + */ + cipherKey?: string; + /** + * Unique file identifier. + * + * Unique file identifier, and it's {@link fileName} can be used to download file from the channel + * later. + */ + fileId: string; + /** + * Actual file name under which file has been stored. + * + * File name and unique {@link fileId} can be used to download file from the channel later. + * + * **Note:** Actual file name may be different from the one which has been used during file + * upload. + */ + fileName: string; + /** + * Whether published file messages should be stored in the channel's history. + * + * **Note:** If `storeInHistory` not specified, then the history configuration on the key is + * used. + * + * @default `true` + */ + storeInHistory?: boolean; + /** + * How long the message should be stored in the channel's history. + * + * **Note:** If not specified, defaults to the key set's retention value. + * + * @default `0` + */ + ttl?: number; + /** + * Metadata, which should be associated with published file. + * + * Associated metadata can be utilized by message filtering feature. + */ + meta?: Payload; + }; + + /** + * Publish File Message request response. + */ + export type PublishFileMessageResponse = { + /** + * High-precision time when published file message has been received by the PubNub service. + */ + timetoken: string; + }; + + /** + * Download File request parameters. + */ + export type DownloadFileParameters = FileUrlParameters & { + /** + * Custom file and message encryption key. + * + * @deprecated Use {@link Configuration#cryptoModule|cryptoModule} configured for PubNub client + * instance or encrypt file prior {@link PubNub#sendFile|sendFile} method call. + */ + cipherKey?: string; + }; + + /** + * Generate File download Url request parameters. + */ + export type FileUrlParameters = { + /** + * Name of channel where file has been sent. + */ + channel: string; + /** + * Unique file identifier. + * + * Unique file identifier, and it's {@link name} can be used to download file from the channel + * later. + */ + id: string; + /** + * Actual file name under which file has been stored. + * + * File name and unique {@link id} can be used to download file from the channel later. + * + * **Important:** Actual file name may be different from the one which has been used during file + * upload. + */ + name: string; + }; + + /** + * Generate File Download Url response. + */ + export type FileUrlResponse = string; + + /** + * Delete File request parameters. + */ + export type DeleteFileParameters = { + /** + * Name of channel where file has been sent. + */ + channel: string; + /** + * Unique file identifier. + * + * Unique file identifier, and it's {@link name} can be used to download file from the channel + * later. + */ + id: string; + /** + * Actual file name under which file has been stored. + * + * File name and unique {@link id} can be used to download file from the channel later. + * + * **Important:** Actual file name may be different from the one which has been used during file + * upload. + */ + name: string; + }; + + /** + * Delete File request response. + */ + export type DeleteFileResponse = { + /** + * Delete File request processing status code. + */ + status: number; + }; + } + + export namespace PAM { + /** + * Metadata which will be associated with access token. + */ + export type Metadata = Record; + + /** + * Channel-specific token permissions. + */ + export type ChannelTokenPermissions = { + /** + * Whether `read` operations are permitted for corresponding level or not. + */ + read?: boolean; + /** + * Whether `write` operations are permitted for corresponding level or not. + */ + write?: boolean; + /** + * Whether `get` operations are permitted for corresponding level or not. + */ + get?: boolean; + /** + * Whether `manage` operations are permitted for corresponding level or not. + */ + manage?: boolean; + /** + * Whether `update` operations are permitted for corresponding level or not. + */ + update?: boolean; + /** + * Whether `join` operations are permitted for corresponding level or not. + */ + join?: boolean; + /** + * Whether `delete` operations are permitted for corresponding level or not. + */ + delete?: boolean; + }; + + /** + * Space-specific token permissions. + */ + type SpaceTokenPermissions = ChannelTokenPermissions; + + /** + * Channel group-specific token permissions. + */ + export type ChannelGroupTokenPermissions = { + /** + * Whether `read` operations are permitted for corresponding level or not. + */ + read?: boolean; + /** + * Whether `manage` operations are permitted for corresponding level or not. + */ + manage?: boolean; + }; + + /** + * Uuid-specific token permissions. + */ + export type UuidTokenPermissions = { + /** + * Whether `get` operations are permitted for corresponding level or not. + */ + get?: boolean; + /** + * Whether `update` operations are permitted for corresponding level or not. + */ + update?: boolean; + /** + * Whether `delete` operations are permitted for corresponding level or not. + */ + delete?: boolean; + }; + + /** + * User-specific token permissions. + */ + type UserTokenPermissions = UuidTokenPermissions; + + /** + * Generate access token with permissions. + * + * Generate time-limited access token with required permissions for App Context objects. + */ + export type ObjectsGrantTokenParameters = { + /** + * Total number of minutes for which the token is valid. + * + * The minimum allowed value is `1`. + * The maximum is `43,200` minutes (`30` days). + */ + ttl: number; + /** + * Object containing resource permissions. + */ + resources?: { + /** + * Object containing `spaces` metadata permissions. + */ + spaces?: Record; + /** + * Object containing `users` permissions. + */ + users?: Record; + }; + /** + * Object containing permissions to multiple resources specified by a RegEx pattern. + */ + patterns?: { + /** + * Object containing `spaces` metadata permissions. + */ + spaces?: Record; + /** + * Object containing `users` permissions. + */ + users?: Record; + }; + /** + * Extra metadata to be published with the request. + * + * **Important:** Values must be scalar only; `arrays` or `objects` aren't supported. + */ + meta?: Metadata; + /** + * Single `userId` which is authorized to use the token to make API requests to PubNub. + */ + authorizedUserId?: string; + }; + + /** + * Generate token with permissions. + * + * Generate time-limited access token with required permissions for resources. + */ + export type GrantTokenParameters = { + /** + * Total number of minutes for which the token is valid. + * + * The minimum allowed value is `1`. + * The maximum is `43,200` minutes (`30` days). + */ + ttl: number; + /** + * Object containing resource permissions. + */ + resources?: { + /** + * Object containing `uuid` metadata permissions. + */ + uuids?: Record; + /** + * Object containing `channel` permissions. + */ + channels?: Record; + /** + * Object containing `channel group` permissions. + */ + groups?: Record; + }; + /** + * Object containing permissions to multiple resources specified by a RegEx pattern. + */ + patterns?: { + /** + * Object containing `uuid` metadata permissions to apply to all `uuids` matching the RegEx + * pattern. + */ + uuids?: Record; + /** + * Object containing `channel` permissions to apply to all `channels` matching the RegEx + * pattern. + */ + channels?: Record; + /** + * Object containing `channel group` permissions to apply to all `channel groups` matching the + * RegEx pattern. + */ + groups?: Record; + }; + /** + * Extra metadata to be published with the request. + * + * **Important:** Values must be scalar only; `arrays` or `objects` aren't supported. + */ + meta?: Metadata; + /** + * Single `uuid` which is authorized to use the token to make API requests to PubNub. + */ + authorized_uuid?: string; + }; + + /** + * Response with generated access token. + */ + export type GrantTokenResponse = string; + + /** + * Access token for which permissions should be revoked. + */ + export type RevokeParameters = string; + + /** + * Response with revoked access token. + */ + export type RevokeTokenResponse = Record; + + /** + * Channel-specific permissions. + * + * Permissions include objects to the App Context Channel object as well. + */ + type ChannelPermissions = { + /** + * Whether `read` operations are permitted for corresponding level or not. + */ + r?: 0 | 1; + /** + * Whether `write` operations are permitted for corresponding level or not. + */ + w?: 0 | 1; + /** + * Whether `delete` operations are permitted for corresponding level or not. + */ + d?: 0 | 1; + /** + * Whether `get` operations are permitted for corresponding level or not. + */ + g?: 0 | 1; + /** + * Whether `update` operations are permitted for corresponding level or not. + */ + u?: 0 | 1; + /** + * Whether `manage` operations are permitted for corresponding level or not. + */ + m?: 0 | 1; + /** + * Whether `join` operations are permitted for corresponding level or not. + */ + j?: 0 | 1; + /** + * Duration for which permissions has been granted. + */ + ttl?: number; + }; + + /** + * Channel group-specific permissions. + */ + type ChannelGroupPermissions = { + /** + * Whether `read` operations are permitted for corresponding level or not. + */ + r?: 0 | 1; + /** + * Whether `manage` operations are permitted for corresponding level or not. + */ + m?: 0 | 1; + /** + * Duration for which permissions has been granted. + */ + ttl?: number; + }; + + /** + * App Context User-specific permissions. + */ + type UserPermissions = { + /** + * Whether `get` operations are permitted for corresponding level or not. + */ + g?: 0 | 1; + /** + * Whether `update` operations are permitted for corresponding level or not. + */ + u?: 0 | 1; + /** + * Whether `delete` operations are permitted for corresponding level or not. + */ + d?: 0 | 1; + /** + * Duration for which permissions has been granted. + */ + ttl?: number; + }; + + /** + * Common permissions audit response content. + */ + type BaseAuditResponse< + Level extends 'channel' | 'channel+auth' | 'channel-group' | 'channel-group+auth' | 'user' | 'subkey', + > = { + /** + * Permissions level. + */ + level: Level; + /** + * Subscription key at which permissions has been granted. + */ + subscribe_key: string; + /** + * Duration for which permissions has been granted. + */ + ttl?: number; + }; + + /** + * Auth keys permissions for specified `level`. + */ + type AuthKeysPermissions = { + /** + * Auth keys-based permissions for specified `level` permission. + */ + auths: Record; + }; + + /** + * Single channel permissions audit result. + */ + type ChannelPermissionsResponse = BaseAuditResponse<'channel+auth'> & { + /** + * Name of channel for which permissions audited. + */ + channel: string; + } & AuthKeysPermissions; + + /** + * Multiple channels permissions audit result. + */ + type ChannelsPermissionsResponse = BaseAuditResponse<'channel'> & { + /** + * Per-channel permissions. + */ + channels: Record>; + }; + + /** + * Single channel group permissions result. + */ + type ChannelGroupPermissionsResponse = BaseAuditResponse<'channel-group+auth'> & { + /** + * Name of channel group for which permissions audited. + */ + 'channel-group': string; + } & AuthKeysPermissions; + + /** + * Multiple channel groups permissions audit result. + */ + type ChannelGroupsPermissionsResponse = BaseAuditResponse<'channel'> & { + /** + * Per-channel group permissions. + */ + 'channel-groups': Record>; + }; + + /** + * App Context User permissions audit result. + */ + type UserPermissionsResponse = BaseAuditResponse<'user'> & { + /** + * Name of channel for which `user` permissions audited. + */ + channel: string; + } & AuthKeysPermissions; + + /** + * Global sub-key level permissions audit result. + */ + type SubKeyPermissionsResponse = BaseAuditResponse<'subkey'> & { + /** + * Per-channel permissions. + */ + channels: Record>; + /** + * Per-channel group permissions. + */ + 'channel-groups': Record>; + /** + * Per-object permissions. + */ + objects: Record>; + }; + + /** + * Response with permission information. + */ + export type PermissionsResponse = + | ChannelPermissionsResponse + | ChannelsPermissionsResponse + | ChannelGroupPermissionsResponse + | ChannelGroupsPermissionsResponse + | UserPermissionsResponse + | SubKeyPermissionsResponse; + + /** + * Audit permissions for provided auth keys / global permissions. + * + * Audit permissions on specific channel and / or channel group for the set of auth keys. + */ + export type AuditParameters = { + /** + * Name of channel for which channel-based permissions should be checked for {@link authKeys}. + */ + channel?: string; + /** + * Name of channel group for which channel group-based permissions should be checked for {@link authKeys}. + */ + channelGroup?: string; + /** + * List of auth keys for which permissions should be checked. + * + * Leave this empty to check channel / group -based permissions or global permissions. + * + * @default `[]` + */ + authKeys?: string[]; + }; + + /** + * Grant permissions for provided auth keys / global permissions. + * + * Grant permissions on specific channel and / or channel group for the set of auth keys. + */ + export type GrantParameters = { + /** + * List of channels for which permissions should be granted. + */ + channels?: string[]; + /** + * List of channel groups for which permissions should be granted. + */ + channelGroups?: string[]; + /** + * List of App Context UUID for which permissions should be granted. + */ + uuids?: string[]; + /** + * List of auth keys for which permissions should be granted on specified objects. + * + * Leave this empty to grant channel / group -based permissions or global permissions. + */ + authKeys?: string[]; + /** + * Whether `read` operations are permitted for corresponding level or not. + * + * @default `false` + */ + read?: boolean; + /** + * Whether `write` operations are permitted for corresponding level or not. + * + * @default `false` + */ + write?: boolean; + /** + * Whether `delete` operations are permitted for corresponding level or not. + * + * @default `false` + */ + delete?: boolean; + /** + * Whether `get` operations are permitted for corresponding level or not. + * + * @default `false` + */ + get?: boolean; + /** + * Whether `update` operations are permitted for corresponding level or not. + * + * @default `false` + */ + update?: boolean; + /** + * Whether `manage` operations are permitted for corresponding level or not. + * + * @default `false` + */ + manage?: boolean; + /** + * Whether `join` operations are permitted for corresponding level or not. + * + * @default `false` + */ + join?: boolean; + /** + * For how long permissions should be effective (in minutes). + * + * @default `1440` + */ + ttl?: number; + }; + } + + export namespace Time { + /** + * Service success response. + */ + export type TimeResponse = { + /** + * High-precision time when published data has been received by the PubNub service. + */ + timetoken: string; + }; + } + + export namespace Push { + /** + * Common managed channels push notification parameters. + */ + type ManagedDeviceChannels = { + /** + * Channels to register or unregister with mobile push notifications. + */ + channels: string[]; + /** + * The device ID to associate with mobile push notifications. + */ + device: string; + /** + * Starting channel for pagination. + * + * **Note:** Use the last channel from the previous page request. + */ + start?: string; + /** + * Number of channels to return for pagination. + * + * **Note:** maximum of 1000 tokens at a time. + * + * @default `500` + */ + count?: number; + }; + + /** + * List all FCM device push notification enabled channels parameters. + */ + type ListFCMDeviceChannelsParameters = Omit; + + /** + * List all APNS device push notification enabled channels parameters. + * + * @deprecated Use `APNS2`-based endpoints. + */ + type ListAPNSDeviceChannelsParameters = Omit; + + /** + * List all APNS2 device push notification enabled channels parameters. + */ + type ListAPNS2DeviceChannelsParameters = Omit; + + /** + * List all device push notification enabled channels parameters. + */ + export type ListDeviceChannelsParameters = + | ListFCMDeviceChannelsParameters + | ListAPNSDeviceChannelsParameters + | ListAPNS2DeviceChannelsParameters; + + /** + * List all device push notification enabled channels response. + */ + export type ListDeviceChannelsResponse = { + /** + * List of channels registered for device push notifications. + */ + channels: string[]; + }; + + /** + * Manage FCM device push notification enabled channels parameters. + */ + type ManageFCMDeviceChannelsParameters = ManagedDeviceChannels & { + /** + * Push Notifications gateway type. + */ + pushGateway: 'gcm'; + }; + + /** + * Manage APNS device push notification enabled channels parameters. + * + * @deprecated Use `APNS2`-based endpoints. + */ + type ManageAPNSDeviceChannelsParameters = ManagedDeviceChannels & { + /** + * Push Notifications gateway type. + */ + pushGateway: 'apns'; + }; + + /** + * Manage APNS2 device push notification enabled channels parameters. + */ + type ManageAPNS2DeviceChannelsParameters = ManagedDeviceChannels & { + /** + * Push Notifications gateway type. + */ + pushGateway: 'apns2'; + /** + * Environment within which device should manage list of channels with enabled notifications. + */ + environment?: 'development' | 'production'; + /** + * Notifications topic name (usually it is bundle identifier of application for Apple platform). + */ + topic: string; + }; + + /** + * Manage device push notification enabled channels parameters. + */ + export type ManageDeviceChannelsParameters = + | ManageFCMDeviceChannelsParameters + | ManageAPNSDeviceChannelsParameters + | ManageAPNS2DeviceChannelsParameters; + + /** + * Manage device push notification enabled channels response. + */ + export type ManageDeviceChannelsResponse = Record; + + /** + * Remove all FCM device push notification enabled channels parameters. + */ + type RemoveFCMDeviceParameters = Omit; + + /** + * Manage APNS device push notification enabled channels parameters. + * + * @deprecated Use `APNS2`-based endpoints. + */ + type RemoveAPNSDeviceParameters = Omit; + + /** + * Manage APNS2 device push notification enabled channels parameters. + */ + type RemoveAPNS2DeviceParameters = Omit; + + /** + * Remove all device push notification enabled channels parameters. + */ + export type RemoveDeviceParameters = + | RemoveFCMDeviceParameters + | RemoveAPNSDeviceParameters + | RemoveAPNS2DeviceParameters; + + /** + * Remove all device push notification enabled channels response. + */ + export type RemoveDeviceResponse = Record; + } +} + +export = PubNub; diff --git a/lib/types/models/Cursor.d.ts b/lib/types/models/Cursor.d.ts deleted file mode 100644 index 20ff1df3a..000000000 --- a/lib/types/models/Cursor.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Subscription cursor. - * - * Cursor used by {@link PubNub} client as reference point in time after which new real-time events should be - * received and processed. - */ -export type Cursor = { - /** - * PubNub high-precision timestamp. - */ - readonly timetoken: string; - /** - * Data center region for which `timetoken` has been generated. - * - * **Note:** This is an _optional_ value and can be set to `0` if not needed. - */ - readonly region?: number; -}; diff --git a/lib/types/node/components/configuration.d.ts b/lib/types/node/components/configuration.d.ts deleted file mode 100644 index 808670572..000000000 --- a/lib/types/node/components/configuration.d.ts +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Node.js specific {@link PubNub} client configuration module. - */ -import { UserConfiguration } from '../../core/interfaces/configuration'; -import { TransportKeepAlive } from '../../core/interfaces/transport'; -import { Payload } from '../../core/types/api'; -import { CryptoModule } from '../../core/interfaces/crypto-module'; -/** - * NodeJS platform PubNub client configuration. - */ -export type PubNubConfiguration = UserConfiguration & { - /** - * Set a custom parameters for setting your connection `keepAlive` if this is set to `true`. - */ - keepAliveSettings?: TransportKeepAlive; - /** - * The cryptography module used for encryption and decryption of messages and files. Takes the - * {@link cipherKey} and {@link useRandomIVs} parameters as arguments. - * - * For more information, refer to the - * {@link /docs/sdks/javascript/api-reference/configuration#cryptomodule|cryptoModule} section. - * - * @default `not set` - */ - cryptoModule?: CryptoModule; - /** - * If passed, will encrypt the payloads. - * - * @deprecated Pass it to {@link cryptoModule} instead. - */ - cipherKey?: string; - /** - * When `true` the initialization vector (IV) is random for all requests (not just for file - * upload). - * When `false` the IV is hard-coded for all requests except for file upload. - * - * @default `true` - * - * @deprecated Pass it to {@link cryptoModule} instead. - */ - useRandomIVs?: boolean; - /** - * Custom data encryption method. - * - * @deprecated Instead use {@link cryptoModule} for data encryption. - */ - customEncrypt?: (data: string | Payload) => string; - /** - * Custom data decryption method. - * - * @deprecated Instead use {@link cryptoModule} for data decryption. - */ - customDecrypt?: (data: string) => string; -}; diff --git a/lib/types/node/index.d.ts b/lib/types/node/index.d.ts deleted file mode 100644 index 10e340600..000000000 --- a/lib/types/node/index.d.ts +++ /dev/null @@ -1,41 +0,0 @@ -/// -/// -import { ProxyAgentOptions } from 'proxy-agent'; -import { Readable } from 'stream'; -import { Buffer } from 'buffer'; -import type { CryptoModule as CryptoModuleType } from '../crypto/modules/NodeCryptoModule/nodeCryptoModule'; -import PubNubFile, { PubNubFileParameters } from '../file/modules/node'; -import { PubNubConfiguration } from './components/configuration'; -import { PubNubFileConstructor } from '../core/types/file'; -import { PubNubCore } from '../core/pubnub-common'; -/** - * PubNub client for Node.js platform. - */ -declare class PubNub extends PubNubCore { - /** - * Data encryption / decryption module constructor. - */ - static CryptoModule: typeof CryptoModuleType; - /** - * PubNub File constructor. - */ - File: PubNubFileConstructor; - /** - * Create and configure PubNub client core. - * - * @param configuration - User-provided PubNub client configuration. - * - * @returns Configured and ready to use PubNub client. - */ - constructor(configuration: PubNubConfiguration); - /** - * Update request proxy configuration. - * - * @param configuration - Updated request proxy configuration. - * - * @throws An error if {@link PubNub} client already configured to use `keepAlive`. - * `keepAlive` and `proxy` can't be used simultaneously. - */ - setProxy(configuration?: ProxyAgentOptions): void; -} -export = PubNub; diff --git a/lib/types/react_native/configuration.d.ts b/lib/types/react_native/configuration.d.ts deleted file mode 100644 index a17ce3370..000000000 --- a/lib/types/react_native/configuration.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { UserConfiguration } from '../core/interfaces/configuration'; -/** - * React Native platform PubNub client configuration. - */ -export type PubNubConfiguration = UserConfiguration; diff --git a/lib/types/react_native/index.d.ts b/lib/types/react_native/index.d.ts deleted file mode 100644 index 696370af5..000000000 --- a/lib/types/react_native/index.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import 'react-native-url-polyfill/auto'; -import { PubNubFileParameters } from '../file/modules/react-native'; -import { PubNubConfiguration } from './configuration'; -import { PubNubCore } from '../core/pubnub-common'; -/** - * PubNub client for React Native platform. - */ -export default class PubNub extends PubNubCore { - /** - * Create and configure PubNub client core. - * - * @param configuration - User-provided PubNub client configuration. - * - * @returns Configured and ready to use PubNub client. - */ - constructor(configuration: PubNubConfiguration); -} diff --git a/lib/types/transport/middleware.d.ts b/lib/types/transport/middleware.d.ts deleted file mode 100644 index 85c6e2861..000000000 --- a/lib/types/transport/middleware.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Common PubNub Network Provider middleware module. - * - * @internal - */ -export {}; diff --git a/lib/types/transport/node-transport.d.ts b/lib/types/transport/node-transport.d.ts deleted file mode 100644 index d6c846809..000000000 --- a/lib/types/transport/node-transport.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Node.js Transport provider module. - * - * @internal - */ -export {}; diff --git a/lib/types/transport/web-react-native-transport.d.ts b/lib/types/transport/web-react-native-transport.d.ts deleted file mode 100644 index b8692fa09..000000000 --- a/lib/types/transport/web-react-native-transport.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Common browser and React Native Transport provider module. - * - * @internal - */ -export {}; diff --git a/package-lock.json b/package-lock.json index ac8a7f405..1c119fc3d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -35,7 +35,6 @@ "@types/cucumber": "^7.0.0", "@types/expect": "^24.3.0", "@types/lil-uuid": "^0.1.3", - "@types/minimist": "^1.2.5", "@types/mocha": "^9.1.0", "@types/nock": "^9.3.1", "@types/node-fetch": "^2.6.11", @@ -47,6 +46,7 @@ "chai": "^4.4.1", "chai-as-promised": "^7.1.1", "chai-nock": "^1.2.0", + "commander": "^12.1.0", "cucumber-pretty": "^6.0.1", "cucumber-tsflow": "^4.4.4", "es6-shim": "^0.35.8", @@ -61,7 +61,6 @@ "karma-sinon-chai": "^2.0.2", "karma-sourcemap-loader": "^0.3.7", "karma-spec-reporter": "0.0.32", - "minimist": "^1.2.8", "mocha": "10.4.0", "nock": "^14.0.0-beta.5", "prettier": "^3.2.5", @@ -2411,6 +2410,16 @@ "regexp-match-indices": "1.0.2" } }, + "node_modules/@cucumber/cucumber/node_modules/commander": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-10.0.1.tgz", + "integrity": "sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + } + }, "node_modules/@cucumber/gherkin": { "version": "28.0.0", "resolved": "https://registry.npmjs.org/@cucumber/gherkin/-/gherkin-28.0.0.tgz", @@ -4791,13 +4800,6 @@ "integrity": "sha512-UozexIWHw7bnQtbfdMqv1u82JmMl63t7lrCXpX6kByNH1F77j+Cdeqx28djuveoFvan9YUYrvK+ys1/hKIOgeA==", "dev": true }, - "node_modules/@types/minimist": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/@types/minimist/-/minimist-1.2.5.tgz", - "integrity": "sha512-hov8bUuiLiyFPGyFPE1lwWhmzYbirOXQNNo40+y3zow8aFVTeyn3VWL0VFFfdNddA8S4Vf0Tc062rzyNr7Paag==", - "dev": true, - "license": "MIT" - }, "node_modules/@types/mocha": { "version": "9.1.1", "resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-9.1.1.tgz", @@ -6321,12 +6323,13 @@ "peer": true }, "node_modules/commander": { - "version": "10.0.1", - "resolved": "https://registry.npmjs.org/commander/-/commander-10.0.1.tgz", - "integrity": "sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug==", + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", + "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", "dev": true, + "license": "MIT", "engines": { - "node": ">=14" + "node": ">=18" } }, "node_modules/commondir": { diff --git a/package.json b/package.json index 2aa6e3621..abedce5d2 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,8 @@ "scripts": { "build": "npm run build:node && npm run build:web", "build:web": "rollup -c ./rollup.config.js --bundleConfigAsCjs", - "build:node": "tsc -p tsconfig.json", + "build:node": "tsc -p tsconfig.json && npm run build:node-types", + "build:node-types": "ts-node ./.scripts/types-aggregate.ts --ts-config=./tsconfig.json --package=PubNub --working-dir=./lib/types --input=./lib/types/node/index.d.ts --output=./lib/types", "test": "npm run test:web && npm run test:node", "test:web": "karma start karma/web.config.cjs", "test:node": "TS_NODE_PROJECT='./tsconfig.json' mocha --project tsconfig.mocha.json", @@ -32,7 +33,7 @@ "contract:test-access-beta": "cucumber-js --require dist/cucumber dist/contract/contract/features --tags '@featureSet=access and not @na=js and @beta'" }, "main": "./lib/node/index.js", - "types": "./lib/types/node/index.d.ts", + "types": "./lib/types/index.d.ts", "react-native": "./lib/react_native/index.js", "metro": "./lib/react_native/index.js", "nativescript": "./lib/nativescript/index.js", @@ -79,7 +80,6 @@ "@types/cucumber": "^7.0.0", "@types/expect": "^24.3.0", "@types/lil-uuid": "^0.1.3", - "@types/minimist": "^1.2.5", "@types/mocha": "^9.1.0", "@types/nock": "^9.3.1", "@types/node-fetch": "^2.6.11", @@ -91,6 +91,7 @@ "chai": "^4.4.1", "chai-as-promised": "^7.1.1", "chai-nock": "^1.2.0", + "commander": "^12.1.0", "cucumber-pretty": "^6.0.1", "cucumber-tsflow": "^4.4.4", "es6-shim": "^0.35.8", @@ -105,7 +106,6 @@ "karma-sinon-chai": "^2.0.2", "karma-sourcemap-loader": "^0.3.7", "karma-spec-reporter": "0.0.32", - "minimist": "^1.2.8", "mocha": "10.4.0", "nock": "^14.0.0-beta.5", "prettier": "^3.2.5", diff --git a/src/core/components/configuration.ts b/src/core/components/configuration.ts index ae8cb0f14..3108ce950 100644 --- a/src/core/components/configuration.ts +++ b/src/core/components/configuration.ts @@ -5,7 +5,7 @@ */ import { ExtendedConfiguration, PlatformConfiguration, PrivateClientConfiguration } from '../interfaces/configuration'; -import { CryptoModule, CryptorConfiguration } from '../interfaces/crypto-module'; +import { ICryptoModule, CryptorConfiguration } from '../interfaces/crypto-module'; import { PubNubFileConstructor, PubNubFileInterface } from '../types/file'; import uuidGenerator from './uuid'; import { Payload } from '../types/api'; @@ -30,7 +30,7 @@ const USE_RANDOM_INITIALIZATION_VECTOR = true; * * @internal */ -type SetupCryptoModule = (configuration: CryptorConfiguration) => CryptoModule | undefined; +type SetupCryptoModule = (configuration: CryptorConfiguration) => ICryptoModule | undefined; /** * Internal state of the {@link PrivateClientConfiguration} to store temporarily information. @@ -60,7 +60,7 @@ type PrivateConfigurationFields = { /** * Configured crypto module. */ - _cryptoModule?: CryptoModule; + _cryptoModule?: ICryptoModule; /** * Currently used data encryption / decryption key. @@ -72,7 +72,7 @@ type PrivateConfigurationFields = { * Create {@link PubNub} client private configuration object. * * @param base - User- and platform-provided configuration. - * @param setupCryptoModule - Platform-provided {@link CryptoModule} configuration block. + * @param setupCryptoModule - Platform-provided {@link ICryptoModule} configuration block. * * @returns `PubNub` client private configuration. * @@ -142,7 +142,7 @@ export const makeConfiguration = ( customDecrypt: this.getCustomDecrypt(), }); }, - getCryptoModule(): CryptoModule | undefined { + getCryptoModule(): ICryptoModule | undefined { return this._cryptoModule; }, getUseRandomIVs(): boolean | undefined { diff --git a/src/core/components/push_payload.ts b/src/core/components/push_payload.ts index c7fbf1d00..e74f2ba23 100644 --- a/src/core/components/push_payload.ts +++ b/src/core/components/push_payload.ts @@ -595,7 +595,7 @@ export class APNSNotificationPayload extends BaseNotificationPayload { } /** - * Message payload for Firebase Clouse Messaging service. + * Message payload for Firebase Cloud Messaging service. */ export class FCMNotificationPayload extends BaseNotificationPayload { /** diff --git a/src/core/components/subscription-manager.ts b/src/core/components/subscription-manager.ts index 696e4edb0..dc9ee44bf 100644 --- a/src/core/components/subscription-manager.ts +++ b/src/core/components/subscription-manager.ts @@ -5,7 +5,7 @@ */ import { Payload, ResultCallback, Status, StatusCallback, StatusEvent } from '../types/api'; -import { RequestParameters as SubscribeRequestParameters } from '../endpoints/subscribe'; +import { SubscribeRequestParameters as SubscribeRequestParameters } from '../endpoints/subscribe'; import { PrivateClientConfiguration } from '../interfaces/configuration'; import { HeartbeatRequest } from '../endpoints/presence/heartbeat'; import { ReconnectionManager } from './reconnection_manager'; diff --git a/src/core/endpoints/fetch_messages.ts b/src/core/endpoints/fetch_messages.ts index 4e7a36bc3..0b42fd62c 100644 --- a/src/core/endpoints/fetch_messages.ts +++ b/src/core/endpoints/fetch_messages.ts @@ -7,7 +7,7 @@ import { createValidationError, PubNubError } from '../../errors/pubnub-error'; import { TransportResponse } from '../types/transport-response'; import { PubNubAPIError } from '../../errors/pubnub-api-error'; -import { CryptoModule } from '../interfaces/crypto-module'; +import { ICryptoModule } from '../interfaces/crypto-module'; import { AbstractRequest } from '../components/request'; import * as FileSharing from '../types/api/file-sharing'; import RequestOperation from '../constants/operations'; @@ -69,7 +69,7 @@ type RequestParameters = History.FetchMessagesParameters & { /** * Published data encryption module. */ - crypto?: CryptoModule; + crypto?: ICryptoModule; /** * File download Url generation function. diff --git a/src/core/endpoints/file_upload/download_file.ts b/src/core/endpoints/file_upload/download_file.ts index 16a021278..90055d25d 100644 --- a/src/core/endpoints/file_upload/download_file.ts +++ b/src/core/endpoints/file_upload/download_file.ts @@ -6,7 +6,7 @@ import { PubNubBasicFileParameters, PubNubFileConstructor, PubNubFileInterface } from '../../types/file'; import { TransportResponse } from '../../types/transport-response'; -import { CryptoModule } from '../../interfaces/crypto-module'; +import { ICryptoModule } from '../../interfaces/crypto-module'; import { Cryptography } from '../../interfaces/cryptography'; import { AbstractRequest } from '../../components/request'; import * as FileSharing from '../../types/api/file-sharing'; @@ -36,7 +36,7 @@ type RequestParameters = FileSharing.DownloadFileParameters & { /** * Send file decryption module. */ - crypto?: CryptoModule; + crypto?: ICryptoModule; /** * Legacy cryptography module. diff --git a/src/core/endpoints/file_upload/publish_file.ts b/src/core/endpoints/file_upload/publish_file.ts index 385f2c484..ae2699445 100644 --- a/src/core/endpoints/file_upload/publish_file.ts +++ b/src/core/endpoints/file_upload/publish_file.ts @@ -6,7 +6,7 @@ import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import { TransportResponse } from '../../types/transport-response'; -import { CryptoModule } from '../../interfaces/crypto-module'; +import { ICryptoModule } from '../../interfaces/crypto-module'; import { AbstractRequest } from '../../components/request'; import * as FileSharing from '../../types/api/file-sharing'; import RequestOperation from '../../constants/operations'; @@ -42,7 +42,7 @@ type RequestParameters = FileSharing.PublishFileMessageParameters & { /** * Published data encryption module. */ - crypto?: CryptoModule; + crypto?: ICryptoModule; }; /** diff --git a/src/core/endpoints/file_upload/send_file.ts b/src/core/endpoints/file_upload/send_file.ts index aa5ddd28b..177dcba73 100644 --- a/src/core/endpoints/file_upload/send_file.ts +++ b/src/core/endpoints/file_upload/send_file.ts @@ -6,7 +6,7 @@ import { PubNubFileConstructor, PubNubFileInterface } from '../../types/file'; import { GenerateFileUploadUrlRequest } from './generate_upload_url'; -import { CryptoModule } from '../../interfaces/crypto-module'; +import { ICryptoModule } from '../../interfaces/crypto-module'; import { Cryptography } from '../../interfaces/cryptography'; import { AbstractRequest } from '../../components/request'; import * as FileSharing from '../../types/api/file-sharing'; @@ -67,7 +67,7 @@ type RequestParameters = FileSharing.SendFileParameters { - constructor(protected readonly parameters: RequestParameters) { + constructor(protected readonly parameters: SubscribeRequestParameters) { super({ cancellable: true }); // Apply default request parameters. diff --git a/src/core/interfaces/configuration.ts b/src/core/interfaces/configuration.ts index a062b7a75..2acb0186f 100644 --- a/src/core/interfaces/configuration.ts +++ b/src/core/interfaces/configuration.ts @@ -4,7 +4,7 @@ import { PubNubFileConstructor, PubNubFileInterface } from '../types/file'; import { RequestRetryPolicy } from '../../event-engine/core/retryPolicy'; -import { CryptoModule } from './crypto-module'; +import { ICryptoModule } from './crypto-module'; import { KeySet, Payload } from '../types/api'; import { PubNubError } from '../../errors/pubnub-error'; @@ -402,7 +402,7 @@ export type PlatformConfiguration = { * * @default `not set` */ - cryptoModule?: CryptoModule; + cryptoModule?: ICryptoModule; /** * Platform-specific file representation @@ -571,7 +571,7 @@ export interface PrivateClientConfiguration * * @returns Data processing crypto module (if set). */ - getCryptoModule(): CryptoModule | undefined; + getCryptoModule(): ICryptoModule | undefined; /** * Retrieve user's presence timeout. @@ -741,7 +741,7 @@ export const setDefaults = (configuration: UserConfiguration): ExtendedConfigura let announceFailedHeartbeats = ANNOUNCE_HEARTBEAT_FAILURE; let fileUploadPublishRetryLimit = FILE_PUBLISH_RETRY_LIMIT; let dedupeOnSubscribe = DEDUPE_ON_SUBSCRIBE; - const maximumCacheSize = DEDUPE_CACHE_SIZE; + let maximumCacheSize = DEDUPE_CACHE_SIZE; let useRequestId = USE_REQUEST_ID; // @ts-expect-error Not documented legacy configuration options. @@ -750,6 +750,12 @@ export const setDefaults = (configuration: UserConfiguration): ExtendedConfigura dedupeOnSubscribe = configurationCopy.dedupeOnSubscribe; } + // @ts-expect-error Not documented legacy configuration options. + if (configurationCopy.maximumCacheSize !== undefined && typeof configurationCopy.maximumCacheSize === 'number') { + // @ts-expect-error Not documented legacy configuration options. + maximumCacheSize = configurationCopy.maximumCacheSize; + } + // @ts-expect-error Not documented legacy configuration options. if (configurationCopy.useRequestId !== undefined && typeof configurationCopy.useRequestId === 'boolean') { // @ts-expect-error Not documented legacy configuration options. diff --git a/src/core/interfaces/crypto-module.ts b/src/core/interfaces/crypto-module.ts index 21c0a05ea..017a3d67d 100644 --- a/src/core/interfaces/crypto-module.ts +++ b/src/core/interfaces/crypto-module.ts @@ -49,7 +49,7 @@ export type CryptorConfiguration = { /** * Base crypto module interface. */ -export interface CryptoModule { +export interface ICryptoModule { // -------------------------------------------------------- // --------------------- Encryption ----------------------- // -------------------------------------------------------- @@ -109,7 +109,7 @@ export interface CryptoModule { // endregion } -export abstract class AbstractCryptoModule implements CryptoModule { +export abstract class AbstractCryptoModule implements ICryptoModule { /** * `String` to {@link ArrayBuffer} response decoder. * @@ -142,7 +142,7 @@ export abstract class AbstractCryptoModule implements CryptoModule { * * @throws Error if `config.cipherKey` not set. */ - static legacyCryptoModule(config: CryptorConfiguration): CryptoModule { + static legacyCryptoModule(config: CryptorConfiguration): ICryptoModule { throw new Error('Should be implemented by concrete crypto module implementation.'); } @@ -156,7 +156,7 @@ export abstract class AbstractCryptoModule implements CryptoModule { * * @throws Error if `config.cipherKey` not set. */ - static aesCbcCryptoModule(config: CryptorConfiguration): CryptoModule { + static aesCbcCryptoModule(config: CryptorConfiguration): ICryptoModule { throw new Error('Should be implemented by concrete crypto module implementation.'); } // endregion @@ -174,7 +174,7 @@ export abstract class AbstractCryptoModule implements CryptoModule { /** * Encrypt data. * - * @param data - Data which should be encrypted using {@link CryptoModule}. + * @param data - Data which should be encrypted using {@link ICryptoModule}. * * @returns Data encryption result. */ @@ -203,7 +203,7 @@ export abstract class AbstractCryptoModule implements CryptoModule { /** * Encrypt data. * - * @param data - Dta which should be encrypted using `CryptoModule`. + * @param data - Dta which should be encrypted using `ICryptoModule`. * * @returns Data decryption result. */ diff --git a/src/core/pubnub-common.ts b/src/core/pubnub-common.ts index aee851af6..ae0d2b568 100644 --- a/src/core/pubnub-common.ts +++ b/src/core/pubnub-common.ts @@ -43,7 +43,7 @@ import * as Publish from './endpoints/publish'; import * as Signal from './endpoints/signal'; // endregion // region Subscription -import { RequestParameters as SubscribeRequestParameters, SubscribeRequest } from './endpoints/subscribe'; +import { SubscribeRequestParameters as SubscribeRequestParameters, SubscribeRequest } from './endpoints/subscribe'; import { ReceiveMessagesSubscribeRequest } from './endpoints/subscriptionUtils/receiveMessages'; import { HandshakeSubscribeRequest } from './endpoints/subscriptionUtils/handshake'; import * as Subscription from './types/api/subscription'; @@ -2847,8 +2847,7 @@ export class PubNubCore< * @param callback - Request completion handler callback. * * @deprecated Use {@link PubNubCore#objects.removeMemberships} or {@link PubNubCore#objects.removeChannelMembers} - * methods instead - * from `objects` API group.. + * methods instead from `objects` API group. */ public removeMemberships< RelationCustom extends AppContext.CustomData = AppContext.CustomData, @@ -2869,8 +2868,7 @@ export class PubNubCore< * @returns Asynchronous memberships modification response. * * @deprecated Use {@link PubNubCore#objects.removeMemberships} or {@link PubNubCore#objects.removeChannelMembers} - * methods instead - * from `objects` API group.. + * methods instead from `objects` API group. */ public async removeMemberships< RelationCustom extends AppContext.CustomData = AppContext.CustomData, @@ -2888,8 +2886,7 @@ export class PubNubCore< * @returns Asynchronous memberships modification response or `void` in case if `callback` provided. * * @deprecated Use {@link PubNubCore#objects.removeMemberships} or {@link PubNubCore#objects.removeChannelMembers} - * methods instead - * from `objects` API group.. + * methods instead from `objects` API group. */ public async removeMemberships< RelationCustom extends AppContext.CustomData = AppContext.CustomData, diff --git a/src/core/types/api/file-sharing.ts b/src/core/types/api/file-sharing.ts index 90200f69a..809da4934 100644 --- a/src/core/types/api/file-sharing.ts +++ b/src/core/types/api/file-sharing.ts @@ -129,7 +129,7 @@ export type SendFileResponse = PublishFileMessageResponse & { /** * Unique file identifier. * - * Unique file identifier and it's {@link name} can be used to download file from the channel + * Unique file identifier, and it's {@link name} can be used to download file from the channel * later. */ id: string; @@ -387,7 +387,7 @@ export type FileUrlParameters = { /** * Unique file identifier. * - * Unique file identifier and it's {@link name} can be used to download file from the channel + * Unique file identifier, and it's {@link name} can be used to download file from the channel * later. */ id: string; @@ -426,7 +426,7 @@ export type DeleteFileParameters = { /** * Unique file identifier. * - * Unique file identifier and it's {@link name} can be used to download file from the channel + * Unique file identifier, and it's {@link name} can be used to download file from the channel * later. */ id: string; diff --git a/src/core/types/api/history.ts b/src/core/types/api/history.ts index 6bea6b7eb..dac984183 100644 --- a/src/core/types/api/history.ts +++ b/src/core/types/api/history.ts @@ -141,7 +141,7 @@ export type Actions = { * High-precision PubNub timetoken with time when {@link uuid} reacted on message. */ actionTimetoken: string; - }; + }[]; }; }; diff --git a/src/core/types/api/index.ts b/src/core/types/api/index.ts index 736194c1f..0f85c95f8 100644 --- a/src/core/types/api/index.ts +++ b/src/core/types/api/index.ts @@ -136,8 +136,6 @@ export type StatusEvent = { /** * {@link TransportRequest} query parameter type. - * - * @internal */ export type Query = Record; @@ -148,4 +146,10 @@ export type Query = Record; * * generic messages and signals content, * * published message metadata. */ -export type Payload = string | number | boolean | { [key: string]: Payload | null } | Payload[]; +export type Payload = + | string + | number + | boolean + | { toJSON: () => Payload } + | { [key: string]: Payload | null } + | Payload[]; diff --git a/src/core/types/api/message-action.ts b/src/core/types/api/message-action.ts index 125d3a3e0..1eabc3d84 100644 --- a/src/core/types/api/message-action.ts +++ b/src/core/types/api/message-action.ts @@ -20,7 +20,7 @@ export type MessageAction = { /** * Timetoken of when message reaction has been added. * - * **Note:** This token required when it will be required to remove raction. + * **Note:** This token required when it will be required to remove reaction. */ actionTimetoken: string; diff --git a/src/core/types/api/push-notifications.ts b/src/core/types/api/push-notifications.ts index 8dd0dadcf..a0c1541e7 100644 --- a/src/core/types/api/push-notifications.ts +++ b/src/core/types/api/push-notifications.ts @@ -15,7 +15,7 @@ type DevicePush = { /** * Push Notifications gateway to use. * - * **Important:** Depends from the source of `device` token and can be `apns2` (for token + * **Important:** Depends on from the source of `device` token and can be `apns2` (for token * provided during device registration using Apple's framework) or `gcm` (when used Firebase * or similar framework to receive token). */ diff --git a/src/core/types/api/subscription.ts b/src/core/types/api/subscription.ts index 5cdab91fe..a7323ca96 100644 --- a/src/core/types/api/subscription.ts +++ b/src/core/types/api/subscription.ts @@ -1,5 +1,5 @@ import { - RequestParameters as SubscribeRequestParameters, + SubscribeRequestParameters, VSPMembershipObjectData, AppContextObjectData, MessageActionData, @@ -302,6 +302,8 @@ type FileEvent = { /** * Cancelable subscribe request parameters. + * + * @internal */ export type CancelableSubscribeParameters = Omit< SubscribeRequestParameters, diff --git a/src/crypto/modules/NodeCryptoModule/ICryptor.ts b/src/crypto/modules/NodeCryptoModule/ICryptor.ts index 63860b300..81cfde5b6 100644 --- a/src/crypto/modules/NodeCryptoModule/ICryptor.ts +++ b/src/crypto/modules/NodeCryptoModule/ICryptor.ts @@ -3,7 +3,7 @@ */ /** - * Data encrypted by {@link CryptoModule}. + * Data encrypted by {@link NodeCryptoModule}. */ export type EncryptedDataType = { /** @@ -18,7 +18,7 @@ export type EncryptedDataType = { }; /** - * {@link Readable} stream encrypted by {@link CryptoModule}. + * {@link Readable} stream encrypted by {@link NodeCryptoModule}. */ export type EncryptedStream = { /** diff --git a/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts index baab0e053..220dc590d 100644 --- a/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts +++ b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts @@ -14,6 +14,7 @@ import { EncryptedDataType, ICryptor } from './ICryptor'; import { ILegacyCryptor } from './ILegacyCryptor'; import AesCbcCryptor from './aesCbcCryptor'; import LegacyCryptor from './legacyCryptor'; +import { Payload } from '../../../core/types/api'; /** * Re-export bundled cryptors. @@ -28,7 +29,7 @@ type CryptorType = ICryptor | ILegacyCryptor; /** * CryptoModule for Node.js platform. */ -export class CryptoModule extends AbstractCryptoModule { +export class NodeCryptoModule extends AbstractCryptoModule { /** * {@link LegacyCryptor|Legacy} cryptor identifier. */ @@ -85,8 +86,8 @@ export class CryptoModule extends AbstractCryptoModule { encrypt(data: ArrayBuffer | string) { // Encrypt data. const encrypted = - data instanceof ArrayBuffer && this.defaultCryptor.identifier === CryptoModule.LEGACY_IDENTIFIER - ? (this.defaultCryptor as ILegacyCryptor).encrypt(CryptoModule.decoder.decode(data)) + data instanceof ArrayBuffer && this.defaultCryptor.identifier === NodeCryptoModule.LEGACY_IDENTIFIER + ? (this.defaultCryptor as ILegacyCryptor).encrypt(NodeCryptoModule.decoder.decode(data)) : (this.defaultCryptor as ICryptor).encrypt(data); if (!encrypted.metadata) return encrypted.data; @@ -96,7 +97,7 @@ export class CryptoModule extends AbstractCryptoModule { // Write encrypted data payload content. const encryptedData = typeof encrypted.data === 'string' - ? CryptoModule.encoder.encode(encrypted.data).buffer + ? NodeCryptoModule.encoder.encode(encrypted.data).buffer : encrypted.data.buffer.slice(encrypted.data.byteOffset, encrypted.data.byteOffset + encrypted.data.length); return this.concatArrayBuffer(headerData, encryptedData); @@ -117,7 +118,7 @@ export class CryptoModule extends AbstractCryptoModule { name: file.name, mimeType: 'application/octet-stream', data: Buffer.from( - typeof encryptedData === 'string' ? CryptoModule.encoder.encode(encryptedData) : encryptedData, + typeof encryptedData === 'string' ? NodeCryptoModule.encoder.encode(encryptedData) : encryptedData, ), }); } @@ -156,7 +157,7 @@ export class CryptoModule extends AbstractCryptoModule { // -------------------------------------------------------- // region Decryption - decrypt(data: ArrayBuffer | string) { + decrypt(data: ArrayBuffer | string): ArrayBuffer | Payload | null { const encryptedData = Buffer.from(typeof data === 'string' ? decode(data) : data); const header = CryptorHeader.tryParse( encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length), @@ -188,7 +189,7 @@ export class CryptoModule extends AbstractCryptoModule { * If It's legacy one then redirect it. * (as long as we support legacy need to check on instance type) */ - if (cryptor?.identifier === CryptoModule.LEGACY_IDENTIFIER) + if (cryptor?.identifier === NodeCryptoModule.LEGACY_IDENTIFIER) return (cryptor as ILegacyCryptor).decryptFile(file, File); return File.create({ @@ -221,7 +222,7 @@ export class CryptoModule extends AbstractCryptoModule { * @internal */ private getLegacyCryptor(): ILegacyCryptor | undefined { - return this.getCryptorFromId(CryptoModule.LEGACY_IDENTIFIER) as ILegacyCryptor; + return this.getCryptorFromId(NodeCryptoModule.LEGACY_IDENTIFIER) as ILegacyCryptor; } /** @@ -438,7 +439,7 @@ class CryptorHeader { let version = null; if (encryptedData.byteLength >= 4) { sentinel = encryptedData.slice(0, 4); - if (!this.isSentinel(sentinel)) return CryptoModule.LEGACY_IDENTIFIER; + if (!this.isSentinel(sentinel)) return NodeCryptoModule.LEGACY_IDENTIFIER; } if (encryptedData.byteLength >= 5) version = encryptedDataView.getInt8(4); diff --git a/src/errors/pubnub-error.ts b/src/errors/pubnub-error.ts index 61b10f26a..b3fee4d9b 100644 --- a/src/errors/pubnub-error.ts +++ b/src/errors/pubnub-error.ts @@ -1,7 +1,5 @@ /** * PubNub operation error module. - * - * @internal */ import { Status } from '../core/types/api'; diff --git a/src/node/components/configuration.ts b/src/node/components/configuration.ts index 00f4a88dc..ee6f8731c 100644 --- a/src/node/components/configuration.ts +++ b/src/node/components/configuration.ts @@ -9,7 +9,7 @@ import { } from '../../core/interfaces/configuration'; import { TransportKeepAlive } from '../../core/interfaces/transport'; import { Payload } from '../../core/types/api'; -import { CryptoModule } from '../../core/interfaces/crypto-module'; +import { ICryptoModule } from '../../core/interfaces/crypto-module'; // -------------------------------------------------------- // ----------------------- Defaults ----------------------- @@ -40,7 +40,7 @@ export type PubNubConfiguration = UserConfiguration & { * * @default `not set` */ - cryptoModule?: CryptoModule; + cryptoModule?: ICryptoModule; // region Deprecated parameters /** diff --git a/src/node/index.ts b/src/node/index.ts index 8681242bf..1ba9a65a2 100755 --- a/src/node/index.ts +++ b/src/node/index.ts @@ -3,8 +3,8 @@ import CborReader from 'cbor-sync'; import { Readable } from 'stream'; import { Buffer } from 'buffer'; -import { CryptoModule, LegacyCryptor, AesCbcCryptor } from '../crypto/modules/NodeCryptoModule/nodeCryptoModule'; -import type { CryptoModule as CryptoModuleType } from '../crypto/modules/NodeCryptoModule/nodeCryptoModule'; +import { NodeCryptoModule, LegacyCryptor, AesCbcCryptor } from '../crypto/modules/NodeCryptoModule/nodeCryptoModule'; +import type { NodeCryptoModule as CryptoModuleType } from '../crypto/modules/NodeCryptoModule/nodeCryptoModule'; import PubNubFile, { PubNubFileParameters } from '../file/modules/node'; import { CryptorConfiguration } from '../core/interfaces/crypto-module'; @@ -31,7 +31,8 @@ class PubNub extends PubNubCore | [Response, ArrayBuffer] => response.arrayBuffer().then((arrayBuffer) => [response, arrayBuffer]), ) diff --git a/src/web/components/configuration.ts b/src/web/components/configuration.ts index 06e65c335..4f0709836 100644 --- a/src/web/components/configuration.ts +++ b/src/web/components/configuration.ts @@ -3,7 +3,7 @@ import { ExtendedConfiguration, setDefaults as setBaseDefaults, } from '../../core/interfaces/configuration'; -import { CryptoModule } from '../../core/interfaces/crypto-module'; +import { ICryptoModule } from '../../core/interfaces/crypto-module'; // -------------------------------------------------------- // ----------------------- Defaults ----------------------- @@ -77,7 +77,7 @@ export type PubNubConfiguration = UserConfiguration & { * * @default `not set` */ - cryptoModule?: CryptoModule; + cryptoModule?: ICryptoModule; // region Deprecated parameters /** diff --git a/test/integration/components/crypto.test.ts b/test/integration/components/crypto.test.ts index d7373805c..073558bd8 100644 --- a/test/integration/components/crypto.test.ts +++ b/test/integration/components/crypto.test.ts @@ -25,7 +25,7 @@ describe('components/crypto useRandomIVs', () => { expect(decrypted).to.deep.equal(data, JSON.stringify(decrypted)); }); - it('should be able to encrypt and decrypt a message with CryptoModule', () => { + it('should be able to encrypt and decrypt a message with ICryptoModule', () => { const pubnub = new PubNub({ subscribeKey: 'demo-36', publishKey: 'demo-36', diff --git a/test/integration/components/subscription_manager.test.ts b/test/integration/components/subscription_manager.test.ts index d68c554f5..802690bf6 100644 --- a/test/integration/components/subscription_manager.test.ts +++ b/test/integration/components/subscription_manager.test.ts @@ -10,6 +10,7 @@ import utils from '../../utils'; describe('#components/subscription_manager', () => { let pubnub: PubNub; + let pubnubWithLimitedDeduplicationQueue: PubNub; let pubnubWithPassingHeartbeats: PubNub; let pubnubWithLimitedQueue: PubNub; let pubnubWithCrypto: PubNub; @@ -34,6 +35,18 @@ describe('#components/subscription_manager', () => { autoNetworkDetection: false, heartbeatInterval: 149, }); + pubnubWithLimitedDeduplicationQueue = new PubNub({ + subscribeKey: 'mySubKey', + publishKey: 'myPublishKey', + origin: 'ps.pndsn.com', + uuid: 'myUUID', + // @ts-expect-error Force override default value. + useRequestId: false, + autoNetworkDetection: false, + maximumCacheSize: 1, + dedupeOnSubscribe: true, + heartbeatInterval: 149, + }); pubnubWithPassingHeartbeats = new PubNub({ subscribeKey: 'mySubKey', publishKey: 'myPublishKey', @@ -69,6 +82,7 @@ describe('#components/subscription_manager', () => { afterEach(() => { pubnub.stop(); + pubnubWithLimitedDeduplicationQueue.stop(); pubnubWithPassingHeartbeats.stop(); pubnubWithLimitedQueue.stop(); }); @@ -703,10 +717,6 @@ describe('#components/subscription_manager', () => { }); it('supports deduping on shallow queue', (done) => { - // @ts-expect-error: This configuration option normally is hidden. - pubnub._config.dedupeOnSubscribe = true; - // @ts-expect-error: This configuration option normally is hidden. - pubnub._config.maximumCacheSize = 1; let messageCount = 0; utils @@ -739,13 +749,13 @@ describe('#components/subscription_manager', () => { { 'content-type': 'text/javascript' }, ); - pubnub.addListener({ + pubnubWithLimitedDeduplicationQueue.addListener({ message() { messageCount += 1; }, }); - pubnub.subscribe({ channels: ['ch1', 'ch2'], withPresence: true }); + pubnubWithLimitedDeduplicationQueue.subscribe({ channels: ['ch1', 'ch2'], withPresence: true }); setTimeout(() => { if (messageCount === 4) {